agent-device 0.17.7 → 0.17.8

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 (29) hide show
  1. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.7.apk → agent-device-android-multitouch-helper-0.17.8.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.17.8.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.17.7.manifest.json → agent-device-android-multitouch-helper-0.17.8.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.7.apk → agent-device-android-snapshot-helper-0.17.8.apk} +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.8.apk.sha256 +1 -0
  6. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.17.7.manifest.json → agent-device-android-snapshot-helper-0.17.8.manifest.json} +6 -6
  7. package/dist/src/2133.js +1 -1
  8. package/dist/src/2577.js +1 -0
  9. package/dist/src/4428.js +1 -1
  10. package/dist/src/8184.js +1 -1
  11. package/dist/src/8358.js +4 -0
  12. package/dist/src/9581.js +13 -2
  13. package/dist/src/9722.js +36 -36
  14. package/dist/src/9873.js +1 -1
  15. package/dist/src/9919.js +5 -5
  16. package/dist/src/cli-help.js +18 -7
  17. package/dist/src/cli.js +28 -18
  18. package/dist/src/interaction.js +1 -1
  19. package/dist/src/internal/bin.js +1 -1
  20. package/dist/src/record-trace-recording.js +1 -1
  21. package/dist/src/selector-runtime.js +1 -1
  22. package/dist/src/session.js +1 -1
  23. package/dist/src/snapshot.js +1 -1
  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.7.apk.sha256 +0 -1
  27. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.17.7.apk.sha256 +0 -1
  28. package/dist/src/2892.js +0 -4
  29. package/dist/src/368.js +0 -1
