agent-device 0.17.4 → 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 (126) hide show
  1. package/README.md +2 -2
  2. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.4.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.4.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.4.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.4.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/RunnerSynthesizedGesture.h +4 -0
  90. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +8 -0
  91. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +118 -10
  92. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +5 -0
  93. package/package.json +14 -13
  94. package/server.json +3 -3
  95. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.4.apk.sha256 +0 -1
  96. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.4.apk.sha256 +0 -1
  97. package/dist/src/1010.js +0 -1
  98. package/dist/src/123.js +0 -1
  99. package/dist/src/1231.js +0 -1
  100. package/dist/src/208.js +0 -1
  101. package/dist/src/221.js +0 -6
  102. package/dist/src/2415.js +0 -38
  103. package/dist/src/3675.js +0 -1
  104. package/dist/src/5611.js +0 -1
  105. package/dist/src/5827.js +0 -1
  106. package/dist/src/6088.js +0 -1
  107. package/dist/src/6133.js +0 -1
  108. package/dist/src/6629.js +0 -1
  109. package/dist/src/7556.js +0 -1
  110. package/dist/src/7719.js +0 -1
  111. package/dist/src/7847.js +0 -1
  112. package/dist/src/8133.js +0 -1
  113. package/dist/src/8656.js +0 -1
  114. package/dist/src/9010.js +0 -1
  115. package/dist/src/9471.js +0 -1
  116. package/dist/src/9542.js +0 -6
  117. package/dist/src/9616.js +0 -2
  118. package/dist/src/9639.js +0 -2
  119. package/dist/src/9671.js +0 -1
  120. package/dist/src/9818.js +0 -1
  121. package/dist/src/989.js +0 -1
  122. /package/dist/src/{2301.js → 4069.js} +0 -0
  123. /package/dist/src/{4829.js → 5560.js} +0 -0
  124. /package/dist/src/{4778.js → 6024.js} +0 -0
  125. /package/dist/src/{9152.js → 733.js} +0 -0
  126. /package/dist/src/{3267.js → 9612.js} +0 -0
