agent-device 0.17.3 → 0.17.4

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 (28) hide show
  1. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.3.apk → agent-device-android-multitouch-helper-0.17.4.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.4.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.3.manifest.json → agent-device-android-multitouch-helper-0.17.4.manifest.json} +4 -4
  4. package/android-snapshot-helper/README.md +3 -0
  5. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.3.apk → agent-device-android-snapshot-helper-0.17.4.apk} +0 -0
  6. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.4.apk.sha256 +1 -0
  7. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.3.manifest.json → agent-device-android-snapshot-helper-0.17.4.manifest.json} +6 -6
  8. package/dist/src/123.js +1 -1
  9. package/dist/src/2415.js +33 -32
  10. package/dist/src/4012.js +4 -0
  11. package/dist/src/6133.js +1 -1
  12. package/dist/src/9542.js +5 -5
  13. package/dist/src/apple.js +1 -1
  14. package/dist/src/cli-output.js +2 -1
  15. package/dist/src/cli.js +4 -4
  16. package/dist/src/index.d.ts +16 -0
  17. package/dist/src/session.js +8 -8
  18. package/dist/src/snapshot.js +2 -2
  19. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +3 -4
  20. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1 -1
  21. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +2 -2
  22. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +47 -3
  23. package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +0 -9
  24. package/package.json +1 -1
  25. package/server.json +2 -2
  26. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.3.apk.sha256 +0 -1
  27. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.3.apk.sha256 +0 -1
  28. package/dist/src/9238.js +0 -4
