agent-device 0.17.5 → 0.17.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 (123) hide show
  1. package/README.md +2 -2
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.5.apk → agent-device-android-multitouch-helper-0.17.6.apk} +0 -0
  3. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.6.apk.sha256 +1 -0
  4. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.5.manifest.json → agent-device-android-multitouch-helper-0.17.6.manifest.json} +4 -4
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.5.apk → agent-device-android-snapshot-helper-0.17.6.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.6.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.5.manifest.json → agent-device-android-snapshot-helper-0.17.6.manifest.json} +6 -6
  8. package/dist/src/2133.js +1 -0
  9. package/dist/src/2748.js +1 -0
  10. package/dist/src/{4012.js → 2892.js} +1 -1
  11. package/dist/src/2948.js +1 -0
  12. package/dist/src/2954.js +2 -0
  13. package/dist/src/{7651.js → 3006.js} +1 -1
  14. package/dist/src/314.js +1 -0
  15. package/dist/src/{8806.js → 3340.js} +5 -5
  16. package/dist/src/4291.js +2 -0
  17. package/dist/src/{7599.js → 432.js} +1 -1
  18. package/dist/src/4418.js +1 -0
  19. package/dist/src/{2403.js → 4428.js} +1 -1
  20. package/dist/src/4723.js +1 -0
  21. package/dist/src/5299.js +1 -0
  22. package/dist/src/{113.js → 5448.js} +1 -1
  23. package/dist/src/5484.js +1 -0
  24. package/dist/src/5628.js +1 -0
  25. package/dist/src/587.js +1 -0
  26. package/dist/src/6311.js +27 -0
  27. package/dist/src/6918.js +1 -0
  28. package/dist/src/7244.js +1 -0
  29. package/dist/src/7394.js +6 -0
  30. package/dist/src/8184.js +1 -0
  31. package/dist/src/8225.js +1 -0
  32. package/dist/src/{1974.js → 8275.js} +1 -1
  33. package/dist/src/8875.js +1 -0
  34. package/dist/src/{1352.js → 9581.js} +1 -1
  35. package/dist/src/9624.js +1 -0
  36. package/dist/src/9722.js +38 -0
  37. package/dist/src/9836.js +1 -0
  38. package/dist/src/9873.js +1 -0
  39. package/dist/src/9919.js +6 -0
  40. package/dist/src/android-adb.d.ts +3 -3
  41. package/dist/src/android-adb.js +1 -1
  42. package/dist/src/android-snapshot-helper.js +1 -1
  43. package/dist/src/android.js +1 -1
  44. package/dist/src/apple.js +1 -1
  45. package/dist/src/apps.js +6 -6
  46. package/dist/src/artifacts.js +1 -1
  47. package/dist/src/batch.d.ts +4 -4
  48. package/dist/src/batch.js +1 -1
  49. package/dist/src/{args.js → cli-help.js} +18 -18
  50. package/dist/src/cli-output.js +4 -30
  51. package/dist/src/cli.js +17 -17
  52. package/dist/src/command-surface.js +1 -1
  53. package/dist/src/contracts.d.ts +6 -6
  54. package/dist/src/contracts.js +1 -1
  55. package/dist/src/devices.js +1 -1
  56. package/dist/src/find.js +1 -1
  57. package/dist/src/finders.d.ts +1 -1
  58. package/dist/src/finders.js +1 -1
  59. package/dist/src/generic.js +8 -14
  60. package/dist/src/index.d.ts +28 -25
  61. package/dist/src/index.js +1 -1
  62. package/dist/src/input-actions.js +1 -1
  63. package/dist/src/input-actions~1.js +1 -1
  64. package/dist/src/install-source.js +1 -1
  65. package/dist/src/interaction.js +1 -1
  66. package/dist/src/internal/bin.js +5 -5
  67. package/dist/src/internal/companion-tunnel.js +1 -1
  68. package/dist/src/internal/daemon.js +1 -1
  69. package/dist/src/internal/png-worker.js +1 -1
  70. package/dist/src/internal/update-check-entry.js +1 -1
  71. package/dist/src/io.js +1 -1
  72. package/dist/src/lease.js +1 -1
  73. package/dist/src/linux.js +1 -1
  74. package/dist/src/metro.js +1 -1
  75. package/dist/src/notifications.js +1 -1
  76. package/dist/src/react-native.js +1 -1
  77. package/dist/src/record-trace-recording.js +2 -2
  78. package/dist/src/record-trace.js +1 -1
  79. package/dist/src/recording-provider.js +1 -1
  80. package/dist/src/remote-config.d.ts +5 -5
  81. package/dist/src/remote-config.js +1 -1
  82. package/dist/src/rslib-runtime.js +1 -1
  83. package/dist/src/selector-runtime.js +1 -1
  84. package/dist/src/selectors.d.ts +1 -1
  85. package/dist/src/selectors.js +1 -1
  86. package/dist/src/server.js +1 -1
  87. package/dist/src/session.js +7 -7
  88. package/dist/src/snapshot.js +2 -2
  89. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +5 -0
  90. package/package.json +14 -13
  91. package/server.json +3 -3
  92. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.5.apk.sha256 +0 -1
  93. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.5.apk.sha256 +0 -1
  94. package/dist/src/1010.js +0 -1
  95. package/dist/src/123.js +0 -1
  96. package/dist/src/1231.js +0 -1
  97. package/dist/src/208.js +0 -1
  98. package/dist/src/221.js +0 -6
  99. package/dist/src/2415.js +0 -38
  100. package/dist/src/3675.js +0 -1
  101. package/dist/src/5611.js +0 -1
  102. package/dist/src/5827.js +0 -1
  103. package/dist/src/6088.js +0 -1
  104. package/dist/src/6133.js +0 -1
  105. package/dist/src/6629.js +0 -1
  106. package/dist/src/7556.js +0 -1
  107. package/dist/src/7719.js +0 -1
  108. package/dist/src/7847.js +0 -1
  109. package/dist/src/8133.js +0 -1
  110. package/dist/src/8656.js +0 -1
  111. package/dist/src/9010.js +0 -1
  112. package/dist/src/9471.js +0 -1
  113. package/dist/src/9542.js +0 -6
  114. package/dist/src/9616.js +0 -2
  115. package/dist/src/9639.js +0 -2
  116. package/dist/src/9671.js +0 -1
  117. package/dist/src/9818.js +0 -1
  118. package/dist/src/989.js +0 -1
  119. /package/dist/src/{2301.js → 4069.js} +0 -0
  120. /package/dist/src/{4829.js → 5560.js} +0 -0
  121. /package/dist/src/{4778.js → 6024.js} +0 -0
  122. /package/dist/src/{9152.js → 733.js} +0 -0
  123. /package/dist/src/{3267.js → 9612.js} +0 -0
package/README.md CHANGED
@@ -9,9 +9,9 @@
9
9
  # agent-device
10
10
 