package/dist/src/9919.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 l}from"node:stream";import d from"node:net";import c from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./432.js";import{isAgentDeviceDaemonProcess as I,stopProcessForTakeover as v}from"./5628.js";import{readSnapshotDiagnosticsSummary as b,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as _,isDaemonResponseEnvelope as M,isDaemonProgressEnvelope as D,resolveDaemonPaths as P,resolveDaemonServerMode as k,computeDaemonCodeSignature as x,resolveDaemonTransportPreference as E}from"./2892.js";import{colorize as N,supportsColor as $}from"./6311.js";import{INTERNAL_COMMANDS as T,PUBLIC_COMMANDS as C}from"./2133.js";import{readVersion as U,findProjectRoot as L}from"./7244.js";import{sleep as R}from"./5560.js";import{normalizeSession as O,readRequiredString as F,readSerializedSnapshotCaptureAnnotations as B,readOptionalString as j,normalizeMaterializationReleaseResult as q,readSnapshotNodes as K,normalizeDeployResult as V,appDaemonWriters as G,observabilityDaemonWriters as H,normalizeOpenDevice as z,replayDaemonWriters as Y,buildMeta as W,systemDaemonWriters as J,resolveSessionName as X,buildFlags as Q,reactNativeDaemonWriters as Z,interactionDaemonWriters as ee,captureDaemonWriters as et,perfDaemonWriters as ea,gestureDaemonWriters as er,selectorDaemonWriters as en,createBatchDaemonWriter as ei,normalizeRuntimeHints as eo,normalizeDevice as es,recordingDaemonWriters as el,readScreenshotOverlayRefs as ed,normalizeStartupSample as ec,normalizeInstallFromSourceResult as eu}from"./9873.js";import{reloadMetro as ef,prepareMetroRuntime as ep}from"./8275.js";function em(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 eh="sha256";async function ey(e){let t=await ew(e.localPath,e.platform),a=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;try{let r=await eb({normalizedBase:a,token:e.token,artifact:t});if(r?.kind==="cache-hit")return r.uploadId;if(r?.kind==="direct-upload")try{return await eA(t.payloadPath,r),await eD({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await ev({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ew(t,a){var n,i,o;let s,l=e.statSync(t),d=r.basename(t),c=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,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 eg(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:d,artifactType:c?"app-bundle":"file",platform:u,contentType:c?"application/gzip":"application/octet-stream",sha256:await eP(a),sizeBytes:r.size,cleanup:()=>eI(f)}}catch(e){throw eI(f),e}}async function eg(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 eI(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function ev(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":eh,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await eS({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 eb(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 eA(e,t){let a=await eS({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 eS(e){return await e_({...e,url:e.url,redirectCount:0,startOffset:0})}async function e_(r){var i,o,s;let l="https:"===r.url.protocol?a:t,d=e.statSync(r.payloadPath).size,c=(i=r.headers,o=r.startOffset,s=d,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=l.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,em(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 e_({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=eM(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=eM(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,d):void 0;void 0!==l?l>=d?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):e_({...r,startOffset:l}).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 eM(e){return Array.isArray(e)?e[0]:e}async function eD(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(eh),r=new l({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 ek(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=e$(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eT("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eT("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=e$(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eT("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let d=await eN(e,t);d&&(s=d.installSource,n=d.uploadedArtifactId??n);let c=()=>eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await ex(e,t,i)??n),c()}async function ex(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let d=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(d)return await ey({localPath:d,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eE(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 eN(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 ey({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function e$(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 eT(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 eC(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 eU({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 eU(i){var o,s;let l,d=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),c="https:"===d.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()}},l=c.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"GET",path:d.pathname+d.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),l.destroy(e)},o);l.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))}),l.end()})}function eL(e){var t,a,r;let n,i,o=eG(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 l=(n=eO((a=o).port),i=eO(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eO(o.pid)??0,version:eR(o.version),codeSignature:eR(o.codeSignature),processStartTime:eR(o.processStartTime)}:null}function eR(e){return"string"==typeof e?e:void 0}function eO(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eF(e){let t=eG(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 eB(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,d;let a=e.existsSync(t.infoPath),r=eL(t.infoPath);if(r){let e=I(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eK(r),i.stoppedInfoProcess=!0),o=t.infoPath,eH(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eH(s),i.removedInfo=!0);let c=e.existsSync(t.lockPath),u=eF(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),l=t.lockPath,eH(l),i.removedLock=!0)}else c&&(d=t.lockPath,eH(d),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 ej(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eq(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return!1;let a=eF(e.lockPath);return!(a&&I(a.pid,a.processStartTime))&&(eH(e.lockPath),!0)}async function eK(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eV(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eG(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eH(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function ez(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`}function eY(e){let t=eW(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>eZ(e,t))]}function eW(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return e1(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&eJ(n)&&eX(n,"line")&&eQ(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&eJ(e)&&eX(e,"line")&&eQ(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,eX(e,"durationMs"),eQ(e,"errorCode"),void 0===e.resultTiming||e1(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function eJ(e){return"number"==typeof e.step}function eX(e,t){return void 0===e[t]||"number"==typeof e[t]}function eQ(e,t){return void 0===e[t]||"string"==typeof e[t]}function eZ(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(e0)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?ez(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function e0(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function e1(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function e3(e,t){return N(e,t,{validateStream:!1})}function e2(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}]`}function e5(e){return`\r\x1b[2K${e}`}function e4(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function e6(e,t){let a=e4(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function e8(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function e7(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e5(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=e2(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,d="⊙ ";if(!a)return e6(`${d}${n}${l}`,t.columns);let c=`${d}"`,u=`" in ${n}${l}`,f=e6(a,Math.max(0,e4(t.columns)-c.length-u.length));return e6(`${c}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,d,c,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(d=function(e){let t=$(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?e3("✓",a):"✓"}return"fail"===e.status?t?e3("⨯","red"):"⨯":"progress"===e.status?"⊙":t?e3("-","dim"):"-"}(a=e),c=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=e2(a),f=void 0!==a.durationMs?` (${ez(a.durationMs??0)})`:"",`${d} ${c}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eW(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>eZ(e,t))]})("pass"===i.status?{...e8(i),status:"passed",replayed:0,healed:0}:{...e8(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e5(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function e9(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
2
- `:a.text)}function te(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,l;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,l=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:l})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));tt(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 tt(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eC(e,t,a):a)}catch(e){n(e)}}let ta=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function tr(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of ta){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,l=s?function(e,t){let a=!1;try{I(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{eK(e)}finally{eH(t.infoPath),eH(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?l.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===C.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 tn(e,t){let a=tl(e,t);if(await ti(e,a))return!0;let r=tc(e,t,a);return!!r&&await ti(e,r)}async function ti(e,r){var n;return"http"===r?await function(e){let r=e.baseUrl?tm(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=d.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 to(e,t,a,r,n){let i=tl(e,a);try{return await ts(e,t,r,n,i)}catch(l){var o;let s=tc(e,a,i);if(!s||(o=l,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw l;return await ts(e,t,r,n,s)}}async function ts(e,t,a,r,n){return"http"===n?await tp(e,t,a,r):await tf(e,t,a,r)}function tl(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(td(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=>td(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function td(e,t){return"http"===t?!!e.httpPort:!!e.port}function tc(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return td(e,r)?r:null}function tu(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 tf(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,l=d.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,l.write(`${JSON.stringify(t)}
3
- `)}),c=!1,u="number"==typeof r?setTimeout(()=>{c=!0,l.destroy(),o(tr(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="",l=e7(a),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)){e9(a.event,l);continue}let r=M(a)?a.response:a;o(),n(r),e.end();return}catch(e){d(t,e);return}})}(l,{req:t,isSettled:()=>c,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{c=!0,i(e)},reject:e=>{c=!0,o(e)}}),l.on("error",e=>{c||(c=!0,u&&clearTimeout(u),o(tu(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function tp(e,r,n,i){var o,s;let l,d=e.baseUrl?new URL(tm(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!d)throw new f("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let c=JSON.stringify((o={includeTokenParam:!e.baseUrl},l=r.meta?.requestId??y(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:l,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:l,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 l=("https:"===d.protocol?a:t).request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},t=>{var a;(a=t.headers?.["content-type"],_(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,l=e7(a),d=e=>{try{let t=JSON.parse(e);if(D(t))return e9(t.event,l),!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=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=>te(t,{info:e,req:r,resolve:o,reject:s})}):em(t).then(t=>{m&&clearTimeout(m),te(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=eV(e),m="number"==typeof i?setTimeout(()=>{l.destroy(),s(tr(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;l.on("error",e=>{m&&clearTimeout(m),s(tu(e,r.meta?.requestId,p))}),l.write(c),l.end()})}function tm(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let th=new d.BlockList;async function ty(e){if(e.remoteBaseUrl)return await tw(e);let t=await tg(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return;let a=eF(e.lockPath);if(!a)return eH(e.lockPath);I(a.pid,a.processStartTime)||eH(e.lockPath)}(e.paths),await tI(e))}async function tw(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tn(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 tg(e){var t,a;let r=eL(e.paths.infoPath);if(!r)return null;let n=await tn(r,e.transportPreference);return(t=r,a=n,t.version===U()&&t.codeSignature===t_()&&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!==U()?`version mismatch (client v${U()})`:r.codeSignature!==t_()?"code-signature mismatch":n?"not reusable":"unreachable");process.stderr.write(`Replacing daemon (${i}) in ${a}: ${o}
4
- `)}catch{}}(r,n,e.paths.baseDir),await eK(r),eH(e.paths.infoPath),null)}async function tI(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 eB(t.paths,"start_error")),o<2){await R(150);continue}break}let l=await tA(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tM(l.exit),i.push(await eB(t.paths,"start_error")),o<2){await R(150);continue}break}if(await eq(t.paths)){n+=1;continue}let d=ej(t.paths),c=o<2,u=await eB(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await tA(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tM(e.exit));break}if(!c)break;d.hasInfo||d.hasLock||await R(150)}let o=ej(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=P(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 tv(t,a,r){if(!tb(t.command)||!a.startedByClient&&!r.ownedStateDir||eV(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eK(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eH(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eH(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 tb(e){return e===C.replay||e===C.test}async function tA(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=eL(t.paths.infoPath);if(e&&await tn(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await R(100)}return{kind:"timeout"}}function tS(){let t=L(),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)),l=e.existsSync(o);if(!s&&!l)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")?l:!s&&l}}function t_(){let e=tS();return x(e.useSrc?e.srcPath:e.distPath,e.root)}function tM(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 tD(t){var a,n,o,s,l;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"))||(d.isIPv4(a)?th.check(a,"ipv4"):!!d.isIPv6(a)&&th.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: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,l=h.rawBaseUrl,{paths:P((v=tb(o.command)&&!s&&!l)?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}),_=function(e){if(e.command!==C.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===C.prepare||t===C.replay||t===C.snapshot)?e.flags.timeoutMs:e.command===C.prepare?24e4:9e4}}(t),M=await w("daemon_startup",async()=>await ty(S),{requestId:b,session:t.session}),D=M.info,x=await ek(t,D),N={...t,positionals:x.positionals,flags:x.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,...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 to(D,N,S.transportPreference,S.paths,_),{requestId:b,command:t.command})}finally{await tv(t,M,S)}}th.addSubnet("127.0.0.0",8,"ipv4"),th.addAddress("::1","ipv6"),th.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tP=/^[0-9a-fA-F-]{32,36}$/;function tk(e){if(e&&tP.test(e))return e.replaceAll("-","").toUpperCase()}function tx(e,t){return`${e.uuid}:${tE(t)}`}function tE(e){return`0x${e.toString(16)}`}function tN(e){return"string"==typeof e&&e.length>0?e:void 0}function t$(...e){for(let t of e){let e=tN(t);if(e)return e}}function tT(e){return"object"==typeof e&&null!==e}function tC(e){return tT(e)?e:void 0}function tU(e){try{let t=JSON.parse(e);return tT(t)?t:null}catch{return null}}function tL(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 tR(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;tO(a,t)}function tO(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 tF(e){return[...new Set(e)]}let tB=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tj(e){return e.dsym&&e.searchPath?[tz(e.cwd,e.dsym),...await tq(tz(e.cwd,e.searchPath))]:e.dsym?[tz(e.cwd,e.dsym)]:e.searchPath?await tq(tz(e.cwd,e.searchPath)):[]}async function tq(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 tK(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 tK(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 tV(e,t){let a=(await Promise.all(tF(e).map(e=>tG(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 tG(e,t){var a;await tH(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=tk(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tH(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 tz(e,t){return r.resolve(e,t)}function tY(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tW(e,t,a,r){return{index:e,image:t.name,address:tE(a),symbol:r.get(tx(t,a))?.text}}function tJ(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 tX(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 tQ(a,n)))r.set(tx(e.image,e.address),e);return r}async function tQ(e,t){var a,r,n,i;let o,s,l=tF(t.addresses.map(tE)),d=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tE(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==d.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."})}(d.stderr),n=t.image,i=l,s=(""===(o=d.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 tZ(){return{dwarfdump:await t0("dwarfdump"),atos:await t0("atos")}}async function t0(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 t1(e){var t,a,n,i,o,s,l,d,u,p,m,h,y,w,g,I,v,b,A,S,_,M,D,P,k,x,E;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(),j=t5(B,e.artifact),q=t5(B,e.out??(a=j,$=(N=r.extname(a))?a.slice(0,-N.length):a,`${$}-symbolicated${N||".log"}`)),K=function(e){var t;let a,n=function(e){let t=tU(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tU(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=tk(tN(e.uuid)),n=tR(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tN(e.path);return[{index:t,name:tN(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tN(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=>tT(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tL(e[t]);if(void 0!==r)return r;tO(a,t)}(e,"imageIndex","IPS frame"),i=tR(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(tx(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 l}from"node:stream";import c from"node:net";import d from"node:fs/promises";import{toAppErrorCode as u,AppError as f}from"./733.js";import{runCmdDetachedMonitored as p,runCmd as m,runCmdSync as h}from"./8875.js";import{createRequestId as y,withDiagnosticTimer as w,emitDiagnostic as g}from"./432.js";import{isAgentDeviceDaemonProcess as v,stopProcessForTakeover as b}from"./5628.js";import{readSnapshotDiagnosticsSummary as I,consumeTextLines as A,shellQuote as S,shouldStreamRequestProgress as M,isDaemonResponseEnvelope as _,isDaemonProgressEnvelope as P,resolveDaemonPaths as D,resolveDaemonServerMode as k,computeDaemonCodeSignature as x,resolveDaemonTransportPreference as E}from"./8358.js";import{colorize as N,supportsColor as $}from"./6311.js";import{INTERNAL_COMMANDS as T,PUBLIC_COMMANDS as C}from"./2133.js";import{readVersion as U,findProjectRoot as L}from"./7244.js";import{sleep as R}from"./5560.js";import{normalizeSession as O,readRequiredString as F,readSerializedSnapshotCaptureAnnotations as B,readOptionalString as j,normalizeMaterializationReleaseResult as q,readSnapshotNodes as V,normalizeDeployResult as K,appDaemonWriters as G,observabilityDaemonWriters as H,normalizeOpenDevice as z,replayDaemonWriters as Y,buildMeta as W,systemDaemonWriters as J,resolveSessionName as X,buildFlags as Q,reactNativeDaemonWriters as Z,interactionDaemonWriters as ee,captureDaemonWriters as et,perfDaemonWriters as ea,gestureDaemonWriters as er,selectorDaemonWriters as en,createBatchDaemonWriter as ei,normalizeRuntimeHints as eo,normalizeDevice as es,recordingDaemonWriters as el,readScreenshotOverlayRefs as ec,normalizeStartupSample as ed,normalizeInstallFromSourceResult as eu}from"./9873.js";import{reloadMetro as ef,prepareMetroRuntime as ep}from"./8275.js";function em(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 eh="sha256";async function ey(e){let t=await ew(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 eA(t.payloadPath,r),await eP({normalizedBase:a,token:e.token,uploadId:r.uploadId})}catch{}return await eb({normalizedBase:a,token:e.token,artifact:t})}finally{t.cleanup()}}async function ew(t,a){var n,i,o;let s,l=e.statSync(t),c=r.basename(t),d=l.isDirectory(),u=("ios"===(n=a)||"android"===n?n:void 0)??(i=t,o=l,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=d?await eg(t,f):t,r=e.statSync(a);return{payloadPath:a,fileName:c,artifactType:d?"app-bundle":"file",platform:u,contentType:d?"application/gzip":"application/octet-stream",sha256:await eD(a),sizeBytes:r.size,cleanup:()=>ev(f)}}catch(e){throw ev(f),e}}async function eg(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 ev(t){for(let a of t)e.rmSync(a,{recursive:!0,force:!0})}async function eb(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":eh,"transfer-encoding":"chunked"};a&&(i.authorization=`Bearer ${a}`,i["x-agent-device-token"]=a);let o=await eS({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 eA(e,t){let a=await eS({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 eS(e){return await eM({...e,url:e.url,redirectCount:0,startOffset:0})}async function eM(r){var i,o,s;let l="https:"===r.url.protocol?a:t,c=e.statSync(r.payloadPath).size,d=(i=r.headers,o=r.startOffset,s=c,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=l.request({protocol:r.url.protocol,host:r.url.hostname,port:r.url.port,method:r.method,path:r.url.pathname+r.url.search,headers:d},e=>{i=!0,em(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 eM({...r,url:e,redirectCount:r.redirectCount+1}).then(t,a)}let l=308===i?function(e,t){let a=function(e){let t=e_(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=e_(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,c):void 0;void 0!==l?l>=c?t({statusCode:200,statusMessage:"Upload already complete",body:""}):l<=r.startOffset?a(new f("COMMAND_FAILED","Artifact upload resume did not advance",{offset:l,previousOffset:r.startOffset,url:r.url.toString()})):eM({...r,startOffset:l}).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 e_(e){return Array.isArray(e)?e[0]:e}async function eP(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 eD(t){let a=o(eh),r=new l({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 ek(e,t){var a;let n,i=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(!("string"==typeof(a=t).baseUrl&&a.baseUrl.length>0))return eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});o=function(e,t,a,n){var i,o;let s=function(e,t){if("screenshot"===e.command){let a=e$(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:eT("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:eT("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=e$(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:eT("recording",r.extname(t)||".mp4")}}return null}(e,t);if(!s)return a;void 0!==s.positionalPath&&(t[s.positionalIndex]=s.positionalPath);let l=(i=a,void 0===(o=s.flagPath)?i:{...i??{},out:o});return n[s.field]=s.localPath,l}(e,i,o,l);let c=await eN(e,t);c&&(s=c.installSource,n=c.uploadedArtifactId??n);let d=()=>eE({positionals:i,flags:o,installSource:s,uploadedArtifactId:n,clientArtifactPaths:l});return"install"!==e.command&&"reinstall"!==e.command||(n=await ex(e,t,i)??n),d()}async function ex(t,a,n){var i,o;let s,l=n[1];if(void 0===l)return;if(l.startsWith("remote:")){n[1]=l.slice(7);return}let c=(i=l,o=t.meta?.cwd,s=r.isAbsolute(i)?i:r.resolve(o??process.cwd(),i),e.existsSync(s)?s:void 0);if(c)return await ey({localPath:c,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform})}function eE(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 eN(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 ey({localPath:o,baseUrl:a.baseUrl,token:a.token,platform:t.flags?.platform});return{installSource:{...n,path:o},uploadedArtifactId:s}}function e$(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 eT(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 eC(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 eU({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 eU(i){var o,s;let l,c=new URL((o=i.baseUrl,s=i.artifactId,l=o.endsWith("/")?o:`${o}/`,new URL(`artifacts/${encodeURIComponent(s)}`,l).toString())),d="https:"===c.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()}},l=d.request({protocol:c.protocol,host:c.hostname,port:c.port,method:"GET",path:c.pathname+c.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),l.destroy(e)},o);l.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))}),l.end()})}function eL(e){var t,a,r;let n,i,o=eG(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 l=(n=eO((a=o).port),i=eO(a.httpPort),void 0===n&&void 0===i?null:{port:n,httpPort:i});return l?{token:s,...l,transport:"socket"===(r=o.transport)||"http"===r||"dual"===r?r:void 0,pid:eO(o.pid)??0,version:eR(o.version),codeSignature:eR(o.codeSignature),processStartTime:eR(o.processStartTime)}:null}function eR(e){return"string"==typeof e?e:void 0}function eO(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function eF(e){let t=eG(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 eB(t,a,r={}){let n=r.stopLiveProcesses??!0,i={reason:a,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{var o,s,l,c;let a=e.existsSync(t.infoPath),r=eL(t.infoPath);if(r){let e=v(r.pid,r.processStartTime);e&&!n?i.retainedInfoProcess=!0:(e&&(await eV(r),i.stoppedInfoProcess=!0),o=t.infoPath,eH(o),i.removedInfo=!0)}else a&&(s=t.infoPath,eH(s),i.removedInfo=!0);let d=e.existsSync(t.lockPath),u=eF(t.lockPath);if(u){let e=v(u.pid,u.processStartTime);e&&!n?i.retainedLockProcess=!0:(e&&(await b(u.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:u.processStartTime}),i.stoppedLockProcess=!0),l=t.lockPath,eH(l),i.removedLock=!0)}else d&&(c=t.lockPath,eH(c),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 ej(t){return{hasInfo:e.existsSync(t.infoPath),hasLock:e.existsSync(t.lockPath)}}async function eq(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return!1;let a=eF(e.lockPath);return!(a&&v(a.pid,a.processStartTime))&&(eH(e.lockPath),!0)}async function eV(e){await b(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function eK(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eG(t){if(!e.existsSync(t))return null;try{return JSON.parse(e.readFileSync(t,"utf8"))}catch{return null}}function eH(t){try{e.existsSync(t)&&e.unlinkSync(t)}catch{}}function ez(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`}function eY(e){let t=eW(e),a=t.findIndex(({stop:e})=>!1===e.ok);if(a<0)return[];let r=t.slice(Math.max(0,a-2),a+1);return[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...r.map(({stop:e,start:t})=>eZ(e,t))]}function eW(t){var a,n;let i=(a=t).artifactsDir?r.join(a.artifactsDir,`attempt-${a.attempts}`,"replay-timing.ndjson"):void 0;if(!i)return[];let o=function(t){try{return e.readFileSync(t,"utf8").split(/\r?\n/).filter(e=>e.trim().length>0).flatMap(e=>{try{let t=JSON.parse(e);return e1(t)?[t]:[]}catch{return[]}})}catch{return[]}}(i);if(0===o.length)return[];let s=[],l=[];for(let e of o){if("replay_action_start"===(n=e).type&&eJ(n)&&eX(n,"line")&&eQ(n,"command")&&(void 0===n.positionals||Array.isArray(n.positionals))){s.push(e);continue}(function(e){var t;return["replay_action_stop"===e.type&&eJ(e)&&eX(e,"line")&&eQ(e,"command"),void 0===(t=e).ok||"boolean"==typeof t.ok,eX(e,"durationMs"),eQ(e,"errorCode"),void 0===e.resultTiming||e1(e.resultTiming)].every(Boolean)})(e)&&l.push({stop:e,start:function(e,t){let a=t.command,r=e.findIndex(e=>e.step===t.step&&(void 0===a||void 0===e.command||e.command===a));if(!(r<0))return e.splice(r,1)[0]}(s,e)})}return l}function eJ(e){return"number"==typeof e.step}function eX(e,t){return void 0===e[t]||"number"==typeof e[t]}function eQ(e,t){return void 0===e[t]||"string"==typeof e[t]}function eZ(e,t){var a,r,n,i;let o,s,l=!1===e.ok?"[FAIL] ":!0===e.ok?"":"[info] ";return` ${l}${a=t,r=e,[function(e){if(!e)return"unknown";if(!e.startsWith("__maestro"))return e;let t=e.slice(9);return t.length>0?t[0].toLowerCase()+t.slice(1):e}(a?.command??r.command),...(a?.positionals??[]).map(e0)].join(" ")}${n=e,i=t,(s=["number"==typeof(o=i?.line??n.line)?`line ${o}`:"","number"==typeof n.durationMs?ez(n.durationMs):"",n.errorCode??"",n.resultTiming?`timing ${JSON.stringify(n.resultTiming)}`:""].filter(Boolean)).length>0?` (${s.join(", ")})`:""}`}function e0(e){return"string"==typeof e?JSON.stringify(e):"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e)}function e1(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function e3(e,t){return N(e,t,{validateStream:!1})}function e2(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}]`}function e5(e){return`\r\x1b[2K${e}`}function e4(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?Math.floor(e):80}function e6(e,t){let a=e4(t);return e.length<=a?e:a<=0?"":a<=3?".".repeat(a):`${e.slice(0,a-3)}...`}function e8(e){return{file:e.file,title:e.title,durationMs:e.durationMs??0,attempts:e.attempt??1,artifactsDir:e.artifactsDir,session:e.session??""}}function e7(e){return function(e={}){let t=new Set,a=!1;return{render(n){var i,o;if("replay-test-suite"===n.type){t.clear(),a=!1;return}if("replay-test"!==n.type)return;if("progress"===n.status){if(!e.liveProgress)return;return a=!0,{text:e5(function(e,t){let a=e.title?.trim(),n=r.basename(e.file),i=e2(e),o=e.stepIndex??0,s=e.stepTotal??0,l=`${i} [${o}/${s}]`,c="⊙ ";if(!a)return e6(`${c}${n}${l}`,t.columns);let d=`${c}"`,u=`" in ${n}${l}`,f=e6(a,Math.max(0,e4(t.columns)-d.length-u.length));return e6(`${d}${f}${u}`,t.columns)}(n,e)),newline:!1}}if("pass"===(i=n).status||"skip"===i.status||"fail"===i.status&&!i.retrying){let e,a=(e="number"==typeof(o=n).shardIndex?o.shardIndex:"",[o.status,o.index,o.total,o.file,o.title??"",e].join("\0"));if(t.has(a))return;t.add(a)}let s=function(e,t={}){if("replay-test"===e.type)return function(e,t){var a,n,i,o;let s,l,c,d,u,f;if("start"===e.status||"progress"===e.status||"fail"===e.status&&e.retrying)return;let p=[(c=function(e){let t=$(process.stderr);if("pass"===e.status){let a=e.attempt&&e.attempt>1?"yellow":"green";return t?e3("✓",a):"✓"}return"fail"===e.status?t?e3("⨯","red"):"⨯":"progress"===e.status?"⊙":t?e3("-","dim"):"-"}(a=e),d=(n=a,s=n.title?.trim(),l=r.basename(n.file),s?`${JSON.stringify(s)} in ${l}`:l),u=e2(a),f=void 0!==a.durationMs?` (${ez(a.durationMs??0)})`:"",`${c} ${d}${u}${f}`)];return function(e,t,a){if(a.verbose&&"fail"===t.status)return;let r=t.message?.replace(/\s+/g," ").trim();r&&e.push(` ${"fail"===t.status?`failed at: ${r}`:r}`),"fail"===t.status&&!t.retrying&&(t.session&&e.push(` session: ${t.session}`),t.artifactsDir&&e.push(` artifacts: ${t.artifactsDir}`))}(p,e,t),t.verbose&&p.push(...("pass"===(i=e).status||"fail"===i.status)&&i.artifactsDir&&i.attempt?(function(e){if("skipped"===e.status)return[];let t=eW(e);return 0===t.length?[]:[e.attempts>1?`steps (attempt ${e.attempts}):`:"steps:",...t.map(({stop:e,start:t})=>eZ(e,t))]})("pass"===i.status?{...e8(i),status:"passed",replayed:0,healed:0}:{...e8(o=i),status:"failed",error:{code:"COMMAND_FAILED",message:o.message??"Unknown test failure"}}).map(e=>` ${e}`):[]),p.join("\n")}(e,t)}(n,e);if(!s)return;let l=a?e5(s):s;return a=!1,{text:l,newline:!0}}}}({verbose:!!(e.flags?.verbose||e.meta?.debug),liveProgress:!0===process.stderr.isTTY&&!process.env.CI,columns:process.stderr.columns})}function e9(e,t){let a=t.render(e);a&&process.stderr.write(a.newline?`${a.text}
2
+ `:a.text)}function te(e,t){let{info:a,req:r,resolve:n,reject:i}=t;try{var o,s,l;let t=(o=e,JSON.parse(o));if(t.error){let e;return void i((s=t.error,l=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:l})))}if(!t.result||"object"!=typeof t.result)return void i(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));tt(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 tt(e,t,a,r,n){try{r(e.baseUrl&&a.ok?await eC(e,t,a):a)}catch(e){n(e)}}let ta=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];function tr(e,t,a,r,n,i){let o=n?{terminated:0}:function(){let e=0;try{for(let t of ta){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,l=s?function(e,t){let a=!1;try{v(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{eV(e)}finally{eH(t.infoPath),eH(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?l.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===C.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 tn(e,t){let a=td(e,t);if(await ti(e,a))return!0;let r=tf(e,t,a);return!!r&&await ti(e,r)}async function ti(e,t){var a;return"http"===t?await ts(e).then(e=>e.reachable):await ((a=e.port)?new Promise(e=>{let t=!1,r=c.createConnection({host:"127.0.0.1",port:a},()=>{n(!0)}),n=a=>{t||(t=!0,r.destroy(),e(a))};r.setTimeout(500),r.on("timeout",()=>{n(!1)}),r.on("error",()=>{n(!1)})}):Promise.resolve(!1))}async function to(e){let t=await ts(e);if(!e.baseUrl||!t.reachable)return t;if("number"==typeof t.rpcProtocolVersion&&1!==t.rpcProtocolVersion)throw new f("COMMAND_FAILED","Remote daemon RPC protocol is incompatible",{daemonBaseUrl:e.baseUrl,clientVersion:U(),remoteVersion:t.version,remoteService:t.service,supportedRpcProtocolVersion:1,remoteRpcProtocolVersion:t.rpcProtocolVersion,hint:"Upgrade agent-device on the client or remote host so both support the same daemon RPC protocol."});return t}function ts(e){let r=e.baseUrl?ty(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve({reachable:!1});let n=new URL(r),i="https:"===n.protocol?a:t,o=e.baseUrl?3e3:500;return new Promise(t=>{let a={};e.baseUrl&&e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token);let r=i.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:o,headers:a},e=>{let a="";e.setEncoding("utf8"),e.on("data",e=>{a+=e}),e.on("end",()=>{let r=e.statusCode??500;t({reachable:r<500,statusCode:r,...function(e){try{let t=JSON.parse(e);return{service:"string"==typeof t.service?t.service:void 0,version:"string"==typeof t.version?t.version:void 0,rpcProtocolVersion:"number"==typeof t.rpcProtocolVersion?t.rpcProtocolVersion:void 0}}catch{return{}}}(a)})})});r.on("timeout",()=>{r.destroy(),t({reachable:!1})}),r.on("error",()=>{t({reachable:!1})}),r.end()})}async function tl(e,t,a,r,n){let i=td(e,a);try{return await tc(e,t,r,n,i)}catch(l){var o;let s=tf(e,a,i);if(!s||(o=l,"socket"!==i||!(o instanceof f)||"COMMAND_FAILED"!==o.code||"Failed to communicate with daemon"!==o.message||o.details?.daemonSocketRequestWritten!==!1))throw l;return await tc(e,t,r,n,s)}}async function tc(e,t,a,r,n){return"http"===n?await th(e,t,a,r):await tm(e,t,a,r)}function td(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(tu(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=>tu(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tu(e,t){return"http"===t?!!e.httpPort:!!e.port}function tf(e,t,a){if("auto"!==t||e.baseUrl)return null;let r="socket"===a?"http":"socket";return tu(e,r)?r:null}function tp(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 tm(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,l=c.createConnection({host:"127.0.0.1",port:n},()=>{s=!0,l.write(`${JSON.stringify(t)}
3
+ `)}),d=!1,u="number"==typeof r?setTimeout(()=>{d=!0,l.destroy(),o(tr(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="",l=e7(a),c=(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(P(a)){e9(a.event,l);continue}let r=_(a)?a.response:a;o(),n(r),e.end();return}catch(e){c(t,e);return}})}(l,{req:t,isSettled:()=>d,clearTimeout:()=>{u&&clearTimeout(u)},resolve:e=>{d=!0,i(e)},reject:e=>{d=!0,o(e)}}),l.on("error",e=>{d||(d=!0,u&&clearTimeout(u),o(tp(e,t.meta?.requestId,!1,{daemonSocketRequestWritten:s})))})})}async function th(e,r,n,i){var o,s;let l,c=e.baseUrl?new URL(ty(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!c)throw new f("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let d=JSON.stringify((o={includeTokenParam:!e.baseUrl},l=r.meta?.requestId??y(),"lease_allocate"!==(s=r.command)&&"lease_heartbeat"!==s&&"lease_release"!==s?{jsonrpc:"2.0",id:l,method:"agent_device.command",params:r}:{jsonrpc:"2.0",id:l,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(d)};return e.baseUrl&&e.token&&(u.authorization=`Bearer ${e.token}`,u["x-agent-device-token"]=e.token),await new Promise((o,s)=>{let l=("https:"===c.protocol?a:t).request({protocol:c.protocol,host:c.hostname,port:c.port,method:"POST",path:c.pathname+c.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,l=e7(a),c=e=>{try{let t=JSON.parse(e);if(P(t))return e9(t.event,l),!1;if(_(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&&c(e))return}),e.on("end",()=>{if(s)return;let e=o.trim();e&&c(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=>te(t,{info:e,req:r,resolve:o,reject:s})}):em(t).then(t=>{m&&clearTimeout(m),te(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=eK(e),m="number"==typeof i?setTimeout(()=>{l.destroy(),s(tr(e,n,r.meta?.requestId,r.command,p,i))},i):void 0;l.on("error",e=>{m&&clearTimeout(m),s(tp(e,r.meta?.requestId,p))}),l.write(d),l.end()})}function ty(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let tw=new c.BlockList;function tg(t){var a,n,o,s,l;let d,u,p,m=(a=t,a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),h=(n=t,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(/\/+$/,"")}}(d=n.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),function(e,t){let a;if(!(!e||"localhost"===(a=new URL(e).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(c.isIPv4(a)?tw.check(a,"ipv4"):!!c.isIPv6(a)&&tw.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,p=n.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN),{rawBaseUrl:d,remoteBaseUrl:u,authToken:p}),y=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:k(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0))}}(t,h.remoteBaseUrl),w=(o=t,s=m,l=h.rawBaseUrl,tM(o.command)&&!s&&!l);return{paths:D(w?e.mkdtempSync(r.join(i.tmpdir(),"agent-device-replay-daemon-")):m),transportPreference:y.preference,serverMode:y.serverMode,ownedStateDir:w,remoteBaseUrl:h.remoteBaseUrl,remoteAuthToken:h.authToken}}async function tv(e){if(e.remoteBaseUrl)return await tb(e);let t=await tI(e);return t?{info:t,startedByClient:!1}:(!function(e){let t=ej(e);if(!t.hasLock||t.hasInfo)return;let a=eF(e.lockPath);if(!a)return eH(e.lockPath);v(a.pid,a.processStartTime)||eH(e.lockPath)}(e.paths),await tA(e))}async function tb(e){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if((await to(t)).reachable)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 tI(e){var t,a;let r=eL(e.paths.infoPath);if(!r)return null;let n=await tn(r,e.transportPreference);return(t=r,a=n,t.version===U()&&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!==U()?`version mismatch (client v${U()})`: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 eV(r),eH(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=tP(),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 eB(t.paths,"start_error")),o<2){await R(150);continue}break}let l=await t_(15e3,t,s);if("ready"===l.kind)return{info:l.info,startedByClient:!0};if("early_exit"===l.kind){if(r=l.exit,a=tk(l.exit),i.push(await eB(t.paths,"start_error")),o<2){await R(150);continue}break}if(await eq(t.paths)){n+=1;continue}let c=ej(t.paths),d=o<2,u=await eB(t.paths,"startup_timeout",{stopLiveProcesses:!1});if(i.push(u),u.retainedInfoProcess||u.retainedLockProcess){let e=await t_(15e3,t,s);if("ready"===e.kind)return{info:e.info,startedByClient:!0};"early_exit"===e.kind&&(r=e.exit,a=tk(e.exit));break}if(!d)break;c.hasInfo||c.hasLock||await R(150)}let o=ej(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=D(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 tS(t,a,r){if(!tM(t.command)||!a.startedByClient&&!r.ownedStateDir||eK(a.info))return;let n={pid:a.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await eV(a.info)}catch(e){n.error=e instanceof Error?e.message:String(e)}finally{let t=e.existsSync(r.paths.infoPath);eH(r.paths.infoPath),n.removedInfo=t&&!e.existsSync(r.paths.infoPath);let a=e.existsSync(r.paths.lockPath);eH(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 tM(e){return e===C.replay||e===C.test}async function t_(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=eL(t.paths.infoPath);if(e&&await tn(e,t.transportPreference))return{kind:"ready",info:e};if(r)return{kind:"early_exit",exit:r};await R(100)}return{kind:"timeout"}}function tP(){let t=L(),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)),l=e.existsSync(o);if(!s&&!l)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")?l:!s&&l}}function tD(){let e=tP();return x(e.useSrc?e.srcPath:e.distPath,e.root)}function tk(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 tx(e){let t=e.meta?.requestId??y(),a=!!(e.meta?.debug||e.flags?.verbose),r=tg(e),n=function(e){if(e.command!==C.test){var t;return"number"==typeof e.flags?.timeoutMs&&((t=e.command)===C.prepare||t===C.replay||t===C.snapshot)?e.flags.timeoutMs:e.command===C.prepare?24e4:9e4}}(e),i=await w("daemon_startup",async()=>await tv(r),{requestId:t,session:e.session}),o=i.info,s=await ek(e,o),l={...e,positionals:s.positionals,flags:s.flags,token:o.token,meta:{...e.meta??{},requestId:t,debug:a,cwd:e.meta?.cwd,sessionExplicit:e.meta?.sessionExplicit,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};g({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}});try{return await w("daemon_request",async()=>await tl(o,l,r.transportPreference,r.paths,n),{requestId:t,command:e.command})}finally{await tS(e,i,r)}}tw.addSubnet("127.0.0.0",8,"ipv4"),tw.addAddress("::1","ipv6"),tw.addSubnet("::ffff:127.0.0.0",104,"ipv6");let tE=/^[0-9a-fA-F-]{32,36}$/;function tN(e){if(e&&tE.test(e))return e.replaceAll("-","").toUpperCase()}function t$(e,t){return`${e.uuid}:${tT(t)}`}function tT(e){return`0x${e.toString(16)}`}function tC(e){return"string"==typeof e&&e.length>0?e:void 0}function tU(...e){for(let t of e){let e=tC(t);if(e)return e}}function tL(e){return"object"==typeof e&&null!==e}function tR(e){return tL(e)?e:void 0}function tO(e){try{let t=JSON.parse(e);return tL(t)?t:null}catch{return null}}function tF(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;tj(a,t)}function tj(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 tq(e){return[...new Set(e)]}let tV=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function tK(e){return e.dsym&&e.searchPath?[tJ(e.cwd,e.dsym),...await tG(tJ(e.cwd,e.searchPath))]:e.dsym?[tJ(e.cwd,e.dsym)]:e.searchPath?await tG(tJ(e.cwd,e.searchPath)):[]}async function tG(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 tH(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 d.readdir(i,{withFileTypes:!0})))e.isDirectory()&&await n(r.join(i,e.name))}}return await n(e),t}async function tH(e,t){try{return await d.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 tz(e,t){let a=(await Promise.all(tq(e).map(e=>tY(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 tY(e,t){var a;await tW(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=tN(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function tW(e){let t=await d.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 tJ(e,t){return r.resolve(e,t)}function tX(e,t){let a=`${t}:`,r=e.find(e=>e.trimStart().startsWith(a));return r&&r.slice(r.indexOf(":")+1).trim()||void 0}function tQ(e,t,a,r){return{index:e,image:t.name,address:tT(a),symbol:r.get(t$(t,a))?.text}}function tZ(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 t0(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 t1(a,n)))r.set(t$(e.image,e.address),e);return r}async function t1(e,t){var a,r,n,i;let o,s,l=tq(t.addresses.map(tT)),c=await m(e,(a=t,r=l,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",tT(a.image.base),...r]),{timeoutMs:3e4,allowFailure:!0});return 0!==c.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."})}(c.stderr),n=t.image,i=l,s=(""===(o=c.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 t3(){return{dwarfdump:await t2("dwarfdump"),atos:await t2("atos")}}async function t2(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 t5(e){var t,a,n,i,o,s,l,c,u,p,m,h,y,w,g,v,b,I,A,S,M,_,P,D,k,x,E;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(),j=t8(B,e.artifact),q=t8(B,e.out??(a=j,$=(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=tO(e);if(t)return{payload:t};let a=e.indexOf("\n");if(-1===a)return null;let r=e.slice(0,a),n=tO(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=tN(tC(e.uuid)),n=tB(e,"base","IPS usedImages");if(!a||void 0===n)return[];let i=tC(e.path);return[{index:t,name:tC(e.name)??(i?r.basename(i):`image-${t}`),uuid:a,arch:tC(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=>tL(e)):[]})(e).flatMap((e,r)=>(function(e,t,a,r){let n=function(e,t,a){if(!Object.hasOwn(e,t))return;let r=tF(e[t]);if(void 0!==r)return r;tj(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(t$(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 t3(j,"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=tk(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tB.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(tx(n.image,n.address))?.text;return!i||t.includes(i)?t:`${t} // ${i}`}).join("\n")}}}(t);K||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 V=await tj({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===V.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 G=await tZ(),H=await tV(V,G.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=tF(e.map(e=>e.uuid)),i=tF(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."})}(K.images,H,!!e.dsym),Y=await tX(K.addresses,z,G.atos),W=K.write(Y);await c.mkdir(r.dirname(q),{recursive:!0}),await c.writeFile(q,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=K.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:j,outPath:q,crash:"ips"===K.format?(n=K.document,i=K.frameMatches,o=Y,U=function(e){let t=tL(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tC(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(l=s.header)?tU(l):null,{appName:(d=T,u=C,t$(d.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,t$(tC(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,t$(tC(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,t$(w.incident,g?.incident_id)),timestamp:(I=T,v=C,t$(I.captureTime,v?.timestamp)),exceptionType:(b=T.exception,tN(tC(b)?.type)),exceptionCodes:function(e){let t=tC(e);if(t)return t$(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tC(e);if(t){let e;return(e=[tN(t.namespace),tN(t.code),tN(t.reason)].filter(e=>!!e)).length>0?e.join(" "):void 0}}(T.termination)}),crashedThread:U,topFrames:(A=i,S=U,_=o,A.filter(e=>void 0===S||e.threadIndex===S).slice(0,5).map(e=>tW(e.frameIndex,e.image,e.address,_))),findings:[]},findings:tJ(L)}):(M=K.lines,D=K.frameMatches,P=Y,O=function(e){let t=tY(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])}}(M),{...F={format:"text",appName:(R=tY(M,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:tY(M,"Identifier"),version:tY(M,"Version"),incident:tY(M,"Incident Identifier"),timestamp:tY(M,"Date/Time"),exceptionType:tY(M,"Exception Type"),exceptionCodes:tY(M,"Exception Codes"),terminationReason:tY(M,"Termination Reason"),crashedThread:O,topFrames:(k=D,x=O,E=P,void 0===x?[]:k.filter(e=>e.threadIndex===x).slice(0,5).map(e=>tW(e.frameIndex,e.image,e.address,E))),findings:[]},findings:tJ(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${q}`}}async function t3(e,t){await t2(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 t2(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 t5(e,t){return r.resolve(e,t)}let t4={...G,...et,...ee,...er,...en,...H,...ea,...Z,...el,...Y,...J,batch:ei(function(e,t){let a=t4[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function t6(e={},t={}){let a=t.transport??tD,r=async(t,r=[],n={})=>{let i=t7(e,n),o=await a({session:X(i.session),command:t,positionals:r,flags:Q(i),runtime:i.runtime,meta:W(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(T.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(O)},i=async(e,t={})=>{let a=t4[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>X(t7(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(es)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>P(t7(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=>V(await i("install",e),o(e)),reinstall:async e=>V(await i("reinstall",e),o(e)),installFromSource:async e=>eu(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=z(a),n=j(a,"appBundleId");return{session:t,sessionStateDir:j(a,"sessionStateDir"),appName:j(a,"appName"),appBundleId:n,appId:n,startup:ec(a.startup),runtime:eo(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=>q(await r(T.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>t9(await r(T.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>t9(await r(T.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(T.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ep({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 ef({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,l,d,c=o(e);return t=await i("snapshot",e),a=c,n=j(t,"appBundleId"),{nodes:K(t.nodes),truncated:!0===t.truncated,appName:j(t,"appName"),appBundleId:n,...(s=t8((r=t).visibility),l=t8(r.unchanged),d=b(r.snapshotDiagnostics),{...s?{visibility:s}:{},...B(r),...l?{unchanged:l}:{},...d?{snapshotDiagnostics:d}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:F(a,"path"),overlayRefs:ed(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 t1({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 t8(e){return"object"==typeof e&&null!==e?e:void 0}function t7(e,t){return{...e,...t}}function t9(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:F(t,"leaseId"),tenantId:F(t,"tenantId"),runId:F(t,"runId"),backend:F(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{t6 as createAgentDeviceClient,ez as formatDurationSeconds,eY as replayTestFailureStepLines,tD as sendToDaemon};
6
+ ${r}`:r})(n,o,e)}}(t=await t4(j,"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=tN(t[4]);if(!a)return null;let n=function(e,t){let a=e.split(/\s+/),n=a.at(-1);if(n&&tV.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(t$(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 K=await tK({cwd:B,dsym:e.dsym,searchPath:e.searchPath});if(0===K.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 G=await t3(),H=await tz(K,G.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=tq(e.map(e=>e.uuid)),i=tq(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,H,!!e.dsym),Y=await t0(V.addresses,z,G.atos),W=V.write(Y);await d.mkdir(r.dirname(q),{recursive:!0}),await d.writeFile(q,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:j,outPath:q,crash:"ips"===V.format?(n=V.document,i=V.frameMatches,o=Y,U=function(e){let t=tF(e.faultingThread);if(void 0!==t)return t;let a=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>tR(e)?.triggered===!0);return -1===a?void 0:a}(n.payload),{...L={format:"ips",...(T=(s=n).payload,C=(l=s.header)?tO(l):null,{appName:(c=T,u=C,tU(c.procName,u?.app_name,u?.name)),bundleId:(p=T,m=C,tU(tR(p.bundleInfo)?.CFBundleIdentifier,m?.bundleID)),version:(h=T,y=C,tU(tR(h.bundleInfo)?.CFBundleShortVersionString,y?.app_version)),incident:(w=T,g=C,tU(w.incident,g?.incident_id)),timestamp:(v=T,b=C,tU(v.captureTime,b?.timestamp)),exceptionType:(I=T.exception,tC(tR(I)?.type)),exceptionCodes:function(e){let t=tR(e);if(t)return tU(t.codes,t.rawCodes)}(T.exception),terminationReason:function(e){let t=tR(e);if(t){let e;return(e=[tC(t.namespace),tC(t.code),tC(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=>tQ(e.frameIndex,e.image,e.address,M))),findings:[]},findings:tZ(L)}):(_=V.lines,P=V.frameMatches,D=Y,O=function(e){let t=tX(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])}}(_),{...F={format:"text",appName:(R=tX(_,"Process"),R?.replace(/\s+\[\d+\]$/,"")),bundleId:tX(_,"Identifier"),version:tX(_,"Version"),incident:tX(_,"Incident Identifier"),timestamp:tX(_,"Date/Time"),exceptionType:tX(_,"Exception Type"),exceptionCodes:tX(_,"Exception Codes"),terminationReason:tX(_,"Termination Reason"),crashedThread:O,topFrames:(k=P,x=O,E=D,void 0===x?[]:k.filter(e=>e.threadIndex===x).slice(0,5).map(e=>tQ(e.frameIndex,e.image,e.address,E))),findings:[]},findings:tZ(F)}),matchedImages:J,symbolicatedFrames:X,skippedImages:Q,warnings:Z,message:`Symbolicated ${X} frame${1===X?"":"s"} -> ${q}`}}async function t4(e,t){await t6(e,t);try{return await d.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 t6(e,t){try{let a=await d.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 t8(e,t){return r.resolve(e,t)}let t7={...G,...et,...ee,...er,...en,...H,...ea,...Z,...el,...Y,...J,batch:ei(function(e,t){let a=t7[e];if(!a)throw Error(`Missing daemon writer for batch command: ${e}`);return a(t)})};function t9(e={},t={}){let a=t.transport??tx,r=async(t,r=[],n={})=>{let i=at(e,n),o=await a({session:X(i.session),command:t,positionals:r,flags:Q(i),runtime:i.runtime,meta:W(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(T.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(O)},i=async(e,t={})=>{let a=t7[e](t);return await r(a.command,a.positionals,a.options)},o=(t={})=>X(at(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(es)},boot:async(e={})=>await i("boot",e),shutdown:async(e={})=>await i("shutdown",e)},sessions:{list:async(e={})=>await n(e),stateDir:async(t={})=>D(at(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=>K(await i("install",e),o(e)),reinstall:async e=>K(await i("reinstall",e),o(e)),installFromSource:async e=>eu(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=z(a),n=j(a,"appBundleId");return{session:t,sessionStateDir:j(a,"sessionStateDir"),appName:j(a,"appName"),appBundleId:n,appId:n,startup:ed(a.startup),runtime:eo(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=>q(await r(T.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>aa(await r(T.leaseAllocate,[],{...e,leaseId:void 0,leaseTtlMs:e.ttlMs})),heartbeat:async e=>aa(await r(T.leaseHeartbeat,[],{...e,leaseTtlMs:e.ttlMs})),release:async e=>({released:!0===(await r(T.leaseRelease,[],e)).released})},metro:{prepare:async t=>await ep({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 ef({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,l,c,d=o(e);return t=await i("snapshot",e),a=d,n=j(t,"appBundleId"),{nodes:V(t.nodes),truncated:!0===t.truncated,appName:j(t,"appName"),appBundleId:n,...(s=ae((r=t).visibility),l=ae(r.unchanged),c=I(r.snapshotDiagnostics),{...s?{visibility:s}:{},...B(r),...l?{unchanged:l}:{},...c?{snapshotDiagnostics:c}:{}}),identifiers:{session:a,appId:n,appBundleId:n}}},screenshot:async(e={})=>{let t=o(e),a=await i("screenshot",e);return{path:F(a,"path"),overlayRefs:ec(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 t5({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 ae(e){return"object"==typeof e&&null!==e?e:void 0}function at(e,t){return{...e,...t}}function aa(e){let t=e.lease;if(!t||"object"!=typeof t||Array.isArray(t))throw Error("Invalid lease response from daemon");return{leaseId:F(t,"leaseId"),tenantId:F(t,"tenantId"),runId:F(t,"runId"),backend:F(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{t9 as createAgentDeviceClient,tv as ensureDaemon,ez as formatDurationSeconds,eY as replayTestFailureStepLines,tg as resolveClientSettings,tx as sendToDaemon};
@@ -1,4 +1,4 @@
1
- import{listCliCommandNames as e}from"./2133.js";import{getCliCommandSchema as t,getCommandSchema as a}from"./9581.js";import{getFlagDefinitions as o,GLOBAL_FLAG_KEYS as s}from"./9873.js";let n=[{label:"help workflow",description:"Normal bootstrap, exploration, and validation loop"},{label:"help debugging",description:"Logs, network, perf memory, and traces"},{label:"help react-native",description:"React Native app automation hazards, overlays, Metro, and routing"},{label:"help react-devtools",description:"React Native performance, profiling, component tree, and renders"},{label:"help physical-device",description:"Connected phone/tablet setup and iOS signing prerequisites"},{label:"help remote",description:"Remote/cloud config, tenants, leases, and local service tunnels"},{label:"help web",description:"Minimal browser sessions through agent-browser"},{label:"help macos",description:"Desktop, frontmost-app, and menu bar surfaces"},{label:"help dogfood",description:"Exploratory QA report workflow"}],r=["Planning output contract: when asked to plan commands, output command lines only: no prose, numbering, Markdown fences, pipes, or shell helpers.","Default loop: devices/apps -> open -> snapshot -i -> press/fill/get/is/wait/find -> verify -> close.",'Use selectors or refs as positional targets: id="submit", label="Allow", or @e12 from snapshot -i.',"Plain snapshot reads state; snapshot -i refreshes current interactive refs only.","Default snapshot text is an agent-facing, token-efficient view for planning and targeting actions.","Read-only visible/state question: use snapshot/get/is/find; use snapshot -i only when refs are needed.","Anti-pattern: snapshot -i followed by snapshot -i | grep ...; prior refs stay valid until app state changes, and --force-full is the explicit full re-read.","Truncated text/input preview: expand first with snapshot -s @e12, not get text.","React Native apps: read help react-native for Metro, DevTools routing, and RN-specific blockers; use react-native dismiss-overlay for LogBox/RedBox overlays.","Android RN/Expo Metro: direct Android localhost URL opens with a port auto-configure host reachability.",'Expo Go/dev clients: use the provided URL when given; on iOS use open "Expo Go" <url> --platform ios, then snapshot -i --platform ios to verify project UI. Do not use plain snapshot or snapshot --diff for this recovery check. Android URL opens infer the foreground package for logs/perf when possible.',"Install flows: install/install-from-source first, then open the installed id with --relaunch.",'Text: fill \'id="field-email"\' "qa@example.com" replaces; type appends after press.','Clearing text: do not use fill <target> ""; use a visible clear/reset control or report that clearing is unsupported.',"Android IME capture: if fill says input was captured by the keyboard/IME, inspect keyboard state and switch/disable handwriting before retrying; do not loop fill/type.","Implicit default sessions are scoped to the current worktree; if a prompt names a Session, include --session <name> on every command in that flow.","Run mutating commands serially within one session; parallelize only read-only commands or separate sessions/devices.","Clipboard limits: iOS Allow Paste cannot be automated through XCUITest; prefill with clipboard write. Android non-ASCII should use fill/type, not raw adb input.","After mutation: refs are stale. If the next target is known, use its selector directly; otherwise refresh with snapshot -i, scoped with -s when a stable container is known. Do not use tap; use press or click.","Raw coordinates are fallback-only: use snapshot -i --json rects when iOS refs no-op or child refs are missing, then verify the action with diff snapshot -i or snapshot --diff.","Sparse or AX-unavailable snapshot: use screenshot for visual truth, press the visible coordinate to leave the bad screen, then retry AX with snapshot -i.","macOS context menus use click <ref> --button secondary, then snapshot -i. Longpress is for mobile hold gestures, not macOS secondary-click menus.","Remote workflow profiles use --remote-config on operational commands. Do not substitute --config; --config only loads CLI defaults.",'Batch JSON steps use "command" and structured "input"; legacy "positionals"/"flags" steps still run in CLI but are deprecated until the next major version.',"Navigation: app-owned back uses back; system back uses back --system.","Web browser sessions: read help web; first slice is web setup if needed -> web doctor -> open <url> --platform web -> snapshot -i -> click/fill/get/is/find/wait/screenshot -> close.","Verification commands must name the expected text/selector; bare screenshots/snapshots are not enough.","Debug evidence: Session state contains request diagnostics and runner.log; use logs clear --restart/mark/path, trace, and network dump --include headers for app evidence.","Use agent-device commands in final plans; raw platform tools, pseudo commands, and helper prose are wrong.","Full operating guide: agent-device help workflow. Exploratory QA: agent-device help dogfood."],i=["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."],c=[{label:"AGENT_DEVICE_SESSION",description:"Explicit session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"},{label:"AGENT_DEVICE_DAEMON_AUTH_TOKEN",description:"Remote daemon service/API token"},{label:"AGENT_DEVICE_CLOUD_BASE_URL",description:"Bridge/control-plane API origin for cloud auth and /api-keys"}],l=["agent-device open Settings --platform ios","agent-device open https://example.com --platform web","agent-device open TextEdit --platform macos","agent-device snapshot -i","agent-device react-devtools get tree --depth 3",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"],d={workflow:{summary:"Normal agent-device bootstrap, exploration, and validation loop",body:`agent-device help workflow
1
+ import{listCliCommandNames as e}from"./2133.js";import{getCliCommandSchema as t,getCommandSchema as o}from"./9581.js";import{getFlagDefinitions as a,GLOBAL_FLAG_KEYS as s}from"./9873.js";let n=[{label:"help workflow",description:"Normal bootstrap, exploration, and validation loop"},{label:"help debugging",description:"Logs, network, perf memory, and traces"},{label:"help react-native",description:"React Native app automation hazards, overlays, Metro, and routing"},{label:"help react-devtools",description:"React Native performance, profiling, component tree, and renders"},{label:"help physical-device",description:"Connected phone/tablet setup and iOS signing prerequisites"},{label:"help remote",description:"Remote/cloud config, tenants, leases, and local service tunnels"},{label:"help web",description:"Minimal browser sessions through agent-browser"},{label:"help macos",description:"Desktop, frontmost-app, and menu bar surfaces"},{label:"help dogfood",description:"Exploratory QA report workflow"}],r=["Planning output contract: when asked to plan commands, output command lines only: no prose, numbering, Markdown fences, pipes, or shell helpers.","Default loop: devices/apps -> open -> snapshot -i -> press/fill/get/is/wait/find -> verify -> close.",'Use selectors or refs as positional targets: id="submit", label="Allow", or @e12 from snapshot -i.',"Plain snapshot reads state; snapshot -i refreshes current interactive refs only.","Default snapshot text is an agent-facing, token-efficient view for planning and targeting actions.","Read-only visible/state question: use snapshot/get/is/find; use snapshot -i only when refs are needed.","Anti-pattern: snapshot -i followed by snapshot -i | grep ...; prior refs stay valid until app state changes, and --force-full is the explicit full re-read.","Truncated text/input preview: expand first with snapshot -s @e12, not get text.","React Native apps: read help react-native for Metro, DevTools routing, and RN-specific blockers; use react-native dismiss-overlay for LogBox/RedBox overlays.","Android RN/Expo Metro: direct Android localhost URL opens with a port auto-configure host reachability.",'Expo Go/dev clients: use the provided URL when given; on iOS use open "Expo Go" <url> --platform ios, then snapshot -i --platform ios to verify project UI. Do not use plain snapshot or snapshot --diff for this recovery check. Android URL opens infer the foreground package for logs/perf when possible.',"Install flows: install/install-from-source first, then open the installed id with --relaunch.",'Text: fill \'id="field-email"\' "qa@example.com" replaces; type appends after press.','Clearing text: do not use fill <target> ""; use a visible clear/reset control or report that clearing is unsupported.',"Android IME capture: if fill says input was captured by the keyboard/IME, inspect keyboard state and switch/disable handwriting before retrying; do not loop fill/type.","Implicit default sessions are scoped to the current worktree; if a prompt names a Session, include --session <name> on every command in that flow.","Run mutating commands serially within one session; parallelize only read-only commands or separate sessions/devices.","Clipboard limits: iOS Allow Paste cannot be automated through XCUITest; prefill with clipboard write. Android non-ASCII should use fill/type, not raw adb input.","After mutation: refs are stale. If the next target is known, use its selector directly; otherwise refresh with snapshot -i, scoped with -s when a stable container is known. Do not use tap; use press or click.","Raw coordinates are fallback-only: use snapshot -i --json rects when iOS refs no-op or child refs are missing, then verify the action with diff snapshot -i or snapshot --diff.","Sparse or AX-unavailable snapshot: use screenshot for visual truth, press the visible coordinate to leave the bad screen, then retry AX with snapshot -i.","macOS context menus use click <ref> --button secondary, then snapshot -i. Longpress is for mobile hold gestures, not macOS secondary-click menus.","Remote workflow profiles use --remote-config on operational commands. Do not substitute --config; --config only loads CLI defaults.",'Batch JSON steps use "command" and structured "input"; legacy "positionals"/"flags" steps still run in CLI but are deprecated until the next major version.',"Navigation: app-owned back uses back; system back uses back --system.","Web browser sessions: read help web; first slice is web setup if needed -> web doctor -> open <url> --platform web -> snapshot -i -> click/fill/get/is/find/wait/screenshot -> close.","Verification commands must name the expected text/selector; bare screenshots/snapshots are not enough.","Debug evidence: Session state contains request diagnostics and runner.log; use logs clear --restart/mark/path, trace, and network dump --include headers for app evidence.","Use agent-device commands in final plans; raw platform tools, pseudo commands, and helper prose are wrong.","Full operating guide: agent-device help workflow. Exploratory QA: agent-device help dogfood."],i=["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."],c=[{label:"AGENT_DEVICE_SESSION",description:"Explicit session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"},{label:"AGENT_DEVICE_DAEMON_AUTH_TOKEN",description:"Remote daemon service/API token"},{label:"AGENT_DEVICE_CLOUD_BASE_URL",description:"Bridge/control-plane API origin for cloud auth and /api-keys"}],l=["agent-device open Settings --platform ios","agent-device open https://example.com --platform web","agent-device open TextEdit --platform macos","agent-device snapshot -i","agent-device react-devtools get tree --depth 3",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"],d={workflow:{summary:"Normal agent-device bootstrap, exploration, and validation loop",body:`agent-device help workflow
2
2
 
3
3
  Version-matched operating guide for normal agent-device work.
4
4
 
@@ -454,10 +454,21 @@ Script flow, per-command config:
454
454
  agent-device snapshot --remote-config ./remote-config.json
455
455
  agent-device disconnect --remote-config ./remote-config.json
456
456
 
457
+ Direct proxy flow for a remote Mac:
458
+ On the Mac with simulator/device access:
459
+ agent-device proxy --port 4310
460
+ cloudflared tunnel --url http://127.0.0.1:4310
461
+ On the remote client:
462
+ agent-device devices --daemon-base-url https://example.trycloudflare.com/agent-device --daemon-auth-token <token>
463
+ agent-device devices
464
+
457
465
  Rules:
458
466
  connect and disconnect are top-level commands. Do not write agent-device remote connect or agent-device remote disconnect.
459
467
  Use connect without --remote-config when the cloud control plane owns the connection profile.
460
468
  Prefer --remote-config over --daemon-base-url, --tenant, --run-id, and --lease-id when using a local profile.
469
+ Use agent-device proxy for direct tunnel access to a Mac you control. Copy the printed daemon base URL and daemon auth token; do not use agent-device auth for this direct proxy flow.
470
+ For repeated direct proxy commands, store daemonBaseUrl and daemonAuthToken in normal agent-device.json CLI config. Keep platform selection on each command or workflow. Do not use --remote-config unless you are using the tenant/run/lease remote connection flow.
471
+ Keep the proxy token secret. Anyone with the token can control the proxied daemon.
461
472
  Do not use --config as a remote profile flag. --config loads CLI defaults; --remote-config selects remote daemon/profile settings.
462
473
  For self-contained scripts, pass the same --remote-config to every operational command, including disconnect; a preceding connect is optional but not required.
463
474
  For remote artifact installs, use install-from-source <url> or install-from-source --github-actions-artifact org/repo:artifact; do not download CI artifacts locally first.
@@ -587,11 +598,11 @@ Rules:
587
598
  Prefer refs for exploration and selectors for deterministic replay.
588
599
  Use logs, network, screenshot --overlay-refs, trace, perf metrics, perf frames, or react-devtools only when they add evidence to a specific issue.
589
600
  Never delete screenshots, videos, traces, or report artifacts during a session.
590
- Escalate to help debugging or help react-devtools when runtime symptoms require those tools.`}};function p(e){let t=e.endsWith("?"),a=t?e.slice(0,-1):e;return t?`[${a}]`:`<${a}>`}function u(){let a,o,d,p,u,v,b,w;return a=`agent-device <command> [args] [--json]
601
+ Escalate to help debugging or help react-devtools when runtime symptoms require those tools.`}};function p(e){let t=e.endsWith("?"),o=t?e.slice(0,-1):e;return t?`[${o}]`:`<${o}>`}function u(){let o,a,d,p,u,v,b,w;return o=`agent-device <command> [args] [--json]
591
602
 
592
603
  CLI to control iOS and Android devices for AI agents.
593
- `,o=m("Commands:",e().map(e=>{let a=t(e);return{name:e,schema:a,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let a=(t.positionalArgs??[]).map(a=>{var o,s,n;let r,i,c,l;return o=e,s=t,i=(r=(n=a).endsWith("?"))?n.slice(0,-1):n,l=(c=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==s.usageOverride&&s.usageOverride.startsWith(`${o} ${i}`),r?c?`[${i}]`:l?i:`[${i}]`:l?i:`<${i}>`});return[e,...a].join(" ")}(e,a)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),d=f("Global Flags:",h(s)),p=g("Agent Quickstart:",r),u=m("Agent Workflows:",n),v=g("Configuration:",i),b=m("Environment:",c),w=g("Examples:",l),`${a}
594
- ${o}
604
+ `,a=m("Commands:",e().map(e=>{let o=t(e);return{name:e,schema:o,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let o=(t.positionalArgs??[]).map(o=>{var a,s,n;let r,i,c,l;return a=e,s=t,i=(r=(n=o).endsWith("?"))?n.slice(0,-1):n,l=(c=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==s.usageOverride&&s.usageOverride.startsWith(`${a} ${i}`),r?c?`[${i}]`:l?i:`[${i}]`:l?i:`<${i}>`});return[e,...o].join(" ")}(e,o)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),d=f("Global Flags:",h(s)),p=g("Agent Quickstart:",r),u=m("Agent Workflows:",n),v=g("Configuration:",i),b=m("Environment:",c),w=g("Examples:",l),`${o}
605
+ ${a}
595
606
 
596
607
  ${d}
597
608
 
@@ -604,15 +615,15 @@ ${v}
604
615
  ${b}
605
616
 
606
617
  ${w}
607
- `}function h(e){return o().filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function f(e,t){return m(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function m(e,t){if(0===t.length)return`${e}
608
- (none)`;let a=Math.max(...t.map(e=>e.label.length))+2,o=[e];for(let e of t)o.push(` ${e.label.padEnd(a)}${e.description}`);return o.join("\n")}function g(e,t){return 0===t.length?`${e}
618
+ `}function h(e){return a().filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function f(e,t){return m(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function m(e,t){if(0===t.length)return`${e}
619
+ (none)`;let o=Math.max(...t.map(e=>e.label.length))+2,a=[e];for(let e of t)a.push(` ${e.label.padEnd(o)}${e.description}`);return a.join("\n")}function g(e,t){return 0===t.length?`${e}
609
620
  (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}function v(e){var t,s;let n,r=(n=d[e])?`${n.body}
610
621
 
611
622
  Related:
612
623
  agent-device help command list and global flags
613
624
  agent-device help <command> command-specific flags
614
625
  agent-device help workflow normal app automation loop
615
- `:null;if(r)return r;let i=a(e);if(!i)return null;let c=(t=e,(s=i).usageOverride?s.usageOverride:[t,...(s.positionalArgs??[]).map(p),...(s.allowedFlags??[]).flatMap(e=>{var t;return(t=e,o().filter(e=>e.key===t)).map(e=>e.usageLabel??e.names[0])}).map(e=>`[${e}]`)].join(" ")),l=h(new Set(i.allowedFlags??[])),u=[];l.length>0&&u.push(f("Command flags:",l));let m=u.length>0?`
626
+ `:null;if(r)return r;let i=o(e);if(!i)return null;let c=(t=e,(s=i).usageOverride?s.usageOverride:[t,...(s.positionalArgs??[]).map(p),...(s.allowedFlags??[]).flatMap(e=>{var t;return(t=e,a().filter(e=>e.key===t)).map(e=>e.usageLabel??e.names[0])}).map(e=>`[${e}]`)].join(" ")),l=h(new Set(i.allowedFlags??[])),u=[];l.length>0&&u.push(f("Command flags:",l));let m=u.length>0?`
616
627
 
617
628
  ${u.join("\n\n")}`:"";return`agent-device ${c}
618
629