package/dist/src/9542.js CHANGED
@@ -1,6 +1,6 @@
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{consumeTextLines as b,shellQuote as A,shouldStreamRequestProgress as S,isDaemonResponseEnvelope as M,isDaemonProgressEnvelope as P,resolveDaemonPaths as _,resolveDaemonServerMode as D,computeDaemonCodeSignature as k,resolveDaemonTransportPreference as E}from"./9238.js";import{INTERNAL_COMMANDS as x,PUBLIC_COMMANDS as N}from"./6088.js";import{readVersion as $,findProjectRoot as T}from"./9671.js";import{sleep as C}from"./4829.js";import{normalizeSession as U,readRequiredString as L,readSerializedSnapshotCaptureAnnotations as R,readOptionalString as O,normalizeMaterializationReleaseResult as F,readSnapshotNodes as B,normalizeDeployResult as q,appDaemonWriters as j,observabilityDaemonWriters as V,normalizeOpenDevice as G,replayDaemonWriters as H,buildMeta as K,systemDaemonWriters as z,resolveSessionName as Y,buildFlags as W,reactNativeDaemonWriters as J,interactionDaemonWriters as X,captureDaemonWriters as Q,perfDaemonWriters as Z,gestureDaemonWriters as ee,selectorDaemonWriters as et,createBatchDaemonWriter as ea,normalizeRuntimeHints as er,normalizeDevice as en,recordingDaemonWriters as ei,readScreenshotOverlayRefs as eo,normalizeStartupSample as es,normalizeInstallFromSourceResult as ed}from"./6133.js";import{reloadMetro as el,prepareMetroRuntime as ec}from"./1974.js";function eu(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 ef="sha256";async function ep(e){let t=await em(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eg({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eI(t.payloadPath,r),await eS({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await ew({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function em(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 eh(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 eM(a),sizeBytes:r.size,cleanup:()=>ey(f)}}catch(e){throw ey(f),e}}async function eh(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 ey(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function ew(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":ef,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await ev({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 eg(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 eI(e,t){let a=await ev({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 ev(e){return await eb({...e,url:e.url,redirectCount:0,startOffset:0})}async function eb(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,eu(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 eb({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let d=308===i?function(e,t){let a=function(e){let t=eA(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=eA(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()})):eb({...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 eA(e){return Array.isArray(e)?e[0]:e}async function eS(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 eM(t){let a=o(ef),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 eP(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 eD({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=eE(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:ex("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:ex("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=eE(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:ex("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 ek(e,t);l&&(s=l.installSource,n=l.uploadedArtifactId??n);let c=()=>eD({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 ep({localPath:l,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eD(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 ek(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 ep({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function eE(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 ex(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 eN(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 e$({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 e$(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 eT(e){var t,a,r;let n,i,o=ej(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=eU((a=o).port),i=eU(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:eU(o.pid)??0,version:eC(o.version),codeSignature:eC(o.codeSignature),processStartTime:eC(o.processStartTime)}:null}function eC(e){return"string"==typeof e?e:void 0}function eU(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eL(e){let t=ej(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 eR(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=eT(t.infoPath);if(r){let e=I(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eB(r),i.stoppedInfoProcess=!0),o=t.infoPath,eV(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eV(s),i.removedInfo=!0);let c=e.existsSync(t.lockPath),u=eL(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,eV(d),i.removedLock=!0)}else c&&(l=t.lockPath,eV(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 eO(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eF(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return!1;let a=eL(e.lockPath);return!(a&&I(a.pid,a.processStartTime))&&(eV(e.lockPath),!0)}async function eB(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eq(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ej(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eV(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function eG(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 eH={start:"START",pass:"PASS",fail:"FAIL",skip:"SKIP"};function eK(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":eH[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=eG((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 ez(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}));eY(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 eY(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eN(e,t,a):a)}catch(e){n(e)}}let eW=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function eJ(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of eW){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{eB(e)}finally{eV(t.infoPath),eV(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===N.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 eX(e,t){let a=e1(e,t);if(await eQ(e,a))return!0;let r=e2(e,t,a);return!!r&&await eQ(e,r)}async function eQ(e,r){var n;return"http"===r?await function(e){let r=e.baseUrl?e8(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 eZ(e,t,a,r,n){let i=e1(e,a);try{return await e0(e,t,r,n,i)}catch(d){var o;let s=e2(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 e0(e,t,r,n,s)}}async function e0(e,t,a,r,n){return"http"===n?await e4(e,t,a,r):await e6(e,t,a,r)}function e1(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(e3(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=>e3(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function e3(e,t){return"http"===t?!!e.httpPort:!!e.port}function e2(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return e3(e,r)?r:null}function e5(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(eJ(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=b(s,t);for(let t of(s=a.buffer,a.lines))try{let a=JSON.parse(t);if(P(a)){eK(a.event);continue}let r=M(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(e5(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function e4(e,r,n,i){var o,s;let d,l=e.baseUrl?new URL(e8(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"],S(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(P(t))return eK(t.event),!1;if(M(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=b(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=>ez(t,{info:e,req:r,resolve:o,reject:s})}):eu(t).then(t=>{m&&clearTimeout(m),ez(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=eq(e),m="number"==typeof i?setTimeout(()=>{d.destroy(),s(eJ(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;d.on("error",e=>{m&&clearTimeout(m),s(e5(e,r.meta?.requestId,p))}),d.write(c),d.end()})}function e8(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let e9=new l.BlockList;async function e7(e){if(e.remoteBaseUrl)return await te(e);let t=await tt(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=eO(e);if(!t.hasLock||t.hasInfo)return;let a=eL(e.lockPath);if(!a)return eV(e.lockPath);I(a.pid,a.processStartTime)||eV(e.lockPath)}(e.paths),await ta(e))}async function te(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await eX(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 tt(e){var t,a;let r=eT(e.paths.infoPath);if(!r)return null;let n=await eX(r,e.transportPreference);return(t=r,a=n,t.version===$()&&t.codeSignature===ts()&&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!==$()?`version mismatch (client v${$()})`:r.codeSignature!==ts()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
4
- `)}catch{}}(r,n,e.paths.baseDir),await eB(r),eV(e.paths.infoPath),null)}async function ta(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=to(),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 eR(t.paths,"start_error")),o<2){await C(150);continue}break}let d=await ti(15e3,t,s);if("ready"===d.kind)return{info:d.info,startedByClient:!0};if("early_exit"===d.kind){if(r=d.exit,a=td(d.exit),i.push(await eR(t.paths,"start_error")),o<2){await C(150);continue}break}if(await eF(t.paths)){n+=1;continue}let l=eO(t.paths),c=o<2,u=await eR(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await ti(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=td(e.exit));break}if(!c)break;l.hasInfo||l.hasLock||await C(150)}let o=eO(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 ${A(a.infoPath)} ${A(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 tr(t,a,r){if(!tn(t.command)||!a.startedByClient&&!r.ownedStateDir||eq(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eB(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eV(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eV(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 tn(e){return e===N.replay||e===N.test}async function ti(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=eT(t.paths.infoPath);if(e&&await eX(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await C(100)}return{kind:"timeout"}}function to(){let t=T(),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 ts(){let e=to();return k(e.useSrc?e.srcPath:e.distPath,e.root)}function td(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 tl(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)?e9.check(a,"ipv4"):!!l.isIPv6(a)&&e9.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=E(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:D(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=tn(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!==N.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===N.prepare||t===N.replay||t===N.snapshot)?e.flags.timeoutMs:e.command===N.prepare?24e4:9e4}}(t),P=await w("daemon_startup",async()=>await e7(S),{requestId:b,session:t.session}),k=P.info,x=await eP(t,k),$={...t,positionals:x.positionals,flags:x.flags,token:k.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,...x.uploadedArtifactId?{uploadedArtifactId:x.uploadedArtifactId}:{},...x.clientArtifactPaths?{clientArtifactPaths:x.clientArtifactPaths}:{},...x.installSource?{installSource:x.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 eZ(k,$,S.transportPreference,S.paths,M),{requestId:b,command:t.command})}finally{await tr(t,P,S)}}e9.addSubnet("127.0.0.0",8,"ipv4"),e9.addAddress("::1","ipv6"),e9.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tc=/^[0-9a-fA-F-]{32,36}$/;function tu(e){if(e&&tc.test(e))return e.replaceAll("-","").toUpperCase()}function tf(e,t){return`${e.uuid}:${tp(t)}`}function tp(e){return`0x${e.toString(16)}`}function tm(e){return"string"==typeof e&&e.length>0?e:void 0}function th(...e){for(let t of e){let e=tm(t);if(e)return e}}function ty(e){return"object"==typeof e&&null!==e}function tw(e){return ty(e)?e:void 0}function tg(e){try{let t=JSON.parse(e);return ty(t)?t:null}catch{return null}}function tI(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 tv(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;tb(a,t)}function tb(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 tA(e){return[...new Set(e)]}let tS=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tM(e){return e.dsym&&e.searchPath?[tx(e.cwd,e.dsym),...await tP(tx(e.cwd,e.searchPath))]:e.dsym?[tx(e.cwd,e.dsym)]:e.searchPath?await tP(tx(e.cwd,e.searchPath)):[]}async function tP(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 tD(e,t){let a=(await Promise.all(tA(e).map(e=>tk(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 tk(e,t){var a;await tE(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=tu(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tE(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 tx(e,t){return r.resolve(e,t)}function tN(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function t$(e,t,a,r){return{index:e,image:t.name,address:tp(a),symbol:r.get(tf(t,a))?.text}}function tT(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 tC(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 tU(a,n)))r.set(tf(e.image,e.address),e);return r}async function tU(e,t){var a,r,n,i;let o,s,d=tA(t.addresses.map(tp)),l=await m(e,(a=t,r=d,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tp(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 tL(){return{dwarfdump:await tR("dwarfdump"),atos:await tR("atos")}}async function tR(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 tO(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=tq(B,e.artifact),j=tq(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=tg(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tg(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=tu(tm(e.uuid)),n=tv(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tm(e.path);return[{index:t,name:tm(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tm(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=>ty(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tI(e[t]);if(void 0!==r)return r;tb(a,t)}(e,"imageIndex","IPS frame"),i=tv(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(tf(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)}
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
5
  `;return e.header?`${e.header}
6
- ${r}`:r})(n,o,e)}}(t=await tF(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=tu(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tS.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(tf(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 tM({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 tL(),K=await tD(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=tA(e.map(e=>e.uuid)),i=tA(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 tC(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=tI(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tw(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(d=s.header)?tg(d):null,{appName:(l=T,u=C,th(l.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,th(tw(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,th(tw(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,th(w.incident,g?.incident_id)),timestamp:(I=T,v=C,th(I.captureTime,v?.timestamp)),exceptionType:(b=T.exception,tm(tw(b)?.type)),exceptionCodes:function(e){let t=tw(e);if(t)return th(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tw(e);if(t){let e;return(e=[tm(t.namespace),tm(t.code),tm(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=>t$(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tT(L)}):(P=V.lines,_=V.frameMatches,D=Y,O=function(e){let t=tN(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=tN(P,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:tN(P,"Identifier"),version:tN(P,"Version"),incident:tN(P,"Incident Identifier"),timestamp:tN(P,"Date/Time"),exceptionType:tN(P,"Exception Type"),exceptionCodes:tN(P,"Exception Codes"),terminationReason:tN(P,"Termination Reason"),crashedThread:O,topFrames:(k=_,E=O,x=D,void 0===E?[]:k.filter(e=>e.threadIndex===E).slice(0,5).map(e=>t$(e.frameIndex,e.image,e.address,x))),findings:[]},findings:tT(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${j}`}}async function tF(e,t){await tB(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 tB(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 tq(e,t){return r.resolve(e,t)}let tj={...j,...Q,...X,...ee,...et,...V,...Z,...J,...ei,...H,...z,batch:ea(function(e,t){let a=tj[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function tV(e={},t={}){let a=t.transport??tl,r=async(t,r=[],n={})=>{let i=tH(e,n),o=await a({session:Y(i.session),command:t,positionals:r,flags:W(i),runtime:i.runtime,meta:K(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(x.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(U)},i=async(e,t={})=>{let a=tj[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>Y(tH(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(en)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>_(tH(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=>q(await i("install",e),o(e)),reinstall:async e=>q(await i("reinstall",e),o(e)),installFromSource:async e=>ed(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=G(a),n=O(a,"appBundleId");return{session:t,sessionStateDir:O(a,"sessionStateDir"),appName:O(a,"appName"),appBundleId:n,appId:n,startup:es(a.startup),runtime:er(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=>F(await r(x.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>tK(await r(x.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>tK(await r(x.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(x.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ec({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 el({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=o(e);return t=await i("snapshot",e),a=l,n=O(t,"appBundleId"),{nodes:B(t.nodes),truncated:!0===t.truncated,appName:O(t,"appName"),appBundleId:n,...(s=tG((r=t).visibility),d=tG(r.unchanged),{...s?{visibility:s}:{},...R(r),...d?{unchanged:d}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:L(a,"path"),overlayRefs:eo(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 tO({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 tG(e){return"object"==typeof e&&null!==e?e:void 0}function tH(e,t){return{...e,...t}}function tK(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:L(t,"leaseId"),tenantId:L(t,"tenantId"),runId:L(t,"runId"),backend:L(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{tV as createAgentDeviceClient,eG as formatDurationSeconds,tl as sendToDaemon};
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/apple.js CHANGED
@@ -1 +1 @@
1
- import{readSnapshotQualityVerdict as a,assertScrollGestureInput as e,buildScrollGesturePlan as t}from"./6133.js";import{parseRunnerSequenceResult as n,buildRunnerSequenceCommand as d,runMacOsScreenshotAction as o,runIosRunnerCommand as r}from"./2415.js";import{writeIosClipboardText as l,openIosApp as p,openIosDevice as i,screenshotIos as s,closeIosApp as u,setIosSetting as c,readIosClipboardText as m}from"./apps.js";import{withDiagnosticTimer as y}from"./7599.js";import{AppError as v}from"./9152.js";function I(a,e,t,n){return{command:"tap",x:t,y:n,..."ios"===a.platform&&"tv"!==a.target?{synthesized:!0}:{},appBundleId:e.appBundleId}}function f(a,e,t,n,d,o,r,l){var p,i;let s="ios"===a.platform&&"tv"!==a.target?(p=r,i=l.defaultDurationMs,void 0===p?i:Math.min(1e4,Math.max(16,Math.round(p)))):r??l.legacyDefaultDurationMs;return{command:"drag",x:t,y:n,x2:d,y2:o,...void 0!==s?{durationMs:s}:{},appBundleId:e.appBundleId}}function B(a,e,t){return{command:"remotePress",remoteButton:a,...void 0!==t?{durationMs:t}:{},...void 0!==e?{appBundleId:e}:{}}}async function w(a,n,d,o,r,l){if("tv"===n.target)return g(await a(n,B(r,d.appBundleId),o),l);e(l??{});let p=await a(n,{command:"scroll",direction:r,...l?.amount!==void 0?{amount:l.amount}:{},...l?.pixels!==void 0?{pixels:l.pixels}:{},appBundleId:d.appBundleId},o),i=h(p.referenceWidth),s=h(p.referenceHeight);if(void 0!==i&&void 0!==s){let a=t({direction:r,amount:l?.amount,pixels:l?.pixels,referenceWidth:i,referenceHeight:s});return g(p,{amount:l?.amount,pixels:a.pixels,preferProvidedPixels:!0})}return g(p,{amount:l?.amount})}function h(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}function g(a,e){var t;let{x1:n,y1:d,x2:o,y2:r}={x1:h((t=a).x),y1:h(t.y),x2:h(t.x2),y2:h(t.y2)},l=h(a.referenceWidth),p=h(a.referenceHeight),i=void 0!==n&&void 0!==o?Math.round(Math.abs(o-n)):void 0,s=void 0!==d&&void 0!==r?Math.round(Math.abs(r-d)):void 0,u=e?.preferProvidedPixels&&void 0!==e.pixels?e.pixels:i&&i>0?i:s&&s>0?s:void 0;return{...void 0!==n?{x1:n}:{},...void 0!==d?{y1:d}:{},...void 0!==o?{x2:o}:{},...void 0!==r?{y2:r}:{},...void 0!==l?{referenceWidth:l}:{},...void 0!==p?{referenceHeight:p}:{},...e?.amount!==void 0?{amount:e.amount}:{},...void 0!==u?{pixels:u}:{}}}function x(e,t){let h,{overrides:g,runnerOpts:x}={runnerOpts:h={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(a,n)=>await r(e,I(e,t,a,n),h),tapElementSelector:async a=>await r(e,{command:"tap",selectorKey:a.key,selectorValue:a.value,allowNonHittableCoordinateFallback:a.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},h),doubleTap:async(a,o)=>{let l=await r(e,d([{kind:"doubleTap",x:a,y:o}],t.appBundleId),h);return n(l),l},swipe:async(a,n,d,o,l)=>await r(e,f(e,t,a,n,d,o,l,{defaultDurationMs:250}),h),pan:async(a,n,d,o,l)=>await r(e,f(e,t,a,n,d,o,l,{defaultDurationMs:500,legacyDefaultDurationMs:500}),h),fling:async(a,n,d,o,l)=>await r(e,{command:"drag",x:a,y:n,x2:d,y2:o,durationMs:l??16,appBundleId:t.appBundleId},h),longPress:async(a,n,d)=>await r(e,{command:"longPress",x:a,y:n,durationMs:d,appBundleId:t.appBundleId},h),focus:async(a,n)=>await r(e,I(e,t,a,n),h),type:async(a,n)=>{await r(e,{command:"type",text:a,delayMs:n,textEntryMode:"\n"===a?void 0:"append",appBundleId:t.appBundleId},h)},fillElementSelector:async(a,n,d)=>await r(e,{command:"type",selectorKey:a.key,selectorValue:a.value,allowNonHittableCoordinateFallback:a.allowNonHittableCoordinateFallback,text:n,delayMs:d,textEntryMode:"replace",appBundleId:t.appBundleId},h),fill:async(a,n,d,o)=>await r(e,{command:"type",x:a,y:n,text:d,delayMs:o,textEntryMode:"replace",appBundleId:t.appBundleId},h),scroll:async(a,n)=>await w(r,e,t,h,a,n),pinch:async(a,n,d)=>{await r(e,{command:"pinch",scale:a,x:n,y:d,appBundleId:t.appBundleId},h)},rotateGesture:async(a,n,d,o)=>{await r(e,{command:"rotateGesture",degrees:a,x:n,y:d,velocity:o,appBundleId:t.appBundleId},h)},transformGesture:async a=>await r(e,{command:"transformGesture",x:a.x,y:a.y,dx:a.dx,dy:a.dy,scale:a.scale,degrees:a.degrees,durationMs:a.durationMs,appBundleId:t.appBundleId},h)}};return{open:(a,t)=>p(e,a,{appBundleId:t?.appBundleId,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,url:t?.url}),openDevice:()=>i(e),close:a=>u(e,a),screenshot:async(a,t)=>{"macos"===e.platform&&t?.surface&&"app"!==t.surface?await o(a,{surface:t.surface,fullscreen:t.fullscreen}):await s(e,a,t?.appBundleId,t?.fullscreen,x)},snapshot:async t=>{var n;let d={nodes:Array.isArray((n=await y("snapshot_capture",async()=>await r(e,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,depth:t?.depth,scope:t?.scope,raw:t?.raw},x),{backend:"xctest"})).nodes)?n.nodes:void 0,truncated:"boolean"==typeof n.truncated?n.truncated:void 0,quality:a(n.snapshotQuality),message:"string"==typeof n.message&&n.message.trim().length>0?n.message:void 0},o=d.nodes??[];if(0===o.length&&"simulator"===e.kind)throw new v("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:o,truncated:d.truncated??!1,backend:"xctest",...d.quality?{quality:d.quality}:{},...!d.quality&&d.message?{warnings:[d.message]}:{}}},back:async a=>{"tv"===e.target?await r(e,B("menu",t.appBundleId),x):await r(e,{command:"system"===a?"backSystem":"backInApp",appBundleId:t.appBundleId},x)},home:async()=>{"tv"===e.target?await r(e,B("home",t.appBundleId),x):await r(e,{command:"home",appBundleId:t.appBundleId},x)},rotate:async a=>{await r(e,{command:"rotate",orientation:a,appBundleId:t.appBundleId},x)},appSwitcher:async()=>{await r(e,{command:"appSwitcher",appBundleId:t.appBundleId},x)},readClipboard:()=>m(e),writeClipboard:a=>l(e,a),setSetting:(a,t,n,d)=>c(e,a,t,n,d),...g}}export{x as createAppleInteractor};
1
+ import{readSnapshotQualityVerdict as e,assertScrollGestureInput as a,buildScrollGesturePlan as t}from"./6133.js";import{parseRunnerSequenceResult as n,buildRunnerSequenceCommand as d,runMacOsScreenshotAction as o,runIosRunnerCommand as r}from"./2415.js";import{writeIosClipboardText as i,openIosApp as l,openIosDevice as s,screenshotIos as p,closeIosApp as u,setIosSetting as c,readIosClipboardText as m}from"./apps.js";import{withDiagnosticTimer as y}from"./7599.js";import{AppError as f}from"./9152.js";function v(e,a,t,n){return{command:"tap",x:t,y:n,...I(e)?{synthesized:!0}:{},appBundleId:a.appBundleId}}function I(e){return"ios"===e.platform&&"tv"!==e.target}function h(e,a,t,n,d,o,r,i){var l,s;let p="ios"===e.platform&&"tv"!==e.target?(l=r,s=i.defaultDurationMs,void 0===l?s:Math.min(1e4,Math.max(16,Math.round(l)))):r??i.legacyDefaultDurationMs;return{command:"drag",x:t,y:n,x2:d,y2:o,...void 0!==p?{durationMs:p}:{},...!0===i.synthesized?{synthesized:!0}:{},appBundleId:a.appBundleId}}function w(e,a,t){return{command:"remotePress",remoteButton:e,...void 0!==t?{durationMs:t}:{},...void 0!==a?{appBundleId:a}:{}}}async function B(e,n,d,o,r,i){if("tv"===n.target)return x(await e(n,w(r,d.appBundleId),o),i);a(i??{});let l=await e(n,{command:"scroll",direction:r,...i?.amount!==void 0?{amount:i.amount}:{},...i?.pixels!==void 0?{pixels:i.pixels}:{},appBundleId:d.appBundleId},o),s=g(l.referenceWidth),p=g(l.referenceHeight);if(void 0!==s&&void 0!==p){let e=t({direction:r,amount:i?.amount,pixels:i?.pixels,referenceWidth:s,referenceHeight:p});return x(l,{amount:i?.amount,pixels:e.pixels,preferProvidedPixels:!0})}return x(l,{amount:i?.amount})}function g(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function x(e,a){var t;let{x1:n,y1:d,x2:o,y2:r}={x1:g((t=e).x),y1:g(t.y),x2:g(t.x2),y2:g(t.y2)},i=g(e.referenceWidth),l=g(e.referenceHeight),s=void 0!==n&&void 0!==o?Math.round(Math.abs(o-n)):void 0,p=void 0!==d&&void 0!==r?Math.round(Math.abs(r-d)):void 0,u=a?.preferProvidedPixels&&void 0!==a.pixels?a.pixels:s&&s>0?s:p&&p>0?p:void 0;return{...void 0!==n?{x1:n}:{},...void 0!==d?{y1:d}:{},...void 0!==o?{x2:o}:{},...void 0!==r?{y2:r}:{},...void 0!==i?{referenceWidth:i}:{},...void 0!==l?{referenceHeight:l}:{},...a?.amount!==void 0?{amount:a.amount}:{},...void 0!==u?{pixels:u}:{}}}function M(a,t){let g,{overrides:x,runnerOpts:M}={runnerOpts:g={verbose:t.verbose,logPath:t.logPath,traceLogPath:t.traceLogPath,requestId:t.requestId},overrides:{tap:async(e,n)=>await r(a,v(a,t,e,n),g),tapElementSelector:async e=>await r(a,{command:"tap",selectorKey:e.key,selectorValue:e.value,allowNonHittableCoordinateFallback:e.allowNonHittableCoordinateFallback,appBundleId:t.appBundleId},g),doubleTap:async(e,o)=>{let i=await r(a,d([{kind:"doubleTap",x:e,y:o}],t.appBundleId),g);return n(i),i},swipe:async(e,n,d,o,i)=>await r(a,h(a,t,e,n,d,o,i,{defaultDurationMs:250,synthesized:I(a)}),g),pan:async(e,n,d,o,i)=>await r(a,h(a,t,e,n,d,o,i,{defaultDurationMs:500,legacyDefaultDurationMs:500,synthesized:I(a)}),g),fling:async(e,n,d,o,i)=>await r(a,h(a,t,e,n,d,o,i,{defaultDurationMs:16,legacyDefaultDurationMs:16,synthesized:I(a)}),g),longPress:async(e,n,d)=>await r(a,{command:"longPress",x:e,y:n,durationMs:d,appBundleId:t.appBundleId},g),focus:async(e,n)=>await r(a,v(a,t,e,n),g),type:async(e,n)=>{await r(a,{command:"type",text:e,delayMs:n,textEntryMode:"\n"===e?void 0:"append",appBundleId:t.appBundleId},g)},fillElementSelector:async(e,n,d)=>await r(a,{command:"type",selectorKey:e.key,selectorValue:e.value,allowNonHittableCoordinateFallback:e.allowNonHittableCoordinateFallback,text:n,delayMs:d,textEntryMode:"replace",appBundleId:t.appBundleId},g),fill:async(e,n,d,o)=>await r(a,{command:"type",x:e,y:n,text:d,delayMs:o,textEntryMode:"replace",appBundleId:t.appBundleId},g),scroll:async(e,n)=>await B(r,a,t,g,e,n),pinch:async(e,n,d)=>{await r(a,{command:"pinch",scale:e,x:n,y:d,appBundleId:t.appBundleId},g)},rotateGesture:async(e,n,d,o)=>{await r(a,{command:"rotateGesture",degrees:e,x:n,y:d,velocity:o,appBundleId:t.appBundleId},g)},transformGesture:async e=>await r(a,{command:"transformGesture",x:e.x,y:e.y,dx:e.dx,dy:e.dy,scale:e.scale,degrees:e.degrees,durationMs:e.durationMs,appBundleId:t.appBundleId},g)}};return{open:(e,t)=>l(a,e,{appBundleId:t?.appBundleId,launchConsole:t?.launchConsole,launchArgs:t?.launchArgs,url:t?.url}),openDevice:()=>s(a),close:e=>u(a,e),screenshot:async(e,t)=>{"macos"===a.platform&&t?.surface&&"app"!==t.surface?await o(e,{surface:t.surface,fullscreen:t.fullscreen}):await p(a,e,t?.appBundleId,t?.fullscreen,M)},snapshot:async t=>{var n;let d={nodes:Array.isArray((n=await y("snapshot_capture",async()=>await r(a,{command:"snapshot",appBundleId:t?.appBundleId,interactiveOnly:t?.interactiveOnly,depth:t?.depth,scope:t?.scope,raw:t?.raw},M),{backend:"xctest"})).nodes)?n.nodes:void 0,truncated:"boolean"==typeof n.truncated?n.truncated:void 0,quality:e(n.snapshotQuality),message:"string"==typeof n.message&&n.message.trim().length>0?n.message:void 0},o=d.nodes??[];if(0===o.length&&"simulator"===a.kind)throw new f("COMMAND_FAILED","XCTest snapshot returned 0 nodes on iOS simulator.");return{nodes:o,truncated:d.truncated??!1,backend:"xctest",...d.quality?{quality:d.quality}:{},...!d.quality&&d.message?{warnings:[d.message]}:{}}},back:async e=>{"tv"===a.target?await r(a,w("menu",t.appBundleId),M):await r(a,{command:"system"===e?"backSystem":"backInApp",appBundleId:t.appBundleId},M)},home:async()=>{"tv"===a.target?await r(a,w("home",t.appBundleId),M):await r(a,{command:"home",appBundleId:t.appBundleId},M)},rotate:async e=>{await r(a,{command:"rotate",orientation:e,appBundleId:t.appBundleId},M)},appSwitcher:async()=>{await r(a,{command:"appSwitcher",appBundleId:t.appBundleId},M)},readClipboard:()=>m(a),writeClipboard:e=>i(a,e),setSetting:(e,t,n,d)=>c(a,e,t,n,d),...x}}export{M as createAppleInteractor};
@@ -13,7 +13,8 @@ ${e.summaryLines.join("\n")}`:""}function _(e){var n;let r=!0===e.baselineInitia
13
13
  `}function z(e){var n,r,i,o;let a,s,u,l,d=Y(),f=!0===e.match,p=e.dimensionMismatch,c=[];return c.push(...function(e,n){if(!0===e.match){let e=n?function(e,n){return t(n,e)}("✓","green"):"✓";return[`${e} Screenshots match.`]}let r=e.dimensionMismatch,i=n?function(e,n){return t(n,e)}("✗","red"):"✗";if(r){let e=r.expected,t=r.actual;return[`${i} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let o=Q(e.differentPixels),a=Q(e.mismatchPercentage),s=0===a&&o>0?"<0.01":String(a),u=`${s}% pixels differ`;return[`${i} ${n?function(e,n){return t(n,e)}(u,"red"):u}`]}(e,d)),c.push(...function(e,n,r){if(n)return[];let i=[];if(e.diffPath){let n=q(e.diffPath),o=r?function(e,n){return t(n,e)}("Diff image:","dim"):"Diff image:",a=r?function(e,n){return t(n,e)}(n,"green"):n;i.push(` ${o} ${a}`)}if(e.currentOverlayPath){let n=q(e.currentOverlayPath),o=r?function(e,n){return t(n,e)}("Current overlay:","dim"):"Current overlay:",a=r?function(e,n){return t(n,e)}(n,"green"):n,s=Q(e.currentOverlayRefCount),u=s>0?` (${s} refs)`:"";i.push(` ${o} ${a}${u}`)}return i}(e,f,d)),f||p||(c.push(...(n=e,r=d,a=Q(n.differentPixels),s=Q(n.totalPixels),u=r?function(e,n){return t(n,e)}(String(a),"red"):String(a),[` ${u} different / ${s} total pixels`])),c.push(...(i=e,o=d,0===(l=function(e){let t=[];for(let n of(e.ocr?.movementClusters??[]).slice(0,2))t.push(`text movement cluster: ${function(e){let t=e.slice(0,4).map(e=>JSON.stringify(e)),n=e.length>t.length?` +${e.length-t.length} more`:"";return`${t.join(", ")}${n}`}(n.texts)} dx=${U(n.xRange)}px dy=${U(n.yRange)}px`);let n=(e.nonTextDeltas??[]).filter(e=>["icon","toggle","chevron"].includes(e.likelyKind)).slice(0,3);n.length>0&&t.push(`non-text controls: ${n.map(E).join("; ")}`);let r=(e.nonTextDeltas??[]).filter(e=>"separator"===e.likelyKind).slice(0,2);return r.length>0&&t.push(`non-text boundaries: ${r.map(E).join("; ")}`),t.slice(0,6)}(i)).length?[]:[` ${G("Hints:",o)}`,...l.map(e=>` - ${e}`)])),c.push(...function(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(0===n.length)return[];let r=[` ${G("Changed regions:",t)}`];for(let e of n.slice(0,5))r.push(...function(e){let t=0===e.shareOfDiffPercentage&&e.differentPixels>0?"<0.01":String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. ${e.location} x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff, change=${e.dominantChange}`],i=function(e){let t=[e.size?`size=${e.size}`:null,e.shape?`shape=${e.shape}`:null,"number"==typeof e.densityPercentage?`density=${e.densityPercentage}%`:null,e.averageBaselineColorHex&&e.averageCurrentColorHex?`avgColor=${e.averageBaselineColorHex}->${e.averageCurrentColorHex}`:null,"number"==typeof e.baselineLuminance&&"number"==typeof e.currentLuminance?`luminance=${e.baselineLuminance}->${e.currentLuminance}`:null].filter(e=>null!==e);return t.length>0?t.join(" "):null}(e);i&&r.push(` ${i}`);let o=e.currentOverlayMatches?.[0];if(o){let e=o.label?` "${o.label}"`:"";r.push(` overlaps @${o.ref}${e}, ${o.regionCoveragePercentage}% of region`)}return r}(e));return r}(e,d)),c.push(...function(e,t){let n=e.ocr?.matches??[];if(0===n.length)return[];let r=n.slice(0,8),i=[` ${G(`OCR text deltas (${e.ocr?.provider}; baselineBlocks=${e.ocr?.baselineBlocks} currentBlocks=${e.ocr?.currentBlocks}; showing ${r.length}/${n.length}; px):`,t)}`,` ${G("item | text | movePx | sizeDeltaPx | bboxBaseline | bboxCurrent | confidence | issueHint",t)}`];for(let[e,t]of r.entries()){let n=t.delta;i.push(` ${e+1} | ${JSON.stringify(t.text)} | ${J(n.x)},${J(n.y)} | ${J(n.width)},${J(n.height)} | ${W(t.baselineRect)} | ${W(t.currentRect)} | ${t.confidence} | ${t.possibleTextMetricMismatch?"ocr-bbox-size-change":"-"}`)}return i}(e,d)),c.push(...function(e,t){let n=e.nonTextDeltas??[];if(0===n.length)return[];let r=n.slice(0,8),i=[` ${G(`Non-text visual deltas (showing ${r.length}/${n.length}; px):`,t)}`,` ${G("item | region | slot | kind | bboxCurrent | nearestText",t)}`];for(let e of r)i.push(` ${e.index} | ${e.regionIndex?`r${e.regionIndex}`:"-"} | ${e.slot} | ${e.likelyKind} | ${W(e.rect)} | ${e.nearestText?JSON.stringify(e.nearestText):"-"}`);return i}(e,d))),`${c.join("\n")}
14
14
  `}function W(e){return`x=${e.x},y=${e.y},w=${e.width},h=${e.height}`}function J(e){return e>0?`+${e}`:String(e)}function E(e){let t=e.nearestText?` near ${JSON.stringify(e.nearestText)}`:"",n=e.regionIndex?` r${e.regionIndex}`:"";return`${e.likelyKind}${t}${n}`}function U(e){return e.min===e.max?J(e.min):`${J(e.min)}..${J(e.max)}`}function q(t){let n=process.cwd(),r=e.relative(n,t);return""!==r&&(r.startsWith("..")||e.isAbsolute(r))?t:""===r?".":`.${e.sep}${r}`}function Q(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function Y(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function G(e,n){return n?t("dim",e):e}function V(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function X(e,t){var n;let r="scroll-area"===(n=e.type)||"list"===n||"collection"===n||"table"===n?n:null;if(!r)return[];let i=[];if(e.node.hiddenContentAbove&&"below"!==t&&i.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&"above"!==t&&i.push(`[content below ${r} hidden]`),0===i.length)return[];let o=" ".repeat(e.depth+1);return i.map(e=>`${o}${e}`)}let Z={debug:g(function(e){let t=[e.outPath,e.message];for(let n of(t.push(...function(e){let t=e.crash,n=[`Crash: ${t.appName??"unknown app"}${void 0===t.crashedThread?"":` thread ${t.crashedThread}`}`];for(let e of(t.bundleId&&n.push(`Bundle: ${t.bundleId}`),t.exceptionType&&n.push(`Exception: ${t.exceptionType}`),t.terminationReason&&n.push(`Termination: ${t.terminationReason}`),t.topFrames))n.push(`Frame ${e.index}: ${e.image} ${e.symbol??e.address}`);for(let e of t.findings)n.push(`Finding: ${e}`);return n}(e)),e.matchedImages))t.push(`Matched: ${n.name} ${n.uuid}${n.arch?` ${n.arch}`:""}`);for(let n of e.warnings??[])t.push(`Warning: ${n}`);return{data:e,text:t.join("\n")}})};function ee(e){let t=e.ref??"",n=e.x,r=e.y;return t&&"number"==typeof n&&"number"==typeof r?{data:e,text:`Tapped @${t} (${n}, ${r})`}:y(e)}let et={click:g(ee),press:g(ee),get:({input:e,result:t})=>{var n;let r;return r=(n={result:t,format:e.format}).result,"text"===n.format?{data:r,text:"string"==typeof r.text?r.text:""}:"attrs"===n.format?{data:r,text:JSON.stringify(r.node??{},null,2)}:y(r)},is:g(function(e){return{data:e,text:`Passed: is ${e.predicate??"assertion"}`}}),find:g(function(e){return"string"==typeof e.text?{data:e,text:e.text}:"boolean"==typeof e.found?{data:e,text:`Found: ${e.found}`}:e.node?{data:e,text:JSON.stringify(e.node,null,2)}:y(e)})};function en(e){return y(s(e))}let er={boot:g(function(e){let t=e.platform??"unknown",n=e.device??e.id??"unknown";return{data:e,text:`Boot ready: ${n} (${t})`}}),shutdown:g(function(e){let t=e.platform??"unknown",n=e.device??e.id??"unknown",r=e.shutdown,i=!!r&&"object"==typeof r&&"success"in r&&!0===r.success;return{data:e,text:`${i?"Shutdown":"Shutdown failed"}: ${n} (${t})`}}),devices:g(function(e){return{data:{devices:e.map(f)},text:e.map(ei).join("\n")}}),apps:({input:e,result:t})=>{var n;return{data:{apps:(n={result:t,appsFilter:e.appsFilter}).result},stderr:"all"===n.appsFilter?"Showing all apps, including system apps.\n":"Showing user-installed apps. Use --all to include system apps.\n",text:n.result.length>0?n.result.join("\n"):"all"===n.appsFilter?"No apps found.":"No user-installed apps found."}},session:g(function(e){if("stateDir"in e)return{data:e,text:e.stateDir};let t={sessions:e.sessions.map(o)};return{data:t,text:JSON.stringify(t,null,2)}}),open:g(function(e){let t=r(e),n=[a(t)].filter(e=>!!e);return"string"==typeof t.sessionStateDir&&n.push(`Session state: ${t.sessionStateDir}`),{data:t,text:n.join("\n")||null}}),close:g(function(e){return y(u(e))}),install:g(en),reinstall:g(en),"install-from-source":g(function(e){return y(d(e))}),prepare:m};function ei(e){let t=e.kind?` ${e.kind}`:"",n=e.target?` target=${e.target}`:"",r="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${n})${r}`}let eo={logs:g(function(e){var t;return{data:e,text:"string"==typeof e.path?e.path:"",stderr:el([es(e,["active","state","backend","sizeBytes"]),(t=e,["started","stopped","marked","cleared","restarted","removedRotatedFiles"].map(e=>{var n,r;return n=e,!0===(r=t[e])?`${n}=true`:"number"==typeof r?`${n}=${r}`:""}).filter(Boolean).join(" ")||void 0),"string"==typeof e.hint?e.hint:void 0,eu(e.notes)])}}),network:g(function(e){let t=[],n="string"==typeof e.path?e.path:"";n&&t.push(n);let r=Array.isArray(e.entries)?e.entries:[];if(0===r.length)t.push("No recent HTTP(s) entries found.");else for(let e of r)t.push(...function(e){let t=x(e)??{},n="string"==typeof t.method?t.method:"HTTP",r="string"==typeof t.url?t.url:"<unknown-url>",i="number"==typeof t.status?` status=${t.status}`:"",o="string"==typeof t.timestamp?`${t.timestamp} `:"",a="number"==typeof t.durationMs?` durationMs=${t.durationMs}`:"",s=[`${o}${n} ${r}${i}${a}`];return ea(s,"headers",t.headers),ea(s,"request",t.requestBody),ea(s,"response",t.responseBody),s}(e));return{data:e,text:t.join("\n"),stderr:el([es(e,["active","state","backend","include","scannedLines","matchedLines"]),eu(e.notes)])}})};function ea(e,t,n){"string"==typeof n&&e.push(` ${t}: ${n}`)}function es(e,t){return t.map(t=>void 0!==e[t]&&null!==e[t]?`${t}=${e[t]}`:"").filter(Boolean).join(" ")||void 0}function eu(e){if(!Array.isArray(e))return;let t=e.filter(e=>"string"==typeof e&&e.length>0);return t.length>0?t.join("\n"):void 0}function el(e){return e.filter(e=>!!e).join("\n")||void 0}let ed={perf:g(function(e){return{data:e,text:function(e){var t,n,r,i;let o,a="xctrace"===(t=e).kind?function(e){var t,n,r,i,o;let a="string"==typeof e.perf?e.perf:void 0,s="string"==typeof(t=e).outPath?t.outPath:"string"==typeof t.reportPath?t.reportPath:void 0;if(a&&s&&"xctrace"===e.kind){let t;return n=s,r="string"==typeof e.mode?e.mode:"capture",i=a,o=e.template,t=[n,`Perf ${r}: ${i}`],"string"==typeof o&&t.push(`Template: ${o}`),t.join("\n")}}(t):function(e){var t;let n,r,i,o=(n=ef((t=e).action),r=ef(t.kind),i=ef(t.type),n&&r&&i?{action:n,kind:r,type:i}:void 0);if(o){let t;return`Perf ${o.action}: ${o.kind} ${o.type}${(t=ef(e.state))?` state=${t}`:""}${function(e){let t=ef(e.outPath);if(!t)return"";let n=ec(e.sizeBytes);return`
15
15
  ${t}${void 0!==n?` (${eg(n)})`:""}`}(e)}${function(e){let t=x(e.summary),n=x(t?.frameHealth);if(!n||!0!==n.available)return"";let r=ec(n.droppedFramePercent),i=ec(n.droppedFrameCount),o=ec(n.totalFrameCount);return void 0===r||void 0===i||void 0===o?"":`
16
- Trace frame health: dropped ${eh(r)} (${Math.round(i)}/${Math.round(o)} frames)`}(e)}`}}(t);if(a)return a;let s=x(e.artifact);if(s)return function(e){let t="string"==typeof e.kind?e.kind:"memory";if(!1===e.available){let n="string"==typeof e.reason&&e.reason.length>0?e.reason:"not available";return`Memory artifact (${t}): unavailable - ${n}`}let n="string"==typeof e.path?e.path:void 0,r=ec(e.sizeBytes),i=void 0===r?"":` (${eg(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}(s);let u=x(e.metrics),l=x(u?.fps),d=(n=u,(o=[function(e){if(e?.available!==!0)return;let t=ec(e.usagePercent);return void 0!==t?`CPU ${eh(t)}`:void 0}(x(n?.cpu)),function(e){let t;if(e?.available!==!0)return;let n=ec(e.residentMemoryKb)??ec(e.totalPssKb)??ec(e.totalRssKb);return void 0!==n?`memory ${t=n/1024,`${t>=10?Math.round(t):t.toFixed(1)}MB`}`:void 0}(x(n?.memory))].filter(e=>!!e)).length>0?o.join(", "):void 0);if(!l)return ep(d,"missing frame metric");if(!1===l.available){return ep(d,"string"==typeof(r=l).reason&&r.reason.length>0?r.reason:"not available")}let f=function(e){let t=ec(e.droppedFramePercent),n=ec(e.droppedFrameCount);if(void 0!==t&&void 0!==n){var r,i,o;return[`dropped ${eh(t)}`,(r=n,void 0!==(i=ec(e.totalFrameCount))?`(${Math.round(r)}/${Math.round(i)} frames)`:`(${Math.round(r)} dropped frames)`),void 0!==(o=ec(e.sampleWindowMs))?`window ${e$(o)}`:""].filter(Boolean).join(" ")}}(l);if(!f)return ep(d,"missing dropped-frame summary");let p=[`Frame health: ${f}`],c=(Array.isArray(i=l.worstWindows)?i.filter(v):[]).flatMap(e=>{let t=function(e){let t=ec(e.startOffsetMs),n=ec(e.endOffsetMs),r=ec(e.missedDeadlineFrameCount);if(void 0===t||void 0===n||void 0===r)return;let i=ec(e.worstFrameMs),o=void 0===i?"":`, worst ${e$(i)}`;return`- +${e$(t)}-+${e$(n)}: ${Math.round(r)} missed-deadline frames${o}`}(e);return t?[t]:[]});return c.length>0&&p.push("Worst windows:",...c),p.join("\n")}(e)}})};function ef(e){return"string"==typeof e?e:void 0}function ep(e,t){return e?`Performance: ${e}`:`Frame health: unavailable - ${t}`}function ec(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eh(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function e$(e){let t=Math.max(0,Math.round(e));if(t<1e3)return`${t}ms`;let n=Math.round(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}m ${i}s`:`${r}m`}function eg(e){if(e<1024)return`${Math.round(e)}B`;let t=e/1024;if(t<1024)return`${t>=10?Math.round(t):t.toFixed(1)}KB`;let n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)}MB`}let em={record:g(function(e){let t,n="string"==typeof e.outPath?e.outPath:"",r=Array.isArray(t=e.chunks)?t.flatMap(e=>e&&"object"==typeof e?"number"!=typeof e.index||"string"!=typeof e.path?[]:[{index:e.index,path:e.path}]:[]):[];if(r.length<=1){var i,o;let t;return{data:e,text:(i=e,t=[],(o=n)&&t.push(o),"string"==typeof i.sessionStateDir&&t.push(`Session state: ${i.sessionStateDir}`),"string"==typeof i.warning&&t.push(`Warning: ${i.warning}`),"string"==typeof i.overlayWarning&&t.push(`Overlay warning: ${i.overlayWarning}`),t.join("\n"))}}let a=["Recording chunks:"];for(let e of r)a.push(` ${e.index}: ${e.path}`);return"string"==typeof e.telemetryPath&&a.push(`Telemetry: ${e.telemetryPath}`),"string"==typeof e.warning&&a.push(`Warning: ${e.warning}`),"string"==typeof e.overlayWarning&&a.push(`Overlay warning: ${e.overlayWarning}`),{data:e,text:a.join("\n")}})},ey={appstate:g(function(e){return{data:e,text:function(e){if("ios"===e.platform){let t=[`Foreground app: ${e.appName??e.appBundleId??"unknown"}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.source&&t.push(`Source: ${e.source}`),t.join("\n")}if("android"===e.platform){let t=[`Foreground app: ${e.package??"unknown"}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join("\n")}return null}(e)}}),back:m,home:m,rotate:m,"app-switcher":m,keyboard:g(function(e){if("android"===e.platform&&"status"===e.action){var t;let n=[`Keyboard visible: ${!0===e.visible?"yes":"no"}`,`Input type: ${e.type??e.inputType??"unknown"}`,`Input owner: ${e.inputOwner??"unknown"}`];return e.inputMethodPackage&&n.push(`Input method: ${e.inputMethodPackage}`),e.focusedPackage&&n.push(`Focused package: ${e.focusedPackage}`),e.focusedResourceId&&n.push(`Focused resource: ${e.focusedResourceId}`),n.push(`Next action: ${(t=e.visible,"ime"===e.inputOwner?"Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry.":!0===t?"Keyboard is visible and focused input appears app-owned; fill/type can proceed.":"Keyboard is hidden; focus an app field before type, or use fill with a concrete target.")}`),{data:e,text:n.join("\n")}}return y(e)}),clipboard:g(function(e){return"read"===e.action?{data:e,text:e.text}:y(e)})},ex={...er,snapshot:({input:e,result:t})=>{var r;let o;return{data:o=i((r={result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}).result),jsonData:function(e){let{unchanged:t,...n}=e;return n}(o),text:function(e,t={}){var r,i,o,a;let s,u,d,f,p,c=e.nodes,g=Array.isArray(c)?c:[],m="string"==typeof e.backend?e.backend:void 0,y=function(e,t,n){let r;if(n.raw||!((r=e.androidSnapshot)&&"object"==typeof r&&"android-helper"===r.backend))return{nodes:t,filteredCount:0};let i=function(e){var t,n;if(0===e.length)return e;let r=new Set,i=new Map,o=new Map(e.map(e=>[e.index,e]));(function(e,t){for(let n of e)!n.rect||w(n.rect)||M(n)||j(e,n.index,t)})(e,r),function(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||M(i))continue;let o=function(e,t,n){let r=e;for(;"number"==typeof r.parentIndex;){let e=t.get(r.parentIndex);if(!e)break;if(n(e))return e;r=e}return null}(i,t,k);o&&function(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:!0===r.hiddenContentAbove||"above"===n||void 0,hiddenContentBelow:!0===r.hiddenContentBelow||"below"===n||void 0})}(r,o,function(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&w(t.rect)).map(e=>e.index);return 0===n.length?null:e.index<Math.min(...n)?"above":e.index>Math.max(...n)?"below":null}(i,e)),j(e,i.index,n)}}(e,o,r,i);for(let n of e){if(r.has(n.index)||!(!0===(t=n).hittable&&!S(t)&&t.rect&&w(t.rect)&&0===P(t).trim().length))continue;let o=function(e,t,n){let r=[],i=[],o=new Set;for(let a of e){if(n.has(a.index)||!F(a)||!C(a.rect,t.rect))continue;let e=P(a).trim().replace(/\s+/g," "),s=I(e);i.push(a.index),!e||!s||o.has(s)||(o.add(s),r.push(e))}return{label:r.join(", "),removableIndexes:i}}(N(e,n.index),n,r);if(o.label)for(let t of(i.set(n.index,{...n,...i.get(n.index),label:o.label}),o.removableIndexes))j(e,t,r)}for(let t of e){if(r.has(t.index)||!(!0===(n=t).hittable&&!S(n)&&n.rect&&w(n.rect)&&I(P(n))))continue;let i=I(P(t));if(!i)continue;let o=N(e,t.index).filter(e=>!r.has(e.index)&&function(e,t,n){if(!B(t)||!C(t.rect,e.rect))return!1;let r=I(P(t));return!!(r&&n!==r&&n.includes(r))}(t,e,i));for(let t of o.filter(F))j(e,t.index,r);let a=o.filter(e=>!F(e)),s=new Set(a.map(e=>I(P(e))).filter(e=>!!e));if(!(a.length<2)&&!(s.size<2))for(let t of a)j(e,t.index,r)}let a=new Map;for(let t of e){if(r.has(t.index)||!B(t))continue;let n=I(P(t));if(!n)continue;let o=a.get(n);if(o&&function(e,t,n){var r,i,o,a;return!n.has(e.index)&&(r=e.rect,i=t.rect,!r||!i||Math.abs(r.y+r.height/2-(i.y+i.height/2))<=Math.max(r.height,i.height,1))&&(o=e,a=t,(o.parentIndex===a.parentIndex?3>=Math.abs(o.index-a.index):o.parentIndex!==a.index&&a.parentIndex!==o.index&&1>=Math.abs((o.depth??0)-(a.depth??0))&&2>=Math.abs(o.index-a.index))||function(e,t){let n=e.parentIndex===t.index?t:t.parentIndex===e.index?e:null,r=n?.index===e.index?t:n?.index===t.index?e:null;return!!n&&!!r&&T(n,r).index===n.index}(e,t))}(o,t,r)){let s=function(e,t,n,r,i){var o,a,s;let u=T(t,n),l=u.index===t.index?n:t,d=(l.type??"").toLowerCase().includes("image")?"has image":null,f=i.get(u.index)??u,p=i.get(l.index)?.presentationHints??l.presentationHints;return i.set(u.index,{...f,presentationHints:(o=f.presentationHints,a=p,s=d,[...new Set([...Array.isArray(o)?o:[],...Array.isArray(a)?a:[],...s?[s]:[]])])}),j(e,l.index,r),i.get(u.index)??u}(e,o,t,r,i);a.set(n,s);continue}a.set(n,t)}return e.filter(e=>!r.has(e.index)).map(e=>i.get(e.index)??e)}(t);return{nodes:i,filteredCount:t.length-i.length}}(e,g,t),x=(s="string"==typeof(r=e).appName?r.appName:void 0,u="string"==typeof r.appBundleId?r.appBundleId:void 0,d=[],s&&d.push(`Page: ${s}`),u&&d.push(`App: ${u}`),d.length>0?`${d.join("\n")}
16
+ Trace frame health: dropped ${eh(r)} (${Math.round(i)}/${Math.round(o)} frames)`}(e)}`}}(t);if(a)return a;let s=x(e.artifact);if(s)return function(e){let t="string"==typeof e.kind?e.kind:"memory";if(!1===e.available){let n="string"==typeof e.reason&&e.reason.length>0?e.reason:"not available";return`Memory artifact (${t}): unavailable - ${n}`}let n="string"==typeof e.path?e.path:void 0,r=ec(e.sizeBytes),i=void 0===r?"":` (${eg(r)})`;return n?`Memory artifact (${t}): ${n}${i}`:`Memory artifact (${t}): captured${i}`}(s);let u=x(e.metrics),l=x(u?.fps),d=(n=u,(o=[function(e){if(e?.available!==!0)return;let t=ec(e.usagePercent);return void 0!==t?`CPU ${eh(t)}`:void 0}(x(n?.cpu)),function(e){let t;if(e?.available!==!0)return;let n=ec(e.residentMemoryKb)??ec(e.totalPssKb)??ec(e.totalRssKb);return void 0!==n?`memory ${t=n/1024,`${t>=10?Math.round(t):t.toFixed(1)}MB`}`:void 0}(x(n?.memory))].filter(e=>!!e)).length>0?o.join(", "):void 0);if(!l)return ep(d,"missing frame metric");if(!1===l.available){return ep(d,"string"==typeof(r=l).reason&&r.reason.length>0?r.reason:"not available")}let f=function(e){let t=ec(e.droppedFramePercent),n=ec(e.droppedFrameCount);if(void 0!==t&&void 0!==n){var r,i,o;return[`dropped ${eh(t)}`,(r=n,void 0!==(i=ec(e.totalFrameCount))?`(${Math.round(r)}/${Math.round(i)} frames)`:`(${Math.round(r)} dropped frames)`),void 0!==(o=ec(e.sampleWindowMs))?`window ${e$(o)}`:""].filter(Boolean).join(" ")}}(l);if(!f)return ep(d,"missing dropped-frame summary");let p=[`Frame health: ${f}`],c=(Array.isArray(i=l.worstWindows)?i.filter(v):[]).flatMap(e=>{let t=function(e){let t=ec(e.startOffsetMs),n=ec(e.endOffsetMs),r=ec(e.missedDeadlineFrameCount);if(void 0===t||void 0===n||void 0===r)return;let i=ec(e.worstFrameMs),o=void 0===i?"":`, worst ${e$(i)}`;return`- +${e$(t)}-+${e$(n)}: ${Math.round(r)} missed-deadline frames${o}`}(e);return t?[t]:[]});return c.length>0&&p.push("Worst windows:",...c),p.join("\n")}(e)}})};function ef(e){return"string"==typeof e?e:void 0}function ep(e,t){return e?`Performance: ${e}`:`Frame health: unavailable - ${t}`}function ec(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eh(e){return`${Number.isInteger(e)?e:e.toFixed(1)}%`}function e$(e){let t=Math.max(0,Math.round(e));if(t<1e3)return`${t}ms`;let n=Math.round(t/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60),i=n%60;return i>0?`${r}m ${i}s`:`${r}m`}function eg(e){if(e<1024)return`${Math.round(e)}B`;let t=e/1024;if(t<1024)return`${t>=10?Math.round(t):t.toFixed(1)}KB`;let n=t/1024;return`${n>=10?Math.round(n):n.toFixed(1)}MB`}let em={record:g(function(e){let t,n="string"==typeof e.outPath?e.outPath:"",r=Array.isArray(t=e.chunks)?t.flatMap(e=>e&&"object"==typeof e?"number"!=typeof e.index||"string"!=typeof e.path?[]:[{index:e.index,path:e.path}]:[]):[];if(r.length<=1){var i,o;let t;return{data:e,text:(i=e,t=[],(o=n)&&t.push(o),"string"==typeof i.sessionStateDir&&t.push(`Session state: ${i.sessionStateDir}`),"string"==typeof i.warning&&t.push(`Warning: ${i.warning}`),"string"==typeof i.overlayWarning&&t.push(`Overlay warning: ${i.overlayWarning}`),t.join("\n"))}}let a=["Recording chunks:"];for(let e of r)a.push(` ${e.index}: ${e.path}`);return"string"==typeof e.telemetryPath&&a.push(`Telemetry: ${e.telemetryPath}`),"string"==typeof e.warning&&a.push(`Warning: ${e.warning}`),"string"==typeof e.overlayWarning&&a.push(`Overlay warning: ${e.overlayWarning}`),{data:e,text:a.join("\n")}})},ey={appstate:g(function(e){return{data:e,text:function(e){if("ios"===e.platform){let t=[`Foreground app: ${e.appName??e.appBundleId??"unknown"}`];return e.appBundleId&&t.push(`Bundle: ${e.appBundleId}`),e.source&&t.push(`Source: ${e.source}`),t.join("\n")}if("android"===e.platform){let t=[`Foreground app: ${e.package??"unknown"}`];return e.activity&&t.push(`Activity: ${e.activity}`),t.join("\n")}return null}(e)}}),back:m,home:m,rotate:m,"app-switcher":m,keyboard:g(function(e){if("android"===e.platform&&"status"===e.action){var t;let n=[`Keyboard visible: ${!0===e.visible?"yes":"no"}`,`Input type: ${e.type??e.inputType??"unknown"}`,`Input owner: ${e.inputOwner??"unknown"}`];return e.inputMethodPackage&&n.push(`Input method: ${e.inputMethodPackage}`),e.focusedPackage&&n.push(`Focused package: ${e.focusedPackage}`),e.focusedResourceId&&n.push(`Focused resource: ${e.focusedResourceId}`),n.push(`Next action: ${(t=e.visible,"ime"===e.inputOwner?"Focused input appears to be owned by the keyboard/IME; dismiss or change the IME before retrying text entry.":!0===t?"Keyboard is visible and focused input appears app-owned; fill/type can proceed.":"Keyboard is hidden; focus an app field before type, or use fill with a concrete target.")}`),{data:e,text:n.join("\n")}}return y(e)}),clipboard:g(function(e){return"read"===e.action?{data:e,text:e.text}:y(e)})},ex={...er,snapshot:({input:e,result:t})=>{var r;let o;return{data:o=i((r={result:t,raw:e.raw,interactiveOnly:e.interactiveOnly,scope:e.scope,depth:e.depth}).result),jsonData:function(e){let{unchanged:t,...n}=e;return n}(o),stderr:r.result.snapshotDiagnostics?.warning?`${r.result.snapshotDiagnostics.warning}
17
+ `:void 0,text:function(e,t={}){var r,i,o,a;let s,u,d,f,p,c=e.nodes,g=Array.isArray(c)?c:[],m="string"==typeof e.backend?e.backend:void 0,y=function(e,t,n){let r;if(n.raw||!((r=e.androidSnapshot)&&"object"==typeof r&&"android-helper"===r.backend))return{nodes:t,filteredCount:0};let i=function(e){var t,n;if(0===e.length)return e;let r=new Set,i=new Map,o=new Map(e.map(e=>[e.index,e]));(function(e,t){for(let n of e)!n.rect||w(n.rect)||M(n)||j(e,n.index,t)})(e,r),function(e,t,n,r){for(let i of e){if(n.has(i.index)||i.rect||M(i))continue;let o=function(e,t,n){let r=e;for(;"number"==typeof r.parentIndex;){let e=t.get(r.parentIndex);if(!e)break;if(n(e))return e;r=e}return null}(i,t,k);o&&function(e,t,n){if(!n)return;let r=e.get(t.index)??t;e.set(t.index,{...r,hiddenContentAbove:!0===r.hiddenContentAbove||"above"===n||void 0,hiddenContentBelow:!0===r.hiddenContentBelow||"below"===n||void 0})}(r,o,function(e,t){let n=t.filter(t=>t.parentIndex===e.parentIndex&&t.rect&&w(t.rect)).map(e=>e.index);return 0===n.length?null:e.index<Math.min(...n)?"above":e.index>Math.max(...n)?"below":null}(i,e)),j(e,i.index,n)}}(e,o,r,i);for(let n of e){if(r.has(n.index)||!(!0===(t=n).hittable&&!S(t)&&t.rect&&w(t.rect)&&0===P(t).trim().length))continue;let o=function(e,t,n){let r=[],i=[],o=new Set;for(let a of e){if(n.has(a.index)||!F(a)||!C(a.rect,t.rect))continue;let e=P(a).trim().replace(/\s+/g," "),s=I(e);i.push(a.index),!e||!s||o.has(s)||(o.add(s),r.push(e))}return{label:r.join(", "),removableIndexes:i}}(N(e,n.index),n,r);if(o.label)for(let t of(i.set(n.index,{...n,...i.get(n.index),label:o.label}),o.removableIndexes))j(e,t,r)}for(let t of e){if(r.has(t.index)||!(!0===(n=t).hittable&&!S(n)&&n.rect&&w(n.rect)&&I(P(n))))continue;let i=I(P(t));if(!i)continue;let o=N(e,t.index).filter(e=>!r.has(e.index)&&function(e,t,n){if(!B(t)||!C(t.rect,e.rect))return!1;let r=I(P(t));return!!(r&&n!==r&&n.includes(r))}(t,e,i));for(let t of o.filter(F))j(e,t.index,r);let a=o.filter(e=>!F(e)),s=new Set(a.map(e=>I(P(e))).filter(e=>!!e));if(!(a.length<2)&&!(s.size<2))for(let t of a)j(e,t.index,r)}let a=new Map;for(let t of e){if(r.has(t.index)||!B(t))continue;let n=I(P(t));if(!n)continue;let o=a.get(n);if(o&&function(e,t,n){var r,i,o,a;return!n.has(e.index)&&(r=e.rect,i=t.rect,!r||!i||Math.abs(r.y+r.height/2-(i.y+i.height/2))<=Math.max(r.height,i.height,1))&&(o=e,a=t,(o.parentIndex===a.parentIndex?3>=Math.abs(o.index-a.index):o.parentIndex!==a.index&&a.parentIndex!==o.index&&1>=Math.abs((o.depth??0)-(a.depth??0))&&2>=Math.abs(o.index-a.index))||function(e,t){let n=e.parentIndex===t.index?t:t.parentIndex===e.index?e:null,r=n?.index===e.index?t:n?.index===t.index?e:null;return!!n&&!!r&&T(n,r).index===n.index}(e,t))}(o,t,r)){let s=function(e,t,n,r,i){var o,a,s;let u=T(t,n),l=u.index===t.index?n:t,d=(l.type??"").toLowerCase().includes("image")?"has image":null,f=i.get(u.index)??u,p=i.get(l.index)?.presentationHints??l.presentationHints;return i.set(u.index,{...f,presentationHints:(o=f.presentationHints,a=p,s=d,[...new Set([...Array.isArray(o)?o:[],...Array.isArray(a)?a:[],...s?[s]:[]])])}),j(e,l.index,r),i.get(u.index)??u}(e,o,t,r,i);a.set(n,s);continue}a.set(n,t)}return e.filter(e=>!r.has(e.index)).map(e=>i.get(e.index)??e)}(t);return{nodes:i,filteredCount:t.length-i.length}}(e,g,t),x=(s="string"==typeof(r=e).appName?r.appName:void 0,u="string"==typeof r.appBundleId?r.appBundleId:void 0,d=[],s&&d.push(`Page: ${s}`),u&&d.push(`App: ${u}`),d.length>0?`${d.join("\n")}
17
18
  `:""),v=function(e,t,n,r={nodes:t,filteredCount:0}){let i=V(e);if(!e.snapshotQuality){let e=function(e,t){if(!0===t.scoped||!0===t.depthLimited||e.length>3)return null;let n=1===e.length?"node":"nodes";return`Hint: sparse accessibility snapshot returned ${e.length} ${n}; snapshot state is invalid or unavailable for this screen. Use plain screenshot, not screenshot --overlay-refs, as visual truth. If screenshot shows the Home Screen or another app, run open for this app again first. Then navigate away with coordinates if needed and retry snapshot -i on the next screen.`}(t,n);e&&i.push(e)}!n.raw&&r.filteredCount>0&&i.push(`Collapsed ${r.filteredCount} Android helper node${1===r.filteredCount?"":"s"} from the agent-facing text snapshot; use --raw or --json for the full hierarchy.`);let o=r.filteredCount>0?r.nodes:t;return!n.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let n of e){let e=(n.type??"").toLowerCase(),r=function(e){var t;let n=e.trim().replace(/\s+/g," ").toLowerCase();return!n||(t=n,/\S+@\S+\.\S+/.test(t))?null:n}(l(n));if(!r)continue;let i=`${e}|${r}`,o=t.get(i)??[];o.push(n),t.set(i,o)}let n=0;for(let e of t.values())!(e.length<=1)&&function(e){for(let r=0;r<e.length;r+=1)for(let i=r+1;i<e.length;i+=1){var t,n;if(t=e[r]?.rect,n=e[i]?.rect,!t||!n||!(t.x+t.width<=n.x+.5||n.x+n.width<=t.x+.5||t.y+t.height<=n.y+.5||n.y+n.height<=t.y+.5))return!0}return!1}(e)&&(n+=e.length);return n>=8}(o)&&i.push("Warning: possible repeated nav subtree detected."),i}(e,g,t,y),b=v.length>0?`${v.join("\n")}
18
19
  `:"",A=t.raw?null:(f=e.unchanged)&&"object"==typeof f?"number"!=typeof f.ageMs||"number"!=typeof f.nodeCount?null:{ageMs:f.ageMs,nodeCount:f.nodeCount,interactiveOnly:!0===f.interactiveOnly||void 0,scope:"string"==typeof f.scope?f.scope:void 0}:null;if(A){let e;return`${x}${b}${e=function(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(Math.round(e/100)/10).toFixed(1)}s`;let t=e/6e4;return t<60?`${(Math.round(10*t)/10).toFixed(1)}m`:`${(Math.round(t/60*10)/10).toFixed(1)}h`}((i=A).ageMs),i.scope?`Scoped snapshot unchanged for scope "${i.scope}" since previous read ${e} ago.
19
20
  Previous refs in this scope remain valid. Use find/get/is for a targeted query, or --force-full to re-emit.`:i.interactiveOnly?`Interactive snapshot unchanged since previous read ${e} ago.