package/dist/src/9542.js DELETED
@@ -1,6 +0,0 @@
1
- import e from"node:fs";import t from"node:http";import a from"node:https";import r from"node:path";import{pipeline as n}from"node:stream/promises";import i from"node:os";import{createHash as o,randomUUID as s}from"node:crypto";import{Writable as d}from"node:stream";import l from"node:net";import c from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./9152.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./9818.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./7599.js";import{isAgentDeviceDaemonProcess as I,stopProcessForTakeover as v}from"./8656.js";import{readSnapshotDiagnosticsSummary as b,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as M,isDaemonResponseEnvelope as P,isDaemonProgressEnvelope as D,resolveDaemonPaths as _,resolveDaemonServerMode as k,computeDaemonCodeSignature as E,resolveDaemonTransportPreference as x}from"./4012.js";import{INTERNAL_COMMANDS as N,PUBLIC_COMMANDS as $}from"./6088.js";import{readVersion as T,findProjectRoot as C}from"./9671.js";import{sleep as U}from"./4829.js";import{normalizeSession as L,readRequiredString as R,readSerializedSnapshotCaptureAnnotations as O,readOptionalString as F,normalizeMaterializationReleaseResult as B,readSnapshotNodes as q,normalizeDeployResult as j,appDaemonWriters as V,observabilityDaemonWriters as G,normalizeOpenDevice as H,replayDaemonWriters as K,buildMeta as z,systemDaemonWriters as Y,resolveSessionName as W,buildFlags as J,reactNativeDaemonWriters as X,interactionDaemonWriters as Q,captureDaemonWriters as Z,perfDaemonWriters as ee,gestureDaemonWriters as et,selectorDaemonWriters as ea,createBatchDaemonWriter as er,normalizeRuntimeHints as en,normalizeDevice as ei,recordingDaemonWriters as eo,readScreenshotOverlayRefs as es,normalizeStartupSample as ed,normalizeInstallFromSourceResult as el}from"./6133.js";import{reloadMetro as ec,prepareMetroRuntime as eu}from"./1974.js";function ef(e){return new Promise((t,a)=>{let r="";e.setEncoding("utf8"),e.on("data",e=>{r+=e}),e.on("end",()=>t(r)),e.on("error",a)})}let ep="sha256";async function em(e){let t=await eh(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eI({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await ev(t.payloadPath,r),await eM({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await eg({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function eh(t,a){var n,i,o;let s,d=e.statSync(t),l=r.basename(t),c=d.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=d,s=i.toLowerCase(),o.isDirectory()&&s.endsWith(".app")||s.endsWith(".ipa")?"ios":s.endsWith(".apk")||s.endsWith(".aab")?"android":void 0),f=[];try{let a=c?await ey(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:l,artifactType:c?"app-bundle":"file",platform:u,contentType:c?"application/gzip":"application/octet-stream",sha256:await eP(a),sizeBytes:r.size,cleanup:()=>ew(f)}}catch(e){throw ew(f),e}}async function ey(t,a){let n=e.mkdtempSync(r.join(i.tmpdir(),`agent-device-upload-${s()}-`));a.push(n);let o=r.join(n,`${r.basename(t)}.tar.gz`);return await m("tar",["czf",o,"-C",r.dirname(t),r.basename(t)],{env:{...process.env,COPYFILE_DISABLE:"1"}}),o}function ew(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function eg(e){let{normalizedBase:t,token:a,artifact:r}=e,n=new URL("upload",t),i={"content-type":r.contentType,"x-artifact-type":r.artifactType,"x-artifact-filename":r.fileName,"x-artifact-hash":r.sha256,"x-artifact-hash-algorithm":ep,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await eb({url:n,method:"POST",headers:i,payloadPath:r.payloadPath,timeoutMessage:"Artifact upload timed out",timeoutHint:"The upload to the remote daemon exceeded the 5-minute timeout.",errorMessage:"Failed to upload artifact to remote daemon",errorHint:"Verify the remote daemon is reachable and supports artifact uploads."});try{let e=JSON.parse(o.body);if(!e.ok||!e.uploadId)throw new f("COMMAND_FAILED",`Upload failed: ${o.body}`);return e.uploadId}catch(e){if(e instanceof f)throw e;throw new f("COMMAND_FAILED",`Invalid upload response: ${o.body}`)}}async function eI(e){let t=new URL("upload/preflight",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return function(e){var t;if(!e||"object"!=typeof e||!0!==e.ok||"string"!=typeof e.uploadId)return;if(!0===e.cacheHit)return{kind:"cache-hit",uploadId:e.uploadId};let a=e.upload;if(!a||"string"!=typeof a.url)return;let r=a.headers??{};if(!(!(t=r)||"object"!=typeof t||Array.isArray(t))&&Object.values(t).every(e=>"string"==typeof e))return{kind:"direct-upload",uploadId:e.uploadId,url:a.url,headers:r}}(await r.json().catch(()=>void 0))}async function ev(e,t){let a=await eb({url:new URL(t.url),method:"PUT",headers:t.headers,payloadPath:e,timeoutMessage:"Direct artifact upload timed out",timeoutHint:"The direct upload ticket did not accept the artifact within the timeout.",errorMessage:"Failed to upload artifact with direct upload ticket"});if(a.statusCode<200||a.statusCode>=300)throw new f("COMMAND_FAILED","Direct artifact upload failed",{statusCode:a.statusCode,statusMessage:a.statusMessage})}async function eb(e){return await eA({...e,url:e.url,redirectCount:0,startOffset:0})}async function eA(r){var i,o,s;let d="https:"===r.url.protocol?a:t,l=e.statSync(r.payloadPath).size,c=(i=r.headers,o=r.startOffset,s=l,o<=0?i:{...i,"content-length":Math.max(s-o,0),"content-range":`bytes ${o}-${s-1}/${s}`});return await new Promise((t,a)=>{let i=!1,o=d.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:c},e=>{i=!0,ef(e).then(n=>{clearTimeout(s);let i=e.statusCode??500,o=e.headers.location;if(o&&[301,302,303,307,308].includes(i)){if(r.redirectCount>=5)return void a(new f("COMMAND_FAILED","Artifact upload exceeded redirect limit",{maxRedirects:5,url:r.url.toString()}));let e=new URL(o,r.url);return void eA({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let d=308===i?function(e,t){let a=function(e){let t=eS(e);if(void 0===t)return;let a=Number(t);return Number.isSafeInteger(a)&&a>=0?a:void 0}(e["x-upload-offset"]??e["upload-offset"]);if(void 0!==a)return Math.min(a,t);let r=eS(e.range),n=r?.match(/^bytes=0-(\d+)$/);if(!n)return;let i=Number(n[1]);if(Number.isSafeInteger(i)&&!(i<0))return Math.min(i+1,t)}(e.headers,l):void 0;void 0!==d?d>=l?t({statusCode:200,statusMessage:"Upload already complete",body:""}):d<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:d,previousOffset:r.startOffset,url:r.url.toString()})):eA({...r,startOffset:d}).then(t,a):t({statusCode:i,statusMessage:e.statusMessage,body:n})}).catch(a)}),s=setTimeout(()=>{o.destroy(),a(new f("COMMAND_FAILED",r.timeoutMessage,{timeoutMs:3e5,...r.timeoutHint?{hint:r.timeoutHint}:{}}))},3e5);o.on("error",e=>{i||(clearTimeout(s),a(new f("COMMAND_FAILED",r.errorMessage,r.errorHint?{hint:r.errorHint}:{},e)))}),o.on("close",()=>clearTimeout(s)),n(e.createReadStream(r.payloadPath,{start:r.startOffset}),o).catch(e=>{i||(o.destroy(),a(new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:Error(String(e)))))})})}function eS(e){return Array.isArray(e)?e[0]:e}async function eM(e){let t=new URL("upload/finalize",e.normalizedBase),a={"content-type":"application/json"};e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=await fetch(t,{method:"POST",headers:a,signal:AbortSignal.timeout(3e4),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new f("COMMAND_FAILED","Failed to finalize direct artifact upload",{},e)});if(!r.ok)throw new f("COMMAND_FAILED","Direct artifact upload finalize failed",{status:r.status,statusText:r.statusText});let n=await r.json().catch(()=>void 0);if(!n?.ok||!n.uploadId)throw new f("COMMAND_FAILED","Invalid upload finalize response");return n.uploadId}async function eP(t){let a=o(ep),r=new d({write(e,t,r){a.update(e),r()}});return await n(e.createReadStream(t),r).catch(e=>{throw new f("COMMAND_FAILED","Failed to read local artifact",{},e instanceof Error?e:void 0)}),a.digest("hex")}async function eD(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,d={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return ek({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:d});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=ex(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eN("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eN("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=ex(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eN("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let d=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,d}(e,i,o,d);let l=await eE(e,t);l&&(s=l.installSource,n=l.uploadedArtifactId??n);let c=()=>ek({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:d});return"install"!==e.command&&"reinstall"!==e.command||(n=await e_(e,t,i)??n),c()}async function e_(t,a,n){var i,o;let s,d=n[1];if(void 0===d)return;if(d.startsWith("remote:")){n[1]=d.slice(7);return}let l=(i=d,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(l)return await em({localPath:l,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function ek(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function eE(t,a){let n=t.meta?.installSource;if("install_source"!==t.command||!n||"path"!==n.kind)return null;let i=n.path.trim();if(!i)return{installSource:n};if(i.startsWith("remote:"))return{installSource:{...n,path:i.slice(7)}};let o=r.isAbsolute(i)?i:r.resolve(t.meta?.cwd??process.cwd(),i);if(!e.existsSync(o))return{installSource:{...n,path:o}};let s=await em({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function ex(e,t,a,n=0){let i=e.positionals?.[n]??e.flags?.out,o=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=i&&i.trim().length>0?i:o;return r.isAbsolute(s)?s:r.resolve(e.meta?.cwd??process.cwd(),s)}function eN(e,t){let a=t.startsWith(".")?t:`.${t}`;return r.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function e$(e,t,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let i=a.data?{...a.data}:{},o=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){o.push(a);continue}let n=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=t.meta?.clientArtifactPaths?.[e.field];if(a&&a.trim().length>0)return a;let n=e.fileName?.trim()||`${e.field}-${Date.now()}`;return r.resolve(t.meta?.cwd??process.cwd(),n)}(a,t);await eT({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:t.meta?.requestId}),i[a.field]=n,o.push({...a,localPath:n})}return i.artifacts=o,{ok:!0,data:i}}async function eT(i){var o,s;let d,l=new URL((o=i.baseUrl,s=i.artifactId,d=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,d).toString())),c="https:"===l.protocol?a:t;await e.promises.mkdir(r.dirname(i.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,o=i.timeoutMs??9e4,s=n=>{if(!r){if(r=!0,clearTimeout(u),n)return void e.promises.rm(i.destinationPath,{force:!0}).finally(()=>a(n));t()}},d=c.request({protocol:l.protocol,host:l.hostname,port:l.port,method:"GET",path:l.pathname+l.search,headers:i.token?{authorization:`Bearer ${i.token}`,"x-agent-device-token":i.token}:void 0},t=>{if((t.statusCode??500)>=400){let e="";t.setEncoding("utf8"),t.on("data",t=>{e+=t}),t.on("end",()=>{s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,statusCode:t.statusCode,requestId:i.requestId,body:e}))});return}t.on("aborted",()=>{s(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:i.artifactId,requestId:i.requestId}))}),n(t,e.createWriteStream(i.destinationPath)).then(()=>s(),e=>s(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let e=new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o});s(e),d.destroy(e)},o);d.on("error",e=>{e instanceof f?s(e):s(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:i.artifactId,requestId:i.requestId,timeoutMs:o},e instanceof Error?e:void 0))}),d.end()})}function eC(e){var t,a,r;let n,i,o=eV(e);if(!o||"object"!=typeof o)return null;let s="string"==typeof(t=o).token&&t.token.length>0?t.token:null;if(!s)return null;let d=(n=eL((a=o).port),i=eL(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return d?{token:s,...d,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eL(o.pid)??0,version:eU(o.version),codeSignature:eU(o.codeSignature),processStartTime:eU(o.processStartTime)}:null}function eU(e){return"string"==typeof e?e:void 0}function eL(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eR(e){let t=eV(e);return t&&"object"==typeof t&&Number.isInteger(t.pid)&&Number(t.pid)>0?{pid:Number(t.pid),processStartTime:"string"==typeof t.processStartTime?t.processStartTime:void 0,startedAt:"number"==typeof t.startedAt?t.startedAt:void 0}:null}async function eO(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,d,l;let a=e.existsSync(t.infoPath),r=eC(t.infoPath);if(r){let e=I(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eq(r),i.stoppedInfoProcess=!0),o=t.infoPath,eG(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eG(s),i.removedInfo=!0);let c=e.existsSync(t.lockPath),u=eR(t.lockPath);if(u){let e=I(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await v(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),d=t.lockPath,eG(d),i.removedLock=!0)}else c&&(l=t.lockPath,eG(l),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return g({level:i.error?"warn":"info",phase:"daemon_startup_metadata_cleanup",data:i}),i}function eF(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eB(e){let t=eF(e);if(!t.hasLock||t.hasInfo)return!1;let a=eR(e.lockPath);return!(a&&I(a.pid,a.processStartTime))&&(eG(e.lockPath),!0)}async function eq(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function ej(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eV(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eG(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function eH(e){let t=Math.max(0,e)/1e3;return t>=10?`${t.toFixed(1)}s`:t>=1?`${t.toFixed(2)}s`:`${t.toFixed(3).replace(/0+$/,"").replace(/\.$/,"")}s`}let eK={start:"START",pass:"PASS",fail:"FAIL",skip:"SKIP"};function ez(e){var t,a,n,i,o,s,d;let l,c,u,f,p,m,h,y,w,g,I,v="replay-test-suite"===e.type?(t=e,l=[`Running replay suite: ${t.total} ${1===t.total?"file":"files"}`],t.shardMode&&t.shardCount&&t.shardCount>1&&l.push(` sharding: ${t.shardMode} across ${t.shardCount} devices`),l.push(` artifacts: ${t.artifactsDir}`),l.join("\n")):"replay-test"===e.type?(function(e,t){if("start"===t.status){t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`);return}let a=t.message?.replace(/\s+/g," ").trim();a&&e.push(` ${a}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(I=[(n=a=e,p=`[${n.index}/${n.total}]`,m=(i=n).retrying?"RETRY":eK[i.status],h=(o=n,c=o.title?.trim(),u=r.basename(o.file),c?`${JSON.stringify(c)} in ${u}`:u),y=function(e){if("number"!=typeof e.shardIndex)return"";let t="number"==typeof e.shardCount?e.shardCount:"?",a="string"==typeof e.deviceId?` ${e.deviceId}`:"";return` [shard ${e.shardIndex+1}/${t}${a}]`}(n),w=void 0===(s=n).attempt||"start"===s.status?"":"fail"===s.status&&s.retrying&&void 0!==s.maxAttempts?` attempt ${s.attempt}/${s.maxAttempts}`:s.attempt>1?` after ${s.attempt} attempts`:"",g=void 0!==n.durationMs?` (${f=eH((d=n).durationMs??0),d.attempt&&d.attempt>1&&!d.retrying?`total ${f}`:f})`:"",`${p} ${m} ${h}${y}${w}${g}`)],a),I.join("\n")):void 0;v&&process.stderr.write(`${v}
2
- `)}function eY(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,d;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,d=r.meta?.requestId,e=s.data??{},new f(u(null!=e.code?String(e.code):void 0,"COMMAND_FAILED"),String(e.message??s.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:d})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));eW(a,r,t.result,n,i)}catch(t){i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:e},t instanceof Error?t:void 0))}}async function eW(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await e$(e,t,a):a)}catch(e){n(e)}}let eJ=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function eX(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of eJ){let a=h("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=!n&&"snapshot"!==r,d=s?function(e,t){let a=!1;try{I(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{eq(e)}finally{eG(t.infoPath),eG(t.lockPath)}return{forcedKill:a}}(e,t):{forcedKill:!1};return g({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:i,requestId:a,command:r,timedOutRunnerPidsTerminated:o.terminated,timedOutRunnerCleanupError:o.error,daemonPidReset:s?e.pid:void 0,daemonPidForceKilled:s?d.forcedKill:void 0,daemonPreservedAfterTimeout:!n&&!s,daemonBaseUrl:e.baseUrl}}),new f("COMMAND_FAILED","Daemon request timed out",{timeoutMs:i,requestId:a,hint:function(e){let{remote:t,resetDaemon:a,command:r}=e;if(t)return"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.";if(!a){let e=r===$.snapshot?" If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.":"";return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??"request"} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return"Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected."}({remote:n,resetDaemon:s,command:r})})}async function eQ(e,t){let a=e3(e,t);if(await eZ(e,a))return!0;let r=e5(e,t,a);return!!r&&await eZ(e,r)}async function eZ(e,r){var n;return"http"===r?await function(e){let r=e.baseUrl?e9(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve(!1);let n=new URL(r),i="https:"===n.protocol?a:t,o=e.baseUrl?3e3:500;return new Promise(e=>{let t=i.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:o},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((n=e.port)?new Promise(e=>{let t=!1,a=l.createConnection({host:"127.0.0.1",port:n},()=>{r(!0)}),r=r=>{t||(t=!0,a.destroy(),e(r))};a.setTimeout(500),a.on("timeout",()=>{r(!1)}),a.on("error",()=>{r(!1)})}):Promise.resolve(!1))}async function e0(e,t,a,r,n){let i=e3(e,a);try{return await e1(e,t,r,n,i)}catch(d){var o;let s=e5(e,a,i);if(!s||(o=d,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw d;return await e1(e,t,r,n,s)}}async function e1(e,t,a,r,n){return"http"===n?await e8(e,t,a,r):await e6(e,t,a,r)}function e3(e,t){if(e.baseUrl){if("socket"===t)throw new f("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(e2(a,r))return r;throw new f("COMMAND_FAILED","http"===r?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>e2(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function e2(e,t){return"http"===t?!!e.httpPort:!!e.port}function e5(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return e2(e,r)?r:null}function e4(e,t,a,r={}){return g({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new f("COMMAND_FAILED","Failed to communicate with daemon",{...r,requestId:t,hint:a?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e instanceof Error?e:void 0)}async function e6(e,t,a,r){let n=e.port;if(!n)throw new f("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((i,o)=>{let s=!1,d=l.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,d.write(`${JSON.stringify(t)}
3
- `)}),c=!1,u="number"==typeof r?setTimeout(()=>{c=!0,d.destroy(),o(eX(e,a,t.meta?.requestId,t.command,!1,r))},r):void 0;!function(e,t){let{req:a,isSettled:r,resolve:n,reject:i,clearTimeout:o}=t,s="",d=(e,t)=>{o(),i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0))};e.setEncoding("utf8"),e.on("data",t=>{if(r())return;let a=A(s,t);for(let t of(s=a.buffer,a.lines))try{let a=JSON.parse(t);if(D(a)){ez(a.event);continue}let r=P(a)?a.response:a;o(),n(r),e.end();return}catch(e){d(t,e);return}})}(d,{req:t,isSettled:()=>c,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{c=!0,i(e)},reject:e=>{c=!0,o(e)}}),d.on("error",e=>{c||(c=!0,u&&clearTimeout(u),o(e4(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function e8(e,r,n,i){var o,s;let d,l=e.baseUrl?new URL(e9(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!l)throw new f("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let c=JSON.stringify((o={includeTokenParam:!e.baseUrl},d=r.meta?.requestId??y(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:d,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:d,method:function(e){switch(e){case"lease_allocate":return"agent_device.lease.allocate";case"lease_heartbeat":return"agent_device.lease.heartbeat";case"lease_release":return"agent_device.lease.release"}}(r.command),params:function(e,t,a){let r={...a.includeTokenParam?{token:e.token}:{},session:e.session,tenantId:e.meta?.tenantId,runId:e.meta?.runId};switch(t){case"lease_allocate":return{...r,ttlMs:e.meta?.leaseTtlMs,backend:e.meta?.leaseBackend};case"lease_heartbeat":return{...r,leaseId:e.meta?.leaseId,ttlMs:e.meta?.leaseTtlMs};case"lease_release":return{...r,leaseId:e.meta?.leaseId}}}(r,r.command,o)})),u={"content-type":"application/json","content-length":Buffer.byteLength(c)};return e.baseUrl&&e.token&&(u.authorization=`Bearer ${e.token}`,u["x-agent-device-token"]=e.token),await new Promise((o,s)=>{let d=("https:"===l.protocol?a:t).request({protocol:l.protocol,host:l.hostname,port:l.port,method:"POST",path:l.pathname+l.search,headers:u},t=>{var a;(a=t.headers?.["content-type"],M(r)&&String(Array.isArray(a)?a.join(","):a??"").includes("application/x-ndjson"))?function(e,t){let{req:a,handleResponseBody:r,reject:n,clearTimeout:i}=t,o="",s=!1,d=e=>{try{let t=JSON.parse(e);if(D(t))return ez(t.event),!1;if(P(t))return s=!0,i(),r(JSON.stringify(t.response)),!0;throw Error("Missing daemon progress response envelope")}catch(t){return s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e},t instanceof Error?t:void 0)),!0}};e.setEncoding("utf8"),e.on("data",e=>{if(s)return;let t=A(o,e);for(let e of(o=t.buffer,t.lines))if(e&&d(e))return}),e.on("end",()=>{if(s)return;let e=o.trim();e&&d(e)||(s=!0,i(),n(new f("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:e})))}),e.on("error",e=>{s||(s=!0,i(),n(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:a.meta?.requestId},e instanceof Error?e:void 0)))})}(t,{req:r,reject:s,clearTimeout:()=>{m&&clearTimeout(m)},handleResponseBody:t=>eY(t,{info:e,req:r,resolve:o,reject:s})}):ef(t).then(t=>{m&&clearTimeout(m),eY(t,{info:e,req:r,resolve:o,reject:s})}).catch(e=>{m&&clearTimeout(m),s(new f("COMMAND_FAILED","Failed to read daemon response",{requestId:r.meta?.requestId},e instanceof Error?e:void 0))})}),p=ej(e),m="number"==typeof i?setTimeout(()=>{d.destroy(),s(eX(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;d.on("error",e=>{m&&clearTimeout(m),s(e4(e,r.meta?.requestId,p))}),d.write(c),d.end()})}function e9(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let e7=new l.BlockList;async function te(e){if(e.remoteBaseUrl)return await tt(e);let t=await ta(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=eF(e);if(!t.hasLock||t.hasInfo)return;let a=eR(e.lockPath);if(!a)return eG(e.lockPath);I(a.pid,a.processStartTime)||eG(e.lockPath)}(e.paths),await tr(e))}async function tt(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await eQ(t,"http"))return{info:t,startedByClient:!1};throw new f("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}async function ta(e){var t,a;let r=eC(e.paths.infoPath);if(!r)return null;let n=await eQ(r,e.transportPreference);return(t=r,a=n,t.version===T()&&t.codeSignature===td()&&a)?r:(function(e,t,a){try{var r,n;let i=e.version?`pid ${e.pid}, v${e.version}`:`pid ${e.pid}`,o=(r=e,n=t,r.version!==T()?`version mismatch (client v${T()})`:r.codeSignature!==td()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
4
- `)}catch{}}(r,n,e.paths.baseDir),await eq(r),eG(e.paths.infoPath),null)}async function tr(t){let a,r,n=0,i=[];for(let o=1;o<=2;o+=1){let s;try{r={pid:(s=function(t){let a=ts(),r=a.useSrc?["--experimental-strip-types",a.srcPath]:[a.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:t.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:t.serverMode};e.mkdirSync(t.paths.baseDir,{recursive:!0});let i=e.openSync(t.paths.logPath,"a"),o=e.openSync(t.paths.logPath,"a");try{return p(process.execPath,r,{env:n,stdio:["ignore",i,o]})}finally{e.closeSync(i),e.closeSync(o)}}(t)).pid}}catch(e){if(a=e instanceof Error?e.message:String(e),i.push(await eO(t.paths,"start_error")),o<2){await U(150);continue}break}let d=await to(15e3,t,s);if("ready"===d.kind)return{info:d.info,startedByClient:!0};if("early_exit"===d.kind){if(r=d.exit,a=tl(d.exit),i.push(await eO(t.paths,"start_error")),o<2){await U(150);continue}break}if(await eB(t.paths)){n+=1;continue}let l=eF(t.paths),c=o<2,u=await eO(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await to(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tl(e.exit));break}if(!c)break;l.hasInfo||l.hasLock||await U(150)}let o=eF(t.paths),s=function(t){try{if(!e.existsSync(t))return;let a=e.statSync(t);if(a.size<=0)return;let r=Math.min(a.size,64e3),n=e.openSync(t,"r");try{let t=Buffer.alloc(r);e.readSync(n,t,0,r,a.size-r);let i=t.toString("utf8").trim();return i.length>0?i:void 0}finally{e.closeSync(n)}}catch{return}}(t.paths.logPath);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",stateDir:t.paths.baseDir,infoPath:t.paths.infoPath,lockPath:t.paths.lockPath,logPath:t.paths.logPath,startupTimeoutMs:15e3,startupAttempts:2,lockRecoveryCount:n,cleanupResults:i,startError:a,daemonProcess:r,...s?{daemonLogTail:s}:{},metadataState:o,hint:function(e,t=_(process.env.AGENT_DEVICE_STATE_DIR)){var a;let r=(a=t,`rm -f ${S(a.infoPath)} ${S(a.lockPath)}`);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${r}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${r}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${r}`}(o,t.paths)})}async function tn(t,a,r){if(!ti(t.command)||!a.startedByClient&&!r.ownedStateDir||ej(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eq(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eG(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eG(r.paths.lockPath),n.removedLock=a&&!e.existsSync(r.paths.lockPath),r.ownedStateDir&&(e.rmSync(r.paths.baseDir,{recursive:!0,force:!0}),n.removedStateDir=!e.existsSync(r.paths.baseDir))}g({level:n.error?"warn":"info",phase:"daemon_replay_cleanup",data:n})}function ti(e){return e===$.replay||e===$.test}async function to(e,t,a){let r,n=Date.now();for(a.exited.then(e=>{r=e});Date.now()-n<e;){if(r)return{kind:"early_exit",exit:r};let e=eC(t.paths.infoPath);if(e&&await eQ(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await U(100)}return{kind:"timeout"}}function ts(){let t=C(),a=[r.join(t,"dist","src","internal","daemon.js"),r.join(t,"dist","src","daemon.js")],n=a[0];if(void 0===n)throw new f("COMMAND_FAILED","Daemon dist path list is empty");let i=a.find(t=>e.existsSync(t))??n,o=r.join(t,"src","daemon.ts"),s=a.some(t=>e.existsSync(t)),d=e.existsSync(o);if(!s&&!d)throw new f("COMMAND_FAILED","Daemon entry not found",{distPaths:a,srcPath:o});return{root:t,distPath:i,distPaths:a,srcPath:o,useSrc:process.execArgv.includes("--experimental-strip-types")?d:!s&&d}}function td(){let e=ts();return E(e.useSrc?e.srcPath:e.distPath,e.root)}function tl(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}async function tc(t){var a,n,o,s,d;let c,u,p,m,h,I,v,b=t.meta?.requestId??y(),A=!!(t.meta?.debug||t.flags?.verbose),S=(a=t,m=a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,n=t,function(e,t){let a;if(!(!e||"localhost"===(a=new URL(e).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(l.isIPv4(a)?e7.check(a,"ipv4"):!!l.isIPv6(a)&&e7.check(a,"ipv6")))&&("string"!=typeof t||!(t.trim().length>0)))throw new f("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:e,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."})}(u=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new f("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new f("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(c=n.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),p=n.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),I=function(e,t){let a=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,r=x(a);if(t&&"socket"===r)throw new f("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:t});return{preference:r,serverMode:k(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(t,(h={rawBaseUrl:c,remoteBaseUrl:u,authToken:p}).remoteBaseUrl),o=t,s=m,d=h.rawBaseUrl,{paths:_((v=ti(o.command)&&!s&&!d)?e.mkdtempSync(r.join(i.tmpdir(),"agent-device-replay-daemon-")):m),transportPreference:I.preference,serverMode:I.serverMode,ownedStateDir:v,remoteBaseUrl:h.remoteBaseUrl,remoteAuthToken:h.authToken}),M=function(e){if(e.command!==$.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===$.prepare||t===$.replay||t===$.snapshot)?e.flags.timeoutMs:e.command===$.prepare?24e4:9e4}}(t),P=await w("daemon_startup",async()=>await te(S),{requestId:b,session:t.session}),D=P.info,E=await eD(t,D),N={...t,positionals:E.positionals,flags:E.flags,token:D.token,meta:{...t.meta??{},requestId:b,debug:A,cwd:t.meta?.cwd,sessionExplicit:t.meta?.sessionExplicit,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,lockPolicy:t.meta?.lockPolicy,lockPlatform:t.meta?.lockPlatform,...E.uploadedArtifactId?{uploadedArtifactId:E.uploadedArtifactId}:{},...E.clientArtifactPaths?{clientArtifactPaths:E.clientArtifactPaths}:{},...E.installSource?{installSource:E.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:b,command:t.command,session:t.session}});try{return await w("daemon_request",async()=>await e0(D,N,S.transportPreference,S.paths,M),{requestId:b,command:t.command})}finally{await tn(t,P,S)}}e7.addSubnet("127.0.0.0",8,"ipv4"),e7.addAddress("::1","ipv6"),e7.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tu=/^[0-9a-fA-F-]{32,36}$/;function tf(e){if(e&&tu.test(e))return e.replaceAll("-","").toUpperCase()}function tp(e,t){return`${e.uuid}:${tm(t)}`}function tm(e){return`0x${e.toString(16)}`}function th(e){return"string"==typeof e&&e.length>0?e:void 0}function ty(...e){for(let t of e){let e=th(t);if(e)return e}}function tw(e){return"object"==typeof e&&null!==e}function tg(e){return tw(e)?e:void 0}function tI(e){try{let t=JSON.parse(e);return tw(t)?t:null}catch{return null}}function tv(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function tb(e,t,a){var r;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(r=e[t])?r:"number"==typeof r&&Number.isSafeInteger(r)?BigInt(r):"string"!=typeof r?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(r)?BigInt(r):void 0;if(void 0!==n)return n;tA(a,t)}function tA(e,t){throw new f("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function tS(e){return[...new Set(e)]}let tM=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tP(e){return e.dsym&&e.searchPath?[tN(e.cwd,e.dsym),...await tD(tN(e.cwd,e.searchPath))]:e.dsym?[tN(e.cwd,e.dsym)]:e.searchPath?await tD(tN(e.cwd,e.searchPath)):[]}async function tD(e){let t=[],a=0;async function n(i){if(!(t.length>=200)){if((a+=1)>1e4)throw new f("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:e,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await t_(i,e)).isDirectory()){i===e&&function(e){throw new f("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(e);return}if(i.endsWith(".dSYM"))return void t.push(i);for(let e of(await c.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function t_(e,t){try{return await c.stat(e)}catch{throw new f("INVALID_ARGS",`debug symbols search path does not exist: ${t}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function tk(e,t){let a=(await Promise.all(tS(e).map(e=>tE(e,t)))).flat();if(0===a.length)throw new f("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function tE(e,t){var a;await tx(e);let r=await m(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==r.exitCode)throw new f("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:r.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,r.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=tf(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tx(e){let t=await c.stat(e).catch(()=>null);if(!(t?.isDirectory()&&e.endsWith(".dSYM")))throw new f("INVALID_ARGS",`Not a .dSYM bundle: ${e}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function tN(e,t){return r.resolve(e,t)}function t$(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tT(e,t,a,r){return{index:e,image:t.name,address:tm(a),symbol:r.get(tp(t,a))?.text}}function tC(e){var t;let a;return[(a=(t=e).topFrames.find(e=>e.symbol))?`Start with ${a.symbol} in ${a.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function tU(e,t,a){let r=new Map;for(let n of(function(e,t){let a=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let n=`${r.image.uuid}:${e.dsym.binaryPath}`,i=a.get(n)??{...e,addresses:[]};i.addresses.push(r.address),a.set(n,i)}return a})(e,t).values())for(let e of(await tL(a,n)))r.set(tp(e.image,e.address),e);return r}async function tL(e,t){var a,r,n,i;let o,s,d=tS(t.addresses.map(tm)),l=await m(e,(a=t,r=d,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tm(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==l.exitCode&&function(e){throw new f("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(l.stderr),n=t.image,i=d,s=(""===(o=l.stdout.split(/\r?\n/)).at(-1)&&o.pop(),o),i.map((e,t)=>{let a=s[t]?.trim();return{image:n,address:BigInt(e),text:!function(e,t){if(!e)return!1;let a=e.trim().toLowerCase();return!!a&&"??"!==a&&a!==t.toLowerCase()&&!a.startsWith("0x")}(a,e)?void 0:a}})}async function tR(){return{dwarfdump:await tO("dwarfdump"),atos:await tO("atos")}}async function tO(e){try{let t=await m("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),a=t.stdout.trim();if(0===t.exitCode&&a.length>0)return a}catch{}throw new f("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function tF(e){var t,a,n,i,o,s,d,l,u,p,m,h,y,w,g,I,v,b,A,S,M,P,D,_,k,E,x;let N,$,T,C,U,L,R,O,F;if(void 0!==e.action&&"symbols"!==e.action)throw new f("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let B=e.cwd??process.cwd(),q=tj(B,e.artifact),j=tj(B,e.out??(a=q,$=(N=r.extname(a))?a.slice(0,-N.length):a,`${$}-symbolicated${N||".log"}`)),V=function(e){var t;let a,n=function(e){let t=tI(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tI(e.slice(a+1));return n?{header:r,payload:n}:null}(e);if(!n)return null;let i=(Array.isArray(n.payload.usedImages)?n.payload.usedImages:[]).flatMap((e,t)=>(function(e,t){if(!e||"object"!=typeof e)return[];let a=tf(th(e.uuid)),n=tb(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=th(e.path);return[{index:t,name:th(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:th(e.arch),base:n,path:i}]})(e,t));if(0===i.length)return null;let o=(t=Array.isArray(n.payload.threads)?n.payload.threads:[],a=new Map(i.map(e=>[e.index,e])),t.flatMap((e,t)=>(function(e){if(!e||"object"!=typeof e)return[];let t=e.frames;return Array.isArray(t)?t.filter(e=>tw(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tv(e[t]);if(void 0!==r)return r;tA(a,t)}(e,"imageIndex","IPS frame"),i=tb(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let o=t.get(n);return o?[{frame:e,frameIndex:r,threadIndex:a,image:o,address:o.base+i}]:[]})(e,a,t,r))));return{format:"ips",images:i,addresses:o.map(({frame:e,...t})=>t),document:n,frameMatches:o,write:e=>(function(e,t,a){for(let e of t){let t=a.get(tp(e.image,e.address))?.text;t&&function(e,t){let a,r=(a=t.match(/^(.*) \+ (\d+)$/))?{symbol:a[1],location:Number(a[2])}:{symbol:t};e.symbol=r.symbol,void 0!==r.location&&(e.symbolLocation=r.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...a.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}
5
- `;return e.header?`${e.header}
6
- ${r}`:r})(n,o,e)}}(t=await tB(q,"crash artifact"))??function(e){let t=e.split("\n"),a=function(e){let t=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return t;for(let n of e.slice(a+1)){let e=function(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let a=tf(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tM.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=r.basename(t);return{name:e.startsWith(i)?i:e}}(t[3].trim(),t[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}(n);e&&t.push(e)}return t}(t);if(0===a.length)return null;let n=function(e,t){let a,r=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?a=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(a=void 0);let o=function(e,t){let a=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!a)return null;let r=a[1].trim(),n=BigInt(a[2]),i=function(e,t,a){let r=e.filter(e=>e.name===t);return r.find(e=>{var t,r;return t=e,r=a,void 0!==t.end&&t.base<=r&&r<=t.end})??(1===r.length?r[0]:void 0)}(t,r,n);return i?{image:i,address:n}:null}(i,t),s=i.match(/^\s*(\d+)/);o&&s&&r.push({...o,frameIndex:Number(s[1]),lineIndex:n,threadIndex:a})}return r}(t,a);return{format:"text",images:a,addresses:n,lines:t,frameMatches:n,write(e){let a=new Map(n.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let n=a.get(r);if(!n)return t;let i=e.get(tp(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);V||function(){throw new f("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let G=await tP({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===G.length)throw new f("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let H=await tR(),K=await tk(G,H.dwarfdump),z=function(e,t,a){let r=new Map;for(let a of e){let e=t.find(e=>e.uuid===a.uuid&&(void 0===a.arch||void 0===e.arch||e.arch===a.arch));e&&r.set(a.uuid,{image:a,dsym:e})}if(r.size>0)return r;let n=tS(e.map(e=>e.uuid)),i=tS(t.map(e=>e.uuid));throw new f("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:n.length,artifactUuidSample:n.slice(0,5),dsymUuidCount:i.length,dsymUuidSample:i.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(V.images,K,!!e.dsym),Y=await tU(V.addresses,z,H.atos),W=V.write(Y);await c.mkdir(r.dirname(j),{recursive:!0}),await c.writeFile(j,W,"utf8");let J=[...z.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),X=[...Y.values()].filter(e=>e.text).length,Q=V.images.length-J.length,Z=Q>0?[`${Q} Apple image${1===Q?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:q,outPath:j,crash:"ips"===V.format?(n=V.document,i=V.frameMatches,o=Y,U=function(e){let t=tv(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tg(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(d=s.header)?tI(d):null,{appName:(l=T,u=C,ty(l.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,ty(tg(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,ty(tg(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,ty(w.incident,g?.incident_id)),timestamp:(I=T,v=C,ty(I.captureTime,v?.timestamp)),exceptionType:(b=T.exception,th(tg(b)?.type)),exceptionCodes:function(e){let t=tg(e);if(t)return ty(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tg(e);if(t){let e;return(e=[th(t.namespace),th(t.code),th(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,M=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>tT(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tC(L)}):(P=V.lines,D=V.frameMatches,_=Y,O=function(e){let t=t$(e,"Triggered by Thread"),a=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(a))return a;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(P),{...F={format:"text",appName:(R=t$(P,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:t$(P,"Identifier"),version:t$(P,"Version"),incident:t$(P,"Incident Identifier"),timestamp:t$(P,"Date/Time"),exceptionType:t$(P,"Exception Type"),exceptionCodes:t$(P,"Exception Codes"),terminationReason:t$(P,"Termination Reason"),crashedThread:O,topFrames:(k=D,E=O,x=_,void 0===E?[]:k.filter(e=>e.threadIndex===E).slice(0,5).map(e=>tT(e.frameIndex,e.image,e.address,x))),findings:[]},findings:tC(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${j}`}}async function tB(e,t){await tq(e,t);try{return await c.readFile(e,"utf8")}catch(a){throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}async function tq(e,t){try{let a=await c.stat(e);if(a.size<=0x4000000)return;throw new f("INVALID_ARGS",`${t} is too large: ${e}`,{actualBytes:a.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(a){if(a instanceof f)throw a;throw new f("INVALID_ARGS",`Failed to read ${t}: ${e}`,{message:a instanceof Error?a.message:String(a)})}}function tj(e,t){return r.resolve(e,t)}let tV={...V,...Z,...Q,...et,...ea,...G,...ee,...X,...eo,...K,...Y,batch:er(function(e,t){let a=tV[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function tG(e={},t={}){let a=t.transport??tc,r=async(t,r=[],n={})=>{let i=tK(e,n),o=await a({session:W(i.session),command:t,positionals:r,flags:J(i),runtime:i.runtime,meta:z(i)});return o.ok||function(e){throw new f(u(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(o.error),o.data??{}},n=async(e={})=>{let t=await r(N.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(L)},i=async(e,t={})=>{let a=tV[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>W(tK(e,t).session);return{command:{wait:async e=>await i("wait",e),alert:async(e={})=>await i("alert",e),appState:async(e={})=>await i("appstate",e),back:async(e={})=>await i("back",e),home:async(e={})=>await i("home",e),rotate:async e=>await i("rotate",e),appSwitcher:async(e={})=>await i("app-switcher",e),keyboard:async(e={})=>await i("keyboard",e),clipboard:async e=>await i("clipboard",e),reactNative:async e=>await i("react-native",e),prepare:async e=>await i("prepare",e)},devices:{list:async(e={})=>{let t=await i("devices",e);return(Array.isArray(t.devices)?t.devices:[]).map(ei)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>_(tK(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},apps:{install:async e=>j(await i("install",e),o(e)),reinstall:async e=>j(await i("reinstall",e),o(e)),installFromSource:async e=>el(await i("install-from-source",e),o(e)),list:async(e={})=>{let t=await i("apps",e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async e=>{let t=o(e),a=await i("open",e),r=H(a),n=F(a,"appBundleId");return{session:t,sessionStateDir:F(a,"sessionStateDir"),appName:F(a,"appName"),appBundleId:n,appId:n,startup:ed(a.startup),runtime:en(a.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=o(e),a=(await i("close",e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>await i("push",e),triggerEvent:async e=>await i("trigger-app-event",e)},materializations:{release:async e=>B(await r(N.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>tz(await r(N.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>tz(await r(N.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(N.leaseRelease,[],e)).released})},metro:{prepare:async t=>await eu({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await ec({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{var t,a,r;let n,s,d,l,c=o(e);return t=await i("snapshot",e),a=c,n=F(t,"appBundleId"),{nodes:q(t.nodes),truncated:!0===t.truncated,appName:F(t,"appName"),appBundleId:n,...(s=tH((r=t).visibility),d=tH(r.unchanged),l=b(r.snapshotDiagnostics),{...s?{visibility:s}:{},...O(r),...d?{unchanged:d}:{},...l?{snapshotDiagnostics:l}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:R(a,"path"),overlayRefs:es(a),identifiers:{session:t}}},diff:async e=>await i("diff",e)},interactions:{click:async e=>await i("click",e),press:async e=>await i("press",e),longPress:async e=>await i("longpress",e),swipe:async e=>await i("swipe",e),pan:async e=>await i("gesture-pan",e),fling:async e=>await i("gesture-fling",e),swipeGesture:async e=>await i("gesture-swipe",e),focus:async e=>await i("focus",e),type:async e=>await i("type",e),fill:async e=>await i("fill",e),scroll:async e=>await i("scroll",e),pinch:async e=>await i("gesture-pinch",e),rotateGesture:async e=>await i("gesture-rotate",e),transformGesture:async e=>await i("gesture-transform",e),get:async e=>await i("get",e),is:async e=>await i("is",e),find:async e=>await i("find",e)},replay:{run:async e=>await i("replay",e),test:async e=>await i("test",e)},batch:{run:async e=>await i("batch",e)},observability:{perf:async(e={})=>await i("perf",e),logs:async(e={})=>await i("logs",e),network:async(e={})=>await i("network",e)},debug:{symbols:async t=>await tF({cwd:t.cwd??e.cwd,...t})},recording:{record:async e=>await i("record",e),trace:async e=>await i("trace",e)},settings:{update:async e=>await i("settings",e)}}}function tH(e){return"object"==typeof e&&null!==e?e:void 0}function tK(e,t){return{...e,...t}}function tz(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:R(t,"leaseId"),tenantId:R(t,"tenantId"),runId:R(t,"runId"),backend:R(t,"backend"),createdAt:"number"==typeof t.createdAt?t.createdAt:void 0,heartbeatAt:"number"==typeof t.heartbeatAt?t.heartbeatAt:void 0,expiresAt:"number"==typeof t.expiresAt?t.expiresAt:void 0}}export{tG as createAgentDeviceClient,eH as formatDurationSeconds,tc as sendToDaemon};
package/dist/src/9616.js DELETED
@@ -1,2 +0,0 @@
1
- import{AppError as e}from"./9152.js";let t=["ios","macos","android","linux","apple"],r=["mobile","tv","desktop"];function a(e){return e}function n(e){return"apple"===e||"ios"===e||"macos"===e}function i(e,t){return!t||("apple"===t?n(e):e===t)}function o(e){return"macos"===e||"desktop"===e?"macOS":"tv"===e?"tvOS":"iOS"}function l(e){let{simulatorSetPath:t,platform:r,target:a}=e;if(t&&"macos"!==r&&"desktop"!==a)return t}async function s(t,r,a={}){let o=t,l=e=>e.toLowerCase().replace(/_/g," ").replace(/\s+/g," ").trim();if(r.platform&&(o=o.filter(e=>i(e.platform,r.platform))),r.target&&(o=o.filter(e=>(e.target??"mobile")===r.target)),r.udid){let t=o.find(e=>e.id===r.udid&&n(e.platform));if(!t)throw new e("DEVICE_NOT_FOUND",`No Apple device with UDID ${r.udid}`);return t}if(r.serial){let t=o.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=l(r.deviceName),a=o.find(e=>l(e.name)===t);if(!a)throw new e("DEVICE_NOT_FOUND",`No device named ${r.deviceName}`);return a}let d=o[0];if(void 0!==d&&1===o.length)return d;if(0===o.length){var c;let t=a.simulatorSetPath;if(t&&(!(c=r.platform)||"apple"===c||"ios"===c))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 u=o.filter(e=>"device"!==e.kind);u.length>0&&(o=u);let m=o.filter(e=>e.booted),f=m[0];if(void 0!==f&&1===m.length)return f;let p=m[0]??o[0];if(void 0===p)throw new e("DEVICE_NOT_FOUND","No devices found",{selector:r});return p}function d(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function c(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function u(e,t){return e.find(e=>e.ref===t)??null}function m(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 f(e){if(e)return{depth:e.snapshotDepth,interactiveOnly:e.snapshotInteractiveOnly,raw:e.snapshotRaw,scope:e.snapshotScope}}function p(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}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,r)=>{var a,n;let i=_(e,r),o=(a=i.positionals,n=`${r}.positionals`,Array.isArray(a)||O(n,"Expected an array"),a),l=D(i,"meta",r);return{token:b(i,"token",r),session:b(i,"session",r),command:g(i.command,`${r}.command`),positionals:o.map((e,t)=>g(e,`${r}.positionals[${String(t)}]`)),flags:D(i,"flags",r),runtime:void 0===i.runtime?void 0:k.parse(i.runtime),meta:void 0===l?void 0:{requestId:b(l,"requestId",`${r}.meta`),debug:w(l,"debug",`${r}.meta`),cwd:b(l,"cwd",`${r}.meta`),sessionExplicit:w(l,"sessionExplicit",`${r}.meta`),tenantId:b(l,"tenantId",`${r}.meta`),runId:b(l,"runId",`${r}.meta`),leaseId:b(l,"leaseId",`${r}.meta`),leaseTtlMs:A(l,"leaseTtlMs",`${r}.meta`),leaseBackend:M(l,"leaseBackend",$,`${r}.meta`),sessionIsolation:M(l,"sessionIsolation",v,`${r}.meta`),uploadedArtifactId:b(l,"uploadedArtifactId",`${r}.meta`),clientArtifactPaths:void 0===l.clientArtifactPaths?void 0:R(l.clientArtifactPaths,`${r}.meta.clientArtifactPaths`),installSource:void 0===l.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"')}(l.installSource,`${r}.meta.installSource`),retainMaterializedPaths:w(l,"retainMaterializedPaths",`${r}.meta`),materializedPathRetentionMs:A(l,"materializedPathRetentionMs",`${r}.meta`),materializationId:b(l,"materializationId",`${r}.meta`),lockPolicy:M(l,"lockPolicy",h,`${r}.meta`),lockPlatform:M(l,"lockPlatform",t,`${r}.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,r as DEVICE_TARGETS,$ as LEASE_BACKENDS,S as NETWORK_INCLUDE_MODES,t as PLATFORM_SELECTORS,v as SESSION_ISOLATION_MODES,d as attachRefs,m as buildSnapshotPresentationKey,p as centerOfRect,x as daemonCommandRequestSchema,k as daemonRuntimeSchema,u as findNodeByRef,n as isApplePlatform,j as jsonRpcRequestSchema,T as leaseAllocateSchema,U as leaseHeartbeatSchema,F as leaseReleaseSchema,i as matchesPlatformSelector,a as normalizePlatformSelector,c as normalizeRef,o as resolveApplePlatformName,l as resolveAppleSimulatorSetPathForSelector,s as resolveDevice,f as snapshotPresentationOptionsFromFlags};
package/dist/src/9639.js DELETED
@@ -1,2 +0,0 @@
1
- import{AsyncLocalStorage as e}from"node:async_hooks";import{runCmdBackground as r,withoutCommandExecutorOverride as t,runCmd as i,withCommandExecutorOverride as n}from"./9818.js";import{AppError as a}from"./9152.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};
package/dist/src/9671.js DELETED
@@ -1 +0,0 @@
1
- import r from"node:fs";import e from"node:path";import{fileURLToPath as o}from"node:url";function t(){try{let o=n();return JSON.parse(r.readFileSync(e.join(o,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function n(){let t=e.dirname(o(import.meta.url)),n=t;for(let o=0;o<6;o+=1){let o=e.join(n,"package.json");if(r.existsSync(o))return n;n=e.dirname(n)}return t}export{n as findProjectRoot,t as readVersion};
package/dist/src/9818.js DELETED
@@ -1 +0,0 @@
1
- import{AsyncLocalStorage as t}from"node:async_hooks";import{constants as e}from"node:fs";import{access as r,stat as n}from"node:fs/promises";import o from"node:path";import{spawn as i,spawnSync as u}from"node:child_process";import{Readable as d}from"node:stream";import{pipeline as s}from"node:stream/promises";import{AppError as a}from"./9152.js";let f=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/,c=[".com",".exe",".bat",".cmd"],l=new t;async function m(t,e){return t?await l.run(t,e):await e()}async function p(t){return await l.run(void 0,t)}async function w(t,e,r={}){let n=l.getStore()?.(t,e,r);return n?await n:await v(t,e,r)}async function h(t,e,r={}){let n=l.getStore()?.(t,e,r);return n?await n:await v(t,e,r)}function v(t,e,r={}){let n=O(t);return new Promise((o,u)=>{let d=i(n,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached,windowsHide:!0,shell:!1});r.onSpawn?.(d);let s="",f=r.binaryStdout?[]:void 0,c="",l=!1,m=P(r.timeoutMs),p=m?setTimeout(()=>{l=!0,H(d,r.detached)},m):null,w=B(d,r);r.binaryStdout||d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),G(d,r.stdin).catch(o=>{var i,s,f,c;w.didAbort||l||(i=o)instanceof Error&&"code"in i&&"EPIPE"===i.code||(u((s=n,f=t,new a("COMMAND_FAILED",`Failed to write stdin for ${s}`,{cmd:f,args:e},(c=o)instanceof Error?c:void 0))),H(d,r.detached))}),d.stdout.on("data",t=>{if(r.binaryStdout)return void f?.push(Buffer.isBuffer(t)?t:Buffer.from(t));let e=String(t);s+=e,r.onStdoutChunk?.(e)}),d.stderr.on("data",t=>{let e=String(t);c+=e,r.onStderrChunk?.(e)}),d.on("error",r=>{p&&clearTimeout(p),w.dispose(),u(L(w,n,t,e,r))}),d.on("close",i=>{p&&clearTimeout(p),w.dispose();let d=i??1;if(!w.didAbort&&l&&m){var h,v,A,S,b,E;return void u((h=n,v=t,A=e,S=m,b=d,E=s,new a("COMMAND_FAILED",`${h} timed out after ${S}ms`,{cmd:v,args:A,stdout:E,stderr:c,exitCode:b,timeoutMs:S})))}let g=N(w,n,t,e,d,r.allowFailure,s,c);g?u(g):o({stdout:s,stderr:c,exitCode:d,stdoutBuffer:f?Buffer.concat(f):void 0})})})}async function A(t){let e=D(t);if(!e)return!1;if(o.isAbsolute(e))return F(e);let r=process.env.PATH;if(!r)return!1;let n=function(){if("win32"!==process.platform)return[""];let t=process.env.PATHEXT;if(!t)return c;let e=t.split(";").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0);return e.length>0?e:c}();for(let t of r.split(o.delimiter)){let r=t.trim();if(r){for(let t of function(t,e){if("win32"!==process.platform)return[t];let r=t.toLowerCase();return e.some(t=>r.endsWith(t))?[t]:e.map(e=>`${t}${e}`)}(e,n))if(await F(o.join(r,t)))return!0}}return!1}async function S(t,e){let r=x(t,e,"executable");if(r){if(!await F(r))throw new a("TOOL_MISSING",`${e} points to a missing or non-executable file: ${r}`,{envName:e,path:r});return r}}async function b(t,e){let r=x(t,e,"file");if(r){if(!await T(r))throw new a("TOOL_MISSING",`${e} points to a missing or non-file path: ${r}`,{envName:e,path:r});return r}}function E(t,e,r={}){let n=O(t),o=u(n,e,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:P(r.timeoutMs),windowsHide:!0,shell:!1,...void 0!==r.maxBuffer?{maxBuffer:r.maxBuffer}:{}});if(o.error){let i=o.error.code;if("ETIMEDOUT"===i)throw new a("COMMAND_FAILED",`${n} timed out after ${P(r.timeoutMs)}ms`,{cmd:t,args:e,timeoutMs:P(r.timeoutMs)},o.error);if("ENOENT"===i)throw I(n,t,o.error);throw C(n,t,e,o.error)}let i=r.binaryStdout?Buffer.isBuffer(o.stdout)?o.stdout:Buffer.from(o.stdout??""):void 0,d=r.binaryStdout?"":"string"==typeof o.stdout?o.stdout:(o.stdout??"").toString(),s="string"==typeof o.stderr?o.stderr:(o.stderr??"").toString(),f=o.status??1;if(0!==f&&!r.allowFailure)throw $(n,t,e,f,d,s);return{stdout:d,stderr:s,exitCode:f,stdoutBuffer:i}}function g(t,e,r={}){return y(t,e,r).pid}function y(t,e,r={}){let n=i(O(t),e,{cwd:r.cwd,env:r.env,stdio:r.stdio??"ignore",detached:!0,windowsHide:!0,shell:!1}),o=n.pid??0,u=new Promise(t=>{n.once("error",e=>{t({pid:o,error:e.message})}),n.once("exit",(e,r)=>{t({pid:o,..."number"==typeof e?{exitCode:e}:{},...r?{signal:r}:{}})})});return n.unref(),{pid:o,exited:u}}function M(t,e,r={}){let n=O(t),o=i(n,e,{cwd:r.cwd,env:r.env,stdio:r.stdio??["ignore","pipe","pipe"],detached:r.detached,windowsHide:!0,shell:!1}),u="",d="",s=r.captureOutput??!0,a=B(o,r);s&&(o.stdout?.setEncoding("utf8"),o.stderr?.setEncoding("utf8"),o.stdout?.on("data",t=>{u+=t}),o.stderr?.on("data",t=>{d+=t}));let f=new Promise((i,s)=>{o.on("error",r=>{a.dispose(),s(L(a,n,t,e,r))}),o.on("close",o=>{a.dispose();let f=o??1,c=N(a,n,t,e,f,r.allowFailure,u,d);c?s(c):i({stdout:u,stderr:d,exitCode:f})})});return{child:o,wait:f}}function O(t){let e=D(t);if(!e)throw new a("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(t)}`,{cmd:t,hint:"Use a bare command name from PATH or an absolute executable path."});return e}function I(t,e,r){return new a("TOOL_MISSING",`${t} not found in PATH`,{cmd:e},r)}function C(t,e,r,n){return new a("COMMAND_FAILED",`Failed to run ${t}`,{cmd:e,args:r},n)}function _(t,e,r){return new a("COMMAND_FAILED","request canceled",{cmd:e,args:r,executable:t,reason:"request_canceled"})}function $(t,e,r,n,o,i){return new a("COMMAND_FAILED",`${t} exited with code ${n}`,{cmd:e,args:r,stdout:o,stderr:i,exitCode:n,processExitError:!0})}function L(t,e,r,n,o){return t.didAbort?_(e,r,n):"ENOENT"===o.code?I(e,r,o):C(e,r,n,o)}function N(t,e,r,n,o,i,u,d){return t.didAbort?_(e,r,n):0===o||i?null:$(e,r,n,o,u,d)}function x(t,e,r){let n=t?.trim();if(n){if(!o.isAbsolute(n)||n.includes("\0"))throw new a("INVALID_ARGS",`${e} must be an absolute ${r} path, not ${JSON.stringify(t)}`,{envName:e,path:t});return n}}function D(t){let e=t.trim();return!e||e.includes("\0")?null:o.isAbsolute(e)?e:e.includes("/")||e.includes("\\")?null:f.test(e)?e:null}async function F(t){try{if(!await T(t))return!1;return await r(t,"win32"===process.platform?e.F_OK:e.X_OK),!0}catch{return!1}}async function T(t){try{return(await n(t)).isFile()}catch{return!1}}function P(t){if(!Number.isFinite(t))return;let e=Math.floor(t);if(!(e<=0))return e}function B(t,e){let r=!1,n=()=>{r=!0,H(t,e.detached)};return e.signal?.aborted?n():e.signal?.addEventListener("abort",n,{once:!0}),{get didAbort(){return r},dispose:()=>{e.signal?.removeEventListener("abort",n)}}}function H(t,e){if(e&&t.pid&&"win32"!==process.platform)try{process.kill(-t.pid,"SIGKILL");return}catch{}t.kill("SIGKILL")}async function G(t,e){if(t.stdin){if(void 0===e)return void t.stdin?.end();await s(d.from([e]),t.stdin)}}export{F as isExecutablePath,S as resolveExecutableOverridePath,b as resolveFileOverridePath,w as runCmd,M as runCmdBackground,g as runCmdDetached,y as runCmdDetachedMonitored,h as runCmdStreaming,E as runCmdSync,A as whichCmd,m as withCommandExecutorOverride,p as withoutCommandExecutorOverride};
package/dist/src/989.js DELETED
@@ -1 +0,0 @@
1
- import t from"node:dns/promises";import e from"node:net";import{createWriteStream as a,promises as r}from"node:fs";import o from"node:os";import i from"node:path";import{Readable as n}from"node:stream";import{pipeline as s}from"node:stream/promises";import{AppError as l}from"./9152.js";import{runCmd as c}from"./9818.js";import{expandUserHomePath as h}from"./3267.js";let u=[".zip",".tar",".tar.gz",".tgz"],d=Object.freeze([...u]);async function p(t){let e=[];try{let a=await w(t.source,{signal:t.signal,downloadTimeoutMs:t.downloadTimeoutMs});e.push(a.cleanup);let r=await v(a.localPath,{archivePath:void 0,isInstallablePath:t.isInstallablePath,installableLabel:t.installableLabel,allowArchiveExtraction:!1!==t.allowArchiveExtraction,registerCleanup:t=>{e.push(t)}});return{archivePath:r.archivePath,installablePath:r.installablePath,cleanup:async()=>{await g(e)}}}catch(t){throw await g(e),t}}async function w(t,e){if("path"===t.kind)return{localPath:h(t.path),cleanup:async()=>{}};let a=await r.mkdtemp(i.join(o.tmpdir(),"agent-device-source-"));try{return{localPath:await f(a,t.url,t.headers,e),cleanup:async()=>{await r.rm(a,{recursive:!0,force:!0})}}}catch(t){throw await r.rm(a,{recursive:!0,force:!0}),t}}async function f(t,e,r,o){let c;try{c=new URL(e)}catch{throw new l("INVALID_ARGS",`Invalid source URL: ${e}`)}await m(c);let h=o?.signal;if(h?.aborted)throw new l("COMMAND_FAILED","request canceled",{reason:"request_canceled"});let u=o?.downloadTimeoutMs??12e4,d=AbortSignal.timeout(u),p=h?AbortSignal.any([h,d]):d;try{let e=await fetch(c,{headers:r,redirect:"follow",signal:p});if(!e.ok)throw new l("COMMAND_FAILED",`Failed to download app source: ${e.status} ${e.statusText}`,{status:e.status,statusText:e.statusText,url:c.toString()});let o=function(t,e){let a=t.headers.get("content-disposition"),r=a?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i),o=r?.[1]?.trim();if(o)return i.basename(o);let n=i.basename(e.pathname);return n||"downloaded-artifact.bin"}(e,c),h=i.join(t,o),u=e.body;if(!u)throw new l("COMMAND_FAILED","Download response body was empty",{url:c.toString()});return await s(n.fromWeb(u),a(h)),h}catch(t){if(h?.aborted)throw new l("COMMAND_FAILED","request canceled",{reason:"request_canceled"},t);if(d.aborted)throw new l("COMMAND_FAILED",`App source download timed out after ${u}ms`,{timeoutMs:u,url:c.toString()},t);throw t}}async function m(e){if("http:"!==e.protocol&&"https:"!==e.protocol)throw new l("INVALID_ARGS",`Unsupported source URL protocol: ${e.protocol}`);if(A(e.hostname.toLowerCase()))throw new l("INVALID_ARGS",`Source URL host is not allowed: ${e.hostname}`,{hint:"Use a public artifact URL."});if((await t.lookup(e.hostname,{all:!0,verbatim:!0}).catch(()=>[])).some(t=>L(t.address)))throw new l("INVALID_ARGS",`Source URL host resolved to a private or loopback address: ${e.hostname}`,{hint:"Use a public artifact URL."})}function b(t){var e,a,r,o;let i=t instanceof URL?t:new URL(t),n=i.hostname.toLowerCase();if(!n)return!1;let s=i.pathname;return e=n,a=s,("api.github.com"===e?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(a):"github.com"===e&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(a))||(r=n,o=s,("expo.dev"===r||!!r.endsWith(".expo.dev"))&&/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(o))}function A(t){return!!(!t||"localhost"===t||t.endsWith(".localhost"))||L(t)}function L(t){let a,r=e.isIP(t);return 4===r?function(t){let e=t.split(".").map(t=>Number.parseInt(t,10));if(4!==e.length||e.some(t=>Number.isNaN(t)||t<0||t>255))return!1;let a=e[0],r=e[1];return void 0!==a&&void 0!==r&&(10===a||127===a||169===a&&254===r||172===a&&!!(r>=16)&&!!(r<=31)||192===a&&168===r)}(t):6===r&&!!("::1"===(a=t.toLowerCase())||a.startsWith("fc")||a.startsWith("fd")||a.startsWith("fe80:"))}async function v(t,e){let a=await r.stat(t).catch(()=>null);if(!a)throw new l("INVALID_ARGS",`App source not found: ${t}`);if(e.isInstallablePath(t,a))return{archivePath:e.archivePath,installablePath:t};if(a.isFile()&&S(t)){if(!e.allowArchiveExtraction)throw new l("INVALID_ARGS",`URL sources must point directly to a ${e.installableLabel}; archive extraction is not allowed`,{path:t});let a=await _(t);return e.registerCleanup(a.cleanup),await v(a.outputPath,{...e,archivePath:e.archivePath??t})}if(a.isDirectory()){let a=await I(t,e.isInstallablePath),r=a[0];if(void 0!==r&&1===a.length)return{archivePath:e.archivePath,installablePath:r};if(a.length>1)throw new l("INVALID_ARGS",`Found multiple ${e.installableLabel} candidates under ${t}`,{matches:a});let o=await I(t,(t,e)=>e.isFile()&&S(t)),i=o[0];if(void 0!==i&&1===o.length){if(!e.allowArchiveExtraction)throw new l("INVALID_ARGS",`URL sources must point directly to a ${e.installableLabel}; nested archives are not allowed`,{path:i});let t=await _(i);return e.registerCleanup(t.cleanup),await v(t.outputPath,{...e,archivePath:e.archivePath??i})}if(o.length>1)throw new l("INVALID_ARGS",`Found multiple nested archives under ${t}; expected one ${e.installableLabel} source`,{matches:o})}throw new l("INVALID_ARGS",`Expected ${e.installableLabel} source, but got ${t}`)}async function I(t,e){let a=[],o=[{path:t,depth:0}];for(;o.length>0;){let t=o.shift();if(!t)continue;let n=await r.readdir(t.path,{withFileTypes:!0});for(let r of(n.sort((t,e)=>t.name.localeCompare(e.name)),n)){let n=i.join(t.path,r.name);if(e(n,r)){a.push(n);continue}r.isDirectory()&&t.depth<5&&o.push({path:n,depth:t.depth+1})}}return a}async function _(t){let e=await r.mkdtemp(i.join(o.tmpdir(),"agent-device-archive-"));try{return t.toLowerCase().endsWith(".zip")?await P(t,e):t.toLowerCase().endsWith(".tar.gz")||t.toLowerCase().endsWith(".tgz")?await c("tar",["-xzf",t,"-C",e]):await c("tar",["-xf",t,"-C",e]),{outputPath:e,cleanup:async()=>{await r.rm(e,{recursive:!0,force:!0})}}}catch(t){throw await r.rm(e,{recursive:!0,force:!0}),t}}async function P(t,e){await c("unzip",["-q",t,"-d",e])}function S(t){let e=t.toLowerCase();return u.some(t=>e.endsWith(t))}async function g(t){for(let e of[...t].reverse())await e()}export{d as ARCHIVE_EXTENSIONS,L as isBlockedIpAddress,A as isBlockedSourceHostname,b as isTrustedInstallSourceUrl,p as materializeInstallablePath,m as validateDownloadSourceUrl};
File without changes
File without changes
File without changes
File without changes
File without changes