11
11
  [![npm version](https://img.shields.io/npm/v/agent-device.svg)](https://www.npmjs.com/package/agent-device)
12
- [![CI](https://github.com/callstackincubator/agent-device/actions/workflows/ci.yml/badge.svg)](https://github.com/callstackincubator/agent-device/actions/workflows/ci.yml)
12
+ [![CI](https://github.com/callstack/agent-device/actions/workflows/ci.yml/badge.svg)](https://github.com/callstack/agent-device/actions/workflows/ci.yml)
13
13
  [![License: MIT](https://img.shields.io/badge/license-MIT-black.svg)](LICENSE)
14
- [![Glama MCP server](https://glama.ai/mcp/servers/callstackincubator/agent-device/badges/score.svg)](https://glama.ai/mcp/servers/callstackincubator/agent-device)
14
+ [![Glama MCP server](https://glama.ai/mcp/servers/callstack/agent-device/badges/score.svg)](https://glama.ai/mcp/servers/callstack/agent-device)
15
15
 
16
16
  Mobile app verification for AI agents.
17
17
 
@@ -0,0 +1 @@
1
+ b6bd66b2aa684d61d48ed2159b34ec9cde449b101b806af149ca6874a4ad9090 agent-device-android-multitouch-helper-0.17.6.apk
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "android-multitouch-helper",
3
- "version": "0.17.5",
4
- "assetName": "agent-device-android-multitouch-helper-0.17.5.apk",
5
- "sha256": "45a85cddbdca10a23a6245bf8e6786342551bf61f9d02bd8fdbf419e785dc1f9",
3
+ "version": "0.17.6",
4
+ "assetName": "agent-device-android-multitouch-helper-0.17.6.apk",
5
+ "sha256": "b6bd66b2aa684d61d48ed2159b34ec9cde449b101b806af149ca6874a4ad9090",
6
6
  "packageName": "com.callstack.agentdevice.multitouchhelper",
7
- "versionCode": 17005,
7
+ "versionCode": 17006,
8
8
  "instrumentationRunner": "com.callstack.agentdevice.multitouchhelper/.MultiTouchInstrumentation",
9
9
  "statusProtocol": "android-multitouch-helper-v1"
10
10
  }
@@ -0,0 +1 @@
1
+ a71a58df7650a62b7e10acd668fe3b60039cbb8e2203d7e31de60c848aee34ab agent-device-android-snapshot-helper-0.17.6.apk
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "android-snapshot-helper",
3
- "version": "0.17.5",
4
- "releaseTag": "v0.17.5",
5
- "assetName": "agent-device-android-snapshot-helper-0.17.5.apk",
3
+ "version": "0.17.6",
4
+ "releaseTag": "v0.17.6",
5
+ "assetName": "agent-device-android-snapshot-helper-0.17.6.apk",
6
6
  "apkUrl": null,
7
- "sha256": "94e26dc456437cf7a2112450e8638b5fac62565b4b17e86dc3834f6eedcd3ced",
8
- "checksumName": "agent-device-android-snapshot-helper-0.17.5.apk.sha256",
7
+ "sha256": "a71a58df7650a62b7e10acd668fe3b60039cbb8e2203d7e31de60c848aee34ab",
8
+ "checksumName": "agent-device-android-snapshot-helper-0.17.6.apk.sha256",
9
9
  "packageName": "com.callstack.agentdevice.snapshothelper",
10
- "versionCode": 17005,
10
+ "versionCode": 17006,
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"./733.js";let t={alert:"alert",appState:"appstate",appSwitcher:"app-switcher",apps:"apps",back:"back",batch:"batch",boot:"boot",click:"click",close:"close",clipboard:"clipboard",devices:"devices",diff:"diff",fill:"fill",find:"find",focus:"focus",gesture:"gesture",get:"get",home:"home",install:"install",installFromSource:"install-from-source",is:"is",keyboard:"keyboard",logs:"logs",longPress:"longpress",network:"network",open:"open",perf:"perf",prepare:"prepare",press:"press",push:"push",record:"record",reactNative:"react-native",reinstall:"reinstall",replay:"replay",rotate:"rotate",scroll:"scroll",screenshot:"screenshot",settings:"settings",shutdown:"shutdown",snapshot:"snapshot",swipe:"swipe",test:"test",trace:"trace",triggerAppEvent:"trigger-app-event",type:"type",wait:"wait"},s={installSource:"install_source",leaseAllocate:"lease_allocate",leaseHeartbeat:"lease_heartbeat",leaseRelease:"lease_release",releaseMaterializedPaths:"release_materialized_paths",runtime:"runtime",sessionList:"session_list"},a={auth:"auth",connect:"connect",connection:"connection",debug:"debug",disconnect:"disconnect",mcp:"mcp",metro:"metro",reactDevtools:"react-devtools",session:"session"},r=["pan","fling","swipe","pinch","rotate","transform"],o=`gesture requires one of: ${r.join(", ")}`,n=c(a.auth,a.connect,a.connection,a.disconnect,a.mcp,a.reactDevtools,t.prepare);function c(...e){return new Set(e)}function i(){return[...Object.values(t),...Object.values(a)].sort()}function l(e){return Object.values(t).includes(e)||e===a.debug||e===a.metro||e===a.session}function p(){return i().filter(e=>!n.has(e))}c(a.auth,a.connect,a.connection,a.debug,a.disconnect,a.mcp,a.metro,a.reactDevtools,a.session,t.appState,t.prepare,t.batch,t.devices,t.gesture,t.replay,t.test,t.trace);let u=[t.devices,t.boot,t.shutdown,t.apps,t.open,t.close,t.install,t.reinstall,t.installFromSource,t.push,t.triggerAppEvent,t.snapshot,t.screenshot,t.diff,t.wait,t.alert,t.settings,t.click,t.press,t.longPress,t.swipe,t.focus,t.type,t.fill,t.scroll,t.get,t.gesture,t.is,t.find,t.perf,t.logs,t.network,t.record,t.trace,t.test,t.appState,t.back,t.home,t.rotate,t.appSwitcher,t.keyboard,t.clipboard,t.reactNative],d=new Set(["batch","replay"]),m=["command","positionals","flags","runtime"],h=["platform","target","device","udid","serial","verbose","out"],f=new Set(u);function g(e){return"string"==typeof e?e.trim().toLowerCase():""}function _(t,s){let a=g(t);if(f.has(a))return a;throw new e("INVALID_ARGS",`Batch step ${s} command is not available through command batch: ${String(t)}`)}function S(t,s){if(d.has(t))throw new e("INVALID_ARGS",`Batch step ${s} cannot run ${t}.`)}export{d as BATCH_BLOCKED_COMMANDS,m as BATCH_DAEMON_STEP_KEYS,r as GESTURE_KINDS,o as GESTURE_SUBCOMMAND_ERROR,h as INHERITED_PARENT_FLAG_KEYS,s as INTERNAL_COMMANDS,t as PUBLIC_COMMANDS,u as STRUCTURED_BATCH_COMMAND_NAMES,S as assertBatchRuntimeCommandAllowed,l as isClientBackedCliCommandName,i as listCliCommandNames,p as listMcpExposedCommandNames,g as normalizeBatchCommandName,_ as readStructuredBatchCommandName};
@@ -0,0 +1 @@
1
+ import{AppError as e}from"./733.js";let r="user-installed";function t(e){return e??r}function o(r){if(void 0===r)throw new e("INVALID_ARGS","appsFilter must be resolved before executing the apps command");return r}export{r as DEFAULT_APPS_FILTER,o as assertResolvedAppsFilter,t as resolveAppsFilter};
@@ -1,4 +1,4 @@
1
- import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./3267.js";import{findProjectRoot as s}from"./9671.js";function i(a,u={}){var l,c;let p,f=(l=a,c=u,(p=(l??"").trim())?r(p,{env:c.env}):function(r={}){var i;let a,u,l,c=n.join(o("~",{env:r.env}),".agent-device"),p=r.projectRoot??s();return(i=p,t.existsSync(n.join(i,"package.json"))&&t.existsSync(n.join(i,"src","daemon.ts")))?n.join(c,"dev",(a=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(p),u=n.basename(a).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),l=e.createHash("sha1").update(a).digest("hex").slice(0,12),`${u||"agent-device"}-${l}`)):c}(c));return{baseDir:f,infoPath:n.join(f,"daemon.json"),lockPath:n.join(f,"daemon.lock"),logPath:n.join(f,"daemon.log"),sessionsDir:n.join(f,"sessions")}}function a(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function u(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function l(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function c(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let p=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,f=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,m=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function h(){let e=process.argv[1];return e?d(e):"unknown"}function d(r,o=s()){try{let s=n.resolve(o),i=[n.resolve(r)],a=new Set,u=[];for(;i.length>0;){let e=i.pop();if(!e||a.has(e))continue;a.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;u.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let l=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return g(e,p,t),g(e,f,t),[...t]}(l)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=M(r);if(o)return o;for(let e of m){let t=M(`${r}${e}`);if(t)return t}for(let e of m){let t=M(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let l=u.sort().join("|"),c=e.createHash("sha1").update(l).digest("hex");return`graph:${u.length}:${c}`}catch{return"unknown"}}function g(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function M(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let v=/^[A-Za-z0-9_@%+=:,./-]+$/;function y(e){return`'${e.replaceAll("'","'\\''")}'`}function S(e){return v.test(e)?e:y(e)}function j(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function x(e){return e.meta?.requestProgress==="replay-test"}function $(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function b(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function w(e){return`${JSON.stringify({type:"progress",event:e})}
1
+ import e from"node:crypto";import t from"node:fs";import n from"node:path";import{resolveUserPath as r,expandUserHomePath as o}from"./9612.js";import{findProjectRoot as s}from"./7244.js";function i(a,u={}){var l,c;let p,f=(l=a,c=u,(p=(l??"").trim())?r(p,{env:c.env}):function(r={}){var i;let a,u,l,c=n.join(o("~",{env:r.env}),".agent-device"),p=r.projectRoot??s();return(i=p,t.existsSync(n.join(i,"package.json"))&&t.existsSync(n.join(i,"src","daemon.ts")))?n.join(c,"dev",(a=function(e){try{return t.realpathSync.native(e)}catch{return n.resolve(e)}}(p),u=n.basename(a).replaceAll(/[^a-zA-Z0-9._-]+/g,"-"),l=e.createHash("sha1").update(a).digest("hex").slice(0,12),`${u||"agent-device"}-${l}`)):c}(c));return{baseDir:f,infoPath:n.join(f,"daemon.json"),lockPath:n.join(f,"daemon.lock"),logPath:n.join(f,"daemon.log"),sessionsDir:n.join(f,"sessions")}}function a(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function u(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function l(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function c(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let p=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,f=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,m=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function h(){let e=process.argv[1];return e?d(e):"unknown"}function d(r,o=s()){try{let s=n.resolve(o),i=[n.resolve(r)],a=new Set,u=[];for(;i.length>0;){let e=i.pop();if(!e||a.has(e))continue;a.add(e);let r=t.statSync(e);if(!r.isFile())continue;let o=n.relative(s,e)||e;u.push(`${o}:${r.size}:${Math.trunc(r.mtimeMs)}`);let l=t.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return g(e,p,t),g(e,f,t),[...t]}(l)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=M(r);if(o)return o;for(let e of m){let t=M(`${r}${e}`);if(t)return t}for(let e of m){let t=M(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&i.push(r)}}let l=u.sort().join("|"),c=e.createHash("sha1").update(l).digest("hex");return`graph:${u.length}:${c}`}catch{return"unknown"}}function g(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function M(e){try{return t.statSync(e).isFile()?e:null}catch{return null}}let v=/^[A-Za-z0-9_@%+=:,./-]+$/;function y(e){return`'${e.replaceAll("'","'\\''")}'`}function S(e){return v.test(e)?e:y(e)}function j(e,t){let n=[],r=e+t.toString(),o=r.indexOf("\n");for(;-1!==o;){let e=r.slice(0,o).trim();r=r.slice(o+1),e&&n.push(e),o=r.indexOf("\n")}return{lines:n,buffer:r}}function x(e){return e.meta?.requestProgress==="replay-test"}function $(e){return!!e&&"object"==typeof e&&"progress"===e.type&&!!e.event}function b(e){return!!e&&"object"==typeof e&&"response"===e.type&&!!e.response}function w(e){return`${JSON.stringify({type:"progress",event:e})}
2
2
  `}function D(e){return`${JSON.stringify({type:"response",response:e})}
3
3
  `}function k(e){return`${JSON.stringify({type:"response",response:e})}
4
4
  `}function _(e,t){e&&(e.snapshotDiagnostics??={samples:[]}).samples.push({...t,durationMs:Math.max(0,Math.round(t.durationMs))})}function A(e){let t=e?.snapshotDiagnostics?.samples;if(t&&0!==t.length)return P(t)}function P(e){if(0===e.length)return;let t=O(e);return{stats:t,...t.p95Ms>=1500?{warning:R(t)}:{}}}function z(e){let t=e.flatMap(e=>(function(e){if(!e||e.count<=0)return[];let t=e.platform;return 1===e.count?[{durationMs:e.maxMs,platform:t}]:2===e.count?[{durationMs:e.p50Ms,platform:t},{durationMs:e.maxMs,platform:t}]:[...Array.from({length:e.count-3},()=>({durationMs:e.p50Ms,platform:t})),{durationMs:e.p50Ms,platform:t},{durationMs:e.p95Ms,platform:t},{durationMs:e.maxMs,platform:t}]})(e?.stats));if(0===t.length)return;let n=O(t);return{stats:n,...n.p95Ms>=1500?{warning:R(n)}:{}}}function C(e){if(!e||"object"!=typeof e||Array.isArray(e))return;let t=function(e){let t=T(e);if(!t)return;let n=function(e){let t={count:e.count,p50Ms:e.p50Ms,p95Ms:e.p95Ms,maxMs:e.maxMs,slowThresholdMs:e.slowThresholdMs};if(!Object.values(t).some(e=>"number"!=typeof e))return t}(t);if(n){var r;let e,o,s,i;return{...n,...(o="string"==typeof(r=t).platform?r.platform:void 0,i=(s=T(r.backends))&&(e=Object.entries(s).filter(e=>"number"==typeof e[1])).length>0?Object.fromEntries(e):void 0,{...o?{platform:o}:{},...i?{backends:i}:{}})}}}(e.stats);if(!t)return;let n="string"==typeof e.warning?e.warning:void 0;return{stats:t,...n?{warning:n}:{}}}function O(e){let t,n=e.map(e=>e.durationMs).sort((e,t)=>e-t);return{count:n.length,p50Ms:E(n,50),p95Ms:E(n,95),maxMs:n[n.length-1]??0,slowThresholdMs:1500,...1===new Set(t=e.map(e=>e.platform).filter(e=>!!e)).size?{platform:t[0]}:{},...function(e){let t={};for(let n of e)n.backend&&(t[n.backend]=(t[n.backend]??0)+1);return Object.keys(t).length>0?{backends:t}:{}}(e)}}function E(e,t){if(0===e.length)return 0;let n=Math.max(0,Math.ceil(t/100*e.length)-1);return e[Math.min(n,e.length-1)]??0}function R(e){let t=e.platform?`${e.platform} `:"";return`Warning: ${t}snapshots are slow in this run: p95 ${e.p95Ms}ms over ${e.count} captures. Possible causes: device load, app or dev server stuck, helper fallback, or stale daemon.`}function T(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}export{d as computeDaemonCodeSignature,j as consumeTextLines,$ as isDaemonProgressEnvelope,b as isDaemonResponseEnvelope,z as mergeSnapshotDiagnostics,c as normalizeTenantId,C as readSnapshotDiagnosticsSummary,_ as recordSnapshotTiming,h as resolveDaemonCodeSignature,i as resolveDaemonPaths,a as resolveDaemonServerMode,u as resolveDaemonTransportPreference,l as resolveSessionIsolationMode,w as serializeDaemonProgressEnvelope,D as serializeDaemonResponseEnvelope,k as serializeDaemonRpcResponseEnvelope,y as shellQuote,S as shellQuoteIfNeeded,x as shouldStreamRequestProgress,A as summarizeSnapshotDiagnostics,P as summarizeSnapshotTimingSamples};
@@ -0,0 +1 @@
1
+ import{AppError as e}from"./733.js";import{recordingCommandMetadata as t,recordingCommandDefinitions as r,perfCommandDefinitions as o,METRO_PREPARE_FLAGS as a,defineExecutableCommand as i,systemCommandDefinitions as s,replayCommandMetadataList as n,requiredField as l,captureCommandDefinitions as d,observabilityCommandDefinitions as m,perfCommandMetadataList as p,captureCommandMetadata as u,batchCommandMetadata as c,integerField as b,booleanField as f,managementCommandMetadata as h,stringSchema as g,METRO_RELOAD_FLAGS as y,observabilityCommandMetadata as M,replayCommandDefinitions as P,reactNativeCommandDefinition as I,enumField as S,interactionCommandMetadata as U,commonInputFromFlags as v,defineFieldCommandMetadata as w,systemCommandMetadata as x,managementCommandDefinitions as H,jsonSchemaField as R,stringField as T,reactNativeCommandMetadata as _}from"./9873.js";import{listMcpExposedCommandNames as A}from"./2133.js";let N="debug",C=w(N,"Symbolicate crash artifacts with matching debug symbols.",{action:l(S(["symbols"])),artifact:l(T("Apple crash artifact path (.ips, .crash, or .log).")),dsym:T("Path to a matching .dSYM bundle."),searchPath:T("Directory to scan for matching .dSYM bundles."),out:T("Output path for the symbolicated artifact.")}),k=i(C,(e,t)=>e.debug.symbols(t)),D={[N]:{usageOverride:"debug symbols --artifact <crash.ips|crash.log> (--dsym <App.dSYM> | --search-path <dir>) [--out <symbolicated>]",listUsageOverride:"debug symbols --artifact <path> --dsym <App.dSYM>",helpDescription:"Symbolicate Apple crash artifacts with matching dSYM UUIDs. This debug namespace is intentionally narrow: use logs for app logs, network for HTTP evidence, perf for performance samples, record/trace for media and traces, and react-devtools for React Native profiles.",summary:"Symbolicate Apple crash artifacts",positionalArgs:["symbols"],allowedFlags:["artifact","dsym","searchPath","out"]}},B={debug:(t,r)=>({...v(r),action:function(t){if("symbols"===t)return t;throw new e("INVALID_ARGS","debug supports only symbols; use logs, network, perf, record, trace, or react-devtools for other diagnostics")}(t[0]),artifact:r.artifact,dsym:r.dsym,searchPath:r.searchPath,out:r.out})},E="metro",j=w(E,"Prepare Metro runtime or reload React Native apps.",{action:l(S(["prepare","reload"])),projectRoot:T(),kind:R(g()),publicBaseUrl:T(),proxyBaseUrl:T(),bearerToken:T(),bridgeScope:R({type:"object",additionalProperties:!0}),launchUrl:T(),port:b(),listenHost:T(),statusHost:T(),startupTimeoutMs:b(),probeTimeoutMs:b(),reuseExisting:f(),installDependenciesIfNeeded:f(),runtimeFilePath:T(),logPath:T(),metroHost:T(),metroPort:b(),bundleUrl:T(),timeoutMs:b()}),F=i(j,async(e,t)=>{var r,o,a;return"prepare"===t.action?await e.metro.prepare({projectRoot:(r=t).projectRoot,kind:r.kind,publicBaseUrl:r.publicBaseUrl,proxyBaseUrl:r.proxyBaseUrl,bearerToken:r.bearerToken,bridgeScope:r.bridgeScope??((o=r).tenant&&o.runId&&o.leaseId?{tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId}:void 0),port:r.port,listenHost:r.listenHost,statusHost:r.statusHost,startupTimeoutMs:r.startupTimeoutMs,probeTimeoutMs:r.probeTimeoutMs,reuseExisting:r.reuseExisting,installDependenciesIfNeeded:r.installDependenciesIfNeeded,runtimeFilePath:r.runtimeFilePath}):await e.metro.reload({metroHost:(a=t).metroHost,metroPort:a.metroPort,bundleUrl:a.bundleUrl,timeoutMs:a.timeoutMs})}),K={[E]:{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:[...y,...a]}},L={metro:(t,r)=>{let o=(t[0]??"").toLowerCase();if("prepare"!==o&&"reload"!==o)throw new e("INVALID_ARGS","metro requires a subcommand: prepare or reload");if("reload"===o)return{action:o,metroHost:r.metroHost,metroPort:r.metroPort,bundleUrl:r.bundleUrl,timeoutMs:r.metroProbeTimeoutMs};if(!r.metroPublicBaseUrl&&!r.metroProxyBaseUrl)throw new e("INVALID_ARGS","metro prepare requires --public-base-url <url> or --proxy-base-url <url>.");return{action:o,projectRoot:r.metroProjectRoot,kind:function(t){if(void 0!==t){if("auto"===t||"react-native"===t||"expo"===t)return t;throw new e("INVALID_ARGS","metro prepare --kind must be auto, react-native, or expo")}}(r.kind??r.metroKind),port:r.metroPreparePort,listenHost:r.metroListenHost,statusHost:r.metroStatusHost,publicBaseUrl:r.metroPublicBaseUrl,proxyBaseUrl:r.metroProxyBaseUrl,bearerToken:r.metroBearerToken,bridgeScope:r.tenant&&r.runId&&r.leaseId?{tenantId:r.tenant,runId:r.runId,leaseId:r.leaseId}:void 0,startupTimeoutMs:r.metroStartupTimeoutMs,probeTimeoutMs:r.metroProbeTimeoutMs,reuseExisting:!r.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!r.metroNoInstallDeps&&void 0,runtimeFilePath:r.metroRuntimeFile}}},O=[{metadata:h,definitions:H},{metadata:u,definitions:d},{metadata:x,definitions:s},{metadata:[_],definitions:[I]},{metadata:n,definitions:P},{metadata:M,definitions:m},{metadata:p,definitions:o},{metadata:[C],definitions:[k]},{metadata:t,definitions:r},{metadata:[j],definitions:[F]}],Y=O.flatMap(e=>[...e.metadata]),G=O.flatMap(e=>[...e.definitions]),V=[...U,...Y,c],q=new Map(V.map(e=>[e.name,e]));function $(){return[...V]}function z(){return A().map(e=>{var t;if(!J(e))throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t=e,q.get(t)})}function J(e){return q.has(e)}export{G as clientCommandDefinitions,B as debuggingCliReaders,D as debuggingCliSchemas,J as isCommandName,$ as listCommandMetadata,z as listMcpCommandMetadata,L as metroCliReaders,K as metroCliSchemas};
@@ -0,0 +1,2 @@
1
+ import{AsyncLocalStorage as e}from"node:async_hooks";import{runCmdBackground as r,withoutCommandExecutorOverride as t,runCmd as i,withCommandExecutorOverride as n}from"./8875.js";import{AppError as a}from"./733.js";let o=new e;function l(e){return async(r,n)=>await t(async()=>await i("adb",["-s",e,...r],{...n,detached:"win32"!==process.platform}))}function s(e){var t;let i=l(e.id);return{exec:i,spawn:(t=e.id,(e,i)=>{let n=r("adb",["-s",t,...e],{...i,allowFailure:!0,captureOutput:!1});return n.wait.catch(()=>{}),n.child}),reverse:g(i),pull:async(e,r,t)=>await i(["pull",e,r],t),install:async(e,r)=>{let{installArgs:t,execOptions:n}=h(r);return await i(["install",...t,e],n)}}}function d(e,r){let t=o.getStore();return r?r:t?.serial===e.id?t.provider.exec:l(e.id)}function u(e,r){if(r)return v(r);let t=o.getStore();return t?.serial===e.id?v(t.provider):s(e)}function c(e){let r=o.getStore();return r?.serial===e.id?r.provider.text:void 0}function w(e){let r=o.getStore();return r?.serial===e.id?r.provider.touch:void 0}function f(e){let r=v(e),t=r.reverse??g(r.exec),i=new Map;return{async ensure(e,r){let n=i.get(e.local);if(n&&n.ownerId!==e.ownerId)throw new a("COMMAND_FAILED",`Android port reverse ${e.local} is already owned by ${n.ownerId??"another session"}`,{current:n,requested:e});n?.remote!==e.remote&&(await t.ensure(e,r),i.set(e.local,{...e}))},async remove(e,r){i.has(e)?(await t.remove(e,r),i.delete(e)):await t.remove(e,r)},async removeAllOwned(e,r){let n=[...i.values()].filter(r=>r.ownerId===e).map(e=>e.local);if(0===n.length)return void await t.removeAllOwned(e,r);for(let e of n)await t.remove(e,r),i.delete(e)},list:async e=>t.list?await t.list(e):[...i.values()]}}function v(e){return"function"==typeof e?{exec:e}:e}async function p(e,r,i){let{device:n,provider:o,...l}=i??{},s=A(n,o),d=s?.pull;if(d)return await t(async()=>await d(e,r,l));let u=s?.exec;if(!u)throw new a("COMMAND_FAILED","Android adb pull requires an adb provider");return await t(async()=>await u(["pull",e,r],l))}async function m(e,r){let{device:i,provider:n,...o}=r??{},l=A(i,n),s=l?.install;if(s)return await t(async()=>await s(e,o));let d=l?.exec;if(!d)throw new a("COMMAND_FAILED","Android adb install requires an adb provider");let{installArgs:u,execOptions:c}=h(o);return await t(async()=>await d(["install",...u,e],c))}function A(e,r){if(r)return v(r);if(e)return u(e);let t=o.getStore();if(t)return v(t.provider)}async function y(e,r,i){var a;if(!e)return await i();let l={provider:"function"==typeof e?{exec:e}:e,serial:r.serial},s=(a=l,(e,r,i)=>{if("adb"!==e)return;let n=function(e,r){if("-s"===e[0]&&e[1]&&e[1]===r)return e.slice(2)}(r,a.serial);if(n)return t(async()=>await a.provider.exec(n,i))});return await o.run(l,async()=>await n(s,i))}function g(e){let r=new Map;return{async ensure(t,i){if(await e(["reverse",t.local,t.remote],{allowFailure:!1,signal:i?.signal,timeoutMs:i?.timeoutMs}),t.ownerId){let e=r.get(t.ownerId)??new Set;e.add(t.local),r.set(t.ownerId,e)}},async remove(t,i){var n,a;let o,l=await e(["reverse","--remove",t],{allowFailure:!0,signal:i?.signal,timeoutMs:i?.timeoutMs});if(0!==l.exitCode&&(n=l.stdout,a=l.stderr,!((o=`${n}
2
+ ${a}`.toLowerCase()).includes("listener")&&o.includes("not found"))))throw Error(`Failed to remove Android port reverse ${t}: ${l.stderr}`);for(let e of r.values())e.delete(t)},async removeAllOwned(e,t){for(let i of[...r.get(e)??[]])await this.remove(i,t);r.delete(e)},async list(t){let i=await e(["reverse","--list"],{allowFailure:!0,signal:t?.signal,timeoutMs:t?.timeoutMs});return 0!==i.exitCode?[]:function(e,r){let t=new Map;for(let[e,i]of r)for(let r of i)t.set(r,e);return e.split("\n").map(e=>e.trim().split(/\s+/)).filter(e=>e.length>=3).map(([,e,r])=>({local:e,remote:r,ownerId:t.get(e)}))}(i.stdout,r)}}}function h(e){let{replace:r,allowTestPackages:t,allowDowngrade:i,grantPermissions:n,...a}=e??{},o=[];return r&&o.push("-r"),t&&o.push("-t"),i&&o.push("-d"),n&&o.push("-g"),{installArgs:o,execOptions:a}}export{f as createAndroidPortReverseManager,s as createLocalAndroidAdbProvider,m as installAndroidAdbPackage,p as pullAndroidAdbFile,d as resolveAndroidAdbExecutor,u as resolveAndroidAdbProvider,c as resolveAndroidTextInjector,w as resolveAndroidTouchInjector,y as withAndroidAdbProvider};
@@ -1 +1 @@
1
- let t;import e from"node:fs/promises";import r from"node:path";import{TextDecoder as n}from"node:util";import{promises as i}from"node:fs";import a from"node:os";import{isExecutablePath as o,runCmd as l}from"./9818.js";let f=["emulator","platform-tools",r.join("cmdline-tools","latest","bin"),r.join("cmdline-tools","tools","bin")];function u(t){let e=new Set,r=[];for(let n of t){let t=n.trim();!t||e.has(t)||(e.add(t),r.push(t))}return r}function d(t=process.env){let e=t.ANDROID_SDK_ROOT?.trim(),n=t.ANDROID_HOME?.trim(),i=t.HOME?.trim()||a.homedir();return u([e??"",n??"",i?r.join(i,"Android","Sdk"):""])}async function s(t){try{return await i.access(t,i.constants.X_OK),!0}catch{return!1}}async function c(t=process.env){let e,n=[];for(let i of d(t)){let t=[];for(let e of f){let n=r.join(i,e);await s(n)&&t.push(n)}0!==t.length&&(e||(e=i),n.push(...t))}if(e&&(t.ANDROID_SDK_ROOT=t.ANDROID_SDK_ROOT?.trim()||e,t.ANDROID_HOME=t.ANDROID_HOME?.trim()||e),0===n.length)return;let i=(t.PATH??"").split(r.delimiter).map(t=>t.trim()).filter(t=>t.length>0);t.PATH=u([...n,...i]).join(r.delimiter)}let m=new n("utf-16le");async function h(t){for(let r of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var e;let n=await p(t,r);if(!n)continue;let i=(e=n).subarray(0,Math.min(e.length,128)).toString("utf8").trimStart().startsWith("<")?function(t){let e=t.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return e?.[1]}(e.toString("utf8")):function(t){let e;if(!(t.length<8)&&3===t.readUInt16LE(0))for(let r=t.readUInt16LE(2);r+8<=t.length;){let n=t.readUInt16LE(r),i=t.readUInt16LE(r+2),a=t.readUInt32LE(r+4);if(a<=0||r+a>t.length)break;if(1===n)e=function(t){if(t.length<28)return[];let e=t.readUInt32LE(8),r=t.readUInt32LE(16),n=t.readUInt32LE(20),i=(256&r)!=0,a=[];for(let r=0;r<e;r+=1){let e=28+4*r;if(e+4>t.length)break;let o=n+t.readUInt32LE(e);a.push(i?function(t,e){let[,r]=I(t,e),[n,i]=I(t,e+r),a=e+r+i;return t.subarray(a,a+n).toString("utf8")}(t,o):function(t,e){let[r,n]=function(t,e){let r=t.readUInt16LE(e);return(32768&r)==0?[r,2]:[(32767&r)<<16|t.readUInt16LE(e+2),4]}(t,e),i=e+n;return m.decode(t.subarray(i,i+2*r))}(t,o))}return a}(t.subarray(r,r+a));else if(258===n&&e){let n=function(t,e,r,n){if(r<36||e+r>t.length||"manifest"!==n[t.readUInt32LE(e+20)])return;let i=t.readUInt16LE(e+24),a=t.readUInt16LE(e+26),o=t.readUInt16LE(e+28),l=e+i;for(let e=0;e<o;e+=1){let r=l+e*a;if(r+20>t.length)break;if("package"!==n[t.readUInt32LE(r+4)])continue;let i=t.readUInt32LE(r+8);if(0xffffffff!==i)return n[i];let o=t.readUInt8(r+15),f=t.readUInt32LE(r+16);if(3===o)return n[f];break}}(t,r,i,e);if(n)return n}r+=a}}(e);if(i)return i}return await E(t)}async function p(t,e){try{let r=await l("unzip",["-p",t,e],{allowFailure:!0,binaryStdout:!0});if(0!==r.exitCode||!r.stdoutBuffer||0===r.stdoutBuffer.length)return;return r.stdoutBuffer}catch{return}}function I(t,e){let r=t.readUInt8(e);return(128&r)==0?[r,1]:[(127&r)<<8|t.readUInt8(e+1),2]}async function E(t){let e=await g();if(!e)return;let r=await l(e,["dump","badging",t],{allowFailure:!0});if(0!==r.exitCode)return;let n=r.stdout.match(/package:\s+name='([^']+)'/);return n?.[1]}async function g(){if(void 0!==t)return t??void 0;try{for(let n of d()){let i=r.join(n,"build-tools");try{for(let n of(await e.readdir(i)).sort((t,e)=>e.localeCompare(t,void 0,{numeric:!0}))){let e=r.join(i,n,"aapt");if(r.isAbsolute(e)&&await o(e))return t=e,e}}catch{}}}catch{}t=null}export{c as ensureAndroidSdkPathConfigured,h as resolveAndroidArchivePackageName};
1
+ let t;import e from"node:fs/promises";import r from"node:path";import{TextDecoder as n}from"node:util";import{promises as i}from"node:fs";import a from"node:os";import{isExecutablePath as o,runCmd as l}from"./8875.js";let f=["emulator","platform-tools",r.join("cmdline-tools","latest","bin"),r.join("cmdline-tools","tools","bin")];function u(t){let e=new Set,r=[];for(let n of t){let t=n.trim();!t||e.has(t)||(e.add(t),r.push(t))}return r}function d(t=process.env){let e=t.ANDROID_SDK_ROOT?.trim(),n=t.ANDROID_HOME?.trim(),i=t.HOME?.trim()||a.homedir();return u([e??"",n??"",i?r.join(i,"Android","Sdk"):""])}async function s(t){try{return await i.access(t,i.constants.X_OK),!0}catch{return!1}}async function c(t=process.env){let e,n=[];for(let i of d(t)){let t=[];for(let e of f){let n=r.join(i,e);await s(n)&&t.push(n)}0!==t.length&&(e||(e=i),n.push(...t))}if(e&&(t.ANDROID_SDK_ROOT=t.ANDROID_SDK_ROOT?.trim()||e,t.ANDROID_HOME=t.ANDROID_HOME?.trim()||e),0===n.length)return;let i=(t.PATH??"").split(r.delimiter).map(t=>t.trim()).filter(t=>t.length>0);t.PATH=u([...n,...i]).join(r.delimiter)}let m=new n("utf-16le");async function h(t){for(let r of["AndroidManifest.xml","base/manifest/AndroidManifest.xml"]){var e;let n=await p(t,r);if(!n)continue;let i=(e=n).subarray(0,Math.min(e.length,128)).toString("utf8").trimStart().startsWith("<")?function(t){let e=t.match(/<manifest\b[^>]*\bpackage\s*=\s*["']([^"']+)["']/i);return e?.[1]}(e.toString("utf8")):function(t){let e;if(!(t.length<8)&&3===t.readUInt16LE(0))for(let r=t.readUInt16LE(2);r+8<=t.length;){let n=t.readUInt16LE(r),i=t.readUInt16LE(r+2),a=t.readUInt32LE(r+4);if(a<=0||r+a>t.length)break;if(1===n)e=function(t){if(t.length<28)return[];let e=t.readUInt32LE(8),r=t.readUInt32LE(16),n=t.readUInt32LE(20),i=(256&r)!=0,a=[];for(let r=0;r<e;r+=1){let e=28+4*r;if(e+4>t.length)break;let o=n+t.readUInt32LE(e);a.push(i?function(t,e){let[,r]=I(t,e),[n,i]=I(t,e+r),a=e+r+i;return t.subarray(a,a+n).toString("utf8")}(t,o):function(t,e){let[r,n]=function(t,e){let r=t.readUInt16LE(e);return(32768&r)==0?[r,2]:[(32767&r)<<16|t.readUInt16LE(e+2),4]}(t,e),i=e+n;return m.decode(t.subarray(i,i+2*r))}(t,o))}return a}(t.subarray(r,r+a));else if(258===n&&e){let n=function(t,e,r,n){if(r<36||e+r>t.length||"manifest"!==n[t.readUInt32LE(e+20)])return;let i=t.readUInt16LE(e+24),a=t.readUInt16LE(e+26),o=t.readUInt16LE(e+28),l=e+i;for(let e=0;e<o;e+=1){let r=l+e*a;if(r+20>t.length)break;if("package"!==n[t.readUInt32LE(r+4)])continue;let i=t.readUInt32LE(r+8);if(0xffffffff!==i)return n[i];let o=t.readUInt8(r+15),f=t.readUInt32LE(r+16);if(3===o)return n[f];break}}(t,r,i,e);if(n)return n}r+=a}}(e);if(i)return i}return await E(t)}async function p(t,e){try{let r=await l("unzip",["-p",t,e],{allowFailure:!0,binaryStdout:!0});if(0!==r.exitCode||!r.stdoutBuffer||0===r.stdoutBuffer.length)return;return r.stdoutBuffer}catch{return}}function I(t,e){let r=t.readUInt8(e);return(128&r)==0?[r,1]:[(127&r)<<8|t.readUInt8(e+1),2]}async function E(t){let e=await g();if(!e)return;let r=await l(e,["dump","badging",t],{allowFailure:!0});if(0!==r.exitCode)return;let n=r.stdout.match(/package:\s+name='([^']+)'/);return n?.[1]}async function g(){if(void 0!==t)return t??void 0;try{for(let n of d()){let i=r.join(n,"build-tools");try{for(let n of(await e.readdir(i)).sort((t,e)=>e.localeCompare(t,void 0,{numeric:!0}))){let e=r.join(i,n,"aapt");if(r.isAbsolute(e)&&await o(e))return t=e,e}}catch{}}}catch{}t=null}export{c as ensureAndroidSdkPathConfigured,h as resolveAndroidArchivePackageName};
@@ -0,0 +1 @@
1
+ import{promises as t}from"node:fs";import e from"node:os";import i from"node:path";import{AppError as a}from"./733.js";function r(n={}){let l=n.cwd??process.cwd(),c=n.tempDir??e.tmpdir(),p=n.rootDir?o(n.rootDir,l):void 0;return{resolveInput:async t=>{if("uploadedArtifact"===t.kind)throw new a("UNSUPPORTED_OPERATION","Uploaded artifact inputs require a custom artifact adapter");return{path:o(t.path,l,p)}},reserveOutput:async(e,a)=>{let r,n=a.visibility??"client-visible",d=e?.kind==="path"?o(e.path,l,p):i.join(r=await t.mkdtemp(i.join(c,`agent-device-${a.field}-`)),`${a.field}${a.ext}`);return await t.mkdir(i.dirname(d),{recursive:!0}),{path:d,visibility:n,...r?{cleanup:async()=>{await t.rm(r,{recursive:!0,force:!0})}}:{},publish:async()=>e?.kind==="downloadableArtifact"?{kind:"localPath",field:a.field,path:d,fileName:e.fileName??i.basename(e.clientPath??d)}:void 0}},createTempFile:async e=>{let a=await t.mkdtemp(i.join(c,`${e.prefix}-`));return{path:i.join(a,`file${e.ext}`),visibility:"internal",cleanup:async()=>{await t.rm(a,{recursive:!0,force:!0})}}}}}function o(t,e,r){var o,n;let l,c=i.isAbsolute(t)?t:i.resolve(e,t);if(r&&(o=c,n=r,""!==(l=i.relative(n,o))&&(l.startsWith("..")||i.isAbsolute(l))))throw new a("INVALID_ARGS","Local path is outside the artifact adapter root",{path:c,rootDir:r});return c}export{r as createLocalArtifactAdapter};
@@ -1,7 +1,7 @@
1
- import{promises as t}from"node:fs";import e from"node:os";import a from"node:path";import{asAppError as n,AppError as i}from"./9152.js";import{emitDiagnostic as r}from"./7599.js";import{runCmd as o,resolveFileOverridePath as s,whichCmd as l,runCmdDetached as d}from"./9818.js";import{ensureAndroidSdkPathConfigured as u,resolveAndroidArchivePackageName as c}from"./7651.js";import{sleep as p}from"./4829.js";import{createAndroidPortReverseManager as f,resolveAndroidAdbProvider as m,installAndroidAdbPackage as w,resolveAndroidAdbExecutor as h}from"./9639.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as y}from"./989.js";let g=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],v=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,_=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,M=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function b(t){let e=new Set;for(let a of t.split("\n")){let t=a.trim();if(!t)continue;let n=t.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&e.add(i)}return Array.from(e)}function I(t){return t.split("\n").map(t=>{let e=t.trim();return e.startsWith("package:")?e.slice(8):e}).filter(Boolean)}function N(t){return O(t,t=>(function(t){for(let e of t.trim().split(/\s+/)){let t=e.indexOf("/");if(t<=0)continue;let a=D(e.slice(0,t),!1),n=D(e.slice(t+1),!0);if(a&&n&&a.length===t)return{package:a,activity:n}}return null})(t))}function O(t,e){let a=t.split("\n");for(let t of g)for(let n of a){let a=n.indexOf(t);if(-1===a)continue;let i=n.trim(),r=e(n.slice(a+t.length),i);if(r)return r}return null}function D(t,e){let a=0;for(;a<t.length&&function(t,e){if(!t)return!1;let a=t.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===t||"."===t||e&&"$"===t}(t[a],e);)a+=1;return t.slice(0,a)}function E(t){let e=t.trim();if(!e||/\s/.test(e))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(e);if(!a)return!1;let n=a[1]?.toLowerCase(),i=a[2]??"";return"http"!==n&&"https"!==n&&"ws"!==n&&"wss"!==n&&"ftp"!==n&&"ftps"!==n||i.startsWith("//")}function C(t){let e=t.trim().split(":")[0]?.toLowerCase();return"http"===e||"https"===e}function T(t,e){let a=t?.trim();return a||(C(e)?"com.apple.mobilesafari":void 0)}function L(t={}){let e=t.ttlMs??3e4,a=t.nowMs??Date.now,n=new Map,i=t=>{var e;let a=[(e=t).platform,e.deviceId,""].join("\0");for(let t of n.keys())t.startsWith(a)&&n.delete(t)};return{get(t,e){let i=k(t,e),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(t,i,r)=>(n.set(k(t,i),{value:r,expiresAtMs:a()+e}),r),clear(t){i(t)},async invalidateWhile(t,e){i(t);try{return await e()}finally{i(t)}}}}function k(t,e){return[t.platform,t.deviceId,t.variant??"",e.trim().toLowerCase()].join("\0")}function S(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}class R{startedAtMs;expiresAtMs;constructor(t,e){this.startedAtMs=t,this.expiresAtMs=t+Math.max(0,e)}static fromTimeoutMs(t,e=Date.now()){return new R(e,t)}remainingMs(t=Date.now()){return Math.max(0,this.expiresAtMs-t)}elapsedMs(t=Date.now()){return Math.max(0,t-this.startedAtMs)}isExpired(t=Date.now()){return 0>=this.remainingMs(t)}}async function x(t,e={},a={}){let n,r={maxAttempts:e.maxAttempts??3,baseDelayMs:e.baseDelayMs??200,maxDelayMs:e.maxDelayMs??2e3,jitter:e.jitter??.2,shouldRetry:e.shouldRetry};for(let e=1;e<=r.maxAttempts;e+=1){if(a.signal?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&e>1)break;try{let n=await t({attempt:e,maxAttempts:r.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),P({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let t=a.classifyReason?.(d),i={phase:a.phase,event:"attempt_failed",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};if(a.onEvent?.(i),P(i),e>=r.maxAttempts||r.shouldRetry&&!r.shouldRetry(d,e))break;let o=function(t,e,a,n){let i=Math.min(e,t*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(r.baseDelayMs,r.maxDelayMs,r.jitter,e),s=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(s<=0)break;let l={phase:a.phase,event:"retry_scheduled",attempt:e,maxAttempts:r.maxAttempts,delayMs:s,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};a.onEvent?.(l),P(l),await function(t,e){return new Promise(a=>{if(e?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,e&&e.removeEventListener("abort",o),a())},r=setTimeout(i,t);function o(){clearTimeout(r),i()}e&&e.addEventListener("abort",o,{once:!0})})}(s,a.signal)}}let o={phase:a.phase,event:"exhausted",attempt:r.maxAttempts,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(o),P(o),n)throw n;throw new i("COMMAND_FAILED","retry failed")}async function U(t,e={}){return x(()=>t(),{maxAttempts:e.attempts,baseDelayMs:e.baseDelayMs,maxDelayMs:e.maxDelayMs,jitter:e.jitter,shouldRetry:e.shouldRetry})}function P(t){r({level:"attempt_failed"===t.event||"exhausted"===t.event?"warn":"debug",phase:"retry",data:{...t}})}function F(t){return t?.trim()||void 0}function B(t){return F(t)}function $(t){return new Set(t.split(/[\s,]+/).map(t=>t.trim()).filter(Boolean))}function V(t,e=process.env){let a=F(t)??F(e.AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST);if(a)return $(a)}let W=new Set(["IOS_BOOT_TIMEOUT","IOS_RUNNER_CONNECT_TIMEOUT","IOS_TOOL_MISSING","ANDROID_BOOT_TIMEOUT","ADB_TRANSPORT_UNAVAILABLE","CI_RESOURCE_STARVATION_SUSPECTED"]);function G(t){return W.has(t.toUpperCase())}function j(t){let e=t.error?n(t.error):null,a=t.context?.platform,i=t.context?.phase;if(e?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let r=e?.details??{},o="string"==typeof r.message?r.message:void 0,s="string"==typeof r.stdout?r.stdout:void 0,l="string"==typeof r.stderr?r.stderr:void 0,d=r.boot&&"object"==typeof r.boot?r.boot:null,u=r.bootstatus&&"object"==typeof r.bootstatus?r.bootstatus:null,c=[t.message,e?.message,t.stdout,t.stderr,o,s,l,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0,"string"==typeof u?.stdout?u.stdout:void 0,"string"==typeof u?.stderr?u.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(c.includes("runner did not accept connection")||"connect"===i&&(c.includes("timed out")||c.includes("timeout")||c.includes("econnrefused")||c.includes("connection refused")||c.includes("fetch failed")||c.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":c.includes("resource temporarily unavailable")||c.includes("killed: 9")||c.includes("cannot allocate memory")||c.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(c.includes("device not found")||c.includes("no devices")||c.includes("device offline")||c.includes("offline")||c.includes("unauthorized")||c.includes("not authorized")||c.includes("unable to locate device")||c.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":e?.code==="COMMAND_FAILED"||c.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function H(t){switch(t){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI reduce parallel jobs or use a larger runner.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}let K=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function z(t,e,a){let n=Array(t.length),i=0,r=Math.min(e,t.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<t.length;){let e=i;i+=1,n[e]=await a(t[e])}})),n}function q(t){return`${t.stdout}
1
+ import{promises as t}from"node:fs";import e from"node:os";import a from"node:path";import{asAppError as n,AppError as i}from"./733.js";import{emitDiagnostic as r}from"./432.js";import{runCmd as o,resolveFileOverridePath as s,whichCmd as l,runCmdDetached as d}from"./8875.js";import{ensureAndroidSdkPathConfigured as u,resolveAndroidArchivePackageName as c}from"./3006.js";import{sleep as p}from"./5560.js";import{createAndroidPortReverseManager as f,resolveAndroidAdbProvider as m,installAndroidAdbPackage as w,resolveAndroidAdbExecutor as h}from"./2954.js";import{materializeInstallablePath as A,isTrustedInstallSourceUrl as y}from"./5484.js";let g=["mCurrentFocus=Window{","mFocusedApp=AppWindowToken{","mResumedActivity:","ResumedActivity:"],v=/\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i,_=/([^{}]*\bis(?:n't| not)\s+responding[^{}]*)/i,M=/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/;function b(t){let e=new Set;for(let a of t.split("\n")){let t=a.trim();if(!t)continue;let n=t.split(/\s+/)[0]??"";if(!n.includes("/"))continue;let i=n.split("/")[0]??"";i.includes(".")&&i&&e.add(i)}return Array.from(e)}function I(t){return t.split("\n").map(t=>{let e=t.trim();return e.startsWith("package:")?e.slice(8):e}).filter(Boolean)}function N(t){return O(t,t=>(function(t){for(let e of t.trim().split(/\s+/)){let t=e.indexOf("/");if(t<=0)continue;let a=D(e.slice(0,t),!1),n=D(e.slice(t+1),!0);if(a&&n&&a.length===t)return{package:a,activity:n}}return null})(t))}function O(t,e){let a=t.split("\n");for(let t of g)for(let n of a){let a=n.indexOf(t);if(-1===a)continue;let i=n.trim(),r=e(n.slice(a+t.length),i);if(r)return r}return null}function D(t,e){let a=0;for(;a<t.length&&function(t,e){if(!t)return!1;let a=t.charCodeAt(0);return a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||"_"===t||"."===t||e&&"$"===t}(t[a],e);)a+=1;return t.slice(0,a)}function E(t){let e=t.trim();if(!e||/\s/.test(e))return!1;let a=/^([A-Za-z][A-Za-z0-9+.-]*):(.+)$/.exec(e);if(!a)return!1;let n=a[1]?.toLowerCase(),i=a[2]??"";return"http"!==n&&"https"!==n&&"ws"!==n&&"wss"!==n&&"ftp"!==n&&"ftps"!==n||i.startsWith("//")}function C(t){let e=t.trim().split(":")[0]?.toLowerCase();return"http"===e||"https"===e}function T(t,e){let a=t?.trim();return a||(C(e)?"com.apple.mobilesafari":void 0)}function L(t={}){let e=t.ttlMs??3e4,a=t.nowMs??Date.now,n=new Map,i=t=>{var e;let a=[(e=t).platform,e.deviceId,""].join("\0");for(let t of n.keys())t.startsWith(a)&&n.delete(t)};return{get(t,e){let i=k(t,e),r=n.get(i);if(r)return r.expiresAtMs<=a()?void n.delete(i):r.value},set:(t,i,r)=>(n.set(k(t,i),{value:r,expiresAtMs:a()+e}),r),clear(t){i(t)},async invalidateWhile(t,e){i(t);try{return await e()}finally{i(t)}}}}function k(t,e){return[t.platform,t.deviceId,t.variant??"",e.trim().toLowerCase()].join("\0")}function S(t){return["1","true","yes","on"].includes((t??"").trim().toLowerCase())}class R{startedAtMs;expiresAtMs;constructor(t,e){this.startedAtMs=t,this.expiresAtMs=t+Math.max(0,e)}static fromTimeoutMs(t,e=Date.now()){return new R(e,t)}remainingMs(t=Date.now()){return Math.max(0,this.expiresAtMs-t)}elapsedMs(t=Date.now()){return Math.max(0,t-this.startedAtMs)}isExpired(t=Date.now()){return 0>=this.remainingMs(t)}}async function x(t,e={},a={}){let n,r={maxAttempts:e.maxAttempts??3,baseDelayMs:e.baseDelayMs??200,maxDelayMs:e.maxDelayMs??2e3,jitter:e.jitter??.2,shouldRetry:e.shouldRetry};for(let e=1;e<=r.maxAttempts;e+=1){if(a.signal?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(a.deadline?.isExpired()&&e>1)break;try{let n=await t({attempt:e,maxAttempts:r.maxAttempts,deadline:a.deadline});return a.onEvent?.({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),P({phase:a.phase,event:"succeeded",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs()}),n}catch(d){n=d;let t=a.classifyReason?.(d),i={phase:a.phase,event:"attempt_failed",attempt:e,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};if(a.onEvent?.(i),P(i),e>=r.maxAttempts||r.shouldRetry&&!r.shouldRetry(d,e))break;let o=function(t,e,a,n){let i=Math.min(e,t*2**(n-1));return Math.max(0,i+i*a*(2*Math.random()-1))}(r.baseDelayMs,r.maxDelayMs,r.jitter,e),s=a.deadline?Math.min(o,a.deadline.remainingMs()):o;if(s<=0)break;let l={phase:a.phase,event:"retry_scheduled",attempt:e,maxAttempts:r.maxAttempts,delayMs:s,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:t};a.onEvent?.(l),P(l),await function(t,e){return new Promise(a=>{if(e?.aborted)return void a();let n=!1,i=()=>{n||(n=!0,e&&e.removeEventListener("abort",o),a())},r=setTimeout(i,t);function o(){clearTimeout(r),i()}e&&e.addEventListener("abort",o,{once:!0})})}(s,a.signal)}}let o={phase:a.phase,event:"exhausted",attempt:r.maxAttempts,maxAttempts:r.maxAttempts,elapsedMs:a.deadline?.elapsedMs(),remainingMs:a.deadline?.remainingMs(),reason:a.classifyReason?.(n)};if(a.onEvent?.(o),P(o),n)throw n;throw new i("COMMAND_FAILED","retry failed")}async function U(t,e={}){return x(()=>t(),{maxAttempts:e.attempts,baseDelayMs:e.baseDelayMs,maxDelayMs:e.maxDelayMs,jitter:e.jitter,shouldRetry:e.shouldRetry})}function P(t){r({level:"attempt_failed"===t.event||"exhausted"===t.event?"warn":"debug",phase:"retry",data:{...t}})}function F(t){return t?.trim()||void 0}function B(t){return F(t)}function $(t){return new Set(t.split(/[\s,]+/).map(t=>t.trim()).filter(Boolean))}function V(t,e=process.env){let a=F(t)??F(e.AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST);if(a)return $(a)}let W=new Set(["IOS_BOOT_TIMEOUT","IOS_RUNNER_CONNECT_TIMEOUT","IOS_TOOL_MISSING","ANDROID_BOOT_TIMEOUT","ADB_TRANSPORT_UNAVAILABLE","CI_RESOURCE_STARVATION_SUSPECTED"]);function G(t){return W.has(t.toUpperCase())}function j(t){let e=t.error?n(t.error):null,a=t.context?.platform,i=t.context?.phase;if(e?.code==="TOOL_MISSING")return"android"===a?"ADB_TRANSPORT_UNAVAILABLE":"IOS_TOOL_MISSING";let r=e?.details??{},o="string"==typeof r.message?r.message:void 0,s="string"==typeof r.stdout?r.stdout:void 0,l="string"==typeof r.stderr?r.stderr:void 0,d=r.boot&&"object"==typeof r.boot?r.boot:null,u=r.bootstatus&&"object"==typeof r.bootstatus?r.bootstatus:null,c=[t.message,e?.message,t.stdout,t.stderr,o,s,l,"string"==typeof d?.stdout?d.stdout:void 0,"string"==typeof d?.stderr?d.stderr:void 0,"string"==typeof u?.stdout?u.stdout:void 0,"string"==typeof u?.stderr?u.stderr:void 0].filter(Boolean).join("\n").toLowerCase();return"ios"===a&&(c.includes("runner did not accept connection")||"connect"===i&&(c.includes("timed out")||c.includes("timeout")||c.includes("econnrefused")||c.includes("connection refused")||c.includes("fetch failed")||c.includes("socket hang up")))?"IOS_RUNNER_CONNECT_TIMEOUT":"ios"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"IOS_BOOT_TIMEOUT":"android"===a&&"boot"===i&&(c.includes("timed out")||c.includes("timeout"))?"ANDROID_BOOT_TIMEOUT":c.includes("resource temporarily unavailable")||c.includes("killed: 9")||c.includes("cannot allocate memory")||c.includes("system is low on memory")?"CI_RESOURCE_STARVATION_SUSPECTED":"android"===a&&(c.includes("device not found")||c.includes("no devices")||c.includes("device offline")||c.includes("offline")||c.includes("unauthorized")||c.includes("not authorized")||c.includes("unable to locate device")||c.includes("invalid device"))?"ADB_TRANSPORT_UNAVAILABLE":e?.code==="COMMAND_FAILED"||c.length>0?"BOOT_COMMAND_FAILED":"UNKNOWN"}function H(t){switch(t){case"IOS_BOOT_TIMEOUT":return"Retry simulator boot and inspect simctl bootstatus logs; in CI reduce parallel jobs or use a larger runner.";case"IOS_RUNNER_CONNECT_TIMEOUT":return"Retry runner startup, inspect xcodebuild logs, and verify simulator responsiveness before command execution.";case"ANDROID_BOOT_TIMEOUT":return"Retry emulator startup and verify sys.boot_completed reaches 1; consider increasing startup budget in CI.";case"ADB_TRANSPORT_UNAVAILABLE":return"Check adb server/device transport (adb devices -l), restart adb, and ensure the target device is online and authorized.";case"CI_RESOURCE_STARVATION_SUSPECTED":return"CI machine may be resource constrained; reduce parallel jobs or use a larger runner.";case"IOS_TOOL_MISSING":return"Xcode command-line tools are missing or not in PATH; run xcode-select --install and verify xcrun works.";case"BOOT_COMMAND_FAILED":return"Inspect command stderr/stdout for the failing boot phase and retry after environment validation.";default:return"Retry once and inspect verbose logs for the failing phase."}}let K=["android.software.leanback","android.software.leanback_only","android.hardware.type.television"];async function z(t,e,a){let n=Array(t.length),i=0,r=Math.min(e,t.length);return await Promise.all(Array.from({length:r},async()=>{for(;i<t.length;){let e=i;i+=1,n[e]=await a(t[e])}})),n}function q(t){return`${t.stdout}
2
2
  ${t.stderr}`}function Z(t,e){return["-s",t,...e]}function J(t){return t.startsWith("emulator-")}function X(t){return t.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim()}async function Q(t,e=1e4){return o("adb",Z(t,["shell","getprop","sys.boot_completed"]),{allowFailure:!0,timeoutMs:e})}async function Y(t,e){let a=e.replace(/_/g," ").trim();if(!J(t))return a||t;let n=await te(t);return n?n.replace(/_/g," "):a||t}async function tt(t,e,a){try{return await a("adb",Z(t,e),{allowFailure:!0,timeoutMs:1e4})}catch(t){var i;if("COMMAND_FAILED"===(i=n(t)).code&&"number"==typeof i.details?.timeoutMs)return;throw t}}async function te(t,e=o){for(let a of["ro.boot.qemu.avd_name","persist.sys.avd_name"]){let n=await tt(t,["shell","getprop",a],e);if(!n)continue;let i=n.stdout.trim();if(0===n.exitCode&&i.length>0)return i}let a=await tt(t,["emu","avd","name"],e);if(!a)return;let n=function(t){let e=t.split("\n").map(t=>t.trim()).filter(t=>t.length>0);if(0!==e.length)return"OK"===e.at(-1)&&e.pop(),e.join("\n").trim()||void 0}(a.stdout);if(0===a.exitCode&&n)return n}async function ta(t,e){let a=q(await o("adb",Z(t,["shell","cmd","package","has-feature",e]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase();return!!a.includes("true")||!a.includes("false")&&null}async function tn(t){return(await z(K,2,async e=>await ta(t,e))).some(t=>!0===t)}async function ti(t){var e;let a;return"tv"===((a=q(await o("adb",Z(t,["shell","getprop","ro.build.characteristics"]),{allowFailure:!0,timeoutMs:1e4})).toLowerCase()).includes("tv")||a.includes("leanback")?"tv":null)||await tn(t)?"tv":(e=q(await o("adb",Z(t,["shell","pm","list","features"]),{allowFailure:!0,timeoutMs:1e4})),/feature:android\.(software\.leanback(_only)?|hardware\.type\.television)\b/i.test(e))?"tv":"mobile"}async function tr(t={}){if(await u(),!await l("adb"))throw new i("TOOL_MISSING","adb not found in PATH");let e=t.serialAllowlist??V(void 0),a=(await to()).filter(t=>!e||e.has(t.serial));return await z(a,3,async({serial:t,rawModel:e})=>{let[a,n,i]=await Promise.all([Y(t,e),tu(t),ti(t)]);return{platform:"android",id:t,name:a,kind:J(t)?"emulator":"device",target:i,booted:n}})}async function to(){return(await o("adb",["devices","-l"],{timeoutMs:1e4})).stdout.split("\n").map(t=>t.trim()).filter(t=>t.length>0&&!t.startsWith("List of devices")).map(t=>t.split(/\s+/)).flatMap(t=>{let e=t[0];return void 0===e||"device"!==t[1]?[]:[{serial:e,rawModel:(t.find(t=>t.startsWith("model:"))??"").replace("model:","")}]})}async function ts(){let t=await o("emulator",["-list-avds"],{allowFailure:!0,timeoutMs:1e4});if(0!==t.exitCode)throw new i("COMMAND_FAILED","Failed to list Android emulator AVDs",{stdout:t.stdout,stderr:t.stderr,exitCode:t.exitCode,hint:"Verify Android emulator tooling is installed and available in PATH."});return t.stdout.split("\n").map(t=>t.trim()).filter(t=>t.length>0)}async function tl(t){let e=Date.now();for(;Date.now()-e<t.timeoutMs;){try{let e=await td(t.avdName,t.serial);if(e)return{platform:"android",id:e,name:t.avdName,kind:"emulator",target:"mobile",booted:!1}}catch{}await p(1e3)}throw new i("COMMAND_FAILED","Android emulator did not appear in time",{avdName:t.avdName,serial:t.serial,timeoutMs:t.timeoutMs,hint:"Check emulator logs and verify the AVD can start from command line."})}async function td(t,e){let a=X(t);for(let t of(await to()).filter(t=>(!e||t.serial===e)&&J(t.serial)))if(X(t.rawModel)===a||X(await Y(t.serial,t.rawModel))===a)return t.serial}async function tu(t){try{let e=await Q(t);return"1"===e.stdout.trim()}catch{return!1}}async function tc(t){var e,a;let n;await u();let r=t.avdName.trim();if(!r)throw new i("INVALID_ARGS","Android emulator boot requires a non-empty AVD name.");let o=t.timeoutMs??12e4;if(!await l("adb"))throw new i("TOOL_MISSING","adb not found in PATH");if(!await l("emulator"))throw new i("TOOL_MISSING","emulator not found in PATH");let s=await ts(),c=function(t,e){let a=t.find(t=>t===e);if(a)return a;let n=X(e);return t.find(t=>X(t)===n)}(s,r);if(!c)throw new i("DEVICE_NOT_FOUND",`No Android emulator AVD named ${t.avdName}`,{requestedAvdName:r,availableAvds:s,hint:"Run `emulator -list-avds` and pass an existing AVD name to --device."});let p=Date.now(),f=(e=await tr(),a=t.serial,n=X(c),e.find(t=>"android"===t.platform&&"emulator"===t.kind&&(!a||t.id===a)&&X(t.name)===n));if(!f){let e=["-avd",c];t.headless&&e.push("-no-window","-no-audio"),d("emulator",e)}let m=f??await tl({avdName:c,serial:t.serial,timeoutMs:o}),w=Math.max(1e3,o-(Date.now()-p));await tp(m.id,w);let h=(await tr()).find(t=>t.id===m.id);return h?{...h,name:c,booted:!0}:{...m,name:c,booted:!0}}async function tp(t,e=6e4){let a,r=R.fromTimeoutMs(e),o=Math.max(1,Math.ceil(e/1e3)),s=!1;try{await x(async({deadline:n})=>{if(n?.isExpired())throw s=!0,new i("COMMAND_FAILED","Android boot deadline exceeded",{serial:t,timeoutMs:e,elapsedMs:r.elapsedMs(),message:"timeout"});let o=Math.max(1e3,n?.remainingMs()??e),l=await Q(t,Math.min(o,1e4));if(a=l,"1"!==l.stdout.trim())throw new i("COMMAND_FAILED","Android device is still booting",{serial:t,stdout:l.stdout,stderr:l.stderr,exitCode:l.exitCode})},{maxAttempts:o,baseDelayMs:1e3,maxDelayMs:1e3,jitter:0,shouldRetry:t=>{let e=j({error:t,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}});return"ADB_TRANSPORT_UNAVAILABLE"!==e&&"ANDROID_BOOT_TIMEOUT"!==e}},{deadline:r,phase:"boot",classifyReason:t=>j({error:t,stdout:a?.stdout,stderr:a?.stderr,context:{platform:"android",phase:"boot"}})})}catch(f){let o=n(f),l=a?.stdout,d=a?.stderr,u=a?.exitCode,c=j({error:f,stdout:l,stderr:d,context:{platform:"android",phase:"boot"}});"BOOT_COMMAND_FAILED"===c&&"Android device is still booting"===o.message&&(c="ANDROID_BOOT_TIMEOUT");let p={serial:t,timeoutMs:e,elapsedMs:r.elapsedMs(),reason:c,hint:H(c),stdout:l,stderr:d,exitCode:u};if(s||"ANDROID_BOOT_TIMEOUT"===c)throw new i("COMMAND_FAILED","Android device did not finish booting in time",p);if("TOOL_MISSING"===o.code)throw new i("TOOL_MISSING",o.message,{...p,...o.details??{}});if("ADB_TRANSPORT_UNAVAILABLE"===c)throw new i("COMMAND_FAILED",o.message,{...p,...o.details??{}});throw new i(o.code,o.message,{...p,...o.details??{}},o.cause)}}async function tf(t,e,a){return await h(t)(e,a)}function tm(t){return{platform:"android",id:t,name:t,kind:t.startsWith("emulator-")?"emulator":"device",booted:!0}}function tw(t,e){let a=`${t}
3
- ${e}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let th=/\.(?:apk|aab)$/i,tA=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ty(t){var e,a;let n=t.trim();return 0===n.length?"other":th.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(e=n,!tA.test(e))?"binary":"package":(a=n,tA.test(a))?"package":"other"}function tg(t){return`Android runtime hints require an installed package name, not "${t}". Install or reinstall the app first, then relaunch by package.`}async function tv(t,e){let n="url"===t.kind&&y(t.url),i=await A({source:t,isInstallablePath:(t,e)=>{var n;let i;return e.isFile()&&(n=t,".apk"===(i=a.extname(n).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==t.kind||n,signal:e?.signal});try{let t=e?.resolveIdentity===!1?{}:await t_(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:t.packageName,cleanup:i.cleanup}}catch(t){throw await i.cleanup(),t}}async function t_(t){let e=a.extname(t).toLowerCase();return".apk"!==e&&".aab"!==e?{}:{packageName:await c(t)}}let tM={settings:{type:"intent",value:"android.settings.SETTINGS"}},tb="android.intent.category.LAUNCHER",tI="android.intent.category.LEANBACK_LAUNCHER",tN="android.intent.category.DEFAULT",tO="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",tD=new Set(["localhost","127.0.0.1","::1","[::1]"]),tE=L();function tC(t){return{platform:"android",deviceId:t.id,variant:t.target??""}}async function tT(t,e){let a=e.trim();if("package"===ty(a))return{type:"package",value:a};let n=tM[a.toLowerCase()];if(n)return n;let r=tC(t),o=tE.get(r,a);if(o)return o;let s=(await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean).filter(t=>t.toLowerCase().includes(a.toLowerCase())),l=s[0];if(void 0!==l&&1===s.length)return tE.set(r,a,{type:"package",value:l});if(s.length>1)throw new i("INVALID_ARGS",`Multiple packages matched "${e}"`,{matches:s,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new i("APP_NOT_INSTALLED",`No package found matching "${e}"`,{hint:tO})}async function tL(t,e){let a=await tk(t);return("user-installed"===e?(await tR(t)).filter(t=>a.has(t)):Array.from(a)).sort((t,e)=>t.localeCompare(e)).map(t=>({package:t,name:tx(t)}))}async function tk(t){let e=new Set;for(let a of tS(t,{includeFallbackWhenUnknown:!0})){let n=await tf(t,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",a],{allowFailure:!0});if(0===n.exitCode&&0!==n.stdout.trim().length)for(let t of b(n.stdout))e.add(t)}return e}function tS(t,e={}){return"tv"===t.target?[tI]:"mobile"===t.target?[tb]:e.includeFallbackWhenUnknown?[tb,tI]:[tb]}async function tR(t){return I((await tf(t,["shell","pm","list","packages","-3"])).stdout)}function tx(t){let e=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=t.split(".").flatMap(t=>t.split(/[_-]+/)).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0),n=a[a.length-1]??t;for(let t=a.length-1;t>=0;t-=1){let i=a[t];if(i&&!e.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function tU(t){let e=await tF(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(e)return e;let a=await tF(t,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function tP(t){return await tB(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]])}async function tF(t,e){for(let a of e){let e=N((await tf(t,a,{allowFailure:!0})).stdout??"");if(e)return e}return null}async function tB(t,e){for(let a of e){let e=O((await tf(t,a,{allowFailure:!0})).stdout??"",(t,e)=>(function(t,e){let a=t.split("}")[0]?.trim()??t.trim(),n=v.exec(a);if(n){let t=n[1];return{package:t,focusedWindow:`Application Not Responding: ${t}`,raw:e}}let i=_.exec(a);if(!i)return null;let r=i[1];if(void 0===r)return null;let o=r.trim().replace(/\s+/g," "),s=M.exec(o)?.[1];return{...s?{package:s}:{},focusedWindow:o,raw:e}})(t,e));if(e)return e}return null}async function t$(t,e){let a=function(t){let e;try{e=new URL(t)}catch{return null}let a=e.hostname.toLowerCase();if(!tD.has(a)||!e.port)return null;let n=Number(e.port);return Number.isInteger(n)?`tcp:${n}`:null}(e);if(!a)return;let n=f(m(t));try{await n.ensure({local:a,remote:a})}catch(e){let t={localPort:a.replace("tcp:",""),operation:`adb reverse ${a} ${a}`};throw e instanceof i&&Object.assign(t,{hint:e.details?.hint,diagnosticId:e.details?.diagnosticId,logPath:e.details?.logPath}),new i("COMMAND_FAILED",`Failed to ensure Android port reverse ${a} before opening localhost URL`,t,e)}}function tV(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function tW(t){return(t.launchArgs??[]).map(tV)}async function tG(t,e,a){var n;t.booted||await tp(t.id);let i="string"==typeof(n=a)?{activity:n}:n??{},r=i.activity,o=e.trim();if(E(o))return void await tj(t,o,i);if(void 0!==i.url)return void await tH(t,e,i);let s=await tT(t,e),l=tS(t)[0]??tb;"intent"===s.type?await tK(t,s.value,i):r?await tz(t,s.value,r,l,i):await tq(t,s.value,l,i)}async function tj(t,e,a){var n;let r;if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await t$(t,e),await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",e,...(n=a.appBundleId,(r=n?.trim())?["-p",r]:[]),...tW(a)])}async function tH(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening an app-bound deep link URL");let n=a.url?.trim()??"";if(!E(n))throw new i("INVALID_ARGS","Android app-bound open requires a valid URL target");let r=await tJ(t,e,"app-bound open");await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",n,"-p",r,...tW(a)])}async function tK(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override requires a package name, not an intent");await tf(t,["shell","am","start","-W","-a",e,...tW(a)])}async function tz(t,e,a,n,i){let r=a.includes("/")?a:`${e}/${a.startsWith(".")?a:`.${a}`}`;try{await tf(t,tZ(r,n,i))}catch(a){throw await tY(t,e,a),a}}async function tq(t,e,a,n){let r=await tf(t,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",a,"-p",e,...tW(n)],{allowFailure:!0});if(0===r.exitCode&&!t9(r.stdout,r.stderr))return;let o=await t1(t,e);if(!o){if(!await tQ(t,e))throw tX(e);throw new i("COMMAND_FAILED",`Failed to launch ${e}`,{stdout:r.stdout,stderr:r.stderr})}await tf(t,tZ(o,a,n))}function tZ(t,e,a){return["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",e,"-n",t,...tW(a)]}async function tJ(t,e,a){let n=await tT(t,e);if("intent"===n.type)throw new i("INVALID_ARGS",`Android ${a} requires a package name, not an intent`);return n.value}function tX(t){return new i("APP_NOT_INSTALLED",`No package found matching "${t}"`,{package:t,hint:tO})}async function tQ(t,e){let a=await tf(t,["shell","pm","path",e],{allowFailure:!0}),n=`${a.stdout}
3
+ ${e}`.toLowerCase();return a.includes("no shell command implementation")||a.includes("unknown command")}let th=/\.(?:apk|aab)$/i,tA=/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)+$/;function ty(t){var e,a;let n=t.trim();return 0===n.length?"other":th.test(n)?n.includes("/")||n.includes("\\")||n.startsWith(".")||n.startsWith("~")||(e=n,!tA.test(e))?"binary":"package":(a=n,tA.test(a))?"package":"other"}function tg(t){return`Android runtime hints require an installed package name, not "${t}". Install or reinstall the app first, then relaunch by package.`}async function tv(t,e){let n="url"===t.kind&&y(t.url),i=await A({source:t,isInstallablePath:(t,e)=>{var n;let i;return e.isFile()&&(n=t,".apk"===(i=a.extname(n).toLowerCase())||".aab"===i)},installableLabel:"Android installable (.apk or .aab)",allowArchiveExtraction:"url"!==t.kind||n,signal:e?.signal});try{let t=e?.resolveIdentity===!1?{}:await t_(i.installablePath);return{archivePath:i.archivePath,installablePath:i.installablePath,packageName:t.packageName,cleanup:i.cleanup}}catch(t){throw await i.cleanup(),t}}async function t_(t){let e=a.extname(t).toLowerCase();return".apk"!==e&&".aab"!==e?{}:{packageName:await c(t)}}let tM={settings:{type:"intent",value:"android.settings.SETTINGS"}},tb="android.intent.category.LAUNCHER",tI="android.intent.category.LEANBACK_LAUNCHER",tN="android.intent.category.DEFAULT",tO="Run agent-device apps --platform android to discover the installed package name, then retry open with that exact package.",tD=new Set(["localhost","127.0.0.1","::1","[::1]"]),tE=L();function tC(t){return{platform:"android",deviceId:t.id,variant:t.target??""}}async function tT(t,e){let a=e.trim();if("package"===ty(a))return{type:"package",value:a};let n=tM[a.toLowerCase()];if(n)return n;let r=tC(t),o=tE.get(r,a);if(o)return o;let s=(await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean).filter(t=>t.toLowerCase().includes(a.toLowerCase())),l=s[0];if(void 0!==l&&1===s.length)return tE.set(r,a,{type:"package",value:l});if(s.length>1)throw new i("INVALID_ARGS",`Multiple packages matched "${e}"`,{matches:s,hint:"Run agent-device apps --platform android to see the exact installed package names before retrying open."});throw new i("APP_NOT_INSTALLED",`No package found matching "${e}"`,{hint:tO})}async function tL(t,e){let a=await tk(t);return("user-installed"===e?(await tR(t)).filter(t=>a.has(t)):Array.from(a)).sort((t,e)=>t.localeCompare(e)).map(t=>({package:t,name:tx(t)}))}async function tk(t){let e=new Set;for(let a of tS(t,{includeFallbackWhenUnknown:!0})){let n=await tf(t,["shell","cmd","package","query-activities","--brief","-a","android.intent.action.MAIN","-c",a],{allowFailure:!0});if(0===n.exitCode&&0!==n.stdout.trim().length)for(let t of b(n.stdout))e.add(t)}return e}function tS(t,e={}){return"tv"===t.target?[tI]:"mobile"===t.target?[tb]:e.includeFallbackWhenUnknown?[tb,tI]:[tb]}async function tR(t){return I((await tf(t,["shell","pm","list","packages","-3"])).stdout)}function tx(t){let e=new Set(["com","android","google","app","apps","service","services","mobile","client"]),a=t.split(".").flatMap(t=>t.split(/[_-]+/)).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0),n=a[a.length-1]??t;for(let t=a.length-1;t>=0;t-=1){let i=a[t];if(i&&!e.has(i)){n=i;break}}return n.split(/[^a-z0-9]+/i).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async function tU(t){let e=await tF(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]]);if(e)return e;let a=await tF(t,[["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]);return a||{}}async function tP(t){return await tB(t,[["shell","dumpsys","window","windows"],["shell","dumpsys","window"]])}async function tF(t,e){for(let a of e){let e=N((await tf(t,a,{allowFailure:!0})).stdout??"");if(e)return e}return null}async function tB(t,e){for(let a of e){let e=O((await tf(t,a,{allowFailure:!0})).stdout??"",(t,e)=>(function(t,e){let a=t.split("}")[0]?.trim()??t.trim(),n=v.exec(a);if(n){let t=n[1];return{package:t,focusedWindow:`Application Not Responding: ${t}`,raw:e}}let i=_.exec(a);if(!i)return null;let r=i[1];if(void 0===r)return null;let o=r.trim().replace(/\s+/g," "),s=M.exec(o)?.[1];return{...s?{package:s}:{},focusedWindow:o,raw:e}})(t,e));if(e)return e}return null}async function t$(t,e){let a=function(t){let e;try{e=new URL(t)}catch{return null}let a=e.hostname.toLowerCase();if(!tD.has(a)||!e.port)return null;let n=Number(e.port);return Number.isInteger(n)?`tcp:${n}`:null}(e);if(!a)return;let n=f(m(t));try{await n.ensure({local:a,remote:a})}catch(e){let t={localPort:a.replace("tcp:",""),operation:`adb reverse ${a} ${a}`};throw e instanceof i&&Object.assign(t,{hint:e.details?.hint,diagnosticId:e.details?.diagnosticId,logPath:e.details?.logPath}),new i("COMMAND_FAILED",`Failed to ensure Android port reverse ${a} before opening localhost URL`,t,e)}}function tV(t){return/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function tW(t){return(t.launchArgs??[]).map(tV)}async function tG(t,e,a){var n;t.booted||await tp(t.id);let i="string"==typeof(n=a)?{activity:n}:n??{},r=i.activity,o=e.trim();if(E(o))return void await tj(t,o,i);if(void 0!==i.url)return void await tH(t,e,i);let s=await tT(t,e),l=tS(t)[0]??tb;"intent"===s.type?await tK(t,s.value,i):r?await tz(t,s.value,r,l,i):await tq(t,s.value,l,i)}async function tj(t,e,a){var n;let r;if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening a deep link URL");await t$(t,e),await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",e,...(n=a.appBundleId,(r=n?.trim())?["-p",r]:[]),...tW(a)])}async function tH(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override is not supported when opening an app-bound deep link URL");let n=a.url?.trim()??"";if(!E(n))throw new i("INVALID_ARGS","Android app-bound open requires a valid URL target");let r=await tJ(t,e,"app-bound open");await tf(t,["shell","am","start","-W","-a","android.intent.action.VIEW","-d",n,"-p",r,...tW(a)])}async function tK(t,e,a){if(a.activity)throw new i("INVALID_ARGS","Activity override requires a package name, not an intent");await tf(t,["shell","am","start","-W","-a",e,...tW(a)])}async function tz(t,e,a,n,i){let r=a.includes("/")?a:`${e}/${a.startsWith(".")?a:`.${a}`}`;try{await tf(t,tZ(r,n,i))}catch(a){throw await tY(t,e,a),a}}async function tq(t,e,a,n){let r=await tf(t,["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",a,"-p",e,...tW(n)],{allowFailure:!0});if(0===r.exitCode&&!t3(r.stdout,r.stderr))return;let o=await t1(t,e);if(!o){if(!await tQ(t,e))throw tX(e);throw new i("COMMAND_FAILED",`Failed to launch ${e}`,{stdout:r.stdout,stderr:r.stderr})}await tf(t,tZ(o,a,n))}function tZ(t,e,a){return["shell","am","start","-W","-a","android.intent.action.MAIN","-c",tN,"-c",e,"-n",t,...tW(a)]}async function tJ(t,e,a){let n=await tT(t,e);if("intent"===n.type)throw new i("INVALID_ARGS",`Android ${a} requires a package name, not an intent`);return n.value}function tX(t){return new i("APP_NOT_INSTALLED",`No package found matching "${t}"`,{package:t,hint:tO})}async function tQ(t,e){let a=await tf(t,["shell","pm","path",e],{allowFailure:!0}),n=`${a.stdout}
4
4
  ${a.stderr}`;return!!(0===a.exitCode&&/\bpackage:/i.test(n))||(t0(n),!1)}async function tY(t,e,a){if(t0(a instanceof i?`${String(a.details?.stdout??"")}
5
- ${String(a.details?.stderr??"")}`:"")||!await tQ(t,e))throw tX(e)}function t0(t){return/\bunknown package\b/i.test(t)||/\bpackage .* (?:was|is) not found\b/i.test(t)||/\bpackage .* does not exist\b/i.test(t)||/\bcould not find package\b/i.test(t)}async function t1(t,e){for(let a of Array.from(new Set(tS(t,{includeFallbackWhenUnknown:!0})))){let n=await tf(t,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",a,e],{allowFailure:!0});if(0!==n.exitCode)continue;let i=t2(n.stdout);if(i)return i}return null}function t9(t,e){let a=`${t}
6
- ${e}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(a)}function t2(t){let e=t.split("\n").map(t=>t.trim()).filter(Boolean);for(let t=e.length-1;t>=0;t-=1){let a=e[t];if(void 0===a||!a.includes("/"))continue;let n=a.split(/\s+/)[0];if(void 0!==n)return n}return null}async function t3(t){t.booted||await tp(t.id)}async function t4(t,e){if("settings"===e.trim().toLowerCase()){await tf(t,["shell","am","force-stop","com.android.settings"]),await t5(t,"com.android.settings");return}let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","Close requires a package name, not an intent");await tf(t,["shell","am","force-stop",a.value]),await t5(t,a.value)}async function t5(t,e){await t8(t,e),await t6(t,e)}async function t8(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){let a=await t7(t);if(a?.package!==e)return;await p(50)}}async function t7(t){for(let e of[["shell","dumpsys","window","windows"],["shell","dumpsys","window"],["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]){let a=N((await tf(t,e,{allowFailure:!0})).stdout??"");if(a)return a}return null}async function t6(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){if(!await et(t,e)&&(await p(150),!await et(t,e)))return;await p(50)}}async function et(t,e){return((await tf(t,["shell","pidof",e],{allowFailure:!0})).stdout??"").trim().length>0}async function ee(t,e){let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","App uninstall requires a package name, not an intent");let n=await tf(t,["uninstall",a.value],{allowFailure:!0});if(0!==n.exitCode){let t=`${n.stdout}
7
- ${n.stderr}`.toLowerCase();if(!t.includes("unknown package")&&!t.includes("not installed"))throw new i("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let ea=null;async function en(){let t=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(ea?.key===t)return ea.invocation;if(await l("bundletool")){let e={cmd:"bundletool",prefixArgs:[]};return ea={key:t,invocation:e},e}let e=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!e)throw new i("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",e]};return ea={key:t,invocation:a},a}async function ei(t){let e=await en();await o(e.cmd,[...e.prefixArgs,...t])}async function er(n,i){let r=m(n),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let s=await t.mkdtemp(a.join(e.tmpdir(),"agent-device-aab-")),l=a.join(s,"bundle.apks");try{await ei(["build-apks","--bundle",i,"--output",l,"--mode",o]),await ei(["install-apks","--apks",l,"--device-id",n.id])}finally{await t.rm(s,{recursive:!0,force:!0})}}async function eo(t,e){".aab"===a.extname(e).toLowerCase()?await er(t,e):await w(e,{device:t,replace:!0})}async function es(t){return new Set((await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean))}async function el(t,e){let a=Array.from(await es(t)).filter(t=>!e.has(t));if(1===a.length)return a[0]}async function ed(t,e){await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id),await eo(t,e)})}async function eu(t,e,a){let n=a?void 0:await es(t);return await ed(t,e),a??(n?await el(t,n):void 0)}async function ec(t,e){t.booted||await tp(t.id);let a=await tv({kind:"path",path:e});try{let e=await eu(t,a.installablePath,a.packageName),n=e?tx(e):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:e,appName:n,launchTarget:e}}finally{await a.cleanup()}}async function ep(t,e,a){return await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id);let{package:n}=await ee(t,e),i=await tv({kind:"path",path:a},{resolveIdentity:!1});try{await ed(t,i.installablePath)}finally{await i.cleanup()}return{package:n}})}async function ef(t,e={}){let a=["logcat","-d","-v","time"];void 0!==e.lines&&a.push("-t",String(Math.max(1,Math.floor(e.lines))));let n=await t(a,{allowFailure:!0,timeoutMs:e.timeoutMs,signal:e.signal});if(0!==n.exitCode)throw new i("COMMAND_FAILED","Failed to capture Android logcat",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return n.stdout}function em(t,e={}){if(!t.spawn)throw new i("UNSUPPORTED_OPERATION","Android ADB provider does not support streams",{capability:"adb.spawn"});let a=["logcat","-v","time"];e.pid&&a.push("--pid",e.pid);let n=t.spawn(a,{stdio:["ignore","pipe","pipe"],signal:e.signal});return e.output&&n.stdout&&n.stdout.pipe(e.output,{end:!1}),n}export{R as Deadline,tm as androidDeviceForSerial,H as bootFailureHint,ef as captureAndroidLogcatWithAdb,ty as classifyAndroidAppTarget,j as classifyBootFailure,t4 as closeAndroidApp,L as createAppResolutionCache,tc as ensureAndroidEmulatorBooted,tg as formatAndroidInstalledPackageRequiredMessage,tU as getAndroidAppState,tP as getAndroidBlockingDialogFocus,tx as inferAndroidAppName,ec as installAndroidApp,eu as installAndroidInstallablePathAndResolvePackageName,t9 as isAmStartError,tw as isClipboardShellUnsupported,E as isDeepLinkTarget,S as isEnvTruthy,G as isInfrastructureBootFailureReason,C as isWebUrl,tL as listAndroidApps,tr as listAndroidDevices,tG as openAndroidApp,t3 as openAndroidDevice,N as parseAndroidForegroundApp,t2 as parseAndroidLaunchComponent,b as parseAndroidLaunchablePackages,I as parseAndroidUserInstalledPackages,$ as parseSerialAllowlist,tv as prepareAndroidInstallArtifact,ep as reinstallAndroidApp,tT as resolveAndroidApp,V as resolveAndroidSerialAllowlist,T as resolveIosDeviceDeepLinkBundleId,B as resolveIosSimulatorDeviceSetPath,x as retryWithPolicy,tf as runAndroidAdb,em as streamAndroidLogcatWithAdb,tp as waitForAndroidBoot,U as withRetry};
5
+ ${String(a.details?.stderr??"")}`:"")||!await tQ(t,e))throw tX(e)}function t0(t){return/\bunknown package\b/i.test(t)||/\bpackage .* (?:was|is) not found\b/i.test(t)||/\bpackage .* does not exist\b/i.test(t)||/\bcould not find package\b/i.test(t)}async function t1(t,e){for(let a of Array.from(new Set(tS(t,{includeFallbackWhenUnknown:!0})))){let n=await tf(t,["shell","cmd","package","resolve-activity","--brief","-a","android.intent.action.MAIN","-c",a,e],{allowFailure:!0});if(0!==n.exitCode)continue;let i=t4(n.stdout);if(i)return i}return null}function t3(t,e){let a=`${t}
6
+ ${e}`;return/Error:.*(?:Activity not started|unable to resolve Intent)/i.test(a)}function t4(t){let e=t.split("\n").map(t=>t.trim()).filter(Boolean);for(let t=e.length-1;t>=0;t-=1){let a=e[t];if(void 0===a||!a.includes("/"))continue;let n=a.split(/\s+/)[0];if(void 0!==n)return n}return null}async function t2(t){t.booted||await tp(t.id)}async function t5(t,e){if("settings"===e.trim().toLowerCase()){await tf(t,["shell","am","force-stop","com.android.settings"]),await t9(t,"com.android.settings");return}let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","Close requires a package name, not an intent");await tf(t,["shell","am","force-stop",a.value]),await t9(t,a.value)}async function t9(t,e){await t7(t,e),await t6(t,e)}async function t7(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){let a=await t8(t);if(a?.package!==e)return;await p(50)}}async function t8(t){for(let e of[["shell","dumpsys","window","windows"],["shell","dumpsys","window"],["shell","dumpsys","activity","activities"],["shell","dumpsys","activity"]]){let a=N((await tf(t,e,{allowFailure:!0})).stdout??"");if(a)return a}return null}async function t6(t,e){let a=Date.now()+2e3;for(;Date.now()<a;){if(!await et(t,e)&&(await p(150),!await et(t,e)))return;await p(50)}}async function et(t,e){return((await tf(t,["shell","pidof",e],{allowFailure:!0})).stdout??"").trim().length>0}async function ee(t,e){let a=await tT(t,e);if("intent"===a.type)throw new i("INVALID_ARGS","App uninstall requires a package name, not an intent");let n=await tf(t,["uninstall",a.value],{allowFailure:!0});if(0!==n.exitCode){let t=`${n.stdout}
7
+ ${n.stderr}`.toLowerCase();if(!t.includes("unknown package")&&!t.includes("not installed"))throw new i("COMMAND_FAILED",`adb uninstall failed for ${a.value}`,{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode})}return{package:a.value}}let ea=null;async function en(){let t=`${process.env.PATH??""}::${process.env.AGENT_DEVICE_BUNDLETOOL_JAR??""}`;if(ea?.key===t)return ea.invocation;if(await l("bundletool")){let e={cmd:"bundletool",prefixArgs:[]};return ea={key:t,invocation:e},e}let e=await s(process.env.AGENT_DEVICE_BUNDLETOOL_JAR,"AGENT_DEVICE_BUNDLETOOL_JAR");if(!e)throw new i("TOOL_MISSING","bundletool not found in PATH. Install bundletool or set AGENT_DEVICE_BUNDLETOOL_JAR to a bundletool-all.jar path.");let a={cmd:"java",prefixArgs:["-jar",e]};return ea={key:t,invocation:a},a}async function ei(t){let e=await en();await o(e.cmd,[...e.prefixArgs,...t])}async function er(n,i){let r=m(n),o="universal";if(r.installBundle)return void await r.installBundle(i,{mode:o});let s=await t.mkdtemp(a.join(e.tmpdir(),"agent-device-aab-")),l=a.join(s,"bundle.apks");try{await ei(["build-apks","--bundle",i,"--output",l,"--mode",o]),await ei(["install-apks","--apks",l,"--device-id",n.id])}finally{await t.rm(s,{recursive:!0,force:!0})}}async function eo(t,e){".aab"===a.extname(e).toLowerCase()?await er(t,e):await w(e,{device:t,replace:!0})}async function es(t){return new Set((await tf(t,["shell","pm","list","packages"])).stdout.split("\n").map(t=>t.replace("package:","").trim()).filter(Boolean))}async function el(t,e){let a=Array.from(await es(t)).filter(t=>!e.has(t));if(1===a.length)return a[0]}async function ed(t,e){await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id),await eo(t,e)})}async function eu(t,e,a){let n=a?void 0:await es(t);return await ed(t,e),a??(n?await el(t,n):void 0)}async function ec(t,e){t.booted||await tp(t.id);let a=await tv({kind:"path",path:e});try{let e=await eu(t,a.installablePath,a.packageName),n=e?tx(e):void 0;return{archivePath:a.archivePath,installablePath:a.installablePath,packageName:e,appName:n,launchTarget:e}}finally{await a.cleanup()}}async function ep(t,e,a){return await tE.invalidateWhile(tC(t),async()=>{t.booted||await tp(t.id);let{package:n}=await ee(t,e),i=await tv({kind:"path",path:a},{resolveIdentity:!1});try{await ed(t,i.installablePath)}finally{await i.cleanup()}return{package:n}})}async function ef(t,e={}){let a=["logcat","-d","-v","time"];void 0!==e.lines&&a.push("-t",String(Math.max(1,Math.floor(e.lines))));let n=await t(a,{allowFailure:!0,timeoutMs:e.timeoutMs,signal:e.signal});if(0!==n.exitCode)throw new i("COMMAND_FAILED","Failed to capture Android logcat",{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode});return n.stdout}function em(t,e={}){if(!t.spawn)throw new i("UNSUPPORTED_OPERATION","Android ADB provider does not support streams",{capability:"adb.spawn"});let a=["logcat","-v","time"];e.pid&&a.push("--pid",e.pid);let n=t.spawn(a,{stdio:["ignore","pipe","pipe"],signal:e.signal});return e.output&&n.stdout&&n.stdout.pipe(e.output,{end:!1}),n}export{R as Deadline,tm as androidDeviceForSerial,H as bootFailureHint,ef as captureAndroidLogcatWithAdb,ty as classifyAndroidAppTarget,j as classifyBootFailure,t5 as closeAndroidApp,L as createAppResolutionCache,tc as ensureAndroidEmulatorBooted,tg as formatAndroidInstalledPackageRequiredMessage,tU as getAndroidAppState,tP as getAndroidBlockingDialogFocus,tx as inferAndroidAppName,ec as installAndroidApp,eu as installAndroidInstallablePathAndResolvePackageName,t3 as isAmStartError,tw as isClipboardShellUnsupported,E as isDeepLinkTarget,S as isEnvTruthy,G as isInfrastructureBootFailureReason,C as isWebUrl,tL as listAndroidApps,tr as listAndroidDevices,tG as openAndroidApp,t2 as openAndroidDevice,N as parseAndroidForegroundApp,t4 as parseAndroidLaunchComponent,b as parseAndroidLaunchablePackages,I as parseAndroidUserInstalledPackages,$ as parseSerialAllowlist,tv as prepareAndroidInstallArtifact,ep as reinstallAndroidApp,tT as resolveAndroidApp,V as resolveAndroidSerialAllowlist,T as resolveIosDeviceDeepLinkBundleId,B as resolveIosSimulatorDeviceSetPath,x as retryWithPolicy,tf as runAndroidAdb,em as streamAndroidLogcatWithAdb,tp as waitForAndroidBoot,U as withRetry};
@@ -0,0 +1,2 @@
1
+ import{AppError as e}from"./733.js";function t(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function r(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function a(e,t){return e.find(e=>e.ref===t)??null}function n(e){return JSON.stringify({interactiveOnly:e?.interactiveOnly===!0,depth:"number"==typeof e?.depth?e.depth:null,scope:e?.scope?.trim()||null,raw:e?.raw===!0})}function i(e){if(e)return{depth:e.snapshotDepth,interactiveOnly:e.snapshotInteractiveOnly,raw:e.snapshotRaw,scope:e.snapshotScope}}function o(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}let l=["ios","macos","android","linux","apple"],s=["mobile","tv","desktop"];function d(e){return e}function c(e){return"apple"===e||"ios"===e||"macos"===e}function u(e,t){return!t||("apple"===t?c(e):e===t)}function m(e){return"macos"===e||"desktop"===e?"macOS":"tv"===e?"tvOS":"iOS"}function f(e){let{simulatorSetPath:t,platform:r,target:a}=e;if(t&&"macos"!==r&&"desktop"!==a)return t}async function p(t,r,a={}){let n=t,i=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(r.platform&&(n=n.filter(e=>u(e.platform,r.platform))),r.target&&(n=n.filter(e=>(e.target??"mobile")===r.target)),r.udid){let t=n.find(e=>e.id===r.udid&&c(e.platform));if(!t)throw new e("DEVICE_NOT_FOUND",`No Apple device with UDID ${r.udid}`);return t}if(r.serial){let t=n.find(e=>e.id===r.serial&&"android"===e.platform);if(!t)throw new e("DEVICE_NOT_FOUND",`No Android device with serial ${r.serial}`);return t}if(r.deviceName){let t=i(r.deviceName),a=n.find(e=>i(e.name)===t);if(!a)throw new e("DEVICE_NOT_FOUND",`No device named ${r.deviceName}`);return a}let o=n[0];if(void 0!==o&&1===n.length)return o;if(0===n.length){var l;let t=a.simulatorSetPath;if(t&&(!(l=r.platform)||"apple"===l||"ios"===l))throw new e("DEVICE_NOT_FOUND","No devices found in the scoped simulator set",{simulatorSetPath:t,hint:`The simulator set at "${t}" appears to be empty. Create a simulator first:
2
+ xcrun simctl --set "${t}" create "iPhone 16" com.apple.CoreSimulator.SimDeviceType.iPhone-16 com.apple.CoreSimulator.SimRuntime.iOS-18-0`,selector:r});throw new e("DEVICE_NOT_FOUND","No devices found",{selector:r})}let s=n.filter(e=>"device"!==e.kind);s.length>0&&(n=s);let d=n.filter(e=>e.booted),m=d[0];if(void 0!==m&&1===d.length)return m;let f=d[0]??n[0];if(void 0===f)throw new e("DEVICE_NOT_FOUND","No devices found",{selector:r});return f}let h=["reject","strip"],$=["ios-simulator","ios-instance","android-instance"],E=["socket","http","dual"],I=["auto","socket","http"],v=["none","tenant"],S=["summary","headers","body","all"];function N(e){return{parse:t=>e(t,"$")}}function O(e,t){throw Error(`${e}: ${t}`)}function _(e,t){return(!e||"object"!=typeof e||Array.isArray(e))&&O(t,"Expected an object"),e}function g(e,t){return"string"!=typeof e&&O(t,"Expected a string"),e}function y(e,t){let r=g(e,t).trim();return r||O(t,"Expected a non-empty string"),r}function P(e,t){return Number.isInteger(e)||O(t,"Expected an integer"),e}function b(e,t,r){let a=e[t];return void 0===a?void 0:g(a,`${r}.${t}`)}function w(e,t,r){let a=e[t];if(void 0!==a)return"boolean"!=typeof a&&O(`${r}.${t}`,"Expected a boolean"),a}function A(e,t,r){let a=e[t];return void 0===a?void 0:P(a,`${r}.${t}`)}function D(e,t,r){let a=e[t];return void 0===a?void 0:_(a,`${r}.${t}`)}function M(e,t,r,a){let n=e[t];if(void 0!==n)return"string"==typeof n&&r.includes(n)||O(`${a}.${t}`,`Expected one of: ${r.join(", ")}`),n}function R(e,t){let r=_(e,t),a={};for(let[e,n]of Object.entries(r))a[e]=g(n,`${t}.${e}`);return a}let k=N((e,t)=>{let r=_(e,t);return{platform:M(r,"platform",["ios","android"],t),metroHost:b(r,"metroHost",t),metroPort:A(r,"metroPort",t),bundleUrl:b(r,"bundleUrl",t),launchUrl:b(r,"launchUrl",t)}}),x=N((e,t)=>{var r,a;let n=_(e,t),i=(r=n.positionals,a=`${t}.positionals`,Array.isArray(r)||O(a,"Expected an array"),r),o=D(n,"meta",t);return{token:b(n,"token",t),session:b(n,"session",t),command:g(n.command,`${t}.command`),positionals:i.map((e,r)=>g(e,`${t}.positionals[${String(r)}]`)),flags:D(n,"flags",t),runtime:void 0===n.runtime?void 0:k.parse(n.runtime),meta:void 0===o?void 0:{requestId:b(o,"requestId",`${t}.meta`),debug:w(o,"debug",`${t}.meta`),cwd:b(o,"cwd",`${t}.meta`),sessionExplicit:w(o,"sessionExplicit",`${t}.meta`),tenantId:b(o,"tenantId",`${t}.meta`),runId:b(o,"runId",`${t}.meta`),leaseId:b(o,"leaseId",`${t}.meta`),leaseTtlMs:A(o,"leaseTtlMs",`${t}.meta`),leaseBackend:M(o,"leaseBackend",$,`${t}.meta`),sessionIsolation:M(o,"sessionIsolation",v,`${t}.meta`),uploadedArtifactId:b(o,"uploadedArtifactId",`${t}.meta`),clientArtifactPaths:void 0===o.clientArtifactPaths?void 0:R(o.clientArtifactPaths,`${t}.meta.clientArtifactPaths`),installSource:void 0===o.installSource?void 0:function(e,t){let r=_(e,t),a=g(r.kind,`${t}.kind`);if("url"===a){let e=g(r.url,`${t}.url`),n=void 0===r.headers?void 0:R(r.headers,`${t}.headers`);return n?{kind:a,url:e,headers:n}:{kind:a,url:e}}if("path"===a)return{kind:a,path:g(r.path,`${t}.path`)};if("github-actions-artifact"===a){let e,a,n,i,o;return e=y(r.owner,`${t}.owner`),a=y(r.repo,`${t}.repo`),n=void 0!==r.artifactId,i=void 0!==r.runId,o=void 0!==r.artifactName,(n&&(i||o)&&O(`${t}`,"Expected either artifactId or artifactName, not both"),n||!i||o||O(`${t}`,"Expected artifactName when runId is specified"),n||o||O(`${t}`,"Expected artifactId or artifactName"),n)?{kind:"github-actions-artifact",owner:e,repo:a,artifactId:P(r.artifactId,`${t}.artifactId`)}:{kind:"github-actions-artifact",owner:e,repo:a,...i?{runId:P(r.runId,`${t}.runId`)}:{},artifactName:y(r.artifactName,`${t}.artifactName`)}}O(`${t}.kind`,'Expected "url", "path", or "github-actions-artifact"')}(o.installSource,`${t}.meta.installSource`),retainMaterializedPaths:w(o,"retainMaterializedPaths",`${t}.meta`),materializedPathRetentionMs:A(o,"materializedPathRetentionMs",`${t}.meta`),materializationId:b(o,"materializationId",`${t}.meta`),lockPolicy:M(o,"lockPolicy",h,`${t}.meta`),lockPlatform:M(o,"lockPlatform",l,`${t}.meta`)}}});function C(e,t){return{token:b(e,"token",t),session:b(e,"session",t),tenantId:b(e,"tenantId",t),tenant:b(e,"tenant",t),runId:b(e,"runId",t)}}let T=N((e,t)=>{let r=_(e,t);return{...C(r,t),ttlMs:A(r,"ttlMs",t),backend:M(r,"backend",$,t)}}),U=N((e,t)=>{let r,a={record:r=_(e,t),leaseId:b(r,"leaseId",t),ttlMs:A(r,"ttlMs",t)};return{...C(a.record,t),leaseId:a.leaseId,ttlMs:a.ttlMs}}),F=N((e,t)=>{let r=_(e,t);return void 0!==r.ttlMs&&O(`${t}.ttlMs`,"Unexpected field"),{...C(r,t),leaseId:b(r,"leaseId",t)}}),j=N((e,t)=>{let r,a=_(e,t);return{jsonrpc:b(a,"jsonrpc",t),id:(null==(r=a.id)||"string"!=typeof r&&"number"!=typeof r&&O(`${t}.id`,"Expected a string, number, or null"),r),method:b(a,"method",t),params:a.params}});export{h as DAEMON_LOCK_POLICIES,E as DAEMON_SERVER_MODES,I as DAEMON_TRANSPORT_PREFERENCES,s as DEVICE_TARGETS,$ as LEASE_BACKENDS,S as NETWORK_INCLUDE_MODES,l as PLATFORM_SELECTORS,v as SESSION_ISOLATION_MODES,t as attachRefs,n as buildSnapshotPresentationKey,o as centerOfRect,x as daemonCommandRequestSchema,k as daemonRuntimeSchema,a as findNodeByRef,c as isApplePlatform,j as jsonRpcRequestSchema,T as leaseAllocateSchema,U as leaseHeartbeatSchema,F as leaseReleaseSchema,u as matchesPlatformSelector,d as normalizePlatformSelector,r as normalizeRef,m as resolveApplePlatformName,f as resolveAppleSimulatorSetPathForSelector,p as resolveDevice,i as snapshotPresentationOptionsFromFlags};
@@ -1,4 +1,4 @@
1
- import{AsyncLocalStorage as t}from"node:async_hooks";import e from"node:crypto";import n from"node:fs";import o from"node:os";import i from"node:path";import{redactDiagnosticData as r}from"./9152.js";let s=new t;function a(){return e.randomBytes(8).toString("hex")}async function c(t,n){let o={...t,diagnosticId:`${Date.now().toString(36)}-${e.randomBytes(4).toString("hex")}`,events:[],liveWrittenEventCount:0};return await s.run(o,n)}function l(t){let e=s.getStore();e&&Object.assign(e,t)}function d(){let t=s.getStore();return t?{diagnosticId:t.diagnosticId,requestId:t.requestId,session:t.session,command:t.command,debug:t.debug}:{}}function g(t){let e=s.getStore();if(!e)return;let n={ts:new Date().toISOString(),level:t.level??"info",phase:t.phase,session:e.session,requestId:e.requestId,command:e.command,durationMs:t.durationMs,data:t.data?r(t.data):void 0};if(e.events.push(n),!e.debug)return;let o=`${JSON.stringify(n)}
1
+ import{AsyncLocalStorage as t}from"node:async_hooks";import e from"node:crypto";import n from"node:fs";import o from"node:os";import i from"node:path";import{redactDiagnosticData as r}from"./733.js";let s=new t;function a(){return e.randomBytes(8).toString("hex")}async function c(t,n){let o={...t,diagnosticId:`${Date.now().toString(36)}-${e.randomBytes(4).toString("hex")}`,events:[],liveWrittenEventCount:0};return await s.run(o,n)}function l(t){let e=s.getStore();e&&Object.assign(e,t)}function d(){let t=s.getStore();return t?{diagnosticId:t.diagnosticId,requestId:t.requestId,session:t.session,command:t.command,debug:t.debug}:{}}function g(t){let e=s.getStore();if(!e)return;let n={ts:new Date().toISOString(),level:t.level??"info",phase:t.phase,session:e.session,requestId:e.requestId,command:e.command,durationMs:t.durationMs,data:t.data?r(t.data):void 0};if(e.events.push(n),!e.debug)return;let o=`${JSON.stringify(n)}
2
2
  `;try{e.logPath&&(f(e.logPath,o),e.liveWrittenEventCount=e.events.length),e.traceLogPath&&f(e.traceLogPath,o),e.logPath||e.traceLogPath||process.stderr.write(`[agent-device][diag] ${o}`)}catch{}}async function u(t,e,n){let o=Date.now();try{let i=await e();return g({level:"info",phase:t,durationMs:Date.now()-o,data:n}),i}catch(e){throw g({level:"error",phase:t,durationMs:Date.now()-o,data:{...n??{},error:e instanceof Error?e.message:String(e)}}),e}}function m(t={}){let e=s.getStore();if(!e||!t.force&&!e.debug||0===e.events.length)return null;try{if(e.logPath){let t=e.events.slice(e.liveWrittenEventCount);if(t.length>0){let n=t.map(t=>JSON.stringify(r(t)));f(e.logPath,`${n.join("\n")}
3
3
  `)}let n=e.logPath;return e.events=[],e.liveWrittenEventCount=0,n}let t=(e.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),s=new Date().toISOString().slice(0,10),a=i.join(o.homedir(),".agent-device","logs",t,s);n.mkdirSync(a,{recursive:!0});let c=new Date().toISOString().replace(/[:.]/g,"-"),l=i.join(a,`${c}-${e.diagnosticId}.ndjson`),d=e.events.map(t=>JSON.stringify(r(t)));return n.writeFileSync(l,`${d.join("\n")}
4
4
  `),e.events=[],l}catch{return null}}function f(t,e){n.mkdirSync(i.dirname(t),{recursive:!0}),n.appendFileSync(t,e,"utf8")}export{a as createRequestId,g as emitDiagnostic,m as flushDiagnosticsToSessionFile,d as getDiagnosticsMeta,l as updateDiagnosticsScope,u as withDiagnosticTimer,c as withDiagnosticsScope};
@@ -0,0 +1 @@
1
+ import{deflateSync as t,inflateSync as e}from"node:zlib";import{AppError as r}from"./733.js";let n=Buffer.from([137,80,78,71,13,10,26,10]),i=new Map([[0,1],[2,3],[3,1],[4,2],[6,4]]),o=new Map([[0,new Set([1,2,4,8,16])],[2,new Set([8,16])],[3,new Set([1,2,4,8])],[4,new Set([8,16])],[6,new Set([8,16])]]),f=[{x:0,y:0,dx:8,dy:8},{x:4,y:0,dx:8,dy:8},{x:0,y:4,dx:4,dy:8},{x:2,y:0,dx:4,dy:4},{x:0,y:2,dx:2,dy:4},{x:1,y:0,dx:2,dy:2},{x:0,y:1,dx:1,dy:2}];class a{width;height;data;static sync={read:h,write:l};constructor(t){this.width=E(t.width,"width"),this.height=E(t.height,"height");let e=this.width*this.height*4;if(this.data=t.data?Buffer.from(t.data):Buffer.alloc(e),this.data.length!==e)throw Error(`PNG data length must be ${e} bytes`)}}function h(t){var r;let{metadata:h,idatChunks:l}=function(t){let e,r=[];for(let f of function*(t){if(!t.subarray(0,n.length).equals(n))throw Error("Invalid PNG signature");let e=n.length;for(;e<t.length;){if(e+12>t.length)throw Error("Truncated PNG chunk");let r=t.readUInt32BE(e),n=t.toString("ascii",e+4,e+8),i=e+8,o=i+r;if(o+4>t.length)throw Error(`Truncated PNG ${n} chunk`);let f=t.subarray(i,o),a=t.readUInt32BE(o);if(g(t.subarray(e+4,o))!==a)throw Error(`Invalid PNG ${n} chunk CRC`);e=o+4,yield{type:n,data:f}}}(t))if("IHDR"===f.type?e=function(t){var e;if(13!==t.length)throw Error("Invalid PNG IHDR length");let r=t.readUInt32BE(0),n=t.readUInt32BE(4),f=t[8],a=t[9],h=t[10],l=t[11],u=t[12];if(e=a,!i.has(e))throw Error(`Unsupported PNG color type ${a}`);let c=o.get(a);if(!c?.has(f))throw Error(`Unsupported PNG color type ${a} with bit depth ${f}`);if(0!==h)throw Error(`Unsupported PNG compression method ${h}`);if(0!==l)throw Error(`Unsupported PNG filter method ${l}`);if(0!==u&&1!==u)throw Error(`Unsupported PNG interlace method ${u}`);return{width:E(r,"width"),height:E(n,"height"),bitDepth:f,colorType:a,interlace:u}}(f.data):"IDAT"===f.type?r.push(Buffer.from(f.data)):e=function(t,e){if("PLTE"===t.type){if(!e)throw Error("PNG PLTE appeared before IHDR");e.palette=Buffer.from(t.data)}else if("tRNS"===t.type){if(!e)throw Error("PNG tRNS appeared before IHDR");e.transparency=Buffer.from(t.data)}return e}(f,e),"IEND"===f.type)break;return{metadata:e,idatChunks:r}}(t);if(!h)throw Error("PNG is missing IHDR");if(0===l.length)throw Error("PNG is missing IDAT");let s=function(t,r){let n=function(t){if(0===t.interlace)return function(t,e){return(p(t)+1)*e}(t,t.height);let e=0;for(let r of f){let n=c(t.width,r.x,r.dx),i=c(t.height,r.y,r.dy);0!==n&&0!==i&&(e+=function(t,e){return(p(t)+1)*e}({...t,width:n,height:i},i))}return e}(r);try{let r=e(Buffer.concat(t),{maxOutputLength:n});if(r.length!==n)throw Error("PNG pixel data is truncated");return r}catch(t){var i;if((i=t)instanceof Error&&"code"in i&&"ERR_BUFFER_TOO_LARGE"===i.code)throw Error(`PNG pixel data exceeds expected length ${n}`);throw t}}(l,h);return new a({width:h.width,height:h.height,data:1===h.interlace?function(t,e){let r=Buffer.alloc(e.width*e.height*4),n=0;for(let i of f){let o=c(e.width,i.x,i.dx),f=c(e.height,i.y,i.dy);if(0===o||0===f)continue;let a={...e,width:o,height:f,interlace:0},h=u({inflated:t,offset:n,scanlineLength:p(a),height:f,bytesPerPixel:y(a)});n=h.offset;let l=p(a);for(let t=0;t<f;t+=1){let n=h.raw.subarray(t*l,(t+1)*l);for(let f=0;f<o;f+=1){let o=i.x+f*i.dx,h=((i.y+t*i.dy)*e.width+o)*4,[l,u,c,s]=d(n,f,a);r[h]=l,r[h+1]=u,r[h+2]=c,r[h+3]=s}}}return r}(s,h):function(t,e){let r=Buffer.alloc(e.width*e.height*4),n=p(e);for(let i=0;i<e.height;i+=1){let o=t.subarray(i*n,(i+1)*n);for(let t=0;t<e.width;t+=1){let n=(i*e.width+t)*4,[f,a,h,l]=d(o,t,e);r[n]=f,r[n+1]=a,r[n+2]=h,r[n+3]=l}}return r}(u({inflated:s,offset:0,scanlineLength:p(r=h),height:r.height,bytesPerPixel:y(r)}).raw,h)})}function l(e){let r=4*e.width,i=Buffer.alloc((r+1)*e.height);for(let t=0;t<e.height;t+=1){let n=t*(r+1);i[n]=0,e.data.copy(i,n+1,t*r,(t+1)*r)}let o=Buffer.alloc(13);return o.writeUInt32BE(e.width,0),o.writeUInt32BE(e.height,4),o[8]=8,o[9]=6,o[10]=0,o[11]=0,o[12]=0,Buffer.concat([n,w("IHDR",o),w("IDAT",t(i)),w("IEND",Buffer.alloc(0))])}function u(t){let{inflated:e,offset:r,scanlineLength:n,height:i,bytesPerPixel:o}=t,f=r+(n+1)*i;if(e.length<f)throw Error("PNG pixel data is truncated");let a=Buffer.alloc(n*i);for(let t=0;t<i;t+=1){let i=r+t*(n+1),f=t*n,h=e[i];for(let r=0;r<n;r+=1){let l=e[i+1+r],u=r>=o?a[f+r-o]:0,c=t>0?a[f+r-n]:0,d=t>0&&r>=o?a[f+r-n-o]:0;a[f+r]=function(t,e,r,n,i){if(0===t)return e;if(1===t)return e+r&255;if(2===t)return e+n&255;if(3===t)return e+Math.floor((r+n)/2)&255;if(4===t)return e+function(t,e,r){let n=t+e-r,i=Math.abs(n-t),o=Math.abs(n-e),f=Math.abs(n-r);return i<=o&&i<=f?t:o<=f?e:r}(r,n,i)&255;throw Error(`Unsupported PNG filter type ${t}`)}(h,l,u,c,d)}}return{raw:a,offset:f}}function c(t,e,r){return t<=e?0:Math.floor((t-e+r-1)/r)}function d(t,e,r){if(3===r.colorType){var n,o,f,a,h,l,u,c=t,d=e,p=r;if(!p.palette)throw Error("Indexed PNG is missing PLTE");let i=s(c,d,p.bitDepth),y=3*i;if(y+2>=p.palette.length)throw Error("Indexed PNG palette is invalid");return[p.palette[y],p.palette[y+1],p.palette[y+2],p.transparency?.[i]??255]}if(r.bitDepth<8){let i,o;return[o=Math.round((i=s(t,e,(n=r).bitDepth))/((1<<n.bitDepth)-1)*255),o,o,255*!(n.transparency&&n.transparency.length>=2&&i===n.transparency.readUInt16BE(0))]}let y=16===r.bitDepth?2:1,w=e*i.get(r.colorType)*y,g=e=>16===r.bitDepth?t.readUInt16BE(w+2*e):t[w+e*y],E=t=>{var e;return e=g(t),16===r.bitDepth?Math.round(e/65535*255):e};if(0===r.colorType){let t=E(0);return[t,t,t,255*(o=g(0),!(f=r).transparency||!!(f.transparency.length<2)||o!==f.transparency.readUInt16BE(0))]}if(2===r.colorType){return[E(0),E(1),E(2),255*(a=g(0),h=g(1),l=g(2),!(u=r).transparency||!!(u.transparency.length<6)||a!==u.transparency.readUInt16BE(0)||h!==u.transparency.readUInt16BE(2)||l!==u.transparency.readUInt16BE(4))]}if(4===r.colorType){let t=E(0);return[t,t,t,E(1)]}return[E(0),E(1),E(2),E(3)]}function s(t,e,r){let n=e*r;return t[Math.floor(n/8)]>>8-r-n%8&(1<<r)-1}function p(t){let e=i.get(t.colorType);return Math.ceil(t.width*e*t.bitDepth/8)}function y(t){return Math.max(1,Math.ceil(i.get(t.colorType)*t.bitDepth/8))}function w(t,e){let r=Buffer.from(t,"ascii"),n=Buffer.alloc(8+e.length+4);return n.writeUInt32BE(e.length,0),r.copy(n,4),e.copy(n,8),n.writeUInt32BE(g(Buffer.concat([r,e])),8+e.length),n}function g(t){let e=0xffffffff;for(let r of t){e^=r;for(let t=0;t<8;t+=1)e=1&e?0xedb88320^e>>>1:e>>>1}return(0xffffffff^e)>>>0}function E(t,e){if(!Number.isInteger(t)||t<1)throw Error(`PNG ${e} must be positive`);return t}function x(t,e){try{return a.sync.read(t)}catch(t){throw new r("COMMAND_FAILED",`Failed to decode ${e} as PNG`,{label:e,reason:t instanceof Error?t.message:String(t)})}}function B(t){let{baselineData:e,currentData:r,maxColorDistance:n}=t,i=t.width*t.height,o=Buffer.alloc(4*i),f=new Uint8Array(i),a=0;for(let t=0,i=0;t<e.length;t+=4,i+=1){if(Math.sqrt((e[t]-r[t])**2+(e[t+1]-r[t+1])**2+(e[t+2]-r[t+2])**2)>n){a+=1,f[i]=1;let e=P(r,t);o[t]=b(e,220,.78),o[t+1]=b(e,0,.78),o[t+2]=b(e,0,.78),o[t+3]=255;continue}let h=P(r,t);o[t]=h,o[t+1]=h,o[t+2]=h,o[t+3]=255}return{diffData:o,diffMask:f,differentPixels:a}}function P(t,e){return b(Math.round(.299*t[e]+.587*t[e+1]+.114*t[e+2]),255,.72)}function b(t,e,r){return Math.round(t*(1-r)+e*r)}function I(t){return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}export{a as PNG,B as computeScreenshotDiffPixels,x as decodePng,I as toBuffer};
@@ -1,3 +1,3 @@
1
- import e from"node:fs";import{parseAllDocuments as t,stringify as n}from"yaml";import{AppError as r}from"./9152.js";import{MAESTRO_NEW_ISSUE_URL as i,MAESTRO_COMPAT_TRACKER_URL as o,readScreenshotScriptFlag as s}from"./6133.js";import{formatScriptStringLiteral as l,parseReplayOpenFlags as a,formatPortableActionLine as u,parseReplaySeriesFlags as f,parseReplayRuntimeFlags as p,isClickLikeCommand as c}from"./123.js";let h=/^[A-Z_][A-Z0-9_]*$/,d=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,m="AD_VAR_";function g(e){return e.startsWith("AD_")}function A(e){return new r("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function y(e){let t={};if(e.builtins)for(let[n,r]of Object.entries(e.builtins))t[n]=r;for(let n of[e.fileEnv,e.shellEnv,e.cliEnv])if(n)for(let[e,r]of Object.entries(n)){if(g(e))throw A(e);t[e]=r}return{values:t}}function v(e,t){Object.assign(e.values,t)}function w(e){let t={};for(let[n,r]of Object.entries(e)){if("string"!=typeof r||!n.startsWith(m))continue;let e=n.slice(m.length);0!==e.length&&h.test(e)&&(g(e)||(t[e]=r))}return t}function b(e){let t={};for(let n of e){let e=n.indexOf("=");if(e<=0)throw new r("INVALID_ARGS",`Invalid -e entry "${n}": expected KEY=VALUE.`);let i=n.slice(0,e);if(!h.test(i))throw new r("INVALID_ARGS",`Invalid -e key "${i}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(g(i))throw A(i);t[i]=n.slice(e+1)}return t}function I(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function $(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))"string"==typeof r&&(t[n]=r);return t}return process.env}function S(e,t,n){return e.replace(d,(e,i,o,s)=>{if(i)return"${";if(!o)return e;if(Object.prototype.hasOwnProperty.call(t.values,o))return String(t.values[o]);if(void 0!==s)return s.replace(/\\(.)/g,"$1");throw new r("INVALID_ARGS",`Unresolved variable \${${o}} at ${n.file}:${n.line}.`)})}function _(e,t,n){return{...e,positionals:(e.positionals??[]).map(e=>S(e,t,n)),flags:N(e.flags,t,n)??{},runtime:N(e.runtime,t,n),replayControl:function(e,t,n){if(!e)return e;if(e.kind==="maestroRunFlowWhen"){return{...e,selector:S(e.selector,t,n)}}return e}(e.replayControl,t,n)}}function N(e,t,n){return e?function e(t,n,r){return"string"==typeof t?S(t,n,r):Array.isArray(t)?t.map(t=>e(t,n,r)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,n,r)])):t}(e,t,n):e}let R=new Set(["ios","android","macos","linux"]),D=new Set(["mobile","tv","desktop"]);function M(e){let t=[],n=[],i=e.split(/\r?\n/),o=!1;for(let[e,l]of i.entries()){let i=l.trim();if(0===i.length||i.startsWith("#"))continue;if(x(i)){if(o)throw new r("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let u=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[n,...i]=function(e){let t=[],n=0;for(;n<e.length&&!((n=function(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}(e,n))>=e.length);){let i='"'===e[n]?function(e,t){let n=!1,i=t+1;for(;i<e.length;i+=1){let t=e.charAt(i);if('"'===t&&!n)break;if(n){n=!1;continue}n="\\"===t}if(i>=e.length)throw new r("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,i+1)),nextCursor:i+1}}(e,n):function(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}(e,n);t.push(i.value),n=i.nextCursor}return t}(t);if(void 0===n||"context"===n)return null;let o={ts:Date.now(),command:n,positionals:[],flags:{}};if("snapshot"===n){o.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if("-i"===t){o.flags.snapshotInteractiveOnly=!0;continue}if("-c"!==t){if("--raw"===t){o.flags.snapshotRaw=!0;continue}if("--force-full"===t){o.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(o.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<i.length){o.flags.snapshotScope=i[e+1],e+=1;continue}if("--backend"===t&&e+1<i.length){e+=1;continue}}}return o}if("open"===n){let e=a(i);return o.positionals=e.positionals,Object.assign(o.flags,e.flags),o.runtime=e.runtime,o}if("runtime"===n){let e=p(i);return o.positionals=e.positionals,Object.assign(o.flags,e.flags),o}if(c(n)){let e=f(n,i);Object.assign(o.flags,e.flags);let t=e.positionals[0];if(void 0===t)return o;if(t.startsWith("@"))return o.positionals=[t],e.positionals[1]&&(o.result={refLabel:e.positionals[1]}),o;let r=e.positionals[0],s=e.positionals[1];return j(r)&&j(s)&&e.positionals.length>=2?o.positionals=[r,s]:o.positionals=[e.positionals.join(" ")],o}if("fill"===n){let e=f(n,i);if(Object.assign(o.flags,e.flags),!(e.positionals.length>=2))return o.positionals=e.positionals,o;let[t,r,...s]=e.positionals;return t.startsWith("@")?(s.length>0?(o.positionals=[t,s.join(" ")],o.result={refLabel:r}):o.positionals=[t,r],o):(o.positionals=[t,[r,...s].join(" ")],o)}if("get"===n){let e=i[0],t=i[1];return void 0===e||void 0===t?o.positionals=i:t.startsWith("@")?(o.positionals=[e,t],i[2]&&(o.result={refLabel:i[2]})):o.positionals=[e,i.slice(1).join(" ")],o}if("swipe"===n||"type"===n){let e=f(n,i);return Object.assign(o.flags,e.flags),o.positionals=e.positionals,o}if("record"===n){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t];if("--hide-touches"===n){o.flags.hideTouches=!0;continue}if("--fps"===n&&t+1<i.length){let e=Number(i[t+1]);Number.isFinite(e)&&(o.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===n&&t+1<i.length){let e=Number(i[t+1]);Number.isFinite(e)&&(o.flags.quality=Math.floor(e)),t+=1;continue}e.push(n)}return o.positionals=e,o}if("screenshot"===n){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=s({args:i,index:t,flags:o.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return o.positionals=e,o}return o.positionals=i,o}(l);u&&(t.push(u),n.push(e+1),o=!0)}return{actions:t,actionLines:n}}function O(e){let t=e.split(/\r?\n/),n={};for(let[e,i]of t.entries()){let t=i.trim();if(0===t.length||t.startsWith("#"))continue;if(x(t)){!function(e,t,n){let{key:i,value:o}=function(e,t){let n=e.slice(3).replace(/^[\s]+/,""),i=n.indexOf("=");if(i<=0)throw new r("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let o=n.slice(0,i);if(!h.test(o))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(o.startsWith("AD_"))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${o} to avoid the AD_ prefix.`);return{key:o,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new r("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(n.slice(i+1),t)}}(t,n),s=e.env??{};if(Object.prototype.hasOwnProperty.call(s,i))throw new r("INVALID_ARGS",`Duplicate env directive "${i}" on line ${n}.`);s[i]=o,e.env=s}(n,t,e+1);continue}if(!t.startsWith("context "))break;let o=t.match(/(?:^|\s)platform=([^\s]+)/);if(o){let e=o[1];e&&R.has(e)&&L(n,"platform",e)}let s=t.match(/(?:^|\s)target=([^\s]+)/);if(s){let e=s[1];e&&D.has(e)&&L(n,"target",e)}let l=t.match(/(?:^|\s)timeout=(\d+)/);if(l){let e=Number(l[1]);Number.isFinite(e)&&e>=1&&L(n,"timeoutMs",Math.floor(e))}let a=t.match(/(?:^|\s)retries=(\d+)/);if(a){let e=Number(a[1]);Number.isFinite(e)&&e>=0&&L(n,"retries",Math.floor(e))}}return n}function x(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function L(e,t,n){let i=e[t];if(void 0!==i)throw new r("INVALID_ARGS",i===n?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(i)} vs ${String(n)}.`);e[t]=n}function j(e){return!!e&&!Number.isNaN(Number(e))}function V(t,n,r){let i=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";i.push(`context platform=${r.device.platform}${t} device=${l(r.device.name)}${e} theme=unknown`)}for(let e of n)i.push(u(e,{runtimeIncludeAllPositionals:!0}));let o=`${i.join("\n")}
1
+ import e from"node:fs";import{parseAllDocuments as t,stringify as n}from"yaml";import{AppError as r}from"./733.js";import{MAESTRO_NEW_ISSUE_URL as i,MAESTRO_COMPAT_TRACKER_URL as o,readScreenshotScriptFlag as s}from"./9873.js";import{formatScriptStringLiteral as l,parseReplayOpenFlags as a,formatPortableActionLine as u,parseReplaySeriesFlags as f,parseReplayRuntimeFlags as p,isClickLikeCommand as c}from"./5299.js";let h=/^[A-Z_][A-Z0-9_]*$/,d=/(\\\$\{)|\$\{([A-Za-z_][A-Za-z0-9_.]*)(?::-((?:[^}\\]|\\.)*))?\}/g,m="AD_VAR_";function g(e){return e.startsWith("AD_")}function A(e){return new r("INVALID_ARGS",`The AD_* namespace is reserved for built-in variables. Rename ${e} to avoid the AD_ prefix.`)}function y(e){let t={};if(e.builtins)for(let[n,r]of Object.entries(e.builtins))t[n]=r;for(let n of[e.fileEnv,e.shellEnv,e.cliEnv])if(n)for(let[e,r]of Object.entries(n)){if(g(e))throw A(e);t[e]=r}return{values:t}}function v(e,t){Object.assign(e.values,t)}function w(e){let t={};for(let[n,r]of Object.entries(e)){if("string"!=typeof r||!n.startsWith(m))continue;let e=n.slice(m.length);0!==e.length&&h.test(e)&&(g(e)||(t[e]=r))}return t}function b(e){let t={};for(let n of e){let e=n.indexOf("=");if(e<=0)throw new r("INVALID_ARGS",`Invalid -e entry "${n}": expected KEY=VALUE.`);let i=n.slice(0,e);if(!h.test(i))throw new r("INVALID_ARGS",`Invalid -e key "${i}": keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(g(i))throw A(i);t[i]=n.slice(e+1)}return t}function I(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function $(e){if(e&&"object"==typeof e&&!Array.isArray(e)){let t={};for(let[n,r]of Object.entries(e))"string"==typeof r&&(t[n]=r);return t}return process.env}function S(e,t,n){return e.replace(d,(e,i,o,s)=>{if(i)return"${";if(!o)return e;if(Object.prototype.hasOwnProperty.call(t.values,o))return String(t.values[o]);if(void 0!==s)return s.replace(/\\(.)/g,"$1");throw new r("INVALID_ARGS",`Unresolved variable \${${o}} at ${n.file}:${n.line}.`)})}function _(e,t,n){return{...e,positionals:(e.positionals??[]).map(e=>S(e,t,n)),flags:N(e.flags,t,n)??{},runtime:N(e.runtime,t,n),replayControl:function(e,t,n){if(!e)return e;if(e.kind==="maestroRunFlowWhen"){return{...e,selector:S(e.selector,t,n)}}return e}(e.replayControl,t,n)}}function N(e,t,n){return e?function e(t,n,r){return"string"==typeof t?S(t,n,r):Array.isArray(t)?t.map(t=>e(t,n,r)):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).map(([t,i])=>[t,e(i,n,r)])):t}(e,t,n):e}let R=new Set(["ios","android","macos","linux"]),D=new Set(["mobile","tv","desktop"]);function M(e){let t=[],n=[],i=e.split(/\r?\n/),o=!1;for(let[e,l]of i.entries()){let i=l.trim();if(0===i.length||i.startsWith("#"))continue;if(x(i)){if(o)throw new r("INVALID_ARGS",`env directives must precede all actions (line ${e+1}).`);continue}let u=function(e){let t=e.trim();if(0===t.length||t.startsWith("#"))return null;let[n,...i]=function(e){let t=[],n=0;for(;n<e.length&&!((n=function(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}(e,n))>=e.length);){let i='"'===e[n]?function(e,t){let n=!1,i=t+1;for(;i<e.length;i+=1){let t=e.charAt(i);if('"'===t&&!n)break;if(n){n=!1;continue}n="\\"===t}if(i>=e.length)throw new r("INVALID_ARGS",`Invalid replay script line: ${e}`);return{value:JSON.parse(e.slice(t,i+1)),nextCursor:i+1}}(e,n):function(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}(e,n);t.push(i.value),n=i.nextCursor}return t}(t);if(void 0===n||"context"===n)return null;let o={ts:Date.now(),command:n,positionals:[],flags:{}};if("snapshot"===n){o.positionals=[];for(let e=0;e<i.length;e+=1){let t=i[e];if("-i"===t){o.flags.snapshotInteractiveOnly=!0;continue}if("-c"!==t){if("--raw"===t){o.flags.snapshotRaw=!0;continue}if("--force-full"===t){o.flags.snapshotForceFull=!0;continue}if(("-d"===t||"--depth"===t)&&e+1<i.length){let t=Number(i[e+1]);Number.isFinite(t)&&t>=0&&(o.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if(("-s"===t||"--scope"===t)&&e+1<i.length){o.flags.snapshotScope=i[e+1],e+=1;continue}if("--backend"===t&&e+1<i.length){e+=1;continue}}}return o}if("open"===n){let e=a(i);return o.positionals=e.positionals,Object.assign(o.flags,e.flags),o.runtime=e.runtime,o}if("runtime"===n){let e=p(i);return o.positionals=e.positionals,Object.assign(o.flags,e.flags),o}if(c(n)){let e=f(n,i);Object.assign(o.flags,e.flags);let t=e.positionals[0];if(void 0===t)return o;if(t.startsWith("@"))return o.positionals=[t],e.positionals[1]&&(o.result={refLabel:e.positionals[1]}),o;let r=e.positionals[0],s=e.positionals[1];return j(r)&&j(s)&&e.positionals.length>=2?o.positionals=[r,s]:o.positionals=[e.positionals.join(" ")],o}if("fill"===n){let e=f(n,i);if(Object.assign(o.flags,e.flags),!(e.positionals.length>=2))return o.positionals=e.positionals,o;let[t,r,...s]=e.positionals;return t.startsWith("@")?(s.length>0?(o.positionals=[t,s.join(" ")],o.result={refLabel:r}):o.positionals=[t,r],o):(o.positionals=[t,[r,...s].join(" ")],o)}if("get"===n){let e=i[0],t=i[1];return void 0===e||void 0===t?o.positionals=i:t.startsWith("@")?(o.positionals=[e,t],i[2]&&(o.result={refLabel:i[2]})):o.positionals=[e,i.slice(1).join(" ")],o}if("swipe"===n||"type"===n){let e=f(n,i);return Object.assign(o.flags,e.flags),o.positionals=e.positionals,o}if("record"===n){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t];if("--hide-touches"===n){o.flags.hideTouches=!0;continue}if("--fps"===n&&t+1<i.length){let e=Number(i[t+1]);Number.isFinite(e)&&(o.flags.fps=Math.floor(e)),t+=1;continue}if("--quality"===n&&t+1<i.length){let e=Number(i[t+1]);Number.isFinite(e)&&(o.flags.quality=Math.floor(e)),t+=1;continue}e.push(n)}return o.positionals=e,o}if("screenshot"===n){let e=[];for(let t=0;t<i.length;t+=1){let n=i[t],r=s({args:i,index:t,flags:o.flags});if(r.handled){t=r.nextIndex;continue}e.push(n)}return o.positionals=e,o}return o.positionals=i,o}(l);u&&(t.push(u),n.push(e+1),o=!0)}return{actions:t,actionLines:n}}function O(e){let t=e.split(/\r?\n/),n={};for(let[e,i]of t.entries()){let t=i.trim();if(0===t.length||t.startsWith("#"))continue;if(x(t)){!function(e,t,n){let{key:i,value:o}=function(e,t){let n=e.slice(3).replace(/^[\s]+/,""),i=n.indexOf("=");if(i<=0)throw new r("INVALID_ARGS",`Invalid env directive on line ${t}: expected "env KEY=VALUE".`);let o=n.slice(0,i);if(!h.test(o))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(o.startsWith("AD_"))throw new r("INVALID_ARGS",`Invalid env key "${o}" on line ${t}: the AD_* namespace is reserved for built-in variables. Rename ${o} to avoid the AD_ prefix.`);return{key:o,value:function(e,t){if(0===e.length)return"";if(e.startsWith('"'))try{let t=JSON.parse(e);if("string"!=typeof t)throw Error("not a string literal");return t}catch{throw new r("INVALID_ARGS",`Invalid quoted env value on line ${t}.`)}return e}(n.slice(i+1),t)}}(t,n),s=e.env??{};if(Object.prototype.hasOwnProperty.call(s,i))throw new r("INVALID_ARGS",`Duplicate env directive "${i}" on line ${n}.`);s[i]=o,e.env=s}(n,t,e+1);continue}if(!t.startsWith("context "))break;let o=t.match(/(?:^|\s)platform=([^\s]+)/);if(o){let e=o[1];e&&R.has(e)&&L(n,"platform",e)}let s=t.match(/(?:^|\s)target=([^\s]+)/);if(s){let e=s[1];e&&D.has(e)&&L(n,"target",e)}let l=t.match(/(?:^|\s)timeout=(\d+)/);if(l){let e=Number(l[1]);Number.isFinite(e)&&e>=1&&L(n,"timeoutMs",Math.floor(e))}let a=t.match(/(?:^|\s)retries=(\d+)/);if(a){let e=Number(a[1]);Number.isFinite(e)&&e>=0&&L(n,"retries",Math.floor(e))}}return n}function x(e){return"env"===e||e.startsWith("env ")||e.startsWith("env ")}function L(e,t,n){let i=e[t];if(void 0!==i)throw new r("INVALID_ARGS",i===n?`Duplicate replay test metadata "${t}" in context header.`:`Conflicting replay test metadata "${t}" in context header: ${String(i)} vs ${String(n)}.`);e[t]=n}function j(e){return!!e&&!Number.isNaN(Number(e))}function V(t,n,r){let i=[];if(r){let e=r.device.kind?` kind=${r.device.kind}`:"",t=r.device.target?` target=${r.device.target}`:"";i.push(`context platform=${r.device.platform}${t} device=${l(r.device.name)}${e} theme=unknown`)}for(let e of n)i.push(u(e,{runtimeIncludeAllPositionals:!0}));let o=`${i.join("\n")}
2
2
  `,s=`${t}.tmp-${process.pid}-${Date.now()}`;e.writeFileSync(s,o),e.renameSync(s,t)}function k(e){let n=t(e);for(let e of n)if(e.errors.length>0){let t=e.errors[0]?.message??"Invalid Maestro YAML flow.";throw new r("INVALID_ARGS",`Invalid Maestro YAML flow: ${t}`)}return n.map(e=>e.toJSON()).filter(e=>null!==e)}function E(e){return`${e.map(e=>n(e).trimEnd()).join("\n---\n")}
3
3
  `}function G(e,t=[],n){return{ts:Date.now(),command:e,positionals:t,flags:n??{}}}function C(e,t,n){let r=new Set(n),i=Object.keys(e).filter(e=>!r.has(e));if(i.length>0)throw H(`Maestro ${t} field "${i[0]}" is not supported yet.`)}function P(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function W(e){return e.map((e,t)=>{if("string"==typeof e||P(e))return e;throw new r("INVALID_ARGS",`Unsupported Maestro command at index ${t+1}: expected a scalar or one-key map.`)})}function F(e){if(e){let t;return"android"===(t=e.trim().toLowerCase())?"android":"ios"===t?"ios":void 0}}function K(e,t){if(null==e)return{};if(!P(e))throw new r("INVALID_ARGS",`${t} expects a map.`);let n={};for(let[t,r]of Object.entries(e))("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(n[t]=String(r));return n}function U(e,t){return P(e)&&"number"==typeof e.timeout&&Number.isFinite(e.timeout)?Math.max(0,Math.floor(e.timeout)):t}function q(e,t){if(e.appId)return e.appId;throw new r("INVALID_ARGS",`${t} requires appId in the Maestro flow config.`)}function z(e,t){if("string"==typeof t)return t;throw new r("INVALID_ARGS",`${e} expects a string value.`)}function Y(e,t){return e.replace(/\$\{([A-Za-z_][A-Za-z0-9_.]*)\}/g,(e,n)=>Object.prototype.hasOwnProperty.call(t.env,n)?String(t.env[n]):e)}function Z(e){throw H(`Maestro command "${e}" is not supported yet.`)}function H(e){throw new r("INVALID_ARGS",`${e} See supported/unsupported Maestro compatibility at ${o}. If this syntax matters for your flows, comment there or open a focused issue at ${i}.`)}function J(e,t){return`${e},${t}`}function T(e){let t=e.match(/^(\d+),(\d+)$/);if(!t)throw H('Only absolute Maestro point selectors like "100,200" are supported.');return{x:Number(t[1]),y:Number(t[2])}}function B(e){let t=e.match(/^\s*(\d+)\s*,\s*(\d+)\s*$/);if(t)return{kind:"absolute",x:Number(t[1]),y:Number(t[2])};let n=e.match(/^\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*$/);if(n)return{kind:"percent",x:Number(n[1]),y:Number(n[2])};throw H('Only Maestro swipe coordinates like "100,200" or "50%,75%" are supported.')}export{C as assertOnlyKeys,y as buildReplayVarScope,w as collectReplayShellEnv,J as formatMaestroPoint,P as isPlainRecord,v as mergeReplayVarScopeValues,W as normalizeCommandList,F as normalizePlatform,T as parseAbsolutePoint,B as parseMaestroPoint,k as parseMaestroYamlDocuments,b as parseReplayCliEnvEntries,M as parseReplayScriptDetailed,K as readEnvMap,I as readReplayCliEnvEntries,O as readReplayScriptMetadata,$ as readReplayShellEnvSource,U as readTimeoutMs,q as requireAppId,z as requireStringValue,Y as resolveMaestroString,_ as resolveReplayAction,E as stringifyMaestroYamlDocuments,G as support_action,Z as unsupportedCommand,H as unsupportedMaestroSyntax,V as writeReplayScript};
@@ -0,0 +1 @@
1
+ import e from"node:fs";import t from"node:path";import{AppError as n}from"./733.js";import{resolveUserPath as r}from"./9612.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};