agent-device 0.11.14 → 0.11.16

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.
package/dist/src/index.js CHANGED
@@ -1,2 +1,3 @@
1
- import e from"node:net";import t from"node:http";import r from"node:https";import o from"node:fs";import n from"node:path";import{fileURLToPath as a}from"node:url";import{spawn as i}from"node:child_process";import s,{createHash as l}from"node:crypto";import{resolveUserPath as d,createRequestId as c,emitDiagnostic as u,withDiagnosticTimer as p,expandUserHomePath as m,AppError as f}from"./957.js";import{stopProcessForTakeover as h,prepareMetroRuntime as I,runCmdSync as v,isAgentDeviceDaemonProcess as y,runCmdDetached as w}from"./974.js";function g(){let e=n.dirname(a(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=n.join(t,"package.json");if(o.existsSync(e))return t;t=n.dirname(t)}return e}function A(e){let t,r=(t=(e??"").trim())?d(t):n.join(m("~"),".agent-device");return{baseDir:r,infoPath:n.join(r,"daemon.json"),lockPath:n.join(r,"daemon.lock"),logPath:n.join(r,"daemon.log"),sessionsDir:n.join(r,"sessions")}}let b="sha256";async function D(e){let{localPath:a,baseUrl:s,token:l}=e,d=o.statSync(a),c=d.isDirectory(),u=n.basename(a),p=c?"app-bundle":"file",m=s.endsWith("/")?s:`${s}/`,h=c?void 0:await E(a);if(h){let e=await P({normalizedBase:m,token:l,hash:h,filename:u,sizeBytes:d.size,artifactType:p});if(e)return e}let I=new URL("upload",m),v="https:"===I.protocol?r:t,y={"x-artifact-type":p,"x-artifact-filename":u,"transfer-encoding":"chunked"};return h&&(y["x-artifact-hash"]=h,y["x-artifact-hash-algorithm"]=b),l&&(y.authorization=`Bearer ${l}`,y["x-agent-device-token"]=l),new Promise((e,t)=>{let r=v.request({protocol:I.protocol,host:I.hostname,port:I.port,method:"POST",path:I.pathname+I.search,headers:y},r=>{let o="";r.setEncoding("utf8"),r.on("data",e=>{o+=e}),r.on("end",()=>{clearTimeout(s);try{let r=JSON.parse(o);if(!r.ok||!r.uploadId)return void t(new f("COMMAND_FAILED",`Upload failed: ${o}`));e(r.uploadId)}catch{t(new f("COMMAND_FAILED",`Invalid upload response: ${o}`))}})}),s=setTimeout(()=>{r.destroy(),t(new f("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(r.on("error",e=>{clearTimeout(s),t(new f("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),c){let e=i("tar",["cf","-","-C",n.dirname(a),n.basename(a)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(r),e.on("error",e=>{r.destroy(),t(new f("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(r.destroy(),t(new f("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=o.createReadStream(a);e.pipe(r),e.on("error",e=>{r.destroy(),t(new f("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}async function P(e){var t;let r=new URL("upload/preflight",e.normalizedBase),o={"content-type":"application/json"};e.token&&(o.authorization=`Bearer ${e.token}`,o["x-agent-device-token"]=e.token);let n=await fetch(r,{method:"POST",headers:o,signal:AbortSignal.timeout(3e4),body:JSON.stringify({hash:e.hash,hashAlgorithm:b,fileName:e.filename,sizeBytes:e.sizeBytes,artifactType:e.artifactType})}).catch(()=>void 0);if(!n?.ok)return;let a=await n.json().catch(()=>void 0);return(t=a)&&"object"==typeof t&&!0===t.ok&&!0===t.cacheHit&&"string"==typeof t.uploadId?a.uploadId:void 0}async function E(e){let t=l(b);return await new Promise((r,n)=>{o.createReadStream(e).on("data",e=>t.update(e)).on("error",e=>{n(new f("COMMAND_FAILED","Failed to read local artifact",{},e))}).on("end",r)}),t.digest("hex")}let _=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,S=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,T=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function k(e,t,r){t.lastIndex=0;let o=null;for(;null!==(o=t.exec(e));){let e=o[1]?.trim();e?.startsWith(".")&&r.add(e)}}function M(e){try{return o.statSync(e).isFile()?e:null}catch{return null}}let N=eu(),U=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),R=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),C=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],O=new e.BlockList;async function x(t){let r=t.meta?.requestId??c(),o=!!(t.meta?.debug||t.flags?.verbose),n=function(t){let r,o,n,a=t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,i=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(/\/+$/,"")}}(t.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),s=t.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var l=i,d=s;if(!(!l||"localhost"===(r=new URL(l).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(e.isIPv4(r)?O.check(r,"ipv4"):!!e.isIPv6(r)&&O.check(r,"ipv6")))&&("string"!=typeof d||!(d.trim().length>0)))throw new f("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:l,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let c=t.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,u="auto"===(o=(c??"").trim().toLowerCase())?"auto":"socket"===o?"socket":"http"===o?"http":"auto";if(i&&"socket"===u)throw new f("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:i});let p="http"===(n=(t.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===c?"dual":void 0)??"").trim().toLowerCase())?"http":"dual"===n?"dual":"socket";return{paths:A(a),transportPreference:u,serverMode:p,remoteBaseUrl:i,remoteAuthToken:s}}(t),a=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return eu(t)}(t.command),i=await p("daemon_startup",async()=>await q(n),{requestId:r,session:t.session}),s=await L(t,i),l={...t,positionals:s.positionals,flags:s.flags,token:i.token,meta:{...t.meta??{},requestId:r,debug:o,cwd:t.meta?.cwd,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,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};return u({level:"info",phase:"daemon_request_prepare",data:{requestId:r,command:t.command,session:t.session}}),await p("daemon_request",async()=>await ee(i,l,n.transportPreference,a),{requestId:r,command:t.command})}async function L(e,t){let r,a=[...e.positionals??[]],i=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(es(t)){let o=function(e,t){if("screenshot"===e.command){let r=$(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:j("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:j("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=$(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:j("recording",n.extname(t)||".mp4")}}return null}(e,a);o&&(void 0!==o.positionalPath&&(a[o.positionalIndex]=o.positionalPath),void 0!==o.flagPath&&((i??={}).out=o.flagPath),l[o.field]=o.localPath);let d=await F(e,t);d&&(s=d.installSource,r=d.uploadedArtifactId??r)}if(!es(t)||"install"!==e.command&&"reinstall"!==e.command||a.length<2)return{positionals:a,flags:i,installSource:s,uploadedArtifactId:r,...Object.keys(l).length>0?{clientArtifactPaths:l}:{}};let d=a[1];if(d.startsWith("remote:"))return a[1]=d.slice(7),{positionals:a,flags:i,...Object.keys(l).length>0?{clientArtifactPaths:l}:{}};let c=n.isAbsolute(d)?d:n.resolve(e.meta?.cwd??process.cwd(),d);return o.existsSync(c)?{positionals:a,flags:i,installSource:s,uploadedArtifactId:r=await D({localPath:c,baseUrl:t.baseUrl,token:t.token}),...Object.keys(l).length>0?{clientArtifactPaths:l}:{}}:{positionals:a,flags:i,...Object.keys(l).length>0?{clientArtifactPaths:l}:{}}}async function F(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let a=r.path.trim();if(!a)return{installSource:r};if(a.startsWith("remote:"))return{installSource:{...r,path:a.slice(7)}};let i=n.isAbsolute(a)?a:n.resolve(e.meta?.cwd??process.cwd(),a);if(!o.existsSync(i))return{installSource:{...r,path:i}};let s=await D({localPath:i,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:i},uploadedArtifactId:s}}function $(e,t,r,o=0){let a=e.positionals?.[o]??e.flags?.out,i=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,s=a&&a.trim().length>0?a:i;return n.isAbsolute(s)?s:n.resolve(e.meta?.cwd??process.cwd(),s)}function j(e,t){let r=t.startsWith(".")?t:`.${t}`;return n.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function q(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await X(t,"http"))return t;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."})}let r=H(e.paths.infoPath),a=function(){try{let e=g();return JSON.parse(o.readFileSync(n.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}(),i=function(e,t=g()){try{let r=n.resolve(t),a=[n.resolve(e)],i=new Set,l=[];for(;a.length>0;){let e=a.pop();if(!e||i.has(e))continue;i.add(e);let t=o.statSync(e);if(!t.isFile())continue;let s=n.relative(r,e)||e;l.push(`${s}:${t.size}:${Math.trunc(t.mtimeMs)}`);let d=o.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return k(e,_,t),k(e,S,t),[...t]}(d)){let r=function(e,t){let r=n.resolve(n.dirname(e),t),o=M(r);if(o)return o;for(let e of T){let t=M(`${r}${e}`);if(t)return t}for(let e of T){let t=M(n.join(r,`index${e}`));if(t)return t}return null}(e,t);r&&a.push(r)}}let d=l.sort().join("|"),c=s.createHash("sha1").update(d).digest("hex");return`graph:${l.length}:${c}`}catch{return"unknown"}}((t=Z()).useSrc?t.srcPath:t.distPath,t.root),l=!!r&&await X(r,e.transportPreference);if(r&&r.version===a&&r.codeSignature===i&&l)return r;r&&(r.version!==a||r.codeSignature!==i||!l)&&(await V(r),Q(e.paths.infoPath)),function(e){let t=J(e);if(!t.hasLock||t.hasInfo)return;let r=K(e.lockPath);if(!r)return Q(e.lockPath);y(r.pid,r.processStartTime)||Q(e.lockPath)}(e.paths);let d=0;for(let t=1;t<=R;t+=1){await Y(e);let r=await B(U,e);if(r)return r;if(await G(e.paths)){d+=1;continue}let o=J(e.paths);if(!(t<R))break;if(!o.hasInfo&&!o.hasLock){await z(150);continue}}let c=J(e.paths);throw new f("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:U,startupAttempts:R,lockRecoveryCount:d,metadataState:c,hint:function(e,t=A(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(c,e.paths)})}async function B(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=H(t.paths.infoPath);if(e&&await X(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function z(e){await new Promise(t=>setTimeout(t,e))}async function G(e){let t=J(e);if(!t.hasLock||t.hasInfo)return!1;let r=K(e.lockPath);return r&&y(r.pid,r.processStartTime)&&await h(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),Q(e.lockPath),!0}async function V(e){await h(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function H(e){let t=W(e);if(!t||"object"!=typeof t)return null;let r="string"==typeof t.token&&t.token.length>0?t.token:null;if(!r)return null;let o=Number.isInteger(t.port)&&Number(t.port)>0,n=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!o&&!n)return null;let a=t.transport,i="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,d=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:o?Number(t.port):void 0,httpPort:n?Number(t.httpPort):void 0,transport:"socket"===a||"http"===a||"dual"===a?a:void 0,pid:d?Number(t.pid):0,version:i,codeSignature:s,processStartTime:l}}function K(e){let t=W(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}O.addSubnet("127.0.0.0",8,"ipv4"),O.addAddress("::1","ipv6"),O.addSubnet("::ffff:127.0.0.0",104,"ipv6");function J(e){return{hasInfo:o.existsSync(e.infoPath),hasLock:o.existsSync(e.lockPath)}}function W(e){if(!o.existsSync(e))return null;try{return JSON.parse(o.readFileSync(e,"utf8"))}catch{return null}}function Q(e){try{o.existsSync(e)&&o.unlinkSync(e)}catch{}}async function X(o,n){var a;return"http"===et(o,n)?await function(e){let o=e.baseUrl?el(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!o)return Promise.resolve(!1);let n=new URL(o),a="https:"===n.protocol?r:t,i=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:"GET",timeout:i},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(o):await ((a=o.port)?new Promise(t=>{let r=e.createConnection({host:"127.0.0.1",port:a},()=>{r.destroy(),t(!0)});r.on("error",()=>{t(!1)})}):Promise.resolve(!1))}async function Y(e){let t=Z(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],o={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};w(process.execPath,r,{env:o})}function Z(){let e=g(),t=n.join(e,"dist","src","daemon.js"),r=n.join(e,"src","daemon.ts"),a=o.existsSync(t),i=o.existsSync(r);if(!a&&!i)throw new f("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!a&&i}}async function ee(e,t,r,o){return"http"===et(e,r)?await ei(e,t,o):await ea(e,t,o)}function et(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 r=e,o=t;if(er(r,o))return o;throw new f("COMMAND_FAILED","http"===o?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>er(e,t));if(n)return n;throw new f("COMMAND_FAILED","Daemon metadata has no reachable transport")}function er(e,t){return"http"===t?!!e.httpPort:!!e.port}function eo(e,t,r,o,n,a){let i=n?{terminated:0}:function(){let e=0;try{for(let t of C){let r=v("pkill",["-f",t],{allowFailure:!0});0===r.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),s=n?{forcedKill:!1}:function(e,t){let r=!1;try{y(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{h(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{Q(t.infoPath),Q(t.lockPath)}return{forcedKill:r}}(e,t);return u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:a,requestId:r,command:o,timedOutRunnerPidsTerminated:i.terminated,timedOutRunnerCleanupError:i.error,daemonPidReset:n?void 0:e.pid,daemonPidForceKilled:n?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),new f("COMMAND_FAILED","Daemon request timed out",{timeoutMs:a,requestId:r,hint:n?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."})}function en(e,t,r){return u({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",{requestId:t,hint:r?"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 ea(t,r,o){let n=t.port;if(!n)throw new f("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,i)=>{let s=e.createConnection({host:"127.0.0.1",port:n},()=>{s.write(`${JSON.stringify(r)}
2
- `)}),l=A(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),d="number"==typeof o?setTimeout(()=>{s.destroy(),i(eo(t,l,r.meta?.requestId,r.command,!1,o))},o):void 0,c="";s.setEncoding("utf8"),s.on("data",e=>{let t=(c+=e).indexOf("\n");if(-1===t)return;let o=c.slice(0,t).trim();if(o)try{let e=JSON.parse(o);s.end(),d&&clearTimeout(d),a(e)}catch(e){d&&clearTimeout(d),i(new f("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:o},e instanceof Error?e:void 0))}}),s.on("error",e=>{d&&clearTimeout(d),i(en(e,r.meta?.requestId,!1))})})}async function ei(e,o,n){let a=e.baseUrl?new URL(el(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!a)throw new f("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let i=JSON.stringify({jsonrpc:"2.0",id:o.meta?.requestId??c(),method:"agent_device.command",params:o}),s={"content-type":"application/json","content-length":Buffer.byteLength(i)};return e.baseUrl&&e.token&&(s.authorization=`Bearer ${e.token}`,s["x-agent-device-token"]=e.token),await new Promise((l,d)=>{let c=A(o.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),u=("https:"===a.protocol?r:t).request({protocol:a.protocol,host:a.hostname,port:a.port,method:"POST",path:a.pathname+a.search,headers:s},t=>{let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{m&&clearTimeout(m);try{let t=JSON.parse(r);if(t.error){let e=t.error.data??{};d(new f(String(e.code??"COMMAND_FAILED"),String(e.message??t.error.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:o.meta?.requestId}));return}if(!t.result||"object"!=typeof t.result)return void d(new f("COMMAND_FAILED","Invalid daemon RPC response",{requestId:o.meta?.requestId}));if(e.baseUrl&&t.result.ok)return void ed(e,o,t.result).then(l).catch(d);l(t.result)}catch(e){m&&clearTimeout(m),d(new f("COMMAND_FAILED","Invalid daemon response",{requestId:o.meta?.requestId,line:r},e instanceof Error?e:void 0))}})}),p=es(e),m="number"==typeof n?setTimeout(()=>{u.destroy(),d(eo(e,c,o.meta?.requestId,o.command,p,n))},n):void 0;u.on("error",e=>{m&&clearTimeout(m),d(en(e,o.meta?.requestId,p))}),u.write(i),u.end()})}function es(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function el(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function ed(e,t,r){let o=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===o.length||!e.baseUrl)return r;let a=r.data?{...r.data}:{},i=[];for(let r of o){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){i.push(r);continue}let o=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return n.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await ec({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:o,requestId:t.meta?.requestId}),a[r.field]=o,i.push({...r,localPath:o})}return a.artifacts=i,{ok:!0,data:a}}async function ec(e){var a,i;let s,l=new URL((a=e.baseUrl,i=e.artifactId,s=a.endsWith("/")?a:`${a}/`,new URL(`upload/${encodeURIComponent(i)}`,s).toString())),d="https:"===l.protocol?r:t;await o.promises.mkdir(n.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let n=!1,a=e.timeoutMs??N,i=a=>{if(!n){if(n=!0,clearTimeout(c),a)return void o.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(a));t()}},s=d.request({protocol:l.protocol,host:l.hostname,port:l.port,method:"GET",path:l.pathname+l.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{i(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=o.createWriteStream(e.destinationPath);r.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new f("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),c=setTimeout(()=>{s.destroy(new f("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:a}))},a);s.on("error",t=>{t instanceof f?i(t):i(new f("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:a},t instanceof Error?t:void 0))}),s.end()})}function eu(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}function ep(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function em(e,t,r){return{deviceId:t,deviceName:r,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function ef(e,t,r,o){let n=r(e[t]);if(void 0===n)throw new f("COMMAND_FAILED",o,{response:e});return n}function eh(e,t){return ef(e,t,eA,`Daemon response is missing "${t}".`)}function eI(e,t){return eA(e[t])}function ev(e,t){var r;let o;return r=eA,null===(o=e[t])?null:r(o)}function ey(e,t){return ef(e,t,eD,`Daemon response has invalid "${t}".`)}function ew(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function eg(e,t){let r=e[t];if(!e_(r))return;let o="number"==typeof r.x?r.x:void 0,n="number"==typeof r.y?r.y:void 0,a="number"==typeof r.width?r.width:void 0,i="number"==typeof r.height?r.height:void 0;if(void 0!==o&&void 0!==n&&void 0!==a&&void 0!==i)return{x:o,y:n,width:a,height:i}}function eA(e){return"string"==typeof e&&e.length>0?e:void 0}function eb(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eD(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function eP(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function eE(e){if(!e_(e))throw new f("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function e_(e){return"object"==typeof e&&null!==e}function eS(e){let t={};for(let[r,o]of Object.entries(e))void 0!==o&&(t[r]=o);return t}function eT(e,t){let r=eI(e,"bundleId"),o=eI(e,"package");return{app:eh(e,"app"),appPath:eh(e,"appPath"),platform:ey(e,"platform"),appId:r??o,bundleId:r,package:o,identifiers:ep({session:t,bundleId:r,packageName:o})}}function ek(e){let t=eE(e),r=ey(t,"platform"),o=eh(t,"id"),n=eh(t,"name");return{platform:r,target:ew(t,"target"),kind:ef(t,"kind",eP,'Daemon response has invalid "kind".'),id:o,name:n,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:em(r,o,n),ios:"ios"===r?{udid:o}:void 0,android:"android"===r?{serial:o}:void 0}}function eM(e){let t=eE(e),r=ey(t,"platform"),o=eh(t,"id"),n=eh(t,"name"),a=ew(t,"target"),i=eh(t,"device"),s={session:n,...em(r,o,i)};return{name:n,createdAt:ef(t,"createdAt",eb,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:a,id:o,name:i,identifiers:s,ios:"ios"===r?{udid:o,simulatorSetPath:ev(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:o}:void 0},identifiers:s}}function eN(e,t){return t??e??"default"}function eU(e={},t={}){let r=t.transport??x,o=async(t,o=[],n={})=>{let a={...e,...n},i=await r({session:eN(e.session,n.session),command:t,positionals:o,flags:eS({stateDir:a.stateDir,daemonBaseUrl:a.daemonBaseUrl,daemonAuthToken:a.daemonAuthToken,daemonTransport:a.daemonTransport,daemonServerMode:a.daemonServerMode,tenant:a.tenant,sessionIsolation:a.sessionIsolation,runId:a.runId,leaseId:a.leaseId,platform:a.platform,target:a.target,device:a.device,udid:a.udid,serial:a.serial,iosSimulatorDeviceSet:a.iosSimulatorDeviceSet,androidDeviceAllowlist:a.androidDeviceAllowlist,runtime:a.simulatorRuntimeId,boot:a.boot,reuseExisting:a.reuseExisting,surface:a.surface,activity:a.activity,relaunch:a.relaunch,shutdown:a.shutdown,saveScript:a.saveScript,noRecord:a.noRecord,metroHost:a.metroHost,metroPort:a.metroPort,bundleUrl:a.bundleUrl,launchUrl:a.launchUrl,snapshotInteractiveOnly:a.interactiveOnly,snapshotCompact:a.compact,snapshotDepth:a.depth,snapshotScope:a.scope,snapshotRaw:a.raw,overlayRefs:a.overlayRefs,appsFilter:a.appsFilter,verbose:a.debug}),runtime:a.runtime,meta:eS({requestId:a.requestId,cwd:a.cwd,debug:a.debug,lockPolicy:a.lockPolicy,lockPlatform:a.lockPlatform,tenantId:a.tenant,runId:a.runId,leaseId:a.leaseId,sessionIsolation:a.sessionIsolation,installSource:a.installSource,retainMaterializedPaths:a.retainMaterializedPaths,materializedPathRetentionMs:a.materializedPathRetentionMs,materializationId:a.materializationId})});return i.ok||function(e){throw new f(e.code,e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(i.error),i.data??{}},n=async(e={})=>{let t=await o("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(eM)};return{devices:{list:async(e={})=>{let t=await o("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ek)}},sessions:{list:async(e={})=>await n(e),close:async(t={})=>{let r=eN(e.session,t.session),n=(await o("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await o("ensure-simulator",[],{...r,simulatorRuntimeId:t}),a=eh(n,"udid"),i=eh(n,"device");return{udid:a,device:i,runtime:eh(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:ev(n,"ios_simulator_device_set"),identifiers:{deviceId:a,deviceName:i,udid:a}}}},apps:{install:async t=>eT(await o("install",[t.app,t.appPath],t),eN(e.session,t.session)),reinstall:async t=>eT(await o("reinstall",[t.app,t.appPath],t),eN(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=eI(e,"bundleId"),o=eI(e,"packageName"),n=r??o??eI(e,"appId"),a=eI(e,"launchTarget")??o??r??n;if(!a)throw new f("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:eI(e,"appName"),appId:n,bundleId:r,packageName:o,launchTarget:a,installablePath:eI(e,"installablePath"),archivePath:eI(e,"archivePath"),materializationId:eI(e,"materializationId"),materializationExpiresAt:eI(e,"materializationExpiresAt"),identifiers:ep({session:t,bundleId:r,packageName:o,appId:n})}})(await o("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),eN(e.session,t.session)),list:async(e={})=>{let t=await o("apps",[],e);return Array.isArray(t.apps)?t.apps.filter(e=>"string"==typeof e):[]},open:async t=>{let r=eN(e.session,t.session),n=t.url?[t.app,t.url]:[t.app],a=await o("open",n,t),i=function(e){let t=e.platform,r=eI(e,"id"),o=eI(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!o)return;let n=ew(e,"target"),a=em(t,r,o);return{platform:t,target:n,id:r,name:o,identifiers:a,ios:"ios"===t?{udid:eI(e,"device_udid")??r,simulatorSetPath:ev(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:eI(e,"serial")??r}:void 0}}(a),s=eI(a,"appBundleId");return{session:r,appName:eI(a,"appName"),appBundleId:s,appId:s,startup:function(e){if(e_(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:eI(e,"appTarget"),appBundleId:eI(e,"appBundleId")}}(a.startup),runtime:function(e){if(!e_(e))return;let t=e.platform,r=eI(e,"metroHost"),o="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:o,bundleUrl:eI(e,"bundleUrl"),launchUrl:eI(e,"launchUrl")}}(a.runtime),device:i,identifiers:{session:r,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:s,appBundleId:s}}},close:async(t={})=>{let r=eN(e.session,t.session),n=(await o("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await o("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:eh(t,"materializationId"),identifiers:{}}}},metro:{prepare:async t=>await I({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,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})},capture:{snapshot:async(t={})=>{var r;let n=eN(e.session,t.session),a=await o("snapshot",[],t),i=eI(a,"appBundleId"),s="object"==typeof a.visibility&&null!==a.visibility?a.visibility:void 0;return{nodes:Array.isArray(r=a.nodes)?r:[],truncated:!0===a.truncated,appName:eI(a,"appName"),appBundleId:i,...s?{visibility:s}:{},warnings:Array.isArray(a.warnings)?a.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:n,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let r=eN(e.session,t.session),n=await o("screenshot",t.path?[t.path]:[],t);return{path:eh(n,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!e_(e))continue;let t=eI(e,"ref"),o=eg(e,"rect"),n=eg(e,"overlayRect"),a=function(e,t){let r=e[t];if(!e_(r))return;let o="number"==typeof r.x?r.x:void 0,n="number"==typeof r.y?r.y:void 0;if(void 0!==o&&void 0!==n)return{x:o,y:n}}(e,"center");t&&o&&n&&a&&r.push({ref:t,label:eI(e,"label"),rect:o,overlayRect:n,center:a})}return r}(n),identifiers:{session:r}}}}}}export{AppError}from"./957.js";export{eU as createAgentDeviceClient};
1
+ import e from"node:net";import t from"node:http";import a from"node:https";import r from"node:fs";import o from"node:path";import{fileURLToPath as n}from"node:url";import{AsyncLocalStorage as i}from"node:async_hooks";import s,{createHash as l}from"node:crypto";import"node:os";import{spawn as d}from"node:child_process";import{redactDiagnosticData as c,AppError as u}from"./152.js";import{resolveUserPath as p,expandUserHomePath as m}from"./267.js";import{runCmdDetached as f,runCmdSync as h}from"./818.js";import{prepareMetroRuntime as y,isAgentDeviceDaemonProcess as w,stopProcessForTakeover as v}from"./974.js";import{tryParseSelectorChain as g}from"./940.js";import{REMOTE_CONFIG_FIELD_SPECS as I,resolveRemoteConfigProfile as A,REMOTE_OPEN_PROFILE_KEYS as b}from"./924.js";function S(){let e=o.dirname(n(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=o.join(t,"package.json");if(r.existsSync(e))return t;t=o.dirname(t)}return e}let _=new i;function M(){return s.randomBytes(8).toString("hex")}function P(e){let t=_.getStore();if(!t)return;let a={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?c(e.data):void 0};if(t.events.push(a),!t.debug)return;let o=`[agent-device][diag] ${JSON.stringify(a)}
2
+ `;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function D(e,t,a){let r=Date.now();try{let o=await t();return P({level:"info",phase:e,durationMs:Date.now()-r,data:a}),o}catch(t){throw P({level:"error",phase:e,durationMs:Date.now()-r,data:{...a??{},error:t instanceof Error?t.message:String(t)}}),t}}function E(e){let t,a=(t=(e??"").trim())?p(t):o.join(m("~"),".agent-device");return{baseDir:a,infoPath:o.join(a,"daemon.json"),lockPath:o.join(a,"daemon.lock"),logPath:o.join(a,"daemon.log"),sessionsDir:o.join(a,"sessions")}}let k="sha256";async function T(e){let{localPath:n,baseUrl:i,token:s}=e,l=r.statSync(n),c=l.isDirectory(),p=o.basename(n),m=c?"app-bundle":"file",f=i.endsWith("/")?i:`${i}/`,h=c?void 0:await x(n);if(h){let e=await N({normalizedBase:f,token:s,hash:h,filename:p,sizeBytes:l.size,artifactType:m});if(e)return e}let y=new URL("upload",f),w="https:"===y.protocol?a:t,v={"x-artifact-type":m,"x-artifact-filename":p,"transfer-encoding":"chunked"};return h&&(v["x-artifact-hash"]=h,v["x-artifact-hash-algorithm"]=k),s&&(v.authorization=`Bearer ${s}`,v["x-agent-device-token"]=s),new Promise((e,t)=>{let a=w.request({protocol:y.protocol,host:y.hostname,port:y.port,method:"POST",path:y.pathname+y.search,headers:v},a=>{let r="";a.setEncoding("utf8"),a.on("data",e=>{r+=e}),a.on("end",()=>{clearTimeout(i);try{let a=JSON.parse(r);if(!a.ok||!a.uploadId)return void t(new u("COMMAND_FAILED",`Upload failed: ${r}`));e(a.uploadId)}catch{t(new u("COMMAND_FAILED",`Invalid upload response: ${r}`))}})}),i=setTimeout(()=>{a.destroy(),t(new u("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(a.on("error",e=>{clearTimeout(i),t(new u("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),c){let e=d("tar",["cf","-","-C",o.dirname(n),o.basename(n)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(a),e.on("error",e=>{a.destroy(),t(new u("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(a.destroy(),t(new u("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=r.createReadStream(n);e.pipe(a),e.on("error",e=>{a.destroy(),t(new u("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}async function N(e){var t;let a=new URL("upload/preflight",e.normalizedBase),r={"content-type":"application/json"};e.token&&(r.authorization=`Bearer ${e.token}`,r["x-agent-device-token"]=e.token);let o=await fetch(a,{method:"POST",headers:r,signal:AbortSignal.timeout(3e4),body:JSON.stringify({hash:e.hash,hashAlgorithm:k,fileName:e.filename,sizeBytes:e.sizeBytes,artifactType:e.artifactType})}).catch(()=>void 0);if(!o?.ok)return;let n=await o.json().catch(()=>void 0);return(t=n)&&"object"==typeof t&&!0===t.ok&&!0===t.cacheHit&&"string"==typeof t.uploadId?n.uploadId:void 0}async function x(e){let t=l(k);return await new Promise((a,o)=>{r.createReadStream(e).on("data",e=>t.update(e)).on("error",e=>{o(new u("COMMAND_FAILED","Failed to read local artifact",{},e))}).on("end",a)}),t.digest("hex")}let C=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,U=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,R=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function O(e,t,a){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&a.add(e)}}function L(e){try{return r.statSync(e).isFile()?e:null}catch{return null}}let F=ev(),$=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),j=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),q=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],B=new e.BlockList;async function z(t){let a=t.meta?.requestId??M(),r=!!(t.meta?.debug||t.flags?.verbose),o=function(t){let a,r,o,n=t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,i=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new u("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new u("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(t.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),s=t.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var l=i,d=s;if(!(!l||"localhost"===(a=new URL(l).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(e.isIPv4(a)?B.check(a,"ipv4"):!!e.isIPv6(a)&&B.check(a,"ipv6")))&&("string"!=typeof d||!(d.trim().length>0)))throw new u("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:l,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let c=t.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,p="auto"===(r=(c??"").trim().toLowerCase())?"auto":"socket"===r?"socket":"http"===r?"http":"auto";if(i&&"socket"===p)throw new u("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:i});let m="http"===(o=(t.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===c?"dual":void 0)??"").trim().toLowerCase())?"http":"dual"===o?"dual":"socket";return{paths:E(n),transportPreference:p,serverMode:m,remoteBaseUrl:i,remoteAuthToken:s}}(t),n=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return ev(t)}(t.command),i=await D("daemon_startup",async()=>await J(o),{requestId:a,session:t.session}),s=await V(t,i),l={...t,positionals:s.positionals,flags:s.flags,token:i.token,meta:{...t.meta??{},requestId:a,debug:r,cwd:t.meta?.cwd,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,...s.uploadedArtifactId?{uploadedArtifactId:s.uploadedArtifactId}:{},...s.clientArtifactPaths?{clientArtifactPaths:s.clientArtifactPaths}:{},...s.installSource?{installSource:s.installSource}:{}}};return P({level:"info",phase:"daemon_request_prepare",data:{requestId:a,command:t.command,session:t.session}}),await D("daemon_request",async()=>await es(i,l,o.transportPreference,n),{requestId:a,command:t.command})}async function V(e,t){let a,n=[...e.positionals??[]],i=e.flags?{...e.flags}:void 0,s=e.meta?.installSource,l={};if(ef(t)){let r=function(e,t){if("screenshot"===e.command){let a=K(e,"path",".png");return t[0]?{field:"path",localPath:a,positionalIndex:0,positionalPath:H("screenshot",".png")}:{field:"path",localPath:a,positionalIndex:0,flagPath:H("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=K(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:H("recording",o.extname(t)||".mp4")}}return null}(e,n);r&&(void 0!==r.positionalPath&&(n[r.positionalIndex]=r.positionalPath),void 0!==r.flagPath&&((i??={}).out=r.flagPath),l[r.field]=r.localPath);let d=await G(e,t);d&&(s=d.installSource,a=d.uploadedArtifactId??a)}if(!ef(t)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:i,installSource:s,uploadedArtifactId:a,...Object.keys(l).length>0?{clientArtifactPaths:l}:{}};let d=n[1];if(d.startsWith("remote:"))return n[1]=d.slice(7),{positionals:n,flags:i,...Object.keys(l).length>0?{clientArtifactPaths:l}:{}};let c=o.isAbsolute(d)?d:o.resolve(e.meta?.cwd??process.cwd(),d);return r.existsSync(c)?{positionals:n,flags:i,installSource:s,uploadedArtifactId:a=await T({localPath:c,baseUrl:t.baseUrl,token:t.token}),...Object.keys(l).length>0?{clientArtifactPaths:l}:{}}:{positionals:n,flags:i,...Object.keys(l).length>0?{clientArtifactPaths:l}:{}}}async function G(e,t){let a=e.meta?.installSource;if("install_source"!==e.command||!a||"path"!==a.kind)return null;let n=a.path.trim();if(!n)return{installSource:a};if(n.startsWith("remote:"))return{installSource:{...a,path:n.slice(7)}};let i=o.isAbsolute(n)?n:o.resolve(e.meta?.cwd??process.cwd(),n);if(!r.existsSync(i))return{installSource:{...a,path:i}};let s=await T({localPath:i,baseUrl:t.baseUrl,token:t.token});return{installSource:{...a,path:i},uploadedArtifactId:s}}function K(e,t,a,r=0){let n=e.positionals?.[r]??e.flags?.out,i=`${"path"===t?"screenshot":"recording"}-${Date.now()}${a}`,s=n&&n.trim().length>0?n:i;return o.isAbsolute(s)?s:o.resolve(e.meta?.cwd??process.cwd(),s)}function H(e,t){let a=t.startsWith(".")?t:`.${t}`;return o.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function J(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await eo(t,"http"))return t;throw new u("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."})}let a=Z(e.paths.infoPath),n=function(){try{let e=S();return JSON.parse(r.readFileSync(o.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}(),i=function(e,t=S()){try{let a=o.resolve(t),n=[o.resolve(e)],i=new Set,l=[];for(;n.length>0;){let e=n.pop();if(!e||i.has(e))continue;i.add(e);let t=r.statSync(e);if(!t.isFile())continue;let s=o.relative(a,e)||e;l.push(`${s}:${t.size}:${Math.trunc(t.mtimeMs)}`);let d=r.readFileSync(e,"utf8");for(let t of function(e){let t=new Set;return O(e,C,t),O(e,U,t),[...t]}(d)){let a=function(e,t){let a=o.resolve(o.dirname(e),t),r=L(a);if(r)return r;for(let e of R){let t=L(`${a}${e}`);if(t)return t}for(let e of R){let t=L(o.join(a,`index${e}`));if(t)return t}return null}(e,t);a&&n.push(a)}}let d=l.sort().join("|"),c=s.createHash("sha1").update(d).digest("hex");return`graph:${l.length}:${c}`}catch{return"unknown"}}((t=ei()).useSrc?t.srcPath:t.distPath,t.root),l=!!a&&await eo(a,e.transportPreference);if(a&&a.version===n&&a.codeSignature===i&&l)return a;a&&(a.version!==n||a.codeSignature!==i||!l)&&(await Y(a),er(e.paths.infoPath)),function(e){let t=et(e);if(!t.hasLock||t.hasInfo)return;let a=ee(e.lockPath);if(!a)return er(e.lockPath);w(a.pid,a.processStartTime)||er(e.lockPath)}(e.paths);let d=0;for(let t=1;t<=j;t+=1){await en(e);let a=await W($,e);if(a)return a;if(await X(e.paths)){d+=1;continue}let r=et(e.paths);if(!(t<j))break;if(!r.hasInfo&&!r.hasLock){await Q(150);continue}}let c=et(e.paths);throw new u("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:$,startupAttempts:j,lockRecoveryCount:d,metadataState:c,hint:function(e,t=E(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(c,e.paths)})}async function W(e,t){let a=Date.now();for(;Date.now()-a<e;){let e=Z(t.paths.infoPath);if(e&&await eo(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function Q(e){await new Promise(t=>setTimeout(t,e))}async function X(e){let t=et(e);if(!t.hasLock||t.hasInfo)return!1;let a=ee(e.lockPath);return a&&w(a.pid,a.processStartTime)&&await v(a.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:a.processStartTime}),er(e.lockPath),!0}async function Y(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function Z(e){let t=ea(e);if(!t||"object"!=typeof t)return null;let a="string"==typeof t.token&&t.token.length>0?t.token:null;if(!a)return null;let r=Number.isInteger(t.port)&&Number(t.port)>0,o=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!r&&!o)return null;let n=t.transport,i="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,d=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:a,port:r?Number(t.port):void 0,httpPort:o?Number(t.httpPort):void 0,transport:"socket"===n||"http"===n||"dual"===n?n:void 0,pid:d?Number(t.pid):0,version:i,codeSignature:s,processStartTime:l}}function ee(e){let t=ea(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}B.addSubnet("127.0.0.0",8,"ipv4"),B.addAddress("::1","ipv6"),B.addSubnet("::ffff:127.0.0.0",104,"ipv6");function et(e){return{hasInfo:r.existsSync(e.infoPath),hasLock:r.existsSync(e.lockPath)}}function ea(e){if(!r.existsSync(e))return null;try{return JSON.parse(r.readFileSync(e,"utf8"))}catch{return null}}function er(e){try{r.existsSync(e)&&r.unlinkSync(e)}catch{}}async function eo(r,o){var n;return"http"===el(r,o)?await function(e){let r=e.baseUrl?eh(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!r)return Promise.resolve(!1);let o=new URL(r),n="https:"===o.protocol?a:t,i=e.baseUrl?3e3:500;return new Promise(e=>{let t=n.request({protocol:o.protocol,host:o.hostname,port:o.port,path:o.pathname+o.search,method:"GET",timeout:i},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(r):await ((n=r.port)?new Promise(t=>{let a=e.createConnection({host:"127.0.0.1",port:n},()=>{a.destroy(),t(!0)});a.on("error",()=>{t(!1)})}):Promise.resolve(!1))}async function en(e){let t=ei(),a=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],r={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};f(process.execPath,a,{env:r})}function ei(){let e=S(),t=o.join(e,"dist","src","daemon.js"),a=o.join(e,"src","daemon.ts"),n=r.existsSync(t),i=r.existsSync(a);if(!n&&!i)throw new u("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:a});return{root:e,distPath:t,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!n&&i}}async function es(e,t,a,r){return"http"===el(e,a)?await em(e,t,r):await ep(e,t,r)}function el(e,t){if(e.baseUrl){if("socket"===t)throw new u("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(ed(a,r))return r;throw new u("COMMAND_FAILED","http"===r?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let o=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>ed(e,t));if(o)return o;throw new u("COMMAND_FAILED","Daemon metadata has no reachable transport")}function ed(e,t){return"http"===t?!!e.httpPort:!!e.port}function ec(e,t,a,r,o,n){let i=o?{terminated:0}:function(){let e=0;try{for(let t of q){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=o?{forcedKill:!1}:function(e,t){let a=!1;try{w(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{er(t.infoPath),er(t.lockPath)}return{forcedKill:a}}(e,t);return P({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:n,requestId:a,command:r,timedOutRunnerPidsTerminated:i.terminated,timedOutRunnerCleanupError:i.error,daemonPidReset:o?void 0:e.pid,daemonPidForceKilled:o?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),new u("COMMAND_FAILED","Daemon request timed out",{timeoutMs:n,requestId:a,hint:o?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."})}function eu(e,t,a){return P({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new u("COMMAND_FAILED","Failed to communicate with daemon",{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 ep(t,a,r){let o=t.port;if(!o)throw new u("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((n,i)=>{let s=e.createConnection({host:"127.0.0.1",port:o},()=>{s.write(`${JSON.stringify(a)}
3
+ `)}),l=E(a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),d="number"==typeof r?setTimeout(()=>{s.destroy(),i(ec(t,l,a.meta?.requestId,a.command,!1,r))},r):void 0,c="";s.setEncoding("utf8"),s.on("data",e=>{let t=(c+=e).indexOf("\n");if(-1===t)return;let r=c.slice(0,t).trim();if(r)try{let e=JSON.parse(r);s.end(),d&&clearTimeout(d),n(e)}catch(e){d&&clearTimeout(d),i(new u("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:r},e instanceof Error?e:void 0))}}),s.on("error",e=>{d&&clearTimeout(d),i(eu(e,a.meta?.requestId,!1))})})}async function em(e,r,o){let n=e.baseUrl?new URL(eh(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!n)throw new u("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let i=JSON.stringify({jsonrpc:"2.0",id:r.meta?.requestId??M(),method:"agent_device.command",params:r}),s={"content-type":"application/json","content-length":Buffer.byteLength(i)};return e.baseUrl&&e.token&&(s.authorization=`Bearer ${e.token}`,s["x-agent-device-token"]=e.token),await new Promise((l,d)=>{let c=E(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),p=("https:"===n.protocol?a:t).request({protocol:n.protocol,host:n.hostname,port:n.port,method:"POST",path:n.pathname+n.search,headers:s},t=>{let a="";t.setEncoding("utf8"),t.on("data",e=>{a+=e}),t.on("end",()=>{f&&clearTimeout(f);try{let t=JSON.parse(a);if(t.error){let e=t.error.data??{};d(new u(String(e.code??"COMMAND_FAILED"),String(e.message??t.error.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:r.meta?.requestId}));return}if(!t.result||"object"!=typeof t.result)return void d(new u("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));if(e.baseUrl&&t.result.ok)return void ey(e,r,t.result).then(l).catch(d);l(t.result)}catch(e){f&&clearTimeout(f),d(new u("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:a},e instanceof Error?e:void 0))}})}),m=ef(e),f="number"==typeof o?setTimeout(()=>{p.destroy(),d(ec(e,c,r.meta?.requestId,r.command,m,o))},o):void 0;p.on("error",e=>{f&&clearTimeout(f),d(eu(e,r.meta?.requestId,m))}),p.write(i),p.end()})}function ef(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function eh(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function ey(e,t,a){let r=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===r.length||!e.baseUrl)return a;let n=a.data?{...a.data}:{},i=[];for(let a of r){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){i.push(a);continue}let r=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=e.fileName?.trim()||`${e.field}-${Date.now()}`;return o.resolve(t.meta?.cwd??process.cwd(),a)}(a,t);await ew({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:r,requestId:t.meta?.requestId}),n[a.field]=r,i.push({...a,localPath:r})}return n.artifacts=i,{ok:!0,data:n}}async function ew(e){var n,i;let s,l=new URL((n=e.baseUrl,i=e.artifactId,s=n.endsWith("/")?n:`${n}/`,new URL(`upload/${encodeURIComponent(i)}`,s).toString())),d="https:"===l.protocol?a:t;await r.promises.mkdir(o.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let o=!1,n=e.timeoutMs??F,i=n=>{if(!o){if(o=!0,clearTimeout(c),n)return void r.promises.rm(e.destinationPath,{force:!0}).finally(()=>a(n));t()}},s=d.request({protocol:l.protocol,host:l.hostname,port:l.port,method:"GET",path:l.pathname+l.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let a="";t.setEncoding("utf8"),t.on("data",e=>{a+=e}),t.on("end",()=>{i(new u("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:a}))});return}let a=r.createWriteStream(e.destinationPath);a.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new u("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),a.on("finish",()=>{a.close(()=>i())}),t.pipe(a)}),c=setTimeout(()=>{s.destroy(new u("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);s.on("error",t=>{t instanceof u?i(t):i(new u("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),s.end()})}function ev(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}let eg="clipboard",eI="wait",eA=I.map(e=>e.key);function eb(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function eS(e,t,a){return{deviceId:t,deviceName:a,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function e_(e,t,a,r){let o=a(e[t]);if(void 0===o)throw new u("COMMAND_FAILED",r,{response:e});return o}[...b];function eM(e,t){return e_(e,t,eN,`Daemon response is missing "${t}".`)}function eP(e,t){return eN(e[t])}function eD(e,t){var a;let r;return a=eN,null===(r=e[t])?null:a(r)}function eE(e,t){return e_(e,t,eC,`Daemon response has invalid "${t}".`)}function ek(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function eT(e,t){let a=e[t];if(!eO(a))return;let r="number"==typeof a.x?a.x:void 0,o="number"==typeof a.y?a.y:void 0,n="number"==typeof a.width?a.width:void 0,i="number"==typeof a.height?a.height:void 0;if(void 0!==r&&void 0!==o&&void 0!==n&&void 0!==i)return{x:r,y:o,width:n,height:i}}function eN(e){return"string"==typeof e&&e.length>0?e:void 0}function ex(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eC(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function eU(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function eR(e){if(!eO(e))throw new u("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function eO(e){return"object"==typeof e&&null!==e}function eL(e){let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}function eF(e,t){let a=eP(e,"bundleId"),r=eP(e,"package");return{app:eM(e,"app"),appPath:eM(e,"appPath"),platform:eE(e,"platform"),appId:a??r,bundleId:a,package:r,identifiers:eb({session:t,bundleId:a,packageName:r})}}function e$(e){let t=eR(e),a=eE(t,"platform"),r=eM(t,"id"),o=eM(t,"name");return{platform:a,target:ek(t,"target"),kind:e_(t,"kind",eU,'Daemon response has invalid "kind".'),id:r,name:o,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:eS(a,r,o),ios:"ios"===a?{udid:r}:void 0,android:"android"===a?{serial:r}:void 0}}function ej(e){let t=eR(e),a=eE(t,"platform"),r=eM(t,"id"),o=eM(t,"name"),n=ek(t,"target"),i=eM(t,"device"),s={session:o,...eS(a,r,i)};return{name:o,createdAt:e_(t,"createdAt",ex,'Daemon response is missing numeric "createdAt".'),device:{platform:a,target:n,id:r,name:i,identifiers:s,ios:"ios"===a?{udid:r,simulatorSetPath:eD(t,"ios_simulator_device_set")}:void 0,android:"android"===a?{serial:r}:void 0},identifiers:s}}function eq(e){return e??"default"}function eB(e={},t={}){var a;let r,o=t.transport??z,n=eH(e),i=async(t,a=[],r={})=>{let i=eK(e,n,r),s=await o({session:eq(i.session),command:t,positionals:a,flags:eL({stateDir:i.stateDir,daemonBaseUrl:i.daemonBaseUrl,daemonAuthToken:i.daemonAuthToken,daemonTransport:i.daemonTransport,daemonServerMode:i.daemonServerMode,tenant:i.tenant,sessionIsolation:i.sessionIsolation,runId:i.runId,leaseId:i.leaseId,platform:i.platform,target:i.target,device:i.device,udid:i.udid,serial:i.serial,iosSimulatorDeviceSet:i.iosSimulatorDeviceSet,androidDeviceAllowlist:i.androidDeviceAllowlist,runtime:i.simulatorRuntimeId,boot:i.boot,reuseExisting:i.reuseExisting,surface:i.surface,activity:i.activity,relaunch:i.relaunch,shutdown:i.shutdown,saveScript:i.saveScript,noRecord:i.noRecord,backMode:i.backMode,metroHost:i.metroHost,metroPort:i.metroPort,bundleUrl:i.bundleUrl,launchUrl:i.launchUrl,snapshotInteractiveOnly:i.interactiveOnly,snapshotCompact:i.compact,snapshotDepth:i.depth,snapshotScope:i.scope,snapshotRaw:i.raw,screenshotFullscreen:i.screenshotFullscreen,overlayRefs:i.overlayRefs,appsFilter:i.appsFilter,out:i.out,count:i.count,fps:i.fps,hideTouches:i.hideTouches,intervalMs:i.intervalMs,delayMs:i.delayMs,holdMs:i.holdMs,jitterPx:i.jitterPx,pixels:i.pixels,doubleTap:i.doubleTap,clickButton:i.clickButton,pauseMs:i.pauseMs,pattern:i.pattern,maxScrolls:i.maxScrolls,headless:i.headless,restart:i.restart,replayUpdate:i.replayUpdate,failFast:i.failFast,timeoutMs:i.timeoutMs,retries:i.retries,artifactsDir:i.artifactsDir,reportJunit:i.reportJunit,findFirst:i.findFirst,findLast:i.findLast,networkInclude:i.networkInclude,batchOnError:i.batchOnError,batchMaxSteps:i.batchMaxSteps,batchSteps:i.batchSteps,verbose:i.debug}),runtime:i.runtime,meta:eL({requestId:i.requestId,cwd:i.cwd,debug:i.debug,lockPolicy:i.lockPolicy,lockPlatform:i.lockPlatform,tenantId:i.tenant,runId:i.runId,leaseId:i.leaseId,sessionIsolation:i.sessionIsolation,installSource:i.installSource,retainMaterializedPaths:i.retainMaterializedPaths,materializedPathRetentionMs:i.materializedPathRetentionMs,materializationId:i.materializationId})});return s.ok||function(e){throw new u(e.code,e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath})}(s.error),s.data??{}},s=async(e={})=>{let t=await i("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(ej)},l=async(e,t=[],a={})=>await i(e,t,a),d=(t={})=>eq(eK(e,n,t).session);return{command:(a=async e=>await i(e.command,e.positionals,e.options),r=async e=>await a(e),{wait:async e=>await r(function(e){if(1!==[void 0!==e.durationMs?"durationMs":void 0,void 0!==e.text?"text":void 0,void 0!==e.ref?"ref":void 0,void 0!==e.selector?"selector":void 0].filter(Boolean).length)throw new u("INVALID_ARGS","wait command requires exactly one of durationMs, text, ref, or selector.");if(void 0!==e.durationMs)return{command:eI,positionals:[String(e.durationMs)],options:e};let t=void 0!==e.timeoutMs?[String(e.timeoutMs)]:[];if(void 0!==e.text)return{command:eI,positionals:["text",e.text,...t],options:e};if(void 0!==e.ref)return{command:eI,positionals:[e.ref,...t],options:e};let a=e.selector;return function(e){if(!g(e))throw new u("INVALID_ARGS",`Invalid wait selector: ${e}`)}(a),{command:eI,positionals:[a,...t],options:e}}(e)),alert:async(e={})=>{var t;return await r({command:"alert",positionals:[(t=e).action??"get",...void 0!==t.timeoutMs?[String(t.timeoutMs)]:[]],options:t})},appState:async(e={})=>await r({command:"appstate",positionals:[],options:e}),back:async(e={})=>await r({command:"back",positionals:[],options:{...e,backMode:e.mode}}),home:async(e={})=>await r({command:"home",positionals:[],options:e}),rotate:async e=>await r({command:"rotate",positionals:[e.orientation],options:e}),appSwitcher:async(e={})=>await r({command:"app-switcher",positionals:[],options:e}),keyboard:async(e={})=>await r({command:"keyboard",positionals:e.action?[e.action]:[],options:e}),clipboard:async e=>{var t;return await r("read"===(t=e).action?{command:eg,positionals:["read"],options:t}:{command:eg,positionals:["write",t.text],options:t})}}),devices:{list:async(e={})=>{let t=await i("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(e$)},boot:async(e={})=>await l("boot",[],e)},sessions:{list:async(e={})=>await s(e),close:async(e={})=>{let t=d(e),a=(await i("close",[],e)).shutdown;return{session:t,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}}},simulators:{ensure:async e=>{let{runtime:t,...a}=e,r=await i("ensure-simulator",[],{...a,simulatorRuntimeId:t}),o=eM(r,"udid"),n=eM(r,"device");return{udid:o,device:n,runtime:eM(r,"runtime"),created:!0===r.created,booted:!0===r.booted,iosSimulatorDeviceSet:eD(r,"ios_simulator_device_set"),identifiers:{deviceId:o,deviceName:n,udid:o}}}},apps:{install:async e=>eF(await i("install",[e.app,e.appPath],e),d(e)),reinstall:async e=>eF(await i("reinstall",[e.app,e.appPath],e),d(e)),installFromSource:async e=>(function(e,t){let a=eP(e,"bundleId"),r=eP(e,"packageName"),o=a??r??eP(e,"appId"),n=eP(e,"launchTarget")??r??a??o;if(!n)throw new u("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:eP(e,"appName"),appId:o,bundleId:a,packageName:r,launchTarget:n,installablePath:eP(e,"installablePath"),archivePath:eP(e,"archivePath"),materializationId:eP(e,"materializationId"),materializationExpiresAt:eP(e,"materializationExpiresAt"),identifiers:eb({session:t,bundleId:a,packageName:r,appId:o})}})(await i("install_source",[],{...e,installSource:e.source,retainMaterializedPaths:e.retainPaths,materializedPathRetentionMs:e.retentionMs}),d(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=d(e),a=e.app?e.url?[e.app,e.url]:[e.app]:[],r=await i("open",a,e),o=function(e){let t=e.platform,a=eP(e,"id"),r=eP(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!a||!r)return;let o=ek(e,"target"),n=eS(t,a,r);return{platform:t,target:o,id:a,name:r,identifiers:n,ios:"ios"===t?{udid:eP(e,"device_udid")??a,simulatorSetPath:eD(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:eP(e,"serial")??a}:void 0}}(r),n=eP(r,"appBundleId");return{session:t,appName:eP(r,"appName"),appBundleId:n,appId:n,startup:function(e){if(eO(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:eP(e,"appTarget"),appBundleId:eP(e,"appBundleId")}}(r.startup),runtime:function(e){if(!eO(e))return;let t=e.platform,a=eP(e,"metroHost"),r="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:a,metroPort:r,bundleUrl:eP(e,"bundleUrl"),launchUrl:eP(e,"launchUrl")}}(r.runtime),device:o,identifiers:{session:t,deviceId:o?.id,deviceName:o?.name,udid:o?.ios?.udid,serial:o?.android?.serial,appId:n,appBundleId:n}}},close:async(e={})=>{let t=d(e),a=(await i("close",e.app?[e.app]:[],e)).shutdown;return{session:t,closedApp:e.app,shutdown:"object"==typeof a&&null!==a?a:void 0,identifiers:{session:t}}},push:async e=>{var t;return await l("push",[e.app,"string"==typeof(t=e.payload)?t:JSON.stringify(t)],e)},triggerEvent:async e=>{var t;return await l("trigger-app-event",[(t=e).event,...t.payload?[JSON.stringify(t.payload)]:[]],e)}},materializations:{release:async e=>{var t;return{released:!0===(t=await i("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:eM(t,"materializationId"),identifiers:{}}}},metro:{prepare:async t=>await y({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,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})},capture:{snapshot:async(e={})=>{var t;let a=d(e),r=await i("snapshot",[],e),o=eP(r,"appBundleId"),n="object"==typeof r.visibility&&null!==r.visibility?r.visibility:void 0;return{nodes:Array.isArray(t=r.nodes)?t:[],truncated:!0===r.truncated,appName:eP(r,"appName"),appBundleId:o,...n?{visibility:n}:{},warnings:Array.isArray(r.warnings)?r.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:a,appId:o,appBundleId:o}}},screenshot:async(e={})=>{let t=d(e),a=await i("screenshot",e.path?[e.path]:[],{...e,screenshotFullscreen:e.fullscreen});return{path:eM(a,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let a=[];for(let e of t){if(!eO(e))continue;let t=eP(e,"ref"),r=eT(e,"rect"),o=eT(e,"overlayRect"),n=function(e,t){let a=e[t];if(!eO(a))return;let r="number"==typeof a.x?a.x:void 0,o="number"==typeof a.y?a.y:void 0;if(void 0!==r&&void 0!==o)return{x:r,y:o}}(e,"center");t&&r&&o&&n&&a.push({ref:t,label:eP(e,"label"),rect:r,overlayRect:o,center:n})}return a}(a),identifiers:{session:t}}},diff:async e=>await l("diff",[e.kind],{...e,interactiveOnly:e.interactiveOnly,compact:e.compact,depth:e.depth,scope:e.scope,raw:e.raw})},interactions:{click:async e=>await l("click",ez(e),{...e,clickButton:e.button}),press:async e=>await l("press",ez(e),e),longPress:async e=>await l("longpress",[String(e.x),String(e.y),...eG(e.durationMs)],e),swipe:async e=>await l("swipe",[String(e.from.x),String(e.from.y),String(e.to.x),String(e.to.y),...eG(e.durationMs)],e),focus:async e=>await l("focus",[String(e.x),String(e.y)],e),type:async e=>await l("type",[e.text],e),fill:async e=>await l("fill",[...ez(e),e.text],e),scroll:async e=>await l("scroll",[e.direction,...eG(e.amount)],e),scrollIntoView:async e=>{var t;return await l("scrollintoview",void 0!==(t=e).ref?[t.ref,...eV(t.label)]:[t.text??""],e)},pinch:async e=>await l("pinch",[String(e.scale),...eG(e.x),...eG(e.y)],e),get:async e=>{var t;return await l("get",[e.format,...void 0!==(t=e).ref?[t.ref,...eV(t.label)]:[t.selector]],e)},is:async e=>await l("is",[e.predicate,e.selector,..."text"===e.predicate?[e.value]:[]],e),find:async e=>await l("find",function(e){let t=e.locator&&"any"!==e.locator?[e.locator,e.query]:[e.query];switch(e.action){case void 0:case"click":case"focus":case"exists":return e.action?[...t,e.action]:t;case"getText":return[...t,"get","text"];case"getAttrs":return[...t,"get","attrs"];case"wait":return[...t,"wait",...eG(e.timeoutMs)];case"fill":case"type":return[...t,e.action,e.value]}}(e),{...e,findFirst:e.first,findLast:e.last})},replay:{run:async e=>await l("replay",[e.path],{...e,replayUpdate:e.update}),test:async e=>await l("test",e.paths,{...e,replayUpdate:e.update})},batch:{run:async e=>await l("batch",[],{...e,batchSteps:e.steps,batchOnError:e.onError,batchMaxSteps:e.maxSteps})},observability:{perf:async(e={})=>await l("perf",[],e),logs:async(e={})=>{var t;return await l("logs",[(t=e).action??"path",...eV(t.message)],e)},network:async(e={})=>{var t;return await l("network",[...(t=e).action?[t.action]:[],...eG(t.limit)],{...e,networkInclude:e.include})}},recording:{record:async e=>await l("record",[e.action,...eV(e.path)],e),trace:async e=>await l("trace",[e.action,...eV(e.path)],e)},settings:{update:async e=>await l("settings",[e.setting,e.state,..."permission"in e?[e.permission]:[],..."mode"in e&&e.mode?[e.mode]:[]],e)}}}function ez(e){return void 0!==e.ref?[e.ref,...eV(e.label)]:void 0!==e.selector?[e.selector]:[String(e.x),String(e.y)]}function eV(e){return void 0===e?[]:[e]}function eG(e){return void 0===e?[]:[String(e)]}function eK(e,t,a){return a.remoteConfig&&a.remoteConfig!==e.remoteConfig?{...eH({...e,...a}),...e,...a}:{...t,...e,...a}}function eH(e){var t;if(!e.remoteConfig)return{};let{runtime:a,...r}=(t={remoteConfig:e.remoteConfig,cwd:e.cwd??process.cwd(),env:process.env}).remoteConfig?{...function(e){let t={};for(let a of eA){let r=e[a];void 0!==r&&(t[a]=r)}return t}(A({configPath:t.remoteConfig,cwd:t.cwd,env:t.env}).profile),remoteConfig:t.remoteConfig}:{};return r}export{AppError}from"./152.js";export{centerOfRect}from"./57.js";export{eB as createAgentDeviceClient};
@@ -0,0 +1,40 @@
1
+ export declare const ARCHIVE_EXTENSIONS: readonly [".zip", ".tar", ".tar.gz", ".tgz"];
2
+
3
+ export declare function isBlockedIpAddress(address: string): boolean;
4
+
5
+ export declare function isBlockedSourceHostname(hostname: string): boolean;
6
+
7
+ export declare function isTrustedInstallSourceUrl(sourceUrl: string | URL): boolean;
8
+
9
+ export declare type MaterializedInstallable = {
10
+ archivePath?: string;
11
+ installablePath: string;
12
+ cleanup: () => Promise<void>;
13
+ };
14
+
15
+ declare type MaterializeInstallableOptions = {
16
+ source: MaterializeInstallSource;
17
+ isInstallablePath: (candidatePath: string, stat: {
18
+ isFile(): boolean;
19
+ isDirectory(): boolean;
20
+ }) => boolean;
21
+ installableLabel: string;
22
+ allowArchiveExtraction?: boolean;
23
+ signal?: AbortSignal;
24
+ downloadTimeoutMs?: number;
25
+ };
26
+
27
+ export declare function materializeInstallablePath(options: MaterializeInstallableOptions): Promise<MaterializedInstallable>;
28
+
29
+ export declare type MaterializeInstallSource = {
30
+ kind: 'url';
31
+ url: string;
32
+ headers?: Record<string, string>;
33
+ } | {
34
+ kind: 'path';
35
+ path: string;
36
+ };
37
+
38
+ export declare function validateDownloadSourceUrl(parsedUrl: URL): Promise<void>;
39
+
40
+ export { }
@@ -0,0 +1 @@
1
+ import t from"node:dns/promises";import e from"node:net";import{promises as a}from"node:fs";import r from"node:os";import o from"node:path";import{AppError as i}from"./152.js";import{runCmd as n}from"./818.js";import{expandUserHomePath as s}from"./267.js";let l=[".zip",".tar",".tar.gz",".tgz"],c=Object.freeze([...l]),h=function(t){if(!t)return 12e4;let e=Number(t);return Number.isFinite(e)?Math.max(1e3,Math.floor(e)):12e4}(process.env.AGENT_DEVICE_SOURCE_DOWNLOAD_TIMEOUT_MS),u=["1","true","yes","on"];async function d(t){let e=[];try{let a=await w(t.source,{signal:t.signal,downloadTimeoutMs:t.downloadTimeoutMs});e.push(a.cleanup);let r=await _(a.localPath,{archivePath:void 0,isInstallablePath:t.isInstallablePath,installableLabel:t.installableLabel,allowArchiveExtraction:!1!==t.allowArchiveExtraction,registerCleanup:t=>{e.push(t)}});return{archivePath:r.archivePath,installablePath:r.installablePath,cleanup:async()=>{await E(e)}}}catch(t){throw await E(e),t}}async function w(t,e){if("path"===t.kind)return{localPath:s(t.path),cleanup:async()=>{}};let i=await a.mkdtemp(o.join(r.tmpdir(),"agent-device-source-"));try{return{localPath:await p(i,t.url,t.headers,e),cleanup:async()=>{await a.rm(i,{recursive:!0,force:!0})}}}catch(t){throw await a.rm(i,{recursive:!0,force:!0}),t}}async function p(t,e,r,n){let s;try{s=new URL(e)}catch{throw new i("INVALID_ARGS",`Invalid source URL: ${e}`)}await f(s);let l=n?.signal;if(l?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"});let c=new AbortController,u=()=>{c.abort(l?.reason)};l?.addEventListener("abort",u,{once:!0});let d=n?.downloadTimeoutMs??h,w=setTimeout(()=>{c.abort(Error("download timeout"))},d);try{let e=await fetch(s,{headers:r,redirect:"follow",signal:c.signal});if(!e.ok)throw new i("COMMAND_FAILED",`Failed to download app source: ${e.status} ${e.statusText}`,{status:e.status,statusText:e.statusText,url:s.toString()});let n=function(t,e){let a=t.headers.get("content-disposition"),r=a?.match(/filename\*?=(?:UTF-8'')?"?([^";]+)"?/i),i=r?.[1]?.trim();if(i)return o.basename(i);let n=o.basename(e.pathname);return n||"downloaded-artifact.bin"}(e,s),l=o.join(t,n),h=e.body;if(!h)throw new i("COMMAND_FAILED","Download response body was empty",{url:s.toString()});let u=await a.open(l,"w");try{for await(let t of h)await u.write(t)}finally{await u.close()}return l}catch(t){if(l?.aborted)throw new i("COMMAND_FAILED","request canceled",{reason:"request_canceled"},t);if(c.signal.aborted)throw new i("COMMAND_FAILED",`App source download timed out after ${d}ms`,{timeoutMs:d,url:s.toString()},t);throw t}finally{l?.removeEventListener("abort",u),clearTimeout(w)}}async function f(e){if("http:"!==e.protocol&&"https:"!==e.protocol)throw new i("INVALID_ARGS",`Unsupported source URL protocol: ${e.protocol}`);if(!u.includes((process.env.AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS??"").toLowerCase())){if(A(e.hostname.toLowerCase()))throw new i("INVALID_ARGS",`Source URL host is not allowed: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."});if((await t.lookup(e.hostname,{all:!0,verbatim:!0}).catch(()=>[])).some(t=>L(t.address)))throw new i("INVALID_ARGS",`Source URL host resolved to a private or loopback address: ${e.hostname}`,{hint:"Use a public artifact URL, or set AGENT_DEVICE_ALLOW_PRIVATE_SOURCE_URLS=1 for trusted private-network daemons."})}}function m(t){var e,a,r,o;let i=t instanceof URL?t:new URL(t),n=i.hostname.toLowerCase();if(!n)return!1;let s=i.pathname;return e=n,a=s,("api.github.com"===e?/^\/repos\/[^/]+\/[^/]+\/actions\/artifacts\/\d+\/zip$/i.test(a):"github.com"===e&&/^\/[^/]+\/[^/]+\/(?:actions\/runs\/\d+\/artifacts\/\d+|suites\/\d+\/artifacts\/\d+)$/i.test(a))||(r=n,o=s,("expo.dev"===r||!!r.endsWith(".expo.dev"))&&/^\/(?:artifacts\/eas\/|accounts\/[^/]+\/projects\/[^/]+\/builds\/)/i.test(o))}function A(t){return!!(!t||"localhost"===t||t.endsWith(".localhost"))||L(t)}function L(t){let a,r=e.isIP(t);return 4===r?function(t){let e=t.split(".").map(t=>Number.parseInt(t,10));if(4!==e.length||e.some(t=>Number.isNaN(t)||t<0||t>255))return!1;let[a,r]=e;return 10===a||127===a||169===a&&254===r||172===a&&!!(r>=16)&&!!(r<=31)||192===a&&168===r}(t):6===r&&!!("::1"===(a=t.toLowerCase())||a.startsWith("fc")||a.startsWith("fd")||a.startsWith("fe80:"))}async function _(t,e){let r=await a.stat(t).catch(()=>null);if(!r)throw new i("INVALID_ARGS",`App source not found: ${t}`);if(e.isInstallablePath(t,r))return{archivePath:e.archivePath,installablePath:t};if(r.isFile()&&v(t)){if(!e.allowArchiveExtraction)throw new i("INVALID_ARGS",`URL sources must point directly to a ${e.installableLabel}; archive extraction is not allowed`,{path:t});let a=await I(t);return e.registerCleanup(a.cleanup),await _(a.outputPath,{...e,archivePath:e.archivePath??t})}if(r.isDirectory()){let a=await b(t,e.isInstallablePath);if(1===a.length)return{archivePath:e.archivePath,installablePath:a[0]};if(a.length>1)throw new i("INVALID_ARGS",`Found multiple ${e.installableLabel} candidates under ${t}`,{matches:a});let r=await b(t,(t,e)=>e.isFile()&&v(t));if(1===r.length){if(!e.allowArchiveExtraction)throw new i("INVALID_ARGS",`URL sources must point directly to a ${e.installableLabel}; nested archives are not allowed`,{path:r[0]});let t=await I(r[0]);return e.registerCleanup(t.cleanup),await _(t.outputPath,{...e,archivePath:e.archivePath??r[0]})}if(r.length>1)throw new i("INVALID_ARGS",`Found multiple nested archives under ${t}; expected one ${e.installableLabel} source`,{matches:r})}throw new i("INVALID_ARGS",`Expected ${e.installableLabel} source, but got ${t}`)}async function b(t,e){let r=[],i=[{path:t,depth:0}];for(;i.length>0;){let t=i.shift();if(!t)continue;let n=await a.readdir(t.path,{withFileTypes:!0});for(let a of(n.sort((t,e)=>t.name.localeCompare(e.name)),n)){let n=o.join(t.path,a.name);if(e(n,a)){r.push(n);continue}a.isDirectory()&&t.depth<5&&i.push({path:n,depth:t.depth+1})}}return r}async function I(t){let e=await a.mkdtemp(o.join(r.tmpdir(),"agent-device-archive-"));try{return t.toLowerCase().endsWith(".zip")?await n("ditto",["-x","-k",t,e]):t.toLowerCase().endsWith(".tar.gz")||t.toLowerCase().endsWith(".tgz")?await n("tar",["-xzf",t,"-C",e]):await n("tar",["-xf",t,"-C",e]),{outputPath:e,cleanup:async()=>{await a.rm(e,{recursive:!0,force:!0})}}}catch(t){throw await a.rm(e,{recursive:!0,force:!0}),t}}function v(t){let e=t.toLowerCase();return l.some(t=>e.endsWith(t))}async function E(t){for(let e=t.length-1;e>=0;e-=1)await t[e]()}export{c as ARCHIVE_EXTENSIONS,L as isBlockedIpAddress,A as isBlockedSourceHostname,m as isTrustedInstallSourceUrl,d as materializeInstallablePath,f as validateDownloadSourceUrl};
@@ -179,6 +179,12 @@ export declare type PrepareRemoteMetroResult = {
179
179
  logPath: string;
180
180
  };
181
181
 
182
+ export declare function resolveRuntimeTransport(runtime: SessionRuntimeHints | undefined): {
183
+ host: string;
184
+ port: number;
185
+ scheme: 'http' | 'https';
186
+ } | undefined;
187
+
182
188
  declare type SessionRuntimeHints = {
183
189
  platform?: 'ios' | 'android';
184
190
  metroHost?: string;
package/dist/src/metro.js CHANGED
@@ -1 +1 @@
1
- import{buildMetroRuntimeHints as e,ensureMetroCompanion as t,stopMetroCompanion as r,prepareMetroRuntime as n}from"./974.js";async function o(e){let t=await n({projectRoot:e.projectRoot,kind:e.kind,publicBaseUrl:e.publicBaseUrl,proxyBaseUrl:e.proxyBaseUrl,proxyBearerToken:e.proxyBearerToken,launchUrl:e.launchUrl,companionProfileKey:e.profileKey,companionConsumerKey:e.consumerKey,metroPort:e.port,listenHost:e.listenHost,statusHost:e.statusHost,startupTimeoutMs:e.startupTimeoutMs,probeTimeoutMs:e.probeTimeoutMs,reuseExisting:e.reuseExisting,installDependenciesIfNeeded:e.installDependenciesIfNeeded,runtimeFilePath:e.runtimeFilePath,logPath:e.logPath,env:e.env});return{iosRuntime:t.iosRuntime,androidRuntime:t.androidRuntime,bridge:t.bridge,started:t.started,reused:t.reused,logPath:t.logPath}}async function i(e){let r=await t(e);return{pid:r.pid,started:r.spawned,logPath:r.logPath}}async function s(e){await r(e)}function a(t){return e(t,"ios")}function u(t){return e(t,"android")}export{buildBundleUrl,normalizeBaseUrl}from"./974.js";export{u as buildAndroidRuntimeHints,a as buildIosRuntimeHints,i as ensureMetroTunnel,o as prepareRemoteMetro,s as stopMetroTunnel};
1
+ import{URL as t}from"node:url";import"./818.js";import{AppError as e}from"./152.js";import"./164.js";import{buildMetroRuntimeHints as r,ensureMetroCompanion as o,stopMetroCompanion as n,prepareMetroRuntime as i}from"./974.js";function s(t){let e=t?.trim();return e&&e.length>0?e:void 0}function u(t){if(Number.isInteger(t)&&!(t<=0)&&!(t>65535))return t}function l(r){return function(r){if(!r)return;let o=s(r.metroHost),n=u(r.metroPort),i="http",l=s(r.bundleUrl);if(l){var a;let r;try{r=new t(l)}catch(t){throw new e("INVALID_ARGS",`Invalid runtime bundle URL: ${l}`,{},t)}("http:"===r.protocol||"https:"===r.protocol)&&(o??=s(r.hostname),n??=u(r.port.length>0?Number(r.port):"https:"===(a=r.protocol)?443:"http:"===a?80:void 0),i="https:"===r.protocol?"https":"http")}if(o&&n)return{host:o,port:n,scheme:i}}(r)}async function a(t){let e=await i({projectRoot:t.projectRoot,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.proxyBearerToken,launchUrl:t.launchUrl,companionProfileKey:t.profileKey,companionConsumerKey:t.consumerKey,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,env:t.env});return{iosRuntime:e.iosRuntime,androidRuntime:e.androidRuntime,bridge:e.bridge,started:e.started,reused:e.reused,logPath:e.logPath}}async function p(t){let e=await o(t);return{pid:e.pid,started:e.spawned,logPath:e.logPath}}async function d(t){await n(t)}function m(t){return r(t,"ios")}function c(t){return r(t,"android")}export{buildBundleUrl,normalizeBaseUrl}from"./974.js";export{c as buildAndroidRuntimeHints,m as buildIosRuntimeHints,p as ensureMetroTunnel,a as prepareRemoteMetro,l as resolveRuntimeTransport,d as stopMetroTunnel};
@@ -1 +1 @@
1
- import e from"node:fs";import t from"node:path";import{resolveUserPath as n,AppError as r}from"./957.js";let o=new Set(["1","true","yes","on"]),i=new Set(["0","false","no","off"]);function a(e,t,n,o){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>a({...e,multiple:!1},t,n,o));if("boolean"===e.type){var i=t,s=n,f=o;if("boolean"==typeof i)return i;if("string"==typeof i){let e=l(i);if(void 0!==e)return e}throw new r("INVALID_ARGS",`Invalid value for "${f}" in ${s}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==l(t))return l(t);if("string"==typeof t&&t.trim().length>0)return t;throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var u=e,y=t,p=n,m=o;let i=u.setValue;if(y===i)return i;if("string"==typeof y){let e=y.trim();if(""===e||"true"===e||"1"===e)return i;if("false"===e||"0"===e)return}if(!0===y)return i;if(!1!==y)throw new r("INVALID_ARGS",`Invalid value for "${m}" in ${p}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let g="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(g)||!Number.isInteger(g))throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Expected integer.`);if("number"==typeof e.min&&g<e.min)throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Must be >= ${e.min}.`);if("number"==typeof e.max&&g>e.max)throw new r("INVALID_ARGS",`Invalid value for "${o}" in ${n}. Must be <= ${e.max}.`);return g}function l(e){let t=e.trim().toLowerCase();return!!o.has(t)||!i.has(t)&&void 0}let s=[{key:"stateDir",type:"string",path:!0},{key:"daemonBaseUrl",type:"string"},{key:"daemonAuthToken",type:"string"},{key:"daemonTransport",type:"enum",enumValues:["auto","socket","http"]},{key:"daemonServerMode",type:"enum",enumValues:["socket","http","dual"]},{key:"tenant",type:"string"},{key:"sessionIsolation",type:"enum",enumValues:["none","tenant"]},{key:"runId",type:"string"},{key:"leaseId",type:"string"},{key:"platform",type:"enum",enumValues:["ios","macos","android","linux","apple"]},{key:"target",type:"enum",enumValues:["mobile","tv","desktop"]},{key:"device",type:"string"},{key:"udid",type:"string"},{key:"serial",type:"string"},{key:"iosSimulatorDeviceSet",type:"string",path:!0,legacyEnvNames:["IOS_SIMULATOR_DEVICE_SET"]},{key:"androidDeviceAllowlist",type:"string",legacyEnvNames:["ANDROID_DEVICE_ALLOWLIST"]},{key:"session",type:"string"},{key:"metroProjectRoot",type:"string",path:!0},{key:"metroKind",type:"enum",enumValues:["auto","react-native","expo"]},{key:"metroPublicBaseUrl",type:"string"},{key:"metroProxyBaseUrl",type:"string"},{key:"metroBearerToken",type:"string",legacyEnvNames:["AGENT_DEVICE_PROXY_TOKEN"]},{key:"metroPreparePort",type:"int",min:1,max:65535},{key:"metroListenHost",type:"string"},{key:"metroStatusHost",type:"string"},{key:"metroStartupTimeoutMs",type:"int",min:1},{key:"metroProbeTimeoutMs",type:"int",min:1},{key:"metroRuntimeFile",type:"string",path:!0},{key:"metroNoReuseExisting",type:"boolean"},{key:"metroNoInstallDeps",type:"boolean"}],f=new Map(s.map(e=>[e.key,e]));function u(e){let t=e.env??process.env;return n(e.configPath,{cwd:e.cwd,env:t})}function y(o){let i=function(o){let i,l,s=o.env??process.env,y=u(o);if(!e.existsSync(y))throw new r("INVALID_ARGS",`Remote config file not found: ${y}`);try{i=e.readFileSync(y,"utf8")}catch(e){throw new r("INVALID_ARGS",`Failed to read remote config file: ${y}`,{cause:e instanceof Error?e.message:String(e)})}try{l=JSON.parse(i)}catch(e){throw new r("INVALID_ARGS",`Invalid JSON in remote config file: ${y}`,{cause:e instanceof Error?e.message:String(e)})}if(!l||"object"!=typeof l||Array.isArray(l))throw new r("INVALID_ARGS",`Remote config file must contain a JSON object: ${y}`);let p={},m=l,g=t.dirname(y);for(let[e,t]of Object.entries(m)){let o=f.get(e);if(!o)throw new r("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${y}.`);let i=a(o,t,`remote config file ${y}`,e);p[o.key]="string"==typeof i&&"path"in o&&o.path?n(i,{cwd:g,env:s}):i}return{resolvedPath:y,profile:p}}(o);return{resolvedPath:i.resolvedPath,profile:function(...e){let t={};for(let n of e)if(n)for(let e of s){let r=n[e.key];void 0!==r&&(t[e.key]=r)}return t}(function(e=process.env){let t={};for(let n of s){let r=(function(e){let t=f.get(e);return[`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`,...t?.legacyEnvNames??[]]})(n.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);r&&(t[n.key]=a(n,r.value,`environment variable ${r.name}`,r.name))}return t}(o.env),i.profile)}}export{u as resolveRemoteConfigPath,y as resolveRemoteConfigProfile};
1
+ export{resolveRemoteConfigPath,resolveRemoteConfigProfile}from"./924.js";
@@ -0,0 +1,110 @@
1
+ declare type ApplePlatform = 'ios' | 'macos';
2
+
3
+ export declare function findSelectorChainMatch(nodes: SnapshotState['nodes'], chain: SelectorChain, options: {
4
+ platform: Platform;
5
+ requireRect?: boolean;
6
+ }): {
7
+ selectorIndex: number;
8
+ selector: Selector;
9
+ matches: number;
10
+ diagnostics: SelectorDiagnostics[];
11
+ } | null;
12
+
13
+ export declare function formatSelectorFailure(chain: SelectorChain, diagnostics: SelectorDiagnostics[], options: {
14
+ unique?: boolean;
15
+ }): string;
16
+
17
+ export declare function isNodeEditable(node: SnapshotNode, platform: Platform): boolean;
18
+
19
+ export declare function isNodeVisible(node: SnapshotNode): boolean;
20
+
21
+ export declare function isSelectorToken(token: string): boolean;
22
+
23
+ export declare function parseSelectorChain(expression: string): SelectorChain;
24
+
25
+ declare type Platform = ApplePlatform | 'android' | 'linux';
26
+
27
+ declare type RawSnapshotNode = {
28
+ index: number;
29
+ type?: string;
30
+ role?: string;
31
+ subrole?: string;
32
+ label?: string;
33
+ value?: string;
34
+ identifier?: string;
35
+ rect?: Rect;
36
+ enabled?: boolean;
37
+ selected?: boolean;
38
+ hittable?: boolean;
39
+ depth?: number;
40
+ parentIndex?: number;
41
+ pid?: number;
42
+ bundleId?: string;
43
+ appName?: string;
44
+ windowTitle?: string;
45
+ surface?: string;
46
+ hiddenContentAbove?: boolean;
47
+ hiddenContentBelow?: boolean;
48
+ };
49
+
50
+ declare type Rect = {
51
+ x: number;
52
+ y: number;
53
+ width: number;
54
+ height: number;
55
+ };
56
+
57
+ export declare function resolveSelectorChain(nodes: SnapshotState['nodes'], chain: SelectorChain, options: {
58
+ platform: Platform;
59
+ requireRect?: boolean;
60
+ requireUnique?: boolean;
61
+ disambiguateAmbiguous?: boolean;
62
+ }): SelectorResolution | null;
63
+
64
+ export declare type Selector = {
65
+ raw: string;
66
+ terms: SelectorTerm[];
67
+ };
68
+
69
+ export declare type SelectorChain = {
70
+ raw: string;
71
+ selectors: Selector[];
72
+ };
73
+
74
+ export declare type SelectorDiagnostics = {
75
+ selector: string;
76
+ matches: number;
77
+ };
78
+
79
+ declare type SelectorKey = 'id' | 'role' | 'text' | 'label' | 'value' | 'appname' | 'windowtitle' | 'visible' | 'hidden' | 'editable' | 'selected' | 'enabled' | 'hittable';
80
+
81
+ export declare type SelectorResolution = {
82
+ node: SnapshotNode;
83
+ selector: Selector;
84
+ selectorIndex: number;
85
+ matches: number;
86
+ diagnostics: SelectorDiagnostics[];
87
+ };
88
+
89
+ declare type SelectorTerm = {
90
+ key: SelectorKey;
91
+ value: string | boolean;
92
+ };
93
+
94
+ declare type SnapshotBackend = 'xctest' | 'android' | 'macos-helper' | 'linux-atspi';
95
+
96
+ declare type SnapshotNode = RawSnapshotNode & {
97
+ ref: string;
98
+ };
99
+
100
+ declare type SnapshotState = {
101
+ nodes: SnapshotNode[];
102
+ createdAt: number;
103
+ truncated?: boolean;
104
+ backend?: SnapshotBackend;
105
+ comparisonSafe?: boolean;
106
+ };
107
+
108
+ export declare function tryParseSelectorChain(expression: string): SelectorChain | null;
109
+
110
+ export { }
@@ -0,0 +1 @@
1
+ export{findSelectorChainMatch,formatSelectorFailure,isNodeEditable,isNodeVisible,isSelectorToken,parseSelectorChain,resolveSelectorChain,tryParseSelectorChain}from"./940.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-device",
3
- "version": "0.11.14",
3
+ "version": "0.11.16",
4
4
  "description": "Unified control plane for physical and virtual devices via an agent-driven CLI.",
5
5
  "license": "MIT",
6
6
  "author": "Callstack",
@@ -12,6 +12,10 @@
12
12
  "import": "./dist/src/index.js",
13
13
  "types": "./dist/src/index.d.ts"
14
14
  },
15
+ "./artifacts": {
16
+ "import": "./dist/src/artifacts.js",
17
+ "types": "./dist/src/artifacts.d.ts"
18
+ },
15
19
  "./metro": {
16
20
  "import": "./dist/src/metro.js",
17
21
  "types": "./dist/src/metro.d.ts"
@@ -20,9 +24,21 @@
20
24
  "import": "./dist/src/remote-config.js",
21
25
  "types": "./dist/src/remote-config.d.ts"
22
26
  },
27
+ "./install-source": {
28
+ "import": "./dist/src/install-source.js",
29
+ "types": "./dist/src/install-source.d.ts"
30
+ },
23
31
  "./contracts": {
24
32
  "import": "./dist/src/contracts.js",
25
33
  "types": "./dist/src/contracts.d.ts"
34
+ },
35
+ "./selectors": {
36
+ "import": "./dist/src/selectors.js",
37
+ "types": "./dist/src/selectors.d.ts"
38
+ },
39
+ "./finders": {
40
+ "import": "./dist/src/finders.js",
41
+ "types": "./dist/src/finders.d.ts"
26
42
  }
27
43
  },
28
44
  "engines": {
package/dist/src/32.js DELETED
@@ -1,2 +0,0 @@
1
- import e from"node:fs";import t from"node:path";import{fileURLToPath as n}from"node:url";import r from"node:os";import i from"node:crypto";import{PNG as a}from"pngjs";import{runCmdSync as s,emitDiagnostic as o,AppError as l}from"./818.js";let u="<wifi|airplane|location> <on|off>",c="appearance <light|dark|toggle>",d="faceid <match|nonmatch|enroll|unenroll>",p="touchid <match|nonmatch|enroll|unenroll>",m="fingerprint <match|nonmatch>",f="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",h="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",g=`macOS supports only settings ${c} and settings ${h}. wifi|airplane|location remain unsupported on macOS.`,w=`settings ${u} | settings ${c} | settings ${d} | settings ${p} | settings ${m} | settings ${f} | settings ${h}`,x=`settings requires ${u}, ${c}, ${d}, ${p}, ${m}, ${f}, or ${h}`;function b(e){let t=e.trim().toLowerCase();return"appearance"===t||"permission"===t}function y(e){return`Unsupported macOS setting: ${e}. ${g}`}let v=["app","frontmost-app","desktop","menubar"];function S(e){let t=e?.trim().toLowerCase();if("app"===t||"frontmost-app"===t||"desktop"===t||"menubar"===t)return t;throw new l("INVALID_ARGS",`Invalid surface: ${e}. Use ${v.join("|")}.`)}function I(e){var t;let n,r=M(e.label),i=M(e.value),a=M(e.identifier),s=(t=a)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?a:"";return(n=A(e.type??"")).includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||n.includes("textview")||n.includes("textarea")?i||r||s:r||i||s}function M(e){return"string"==typeof e?e.trim():""}function A(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),n=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==n&&(t=t.slice(n+1)),t}function $(e,t={}){let n=[],r=[];for(let i of e){let e=i.depth??0,a=i.label?.trim()||i.value?.trim()||i.identifier?.trim()||"",s=R(i.type??"Element");if("group"===s&&!a)continue;for(;n.length>0&&e<=n[n.length-1];)n.pop();let o=n.length;n.push(e),r.push({node:i,depth:o,type:s,text:N(i,o,!1,s,t)})}return r}function N(e,t,n,r,i={}){var a,s,o,l,u;let c,d,p=r??R(e.type??"Element"),m=(c=I(e),{text:c,isLargeSurface:d=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let n=A(e.type??""),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("textview")||n.includes("textarea")||n.includes("textfield")||n.includes("securetextfield")||n.includes("searchfield")||n.includes("edittext")||r.includes("text area")||r.includes("text field")}(e,p),shouldSummarize:d&&!!(a=c)&&(a.length>80||/[\r\n]/.test(a))}),f=(s=e,o=p,l=i,u=m,l.summarizeTextSurfaces&&u.shouldSummarize&&function(e,t,n){let r=M(e.label);if(r&&r!==n)return r;let i=M(e.identifier);if(i&&!L(i)&&i!==n)return i;switch(t){case"text":case"text-view":return"Text view";case"text-field":return"Text field";case"search":return"Search field";default:return""}}(s,o,u.text)||D(s,o)),h=" ".repeat(t),g=e.ref?`@${e.ref}`:"",w=(function(e,t,n,r){let i,a=[];if(!1===e.enabled&&a.push("disabled"),!n.summarizeTextSurfaces||(!0===e.selected&&a.push("selected"),E(t)&&a.push("editable"),function(e,t){if("scroll-area"===t)return!0;let n=(e.type??"").toLowerCase(),r=`${e.role??""} ${e.subrole??""}`.toLowerCase();return n.includes("scroll")||r.includes("scroll")}(e,t)&&a.push("scrollable"),!r.shouldSummarize))return a;return a.push(`preview:"${((i=r.text.replace(/\s+/g," ").trim()).length<=48?i:`${i.slice(0,45)}...`).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),a.push("truncated"),[...new Set(a)]})(e,p,i,m).map(e=>` [${e}]`).join(""),x=f?` "${f}"`:"";return n?`${h}${g} [${p}]${w}`.trimEnd():`${h}${g} [${p}]${x}${w}`.trimEnd()}function D(e,t){var n,r;let i,a=e.label?.trim();if(a&&(n=t,r=a,("scroll-area"===n||"list"===n||"collection"===n||"table"===n)&&(i=r.trim().toLowerCase())&&/^(vertical|horizontal)\s+scroll\s+bar(?:,?\s*\d+\s+pages?)?$/.test(i)))return"";let s=e.value?.trim();if(E(t)){if(s)return s;if(a)return a}else if(a)return a;if(s)return s;let o=e.identifier?.trim();return!o||L(o)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":o}function R(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),n=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,""),n&&t.includes(".")&&(t=t.slice(t.lastIndexOf(".")+1))),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return n?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function E(e){return"text-field"===e||"text-view"===e||"search"===e}function L(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function _(e){let t=new Map;for(let[n,r]of e.entries())t.set(r.index,n);let n=[],r=[];for(let[i,a]of e.entries()){let e=Math.max(0,a.depth??0);for(;r.length>0&&e<=r[r.length-1].depth;)r.pop();let s="number"==typeof a.parentIndex?t.get(a.parentIndex):void 0,o="number"==typeof s&&s<i?s:r[r.length-1]?.index;n.push({...a,index:i,depth:e,parentIndex:o}),r.push({depth:e,index:i})}return n}function C(e){return new Map(e.map(e=>[e.index,e]))}function k(e){return e.label?.trim()||e.value?.trim()||e.identifier?.trim()||""}function T(e){return e.map((e,t)=>({...e,ref:`e${t+1}`}))}function j(e){let t=e.trim();return t.startsWith("@")?t.slice(1)||null:t.startsWith("e")?t:null}function P(e,t){return e.find(e=>e.ref===t)??null}function z(e){return{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}function O(e,t){let n=z(t),r=e.filter(e=>{var t;return!!(t=e.rect)&&Number.isFinite(t.x)&&Number.isFinite(t.y)&&Number.isFinite(t.width)&&Number.isFinite(t.height)}),i=r.filter(e=>{let t=(e.type??"").toLowerCase();return t.includes("application")||t.includes("window")}),a=G(i.map(e=>e.rect).filter(e=>F(e,n.x,n.y)));if(a)return a;let s=G(i.map(e=>e.rect));if(s)return s;let o=G(r.map(e=>e.rect).filter(e=>F(e,n.x,n.y)));return o||null}function B(e,t){let n=Math.max(1,t.height),r=t.y,i=t.y+n,a=r+.25*n,s=i-.25*n,o=e.y+e.height/2;return o<a?Math.ceil(a-o):o>s?Math.ceil(o-s):0}function F(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function G(e){let t=null,n=-1;for(let r of e){let e=r.width*r.height;e>n&&(t=r,n=e)}return t}function V(e,t,n,r){return Math.max(e,n)<=Math.min(t,r)}function U(e){let t=`${e??""}`.toLowerCase();return t.includes("scroll")||t.includes("recyclerview")||t.includes("listview")||t.includes("gridview")||t.includes("collectionview")||"table"===t}function W(e){return!!U(e.type)||`${e.role??""} ${e.subrole??""}`.toLowerCase().includes("scroll")}function H(e){if(0===e.length)return{nodes:e,hiddenCount:0,summaryLines:[]};let t=C(e),n=new Set,r=[];for(let i of e){if(J(i,e,t)){!function(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}(i,n,t);continue}r.push(i)}let i=function(e,t,n,r){let i=new Map,a=new Set;for(let e of t){if(!e.rect)continue;let t=K(e,n,r);if(!t?.rect)continue;let s=X(e.rect,t.rect);if(!s)continue;let o=i.get(t.index)??new Set;o.add(s),i.set(t.index,o),a.add(e.index)}return function(e,t,n,r){for(let i of e){let e=function(e){let t=function(e,t){if(!(e?.trim().toLowerCase()??"").includes("vertical scroll bar"))return null;let n=function(e){if(!e)return null;let t=/^(\d{1,3})%$/.exec(e.trim());if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Math.max(0,Math.min(100,n)):null}(t);return null===n?null:n<=1?{above:!1,below:!0}:n>=99?{above:!0,below:!1}:{above:!0,below:!0}}(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add("above"),t.below&&n.add("below"),n.size>0?n:null}(i);if(!e||0===e.size)continue;let a=K(i,t,n);if(!a)continue;let s=r.get(a.index)??new Set;for(let t of e)s.add(t);r.set(a.index,s)}}(e,n,r,i),{directionsByContainer:i,coveredNodeIndexes:a}}(e,r,n,t),a=0===n.size?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>(function(e,t){let n=t.get(e.index);if(!n||0===n.size)return e;let r=!!(!0===e.hiddenContentAbove||n.has("above"))||void 0,i=!!(!0===e.hiddenContentBelow||n.has("below"))||void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}})(e,i.directionsByContainer)),hiddenCount:0===n.size?0:e.length-a.length,summaryLines:function(e,t,n){let r=new Map;for(let i of e){let e=function(e,t,n){if(!e.rect)return null;let r=q(e,t,n);return r?X(e.rect,r):null}(i,t,n);if(!e)continue;let a=r.get(e)??[];a.push(i),r.set(e,a)}return["above","below"].flatMap(e=>{let t=r.get(e);if(!t||0===t.length)return[];let n=(function(e){let t=new Set,n=[];for(let r of e){let e=k(r);!e||t.has(e)||(t.add(e),n.push(e))}return n})(t).slice(0,3).map(e=>`"${e}"`),i=1===t.length?"interactive item":"interactive items",a=n.length>0?`: ${n.join(", ")}`:"";return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&function(e){if(!0===e.hittable)return!0;let t=(e.type??"").toLowerCase();return t.includes("button")||t.includes("link")||t.includes("textfield")||t.includes("edittext")||t.includes("searchfield")||t.includes("checkbox")||t.includes("radio")||t.includes("switch")||t.includes("menuitem")||!!k(e)}(e)),e,t)}}function J(e,t,n=C(t)){var r;if(!e.rect)return!0;let i=q(e,t,n);return!i||(r=e.rect,V(r.x,r.x+r.width,i.x,i.x+i.width)&&V(r.y,r.y+r.height,i.y,i.y+i.height))}function q(e,t,n=C(t)){let r=function(e,t){let n="number"==typeof e.parentIndex?t.get(e.parentIndex):void 0,r=new Set;for(;n&&!r.has(n.index);){if(r.add(n.index),n.rect&&W(n))return n.rect;n="number"==typeof n.parentIndex?t.get(n.parentIndex):void 0}return null}(e,n);return r||O(t,e.rect??{x:0,y:0,width:0,height:0})}function X(e,t){return e.y+e.height<=t.y?"above":e.y>=t.y+t.height?"below":null}function K(e,t,n){let r="number"==typeof e.parentIndex?n.get(e.parentIndex):void 0,i=new Set;for(;r&&!i.has(r.index);){if(i.add(r.index),t.has(r.index)&&W(r))return r;r="number"==typeof r.parentIndex?n.get(r.parentIndex):void 0}return null}function Y(){try{let n=Z();return JSON.parse(e.readFileSync(t.join(n,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function Z(){let r=t.dirname(n(import.meta.url)),i=r;for(let n=0;n<6;n+=1){let n=t.join(i,"package.json");if(e.existsSync(n))return i;i=t.dirname(i)}return r}function Q(e){return e?{message:e}:{}}function ee(e,t){return t?{...e,message:t}:e}function et(e){return"string"==typeof e?.message&&e.message.length>0?e.message:null}let en=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function er(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function ei(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=s("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function ea(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=s("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let n=t.stdout.trim();return n.length>0?n:null}catch{return null}}function es(e,t){let n;if(!er(e))return!1;if(t){let n=ei(e);if(!n||n!==t)return!1}let r=ea(e);return!!r&&!!(n=r.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&en.some(e=>e.test(n))}function eo(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function el(e,t){if(!er(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await new Promise(e=>setTimeout(e,50)),!er(e))return!0;return!er(e)}async function eu(e,t){!es(e,t.expectedStartTime)||!eo(e,"SIGTERM")||await el(e,t.termTimeoutMs)||eo(e,"SIGKILL")&&await el(e,t.killTimeoutMs)}function ec(e){return e?.HOME?.trim()||r.homedir()}function ed(e,n={}){return"~"===e?ec(n.env):e.startsWith("~/")?t.join(ec(n.env),e.slice(2)):e}function ep(e,n={}){let r=ed(e,n);return t.isAbsolute(r)?r:t.resolve(n.cwd??process.cwd(),r)}function em(e){let n,r=(n=(e??"").trim())?ep(n):t.join(ed("~"),".agent-device");return{baseDir:r,infoPath:t.join(r,"daemon.json"),lockPath:t.join(r,"daemon.lock"),logPath:t.join(r,"daemon.log"),sessionsDir:t.join(r,"sessions")}}function ef(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function eh(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function eg(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function ew(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let ex=/(?:^|[^\w$.])(?:import|export)\s+(?:type\s+)?(?:[^'"`]*?\s+from\s+)?['"]([^'"]+)['"]/gm,eb=/import\(\s*['"]([^'"]+)['"]\s*\)/gm,ey=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];function ev(){let e=process.argv[1];return e?eS(e):"unknown"}function eS(n,r=Z()){try{let a=t.resolve(r),s=[t.resolve(n)],o=new Set,l=[];for(;s.length>0;){let n=s.pop();if(!n||o.has(n))continue;o.add(n);let r=e.statSync(n);if(!r.isFile())continue;let i=t.relative(a,n)||n;l.push(`${i}:${r.size}:${Math.trunc(r.mtimeMs)}`);let u=e.readFileSync(n,"utf8");for(let e of function(e){let t=new Set;return eI(e,ex,t),eI(e,eb,t),[...t]}(u)){let r=function(e,n){let r=t.resolve(t.dirname(e),n),i=eM(r);if(i)return i;for(let e of ey){let t=eM(`${r}${e}`);if(t)return t}for(let e of ey){let n=eM(t.join(r,`index${e}`));if(n)return n}return null}(n,e);r&&s.push(r)}}let u=l.sort().join("|"),c=i.createHash("sha1").update(u).digest("hex");return`graph:${l.length}:${c}`}catch{return"unknown"}}function eI(e,t,n){t.lastIndex=0;let r=null;for(;null!==(r=t.exec(e));){let e=r[1]?.trim();e?.startsWith(".")&&n.add(e)}}function eM(t){try{return e.statSync(t).isFile()?t:null}catch{return null}}let eA=100,e$=new Set(["batch","replay"]),eN=new Set(["command","positionals","flags","runtime"]);function eD(e){let t;try{t=JSON.parse(e)}catch{throw new l("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new l("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function eR(e,t){if(!Array.isArray(e)||0===e.length)throw new l("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new l("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let n=[];for(let t=0;t<e.length;t+=1){let r=e[t];if(!r||"object"!=typeof r)throw new l("INVALID_ARGS",`Invalid batch step at index ${t}.`);let i=Object.keys(r).filter(e=>!eN.has(e));if(i.length>0){let e=i.map(e=>`"${e}"`).join(", ");throw new l("INVALID_ARGS",`Batch step ${t+1} has unknown field(s): ${e}. Allowed fields: command, positionals, flags, runtime.`)}let a="string"==typeof r.command?r.command.trim().toLowerCase():"";if(!a)throw new l("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(e$.has(a))throw new l("INVALID_ARGS",`Batch step ${t+1} cannot run ${a}.`);if(void 0!==r.positionals&&!Array.isArray(r.positionals))throw new l("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let s=r.positionals??[];if(s.some(e=>"string"!=typeof e))throw new l("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==r.flags&&("object"!=typeof r.flags||Array.isArray(r.flags)||!r.flags))throw new l("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);if(void 0!==r.runtime&&("object"!=typeof r.runtime||Array.isArray(r.runtime)||!r.runtime))throw new l("INVALID_ARGS",`Batch step ${t+1} runtime must be an object.`);n.push({command:a,positionals:s,flags:r.flags??{},runtime:r.runtime})}return n}function eE(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function eL(e,t,n){return{deviceId:t,deviceName:n,..."android"===e?{serial:t}:"ios"===e?{udid:t}:{}}}function e_(e,t={}){let n=t.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&n?{serial:e.android?.serial??e.id}:{}}}function eC(e){return{name:e.name,...e_(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function ek(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function eT(e){let t=e.created?"Created":"Reused",n=e.booted?" (booted)":"";return ee({udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted},`${t}: ${e.device} ${e.udid}${n}`)}function ej(e){return e.bundleId??e.package??e.app}function eP(e){return ee({app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}},`Installed: ${ej(e)}`)}function ez(e){return e.appName??e.bundleId??e.packageName??e.launchTarget}function eO(e){return ee({launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}},`Installed: ${ez(e)}`)}function eB(e){let t=e.appName??e.appBundleId??e.session;return ee({session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?e_(e.device):{}},t?`Opened: ${t}`:"Opened")}function eF(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{},...Q(e.session?`Closed: ${e.session}`:"Closed")}}function eG(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.visibility?{visibility:e.visibility}:{},...e.warnings&&e.warnings.length>0?{warnings:e.warnings}:{}}}function eV(e,t){try{return a.sync.read(e)}catch(e){throw new l("COMMAND_FAILED",`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}let eU=eW(process.env.AGENT_DEVICE_RETRY_LOGS);function eW(e){return["1","true","yes","on"].includes((e??"").trim().toLowerCase())}let eH={ios_boot:{startupMs:12e4,operationMs:2e4,totalMs:12e4},ios_runner_connect:{startupMs:12e4,operationMs:15e3,totalMs:12e4},android_boot:{startupMs:6e4,operationMs:1e4,totalMs:6e4}};class eJ{startedAtMs;expiresAtMs;constructor(e,t){this.startedAtMs=e,this.expiresAtMs=e+Math.max(0,t)}static fromTimeoutMs(e,t=Date.now()){return new eJ(t,e)}remainingMs(e=Date.now()){return Math.max(0,this.expiresAtMs-e)}elapsedMs(e=Date.now()){return Math.max(0,e-this.startedAtMs)}isExpired(e=Date.now()){return 0>=this.remainingMs(e)}}async function eq(e,t={},n={}){let r,i={maxAttempts:t.maxAttempts??3,baseDelayMs:t.baseDelayMs??200,maxDelayMs:t.maxDelayMs??2e3,jitter:t.jitter??.2,shouldRetry:t.shouldRetry};for(let t=1;t<=i.maxAttempts;t+=1){if(n.signal?.aborted)throw new l("COMMAND_FAILED","request canceled",{reason:"request_canceled"});if(n.deadline?.isExpired()&&t>1)break;try{let r=await e({attempt:t,maxAttempts:i.maxAttempts,deadline:n.deadline});return n.onEvent?.({phase:n.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs()}),eK({phase:n.phase,event:"succeeded",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs()}),r}catch(u){r=u;let e=n.classifyReason?.(u),a={phase:n.phase,event:"attempt_failed",attempt:t,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:e};if(n.onEvent?.(a),eK(a),t>=i.maxAttempts||i.shouldRetry&&!i.shouldRetry(u,t))break;let s=function(e,t,n,r){let i=Math.min(t,e*2**(r-1));return Math.max(0,i+i*n*(2*Math.random()-1))}(i.baseDelayMs,i.maxDelayMs,i.jitter,t),o=n.deadline?Math.min(s,n.deadline.remainingMs()):s;if(o<=0)break;let l={phase:n.phase,event:"retry_scheduled",attempt:t,maxAttempts:i.maxAttempts,delayMs:o,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:e};n.onEvent?.(l),eK(l),await function(e,t){return new Promise(n=>{if(t?.aborted)return void n();let r=!1,i=()=>{r||(r=!0,t&&t.removeEventListener("abort",s),n())},a=setTimeout(i,e);function s(){clearTimeout(a),i()}t&&t.addEventListener("abort",s,{once:!0})})}(o,n.signal)}}let a={phase:n.phase,event:"exhausted",attempt:i.maxAttempts,maxAttempts:i.maxAttempts,elapsedMs:n.deadline?.elapsedMs(),remainingMs:n.deadline?.remainingMs(),reason:n.classifyReason?.(r)};if(n.onEvent?.(a),eK(a),r)throw r;throw new l("COMMAND_FAILED","retry failed")}async function eX(e,t={}){return eq(()=>e(),{maxAttempts:t.attempts,baseDelayMs:t.baseDelayMs,maxDelayMs:t.maxDelayMs,jitter:t.jitter,shouldRetry:t.shouldRetry})}function eK(e){o({level:"attempt_failed"===e.event||"exhausted"===e.event?"warn":"debug",phase:"retry",data:{...e}}),eU&&process.stderr.write(`[agent-device][retry] ${JSON.stringify(e)}
2
- `)}export{eA as DEFAULT_BATCH_MAX_STEPS,eJ as Deadline,v as SESSION_SURFACES,x as SETTINGS_INVALID_ARGS_MESSAGE,w as SETTINGS_USAGE_OVERRIDE,eH as TIMEOUT_PROFILES,T as attachRefs,eE as buildAppIdentifiers,eL as buildDeviceIdentifiers,H as buildMobileSnapshotPresentation,$ as buildSnapshotDisplayLines,z as centerOfRect,eS as computeDaemonCodeSignature,F as containsPoint,eV as decodePng,D as displayLabel,k as displayNodeLabel,B as distanceFromSafeViewportBand,ed as expandUserHomePath,I as extractReadableText,P as findNodeByRef,Z as findProjectRoot,R as formatRole,N as formatSnapshotLine,y as getUnsupportedMacOsSettingMessage,es as isAgentDeviceDaemonProcess,eW as isEnvTruthy,b as isMacOsSettingSupported,J as isNodeVisibleInEffectiveViewport,er as isProcessAlive,U as isScrollableType,j as normalizeRef,_ as normalizeSnapshotTree,ew as normalizeTenantId,eD as parseBatchStepsJson,S as parseSessionSurface,G as pickLargestRect,et as readCommandMessage,ea as readProcessCommand,ei as readProcessStartTime,Y as readVersion,ev as resolveDaemonCodeSignature,em as resolveDaemonPaths,ef as resolveDaemonServerMode,eh as resolveDaemonTransportPreference,ej as resolveDeployResultTarget,q as resolveEffectiveViewportRect,ez as resolveInstallFromSourceResultTarget,eg as resolveSessionIsolationMode,ep as resolveUserPath,O as resolveViewportRect,eq as retryWithPolicy,eF as serializeCloseResult,eP as serializeDeployResult,ek as serializeDevice,eT as serializeEnsureSimulatorResult,eO as serializeInstallFromSourceResult,eB as serializeOpenResult,eC as serializeSessionListEntry,eG as serializeSnapshotResult,eu as stopProcessForTakeover,Q as successText,eR as validateAndNormalizeBatchSteps,el as waitForProcessExit,eX as withRetry,ee as withSuccessText};
package/dist/src/957.js DELETED
@@ -1,2 +0,0 @@
1
- import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r from"node:fs";import o from"node:os";import n from"node:path";let s=new e,a=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,i=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function c(){return t.randomBytes(8).toString("hex")}function u(e){let t=s.getStore();if(!t)return;let o={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?function e(t,r,o){if(null==t)return t;if("string"==typeof t){var n=t,s=o;let e=n.trim();if(!e)return n;if(s&&a.test(s)||i.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let c={};for(let[o,n]of Object.entries(t)){if(a.test(o)){c[o]="[REDACTED]";continue}c[o]=e(n,r,o)}return c}(e.data,new WeakSet):void 0};if(t.events.push(o),!t.debug)return;let n=`[agent-device][diag] ${JSON.stringify(o)}
2
- `;try{t.logPath&&r.appendFile(t.logPath,n,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,n,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(n)}catch{}}async function d(e,t,r){let o=Date.now();try{let n=await t();return u({level:"info",phase:e,durationMs:Date.now()-o,data:r}),n}catch(t){throw u({level:"error",phase:e,durationMs:Date.now()-o,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}class l extends Error{code;details;cause;constructor(e,t,r,o){super(t),this.code=e,this.details=r,this.cause=o}}function f(e){return e?.HOME?.trim()||o.homedir()}function p(e,t={}){return"~"===e?f(t.env):e.startsWith("~/")?n.join(f(t.env),e.slice(2)):e}function h(e,t={}){let r=p(e,t);return n.isAbsolute(r)?r:n.resolve(t.cwd??process.cwd(),r)}export{l as AppError,c as createRequestId,u as emitDiagnostic,p as expandUserHomePath,h as resolveUserPath,d as withDiagnosticTimer};