agent-device 0.11.11 → 0.11.13

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/320.js CHANGED
@@ -1 +1 @@
1
- let E="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL",N="AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN",A="AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL",R="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function O(E){let _=E.length;for(;_>0&&47===E.charCodeAt(_-1);)_-=1;return _===E.length?E:E.slice(0,_)}export{N as ENV_BEARER_TOKEN,R as ENV_LAUNCH_URL,A as ENV_LOCAL_BASE_URL,_ as ENV_SERVER_BASE_URL,E as METRO_COMPANION_RUN_ARG,O as normalizeBaseUrl};
1
+ let E="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL",e="AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN",A="AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL",N="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL",R="AGENT_DEVICE_METRO_COMPANION_STATE_PATH";function O(E){let _=E.length;for(;_>0&&47===E.charCodeAt(_-1);)_-=1;return _===E.length?E:E.slice(0,_)}function r(E,_){let e=new URL(`${O(E)}/index.bundle`);return e.searchParams.set("platform",_),e.searchParams.set("dev","true"),e.searchParams.set("minify","false"),e.toString()}export{e as ENV_BEARER_TOKEN,N as ENV_LAUNCH_URL,A as ENV_LOCAL_BASE_URL,_ as ENV_SERVER_BASE_URL,R as ENV_STATE_PATH,E as METRO_COMPANION_RUN_ARG,r as buildBundleUrl,O as normalizeBaseUrl};
package/dist/src/974.js CHANGED
@@ -1,2 +1,2 @@
1
- import e from"node:fs";import"node:fs/promises";import t from"node:path";import{spawn as r,spawnSync as n}from"node:child_process";import{createHash as o}from"node:crypto";import{fileURLToPath as i}from"node:url";import{resolveUserPath as a,AppError as s}from"./957.js";let l=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/;function u(e,t,r={}){let o=m(e),i=n(o,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:d(r.timeoutMs),shell:!1});if(i.error){let n=i.error.code;if("ETIMEDOUT"===n)throw new s("COMMAND_FAILED",`${o} timed out after ${d(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:d(r.timeoutMs)},i.error);if("ENOENT"===n)throw new s("TOOL_MISSING",`${o} not found in PATH`,{cmd:e},i.error);throw new s("COMMAND_FAILED",`Failed to run ${o}`,{cmd:e,args:t},i.error)}let a=r.binaryStdout?Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(i.stdout??""):void 0,l=r.binaryStdout?"":"string"==typeof i.stdout?i.stdout:(i.stdout??"").toString(),c="string"==typeof i.stderr?i.stderr:(i.stderr??"").toString(),p=i.status??1;if(0!==p&&!r.allowFailure)throw new s("COMMAND_FAILED",`${o} exited with code ${p}`,{cmd:e,args:t,stdout:l,stderr:c,exitCode:p,processExitError:!0});return{stdout:l,stderr:c,exitCode:p,stdoutBuffer:a}}function c(e,t,n={}){let o=r(m(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??"ignore",detached:!0,shell:!1});return o.unref(),o.pid??0}function m(e){var r;let n,o=(r={allowRelativePath:!0},!(n=e.trim())||n.includes("\0")?null:t.isAbsolute(n)?n:n.includes("/")||n.includes("\\")?r.allowRelativePath?n:null:l.test(n)?n:null);if(!o)throw new s("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return o}function d(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let p=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function f(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function h(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function g(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function y(e,t){let r;if(!f(e))return!1;if(t){let r=h(e);if(!r||r!==t)return!1}let n=g(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&p.some(e=>e.test(r))}function b(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 w(e,t){if(!f(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!f(e))return!0;return!f(e)}async function E(e,t){!y(e,t.expectedStartTime)||!b(e,"SIGTERM")||await w(e,t.termTimeoutMs)||b(e,"SIGKILL")&&await w(e,t.killTimeoutMs)}let S="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function M(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)}function P(e){return o("sha256").update(e).digest("hex")}function U(e){return e?.trim()?e.trim():void 0}function v(e,r){let n=t.join(e,".agent-device");if(!r)return{statePath:t.join(n,"metro-companion.json"),logPath:t.join(n,"metro-companion.log")};let o=P(r).slice(0,12),i=t.join(n,"metro-companion");return{statePath:t.join(i,`metro-companion-${o}.json`),logPath:t.join(i,`metro-companion-${o}.log`)}}function A(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));if(!Number.isInteger(r.pid)||0>=Number(r.pid)||"string"!=typeof r.serverBaseUrl||"string"!=typeof r.localBaseUrl||"string"!=typeof r.tokenHash||0===r.tokenHash.length)return null;let n=Array.isArray(r.consumers)?r.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(r.pid),startTime:"string"==typeof r.startTime?r.startTime:void 0,command:"string"==typeof r.command?r.command:void 0,serverBaseUrl:r.serverBaseUrl,localBaseUrl:r.localBaseUrl,launchUrl:U("string"==typeof r.launchUrl?r.launchUrl:void 0),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function N(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
2
- `,"utf8")}function T(t){try{e.unlinkSync(t)}catch{}}function k(e){return e.includes(S)}function I(e){return U(e.consumerKey)??U(e.profileKey)??null}function R(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function $(e){if(!f(e.pid))return;let t=g(e.pid);if(t&&k(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await w(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await w(e.pid,1e3)}}}async function x(r){let n=I(r),o=v(r.projectRoot,r.profileKey),a=A(o.statePath);if(a&&function(e,t){if(!f(e.pid))return!1;if(e.startTime){let t=h(e.pid);if(!t||t!==e.startTime)return!1}let r=g(e.pid);return!!r&&!!k(r)&&e.serverBaseUrl===M(t.serverBaseUrl)&&e.localBaseUrl===M(t.localBaseUrl)&&e.launchUrl===U(t.launchUrl)&&e.tokenHash===P(t.bearerToken)}(a,r)){let e=R(a,n);return e!==a&&N(o.statePath,e),{pid:a.pid,spawned:!1,statePath:o.statePath,logPath:o.logPath}}a&&(await $(a),T(o.statePath));let s=function(r,n){let o=function(){let r=i(import.meta.url),n=t.extname(r)||".js",o=t.join(t.dirname(r),`metro-companion${n}`);if(!e.existsSync(o))throw Error(`Metro companion entrypoint not found at ${o}. Rebuild the package to include the companion worker entry.`);return o}(),a=o.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(n),{recursive:!0});let s=e.openSync(n,"a"),l=0;try{let e;l=c(process.execPath,[...a,o,S],{env:(e={...r.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:M(r.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:r.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:M(r.localBaseUrl)},r.launchUrl?.trim()?e[_]=r.launchUrl.trim():delete e[_],e),stdio:["ignore",s,s]})}finally{e.closeSync(s)}if(!Number.isInteger(l)||l<=0)throw Error("Failed to start Metro companion process.");return{pid:l,startTime:h(l)??void 0,command:g(l)??void 0,serverBaseUrl:M(r.serverBaseUrl),localBaseUrl:M(r.localBaseUrl),launchUrl:U(r.launchUrl),tokenHash:P(r.bearerToken),consumers:[]}}(r,o.logPath);return N(o.statePath,R(s,n)),{pid:s.pid,spawned:!0,statePath:o.statePath,logPath:o.logPath}}async function D(e){let t=I(e),r=v(e.projectRoot,e.profileKey),n=A(r.statePath);if(!n)return T(r.statePath),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(N(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await $(n),T(r.statePath),{stopped:!0,statePath:r.statePath})}function O(e){return"string"==typeof e&&e.trim()?M(e.trim()):""}function C(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function B(e,t,r){return a(e,{env:t,cwd:r})}function j(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function L(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function F(e,t){let r;return{platform:t,bundleUrl:((r=new URL(`${M(e)}/index.bundle`)).searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString())}}function G(e,t){return{platform:t,metroHost:C(e?.metro_host),metroPort:e?.metro_port,bundleUrl:C(e?.metro_bundle_url),launchUrl:C(e?.launch_url)}}async function H(e){await new Promise(t=>setTimeout(t,e))}async function K(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function V(e,t){try{let r=await K(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function J(e,t){let r=Error(e);return r.retryable=t,r}async function q(e){var t,r,n,o;let i;try{i=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw J(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw J(t instanceof Error?t.message:String(t),!0)}let a=await i.text(),s=a?JSON.parse(a):{};if(!i.ok)throw J(`/api/metro/bridge failed (${i.status}): ${JSON.stringify(s)}`,(n=i.status,!!(n>=500||408===n||425===n||429===n||JSON.stringify(s).includes("Metro companion is not connected"))));return{enabled:(o=s.data??s).enabled,baseUrl:o.base_url,statusUrl:o.status_url,bundleUrl:o.bundle_url,iosRuntime:G(o.ios_runtime,"ios"),androidRuntime:G(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url,host:o.upstream.host,port:o.upstream.port,statusUrl:o.upstream.status_url},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function z(e,t,r,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function Z(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await V(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await H(o)}return!1}async function W(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await q({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await H(o)}throw Error(z(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function X(r={}){let n=r.env??process.env,o=process.cwd(),i=B(r.projectRoot??o,n,o),a=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!j(n))throw new s("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(i,r.kind??"auto"),l=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new s("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(r.metroPort??8081),m=C(r.listenHost)??"0.0.0.0",d=C(r.statusHost)??"127.0.0.1",p=O(r.publicBaseUrl),f=L(r.startupTimeoutMs,18e4,3e4),h=L(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?B(r.runtimeFilePath,n,o):null,w=B(r.logPath??t.join(i,".agent-device","metro.log"),n,o);if(!p)throw new s("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,t){if(e&&!t)throw new s("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new s("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(O(r.proxyBaseUrl),C(r.proxyBearerToken)??""),M=y?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let o=j(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:j(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return u(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(i,n):{installed:!1},P=`http://${d}:${l}/status`,U=!1,v=!1,A=0;if(g&&await V(P,h))v=!0;else if(U=!0,A=function(r,n,o,i,a,s){let l="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(t.dirname(a),{recursive:!0});let u=e.openSync(a,"a"),m=0;try{m=c(l.command,l.installArgs,{cwd:r,env:s,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(i,a,l,m,w,n).pid,!await Z(P,f,h))throw Error(`Metro did not become ready at ${P} within ${f}ms. Check ${w}.`);let N=F(p,"ios"),T=F(p,"android"),k=null,I=null;if(E)try{k=await q({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},timeoutMs:h})}catch(e){I=e instanceof Error?e.message:String(e)}if(E&&(!k||!1===k.probe.reachable)){let e;try{e=(await x({projectRoot:i,serverBaseUrl:S,bearerToken:_,localBaseUrl:`http://${d}:${l}`,launchUrl:C(r.launchUrl),profileKey:C(r.companionProfileKey),consumerKey:C(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(z(S,e instanceof Error?e.message:String(e),k,I))}try{k=await W({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:I,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let R=k?.iosRuntime??N,$=k?.androidRuntime??T,D={projectRoot:i,kind:a,dependenciesInstalled:M.installed,packageManager:M.packageManager??null,started:U,reused:v,pid:A,logPath:w,statusUrl:P,runtimeFilePath:b,iosRuntime:R,androidRuntime:$,bridge:k};return b&&(e.mkdirSync(t.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(D,null,2))),D}export{F as buildMetroRuntimeHints,x as ensureMetroCompanion,y as isAgentDeviceDaemonProcess,X as prepareMetroRuntime,c as runCmdDetached,u as runCmdSync,D as stopMetroCompanion,E as stopProcessForTakeover};
1
+ import e from"node:fs";import"node:fs/promises";import t from"node:path";import{spawn as r,spawnSync as n}from"node:child_process";import{createHash as o}from"node:crypto";import{fileURLToPath as i}from"node:url";import{resolveUserPath as a,AppError as s}from"./957.js";let l=/^[A-Za-z0-9][A-Za-z0-9._+-]*$/;function u(e,t,r={}){let o=m(e),i=n(o,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:d(r.timeoutMs),shell:!1});if(i.error){let n=i.error.code;if("ETIMEDOUT"===n)throw new s("COMMAND_FAILED",`${o} timed out after ${d(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:d(r.timeoutMs)},i.error);if("ENOENT"===n)throw new s("TOOL_MISSING",`${o} not found in PATH`,{cmd:e},i.error);throw new s("COMMAND_FAILED",`Failed to run ${o}`,{cmd:e,args:t},i.error)}let a=r.binaryStdout?Buffer.isBuffer(i.stdout)?i.stdout:Buffer.from(i.stdout??""):void 0,l=r.binaryStdout?"":"string"==typeof i.stdout?i.stdout:(i.stdout??"").toString(),c="string"==typeof i.stderr?i.stderr:(i.stderr??"").toString(),p=i.status??1;if(0!==p&&!r.allowFailure)throw new s("COMMAND_FAILED",`${o} exited with code ${p}`,{cmd:e,args:t,stdout:l,stderr:c,exitCode:p,processExitError:!0});return{stdout:l,stderr:c,exitCode:p,stdoutBuffer:a}}function c(e,t,n={}){let o=r(m(e),t,{cwd:n.cwd,env:n.env,stdio:n.stdio??"ignore",detached:!0,shell:!1});return o.unref(),o.pid??0}function m(e){var r;let n,o=(r={allowRelativePath:!0},!(n=e.trim())||n.includes("\0")?null:t.isAbsolute(n)?n:n.includes("/")||n.includes("\\")?r.allowRelativePath?n:null:l.test(n)?n:null);if(!o)throw new s("INVALID_ARGS",`Invalid executable command: ${JSON.stringify(e)}`,{cmd:e});return o}function d(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let p=[/(^|[/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[/\s"'=])src\/daemon\.ts($|[\s"'])/];function f(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function h(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function g(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=u("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function y(e,t){let r;if(!f(e))return!1;if(t){let r=h(e);if(!r||r!==t)return!1}let n=g(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&p.some(e=>e.test(r))}function b(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 w(e,t){if(!f(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!f(e))return!0;return!f(e)}async function E(e,t){!y(e,t.expectedStartTime)||!b(e,"SIGTERM")||await w(e,t.termTimeoutMs)||b(e,"SIGKILL")&&await w(e,t.killTimeoutMs)}let S="--agent-device-run-metro-companion",_="AGENT_DEVICE_METRO_COMPANION_LAUNCH_URL";function M(e){let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)}function P(e,t){let r=new URL(`${M(e)}/index.bundle`);return r.searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString()}let U="metro-companion";function A(e){return o("sha256").update(e).digest("hex")}function v(e){return e?.trim()?e.trim():void 0}function N(e,r){let n=t.join(e,".agent-device");if(!r)return{statePath:t.join(n,"metro-companion.json"),logPath:t.join(n,"metro-companion.log")};let o=A(r).slice(0,12),i=t.join(n,U);return{statePath:t.join(i,`metro-companion-${o}.json`),logPath:t.join(i,`metro-companion-${o}.log`)}}function T(t){try{let r=JSON.parse(e.readFileSync(t,"utf8"));if(!Number.isInteger(r.pid)||0>=Number(r.pid)||"string"!=typeof r.serverBaseUrl||"string"!=typeof r.localBaseUrl||"string"!=typeof r.tokenHash||0===r.tokenHash.length)return null;let n=Array.isArray(r.consumers)?r.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(r.pid),startTime:"string"==typeof r.startTime?r.startTime:void 0,command:"string"==typeof r.command?r.command:void 0,serverBaseUrl:r.serverBaseUrl,localBaseUrl:r.localBaseUrl,launchUrl:v("string"==typeof r.launchUrl?r.launchUrl:void 0),tokenHash:r.tokenHash,consumers:n}}catch{return null}}function I(r,n){e.mkdirSync(t.dirname(r),{recursive:!0}),e.writeFileSync(r,`${JSON.stringify(n,null,2)}
2
+ `,"utf8")}function k(t){try{let r=e.readdirSync(t);0===r.length&&e.rmdirSync(t)}catch{}}function R(r){let n=t.dirname(r.statePath),o=t.dirname(r.logPath);var i=r.statePath;try{e.unlinkSync(i)}catch{}var a=r.logPath;try{e.unlinkSync(a)}catch{}k(n),o!==n&&k(o),t.basename(n)===U&&k(t.dirname(n))}function $(e){return e.includes(S)}function O(e){return v(e.consumerKey)??v(e.profileKey)??null}function C(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function D(e){if(!f(e.pid))return;let t=g(e.pid);if(t&&$(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await w(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await w(e.pid,1e3)}}}async function x(r){let n=O(r),o=N(r.projectRoot,r.profileKey),a=T(o.statePath);if(a&&function(e,t){if(!f(e.pid))return!1;if(e.startTime){let t=h(e.pid);if(!t||t!==e.startTime)return!1}let r=g(e.pid);return!!r&&!!$(r)&&e.serverBaseUrl===M(t.serverBaseUrl)&&e.localBaseUrl===M(t.localBaseUrl)&&e.launchUrl===v(t.launchUrl)&&e.tokenHash===A(t.bearerToken)}(a,r)){let e=C(a,n);return e!==a&&I(o.statePath,e),{pid:a.pid,spawned:!1,statePath:o.statePath,logPath:o.logPath}}a&&(await D(a),R(o));let s=function(r,n){let o=function(){let r=i(import.meta.url),n=t.extname(r)||".js",o=t.join(t.dirname(r),`metro-companion${n}`);if(!e.existsSync(o))throw Error(`Metro companion entrypoint not found at ${o}. Rebuild the package to include the companion worker entry.`);return o}(),a=o.endsWith(".ts")?["--experimental-strip-types"]:[];e.mkdirSync(t.dirname(n),{recursive:!0});let s=e.openSync(n,"a"),l=0;try{let e;l=c(process.execPath,[...a,o,S],{env:(e={...r.env??process.env,AGENT_DEVICE_METRO_COMPANION_SERVER_BASE_URL:M(r.serverBaseUrl),AGENT_DEVICE_METRO_COMPANION_BEARER_TOKEN:r.bearerToken,AGENT_DEVICE_METRO_COMPANION_LOCAL_BASE_URL:M(r.localBaseUrl),AGENT_DEVICE_METRO_COMPANION_STATE_PATH:N(r.projectRoot,r.profileKey).statePath},r.launchUrl?.trim()?e[_]=r.launchUrl.trim():delete e[_],e),stdio:["ignore",s,s]})}finally{e.closeSync(s)}if(!Number.isInteger(l)||l<=0)throw Error("Failed to start Metro companion process.");return{pid:l,startTime:h(l)??void 0,command:g(l)??void 0,serverBaseUrl:M(r.serverBaseUrl),localBaseUrl:M(r.localBaseUrl),launchUrl:v(r.launchUrl),tokenHash:A(r.bearerToken),consumers:[]}}(r,o.logPath);return I(o.statePath,C(s,n)),{pid:s.pid,spawned:!0,statePath:o.statePath,logPath:o.logPath}}async function B(e){let t=O(e),r=N(e.projectRoot,e.profileKey),n=T(r.statePath);if(!n)return R(r),{stopped:!1,statePath:r.statePath};let o=t?{...n,consumers:n.consumers.filter(e=>e!==t)}:{...n,consumers:[]};return o.consumers.length>0?(I(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await D(n),R(r),{stopped:!0,statePath:r.statePath})}function j(e){return"string"==typeof e&&e.trim()?M(e.trim()):""}function L(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function F(e,t,r){return a(e,{env:t,cwd:r})}function G(t){try{return e.accessSync(t,e.constants.F_OK),!0}catch{return!1}}function H(e,t,r){if(null==e||""===e)return t;let n=Number.parseInt(String(e),10);return Number.isInteger(n)?Math.max(n,r):t}function K(e,t){return{platform:t,bundleUrl:P(e,t)}}function V(e,t){return{platform:t,metroHost:L(e?.metro_host),metroPort:e?.metro_port,bundleUrl:L(e?.metro_bundle_url),launchUrl:L(e?.launch_url)}}async function J(e){await new Promise(t=>setTimeout(t,e))}async function q(e,t,r={}){try{let n=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:n.ok,status:n.status,body:await n.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function z(e,t){try{let r=await q(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function Z(e,t){let r=Error(e);return r.retryable=t,r}async function W(e){var t,r,n,o;let i;try{i=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw Z(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw Z(t instanceof Error?t.message:String(t),!0)}let a=await i.text(),s=a?JSON.parse(a):{};if(!i.ok)throw Z(`/api/metro/bridge failed (${i.status}): ${JSON.stringify(s)}`,(n=i.status,!!(n>=500||408===n||425===n||429===n||JSON.stringify(s).includes("Metro companion is not connected"))));return{enabled:(o=s.data??s).enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:V(o.ios_runtime,"ios"),androidRuntime:V(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function X(e,t,r,n,o){let i=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&i.push(`bridgeError=${t}`),r?.probe.reachable===!1&&i.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),n&&n!==t&&i.push(`initialBridgeError=${n}`),o&&i.push(`metroCompanionLog=${o}`),i.join(" ")}async function Y(e,t,r){let n=Date.now()+t;for(;Date.now()<n;){let t=Math.min(r,Math.max(n-Date.now(),1));if(await z(e,t))return!0;let o=Math.min(500,Math.max(n-Date.now(),0));o>0&&await J(o)}return!1}async function Q(e){let t=Date.now()+e.startupTimeoutMs,r=null,n=null;for(;Date.now()<t;){try{let t=await W({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,n=null}catch(e){if(n=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await J(o)}throw Error(X(e.baseUrl,n,r,e.initialBridgeError,e.companionLogPath))}async function ee(r={}){let n=r.env??process.env,o=process.cwd(),i=F(r.projectRoot??o,n,o),a=function(r,n){if("auto"!==n)return n;let o=function(r){let n=t.join(r,"package.json");if(!G(n))throw new s("INVALID_ARGS",`package.json not found at ${n}`);return JSON.parse(e.readFileSync(n,"utf8"))}(r);return"string"==typeof({...o.dependencies??{},...o.devDependencies??{}}).expo?"expo":"react-native"}(i,r.kind??"auto"),l=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new s("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(r.metroPort??8081),m=L(r.listenHost)??"0.0.0.0",d=L(r.statusHost)??"127.0.0.1",p=j(r.publicBaseUrl),f=H(r.startupTimeoutMs,18e4,3e4),h=H(r.probeTimeoutMs,1e4,1e3),g=r.reuseExisting??!0,y=r.installDependenciesIfNeeded??!0,b=r.runtimeFilePath?F(r.runtimeFilePath,n,o):null,w=F(r.logPath??t.join(i,".agent-device","metro.log"),n,o);if(!p)throw new s("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:E,proxyBaseUrl:S,proxyBearerToken:_}=function(e,t){if(e&&!t)throw new s("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new s("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(j(r.proxyBaseUrl),L(r.proxyBearerToken)??""),M=y?function(r,n){if(function(t){try{return e.statSync(t).isDirectory()}catch{return!1}}(t.join(r,"node_modules")))return{installed:!1};let o=G(t.join(r,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:G(t.join(r,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return u(o.command,o.installArgs,{cwd:r,env:n}),{installed:!0,packageManager:o.command}}(i,n):{installed:!1},P=`http://${d}:${l}/status`,U=!1,A=!1,v=0;if(g&&await z(P,h))A=!0;else if(U=!0,v=function(r,n,o,i,a,s){let l="expo"===n?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(o)]}:{command:"npx",installArgs:["react-native","start","--host",i,"--port",String(o)]};e.mkdirSync(t.dirname(a),{recursive:!0});let u=e.openSync(a,"a"),m=0;try{m=c(l.command,l.installArgs,{cwd:r,env:s,stdio:["ignore",u,u]})}finally{e.closeSync(u)}if(!Number.isInteger(m)||m<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:m}}(i,a,l,m,w,n).pid,!await Y(P,f,h))throw Error(`Metro did not become ready at ${P} within ${f}ms. Check ${w}.`);let N=K(p,"ios"),T=K(p,"android"),I=null,k=null;if(E)try{I=await W({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},timeoutMs:h})}catch(e){k=e instanceof Error?e.message:String(e)}if(E&&(!I||!1===I.probe.reachable)){let e;try{e=(await x({projectRoot:i,serverBaseUrl:S,bearerToken:_,localBaseUrl:`http://${d}:${l}`,launchUrl:L(r.launchUrl),profileKey:L(r.companionProfileKey),consumerKey:L(r.companionConsumerKey),env:n})).logPath}catch(e){throw Error(X(S,e instanceof Error?e.message:String(e),I,k))}try{I=await Q({baseUrl:S,bearerToken:_,runtime:{metro_bundle_url:N.bundleUrl},probeTimeoutMs:h,startupTimeoutMs:f,initialBridgeError:k,companionLogPath:e})}catch(e){throw e instanceof Error?e:Error(String(e))}}let R=I?.iosRuntime??N,$=I?.androidRuntime??T,O={projectRoot:i,kind:a,dependenciesInstalled:M.installed,packageManager:M.packageManager??null,started:U,reused:A,pid:v,logPath:w,statusUrl:P,runtimeFilePath:b,iosRuntime:R,androidRuntime:$,bridge:I};return b&&(e.mkdirSync(t.dirname(b),{recursive:!0}),e.writeFileSync(b,JSON.stringify(O,null,2))),O}export{P as buildBundleUrl,K as buildMetroRuntimeHints,x as ensureMetroCompanion,y as isAgentDeviceDaemonProcess,M as normalizeBaseUrl,ee as prepareMetroRuntime,c as runCmdDetached,u as runCmdSync,B as stopMetroCompanion,E as stopProcessForTakeover};
package/dist/src/bin.js CHANGED
@@ -1,7 +1,7 @@
1
- let e,t,r,s,o,a,n;import i from"node:path";import{styleText as l}from"node:util";import{fileURLToPath as u,pathToFileURL as p}from"node:url";import d from"node:net";import c from"node:http";import m from"node:https";import f,{promises as h}from"node:fs";import{spawn as g}from"node:child_process";import{createHash as y}from"node:crypto";import b from"node:os";import{PNG as w}from"pngjs";import{SESSION_SURFACES as v,readProcessCommand as k,waitForProcessExit as D,serializeSessionListEntry as I,serializeSnapshotResult as A,isAgentDeviceDaemonProcess as S,buildDeviceIdentifiers as $,buildAppIdentifiers as P,parseBatchStepsJson as E,computeDaemonCodeSignature as L,resolveDaemonTransportPreference as N,serializeOpenResult as _,expandUserHomePath as x,serializeDeployResult as T,readCommandMessage as M,serializeEnsureSimulatorResult as R,serializeDevice as O,buildSnapshotDisplayLines as C,buildMobileSnapshotPresentation as U,readVersion as F,findProjectRoot as j,resolveUserPath as V,serializeCloseResult as B,SETTINGS_USAGE_OVERRIDE as G,isProcessAlive as q,readProcessStartTime as H,resolveDaemonPaths as K,resolveDaemonServerMode as J,serializeInstallFromSourceResult as z,decodePng as W,stopProcessForTakeover as X,formatSnapshotLine as Y}from"./995.js";import{createRequestId as Z,asAppError as Q,normalizeError as ee,runCmdDetached as et,withDiagnosticsScope as er,AppError as es,getDiagnosticsMeta as eo,runCmdSync as ea,flushDiagnosticsToSessionFile as en,withDiagnosticTimer as ei,emitDiagnostic as el}from"./818.js";import{METRO_COMPANION_RUN_ARG as eu,ENV_LAUNCH_URL as ep,normalizeBaseUrl as ed,ENV_BEARER_TOKEN as ec,ENV_SERVER_BASE_URL as em,ENV_LOCAL_BASE_URL as ef}from"./320.js";import{maybeRunUpgradeNotifier as eh}from"./113.js";function eg(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&(e[r]=s);return e}let ey=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],eb=["snapshotDepth","snapshotScope","snapshotRaw"],ew=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:v,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"maxScrolls",names:["--max-scrolls"],type:"int",min:1,max:200,usageLabel:"--max-scrolls <n>",usageDescription:"scrollintoview: cap the number of scroll gestures before failing"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],ev=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),ek={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",positionalArgs:[],allowedFlags:["snapshotDiff",...ey]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...ey,"baseline","threshold","out"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",listUsageOverride:"metro prepare --public-base-url <url>",helpDescription:"Prepare a local Metro runtime and optionally bridge it through a remote host",summary:"Prepare local Metro runtime",positionalArgs:["prepare"],allowedFlags:["metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss the device keyboard",summary:"Inspect or dismiss the device keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics",summary:"Show performance metrics",positionalArgs:[],allowedFlags:[]},back:{usageOverride:"back [--in-app|--system]",helpDescription:"Navigate back with explicit app or system semantics",summary:"Go back",positionalArgs:[],allowedFlags:["backMode"]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",summary:"Rotate device orientation",positionalArgs:["orientation"],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...eb]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",helpDescription:"Inspect or handle alert (iOS simulator and macOS desktop)",summary:"Inspect or handle iOS/macOS alerts",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",helpDescription:"Tap/click by coordinates, snapshot ref, or selector",summary:"Tap by coordinates, ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap","clickButton",...eb]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return element text/attributes by ref or selector",summary:"Get text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...eb]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},test:{usageOverride:"test <path-or-glob>...",listUsageOverride:"test <path-or-glob>...",helpDescription:"Run one or more .ad scripts as a serial test suite",summary:"Run .ad test suites",positionalArgs:["pathOrGlob"],allowsExtraPositionals:!0,allowedFlags:["replayUpdate","failFast","timeoutMs","retries","artifactsDir","reportJunit"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",summary:"Press by coordinates, ref, or selector",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...eb]},longpress:{helpDescription:"Long press by coordinates (iOS and Android)",summary:"Long press by coordinates",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",summary:"Swipe coordinates",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{helpDescription:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{helpDescription:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:["delayMs"]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",helpDescription:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...eb,"delayMs"]},scroll:{usageOverride:"scroll <direction> [amount] [--pixels <n>]",helpDescription:"Scroll in direction (relative amount or explicit pixels)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:["pixels"]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",helpDescription:"Scroll until text appears or a snapshot ref is brought into view",summary:"Scroll until text or ref is visible",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["maxScrolls"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...eb]},settings:{usageOverride:G,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, appearance, and app permissions (macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location remain unsupported on macOS; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",helpDescription:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},eD=new Map,eI=new Map;for(let e of ew){for(let t of e.names)eD.set(t,e);let t=eI.get(e.key);t?t.push(e):eI.set(e.key,[e])}function eA(e){if(e)return ek[e]}function eS(){return Object.keys(ek)}function e$(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let eP=(e=`agent-device <command> [args] [--json]
1
+ let e,t,r,s,o,a,n;import i from"node:path";import{styleText as l}from"node:util";import{fileURLToPath as u,pathToFileURL as p}from"node:url";import d from"node:net";import c from"node:http";import m from"node:https";import f,{promises as h}from"node:fs";import{spawn as g}from"node:child_process";import{createHash as y}from"node:crypto";import b from"node:os";import{PNG as w}from"pngjs";import{SESSION_SURFACES as v,readProcessCommand as k,waitForProcessExit as D,serializeSessionListEntry as I,serializeSnapshotResult as A,isAgentDeviceDaemonProcess as S,buildDeviceIdentifiers as $,buildAppIdentifiers as P,parseBatchStepsJson as E,computeDaemonCodeSignature as L,resolveDaemonTransportPreference as N,serializeOpenResult as _,expandUserHomePath as x,serializeDeployResult as T,readCommandMessage as M,serializeEnsureSimulatorResult as R,serializeDevice as O,buildSnapshotDisplayLines as C,buildMobileSnapshotPresentation as U,readVersion as F,findProjectRoot as j,resolveUserPath as V,serializeCloseResult as B,SETTINGS_USAGE_OVERRIDE as G,isProcessAlive as q,readProcessStartTime as H,resolveDaemonPaths as K,resolveDaemonServerMode as J,serializeInstallFromSourceResult as z,decodePng as W,stopProcessForTakeover as X,formatSnapshotLine as Y}from"./995.js";import{createRequestId as Z,asAppError as Q,normalizeError as ee,runCmdDetached as et,withDiagnosticsScope as er,AppError as es,getDiagnosticsMeta as eo,runCmdSync as ea,flushDiagnosticsToSessionFile as en,withDiagnosticTimer as ei,emitDiagnostic as el}from"./818.js";import{METRO_COMPANION_RUN_ARG as eu,normalizeBaseUrl as ep,buildBundleUrl as ed,ENV_SERVER_BASE_URL as ec,ENV_LOCAL_BASE_URL as em,ENV_STATE_PATH as ef,ENV_LAUNCH_URL as eh,ENV_BEARER_TOKEN as eg}from"./320.js";import{maybeRunUpgradeNotifier as ey}from"./113.js";function eb(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&(e[r]=s);return e}let ew=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],ev=["snapshotDepth","snapshotScope","snapshotRaw"],ek=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","linux","apple"],usageLabel:"--platform ios|macos|android|linux|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:v,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"delayMs",names:["--delay-ms"],type:"int",min:0,max:1e4,usageLabel:"--delay-ms <ms>",usageDescription:"Delay between typed characters"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"pixels",names:["--pixels"],type:"int",min:1,max:1e5,usageLabel:"--pixels <n>",usageDescription:"Scroll: explicit gesture distance in pixels"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"backMode",names:["--in-app"],type:"enum",enumValues:["in-app","system"],setValue:"in-app",usageLabel:"--in-app",usageDescription:"Back: use app-provided back UI when available"},{key:"backMode",names:["--system"],type:"enum",enumValues:["in-app","system"],setValue:"system",usageLabel:"--system",usageDescription:"Back: use system back input or gesture when available"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"maxScrolls",names:["--max-scrolls"],type:"int",min:1,max:200,usageLabel:"--max-scrolls <n>",usageDescription:"scrollintoview: cap the number of scroll gestures before failing"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"snapshotDiff",names:["--diff"],type:"boolean",usageLabel:"--diff",usageDescription:"Snapshot: show structural diff against the previous session baseline"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"networkInclude",names:["--include"],type:"enum",enumValues:["summary","headers","body","all"],usageLabel:"--include summary|headers|body|all",usageDescription:"Network: include headers, bodies, or both in output"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"failFast",names:["--fail-fast"],type:"boolean",usageLabel:"--fail-fast",usageDescription:"Test: stop the suite after the first failing script"},{key:"timeoutMs",names:["--timeout"],type:"int",min:1,usageLabel:"--timeout <ms>",usageDescription:"Test: maximum wall-clock time per script attempt"},{key:"retries",names:["--retries"],type:"int",min:0,max:3,usageLabel:"--retries <n>",usageDescription:"Test: retry each failed script up to n additional times"},{key:"artifactsDir",names:["--artifacts-dir"],type:"string",usageLabel:"--artifacts-dir <path>",usageDescription:"Test: root directory for suite artifacts"},{key:"reportJunit",names:["--report-junit"],type:"string",usageLabel:"--report-junit <path>",usageDescription:"Test: write a JUnit XML report for the replay suite"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"findFirst",names:["--first"],type:"boolean",usageLabel:"--first",usageDescription:"Find: pick the first match when ambiguous"},{key:"findLast",names:["--last"],type:"boolean",usageLabel:"--last",usageDescription:"Find: pick the last match when ambiguous"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"overlayRefs",names:["--overlay-refs"],type:"boolean",usageLabel:"--overlay-refs",usageDescription:"Screenshot: draw current snapshot refs and target rectangles onto the saved PNG"},{key:"screenshotFullscreen",names:["--fullscreen"],type:"boolean",usageLabel:"--fullscreen",usageDescription:"Screenshot: capture the full screen instead of the app window"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],eD=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),eI={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{usageOverride:"snapshot [--diff] [-i] [-c] [-d <depth>] [-s <scope>] [--raw]",helpDescription:"Capture accessibility tree or diff against the previous session baseline",positionalArgs:[],allowedFlags:["snapshotDiff",...ew]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...ew,"baseline","threshold","out"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",listUsageOverride:"metro prepare --public-base-url <url>",helpDescription:"Prepare a local Metro runtime and optionally bridge it through a remote host",summary:"Prepare local Metro runtime",positionalArgs:["prepare"],allowedFlags:["metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss the device keyboard",summary:"Inspect or dismiss the device keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics",summary:"Show performance metrics",positionalArgs:[],allowedFlags:[]},back:{usageOverride:"back [--in-app|--system]",helpDescription:"Navigate back with explicit app or system semantics",summary:"Go back",positionalArgs:[],allowedFlags:["backMode"]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},rotate:{usageOverride:"rotate <portrait|portrait-upside-down|landscape-left|landscape-right>",helpDescription:"Rotate device orientation on iOS and Android",summary:"Rotate device orientation",positionalArgs:["orientation"],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...ev]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",helpDescription:"Inspect or handle alert (iOS simulator and macOS desktop)",summary:"Inspect or handle iOS/macOS alerts",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",helpDescription:"Tap/click by coordinates, snapshot ref, or selector",summary:"Tap by coordinates, ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap","clickButton",...ev]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return element text/attributes by ref or selector",summary:"Get text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...ev]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},test:{usageOverride:"test <path-or-glob>...",listUsageOverride:"test <path-or-glob>...",helpDescription:"Run one or more .ad scripts as a serial test suite",summary:"Run .ad test suites",positionalArgs:["pathOrGlob"],allowsExtraPositionals:!0,allowedFlags:["replayUpdate","failFast","timeoutMs","retries","artifactsDir","reportJunit"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",summary:"Press by coordinates, ref, or selector",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...ev]},longpress:{helpDescription:"Long press by coordinates (iOS and Android)",summary:"Long press by coordinates",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",summary:"Swipe coordinates",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{helpDescription:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{helpDescription:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:["delayMs"]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",helpDescription:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...ev,"delayMs"]},scroll:{usageOverride:"scroll <direction> [amount] [--pixels <n>]",helpDescription:"Scroll in direction (relative amount or explicit pixels)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:["pixels"]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",helpDescription:"Scroll until text appears or a snapshot ref is brought into view",summary:"Scroll until text or ref is visible",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["maxScrolls"]},pinch:{helpDescription:"Pinch/zoom gesture (Apple simulator or macOS app session)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot (macOS app sessions default to the app window; use --fullscreen for full desktop, or --overlay-refs to annotate the image with current refs)",positionalArgs:["path?"],allowedFlags:["out","overlayRefs","screenshotFullscreen"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] [--include summary|headers|body|all] | network log [limit] [summary|headers|body|all] [--include summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:["networkInclude"]},find:{usageOverride:"find <locator|text> <action> [value] [--first|--last]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw","findFirst","findLast"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...ev]},settings:{usageOverride:G,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, appearance, and app permissions (macOS supports only settings appearance <light|dark|toggle> and settings permission <grant|reset> <accessibility|screen-recording|input-monitoring>; wifi|airplane|location remain unsupported on macOS; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",helpDescription:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},eA=new Map,eS=new Map;for(let e of ek){for(let t of e.names)eA.set(t,e);let t=eS.get(e.key);t?t.push(e):eS.set(e.key,[e])}function e$(e){if(e)return eI[e]}function eP(){return Object.keys(eI)}function eE(e){let t=e.endsWith("?"),r=t?e.slice(0,-1):e;return t?`[${r}]`:`<${r}>`}let eL=(e=`agent-device <command> [args] [--json]
2
2
 
3
3
  CLI to control iOS and Android devices for AI agents.
4
- `,t=eN("Commands:",eS().map(e=>{let t=ek[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let r=t.positionalArgs.map(r=>{var s,o,a;let n,i,l,u;return s=e,o=t,i=(n=(a=r).endsWith("?"))?a.slice(0,-1):a,u=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==o.usageOverride&&o.usageOverride.startsWith(`${s} ${i}`),n?l?`[${i}]`:u?i:`[${i}]`:u?i:`<${i}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=eL("Flags:",eE(ev)),s=[eN("Agent Skills:",[{label:"agent-device",description:"Canonical mobile automation flows"},{label:"dogfood",description:"Exploratory QA and bug hunts"}]),"See `skills/<name>/SKILL.md` in the installed package."].join("\n\n"),o=e_("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),a=eN("Environment:",[{label:"AGENT_DEVICE_SESSION",description:"Default session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"}]),n=e_("Examples:",["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"]),`${e}
4
+ `,t=ex("Commands:",eP().map(e=>{let t=eI[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let r=t.positionalArgs.map(r=>{var s,o,a;let n,i,l,u;return s=e,o=t,i=(n=(a=r).endsWith("?"))?a.slice(0,-1):a,u=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(i))||void 0!==o.usageOverride&&o.usageOverride.startsWith(`${s} ${i}`),n?l?`[${i}]`:u?i:`[${i}]`:u?i:`<${i}>`});return[e,...r].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),r=e_("Flags:",eN(eD)),s=[ex("Agent Skills:",[{label:"agent-device",description:"Canonical mobile automation flows"},{label:"dogfood",description:"Exploratory QA and bug hunts"}]),"See `skills/<name>/SKILL.md` in the installed package."].join("\n\n"),o=eT("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),a=ex("Environment:",[{label:"AGENT_DEVICE_SESSION",description:"Default session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"}]),n=eT("Examples:",["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad","agent-device test ./suite --platform android"]),`${e}
5
5
  ${t}
6
6
 
7
7
  ${r}
@@ -13,45 +13,45 @@ ${o}
13
13
  ${a}
14
14
 
15
15
  ${n}
16
- `);function eE(e){return ew.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function eL(e,t){return eN(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function eN(e,t){if(0===t.length)return`${e}
17
- (none)`;let r=Math.max(...t.map(e=>e.label.length))+2,s=[e];for(let e of t)s.push(` ${e.label.padEnd(r)}${e.description}`);return s.join("\n")}function e_(e,t){return 0===t.length?`${e}
18
- (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let ex=new Set(["1","true","yes","on"]),eT=new Set(["0","false","no","off"]);function eM(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function eR(e,t,r,s){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>eR({...e,multiple:!1},t,r,s));if("boolean"===e.type){var o=t,a=r,n=s;if("boolean"==typeof o)return o;if("string"==typeof o){let e=eO(o);if(void 0!==e)return e}throw new es("INVALID_ARGS",`Invalid value for "${n}" in ${a}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==eO(t))return eO(t);if("string"==typeof t&&t.trim().length>0)return t;throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var i=e,l=t,u=r,p=s;let o=i.setValue;if(l===o)return o;if("string"==typeof l){let e=l.trim();if(""===e||"true"===e||"1"===e)return o;if("false"===e||"0"===e)return}if(!0===l)return o;if(!1!==l)throw new es("INVALID_ARGS",`Invalid value for "${p}" in ${u}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let d="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(d)||!Number.isInteger(d))throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected integer.`);if("number"==typeof e.min&&d<e.min)throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&d>e.max)throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Must be <= ${e.max}.`);return d}function eO(e){let t=e.trim().toLowerCase();return!!ex.has(t)||!eT.has(t)&&void 0}let eC=new Set(["config","remoteConfig","help","version","batchSteps"]),eU={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eF=function(){let e=new Map;for(let t of ew){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of ev)t.set(e,new Set(["*"]));for(let e of eS()){let r=eA(e);if(r)for(let s of r.allowedFlags){let r=t.get(s);r&&r.has("*")||(r?r.add(e):t.set(s,new Set([e])))}}return[...e.entries()].map(([e,r])=>({key:e,flagDefinitions:r,config:{enabled:!eC.has(e),key:e},env:{names:[eM(e),...eU[e]??[]]},supportsCommand(r){let s=t.get(e);return!!s&&(!!s.has("*")||!!r&&s.has(r))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),ej=new Map(eF.map(e=>[e.key,e]));function eV(e,t){return ej.get(e)?.supportsCommand(t)??!1}function eB(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let r=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===r.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...r,setValue:void 0,enumValues:t}}return r}function eG(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function eq(e){return e.replace(/^-+/,"")}function eH(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?eG(e):[e,void 0];return void 0!==eD.get(t)}function eK(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function eJ(e){process.stdout.write(`${JSON.stringify(e,null,2)}
19
- `)}function ez(e,t={}){let r=e instanceof es?ee(e):e;process.stderr.write(`Error (${r.code}): ${r.message}
16
+ `);function eN(e){return ek.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function e_(e,t){return ex(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function ex(e,t){if(0===t.length)return`${e}
17
+ (none)`;let r=Math.max(...t.map(e=>e.label.length))+2,s=[e];for(let e of t)s.push(` ${e.label.padEnd(r)}${e.description}`);return s.join("\n")}function eT(e,t){return 0===t.length?`${e}
18
+ (none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let eM=new Set(["1","true","yes","on"]),eR=new Set(["0","false","no","off"]);function eO(e){return`AGENT_DEVICE_${e.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`}function eC(e,t,r,s){if(e.multiple)return(Array.isArray(t)?t:[t]).map(t=>eC({...e,multiple:!1},t,r,s));if("boolean"===e.type){var o=t,a=r,n=s;if("boolean"==typeof o)return o;if("string"==typeof o){let e=eU(o);if(void 0!==e)return e}throw new es("INVALID_ARGS",`Invalid value for "${n}" in ${a}. Expected boolean.`)}if("booleanOrString"===e.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==eU(t))return eU(t);if("string"==typeof t&&t.trim().length>0)return t;throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected boolean or non-empty string.`)}if("string"===e.type){if("string"==typeof t&&t.trim().length>0)return t;throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected non-empty string.`)}if("enum"===e.type){if(void 0!==e.setValue){var i=e,l=t,u=r,p=s;let o=i.setValue;if(l===o)return o;if("string"==typeof l){let e=l.trim();if(""===e||"true"===e||"1"===e)return o;if("false"===e||"0"===e)return}if(!0===l)return o;if(!1!==l)throw new es("INVALID_ARGS",`Invalid value for "${p}" in ${u}. Expected boolean-like value for enum flag.`);return}if("string"!=typeof t||!e.enumValues?.includes(t))throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected one of: ${e.enumValues?.join(", ")}.`);return t}let d="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(d)||!Number.isInteger(d))throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Expected integer.`);if("number"==typeof e.min&&d<e.min)throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Must be >= ${e.min}.`);if("number"==typeof e.max&&d>e.max)throw new es("INVALID_ARGS",`Invalid value for "${s}" in ${r}. Must be <= ${e.max}.`);return d}function eU(e){let t=e.trim().toLowerCase();return!!eM.has(t)||!eR.has(t)&&void 0}let eF=new Set(["config","remoteConfig","help","version","batchSteps"]),ej={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eV=function(){let e=new Map;for(let t of ek){let r=e.get(t.key);r?r.push(t):e.set(t.key,[t])}let t=new Map;for(let e of eD)t.set(e,new Set(["*"]));for(let e of eP()){let r=e$(e);if(r)for(let s of r.allowedFlags){let r=t.get(s);r&&r.has("*")||(r?r.add(e):t.set(s,new Set([e])))}}return[...e.entries()].map(([e,r])=>({key:e,flagDefinitions:r,config:{enabled:!eF.has(e),key:e},env:{names:[eO(e),...ej[e]??[]]},supportsCommand(r){let s=t.get(e);return!!s&&(!!s.has("*")||!!r&&s.has(r))}})).sort((e,t)=>e.key.localeCompare(t.key))}(),eB=new Map(eV.map(e=>[e.key,e]));function eG(e,t){return eB.get(e)?.supportsCommand(t)??!1}function eq(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let r=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===r.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...r,setValue:void 0,enumValues:t}}return r}function eH(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function eK(e){return e.replace(/^-+/,"")}function eJ(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?eH(e):[e,void 0];return void 0!==eA.get(t)}function ez(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function eW(e){process.stdout.write(`${JSON.stringify(e,null,2)}
19
+ `)}function eX(e,t={}){let r=e instanceof es?ee(e):e;process.stderr.write(`Error (${r.code}): ${r.message}
20
20
  `),r.hint&&process.stderr.write(`Hint: ${r.hint}
21
21
  `),r.diagnosticId&&process.stderr.write(`Diagnostic ID: ${r.diagnosticId}
22
22
  `),r.logPath&&process.stderr.write(`Diagnostics Log: ${r.logPath}
23
23
  `),t.showDetails&&r.details&&process.stderr.write(`${JSON.stringify(r.details,null,2)}
24
- `)}function eW(e,t={}){var r,s,o;let a,n=e.nodes,i=Array.isArray(n)?n:[],l="string"==typeof e.backend?e.backend:void 0,u=t.raw||"macos-helper"===l?null:U(i),p=!!e.truncated,d="string"==typeof e.appName?e.appName:void 0,c="string"==typeof e.appBundleId?e.appBundleId:void 0,m=[];d&&m.push(`Page: ${d}`),c&&m.push(`App: ${c}`);let f=u?.nodes??i,h=t.raw||"macos-helper"===l?null:function(e,t,r,s){let o=e.visibility;if(o&&"object"==typeof o&&"boolean"==typeof o.partial&&"number"==typeof o.visibleNodeCount&&"number"==typeof o.totalNodeCount&&Array.isArray(o.reasons))return{partial:o.partial,visibleNodeCount:o.visibleNodeCount,totalNodeCount:o.totalNodeCount,reasons:o.reasons.filter(e=>"string"==typeof e)};let a=t?.hiddenCount??0,n=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return a>0?{partial:!0,visibleNodeCount:r,totalNodeCount:s,reasons:["offscreen-nodes"]}:n?{partial:!0,visibleNodeCount:r,totalNodeCount:r,reasons:[]}:null}(e,u,f.length,i.length),g=h?.partial?h.totalNodeCount>h.visibleNodeCount?`Snapshot: ${h.visibleNodeCount} visible nodes (${h.totalNodeCount} total)${p?" (truncated)":""}`:`Snapshot: ${h.visibleNodeCount} visible nodes${p?" (truncated)":""}`:`Snapshot: ${i.length} nodes${p?" (truncated)":""}`,y=m.length>0?`${m.join("\n")}
25
- `:"",b=(r=e,s=i,o=t,a=eZ(r),!o.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let s of e){var r;let e=(s.type??"").toLowerCase(),o=(r=s,r.label?.trim()||r.value?.trim()||r.identifier?.trim()||"").trim().toLowerCase();if(!o)continue;let a=`${e}|${o}`;t.set(a,(t.get(a)??0)+1)}let s=0;for(let e of t.values())e>1&&(s+=e);return s>=8}(s)&&a.push("Warning: possible repeated nav subtree detected."),a),w=b.length>0?`${b.join("\n")}
24
+ `)}function eY(e,t={}){var r,s,o;let a,n=e.nodes,i=Array.isArray(n)?n:[],l="string"==typeof e.backend?e.backend:void 0,u=t.raw||"macos-helper"===l?null:U(i),p=!!e.truncated,d="string"==typeof e.appName?e.appName:void 0,c="string"==typeof e.appBundleId?e.appBundleId:void 0,m=[];d&&m.push(`Page: ${d}`),c&&m.push(`App: ${c}`);let f=u?.nodes??i,h=t.raw||"macos-helper"===l?null:function(e,t,r,s){let o=e.visibility;if(o&&"object"==typeof o&&"boolean"==typeof o.partial&&"number"==typeof o.visibleNodeCount&&"number"==typeof o.totalNodeCount&&Array.isArray(o.reasons))return{partial:o.partial,visibleNodeCount:o.visibleNodeCount,totalNodeCount:o.totalNodeCount,reasons:o.reasons.filter(e=>"string"==typeof e)};let a=t?.hiddenCount??0,n=!!t&&t.nodes.some(e=>e.hiddenContentAbove||e.hiddenContentBelow);return a>0?{partial:!0,visibleNodeCount:r,totalNodeCount:s,reasons:["offscreen-nodes"]}:n?{partial:!0,visibleNodeCount:r,totalNodeCount:r,reasons:[]}:null}(e,u,f.length,i.length),g=h?.partial?h.totalNodeCount>h.visibleNodeCount?`Snapshot: ${h.visibleNodeCount} visible nodes (${h.totalNodeCount} total)${p?" (truncated)":""}`:`Snapshot: ${h.visibleNodeCount} visible nodes${p?" (truncated)":""}`:`Snapshot: ${i.length} nodes${p?" (truncated)":""}`,y=m.length>0?`${m.join("\n")}
25
+ `:"",b=(r=e,s=i,o=t,a=e0(r),!o.raw&&function(e){if(e.length<20)return!1;let t=new Map;for(let s of e){var r;let e=(s.type??"").toLowerCase(),o=(r=s,r.label?.trim()||r.value?.trim()||r.identifier?.trim()||"").trim().toLowerCase();if(!o)continue;let a=`${e}|${o}`;t.set(a,(t.get(a)??0)+1)}let s=0;for(let e of t.values())e>1&&(s+=e);return s>=8}(s)&&a.push("Warning: possible repeated nav subtree detected."),a),w=b.length>0?`${b.join("\n")}
26
26
  `:"";if(0===i.length)return`${y}${g}
27
27
  ${w}`;if(t.raw){let e=i.map(e=>JSON.stringify(e));return`${y}${g}
28
28
  ${w}${e.join("\n")}
29
- `}if(t.flatten){let e=C(f,{summarizeTextSurfaces:!0}).flatMap(e=>[Y(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...eQ({...e,depth:0})]),t=u&&u.summaryLines.length>0?`
29
+ `}if(t.flatten){let e=C(f,{summarizeTextSurfaces:!0}).flatMap(e=>[Y(e.node,0,!1,e.type,{summarizeTextSurfaces:!0}),...e1({...e,depth:0})]),t=u&&u.summaryLines.length>0?`
30
30
  ${u.summaryLines.join("\n")}`:"";return`${y}${g}
31
31
  ${w}${e.join("\n")}${t}
32
- `}let v=C(f,{summarizeTextSurfaces:!0}).flatMap(e=>[e.text,...eQ(e)]),k=u&&u.summaryLines.length>0?`
32
+ `}let v=C(f,{summarizeTextSurfaces:!0}).flatMap(e=>[e.text,...e1(e)]),k=u&&u.summaryLines.length>0?`
33
33
  ${u.summaryLines.join("\n")}`:"";return`${y}${g}
34
34
  ${w}${v.join("\n")}${k}
35
- `}function eX(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eY(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function eZ(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function eQ(e){var t;let r="scroll-area"===(t=e.type)||"list"===t||"collection"===t||"table"===t?t:null;if(!r)return[];let s=[];if(e.node.hiddenContentAbove&&s.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&s.push(`[content below ${r} hidden]`),0===s.length)return[];let o=" ".repeat(e.depth+1);return s.map(e=>`${o}${e}`)}async function e0(e){let{localPath:t,baseUrl:r,token:s}=e,o=f.statSync(t).isDirectory(),a=i.basename(t),n=new URL("upload",r.endsWith("/")?r:`${r}/`),l="https:"===n.protocol?m:c,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":a,"transfer-encoding":"chunked"};return s&&(u.authorization=`Bearer ${s}`,u["x-agent-device-token"]=s),new Promise((e,r)=>{let s=l.request({protocol:n.protocol,host:n.hostname,port:n.port,method:"POST",path:n.pathname+n.search,headers:u},t=>{let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{clearTimeout(a);try{let t=JSON.parse(s);if(!t.ok||!t.uploadId)return void r(new es("COMMAND_FAILED",`Upload failed: ${s}`));e(t.uploadId)}catch{r(new es("COMMAND_FAILED",`Invalid upload response: ${s}`))}})}),a=setTimeout(()=>{s.destroy(),r(new es("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(a),r(new es("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=g("tar",["cf","-","-C",i.dirname(t),i.basename(t)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),r(new es("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),r(new es("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=f.createReadStream(t);e.pipe(s),e.on("error",e=>{s.destroy(),r(new es("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let e1=tS(),e2=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}(),e3=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}(),e5=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],e8=new d.BlockList;async function e4(e){let t=e.meta?.requestId??Z(),r=!!(e.meta?.debug||e.flags?.verbose),s=function(e){let t,r=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,s=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new es("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new es("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),o=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var a=s,n=o;if(!(!a||"localhost"===(t=new URL(a).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(d.isIPv4(t)?e8.check(t,"ipv4"):!!d.isIPv6(t)&&e8.check(t,"ipv6")))&&("string"!=typeof n||!(n.trim().length>0)))throw new es("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:a,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let i=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,l=N(i);if(s&&"socket"===l)throw new es("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:s});let u=J(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===i?"dual":void 0));return{paths:K(r),transportPreference:l,serverMode:u,remoteBaseUrl:s,remoteAuthToken:o}}(e),o=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tS(t)}(e.command),a=await ei("daemon_startup",async()=>await tt(s),{requestId:t,session:e.session}),n=await e6(e,a),i={...e,positionals:n.positionals,flags:n.flags,token:a.token,meta:{...e.meta??{},requestId:t,debug:r,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...n.uploadedArtifactId?{uploadedArtifactId:n.uploadedArtifactId}:{},...n.clientArtifactPaths?{clientArtifactPaths:n.clientArtifactPaths}:{},...n.installSource?{installSource:n.installSource}:{}}};return el({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await ei("daemon_request",async()=>await tf(a,i,s.transportPreference,o),{requestId:t,command:e.command})}async function e6(e,t){let r,s=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,a=e.meta?.installSource,n={};if(tk(t)){let l=function(e,t){if("screenshot"===e.command){let r=e9(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:te("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:te("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=e9(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:te("recording",i.extname(t)||".mp4")}}return null}(e,s);l&&(void 0!==l.positionalPath&&(s[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((o??={}).out=l.flagPath),n[l.field]=l.localPath);let u=await e7(e,t);u&&(a=u.installSource,r=u.uploadedArtifactId??r)}if(!tk(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s,flags:o,installSource:a,uploadedArtifactId:r,...Object.keys(n).length>0?{clientArtifactPaths:n}:{}};let l=s[1];if(l.startsWith("remote:"))return s[1]=l.slice(7),{positionals:s,flags:o,...Object.keys(n).length>0?{clientArtifactPaths:n}:{}};let u=i.isAbsolute(l)?l:i.resolve(e.meta?.cwd??process.cwd(),l);return f.existsSync(u)?{positionals:s,flags:o,installSource:a,uploadedArtifactId:r=await e0({localPath:u,baseUrl:t.baseUrl,token:t.token}),...Object.keys(n).length>0?{clientArtifactPaths:n}:{}}:{positionals:s,flags:o,...Object.keys(n).length>0?{clientArtifactPaths:n}:{}}}async function e7(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let s=r.path.trim();if(!s)return{installSource:r};if(s.startsWith("remote:"))return{installSource:{...r,path:s.slice(7)}};let o=i.isAbsolute(s)?s:i.resolve(e.meta?.cwd??process.cwd(),s);if(!f.existsSync(o))return{installSource:{...r,path:o}};let a=await e0({localPath:o,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:o},uploadedArtifactId:a}}function e9(e,t,r,s=0){let o=e.positionals?.[s]??e.flags?.out,a=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,n=o&&o.trim().length>0?o:a;return i.isAbsolute(n)?n:i.resolve(e.meta?.cwd??process.cwd(),n)}function te(e,t){let r=t.startsWith(".")?t:`.${t}`;return i.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function tt(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await td(t,"http"))return t;throw new es("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=tn(e.paths.infoPath),s=F(),o=L((t=tm()).useSrc?t.srcPath:t.distPath,t.root),a=!!r&&await td(r,e.transportPreference);if(r&&r.version===s&&r.codeSignature===o&&a)return r;r&&(r.version!==s||r.codeSignature!==o||!a)&&(await ta(r),tp(e.paths.infoPath)),function(e){let t=tl(e);if(!t.hasLock||t.hasInfo)return;let r=ti(e.lockPath);if(!r)return tp(e.lockPath);S(r.pid,r.processStartTime)||tp(e.lockPath)}(e.paths);let n=0;for(let t=1;t<=e3;t+=1){await tc(e);let r=await tr(e2,e);if(r)return r;if(await to(e.paths)){n+=1;continue}let s=tl(e.paths);if(!(t<e3))break;if(!s.hasInfo&&!s.hasLock){await ts(150);continue}}let i=tl(e.paths);throw new es("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:e2,startupAttempts:e3,lockRecoveryCount:n,metadataState:i,hint:function(e,t=K(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.`}(i,e.paths)})}async function tr(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=tn(t.paths.infoPath);if(e&&await td(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function ts(e){await new Promise(t=>setTimeout(t,e))}async function to(e){let t=tl(e);if(!t.hasLock||t.hasInfo)return!1;let r=ti(e.lockPath);return r&&S(r.pid,r.processStartTime)&&await X(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),tp(e.lockPath),!0}async function ta(e){await X(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function tn(e){let t=tu(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 s=Number.isInteger(t.port)&&Number(t.port)>0,o=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!s&&!o)return null;let a=t.transport,n="string"==typeof t.version?t.version:void 0,i="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,u=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:s?Number(t.port):void 0,httpPort:o?Number(t.httpPort):void 0,transport:"socket"===a||"http"===a||"dual"===a?a:void 0,pid:u?Number(t.pid):0,version:n,codeSignature:i,processStartTime:l}}function ti(e){let t=tu(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}e8.addSubnet("127.0.0.0",8,"ipv4"),e8.addAddress("::1","ipv6"),e8.addSubnet("::ffff:127.0.0.0",104,"ipv6");function tl(e){return{hasInfo:f.existsSync(e.infoPath),hasLock:f.existsSync(e.lockPath)}}function tu(e){if(!f.existsSync(e))return null;try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}}function tp(e){try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}async function td(e,t){var r;return"http"===th(e,t)?await function(e){let t=e.baseUrl?tD(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),s="https:"===r.protocol?m:c,o=e.baseUrl?3e3:500;return new Promise(e=>{let t=s.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:o},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=d.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function tc(e){let t=tm(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],s={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};et(process.execPath,r,{env:s})}function tm(){let e=j(),t=i.join(e,"dist","src","daemon.js"),r=i.join(e,"src","daemon.ts"),s=f.existsSync(t),o=f.existsSync(r);if(!s&&!o)throw new es("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!s&&o}}async function tf(e,t,r,s){return"http"===th(e,r)?await tv(e,t,s):await tw(e,t,s)}function th(e,t){if(e.baseUrl){if("socket"===t)throw new es("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,s=t;if(tg(r,s))return s;throw new es("COMMAND_FAILED","http"===s?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let o=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tg(e,t));if(o)return o;throw new es("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tg(e,t){return"http"===t?!!e.httpPort:!!e.port}function ty(e,t,r,s,o,a){let n=o?{terminated:0}:function(){let e=0;try{for(let t of e5){let r=ea("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)}}}(),i=o?{forcedKill:!1}:function(e,t){let r=!1;try{S(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{X(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{tp(t.infoPath),tp(t.lockPath)}return{forcedKill:r}}(e,t);return el({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:a,requestId:r,command:s,timedOutRunnerPidsTerminated:n.terminated,timedOutRunnerCleanupError:n.error,daemonPidReset:o?void 0:e.pid,daemonPidForceKilled:o?void 0:i.forcedKill,daemonBaseUrl:e.baseUrl}}),new es("COMMAND_FAILED","Daemon request timed out",{timeoutMs:a,requestId:r,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 tb(e,t,r){return el({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new es("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 tw(e,t,r){let s=e.port;if(!s)throw new es("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((o,a)=>{let n=d.createConnection({host:"127.0.0.1",port:s},()=>{n.write(`${JSON.stringify(t)}
36
- `)}),i=K(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{n.destroy(),a(ty(e,i,t.meta?.requestId,t.command,!1,r))},r):void 0,u="";n.setEncoding("utf8"),n.on("data",e=>{let r=(u+=e).indexOf("\n");if(-1===r)return;let s=u.slice(0,r).trim();if(s)try{let e=JSON.parse(s);n.end(),l&&clearTimeout(l),o(e)}catch(e){l&&clearTimeout(l),a(new es("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}}),n.on("error",e=>{l&&clearTimeout(l),a(tb(e,t.meta?.requestId,!1))})})}async function tv(e,t,r){let s=e.baseUrl?new URL(tD(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!s)throw new es("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let o=JSON.stringify({jsonrpc:"2.0",id:t.meta?.requestId??Z(),method:"agent_device.command",params:t}),a={"content-type":"application/json","content-length":Buffer.byteLength(o)};return e.baseUrl&&e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token),await new Promise((n,i)=>{let l=K(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),u=("https:"===s.protocol?m:c).request({protocol:s.protocol,host:s.hostname,port:s.port,method:"POST",path:s.pathname+s.search,headers:a},r=>{let s="";r.setEncoding("utf8"),r.on("data",e=>{s+=e}),r.on("end",()=>{d&&clearTimeout(d);try{let r=JSON.parse(s);if(r.error){let e=r.error.data??{};i(new es(String(e.code??"COMMAND_FAILED"),String(e.message??r.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:t.meta?.requestId}));return}if(!r.result||"object"!=typeof r.result)return void i(new es("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tI(e,t,r.result).then(n).catch(i);n(r.result)}catch(e){d&&clearTimeout(d),i(new es("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}})}),p=tk(e),d="number"==typeof r?setTimeout(()=>{u.destroy(),i(ty(e,l,t.meta?.requestId,t.command,p,r))},r):void 0;u.on("error",e=>{d&&clearTimeout(d),i(tb(e,t.meta?.requestId,p))}),u.write(o),u.end()})}function tk(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function tD(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tI(e,t,r){let s=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===s.length||!e.baseUrl)return r;let o=r.data?{...r.data}:{},a=[];for(let r of s){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){a.push(r);continue}let s=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return i.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await tA({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:s,requestId:t.meta?.requestId}),o[r.field]=s,a.push({...r,localPath:s})}return o.artifacts=a,{ok:!0,data:o}}async function tA(e){var t,r;let s,o=new URL((t=e.baseUrl,r=e.artifactId,s=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,s).toString())),a="https:"===o.protocol?m:c;await f.promises.mkdir(i.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let s=!1,n=e.timeoutMs??e1,i=o=>{if(!s){if(s=!0,clearTimeout(u),o)return void f.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(o));t()}},l=a.request({protocol:o.protocol,host:o.hostname,port:o.port,method:"GET",path:o.pathname+o.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 es("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=f.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 es("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),u=setTimeout(()=>{l.destroy(new es("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);l.on("error",t=>{t instanceof es?i(t):i(new es("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),l.end()})}function tS(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 t$(e){return y("sha256").update(e).digest("hex")}function tP(e){return e?.trim()?e.trim():void 0}function tE(e,t){let r=i.join(e,".agent-device");if(!t)return{statePath:i.join(r,"metro-companion.json"),logPath:i.join(r,"metro-companion.log")};let s=t$(t).slice(0,12),o=i.join(r,"metro-companion");return{statePath:i.join(o,`metro-companion-${s}.json`),logPath:i.join(o,`metro-companion-${s}.log`)}}function tL(e){try{let t=JSON.parse(f.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let r=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:tP("string"==typeof t.launchUrl?t.launchUrl:void 0),tokenHash:t.tokenHash,consumers:r}}catch{return null}}function tN(e,t){f.mkdirSync(i.dirname(e),{recursive:!0}),f.writeFileSync(e,`${JSON.stringify(t,null,2)}
37
- `,"utf8")}function t_(e){try{f.unlinkSync(e)}catch{}}function tx(e){return e.includes(eu)}function tT(e){return tP(e.consumerKey)??tP(e.profileKey)??null}function tM(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function tR(e){if(!q(e.pid))return;let t=k(e.pid);if(t&&tx(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await D(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await D(e.pid,1e3)}}}async function tO(e){let t=tT(e),r=tE(e.projectRoot,e.profileKey),s=tL(r.statePath);if(s&&function(e,t){if(!q(e.pid))return!1;if(e.startTime){let t=H(e.pid);if(!t||t!==e.startTime)return!1}let r=k(e.pid);return!!r&&!!tx(r)&&e.serverBaseUrl===ed(t.serverBaseUrl)&&e.localBaseUrl===ed(t.localBaseUrl)&&e.launchUrl===tP(t.launchUrl)&&e.tokenHash===t$(t.bearerToken)}(s,e)){let e=tM(s,t);return e!==s&&tN(r.statePath,e),{pid:s.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}s&&(await tR(s),t_(r.statePath));let o=function(e,t){let r=function(){let e=u(import.meta.url),t=i.extname(e)||".js",r=i.join(i.dirname(e),`metro-companion${t}`);if(!f.existsSync(r))throw Error(`Metro companion entrypoint not found at ${r}. Rebuild the package to include the companion worker entry.`);return r}(),s=r.endsWith(".ts")?["--experimental-strip-types"]:[];f.mkdirSync(i.dirname(t),{recursive:!0});let o=f.openSync(t,"a"),a=0;try{let t;a=et(process.execPath,[...s,r,eu],{env:(t={...e.env??process.env,[em]:ed(e.serverBaseUrl),[ec]:e.bearerToken,[ef]:ed(e.localBaseUrl)},e.launchUrl?.trim()?t[ep]=e.launchUrl.trim():delete t[ep],t),stdio:["ignore",o,o]})}finally{f.closeSync(o)}if(!Number.isInteger(a)||a<=0)throw Error("Failed to start Metro companion process.");return{pid:a,startTime:H(a)??void 0,command:k(a)??void 0,serverBaseUrl:ed(e.serverBaseUrl),localBaseUrl:ed(e.localBaseUrl),launchUrl:tP(e.launchUrl),tokenHash:t$(e.bearerToken),consumers:[]}}(e,r.logPath);return tN(r.statePath,tM(o,t)),{pid:o.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function tC(e){let t=tT(e),r=tE(e.projectRoot,e.profileKey),s=tL(r.statePath);if(!s)return t_(r.statePath),{stopped:!1,statePath:r.statePath};let o=t?{...s,consumers:s.consumers.filter(e=>e!==t)}:{...s,consumers:[]};return o.consumers.length>0?(tN(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await tR(s),t_(r.statePath),{stopped:!0,statePath:r.statePath})}function tU(e){return"string"==typeof e&&e.trim()?ed(e.trim()):""}function tF(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function tj(e,t,r){return V(e,{env:t,cwd:r})}function tV(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}function tB(e,t,r){if(null==e||""===e)return t;let s=Number.parseInt(String(e),10);return Number.isInteger(s)?Math.max(s,r):t}function tG(e,t){let r;return{platform:t,bundleUrl:((r=new URL(`${ed(e)}/index.bundle`)).searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString())}}function tq(e,t){return{platform:t,metroHost:tF(e?.metro_host),metroPort:e?.metro_port,bundleUrl:tF(e?.metro_bundle_url),launchUrl:tF(e?.launch_url)}}async function tH(e){await new Promise(t=>setTimeout(t,e))}async function tK(e,t,r={}){try{let s=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:s.ok,status:s.status,body:await s.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function tJ(e,t){try{let r=await tK(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function tz(e,t){let r=Error(e);return r.retryable=t,r}async function tW(e){var t,r,s,o;let a;try{a=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw tz(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw tz(t instanceof Error?t.message:String(t),!0)}let n=await a.text(),i=n?JSON.parse(n):{};if(!a.ok)throw tz(`/api/metro/bridge failed (${a.status}): ${JSON.stringify(i)}`,(s=a.status,!!(s>=500||408===s||425===s||429===s||JSON.stringify(i).includes("Metro companion is not connected"))));return{enabled:(o=i.data??i).enabled,baseUrl:o.base_url,statusUrl:o.status_url,bundleUrl:o.bundle_url,iosRuntime:tq(o.ios_runtime,"ios"),androidRuntime:tq(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url,host:o.upstream.host,port:o.upstream.port,statusUrl:o.upstream.status_url},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function tX(e,t,r,s,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&a.push(`bridgeError=${t}`),r?.probe.reachable===!1&&a.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),s&&s!==t&&a.push(`initialBridgeError=${s}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function tY(e,t,r){let s=Date.now()+t;for(;Date.now()<s;){let t=Math.min(r,Math.max(s-Date.now(),1));if(await tJ(e,t))return!0;let o=Math.min(500,Math.max(s-Date.now(),0));o>0&&await tH(o)}return!1}async function tZ(e){let t=Date.now()+e.startupTimeoutMs,r=null,s=null;for(;Date.now()<t;){try{let t=await tW({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,s=null}catch(e){if(s=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await tH(o)}throw Error(tX(e.baseUrl,s,r,e.initialBridgeError,e.companionLogPath))}async function tQ(e={}){let t=e.env??process.env,r=process.cwd(),s=tj(e.projectRoot??r,t,r),o=function(e,t){if("auto"!==t)return t;let r=function(e){let t=i.join(e,"package.json");if(!tV(t))throw new es("INVALID_ARGS",`package.json not found at ${t}`);return JSON.parse(f.readFileSync(t,"utf8"))}(e);return"string"==typeof({...r.dependencies??{},...r.devDependencies??{}}).expo?"expo":"react-native"}(s,e.kind??"auto"),a=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new es("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(e.metroPort??8081),n=tF(e.listenHost)??"0.0.0.0",l=tF(e.statusHost)??"127.0.0.1",u=tU(e.publicBaseUrl),p=tB(e.startupTimeoutMs,18e4,3e4),d=tB(e.probeTimeoutMs,1e4,1e3),c=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?tj(e.runtimeFilePath,t,r):null,g=tj(e.logPath??i.join(s,".agent-device","metro.log"),t,r);if(!u)throw new es("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:y,proxyBaseUrl:b,proxyBearerToken:w}=function(e,t){if(e&&!t)throw new es("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new es("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(tU(e.proxyBaseUrl),tF(e.proxyBearerToken)??""),v=m?function(e,t){if(function(e){try{return f.statSync(e).isDirectory()}catch{return!1}}(i.join(e,"node_modules")))return{installed:!1};let r=tV(i.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:tV(i.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return ea(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(s,t):{installed:!1},k=`http://${l}:${a}/status`,D=!1,I=!1,A=0;if(c&&await tJ(k,d))I=!0;else if(D=!0,A=function(e,t,r,s,o,a){let n="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",s,"--port",String(r)]};f.mkdirSync(i.dirname(o),{recursive:!0});let l=f.openSync(o,"a"),u=0;try{u=et(n.command,n.installArgs,{cwd:e,env:a,stdio:["ignore",l,l]})}finally{f.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:u}}(s,o,a,n,g,t).pid,!await tY(k,p,d))throw Error(`Metro did not become ready at ${k} within ${p}ms. Check ${g}.`);let S=tG(u,"ios"),$=tG(u,"android"),P=null,E=null;if(y)try{P=await tW({baseUrl:b,bearerToken:w,runtime:{metro_bundle_url:S.bundleUrl},timeoutMs:d})}catch(e){E=e instanceof Error?e.message:String(e)}if(y&&(!P||!1===P.probe.reachable)){let r;try{r=(await tO({projectRoot:s,serverBaseUrl:b,bearerToken:w,localBaseUrl:`http://${l}:${a}`,launchUrl:tF(e.launchUrl),profileKey:tF(e.companionProfileKey),consumerKey:tF(e.companionConsumerKey),env:t})).logPath}catch(e){throw Error(tX(b,e instanceof Error?e.message:String(e),P,E))}try{P=await tZ({baseUrl:b,bearerToken:w,runtime:{metro_bundle_url:S.bundleUrl},probeTimeoutMs:d,startupTimeoutMs:p,initialBridgeError:E,companionLogPath:r})}catch(e){throw e instanceof Error?e:Error(String(e))}}let L=P?.iosRuntime??S,N=P?.androidRuntime??$,_={projectRoot:s,kind:o,dependenciesInstalled:v.installed,packageManager:v.packageManager??null,started:D,reused:I,pid:A,logPath:g,statusUrl:k,runtimeFilePath:h,iosRuntime:L,androidRuntime:N,bridge:P};return h&&(f.mkdirSync(i.dirname(h),{recursive:!0}),f.writeFileSync(h,JSON.stringify(_,null,2))),_}function t0(e,t,r,s){let o=r(e[t]);if(void 0===o)throw new es("COMMAND_FAILED",s,{response:e});return o}function t1(e,t){return t0(e,t,t6,`Daemon response is missing "${t}".`)}function t2(e,t){return t6(e[t])}function t3(e,t){var r;let s;return r=t6,null===(s=e[t])?null:r(s)}function t5(e,t){return t0(e,t,t9,`Daemon response has invalid "${t}".`)}function t8(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function t4(e,t){let r=e[t];if(!rr(r))return;let s="number"==typeof r.x?r.x:void 0,o="number"==typeof r.y?r.y:void 0,a="number"==typeof r.width?r.width:void 0,n="number"==typeof r.height?r.height:void 0;if(void 0!==s&&void 0!==o&&void 0!==a&&void 0!==n)return{x:s,y:o,width:a,height:n}}function t6(e){return"string"==typeof e&&e.length>0?e:void 0}function t7(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function t9(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function re(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function rt(e){if(!rr(e))throw new es("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function rr(e){return"object"==typeof e&&null!==e}function rs(e){let t={};for(let[r,s]of Object.entries(e))void 0!==s&&(t[r]=s);return t}function ro(e,t){let r=t2(e,"bundleId"),s=t2(e,"package");return{app:t1(e,"app"),appPath:t1(e,"appPath"),platform:t5(e,"platform"),appId:r??s,bundleId:r,package:s,identifiers:P({session:t,bundleId:r,packageName:s})}}function ra(e){let t=rt(e),r=t5(t,"platform"),s=t1(t,"id"),o=t1(t,"name");return{platform:r,target:t8(t,"target"),kind:t0(t,"kind",re,'Daemon response has invalid "kind".'),id:s,name:o,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:$(r,s,o),ios:"ios"===r?{udid:s}:void 0,android:"android"===r?{serial:s}:void 0}}function rn(e){let t=rt(e),r=t5(t,"platform"),s=t1(t,"id"),o=t1(t,"name"),a=t8(t,"target"),n=t1(t,"device"),i={session:o,...$(r,s,n)};return{name:o,createdAt:t0(t,"createdAt",t7,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:a,id:s,name:n,identifiers:i,ios:"ios"===r?{udid:s,simulatorSetPath:t3(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:s}:void 0},identifiers:i}}function ri(e,t){return t??e??"default"}function rl(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function ru(e,t,r){var s;if(e.json)return void eJ({success:!0,data:t});let o=r?.();o&&(s=o,process.stdout.write(s.endsWith("\n")?s:`${s}
38
- `))}function rp(e,t){ru(e,t,()=>M(t))}let rd=async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new es("INVALID_ARGS","session only supports list");let s={sessions:(await r.sessions.list()).map(I)};return ru(t,s,()=>JSON.stringify(s,null,2)),!0},rc=async({flags:e,client:t})=>{let r=await t.devices.list(rl(e));return ru(e,{devices:r.map(O)},()=>r.map(rm).join("\n")),!0};function rm(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",s="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${s}`}let rf=async({flags:e,client:t})=>{if(!e.device)throw new es("INVALID_ARGS","ensure-simulator requires --device <name>");let r=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet});return ru(e,R(r),()=>{let e=r.created?"Created":"Reused",t=r.booted?" (booted)":"";return r.runtime?`${e}: ${r.device} ${r.udid}${t}
39
- Runtime: ${r.runtime}`:`${e}: ${r.device} ${r.udid}${t}`}),!0},rh=async({positionals:e,flags:t,client:r})=>{if("prepare"!==(e[0]??"").toLowerCase())throw new es("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new es("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let s=await r.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return ru(t,s,()=>JSON.stringify(s,null,2)),!0},rg=async({positionals:e,flags:t,client:r})=>{let s=T(await rw("install",e,t,r));return rp(t,s),!0},ry=async({positionals:e,flags:t,client:r})=>{let s=T(await rw("reinstall",e,t,r));return rp(t,s),!0},rb=async({positionals:e,flags:t,client:r})=>{let s=z(await rv(e,t,r));return rp(t,s),!0};async function rw(e,t,r,s){let o=t[0],a=t[1];if(!o||!a)throw new es("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let n={app:o,appPath:a,...rl(r)};return"install"===e?await s.apps.install(n):await s.apps.reinstall(n)}async function rv(e,t,r){let s=e[0]?.trim();if(!s)throw new es("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new es("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await r.apps.installFromSource({...rl(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:s,headers:function(e){if(!e||0===e.length)return;let t={};for(let r of e){let e=r.indexOf(":");if(e<=0)throw new es("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let s=r.slice(0,e).trim(),o=r.slice(e+1).trim();if(!s)throw new es("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[s]=o}return t}(t.header)}})}async function rk(e){await tC(e)}let rD=[{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"}],rI=["session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],rA=new Map(rD.map(e=>[e.key,e]));function rS(e){let t=e.env??process.env;return V(e.configPath,{cwd:e.cwd,env:t})}function r$(e){let t=function(e){let t,r,s=e.env??process.env,o=rS(e);if(!f.existsSync(o))throw new es("INVALID_ARGS",`Remote config file not found: ${o}`);try{t=f.readFileSync(o,"utf8")}catch(e){throw new es("INVALID_ARGS",`Failed to read remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}try{r=JSON.parse(t)}catch(e){throw new es("INVALID_ARGS",`Invalid JSON in remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new es("INVALID_ARGS",`Remote config file must contain a JSON object: ${o}`);let a={},n=r,l=i.dirname(o);for(let[e,t]of Object.entries(n)){let r=rA.get(e);if(!r)throw new es("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${o}.`);let n=eR(r,t,`remote config file ${o}`,e);a[r.key]="string"==typeof n&&"path"in r&&r.path?V(n,{cwd:l,env:s}):n}return{resolvedPath:o,profile:a}}(e);return{resolvedPath:t.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of rD){let s=r[e.key];void 0!==s&&(t[e.key]=s)}return t}(function(e=process.env){let t={};for(let r of rD){let s=(function(e){let t=rA.get(e);return[eM(e),...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);s&&(t[r.key]=eR(r,s.value,`environment variable ${s.name}`,s.name))}return t}(e.env),t.profile)}}async function rP(e,t){if(!e.remoteConfig)return;let r=e.platform;if("ios"!==r&&"android"!==r)throw new es("INVALID_ARGS",'open --remote-config requires platform "ios" or "android" in the remote config file or CLI flags.');if(!e.metroPublicBaseUrl)throw new es("INVALID_ARGS",'open --remote-config requires "metroPublicBaseUrl" in the remote config file.');let s=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,launchUrl:e.launchUrl,companionProfileKey:rS({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),companionConsumerKey:e.session,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return"ios"===r?s.iosRuntime:s.androidRuntime}let rE=255*Math.sqrt(3);async function rL(e,t,r={}){await rN(e,"Baseline image not found"),await rN(t,"Current screenshot not found");let s=r.outputPath,[o,a]=await Promise.all([h.readFile(e),h.readFile(t)]),n=W(o,"baseline screenshot"),l=W(a,"current screenshot"),u=r.threshold??.1;if(n.width!==l.width||n.height!==l.height){let e=n.width*n.height;return await r_(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:n.width,height:n.height},actual:{width:l.width,height:l.height}}}}let p=n.width*n.height,d=u*rE,c=new w({width:n.width,height:n.height}),m=0;for(let e=0;e<n.data.length;e+=4){if(Math.sqrt((n.data[e]-l.data[e])**2+(n.data[e+1]-l.data[e+1])**2+(n.data[e+2]-l.data[e+2])**2)>d){m+=1,c.data[e]=255,c.data[e+1]=0,c.data[e+2]=0,c.data[e+3]=255;continue}let t=Math.round(.3*Math.round((n.data[e]+n.data[e+1]+n.data[e+2])/3));c.data[e]=t,c.data[e+1]=t,c.data[e+2]=t,c.data[e+3]=255}m>0&&s?(await h.mkdir(i.dirname(s),{recursive:!0}),await h.writeFile(s,w.sync.write(c))):await r_(r.outputPath);let f=p>0?Math.round(m/p*1e4)/100:0;return{...m>0&&s?{diffPath:s}:{},totalPixels:p,differentPixels:m,mismatchPercentage:f,match:0===m}}async function rN(e,t){try{await h.access(e)}catch{throw new es("INVALID_ARGS",`${t}: ${e}`)}}async function r_(e){if(e)try{await h.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}let rx={session:rd,devices:rc,"ensure-simulator":rf,metro:rh,install:rg,reinstall:ry,"install-from-source":rb,open:async({positionals:e,flags:t,client:r})=>{if(!e[0])return!1;let s=await rP(t,r),o=_(await r.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,runtime:s,...rl(t)}));return rp(t,o),!0},close:async({positionals:e,flags:t,client:r})=>{let s=(()=>{let e;if(!t.remoteConfig)return null;try{e=r$({configPath:t.remoteConfig,cwd:process.cwd(),env:process.env})}catch{return null}return e.profile.metroProjectRoot&&e.profile.metroProxyBaseUrl?{projectRoot:e.profile.metroProjectRoot,profileKey:e.resolvedPath,consumerKey:t.session}:null})(),o=async e=>{try{return await e()}finally{try{s&&await rk(s)}catch{}}},a=B(await o(async()=>e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown})));return rp(t,a),!0},snapshot:async({flags:e,client:t})=>{let r=A(await t.capture.snapshot({...rl(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return ru(e,r,()=>eW(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},screenshot:async({positionals:e,flags:t,client:r})=>{let s=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs});return ru(t,{path:s.path,...s.overlayRefs?{overlayRefs:s.overlayRefs}:{}},()=>s.overlayRefs?`Annotated ${s.overlayRefs.length} refs onto ${s.path}`:s.path),!0},diff:async({positionals:e,flags:t,client:r})=>{let s;if("screenshot"!==e[0])return!1;let o=t.baseline;if(!o||"string"!=typeof o)throw new es("INVALID_ARGS","diff screenshot requires --baseline <path>");let a=V(o),n="string"==typeof t.out?V(t.out):void 0,u=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(u=Number(t.threshold))||u<0||u>1))throw new es("INVALID_ARGS","--threshold must be a number between 0 and 1");let p=f.mkdtempSync(i.join(b.tmpdir(),"agent-device-diff-current-")),d=i.join(p,`current-${Date.now()}.png`),c=(await r.capture.screenshot({path:d})).path;try{s=await rL(a,c,{threshold:u,outputPath:n})}finally{try{f.unlinkSync(c)}catch{}try{f.rmSync(p,{recursive:!0,force:!0})}catch{}}return ru(t,s,()=>(function(e){let t=eY(),r=!0===e.match,s=eX(e.differentPixels),o=eX(e.totalPixels),a=eX(e.mismatchPercentage),n=e.diffPath,u=e.dimensionMismatch,p=[];if(r){let e=t?l("green","✓"):"✓";p.push(`${e} Screenshots match.`)}else if(u){let e=t?l("red","✗"):"✗",r=u.expected,s=u.actual;p.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${s?.width}x${s?.height}`)}else{let e=t?l("red","✗"):"✗",r=0===a&&s>0?"<0.01":String(a);p.push(`${e} ${r}% pixels differ`)}if(n&&!r){var d;let e,r,s=(d=n,e=process.cwd(),""!==(r=i.relative(e,d))&&(r.startsWith("..")||i.isAbsolute(r))?d:""===r?".":`.${i.sep}${r}`),o=t?l("dim","Diff image:"):"Diff image:",a=t?l("green",s):s;p.push(` ${o} ${a}`)}if(!r&&!u){let e=t?l("red",String(s)):String(s);p.push(` ${e} different / ${o} total pixels`)}return`${p.join("\n")}
40
- `})(s)),!0}};async function rT(e){let t=rx[e.command];return!!t&&await t(e)}function rM(e){let{suite:t,json:r,verbose:s,reportJunit:o}=e;return(o&&function(e,t){let r=i.dirname(e);try{f.mkdirSync(r,{recursive:!0}),f.writeFileSync(e,function(e){let t=['<?xml version="1.0" encoding="UTF-8"?>',"<testsuites>",` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${rC(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=rU(i.basename(e.file)),r=rU("."===i.dirname(e.file)?e.file:i.dirname(e.file)),s=rU(e.file),o=rC(e.durationMs),a=[` <testcase classname="${r}" name="${t}" file="${s}" time="${o}">`];"failed"===e.status?a.push(` <failure message="${rU(e.error.message)}">${rU(function(e){let t=[e.error.message];e.error.hint&&t.push(`hint: ${e.error.hint}`),e.error.diagnosticId&&t.push(`diagnosticId: ${e.error.diagnosticId}`),e.error.logPath&&t.push(`logPath: ${e.error.logPath}`),e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`);let r=e.error.details?JSON.stringify(e.error.details,null,2):void 0;return r&&t.push(`details: ${r}`),t.join("\n")}(e))}</failure>`):"skipped"===e.status&&a.push(` <skipped message="${rU(e.message)}" />`);let n=function(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return"attempts"in e&&t.push(`attempts: ${e.attempts}`),"session"in e&&t.push(`session: ${e.session}`),"replayed"in e&&t.push(`replayed: ${e.replayed}`),"healed"in e&&t.push(`healed: ${e.healed}`),"artifactsDir"in e&&e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`),"passed"===e.status&&e.attempts>1&&t.push("flaky: true"),t.join("\n")}(e);return n&&a.push(` <system-out>${rU(n)}</system-out>`),a.push(" </testcase>"),a}(r));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
41
- `}(t),"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new es("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(o,t),r)?(eJ({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(rO);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return rR(e);let t="passed"===e.status?rO(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",s=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${s}
35
+ `}function eZ(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eQ(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}function e0(e){let t=e.warnings;return Array.isArray(t)?t.filter(e=>"string"==typeof e&&e.length>0):[]}function e1(e){var t;let r="scroll-area"===(t=e.type)||"list"===t||"collection"===t||"table"===t?t:null;if(!r)return[];let s=[];if(e.node.hiddenContentAbove&&s.push(`[content above ${r} hidden]`),e.node.hiddenContentBelow&&s.push(`[content below ${r} hidden]`),0===s.length)return[];let o=" ".repeat(e.depth+1);return s.map(e=>`${o}${e}`)}async function e2(e){let{localPath:t,baseUrl:r,token:s}=e,o=f.statSync(t).isDirectory(),a=i.basename(t),n=new URL("upload",r.endsWith("/")?r:`${r}/`),l="https:"===n.protocol?m:c,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":a,"transfer-encoding":"chunked"};return s&&(u.authorization=`Bearer ${s}`,u["x-agent-device-token"]=s),new Promise((e,r)=>{let s=l.request({protocol:n.protocol,host:n.hostname,port:n.port,method:"POST",path:n.pathname+n.search,headers:u},t=>{let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{clearTimeout(a);try{let t=JSON.parse(s);if(!t.ok||!t.uploadId)return void r(new es("COMMAND_FAILED",`Upload failed: ${s}`));e(t.uploadId)}catch{r(new es("COMMAND_FAILED",`Invalid upload response: ${s}`))}})}),a=setTimeout(()=>{s.destroy(),r(new es("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(a),r(new es("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=g("tar",["cf","-","-C",i.dirname(t),i.basename(t)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),r(new es("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),r(new es("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=f.createReadStream(t);e.pipe(s),e.on("error",e=>{s.destroy(),r(new es("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let e3=tP(),e5=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}(),e8=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}(),e4=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"],e6=new d.BlockList;async function e7(e){let t=e.meta?.requestId??Z(),r=!!(e.meta?.debug||e.flags?.verbose),s=function(e){let t,r=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,s=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new es("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new es("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),o=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;var a=s,n=o;if(!(!a||"localhost"===(t=new URL(a).hostname.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1"))||(d.isIPv4(t)?e6.check(t,"ipv4"):!!d.isIPv6(t)&&e6.check(t,"ipv6")))&&("string"!=typeof n||!(n.trim().length>0)))throw new es("INVALID_ARGS","Remote daemon base URL for non-loopback hosts requires daemon authentication",{daemonBaseUrl:a,hint:"Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL."});let i=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,l=N(i);if(s&&"socket"===l)throw new es("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:s});let u=J(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===i?"dual":void 0));return{paths:K(r),transportPreference:l,serverMode:u,remoteBaseUrl:s,remoteAuthToken:o}}(e),o=function(e,t=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if("test"!==e)return tP(t)}(e.command),a=await ei("daemon_startup",async()=>await ts(s),{requestId:t,session:e.session}),n=await e9(e,a),i={...e,positionals:n.positionals,flags:n.flags,token:a.token,meta:{...e.meta??{},requestId:t,debug:r,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...n.uploadedArtifactId?{uploadedArtifactId:n.uploadedArtifactId}:{},...n.clientArtifactPaths?{clientArtifactPaths:n.clientArtifactPaths}:{},...n.installSource?{installSource:n.installSource}:{}}};return el({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await ei("daemon_request",async()=>await tg(a,i,s.transportPreference,o),{requestId:t,command:e.command})}async function e9(e,t){let r,s=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,a=e.meta?.installSource,n={};if(tI(t)){let l=function(e,t){if("screenshot"===e.command){let r=tt(e,"path",".png");return t[0]?{field:"path",localPath:r,positionalIndex:0,positionalPath:tr("screenshot",".png")}:{field:"path",localPath:r,positionalIndex:0,flagPath:tr("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=tt(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:tr("recording",i.extname(t)||".mp4")}}return null}(e,s);l&&(void 0!==l.positionalPath&&(s[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((o??={}).out=l.flagPath),n[l.field]=l.localPath);let u=await te(e,t);u&&(a=u.installSource,r=u.uploadedArtifactId??r)}if(!tI(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s,flags:o,installSource:a,uploadedArtifactId:r,...Object.keys(n).length>0?{clientArtifactPaths:n}:{}};let l=s[1];if(l.startsWith("remote:"))return s[1]=l.slice(7),{positionals:s,flags:o,...Object.keys(n).length>0?{clientArtifactPaths:n}:{}};let u=i.isAbsolute(l)?l:i.resolve(e.meta?.cwd??process.cwd(),l);return f.existsSync(u)?{positionals:s,flags:o,installSource:a,uploadedArtifactId:r=await e2({localPath:u,baseUrl:t.baseUrl,token:t.token}),...Object.keys(n).length>0?{clientArtifactPaths:n}:{}}:{positionals:s,flags:o,...Object.keys(n).length>0?{clientArtifactPaths:n}:{}}}async function te(e,t){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let s=r.path.trim();if(!s)return{installSource:r};if(s.startsWith("remote:"))return{installSource:{...r,path:s.slice(7)}};let o=i.isAbsolute(s)?s:i.resolve(e.meta?.cwd??process.cwd(),s);if(!f.existsSync(o))return{installSource:{...r,path:o}};let a=await e2({localPath:o,baseUrl:t.baseUrl,token:t.token});return{installSource:{...r,path:o},uploadedArtifactId:a}}function tt(e,t,r,s=0){let o=e.positionals?.[s]??e.flags?.out,a=`${"path"===t?"screenshot":"recording"}-${Date.now()}${r}`,n=o&&o.trim().length>0?o:a;return i.isAbsolute(n)?n:i.resolve(e.meta?.cwd??process.cwd(),n)}function tr(e,t){let r=t.startsWith(".")?t:`.${t}`;return i.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function ts(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await tm(t,"http"))return t;throw new es("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=tl(e.paths.infoPath),s=F(),o=L((t=th()).useSrc?t.srcPath:t.distPath,t.root),a=!!r&&await tm(r,e.transportPreference);if(r&&r.version===s&&r.codeSignature===o&&a)return r;r&&(r.version!==s||r.codeSignature!==o||!a)&&(await ti(r),tc(e.paths.infoPath)),function(e){let t=tp(e);if(!t.hasLock||t.hasInfo)return;let r=tu(e.lockPath);if(!r)return tc(e.lockPath);S(r.pid,r.processStartTime)||tc(e.lockPath)}(e.paths);let n=0;for(let t=1;t<=e8;t+=1){await tf(e);let r=await to(e5,e);if(r)return r;if(await tn(e.paths)){n+=1;continue}let s=tp(e.paths);if(!(t<e8))break;if(!s.hasInfo&&!s.hasLock){await ta(150);continue}}let i=tp(e.paths);throw new es("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:e5,startupAttempts:e8,lockRecoveryCount:n,metadataState:i,hint:function(e,t=K(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.`}(i,e.paths)})}async function to(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=tl(t.paths.infoPath);if(e&&await tm(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function ta(e){await new Promise(t=>setTimeout(t,e))}async function tn(e){let t=tp(e);if(!t.hasLock||t.hasInfo)return!1;let r=tu(e.lockPath);return r&&S(r.pid,r.processStartTime)&&await X(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),tc(e.lockPath),!0}async function ti(e){await X(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function tl(e){let t=td(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 s=Number.isInteger(t.port)&&Number(t.port)>0,o=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!s&&!o)return null;let a=t.transport,n="string"==typeof t.version?t.version:void 0,i="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,u=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:s?Number(t.port):void 0,httpPort:o?Number(t.httpPort):void 0,transport:"socket"===a||"http"===a||"dual"===a?a:void 0,pid:u?Number(t.pid):0,version:n,codeSignature:i,processStartTime:l}}function tu(e){let t=td(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}e6.addSubnet("127.0.0.0",8,"ipv4"),e6.addAddress("::1","ipv6"),e6.addSubnet("::ffff:127.0.0.0",104,"ipv6");function tp(e){return{hasInfo:f.existsSync(e.infoPath),hasLock:f.existsSync(e.lockPath)}}function td(e){if(!f.existsSync(e))return null;try{return JSON.parse(f.readFileSync(e,"utf8"))}catch{return null}}function tc(e){try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}async function tm(e,t){var r;return"http"===ty(e,t)?await function(e){let t=e.baseUrl?tA(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),s="https:"===r.protocol?m:c,o=e.baseUrl?3e3:500;return new Promise(e=>{let t=s.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:o},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=d.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function tf(e){let t=th(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],s={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};et(process.execPath,r,{env:s})}function th(){let e=j(),t=i.join(e,"dist","src","daemon.js"),r=i.join(e,"src","daemon.ts"),s=f.existsSync(t),o=f.existsSync(r);if(!s&&!o)throw new es("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!s&&o}}async function tg(e,t,r,s){return"http"===ty(e,r)?await tD(e,t,s):await tk(e,t,s)}function ty(e,t){if(e.baseUrl){if("socket"===t)throw new es("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,s=t;if(tb(r,s))return s;throw new es("COMMAND_FAILED","http"===s?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let o=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>tb(e,t));if(o)return o;throw new es("COMMAND_FAILED","Daemon metadata has no reachable transport")}function tb(e,t){return"http"===t?!!e.httpPort:!!e.port}function tw(e,t,r,s,o,a){let n=o?{terminated:0}:function(){let e=0;try{for(let t of e4){let r=ea("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)}}}(),i=o?{forcedKill:!1}:function(e,t){let r=!1;try{S(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{X(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{tc(t.infoPath),tc(t.lockPath)}return{forcedKill:r}}(e,t);return el({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:a,requestId:r,command:s,timedOutRunnerPidsTerminated:n.terminated,timedOutRunnerCleanupError:n.error,daemonPidReset:o?void 0:e.pid,daemonPidForceKilled:o?void 0:i.forcedKill,daemonBaseUrl:e.baseUrl}}),new es("COMMAND_FAILED","Daemon request timed out",{timeoutMs:a,requestId:r,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 tv(e,t,r){return el({level:"error",phase:"daemon_request_socket_error",data:{requestId:t,message:e instanceof Error?e.message:String(e)}}),new es("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 tk(e,t,r){let s=e.port;if(!s)throw new es("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((o,a)=>{let n=d.createConnection({host:"127.0.0.1",port:s},()=>{n.write(`${JSON.stringify(t)}
36
+ `)}),i=K(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l="number"==typeof r?setTimeout(()=>{n.destroy(),a(tw(e,i,t.meta?.requestId,t.command,!1,r))},r):void 0,u="";n.setEncoding("utf8"),n.on("data",e=>{let r=(u+=e).indexOf("\n");if(-1===r)return;let s=u.slice(0,r).trim();if(s)try{let e=JSON.parse(s);n.end(),l&&clearTimeout(l),o(e)}catch(e){l&&clearTimeout(l),a(new es("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}}),n.on("error",e=>{l&&clearTimeout(l),a(tv(e,t.meta?.requestId,!1))})})}async function tD(e,t,r){let s=e.baseUrl?new URL(tA(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!s)throw new es("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let o=JSON.stringify({jsonrpc:"2.0",id:t.meta?.requestId??Z(),method:"agent_device.command",params:t}),a={"content-type":"application/json","content-length":Buffer.byteLength(o)};return e.baseUrl&&e.token&&(a.authorization=`Bearer ${e.token}`,a["x-agent-device-token"]=e.token),await new Promise((n,i)=>{let l=K(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),u=("https:"===s.protocol?m:c).request({protocol:s.protocol,host:s.hostname,port:s.port,method:"POST",path:s.pathname+s.search,headers:a},r=>{let s="";r.setEncoding("utf8"),r.on("data",e=>{s+=e}),r.on("end",()=>{d&&clearTimeout(d);try{let r=JSON.parse(s);if(r.error){let e=r.error.data??{};i(new es(String(e.code??"COMMAND_FAILED"),String(e.message??r.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:t.meta?.requestId}));return}if(!r.result||"object"!=typeof r.result)return void i(new es("COMMAND_FAILED","Invalid daemon RPC response",{requestId:t.meta?.requestId}));if(e.baseUrl&&r.result.ok)return void tS(e,t,r.result).then(n).catch(i);n(r.result)}catch(e){d&&clearTimeout(d),i(new es("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:s},e instanceof Error?e:void 0))}})}),p=tI(e),d="number"==typeof r?setTimeout(()=>{u.destroy(),i(tw(e,l,t.meta?.requestId,t.command,p,r))},r):void 0;u.on("error",e=>{d&&clearTimeout(d),i(tv(e,t.meta?.requestId,p))}),u.write(o),u.end()})}function tI(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function tA(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function tS(e,t,r){let s=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===s.length||!e.baseUrl)return r;let o=r.data?{...r.data}:{},a=[];for(let r of s){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){a.push(r);continue}let s=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return i.resolve(t.meta?.cwd??process.cwd(),r)}(r,t);await t$({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:s,requestId:t.meta?.requestId}),o[r.field]=s,a.push({...r,localPath:s})}return o.artifacts=a,{ok:!0,data:o}}async function t$(e){var t,r;let s,o=new URL((t=e.baseUrl,r=e.artifactId,s=t.endsWith("/")?t:`${t}/`,new URL(`upload/${encodeURIComponent(r)}`,s).toString())),a="https:"===o.protocol?m:c;await f.promises.mkdir(i.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let s=!1,n=e.timeoutMs??e3,i=o=>{if(!s){if(s=!0,clearTimeout(u),o)return void f.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(o));t()}},l=a.request({protocol:o.protocol,host:o.hostname,port:o.port,method:"GET",path:o.pathname+o.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 es("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=f.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 es("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),u=setTimeout(()=>{l.destroy(new es("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);l.on("error",t=>{t instanceof es?i(t):i(new es("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),l.end()})}function tP(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 tE="metro-companion";function tL(e){return y("sha256").update(e).digest("hex")}function tN(e){return e?.trim()?e.trim():void 0}function t_(e,t){let r=i.join(e,".agent-device");if(!t)return{statePath:i.join(r,"metro-companion.json"),logPath:i.join(r,"metro-companion.log")};let s=tL(t).slice(0,12),o=i.join(r,tE);return{statePath:i.join(o,`metro-companion-${s}.json`),logPath:i.join(o,`metro-companion-${s}.log`)}}function tx(e){try{let t=JSON.parse(f.readFileSync(e,"utf8"));if(!Number.isInteger(t.pid)||0>=Number(t.pid)||"string"!=typeof t.serverBaseUrl||"string"!=typeof t.localBaseUrl||"string"!=typeof t.tokenHash||0===t.tokenHash.length)return null;let r=Array.isArray(t.consumers)?t.consumers.filter(e=>"string"==typeof e&&e.length>0):[];return{pid:Number(t.pid),startTime:"string"==typeof t.startTime?t.startTime:void 0,command:"string"==typeof t.command?t.command:void 0,serverBaseUrl:t.serverBaseUrl,localBaseUrl:t.localBaseUrl,launchUrl:tN("string"==typeof t.launchUrl?t.launchUrl:void 0),tokenHash:t.tokenHash,consumers:r}}catch{return null}}function tT(e,t){f.mkdirSync(i.dirname(e),{recursive:!0}),f.writeFileSync(e,`${JSON.stringify(t,null,2)}
37
+ `,"utf8")}function tM(e){try{let t=f.readdirSync(e);0===t.length&&f.rmdirSync(e)}catch{}}function tR(e){let t=i.dirname(e.statePath),r=i.dirname(e.logPath);var s=e.statePath;try{f.unlinkSync(s)}catch{}var o=e.logPath;try{f.unlinkSync(o)}catch{}tM(t),r!==t&&tM(r),i.basename(t)===tE&&tM(i.dirname(t))}function tO(e){return e.includes(eu)}function tC(e){return tN(e.consumerKey)??tN(e.profileKey)??null}function tU(e,t){return!t||e.consumers.includes(t)?e:{...e,consumers:[...e.consumers,t]}}async function tF(e){if(!q(e.pid))return;let t=k(e.pid);if(t&&tO(t)){try{process.kill(e.pid,"SIGTERM")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}if(!await D(e.pid,1e3)){try{process.kill(e.pid,"SIGKILL")}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return;throw t}await D(e.pid,1e3)}}}async function tj(e){let t=tC(e),r=t_(e.projectRoot,e.profileKey),s=tx(r.statePath);if(s&&function(e,t){if(!q(e.pid))return!1;if(e.startTime){let t=H(e.pid);if(!t||t!==e.startTime)return!1}let r=k(e.pid);return!!r&&!!tO(r)&&e.serverBaseUrl===ep(t.serverBaseUrl)&&e.localBaseUrl===ep(t.localBaseUrl)&&e.launchUrl===tN(t.launchUrl)&&e.tokenHash===tL(t.bearerToken)}(s,e)){let e=tU(s,t);return e!==s&&tT(r.statePath,e),{pid:s.pid,spawned:!1,statePath:r.statePath,logPath:r.logPath}}s&&(await tF(s),tR(r));let o=function(e,t){let r=function(){let e=u(import.meta.url),t=i.extname(e)||".js",r=i.join(i.dirname(e),`metro-companion${t}`);if(!f.existsSync(r))throw Error(`Metro companion entrypoint not found at ${r}. Rebuild the package to include the companion worker entry.`);return r}(),s=r.endsWith(".ts")?["--experimental-strip-types"]:[];f.mkdirSync(i.dirname(t),{recursive:!0});let o=f.openSync(t,"a"),a=0;try{let t;a=et(process.execPath,[...s,r,eu],{env:(t={...e.env??process.env,[ec]:ep(e.serverBaseUrl),[eg]:e.bearerToken,[em]:ep(e.localBaseUrl),[ef]:t_(e.projectRoot,e.profileKey).statePath},e.launchUrl?.trim()?t[eh]=e.launchUrl.trim():delete t[eh],t),stdio:["ignore",o,o]})}finally{f.closeSync(o)}if(!Number.isInteger(a)||a<=0)throw Error("Failed to start Metro companion process.");return{pid:a,startTime:H(a)??void 0,command:k(a)??void 0,serverBaseUrl:ep(e.serverBaseUrl),localBaseUrl:ep(e.localBaseUrl),launchUrl:tN(e.launchUrl),tokenHash:tL(e.bearerToken),consumers:[]}}(e,r.logPath);return tT(r.statePath,tU(o,t)),{pid:o.pid,spawned:!0,statePath:r.statePath,logPath:r.logPath}}async function tV(e){let t=tC(e),r=t_(e.projectRoot,e.profileKey),s=tx(r.statePath);if(!s)return tR(r),{stopped:!1,statePath:r.statePath};let o=t?{...s,consumers:s.consumers.filter(e=>e!==t)}:{...s,consumers:[]};return o.consumers.length>0?(tT(r.statePath,o),{stopped:!1,statePath:r.statePath}):(await tF(s),tR(r),{stopped:!0,statePath:r.statePath})}function tB(e){return"string"==typeof e&&e.trim()?ep(e.trim()):""}function tG(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function tq(e,t,r){return V(e,{env:t,cwd:r})}function tH(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}function tK(e,t,r){if(null==e||""===e)return t;let s=Number.parseInt(String(e),10);return Number.isInteger(s)?Math.max(s,r):t}function tJ(e,t){return{platform:t,bundleUrl:ed(e,t)}}function tz(e,t){return{platform:t,metroHost:tG(e?.metro_host),metroPort:e?.metro_port,bundleUrl:tG(e?.metro_bundle_url),launchUrl:tG(e?.launch_url)}}async function tW(e){await new Promise(t=>setTimeout(t,e))}async function tX(e,t,r={}){try{let s=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:s.ok,status:s.status,body:await s.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function tY(e,t){try{let r=await tX(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}function tZ(e,t){let r=Error(e);return r.retryable=t,r}async function tQ(e){var t,r,s,o;let a;try{a=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:"POST",headers:(t=e.baseUrl,r=e.bearerToken,{Authorization:`Bearer ${r}`,"Content-Type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({ios_runtime:e.runtime,timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){if(t instanceof Error&&"TimeoutError"===t.name)throw tZ(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0);throw tZ(t instanceof Error?t.message:String(t),!0)}let n=await a.text(),i=n?JSON.parse(n):{};if(!a.ok)throw tZ(`/api/metro/bridge failed (${a.status}): ${JSON.stringify(i)}`,(s=a.status,!!(s>=500||408===s||425===s||429===s||JSON.stringify(i).includes("Metro companion is not connected"))));return{enabled:(o=i.data??i).enabled,baseUrl:o.base_url,statusUrl:o.status_url??"",bundleUrl:o.bundle_url??"",iosRuntime:tz(o.ios_runtime,"ios"),androidRuntime:tz(o.android_runtime,"android"),upstream:{bundleUrl:o.upstream.bundle_url??"",host:o.upstream.host??"",port:o.upstream.port??0,statusUrl:o.upstream.status_url??""},probe:{reachable:o.probe.reachable,statusCode:o.probe.status_code,latencyMs:o.probe.latency_ms,detail:o.probe.detail}}}function t0(e,t,r,s,o){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&a.push(`bridgeError=${t}`),r?.probe.reachable===!1&&a.push(`bridgeProbe=${r.probe.detail||`unreachable (status ${r.probe.statusCode||0})`}`),s&&s!==t&&a.push(`initialBridgeError=${s}`),o&&a.push(`metroCompanionLog=${o}`),a.join(" ")}async function t1(e,t,r){let s=Date.now()+t;for(;Date.now()<s;){let t=Math.min(r,Math.max(s-Date.now(),1));if(await tY(e,t))return!0;let o=Math.min(500,Math.max(s-Date.now(),0));o>0&&await tW(o)}return!1}async function t2(e){let t=Date.now()+e.startupTimeoutMs,r=null,s=null;for(;Date.now()<t;){try{let t=await tQ({baseUrl:e.baseUrl,bearerToken:e.bearerToken,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(!1!==t.probe.reachable)return t;r=t,s=null}catch(e){if(s=e instanceof Error?e.message:String(e),!(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable))break}let o=Math.min(1e3,Math.max(t-Date.now(),0));o>0&&await tW(o)}throw Error(t0(e.baseUrl,s,r,e.initialBridgeError,e.companionLogPath))}async function t3(e={}){let t=e.env??process.env,r=process.cwd(),s=tq(e.projectRoot??r,t,r),o=function(e,t){if("auto"!==t)return t;let r=function(e){let t=i.join(e,"package.json");if(!tH(t))throw new es("INVALID_ARGS",`package.json not found at ${t}`);return JSON.parse(f.readFileSync(t,"utf8"))}(e);return"string"==typeof({...r.dependencies??{},...r.devDependencies??{}}).expo?"expo":"react-native"}(s,e.kind??"auto"),a=function(e){if(null==e||""===e)return 8081;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<1||t>65535)throw new es("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return t}(e.metroPort??8081),n=tG(e.listenHost)??"0.0.0.0",l=tG(e.statusHost)??"127.0.0.1",u=tB(e.publicBaseUrl),p=tK(e.startupTimeoutMs,18e4,3e4),d=tK(e.probeTimeoutMs,1e4,1e3),c=e.reuseExisting??!0,m=e.installDependenciesIfNeeded??!0,h=e.runtimeFilePath?tq(e.runtimeFilePath,t,r):null,g=tq(e.logPath??i.join(s,".agent-device","metro.log"),t,r);if(!u)throw new es("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:y,proxyBaseUrl:b,proxyBearerToken:w}=function(e,t){if(e&&!t)throw new es("INVALID_ARGS","metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.");if(!e&&t)throw new es("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(tB(e.proxyBaseUrl),tG(e.proxyBearerToken)??""),v=m?function(e,t){if(function(e){try{return f.statSync(e).isDirectory()}catch{return!1}}(i.join(e,"node_modules")))return{installed:!1};let r=tH(i.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:tH(i.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return ea(r.command,r.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:r.command}}(s,t):{installed:!1},k=`http://${l}:${a}/status`,D=!1,I=!1,A=0;if(c&&await tY(k,d))I=!0;else if(D=!0,A=function(e,t,r,s,o,a){let n="expo"===t?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(r)]}:{command:"npx",installArgs:["react-native","start","--host",s,"--port",String(r)]};f.mkdirSync(i.dirname(o),{recursive:!0});let l=f.openSync(o,"a"),u=0;try{u=et(n.command,n.installArgs,{cwd:e,env:a,stdio:["ignore",l,l]})}finally{f.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw Error("Failed to start Metro. Expected a detached child PID.");return{pid:u}}(s,o,a,n,g,t).pid,!await t1(k,p,d))throw Error(`Metro did not become ready at ${k} within ${p}ms. Check ${g}.`);let S=tJ(u,"ios"),$=tJ(u,"android"),P=null,E=null;if(y)try{P=await tQ({baseUrl:b,bearerToken:w,runtime:{metro_bundle_url:S.bundleUrl},timeoutMs:d})}catch(e){E=e instanceof Error?e.message:String(e)}if(y&&(!P||!1===P.probe.reachable)){let r;try{r=(await tj({projectRoot:s,serverBaseUrl:b,bearerToken:w,localBaseUrl:`http://${l}:${a}`,launchUrl:tG(e.launchUrl),profileKey:tG(e.companionProfileKey),consumerKey:tG(e.companionConsumerKey),env:t})).logPath}catch(e){throw Error(t0(b,e instanceof Error?e.message:String(e),P,E))}try{P=await t2({baseUrl:b,bearerToken:w,runtime:{metro_bundle_url:S.bundleUrl},probeTimeoutMs:d,startupTimeoutMs:p,initialBridgeError:E,companionLogPath:r})}catch(e){throw e instanceof Error?e:Error(String(e))}}let L=P?.iosRuntime??S,N=P?.androidRuntime??$,_={projectRoot:s,kind:o,dependenciesInstalled:v.installed,packageManager:v.packageManager??null,started:D,reused:I,pid:A,logPath:g,statusUrl:k,runtimeFilePath:h,iosRuntime:L,androidRuntime:N,bridge:P};return h&&(f.mkdirSync(i.dirname(h),{recursive:!0}),f.writeFileSync(h,JSON.stringify(_,null,2))),_}function t5(e,t,r,s){let o=r(e[t]);if(void 0===o)throw new es("COMMAND_FAILED",s,{response:e});return o}function t8(e,t){return t5(e,t,rt,`Daemon response is missing "${t}".`)}function t4(e,t){return rt(e[t])}function t6(e,t){var r;let s;return r=rt,null===(s=e[t])?null:r(s)}function t7(e,t){return t5(e,t,rs,`Daemon response has invalid "${t}".`)}function t9(e,t){return function(e){return"tv"===e||"mobile"===e||"desktop"===e?e:void 0}(e[t])??"mobile"}function re(e,t){let r=e[t];if(!rn(r))return;let s="number"==typeof r.x?r.x:void 0,o="number"==typeof r.y?r.y:void 0,a="number"==typeof r.width?r.width:void 0,n="number"==typeof r.height?r.height:void 0;if(void 0!==s&&void 0!==o&&void 0!==a&&void 0!==n)return{x:s,y:o,width:a,height:n}}function rt(e){return"string"==typeof e&&e.length>0?e:void 0}function rr(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function rs(e){return"ios"===e||"macos"===e||"android"===e?e:void 0}function ro(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function ra(e){if(!rn(e))throw new es("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function rn(e){return"object"==typeof e&&null!==e}function ri(e){let t={};for(let[r,s]of Object.entries(e))void 0!==s&&(t[r]=s);return t}function rl(e,t){let r=t4(e,"bundleId"),s=t4(e,"package");return{app:t8(e,"app"),appPath:t8(e,"appPath"),platform:t7(e,"platform"),appId:r??s,bundleId:r,package:s,identifiers:P({session:t,bundleId:r,packageName:s})}}function ru(e){let t=ra(e),r=t7(t,"platform"),s=t8(t,"id"),o=t8(t,"name");return{platform:r,target:t9(t,"target"),kind:t5(t,"kind",ro,'Daemon response has invalid "kind".'),id:s,name:o,booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:$(r,s,o),ios:"ios"===r?{udid:s}:void 0,android:"android"===r?{serial:s}:void 0}}function rp(e){let t=ra(e),r=t7(t,"platform"),s=t8(t,"id"),o=t8(t,"name"),a=t9(t,"target"),n=t8(t,"device"),i={session:o,...$(r,s,n)};return{name:o,createdAt:t5(t,"createdAt",rr,'Daemon response is missing numeric "createdAt".'),device:{platform:r,target:a,id:s,name:n,identifiers:i,ios:"ios"===r?{udid:s,simulatorSetPath:t6(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:s}:void 0},identifiers:i}}function rd(e,t){return t??e??"default"}function rc(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function rm(e,t,r){var s;if(e.json)return void eW({success:!0,data:t});let o=r?.();o&&(s=o,process.stdout.write(s.endsWith("\n")?s:`${s}
38
+ `))}function rf(e,t){rm(e,t,()=>M(t))}let rh=async({positionals:e,flags:t,client:r})=>{if("list"!==(e[0]??"list"))throw new es("INVALID_ARGS","session only supports list");let s={sessions:(await r.sessions.list()).map(I)};return rm(t,s,()=>JSON.stringify(s,null,2)),!0},rg=async({flags:e,client:t})=>{let r=await t.devices.list(rc(e));return rm(e,{devices:r.map(O)},()=>r.map(ry).join("\n")),!0};function ry(e){let t=e.kind?` ${e.kind}`:"",r=e.target?` target=${e.target}`:"",s="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${r})${s}`}let rb=async({flags:e,client:t})=>{if(!e.device)throw new es("INVALID_ARGS","ensure-simulator requires --device <name>");let r=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet});return rm(e,R(r),()=>{let e=r.created?"Created":"Reused",t=r.booted?" (booted)":"";return r.runtime?`${e}: ${r.device} ${r.udid}${t}
39
+ Runtime: ${r.runtime}`:`${e}: ${r.device} ${r.udid}${t}`}),!0},rw=async({positionals:e,flags:t,client:r})=>{if("prepare"!==(e[0]??"").toLowerCase())throw new es("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new es("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let s=await r.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile});return rm(t,s,()=>JSON.stringify(s,null,2)),!0},rv=async({positionals:e,flags:t,client:r})=>{let s=T(await rI("install",e,t,r));return rf(t,s),!0},rk=async({positionals:e,flags:t,client:r})=>{let s=T(await rI("reinstall",e,t,r));return rf(t,s),!0},rD=async({positionals:e,flags:t,client:r})=>{let s=z(await rA(e,t,r));return rf(t,s),!0};async function rI(e,t,r,s){let o=t[0],a=t[1];if(!o||!a)throw new es("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let n={app:o,appPath:a,...rc(r)};return"install"===e?await s.apps.install(n):await s.apps.reinstall(n)}async function rA(e,t,r){let s=e[0]?.trim();if(!s)throw new es("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new es("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await r.apps.installFromSource({...rc(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:s,headers:function(e){if(!e||0===e.length)return;let t={};for(let r of e){let e=r.indexOf(":");if(e<=0)throw new es("INVALID_ARGS",`Invalid --header value "${r}". Expected "name:value".`);let s=r.slice(0,e).trim(),o=r.slice(e+1).trim();if(!s)throw new es("INVALID_ARGS",`Invalid --header value "${r}". Header name cannot be empty.`);t[s]=o}return t}(t.header)}})}async function rS(e){await tV(e)}let r$=[{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"}],rP=new Map(r$.map(e=>[e.key,e]));function rE(e){let t=e.env??process.env;return V(e.configPath,{cwd:e.cwd,env:t})}function rL(e){let t=function(e){let t,r,s=e.env??process.env,o=rE(e);if(!f.existsSync(o))throw new es("INVALID_ARGS",`Remote config file not found: ${o}`);try{t=f.readFileSync(o,"utf8")}catch(e){throw new es("INVALID_ARGS",`Failed to read remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}try{r=JSON.parse(t)}catch(e){throw new es("INVALID_ARGS",`Invalid JSON in remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new es("INVALID_ARGS",`Remote config file must contain a JSON object: ${o}`);let a={},n=r,l=i.dirname(o);for(let[e,t]of Object.entries(n)){let r=rP.get(e);if(!r)throw new es("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${o}.`);let n=eC(r,t,`remote config file ${o}`,e);a[r.key]="string"==typeof n&&"path"in r&&r.path?V(n,{cwd:l,env:s}):n}return{resolvedPath:o,profile:a}}(e);return{resolvedPath:t.resolvedPath,profile:function(...e){let t={};for(let r of e)if(r)for(let e of r$){let s=r[e.key];void 0!==s&&(t[e.key]=s)}return t}(function(e=process.env){let t={};for(let r of r$){let s=(function(e){let t=rP.get(e);return[eO(e),...t?.legacyEnvNames??[]]})(r.key).map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);s&&(t[r.key]=eC(r,s.value,`environment variable ${s.name}`,s.name))}return t}(e.env),t.profile)}}async function rN(e,t){if(!e.remoteConfig)return;let r=e.platform;if("ios"!==r&&"android"!==r)throw new es("INVALID_ARGS",'open --remote-config requires platform "ios" or "android" in the remote config file or CLI flags.');if(!e.metroPublicBaseUrl)throw new es("INVALID_ARGS",'open --remote-config requires "metroPublicBaseUrl" in the remote config file.');let s=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,launchUrl:e.launchUrl,companionProfileKey:rE({configPath:e.remoteConfig,cwd:process.cwd(),env:process.env}),companionConsumerKey:e.session,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return"ios"===r?s.iosRuntime:s.androidRuntime}let r_=255*Math.sqrt(3);async function rx(e,t,r={}){await rT(e,"Baseline image not found"),await rT(t,"Current screenshot not found");let s=r.outputPath,[o,a]=await Promise.all([h.readFile(e),h.readFile(t)]),n=W(o,"baseline screenshot"),l=W(a,"current screenshot"),u=r.threshold??.1;if(n.width!==l.width||n.height!==l.height){let e=n.width*n.height;return await rM(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:n.width,height:n.height},actual:{width:l.width,height:l.height}}}}let p=n.width*n.height,d=u*r_,c=new w({width:n.width,height:n.height}),m=0;for(let e=0;e<n.data.length;e+=4){if(Math.sqrt((n.data[e]-l.data[e])**2+(n.data[e+1]-l.data[e+1])**2+(n.data[e+2]-l.data[e+2])**2)>d){m+=1,c.data[e]=255,c.data[e+1]=0,c.data[e+2]=0,c.data[e+3]=255;continue}let t=Math.round(.3*Math.round((n.data[e]+n.data[e+1]+n.data[e+2])/3));c.data[e]=t,c.data[e+1]=t,c.data[e+2]=t,c.data[e+3]=255}m>0&&s?(await h.mkdir(i.dirname(s),{recursive:!0}),await h.writeFile(s,w.sync.write(c))):await rM(r.outputPath);let f=p>0?Math.round(m/p*1e4)/100:0;return{...m>0&&s?{diffPath:s}:{},totalPixels:p,differentPixels:m,mismatchPercentage:f,match:0===m}}async function rT(e,t){try{await h.access(e)}catch{throw new es("INVALID_ARGS",`${t}: ${e}`)}}async function rM(e){if(e)try{await h.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}let rR={session:rh,devices:rg,"ensure-simulator":rb,metro:rw,install:rv,reinstall:rk,"install-from-source":rD,open:async({positionals:e,flags:t,client:r})=>{if(!e[0])return!1;let s=await rN(t,r),o=_(await r.apps.open({app:e[0],url:e[1],surface:t.surface,activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,runtime:s,...rc(t)}));return rf(t,o),!0},close:async({positionals:e,flags:t,client:r})=>{let s=(()=>{let e;if(!t.remoteConfig)return null;try{e=rL({configPath:t.remoteConfig,cwd:process.cwd(),env:process.env})}catch{return null}return e.profile.metroProjectRoot&&e.profile.metroProxyBaseUrl?{projectRoot:e.profile.metroProjectRoot,profileKey:e.resolvedPath,consumerKey:t.session}:null})(),o=async e=>{try{return await e()}finally{try{s&&await rS(s)}catch{}}},a=B(await o(async()=>e[0]?await r.apps.close({app:e[0],shutdown:t.shutdown}):await r.sessions.close({shutdown:t.shutdown})));return rf(t,a),!0},snapshot:async({flags:e,client:t})=>{let r=A(await t.capture.snapshot({...rc(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return rm(e,r,()=>eY(r,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},screenshot:async({positionals:e,flags:t,client:r})=>{let s=await r.capture.screenshot({path:e[0]??t.out,overlayRefs:t.overlayRefs});return rm(t,{path:s.path,...s.overlayRefs?{overlayRefs:s.overlayRefs}:{}},()=>s.overlayRefs?`Annotated ${s.overlayRefs.length} refs onto ${s.path}`:s.path),!0},diff:async({positionals:e,flags:t,client:r})=>{let s;if("screenshot"!==e[0])return!1;let o=t.baseline;if(!o||"string"!=typeof o)throw new es("INVALID_ARGS","diff screenshot requires --baseline <path>");let a=V(o),n="string"==typeof t.out?V(t.out):void 0,u=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(u=Number(t.threshold))||u<0||u>1))throw new es("INVALID_ARGS","--threshold must be a number between 0 and 1");let p=f.mkdtempSync(i.join(b.tmpdir(),"agent-device-diff-current-")),d=i.join(p,`current-${Date.now()}.png`),c=(await r.capture.screenshot({path:d})).path;try{s=await rx(a,c,{threshold:u,outputPath:n})}finally{try{f.unlinkSync(c)}catch{}try{f.rmSync(p,{recursive:!0,force:!0})}catch{}}return rm(t,s,()=>(function(e){let t=eQ(),r=!0===e.match,s=eZ(e.differentPixels),o=eZ(e.totalPixels),a=eZ(e.mismatchPercentage),n=e.diffPath,u=e.dimensionMismatch,p=[];if(r){let e=t?l("green","✓"):"✓";p.push(`${e} Screenshots match.`)}else if(u){let e=t?l("red","✗"):"✗",r=u.expected,s=u.actual;p.push(`${e} Screenshots have different dimensions: expected ${r?.width}x${r?.height}, got ${s?.width}x${s?.height}`)}else{let e=t?l("red","✗"):"✗",r=0===a&&s>0?"<0.01":String(a);p.push(`${e} ${r}% pixels differ`)}if(n&&!r){var d;let e,r,s=(d=n,e=process.cwd(),""!==(r=i.relative(e,d))&&(r.startsWith("..")||i.isAbsolute(r))?d:""===r?".":`.${i.sep}${r}`),o=t?l("dim","Diff image:"):"Diff image:",a=t?l("green",s):s;p.push(` ${o} ${a}`)}if(!r&&!u){let e=t?l("red",String(s)):String(s);p.push(` ${e} different / ${o} total pixels`)}return`${p.join("\n")}
40
+ `})(s)),!0}};async function rO(e){let t=rR[e.command];return!!t&&await t(e)}function rC(e){let{suite:t,json:r,verbose:s,reportJunit:o}=e;return(o&&function(e,t){let r=i.dirname(e);try{f.mkdirSync(r,{recursive:!0}),f.writeFileSync(e,function(e){let t=['<?xml version="1.0" encoding="UTF-8"?>',"<testsuites>",` <testsuite name="agent-device replay suite" tests="${e.total}" failures="${e.failed}" skipped="${e.skipped}" time="${rj(e.durationMs)}">`];for(let r of e.tests)t.push(...function(e){let t=rV(i.basename(e.file)),r=rV("."===i.dirname(e.file)?e.file:i.dirname(e.file)),s=rV(e.file),o=rj(e.durationMs),a=[` <testcase classname="${r}" name="${t}" file="${s}" time="${o}">`];"failed"===e.status?a.push(` <failure message="${rV(e.error.message)}">${rV(function(e){let t=[e.error.message];e.error.hint&&t.push(`hint: ${e.error.hint}`),e.error.diagnosticId&&t.push(`diagnosticId: ${e.error.diagnosticId}`),e.error.logPath&&t.push(`logPath: ${e.error.logPath}`),e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`);let r=e.error.details?JSON.stringify(e.error.details,null,2):void 0;return r&&t.push(`details: ${r}`),t.join("\n")}(e))}</failure>`):"skipped"===e.status&&a.push(` <skipped message="${rV(e.message)}" />`);let n=function(e){let t=[`status: ${e.status}`,`durationMs: ${e.durationMs}`];return"attempts"in e&&t.push(`attempts: ${e.attempts}`),"session"in e&&t.push(`session: ${e.session}`),"replayed"in e&&t.push(`replayed: ${e.replayed}`),"healed"in e&&t.push(`healed: ${e.healed}`),"artifactsDir"in e&&e.artifactsDir&&t.push(`artifactsDir: ${e.artifactsDir}`),"passed"===e.status&&e.attempts>1&&t.push("flaky: true"),t.join("\n")}(e);return n&&a.push(` <system-out>${rV(n)}</system-out>`),a.push(" </testcase>"),a}(r));return t.push(" </testsuite>"),t.push("</testsuites>"),`${t.join("\n")}
41
+ `}(t),"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new es("COMMAND_FAILED",`Failed to write JUnit report to ${e}: ${t}`)}}(o,t),r)?(eW({success:!0,data:t}),function(e){return+(e.failed>0)}(t)):function(e,t={}){let r=e.tests.filter(rF);if(t.verbose)for(let t of e.tests)!function(e){if("failed"===e.status)return rU(e);let t="passed"===e.status?rF(e)?"FLAKY":"PASS":"skipped"===e.status?"SKIP":"INFO",r="attempts"in e&&e.attempts>1?` after ${e.attempts} attempts`:"",s=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`${t} ${e.file}${r}${s}
42
42
  `),"skipped"===e.status&&process.stdout.write(` ${e.message??"skipped"}
43
- `)}(t);else{for(let t of e.failures)rR(t);for(let e of r)!function(e){let t=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FLAKY ${e.file} after ${e.attempts} attempts${t}
43
+ `)}(t);else{for(let t of e.failures)rU(t);for(let e of r)!function(e){let t=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FLAKY ${e.file} after ${e.attempts} attempts${t}
44
44
  `)}(e)}let s="number"==typeof e.durationMs?e.durationMs:void 0,o=r.length>0?`, ${r.length} flaky`:"";return process.stdout.write(`Test summary: ${e.passed} passed, ${e.failed} failed${o}${void 0!==s?` in ${s}ms`:""}
45
- `),function(e){return+(e.failed>0)}(e)}(t,{verbose:s})}function rR(e){let t=e.attempts>1?` after ${e.attempts} attempts`:"",r=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FAIL ${e.file}${t}${r}
45
+ `),function(e){return+(e.failed>0)}(e)}(t,{verbose:s})}function rU(e){let t=e.attempts>1?` after ${e.attempts} attempts`:"",r=e.durationMs>0?` (${e.durationMs}ms)`:"";process.stdout.write(`FAIL ${e.file}${t}${r}
46
46
  `),process.stdout.write(` ${e.error?.message??"Unknown test failure"}
47
47
  `),e.error?.hint&&process.stdout.write(` hint: ${e.error.hint}
48
48
  `),e.artifactsDir&&process.stdout.write(` artifacts: ${e.artifactsDir}
49
49
  `),e.error?.logPath&&process.stdout.write(` log: ${e.error.logPath}
50
50
  `),e.error?.diagnosticId&&process.stdout.write(` diagnostic: ${e.error.diagnosticId}
51
- `)}function rO(e){return"passed"===e.status&&e.attempts>1}function rC(e){return(Math.max(0,e)/1e3).toFixed(3)}function rU(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function rF(e,t={}){let r=rj(t),s={...e};return r.defaultPlatform&&void 0===s.platform&&(s.platform=r.defaultPlatform),s}function rj(e){var t,r,s,o;let a,n=e.env??process.env,i=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new es("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(n.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??n.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:i,lockPolicy:(r=e.policyOverrides,s=n,o=l,(a=r?.sessionLock??r?.sessionLockConflicts??rV(s.AGENT_DEVICE_SESSION_LOCK)??rV(s.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||function(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;default:return!1}}(s.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function rV(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new es("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let rB=["remoteConfig",...rI],rG={sendToDaemon:e4};async function rq(e,t=rG){let r=Z(),s=F(),o=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),a=e.includes("--json"),n=function(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r.startsWith("--session=")){let e=r.slice(10).trim();return e.length>0?e:null}if("--session"===r){let r=e[t+1]?.trim();if(r&&!r.startsWith("-"))return r;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await er({session:n,requestId:r,command:e[0],debug:o},async()=>{var n,u,p,d,c,m,h,g,y,b,w;let v;try{let t,r,s,o,a,l,w,k,D;n={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,s=[],o=[],a=!0;for(let n=0;n<e.length;n+=1){let i=e[n];if(a&&"--"===i){a=!1;continue}if(!a){r?s.push(i):r=eK(i);continue}let l=i.startsWith("--"),u=i.startsWith("-")&&i.length>1;if(!l&&!u){r?s.push(i):r=eK(i);continue}let[p,d]=l?eG(i):[i,void 0],c=eD.get(p);if(!c){if(function(e,t,r){var s;if(s=r,!/^-\d+(\.\d+)?$/.test(s)||!e)return!1;let o=eA(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(r,s,i)){r?s.push(i):r=i;continue}throw new es("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,r,s){if(void 0!==e.setValue){if(void 0!==r)throw new es("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==r)throw new es("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==r){if(0===r.trim().length)throw new es("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:r,consumeNext:!1}}return void 0===s||eH(s)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(s)?{value:!0,consumeNext:!1}:{value:s,consumeNext:!0}}let o=r??s;if(void 0===o||void 0===r&&eH(o))throw new es("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new es("INVALID_ARGS",`Invalid ${eq(t)}: ${o}`);return{value:o,consumeNext:void 0===r}}let a=Number(o);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new es("INVALID_ARGS",`Invalid ${eq(t)}: ${o}`);return{value:Math.floor(a),consumeNext:void 0===r}}(c,p,d,e[n+1]);m.consumeNext&&(n+=1);let f=t[c.key];if(c.multiple){let e=Array.isArray(f)?[...f,m.value]:void 0===f?[m.value]:[f,m.value];t[c.key]=e}else t[c.key]=m.value;o.push({key:c.key,token:p})}return{command:r,positionals:s,flags:t,warnings:[],providedFlags:o}}(e),r=n?.env??process.env,s=n?.cwd??process.cwd(),o=(u={cliFlags:t.flags,cwd:s,env:r}).cliFlags.remoteConfig?{...function(e){let t={};for(let r of rI){let s=e[r];void 0!==s&&(t[r]=s)}return t}(r$({configPath:u.cliFlags.remoteConfig,cwd:u.cwd,env:u.env}).profile),remoteConfig:u.cliFlags.remoteConfig}:{},w=eg((a=(p={command:t.command,cwd:s,cliFlags:t.flags,env:r}).env??process.env,l=eg({},function(e){let t={};for(let r of e)eg(t,function(e,t){let r,s;if(!f.existsSync(e)){if(t)throw new es("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{r=f.readFileSync(e,"utf8")}catch(t){throw new es("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{s=JSON.parse(r)}catch(t){throw new es("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new es("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[s,o]of Object.entries(e)){let e=ej.get(s);if(!e)throw new es("INVALID_ARGS",`Unknown config key "${s}" in ${t}.`);if(!e.config.enabled)throw new es("INVALID_ARGS",`Unsupported config key "${s}" in ${t}.`);r[s]=eR(eB(e),o,t,s)}return r}(s,`config file ${e}`)}(r.path,r.required));return t}((d=p.cwd,c=p.cliFlags.config,m=a,(D=c??m.AGENT_DEVICE_CONFIG)?[{path:(h=D,g=d,y=m,V(h,{cwd:g,env:y})),required:!0}]:[{path:(b=m,i.join(x("~",{env:b}),".agent-device","config.json")),required:!1},{path:i.resolve(d,"agent-device.json"),required:!1}]))),eg(l,function(e,t){var r,s,o;let a={};for(let n of eF.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=n.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(a[n.key]=(r=t.value,s=`environment variable ${t.name}`,o=t.name,eR(eB(n),r,s,o)))}return a}(a,p.command))),o),k=function(e,t){let r=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),s=[...e.warnings],o=eg({json:!1,help:!1,version:!1},t?.defaultFlags??{});eg(o,e.flags);let a=eA(e.command),n=e.providedFlags.filter(t=>!eV(t.key,e.command));if(n.length>0){var i,l;let t=n.map(e=>e.token),a=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(r)throw new es("INVALID_ARGS",a);for(let e of(s.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),n))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(eV(t,e.command)||delete o[t]);if(function(e){if("back"===e.command&&!(new Set(e.providedFlags.filter(e=>"backMode"===e.key).map(e=>e.token)).size<=1))throw new es("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),a?.defaults)for(let[e,t]of Object.entries(a.defaults))void 0===o[e]&&(o[e]=t);if("batch"===e.command&&1!=+!!o.steps+ +!!o.stepsFile)throw new es("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return function(e){if(e.flags.help)return e;if("snapshot"===e.command&&e.flags.snapshotDiff){let{snapshotDiff:t,...r}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:r,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:o,warnings:s})}(t,{strictFlags:n?.strictFlags,defaultFlags:w}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&void 0===e[r]&&(e[r]=s)}(k.flags,function(e){let t={};for(let r of rB){let s=e[r];void 0!==s&&(t[r]=s)}return t}(w)),v=k}catch(t){el({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=ee(t,{diagnosticId:eo().diagnosticId,logPath:en({force:!0})??void 0});a?eJ({success:!1,error:e}):ez(e,{showDetails:o}),process.exit(1);return}for(let e of v.warnings)process.stderr.write(`Warning: ${e}
51
+ `)}function rF(e){return"passed"===e.status&&e.attempts>1}function rj(e){return(Math.max(0,e)/1e3).toFixed(3)}function rV(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function rB(e,t={}){let r=rG(t),s={...e};return r.defaultPlatform&&void 0===s.platform&&(s.platform=r.defaultPlatform),s}function rG(e){var t,r,s,o;let a,n=e.env??process.env,i=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new es("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(n.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??n.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:i,lockPolicy:(r=e.policyOverrides,s=n,o=l,(a=r?.sessionLock??r?.sessionLockConflicts??rq(s.AGENT_DEVICE_SESSION_LOCK)??rq(s.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(r?.sessionLocked===!0||function(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;default:return!1}}(s.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function rq(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new es("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}let rH=r$.map(e=>e.key),rK=["remoteConfig","session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],rJ={sendToDaemon:e7};async function rz(e,t=rJ){let r=Z(),s=F(),o=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),a=e.includes("--json"),n=function(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r.startsWith("--session=")){let e=r.slice(10).trim();return e.length>0?e:null}if("--session"===r){let r=e[t+1]?.trim();if(r&&!r.startsWith("-"))return r;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await er({session:n,requestId:r,command:e[0],debug:o},async()=>{var n,u,p,d,c,m,h,g,y,b,w;let v;try{let t,r,s,o,a,l,w,k,D;n={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},r=null,s=[],o=[],a=!0;for(let n=0;n<e.length;n+=1){let i=e[n];if(a&&"--"===i){a=!1;continue}if(!a){r?s.push(i):r=ez(i);continue}let l=i.startsWith("--"),u=i.startsWith("-")&&i.length>1;if(!l&&!u){r?s.push(i):r=ez(i);continue}let[p,d]=l?eH(i):[i,void 0],c=eA.get(p);if(!c){if(function(e,t,r){var s;if(s=r,!/^-\d+(\.\d+)?$/.test(s)||!e)return!1;let o=e$(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(r,s,i)){r?s.push(i):r=i;continue}throw new es("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,r,s){if(void 0!==e.setValue){if(void 0!==r)throw new es("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==r)throw new es("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==r){if(0===r.trim().length)throw new es("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:r,consumeNext:!1}}return void 0===s||eJ(s)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(s)?{value:!0,consumeNext:!1}:{value:s,consumeNext:!0}}let o=r??s;if(void 0===o||void 0===r&&eJ(o))throw new es("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===r};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new es("INVALID_ARGS",`Invalid ${eK(t)}: ${o}`);return{value:o,consumeNext:void 0===r}}let a=Number(o);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new es("INVALID_ARGS",`Invalid ${eK(t)}: ${o}`);return{value:Math.floor(a),consumeNext:void 0===r}}(c,p,d,e[n+1]);m.consumeNext&&(n+=1);let f=t[c.key];if(c.multiple){let e=Array.isArray(f)?[...f,m.value]:void 0===f?[m.value]:[f,m.value];t[c.key]=e}else t[c.key]=m.value;o.push({key:c.key,token:p})}return{command:r,positionals:s,flags:t,warnings:[],providedFlags:o}}(e),r=n?.env??process.env,s=n?.cwd??process.cwd(),o=(u={cliFlags:t.flags,cwd:s,env:r}).cliFlags.remoteConfig?{...function(e){let t={};for(let r of rH){let s=e[r];void 0!==s&&(t[r]=s)}return t}(rL({configPath:u.cliFlags.remoteConfig,cwd:u.cwd,env:u.env}).profile),remoteConfig:u.cliFlags.remoteConfig}:{},w=eb((a=(p={command:t.command,cwd:s,cliFlags:t.flags,env:r}).env??process.env,l=eb({},function(e){let t={};for(let r of e)eb(t,function(e,t){let r,s;if(!f.existsSync(e)){if(t)throw new es("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{r=f.readFileSync(e,"utf8")}catch(t){throw new es("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{s=JSON.parse(r)}catch(t){throw new es("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new es("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let r={};for(let[s,o]of Object.entries(e)){let e=eB.get(s);if(!e)throw new es("INVALID_ARGS",`Unknown config key "${s}" in ${t}.`);if(!e.config.enabled)throw new es("INVALID_ARGS",`Unsupported config key "${s}" in ${t}.`);r[s]=eC(eq(e),o,t,s)}return r}(s,`config file ${e}`)}(r.path,r.required));return t}((d=p.cwd,c=p.cliFlags.config,m=a,(D=c??m.AGENT_DEVICE_CONFIG)?[{path:(h=D,g=d,y=m,V(h,{cwd:g,env:y})),required:!0}]:[{path:(b=m,i.join(x("~",{env:b}),".agent-device","config.json")),required:!1},{path:i.resolve(d,"agent-device.json"),required:!1}]))),eb(l,function(e,t){var r,s,o;let a={};for(let n of eV.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=n.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(a[n.key]=(r=t.value,s=`environment variable ${t.name}`,o=t.name,eC(eq(n),r,s,o)))}return a}(a,p.command))),o),k=function(e,t){let r=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),s=[...e.warnings],o=eb({json:!1,help:!1,version:!1},t?.defaultFlags??{});eb(o,e.flags);let a=e$(e.command),n=e.providedFlags.filter(t=>!eG(t.key,e.command));if(n.length>0){var i,l;let t=n.map(e=>e.token),a=(i=e.command,l=t,i?1===l.length?`Flag ${l[0]} is not supported for command ${i}.`:`Flags ${l.join(", ")} are not supported for command ${i}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(r)throw new es("INVALID_ARGS",a);for(let e of(s.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),n))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(eG(t,e.command)||delete o[t]);if(function(e){if("back"===e.command&&!(new Set(e.providedFlags.filter(e=>"backMode"===e.key).map(e=>e.token)).size<=1))throw new es("INVALID_ARGS","back accepts only one explicit mode flag: use either --in-app or --system.")}(e),a?.defaults)for(let[e,t]of Object.entries(a.defaults))void 0===o[e]&&(o[e]=t);if("batch"===e.command&&1!=+!!o.steps+ +!!o.stepsFile)throw new es("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return function(e){if(e.flags.help)return e;if("snapshot"===e.command&&e.flags.snapshotDiff){let{snapshotDiff:t,...r}=e.flags;return{command:"diff",positionals:["snapshot",...e.positionals],flags:r,warnings:e.warnings}}return e}({command:e.command,positionals:e.positionals,flags:o,warnings:s})}(t,{strictFlags:n?.strictFlags,defaultFlags:w}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[r,s]of Object.entries(t))void 0!==s&&void 0===e[r]&&(e[r]=s)}(k.flags,function(e){let t={};for(let r of rK){let s=e[r];void 0!==s&&(t[r]=s)}return t}(w)),v=k}catch(t){el({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=ee(t,{diagnosticId:eo().diagnosticId,logPath:en({force:!0})??void 0});a?eW({success:!1,error:e}):eX(e,{showDetails:o}),process.exit(1);return}for(let e of v.warnings)process.stderr.write(`Warning: ${e}
52
52
  `);v.flags.version&&(process.stdout.write(`${s}
53
- `),process.exit(0));let k="help"===v.command,D=v.flags.help;if(k||D){k&&v.positionals.length>1&&(ez(new es("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=k?v.positionals[0]:v.command;e||(process.stdout.write(`${eP}
54
- `),process.exit(0));let t=function(e){var t,r;let s=eA(e);if(!s)return null;let o=(t=e,(r=s).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(e$),...r.allowedFlags.flatMap(e=>(eI.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),a=eE(new Set(s.allowedFlags)),n=eE(ev),i=[];return a.length>0&&i.push(eL("Command flags:",a)),i.push(eL("Global flags:",n)),`agent-device ${o}
53
+ `),process.exit(0));let k="help"===v.command,D=v.flags.help;if(k||D){k&&v.positionals.length>1&&(eX(new es("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=k?v.positionals[0]:v.command;e||(process.stdout.write(`${eL}
54
+ `),process.exit(0));let t=function(e){var t,r;let s=e$(e);if(!s)return null;let o=(t=e,(r=s).usageOverride?r.usageOverride:[t,...r.positionalArgs.map(eE),...r.allowedFlags.flatMap(e=>(eS.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),a=eN(new Set(s.allowedFlags)),n=eN(eD),i=[];return a.length>0&&i.push(e_("Command flags:",a)),i.push(e_("Global flags:",n)),`agent-device ${o}
55
55
 
56
56
  ${s.helpDescription}
57
57
 
@@ -59,11 +59,11 @@ Usage:
59
59
  agent-device ${o}
60
60
 
61
61
  ${i.join("\n\n")}
62
- `}(eK(e));t&&(process.stdout.write(t),process.exit(0)),ez(new es("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${eP}
63
- `),process.exit(1)}v.command||(process.stdout.write(`${eP}
64
- `),process.exit(1));let{command:I,positionals:A}=v,S=rj({policyOverrides:v.flags,configuredPlatform:v.flags.platform,configuredSession:v.flags.session}),L=S.lockPolicy?{...v.flags}:rF(v.flags,{policyOverrides:v.flags,configuredPlatform:v.flags.platform,configuredSession:v.flags.session}),N=function(e){let{json:t,config:r,remoteConfig:s,help:o,version:a,sessionLock:n,sessionLocked:i,sessionLockConflicts:l,...u}=e;return u}(L),_=K(L.stateDir),T=L.session??"default";eh({command:I,currentVersion:s,stateDir:_.baseDir,flags:L});let R=L.daemonBaseUrl,O=!L.verbose||L.json||R?null:function(e){try{let t=0,r=!1,s=setInterval(()=>{if(!r&&f.existsSync(e))try{let r=f.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let s=f.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);f.readSync(s,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{f.closeSync(s)}}catch{}},200);return()=>{r=!0,clearInterval(s)}}catch{return null}}(_.logPath),C=function(e={},t={}){let r=t.transport??e4,s=async(t,s=[],o={})=>{let a={...e,...o},n=await r({session:ri(e.session,o.session),command:t,positionals:s,flags:rs({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,verbose:a.debug}),runtime:a.runtime,meta:rs({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})});if(!n.ok)throw new es(n.error.code,n.error.message,{...n.error.details??{},hint:n.error.hint,diagnosticId:n.error.diagnosticId,logPath:n.error.logPath});return n.data??{}},o=async(e={})=>{let t=await s("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(rn)};return{devices:{list:async(e={})=>{let t=await s("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ra)}},sessions:{list:async(e={})=>await o(e),close:async(t={})=>{let r=ri(e.session,t.session),o=(await s("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof o&&null!==o?o:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,o=await s("ensure-simulator",[],{...r,simulatorRuntimeId:t}),a=t1(o,"udid"),n=t1(o,"device");return{udid:a,device:n,runtime:t1(o,"runtime"),created:!0===o.created,booted:!0===o.booted,iosSimulatorDeviceSet:t3(o,"ios_simulator_device_set"),identifiers:{deviceId:a,deviceName:n,udid:a}}}},apps:{install:async t=>ro(await s("install",[t.app,t.appPath],t),ri(e.session,t.session)),reinstall:async t=>ro(await s("reinstall",[t.app,t.appPath],t),ri(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=t2(e,"bundleId"),s=t2(e,"packageName"),o=r??s??t2(e,"appId"),a=t2(e,"launchTarget")??s??r??o;if(!a)throw new es("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:t2(e,"appName"),appId:o,bundleId:r,packageName:s,launchTarget:a,installablePath:t2(e,"installablePath"),archivePath:t2(e,"archivePath"),materializationId:t2(e,"materializationId"),materializationExpiresAt:t2(e,"materializationExpiresAt"),identifiers:P({session:t,bundleId:r,packageName:s,appId:o})}})(await s("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),ri(e.session,t.session)),open:async t=>{let r=ri(e.session,t.session),o=t.url?[t.app,t.url]:[t.app],a=await s("open",o,t),n=function(e){let t=e.platform,r=t2(e,"id"),s=t2(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!s)return;let o=t8(e,"target"),a=$(t,r,s);return{platform:t,target:o,id:r,name:s,identifiers:a,ios:"ios"===t?{udid:t2(e,"device_udid")??r,simulatorSetPath:t3(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:t2(e,"serial")??r}:void 0}}(a),i=t2(a,"appBundleId");return{session:r,appName:t2(a,"appName"),appBundleId:i,appId:i,startup:function(e){if(rr(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:t2(e,"appTarget"),appBundleId:t2(e,"appBundleId")}}(a.startup),runtime:function(e){if(!rr(e))return;let t=e.platform,r=t2(e,"metroHost"),s="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:s,bundleUrl:t2(e,"bundleUrl"),launchUrl:t2(e,"launchUrl")}}(a.runtime),device:n,identifiers:{session:r,deviceId:n?.id,deviceName:n?.name,udid:n?.ios?.udid,serial:n?.android?.serial,appId:i,appBundleId:i}}},close:async(t={})=>{let r=ri(e.session,t.session),o=(await s("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof o&&null!==o?o:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await s("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:t1(t,"materializationId"),identifiers:{}}}},metro:{prepare:async t=>await tQ({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 o=ri(e.session,t.session),a=await s("snapshot",[],t),n=t2(a,"appBundleId"),i="object"==typeof a.visibility&&null!==a.visibility?a.visibility:void 0;return{nodes:Array.isArray(r=a.nodes)?r:[],truncated:!0===a.truncated,appName:t2(a,"appName"),appBundleId:n,...i?{visibility:i}:{},warnings:Array.isArray(a.warnings)?a.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:o,appId:n,appBundleId:n}}},screenshot:async(t={})=>{let r=ri(e.session,t.session),o=await s("screenshot",t.path?[t.path]:[],t);return{path:t1(o,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!rr(e))continue;let t=t2(e,"ref"),s=t4(e,"rect"),o=t4(e,"overlayRect"),a=function(e,t){let r=e[t];if(!rr(r))return;let s="number"==typeof r.x?r.x:void 0,o="number"==typeof r.y?r.y:void 0;if(void 0!==s&&void 0!==o)return{x:s,y:o}}(e,"center");t&&s&&o&&a&&r.push({ref:t,label:t2(e,"label"),rect:s,overlayRect:o,center:a})}return r}(o),identifiers:{session:r}}}}}}({session:T,requestId:r,stateDir:L.stateDir,daemonBaseUrl:L.daemonBaseUrl,daemonAuthToken:L.daemonAuthToken,daemonTransport:L.daemonTransport,daemonServerMode:L.daemonServerMode,tenant:L.tenant,sessionIsolation:L.sessionIsolation,runId:L.runId,leaseId:L.leaseId,lockPolicy:S.lockPolicy,lockPlatform:S.defaultPlatform,cwd:process.cwd(),debug:!!L.verbose},{transport:t.sendToDaemon}),U=async e=>await t.sendToDaemon({session:T,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:r,debug:!!L.verbose,cwd:process.cwd(),tenantId:L.tenant,runId:L.runId,leaseId:L.leaseId,sessionIsolation:L.sessionIsolation,lockPolicy:S.lockPolicy,lockPlatform:S.defaultPlatform}});try{if("batch"===I){if(A.length>0)throw new es("INVALID_ARGS","batch does not accept positional arguments.");let e=(function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=f.readFileSync(e.stepsFile,"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new es("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return E(t)})(L).map((e,t)=>({...e,flags:S.lockPolicy&&void 0===L.platform?{...e.flags??{}}:rF(e.flags??{},{policyOverrides:L,configuredPlatform:L.platform,configuredSession:L.session,inheritedPlatform:L.platform})})),t={...N,batchSteps:e};delete t.steps,delete t.stepsFile;let r=await U({command:"batch",positionals:A,flags:t});if(!r.ok)throw new es(r.error.code,r.error.message,{...r.error.details??{},hint:r.error.hint,diagnosticId:r.error.diagnosticId,logPath:r.error.logPath});L.json?eJ({success:!0,data:r.data??{}}):function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,s="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let a of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==s?` in ${s}ms`:""}
62
+ `}(ez(e));t&&(process.stdout.write(t),process.exit(0)),eX(new es("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${eL}
63
+ `),process.exit(1)}v.command||(process.stdout.write(`${eL}
64
+ `),process.exit(1));let{command:I,positionals:A}=v,S=rG({policyOverrides:v.flags,configuredPlatform:v.flags.platform,configuredSession:v.flags.session}),L=S.lockPolicy?{...v.flags}:rB(v.flags,{policyOverrides:v.flags,configuredPlatform:v.flags.platform,configuredSession:v.flags.session}),N=function(e){let{json:t,config:r,remoteConfig:s,help:o,version:a,sessionLock:n,sessionLocked:i,sessionLockConflicts:l,...u}=e;return u}(L),_=K(L.stateDir),T=L.session??"default";ey({command:I,currentVersion:s,stateDir:_.baseDir,flags:L});let R=L.daemonBaseUrl,O=!L.verbose||L.json||R?null:function(e){try{let t=0,r=!1,s=setInterval(()=>{if(!r&&f.existsSync(e))try{let r=f.statSync(e);if(r.size<t&&(t=0),r.size<=t)return;let s=f.openSync(e,"r");try{let e=Buffer.alloc(r.size-t);f.readSync(s,e,0,e.length,t),t=r.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{f.closeSync(s)}}catch{}},200);return()=>{r=!0,clearInterval(s)}}catch{return null}}(_.logPath),C=function(e={},t={}){let r=t.transport??e7,s=async(t,s=[],o={})=>{let a={...e,...o},n=await r({session:rd(e.session,o.session),command:t,positionals:s,flags:ri({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,verbose:a.debug}),runtime:a.runtime,meta:ri({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})});if(!n.ok)throw new es(n.error.code,n.error.message,{...n.error.details??{},hint:n.error.hint,diagnosticId:n.error.diagnosticId,logPath:n.error.logPath});return n.data??{}},o=async(e={})=>{let t=await s("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(rp)};return{devices:{list:async(e={})=>{let t=await s("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ru)}},sessions:{list:async(e={})=>await o(e),close:async(t={})=>{let r=rd(e.session,t.session),o=(await s("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof o&&null!==o?o:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,o=await s("ensure-simulator",[],{...r,simulatorRuntimeId:t}),a=t8(o,"udid"),n=t8(o,"device");return{udid:a,device:n,runtime:t8(o,"runtime"),created:!0===o.created,booted:!0===o.booted,iosSimulatorDeviceSet:t6(o,"ios_simulator_device_set"),identifiers:{deviceId:a,deviceName:n,udid:a}}}},apps:{install:async t=>rl(await s("install",[t.app,t.appPath],t),rd(e.session,t.session)),reinstall:async t=>rl(await s("reinstall",[t.app,t.appPath],t),rd(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=t4(e,"bundleId"),s=t4(e,"packageName"),o=r??s??t4(e,"appId"),a=t4(e,"launchTarget")??s??r??o;if(!a)throw new es("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:t4(e,"appName"),appId:o,bundleId:r,packageName:s,launchTarget:a,installablePath:t4(e,"installablePath"),archivePath:t4(e,"archivePath"),materializationId:t4(e,"materializationId"),materializationExpiresAt:t4(e,"materializationExpiresAt"),identifiers:P({session:t,bundleId:r,packageName:s,appId:o})}})(await s("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),rd(e.session,t.session)),open:async t=>{let r=rd(e.session,t.session),o=t.url?[t.app,t.url]:[t.app],a=await s("open",o,t),n=function(e){let t=e.platform,r=t4(e,"id"),s=t4(e,"device");if("ios"!==t&&"macos"!==t&&"android"!==t||!r||!s)return;let o=t9(e,"target"),a=$(t,r,s);return{platform:t,target:o,id:r,name:s,identifiers:a,ios:"ios"===t?{udid:t4(e,"device_udid")??r,simulatorSetPath:t6(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:t4(e,"serial")??r}:void 0}}(a),i=t4(a,"appBundleId");return{session:r,appName:t4(a,"appName"),appBundleId:i,appId:i,startup:function(e){if(rn(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:t4(e,"appTarget"),appBundleId:t4(e,"appBundleId")}}(a.startup),runtime:function(e){if(!rn(e))return;let t=e.platform,r=t4(e,"metroHost"),s="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:s,bundleUrl:t4(e,"bundleUrl"),launchUrl:t4(e,"launchUrl")}}(a.runtime),device:n,identifiers:{session:r,deviceId:n?.id,deviceName:n?.name,udid:n?.ios?.udid,serial:n?.android?.serial,appId:i,appBundleId:i}}},close:async(t={})=>{let r=rd(e.session,t.session),o=(await s("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof o&&null!==o?o:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await s("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:t8(t,"materializationId"),identifiers:{}}}},metro:{prepare:async t=>await t3({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 o=rd(e.session,t.session),a=await s("snapshot",[],t),n=t4(a,"appBundleId"),i="object"==typeof a.visibility&&null!==a.visibility?a.visibility:void 0;return{nodes:Array.isArray(r=a.nodes)?r:[],truncated:!0===a.truncated,appName:t4(a,"appName"),appBundleId:n,...i?{visibility:i}:{},warnings:Array.isArray(a.warnings)?a.warnings.filter(e=>"string"==typeof e):void 0,identifiers:{session:o,appId:n,appBundleId:n}}},screenshot:async(t={})=>{let r=rd(e.session,t.session),o=await s("screenshot",t.path?[t.path]:[],t);return{path:t8(o,"path"),overlayRefs:function(e){let t=e.overlayRefs;if(!Array.isArray(t))return;let r=[];for(let e of t){if(!rn(e))continue;let t=t4(e,"ref"),s=re(e,"rect"),o=re(e,"overlayRect"),a=function(e,t){let r=e[t];if(!rn(r))return;let s="number"==typeof r.x?r.x:void 0,o="number"==typeof r.y?r.y:void 0;if(void 0!==s&&void 0!==o)return{x:s,y:o}}(e,"center");t&&s&&o&&a&&r.push({ref:t,label:t4(e,"label"),rect:s,overlayRect:o,center:a})}return r}(o),identifiers:{session:r}}}}}}({session:T,requestId:r,stateDir:L.stateDir,daemonBaseUrl:L.daemonBaseUrl,daemonAuthToken:L.daemonAuthToken,daemonTransport:L.daemonTransport,daemonServerMode:L.daemonServerMode,tenant:L.tenant,sessionIsolation:L.sessionIsolation,runId:L.runId,leaseId:L.leaseId,lockPolicy:S.lockPolicy,lockPlatform:S.defaultPlatform,cwd:process.cwd(),debug:!!L.verbose},{transport:t.sendToDaemon}),U=async e=>await t.sendToDaemon({session:T,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:r,debug:!!L.verbose,cwd:process.cwd(),tenantId:L.tenant,runId:L.runId,leaseId:L.leaseId,sessionIsolation:L.sessionIsolation,lockPolicy:S.lockPolicy,lockPlatform:S.defaultPlatform}});try{if("batch"===I){if(A.length>0)throw new es("INVALID_ARGS","batch does not accept positional arguments.");let e=(function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=f.readFileSync(e.stepsFile,"utf8")}catch(r){let t=r instanceof Error?r.message:String(r);throw new es("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return E(t)})(L).map((e,t)=>({...e,flags:S.lockPolicy&&void 0===L.platform?{...e.flags??{}}:rB(e.flags??{},{policyOverrides:L,configuredPlatform:L.platform,configuredSession:L.session,inheritedPlatform:L.platform})})),t={...N,batchSteps:e};delete t.steps,delete t.stepsFile;let r=await U({command:"batch",positionals:A,flags:t});if(!r.ok)throw new es(r.error.code,r.error.message,{...r.error.details??{},hint:r.error.hint,diagnosticId:r.error.diagnosticId,logPath:r.error.logPath});L.json?eW({success:!0,data:r.data??{}}):function(e){let t="number"==typeof e.total?e.total:0,r="number"==typeof e.executed?e.executed:0,s="number"==typeof e.totalDurationMs?e.totalDurationMs:void 0;for(let a of(process.stdout.write(`Batch completed: ${r}/${t} steps${void 0!==s?` in ${s}ms`:""}
65
65
  `),Array.isArray(e.results)?e.results:[])){var o;if(!a||"object"!=typeof a)continue;let e="number"==typeof a.step?a.step:void 0,t="string"==typeof a.command?a.command:"step",r=!1!==a.ok,s="number"==typeof a.durationMs?a.durationMs:void 0,n=a.data&&"object"==typeof a.data?a.data:void 0,i=a.error&&"object"==typeof a.error?a.error:void 0,l=r?M(n)??t:(o=i,("string"==typeof o?.message&&o.message.length>0?o.message:null)??t),u=void 0!==e?`${e}. `:"- ",p=void 0!==s?` (${s}ms)`:"";process.stdout.write(`${u}${r?"OK":"FAILED"} ${l}${p}
66
- `)}}(r.data??{}),O&&O();return}if("runtime"===I)throw new es("INVALID_ARGS","runtime command was removed. Use open --remote-config <path> --relaunch for remote Metro launches, or metro prepare --remote-config <path> for inspection.");if(await rT({command:I,positionals:A,flags:L,client:C})){O&&O();return}"test"===I&&(({json:L.json}).json||process.stderr.write("Running replay suite...\n"));let e=await U({command:I,positionals:A,flags:N});if(e.ok){if(L.json){if("test"===I){let t=rM({suite:e.data??{},json:!0,reportJunit:L.reportJunit});O&&O(),0!==t&&process.exit(t);return}eJ({success:!0,data:e.data??{}}),O&&O();return}if("snapshot"===I){process.stdout.write(eW(e.data??{},{raw:L.snapshotRaw,flatten:L.snapshotInteractiveOnly})),O&&O();return}if("test"===I){let t=rM({suite:e.data??{},verbose:L.verbose,reportJunit:L.reportJunit});O&&O(),0!==t&&process.exit(t);return}if("diff"===I&&"snapshot"===A[0]){process.stdout.write(function(e){var t,r,s,o;let a=!0===e.baselineInitialized,n=e.summary??{},i=eX(n.additions),u=eX(n.removals),p=eX(n.unchanged),d=eY(),c=eZ(e),m=c.length>0?`${c.join("\n")}
66
+ `)}}(r.data??{}),O&&O();return}if("runtime"===I)throw new es("INVALID_ARGS","runtime command was removed. Use open --remote-config <path> --relaunch for remote Metro launches, or metro prepare --remote-config <path> for inspection.");if(await rO({command:I,positionals:A,flags:L,client:C})){O&&O();return}"test"===I&&(({json:L.json}).json||process.stderr.write("Running replay suite...\n"));let e=await U({command:I,positionals:A,flags:N});if(e.ok){if(L.json){if("test"===I){let t=rC({suite:e.data??{},json:!0,reportJunit:L.reportJunit});O&&O(),0!==t&&process.exit(t);return}eW({success:!0,data:e.data??{}}),O&&O();return}if("snapshot"===I){process.stdout.write(eY(e.data??{},{raw:L.snapshotRaw,flatten:L.snapshotInteractiveOnly})),O&&O();return}if("test"===I){let t=rC({suite:e.data??{},verbose:L.verbose,reportJunit:L.reportJunit});O&&O(),0!==t&&process.exit(t);return}if("diff"===I&&"snapshot"===A[0]){process.stdout.write(function(e){var t,r,s,o;let a=!0===e.baselineInitialized,n=e.summary??{},i=eZ(n.additions),u=eZ(n.removals),p=eZ(n.unchanged),d=eQ(),c=e0(e),m=c.length>0?`${c.join("\n")}
67
67
  `:"";if(a)return`${m}Baseline initialized (${p} lines).
68
68
  `;let f=(function(e){if(0===e.length)return e;let t=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===t.length)return e;let r=Array(e.length).fill(!1);for(let s of t){let t=Math.max(0,s-1),o=Math.min(e.length-1,s+1);for(let e=t;e<=o;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[]).map(e=>{var t,r,s,o;let a="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=a.startsWith(" ")?`+${a}`:`+ ${a}`;return d?(t=e,r="green",l(r,t)):e}if("removed"===e.kind){let e=a.startsWith(" ")?`-${a}`:`- ${a}`;return d?(s=e,l("red",s)):e}return d?(o=a,l("dim",o)):a}),h=f.length>0?`${f.join("\n")}
69
69
  `:"";if(!d)return`${m}${h}${i} additions, ${u} removals, ${p} unchanged
@@ -103,7 +103,7 @@ ${i.join("\n\n")}
103
103
  `),O&&O();return}}if("perf"===I){process.stdout.write(`${JSON.stringify(t,null,2)}
104
104
  `),O&&O();return}let r=M(t);if(r){for(let e of(process.stdout.write(`${r}
105
105
  `),function(e,t){if("scrollintoview"!==e)return[];let r="string"==typeof t.ref?t.ref:"",s="string"==typeof t.currentRef?t.currentRef:"";return s&&s!==r?[`Current ref: @${s}`]:[]}(I,t)))process.stdout.write(`${e}
106
- `);O&&O();return}}O&&O();return}throw new es(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(r){let e=Q(r),t=ee(e,{diagnosticId:eo().diagnosticId,logPath:en({force:!0})??void 0});if("close"===I&&"COMMAND_FAILED"===(w=e).code&&(w.details?.kind==="daemon_startup_failed"||w.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof w.details?.infoPath||"string"==typeof w.details?.lockPath))){L.json&&eJ({success:!0,data:{closed:"session",source:"no-daemon"}}),O&&O();return}if(L.json)eJ({success:!1,error:t});else if(ez(t,{showDetails:L.verbose}),L.verbose)try{let e=_.logPath;if(f.existsSync(e)){let t=f.readFileSync(e,"utf8").split("\n"),r=t.slice(Math.max(0,t.length-200)).join("\n");r.trim().length>0&&process.stderr.write(`
106
+ `);O&&O();return}}O&&O();return}throw new es(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(r){let e=Q(r),t=ee(e,{diagnosticId:eo().diagnosticId,logPath:en({force:!0})??void 0});if("close"===I&&"COMMAND_FAILED"===(w=e).code&&(w.details?.kind==="daemon_startup_failed"||w.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof w.details?.infoPath||"string"==typeof w.details?.lockPath))){L.json&&eW({success:!0,data:{closed:"session",source:"no-daemon"}}),O&&O();return}if(L.json)eW({success:!1,error:t});else if(eX(t,{showDetails:L.verbose}),L.verbose)try{let e=_.logPath;if(f.existsSync(e)){let t=f.readFileSync(e,"utf8").split("\n"),r=t.slice(Math.max(0,t.length-200)).join("\n");r.trim().length>0&&process.stderr.write(`
107
107
  [daemon log]
108
108
  ${r}
109
- `)}}catch{}O&&O(),process.exit(1)}})}p(process.argv[1]??"").href===import.meta.url&&rq(process.argv.slice(2)).catch(e=>{ez(ee(Q(e)),{showDetails:!0}),process.exit(1)}),rq(process.argv.slice(2));
109
+ `)}}catch{}O&&O(),process.exit(1)}})}p(process.argv[1]??"").href===import.meta.url&&rz(process.argv.slice(2)).catch(e=>{eX(ee(Q(e)),{showDetails:!0}),process.exit(1)}),rz(process.argv.slice(2));
@@ -6,6 +6,8 @@ export declare type DaemonArtifact = {
6
6
  path?: string;
7
7
  };
8
8
 
9
+ export declare const daemonCommandRequestSchema: RuntimeSchema<DaemonRequest>;
10
+
9
11
  export declare type DaemonError = {
10
12
  code: string;
11
13
  message: string;
@@ -27,8 +29,8 @@ export declare type DaemonInstallSource = {
27
29
  export declare type DaemonLockPolicy = 'reject' | 'strip';
28
30
 
29
31
  export declare type DaemonRequest = {
30
- token: string;
31
- session: string;
32
+ token?: string;
33
+ session?: string;
32
34
  command: string;
33
35
  positionals: string[];
34
36
  flags?: Record<string, unknown>;
@@ -44,7 +46,7 @@ export declare type DaemonRequestMeta = {
44
46
  runId?: string;
45
47
  leaseId?: string;
46
48
  leaseTtlMs?: number;
47
- leaseBackend?: 'ios-simulator';
49
+ leaseBackend?: LeaseBackend;
48
50
  sessionIsolation?: 'none' | 'tenant';
49
51
  uploadedArtifactId?: string;
50
52
  clientArtifactPaths?: Record<string, string>;
@@ -68,6 +70,60 @@ export declare type DaemonResponseData = Record<string, unknown> & {
68
70
  artifacts?: DaemonArtifact[];
69
71
  };
70
72
 
73
+ export declare const daemonRuntimeSchema: RuntimeSchema<SessionRuntimeHints>;
74
+
75
+ export declare type JsonRpcId = string | number | null;
76
+
77
+ export declare type JsonRpcRequestEnvelope<TParams = unknown> = {
78
+ jsonrpc?: string;
79
+ id?: JsonRpcId;
80
+ method?: string;
81
+ params?: TParams;
82
+ };
83
+
84
+ export declare const jsonRpcRequestSchema: RuntimeSchema<JsonRpcRequestEnvelope<unknown>>;
85
+
86
+ export declare type LeaseAllocatePayload = {
87
+ token?: string;
88
+ session?: string;
89
+ tenantId?: string;
90
+ tenant?: string;
91
+ runId?: string;
92
+ ttlMs?: number;
93
+ backend?: LeaseBackend;
94
+ };
95
+
96
+ export declare const leaseAllocateSchema: RuntimeSchema<LeaseAllocatePayload>;
97
+
98
+ export declare type LeaseBackend = 'ios-simulator' | 'ios-instance' | 'android-instance';
99
+
100
+ export declare type LeaseHeartbeatPayload = {
101
+ token?: string;
102
+ session?: string;
103
+ tenantId?: string;
104
+ tenant?: string;
105
+ runId?: string;
106
+ leaseId?: string;
107
+ ttlMs?: number;
108
+ };
109
+
110
+ export declare const leaseHeartbeatSchema: RuntimeSchema<LeaseHeartbeatPayload>;
111
+
112
+ export declare type LeaseReleasePayload = {
113
+ token?: string;
114
+ session?: string;
115
+ tenantId?: string;
116
+ tenant?: string;
117
+ runId?: string;
118
+ leaseId?: string;
119
+ };
120
+
121
+ export declare const leaseReleaseSchema: RuntimeSchema<LeaseReleasePayload>;
122
+
123
+ declare type RuntimeSchema<T> = {
124
+ parse(input: unknown): T;
125
+ };
126
+
71
127
  export declare type SessionRuntimeHints = {
72
128
  platform?: 'ios' | 'android';
73
129
  metroHost?: string;
@@ -0,0 +1 @@
1
+ function e(e){return{parse:t=>e(t,"$")}}function t(e,t){throw Error(`${e}: ${t}`)}function n(e,n){return(!e||"object"!=typeof e||Array.isArray(e))&&t(n,"Expected an object"),e}function a(e,n){return"string"!=typeof e&&t(n,"Expected a string"),e}function o(e,t,n){let o=e[t];return void 0===o?void 0:a(o,`${n}.${t}`)}function r(e,n,a){let o=e[n];if(void 0!==o)return"boolean"!=typeof o&&t(`${a}.${n}`,"Expected a boolean"),o}function i(e,n,a){var o;let r=e[n];return void 0===r?void 0:(o=`${a}.${n}`,Number.isInteger(r)||t(o,"Expected an integer"),r)}function s(e,t,a){let o=e[t];return void 0===o?void 0:n(o,`${a}.${t}`)}function l(e,n,a,o){let r=e[n];if(void 0!==r)return"string"==typeof r&&a.includes(r)||t(`${o}.${n}`,`Expected one of: ${a.join(", ")}`),r}function d(e,t){let o=n(e,t),r={};for(let[e,n]of Object.entries(o))r[e]=a(n,`${t}.${e}`);return r}let c=e((e,t)=>{let a=n(e,t);return{platform:l(a,"platform",["ios","android"],t),metroHost:o(a,"metroHost",t),metroPort:i(a,"metroPort",t),bundleUrl:o(a,"bundleUrl",t),launchUrl:o(a,"launchUrl",t)}}),u=e((e,u)=>{var m,$;let p=n(e,u),f=(m=p.positionals,$=`${u}.positionals`,Array.isArray(m)||t($,"Expected an array"),m),I=s(p,"meta",u);return{token:o(p,"token",u),session:o(p,"session",u),command:a(p.command,`${u}.command`),positionals:f.map((e,t)=>a(e,`${u}.positionals[${String(t)}]`)),flags:s(p,"flags",u),runtime:void 0===p.runtime?void 0:c.parse(p.runtime),meta:void 0===I?void 0:{requestId:o(I,"requestId",`${u}.meta`),debug:r(I,"debug",`${u}.meta`),cwd:o(I,"cwd",`${u}.meta`),tenantId:o(I,"tenantId",`${u}.meta`),runId:o(I,"runId",`${u}.meta`),leaseId:o(I,"leaseId",`${u}.meta`),leaseTtlMs:i(I,"leaseTtlMs",`${u}.meta`),leaseBackend:l(I,"leaseBackend",["ios-simulator","ios-instance","android-instance"],`${u}.meta`),sessionIsolation:l(I,"sessionIsolation",["none","tenant"],`${u}.meta`),uploadedArtifactId:o(I,"uploadedArtifactId",`${u}.meta`),clientArtifactPaths:void 0===I.clientArtifactPaths?void 0:d(I.clientArtifactPaths,`${u}.meta.clientArtifactPaths`),installSource:void 0===I.installSource?void 0:function(e,o){let r=n(e,o),i=a(r.kind,`${o}.kind`);if("url"===i){let e=a(r.url,`${o}.url`),t=void 0===r.headers?void 0:d(r.headers,`${o}.headers`);return t?{kind:i,url:e,headers:t}:{kind:i,url:e}}if("path"===i)return{kind:i,path:a(r.path,`${o}.path`)};t(`${o}.kind`,'Expected "url" or "path"')}(I.installSource,`${u}.meta.installSource`),retainMaterializedPaths:r(I,"retainMaterializedPaths",`${u}.meta`),materializedPathRetentionMs:i(I,"materializedPathRetentionMs",`${u}.meta`),materializationId:o(I,"materializationId",`${u}.meta`),lockPolicy:l(I,"lockPolicy",["reject","strip"],`${u}.meta`),lockPlatform:l(I,"lockPlatform",["ios","macos","android","linux","apple"],`${u}.meta`)}}}),m=e((e,t)=>{let a=n(e,t);return{token:o(a,"token",t),session:o(a,"session",t),tenantId:o(a,"tenantId",t),tenant:o(a,"tenant",t),runId:o(a,"runId",t),ttlMs:i(a,"ttlMs",t),backend:l(a,"backend",["ios-simulator","ios-instance","android-instance"],t)}}),$=e((e,t)=>{let a,r={token:o(a=n(e,t),"token",t),session:o(a,"session",t),leaseId:o(a,"leaseId",t),ttlMs:i(a,"ttlMs",t)},s=n(e,t);return{token:r.token,session:r.session,tenantId:o(s,"tenantId",t),tenant:o(s,"tenant",t),runId:o(s,"runId",t),leaseId:r.leaseId,ttlMs:r.ttlMs}}),p=e((e,a)=>{let r=n(e,a);return void 0!==r.ttlMs&&t(`${a}.ttlMs`,"Unexpected field"),{token:o(r,"token",a),session:o(r,"session",a),tenantId:o(r,"tenantId",a),tenant:o(r,"tenant",a),runId:o(r,"runId",a),leaseId:o(r,"leaseId",a)}}),f=e((e,a)=>{let r,i=n(e,a);return{jsonrpc:o(i,"jsonrpc",a),id:(null==(r=i.id)||"string"!=typeof r&&"number"!=typeof r&&t(`${a}.id`,"Expected a string, number, or null"),r),method:o(i,"method",a),params:i.params}});export{u as daemonCommandRequestSchema,c as daemonRuntimeSchema,f as jsonRpcRequestSchema,m as leaseAllocateSchema,$ as leaseHeartbeatSchema,p as leaseReleaseSchema};
@@ -350,51 +350,79 @@ declare type DaemonArtifact = {
350
350
  path?: string;
351
351
  };
352
352
 
353
+ declare type DaemonError = {
354
+ code: string;
355
+ message: string;
356
+ hint?: string;
357
+ diagnosticId?: string;
358
+ logPath?: string;
359
+ details?: Record<string, unknown>;
360
+ };
361
+
353
362
  declare type DaemonInstallSource = MaterializeInstallSource;
354
363
 
364
+ declare type DaemonInstallSource_2 = {
365
+ kind: 'url';
366
+ url: string;
367
+ headers?: Record<string, string>;
368
+ } | {
369
+ kind: 'path';
370
+ path: string;
371
+ };
372
+
355
373
  declare type DaemonLockPolicy = 'reject' | 'strip';
356
374
 
357
- declare type DaemonRequest = {
375
+ declare type DaemonRequest = Omit<DaemonRequest_2, 'token' | 'session' | 'flags' | 'meta'> & {
358
376
  token: string;
359
377
  session: string;
378
+ flags?: CommandFlags;
379
+ meta?: DaemonRequestMeta_2;
380
+ };
381
+
382
+ declare type DaemonRequest_2 = {
383
+ token?: string;
384
+ session?: string;
360
385
  command: string;
361
386
  positionals: string[];
362
- flags?: CommandFlags;
363
- runtime?: SessionRuntimeHints;
364
- meta?: {
365
- requestId?: string;
366
- debug?: boolean;
367
- cwd?: string;
368
- tenantId?: string;
369
- runId?: string;
370
- leaseId?: string;
371
- leaseTtlMs?: number;
372
- leaseBackend?: 'ios-simulator';
373
- sessionIsolation?: 'none' | 'tenant';
374
- uploadedArtifactId?: string;
375
- clientArtifactPaths?: Record<string, string>;
376
- installSource?: DaemonInstallSource;
377
- retainMaterializedPaths?: boolean;
378
- materializedPathRetentionMs?: number;
379
- materializationId?: string;
380
- lockPolicy?: DaemonLockPolicy;
381
- lockPlatform?: PlatformSelector;
382
- };
387
+ flags?: Record<string, unknown>;
388
+ runtime?: SessionRuntimeHints_2;
389
+ meta?: DaemonRequestMeta;
383
390
  };
384
391
 
385
- declare type DaemonResponse = {
392
+ declare type DaemonRequestMeta = {
393
+ requestId?: string;
394
+ debug?: boolean;
395
+ cwd?: string;
396
+ tenantId?: string;
397
+ runId?: string;
398
+ leaseId?: string;
399
+ leaseTtlMs?: number;
400
+ leaseBackend?: LeaseBackend;
401
+ sessionIsolation?: 'none' | 'tenant';
402
+ uploadedArtifactId?: string;
403
+ clientArtifactPaths?: Record<string, string>;
404
+ installSource?: DaemonInstallSource_2;
405
+ retainMaterializedPaths?: boolean;
406
+ materializedPathRetentionMs?: number;
407
+ materializationId?: string;
408
+ lockPolicy?: DaemonLockPolicy;
409
+ lockPlatform?: 'ios' | 'macos' | 'android' | 'linux' | 'apple';
410
+ };
411
+
412
+ declare type DaemonRequestMeta_2 = Omit<DaemonRequestMeta, 'installSource' | 'lockPlatform'> & {
413
+ installSource?: DaemonInstallSource;
414
+ lockPlatform?: PlatformSelector;
415
+ leaseBackend?: 'ios-simulator';
416
+ };
417
+
418
+ declare type DaemonResponse = DaemonResponse_2;
419
+
420
+ declare type DaemonResponse_2 = {
386
421
  ok: true;
387
422
  data?: DaemonResponseData;
388
423
  } | {
389
424
  ok: false;
390
- error: {
391
- code: string;
392
- message: string;
393
- hint?: string;
394
- diagnosticId?: string;
395
- logPath?: string;
396
- details?: Record<string, unknown>;
397
- };
425
+ error: DaemonError;
398
426
  };
399
427
 
400
428
  declare type DaemonResponseData = Record<string, unknown> & {
@@ -429,6 +457,8 @@ declare type EnsureSimulatorResult = {
429
457
 
430
458
  declare type ErrorCode = 'INVALID_ARGS' | 'DEVICE_NOT_FOUND' | 'TOOL_MISSING' | 'APP_NOT_INSTALLED' | 'UNSUPPORTED_PLATFORM' | 'UNSUPPORTED_OPERATION' | 'COMMAND_FAILED' | 'SESSION_NOT_FOUND' | 'UNAUTHORIZED' | 'UNKNOWN';
431
459
 
460
+ declare type LeaseBackend = 'ios-simulator' | 'ios-instance' | 'android-instance';
461
+
432
462
  declare type MaterializationReleaseOptions = AgentDeviceRequestOverrides & {
433
463
  materializationId: string;
434
464
  };
@@ -493,13 +523,7 @@ declare type MetroPrepareOptions = {
493
523
 
494
524
  declare type MetroPrepareResult = PrepareMetroRuntimeResult;
495
525
 
496
- declare type MetroRuntimeHints = {
497
- platform?: 'ios' | 'android';
498
- metroHost?: string;
499
- metroPort?: number;
500
- bundleUrl?: string;
501
- launchUrl?: string;
502
- };
526
+ declare type MetroRuntimeHints = SessionRuntimeHints_2;
503
527
 
504
528
  declare type Platform = ApplePlatform | 'android' | 'linux';
505
529
 
@@ -574,7 +598,9 @@ declare type SessionCloseResult = {
574
598
 
575
599
  declare type SessionIsolationMode = 'none' | 'tenant';
576
600
 
577
- declare type SessionRuntimeHints = {
601
+ declare type SessionRuntimeHints = SessionRuntimeHints_2;
602
+
603
+ declare type SessionRuntimeHints_2 = {
578
604
  platform?: 'ios' | 'android';
579
605
  metroHost?: string;
580
606
  metroPort?: number;
@@ -1 +1 @@
1
- import{setTimeout as e}from"node:timers/promises";import{normalizeBaseUrl as r,METRO_COMPANION_RUN_ARG as t,ENV_LAUNCH_URL as a,ENV_BEARER_TOKEN as s,ENV_SERVER_BASE_URL as n,ENV_LOCAL_BASE_URL as o}from"./320.js";async function i(e){var t,a;let s=await fetch(`${r(e.serverBaseUrl)}/api/metro/companion/register`,{method:"POST",headers:(t=e.serverBaseUrl,a=e.bearerToken,{authorization:`Bearer ${a}`,"content-type":"application/json",...t.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({local_base_url:r(e.localBaseUrl),...e.launchUrl?{launch_url:e.launchUrl}:{}})}),n=await s.json();if(!s.ok||!0!==n.ok||"string"!=typeof n.data?.ws_url)throw Error(`Failed to register Metro companion: ${JSON.stringify(n)}`);return{wsUrl:n.data.ws_url}}async function c(e){return"string"==typeof e?Buffer.from(e,"utf8"):e instanceof ArrayBuffer?Buffer.from(e):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):"u">typeof Blob&&e instanceof Blob?Buffer.from(await e.arrayBuffer()):Buffer.from(String(e),"utf8")}async function f(e){return JSON.parse((await c(e.data)).toString("utf8"))}function d(e,r){1===e.readyState&&e.send(JSON.stringify(r))}async function l(e,r){1!==e.readyState&&await new Promise((t,a)=>{let s=()=>{i(),t()},n=()=>{i(),a(Error(`${r} WebSocket failed before opening.`))},o=()=>{i(),a(Error(`${r} WebSocket closed before opening.`))},i=()=>{e.removeEventListener("open",s),e.removeEventListener("error",n),e.removeEventListener("close",o)};e.addEventListener("open",s,{once:!0}),e.addEventListener("error",n,{once:!0}),e.addEventListener("close",o,{once:!0})})}async function u(e){e.readyState>=WebSocket.CLOSING||await new Promise(r=>{let t=()=>{a(),r()},a=()=>{e.removeEventListener("close",t),e.removeEventListener("error",t)};e.addEventListener("close",t,{once:!0}),e.addEventListener("error",t,{once:!0}),e.readyState>=WebSocket.CLOSING&&t()})}function m(e,r,t){try{e.close(r,t)}catch{}}async function p(e,t,a,s){var n,o;switch(t.type){case"ping":return void d(e,{type:"pong",timestamp:t.timestamp});case"http-request":try{let s=await fetch(new URL(t.path,`${r(a.localBaseUrl)}/`),{method:t.method,headers:t.headers,...t.bodyBase64?{body:Buffer.from(t.bodyBase64,"base64")}:{}}),n=Buffer.from(await s.arrayBuffer());d(e,{type:"http-response",requestId:t.requestId,status:s.status,headers:Object.fromEntries(s.headers.entries()),...n.length>0?{bodyBase64:n.toString("base64")}:{}})}catch(r){d(e,{type:"http-error",requestId:t.requestId,message:r instanceof Error?r.message:String(r)})}return;case"ws-open":{let o,i=new WebSocket((n=a.localBaseUrl,(o=new URL(t.path,`${r(n)}/`)).protocol="https:"===o.protocol?"wss:":"ws:",o.toString()));i.binaryType="arraybuffer";let f=!1;i.addEventListener("message",r=>{(async()=>{if(!f)return;let a=await c(r.data);d(e,{type:"ws-frame",streamId:t.streamId,dataBase64:a.toString("base64"),binary:"string"!=typeof r.data})})().catch(e=>{console.error(e instanceof Error?e.message:String(e))})}),i.addEventListener("close",r=>{s.delete(t.streamId),f&&d(e,{type:"ws-close",streamId:t.streamId,code:r.code,reason:r.reason})}),i.addEventListener("error",()=>{f&&d(e,{type:"ws-close",streamId:t.streamId,code:1011,reason:"Upstream WebSocket error."})}),s.set(t.streamId,i);try{await l(i,"Upstream"),f=!0,d(e,{type:"ws-open-result",streamId:t.streamId,success:!0,headers:{}})}catch(r){s.delete(t.streamId),m(i,1011,"open failed"),d(e,{type:"ws-open-result",streamId:t.streamId,success:!1,error:r instanceof Error?r.message:String(r)})}return}case"ws-frame":{let e=s.get(t.streamId);if(!e||1!==e.readyState)return;let r=Buffer.from(t.dataBase64,"base64");e.send(t.binary?r:r.toString("utf8"));return}case"ws-close":{let e=s.get(t.streamId);if(!e)return;s.delete(t.streamId),m(e,"number"==typeof(o=t.code)&&Number.isInteger(o)&&(1e3===o||o>=3e3&&o<=4999||o>=1001&&o<=1015&&1004!==o&&1005!==o&&1006!==o)?o:1011,t.reason??"bridge requested close");return}}}async function y(r){let t=new Map;for(;;){try{let e=await i(r),a=new WebSocket(e.wsUrl);a.binaryType="arraybuffer",await l(a,"Bridge"),a.addEventListener("message",e=>{(async()=>{let s=await f(e);await p(a,s,r,t)})().catch(e=>{console.error(e instanceof Error?e.message:String(e))})}),await u(a),t.forEach(e=>m(e,1012,"bridge disconnected")),t.clear()}catch(e){console.error(e instanceof Error?e.message:String(e))}await e(1e3)}}(async function(e,r){let i=function(e,r){if(e[0]!==t)return null;let i=r[n]?.trim(),c=r[s]?.trim(),f=r[o]?.trim();if(!i||!c||!f)throw Error("Metro companion worker is missing required environment configuration.");return{serverBaseUrl:i,bearerToken:c,localBaseUrl:f,launchUrl:r[a]?.trim()||void 0}}(e,r);return!!i&&(await y(i),!0)})(process.argv.slice(2),process.env).catch(e=>{if(e instanceof Error&&e.message.includes("missing required environment")){console.error(e.message),process.exitCode=1;return}console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1});
1
+ import e from"node:fs";import{setTimeout as r}from"node:timers/promises";import{normalizeBaseUrl as t,METRO_COMPANION_RUN_ARG as a,ENV_LAUNCH_URL as s,ENV_BEARER_TOKEN as n,ENV_SERVER_BASE_URL as o,ENV_LOCAL_BASE_URL as i,ENV_STATE_PATH as c}from"./320.js";async function f(e){var r,a;let s=await fetch(`${t(e.serverBaseUrl)}/api/metro/companion/register`,{method:"POST",headers:(r=e.serverBaseUrl,a=e.bearerToken,{authorization:`Bearer ${a}`,"content-type":"application/json",...r.includes("ngrok")?{"ngrok-skip-browser-warning":"1"}:{}}),body:JSON.stringify({local_base_url:t(e.localBaseUrl),...e.launchUrl?{launch_url:e.launchUrl}:{}})}),n=await s.json();if(!s.ok||!0!==n.ok||"string"!=typeof n.data?.ws_url)throw Error(`Failed to register Metro companion: ${JSON.stringify(n)}`);return{wsUrl:n.data.ws_url}}async function d(e){return"string"==typeof e?Buffer.from(e,"utf8"):e instanceof ArrayBuffer?Buffer.from(e):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):"u">typeof Blob&&e instanceof Blob?Buffer.from(await e.arrayBuffer()):Buffer.from(String(e),"utf8")}async function l(e){return JSON.parse((await d(e.data)).toString("utf8"))}function u(e,r){1===e.readyState&&e.send(JSON.stringify(r))}async function m(e,r){1!==e.readyState&&await new Promise((t,a)=>{let s=()=>{i(),t()},n=()=>{i(),a(Error(`${r} WebSocket failed before opening.`))},o=()=>{i(),a(Error(`${r} WebSocket closed before opening.`))},i=()=>{e.removeEventListener("open",s),e.removeEventListener("error",n),e.removeEventListener("close",o)};e.addEventListener("open",s,{once:!0}),e.addEventListener("error",n,{once:!0}),e.addEventListener("close",o,{once:!0})})}async function p(e){e.readyState>=WebSocket.CLOSING||await new Promise(r=>{let t=()=>{a(),r()},a=()=>{e.removeEventListener("close",t),e.removeEventListener("error",t)};e.addEventListener("close",t,{once:!0}),e.addEventListener("error",t,{once:!0}),e.readyState>=WebSocket.CLOSING&&t()})}function y(e,r,t){try{e.close(1e3===r||r>=3e3&&r<=4999?r:3001,t)}catch{}}function g(r){return!r.statePath||e.existsSync(r.statePath)}async function w(e,r,a,s){var n,o;switch(r.type){case"ping":return void u(e,{type:"pong",timestamp:r.timestamp});case"http-request":try{let s=await fetch(new URL(r.path,`${t(a.localBaseUrl)}/`),{method:r.method,headers:r.headers,...r.bodyBase64?{body:Buffer.from(r.bodyBase64,"base64")}:{}}),n=Buffer.from(await s.arrayBuffer());u(e,{type:"http-response",requestId:r.requestId,status:s.status,headers:Object.fromEntries(s.headers.entries()),...n.length>0?{bodyBase64:n.toString("base64")}:{}})}catch(t){u(e,{type:"http-error",requestId:r.requestId,message:t instanceof Error?t.message:String(t)})}return;case"ws-open":{let o,i=new WebSocket((n=a.localBaseUrl,(o=new URL(r.path,`${t(n)}/`)).protocol="https:"===o.protocol?"wss:":"ws:",o.toString()));i.binaryType="arraybuffer";let c=!1;i.addEventListener("message",t=>{(async()=>{if(!c)return;let a=await d(t.data);u(e,{type:"ws-frame",streamId:r.streamId,dataBase64:a.toString("base64"),binary:"string"!=typeof t.data})})().catch(e=>{console.error(e instanceof Error?e.message:String(e))})}),i.addEventListener("close",t=>{s.delete(r.streamId),c&&u(e,{type:"ws-close",streamId:r.streamId,code:t.code,reason:t.reason})}),i.addEventListener("error",()=>{c&&u(e,{type:"ws-close",streamId:r.streamId,code:1011,reason:"Upstream WebSocket error."})}),s.set(r.streamId,i);try{await m(i,"Upstream"),c=!0,u(e,{type:"ws-open-result",streamId:r.streamId,success:!0,headers:{}})}catch(t){s.delete(r.streamId),y(i,1011,"open failed"),u(e,{type:"ws-open-result",streamId:r.streamId,success:!1,error:t instanceof Error?t.message:String(t)})}return}case"ws-frame":{let e=s.get(r.streamId);if(!e||1!==e.readyState)return;let t=Buffer.from(r.dataBase64,"base64");e.send(r.binary?t:t.toString("utf8"));return}case"ws-close":{let e=s.get(r.streamId);if(!e)return;s.delete(r.streamId),y(e,"number"==typeof(o=r.code)&&Number.isInteger(o)&&(1e3===o||o>=3e3&&o<=4999||o>=1001&&o<=1015&&1004!==o&&1005!==o&&1006!==o)?o:1011,r.reason??"bridge requested close");return}}}async function b(e){let t=new Map,a=setInterval(()=>{g(e)||process.exit(0)},250);for(a.unref();g(e);){try{let r=await f(e),a=new WebSocket(r.wsUrl);a.binaryType="arraybuffer",await m(a,"Bridge"),a.addEventListener("message",r=>{(async()=>{let s=await l(r);await w(a,s,e,t)})().catch(e=>{console.error(e instanceof Error?e.message:String(e))})}),await p(a),t.forEach(e=>y(e,1012,"bridge disconnected")),t.clear()}catch(r){if(!g(e))break;console.error(r instanceof Error?r.message:String(r))}if(!g(e))break;await r(1e3)}clearInterval(a)}(async function(e,r){let t=function(e,r){if(e[0]!==a)return null;let t=r[o]?.trim(),f=r[n]?.trim(),d=r[i]?.trim();if(!t||!f||!d)throw Error("Metro companion worker is missing required environment configuration.");return{serverBaseUrl:t,bearerToken:f,localBaseUrl:d,launchUrl:r[s]?.trim()||void 0,statePath:r[c]?.trim()||void 0}}(e,r);return!!t&&(await b(t),!0)})(process.argv.slice(2),process.env).catch(e=>{if(e instanceof Error&&e.message.includes("missing required environment")){console.error(e.message),process.exitCode=1;return}console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1});
@@ -1,5 +1,7 @@
1
1
  export declare function buildAndroidRuntimeHints(baseUrl: string): MetroRuntimeHints;
2
2
 
3
+ export declare function buildBundleUrl(baseUrl: string, platform: 'ios' | 'android'): string;
4
+
3
5
  export declare function buildIosRuntimeHints(baseUrl: string): MetroRuntimeHints;
4
6
 
5
7
  export declare function ensureMetroTunnel(options: EnsureMetroTunnelOptions): Promise<EnsureMetroTunnelResult>;
@@ -23,6 +25,27 @@ export declare type EnsureMetroTunnelResult = {
23
25
 
24
26
  declare type EnvSource = NodeJS.ProcessEnv | Record<string, string | undefined>;
25
27
 
28
+ export declare type MetroBridgeDescriptor = {
29
+ enabled: boolean;
30
+ base_url: string;
31
+ status_url?: string;
32
+ bundle_url?: string;
33
+ ios_runtime: MetroBridgeRuntimePayload;
34
+ android_runtime: MetroBridgeRuntimePayload;
35
+ upstream: {
36
+ bundle_url?: string;
37
+ host?: string;
38
+ port?: number;
39
+ status_url?: string;
40
+ };
41
+ probe: {
42
+ reachable: boolean;
43
+ status_code: number;
44
+ latency_ms: number;
45
+ detail: string;
46
+ };
47
+ };
48
+
26
49
  export declare type MetroBridgeResult = {
27
50
  enabled: boolean;
28
51
  baseUrl: string;
@@ -44,14 +67,85 @@ export declare type MetroBridgeResult = {
44
67
  };
45
68
  };
46
69
 
47
- export declare type MetroRuntimeHints = {
48
- platform?: 'ios' | 'android';
49
- metroHost?: string;
50
- metroPort?: number;
51
- bundleUrl?: string;
52
- launchUrl?: string;
70
+ export declare type MetroBridgeRuntimePayload = {
71
+ metro_host?: string;
72
+ metro_port?: number;
73
+ metro_bundle_url?: string;
74
+ launch_url?: string;
75
+ };
76
+
77
+ export declare type MetroRuntimeHints = SessionRuntimeHints;
78
+
79
+ export declare type MetroTunnelHttpErrorMessage = {
80
+ type: 'http-error';
81
+ requestId: string;
82
+ message: string;
53
83
  };
54
84
 
85
+ export declare type MetroTunnelHttpRequestMessage = {
86
+ type: 'http-request';
87
+ requestId: string;
88
+ method: string;
89
+ path: string;
90
+ headers?: Record<string, string>;
91
+ bodyBase64?: string;
92
+ };
93
+
94
+ export declare type MetroTunnelHttpResponseMessage = {
95
+ type: 'http-response';
96
+ requestId: string;
97
+ status: number;
98
+ headers: Record<string, string>;
99
+ bodyBase64?: string;
100
+ };
101
+
102
+ export declare type MetroTunnelMessage = MetroTunnelRequestMessage | MetroTunnelResponseMessage;
103
+
104
+ export declare type MetroTunnelPingMessage = {
105
+ type: 'ping';
106
+ timestamp: number;
107
+ };
108
+
109
+ export declare type MetroTunnelPongMessage = {
110
+ type: 'pong';
111
+ timestamp: number;
112
+ };
113
+
114
+ export declare type MetroTunnelRequestMessage = MetroTunnelPingMessage | MetroTunnelHttpRequestMessage | MetroTunnelWebSocketOpenMessage | MetroTunnelWebSocketFrameMessage | MetroTunnelWebSocketCloseMessage;
115
+
116
+ export declare type MetroTunnelResponseMessage = MetroTunnelPongMessage | MetroTunnelHttpResponseMessage | MetroTunnelHttpErrorMessage | MetroTunnelWebSocketOpenResultMessage | MetroTunnelWebSocketFrameMessage | MetroTunnelWebSocketCloseMessage;
117
+
118
+ export declare type MetroTunnelWebSocketCloseMessage = {
119
+ type: 'ws-close';
120
+ streamId: string;
121
+ code?: number;
122
+ reason?: string;
123
+ };
124
+
125
+ export declare type MetroTunnelWebSocketFrameMessage = {
126
+ type: 'ws-frame';
127
+ streamId: string;
128
+ dataBase64: string;
129
+ binary: boolean;
130
+ };
131
+
132
+ export declare type MetroTunnelWebSocketOpenMessage = {
133
+ type: 'ws-open';
134
+ streamId: string;
135
+ path: string;
136
+ headers?: Record<string, string>;
137
+ };
138
+
139
+ export declare type MetroTunnelWebSocketOpenResultMessage = {
140
+ type: 'ws-open-result';
141
+ streamId: string;
142
+ success: boolean;
143
+ headers?: Record<string, string>;
144
+ error?: string;
145
+ };
146
+
147
+ export declare function normalizeBaseUrl(input: string): string;
148
+
55
149
  export declare function prepareRemoteMetro(options: PrepareRemoteMetroOptions): Promise<PrepareRemoteMetroResult>;
56
150
 
57
151
  export declare type PrepareRemoteMetroOptions = {
@@ -84,6 +178,14 @@ export declare type PrepareRemoteMetroResult = {
84
178
  logPath: string;
85
179
  };
86
180
 
181
+ declare type SessionRuntimeHints = {
182
+ platform?: 'ios' | 'android';
183
+ metroHost?: string;
184
+ metroPort?: number;
185
+ bundleUrl?: string;
186
+ launchUrl?: string;
187
+ };
188
+
87
189
  export declare function stopMetroTunnel(options: StopMetroTunnelOptions): Promise<void>;
88
190
 
89
191
  export declare type StopMetroTunnelOptions = {
package/dist/src/metro.js CHANGED
@@ -1 +1 @@
1
- import{buildMetroRuntimeHints as e,ensureMetroCompanion as t,stopMetroCompanion as n,prepareMetroRuntime as o}from"./974.js";async function r(e){let t=await o({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 n=await t(e);return{pid:n.pid,started:n.spawned,logPath:n.logPath}}async function s(e){await n(e)}function a(t){return e(t,"ios")}function u(t){return e(t,"android")}export{u as buildAndroidRuntimeHints,a as buildIosRuntimeHints,i as ensureMetroTunnel,r as prepareRemoteMetro,s as stopMetroTunnel};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-device",
3
- "version": "0.11.11",
3
+ "version": "0.11.13",
4
4
  "description": "Unified control plane for physical and virtual devices via an agent-driven CLI.",
5
5
  "license": "MIT",
6
6
  "author": "Callstack",