agent-device 0.8.5 → 0.8.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/src/224.js +2 -2
- package/dist/src/bin.js +46 -45
- package/dist/src/client-metro.d.ts +64 -0
- package/dist/src/client-types.d.ts +21 -0
- package/dist/src/client.d.ts +1 -1
- package/dist/src/index.d.ts +2 -1
- package/dist/src/utils/command-schema.d.ts +13 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -349,6 +349,7 @@ Navigation helpers:
|
|
|
349
349
|
- `install`/`reinstall` accept package/bundle id style app names and support `~` in paths.
|
|
350
350
|
- `install-from-source` supports `--retain-paths` and `--retention-ms <ms>` when callers need retained materialized artifact paths after the install.
|
|
351
351
|
- When `AGENT_DEVICE_DAEMON_BASE_URL` targets a remote daemon, local `.apk`/`.aab`/`.ipa` files and `.app` bundles are uploaded automatically before `install`/`reinstall`.
|
|
352
|
+
- `metro prepare --public-base-url <url>` starts or reuses a local Metro server for sandbox/client flows and prints runtime JSON to stdout. `--json` wraps the same payload in the standard `{ success, data }` envelope. Pass `--proxy-base-url <url>` plus `AGENT_DEVICE_PROXY_TOKEN` (preferred) or `--bearer-token <token>` when the runtime must be bridged through `agent-device-proxy`, and `--runtime-file <path>` only when a persisted artifact is needed.
|
|
352
353
|
- Remote daemon clients can persist session-scoped runtime hints with `runtime set` before `open`; Android launches write React Native dev prefs, and iOS simulator launches write React Native bundle defaults before app start. Example: `agent-device runtime set --session my-session --platform android --metro-host 10.0.0.10 --metro-port 8081 --launch-url "myapp://dev"`.
|
|
353
354
|
- Remote daemon screenshots and recordings are materialized back to the caller path instead of returning host-local daemon paths.
|
|
354
355
|
- To force a daemon-side path instead of uploading a local file, prefix it with `remote:`, for example `remote:/srv/builds/MyApp.app`.
|
|
@@ -567,6 +568,7 @@ Environment selectors:
|
|
|
567
568
|
- `AGENT_DEVICE_DAEMON_BASE_URL=http(s)://host:port[/base-path]` connect directly to a remote HTTP daemon and skip local daemon metadata/startup.
|
|
568
569
|
- Remote daemon installs upload local artifacts through `POST /upload`; use a `remote:` path prefix when you need the daemon to read an existing server-side artifact path as-is.
|
|
569
570
|
- `AGENT_DEVICE_DAEMON_AUTH_TOKEN=<token>` auth token for remote HTTP daemon mode; sent in both the JSON-RPC request token and HTTP auth headers (`Authorization: Bearer` and `x-agent-device-token`).
|
|
571
|
+
- `AGENT_DEVICE_PROXY_TOKEN=<token>` preferred bearer token for `metro prepare --proxy-base-url <url>` so the proxy secret does not need to be passed on the command line. `AGENT_DEVICE_METRO_BEARER_TOKEN` is also supported.
|
|
570
572
|
- `AGENT_DEVICE_DAEMON_SERVER_MODE=socket|http|dual` daemon server mode. `http` and `dual` expose JSON-RPC 2.0 at `POST /rpc` (`GET /health` available for liveness).
|
|
571
573
|
- `AGENT_DEVICE_DAEMON_TRANSPORT=auto|socket|http` client preference when connecting to daemon metadata.
|
|
572
574
|
- `AGENT_DEVICE_HTTP_AUTH_HOOK=<module-path>` optional HTTP auth hook module path for JSON-RPC server mode.
|
package/dist/src/224.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequestId as e,node_path as t,isAgentDeviceDaemonProcess as a,runCmdDetached as r,readVersion as n,findProjectRoot as o,node_https as i,runCmdSync as s,withDiagnosticTimer as d,resolveDaemonTransportPreference as l,emitDiagnostic as u,spawn as c,AppError as p,node_fs as m,resolveDaemonPaths as f,node_net as h,resolveDaemonServerMode as I,stopProcessForTakeover as v,node_http as g}from"./331.js";async function w(e){let{localPath:a,baseUrl:r,token:n}=e,o=m.statSync(a).isDirectory(),s=t.basename(a),d=new URL("upload",r.endsWith("/")?r:`${r}/`),l="https:"===d.protocol?i:g,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":s,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,r)=>{let n=l.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},t=>{let a="";t.setEncoding("utf8"),t.on("data",e=>{a+=e}),t.on("end",()=>{clearTimeout(i);try{let t=JSON.parse(a);if(!t.ok||!t.uploadId)return void r(new p("COMMAND_FAILED",`Upload failed: ${a}`));e(t.uploadId)}catch{r(new p("COMMAND_FAILED",`Invalid upload response: ${a}`))}})}),i=setTimeout(()=>{n.destroy(),r(new p("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(i),r(new p("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=c("tar",["cf","-","-C",t.dirname(a),t.basename(a)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),r(new p("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),r(new p("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=m.createReadStream(a);e.pipe(n),e.on("error",e=>{n.destroy(),r(new p("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let A=function(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}(),y=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}(),D=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}(),b=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function P(t){let a=t.meta?.requestId??e(),r=!!(t.meta?.debug||t.flags?.verbose),n=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,a=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new p("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new p("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),r=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,n=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=l(n);if(a&&"socket"===o)throw new p("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:a});let i=I(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===n?"dual":void 0));return{paths:f(t),transportPreference:o,serverMode:i,remoteBaseUrl:a,remoteAuthToken:r}}(t),o=await d("daemon_startup",async()=>await T(n),{requestId:a,session:t.session}),i=await E(t,o),s={...t,positionals:i.positionals,flags:i.flags,token:o.token,meta:{...t.meta??{},requestId:a,debug:r,cwd:t.meta?.cwd,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,lockPolicy:t.meta?.lockPolicy,lockPlatform:t.meta?.lockPlatform,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{},...i.installSource?{installSource:i.installSource}:{}}};return u({level:"info",phase:"daemon_request_prepare",data:{requestId:a,command:t.command,session:t.session}}),await d("daemon_request",async()=>await B(o,s,n.transportPreference),{requestId:a,command:t.command})}async function E(e,a){let r,n=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,s={};if(J(a)){let d=function(e,a){if("screenshot"===e.command){let t=S(e,"path",".png");return a[0]?{field:"path",localPath:t,positionalIndex:0,positionalPath:M("screenshot",".png")}:{field:"path",localPath:t,positionalIndex:0,flagPath:M("screenshot",".png")}}if("record"===e.command&&"start"===(a[0]??"").toLowerCase()){let a=S(e,"outPath",".mp4",1);return{field:"outPath",localPath:a,positionalIndex:1,positionalPath:M("recording",t.extname(a)||".mp4")}}return null}(e,n);d&&(void 0!==d.positionalPath&&(n[d.positionalIndex]=d.positionalPath),void 0!==d.flagPath&&((o??={}).out=d.flagPath),s[d.field]=d.localPath);let l=await _(e,a);l&&(i=l.installSource,r=l.uploadedArtifactId??r)}if(!J(a)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:o,installSource:i,uploadedArtifactId:r,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let d=n[1];if(d.startsWith("remote:"))return n[1]=d.slice(7),{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let l=t.isAbsolute(d)?d:t.resolve(e.meta?.cwd??process.cwd(),d);return m.existsSync(l)?{positionals:n,flags:o,installSource:i,uploadedArtifactId:r=await w({localPath:l,baseUrl:a.baseUrl,token:a.token}),...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}:{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}}async function _(e,a){let r=e.meta?.installSource;if("install_source"!==e.command||!r||"path"!==r.kind)return null;let n=r.path.trim();if(!n)return{installSource:r};if(n.startsWith("remote:"))return{installSource:{...r,path:n.slice(7)}};let o=t.isAbsolute(n)?n:t.resolve(e.meta?.cwd??process.cwd(),n);if(!m.existsSync(o))return{installSource:{...r,path:o}};let i=await w({localPath:o,baseUrl:a.baseUrl,token:a.token});return{installSource:{...r,path:o},uploadedArtifactId:i}}function S(e,a,r,n=0){let o=e.positionals?.[n]??e.flags?.out,i=`${"path"===a?"screenshot":"recording"}-${Date.now()}${r}`,s=o&&o.trim().length>0?o:i;return t.isAbsolute(s)?s:t.resolve(e.meta?.cwd??process.cwd(),s)}function M(e,a){let r=a.startsWith(".")?a:`.${a}`;return t.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${r}`)}async function T(e){let r;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await F(t,"http"))return t;throw new p("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 i=U(e.paths.infoPath),s=n(),d=function(e,a=o()){try{let r=m.statSync(e),n=t.relative(a,e)||e;return`${n}:${r.size}:${Math.trunc(r.mtimeMs)}`}catch{return"unknown"}}((r=$()).useSrc?r.srcPath:r.distPath,r.root),l=!!i&&await F(i,e.transportPreference);if(i&&i.version===s&&i.codeSignature===d&&l)return i;i&&(i.version!==s||i.codeSignature!==d||!l)&&(await O(i),x(e.paths.infoPath)),function(e){let t=L(e);if(!t.hasLock||t.hasInfo)return;let r=C(e.lockPath);if(!r)return x(e.lockPath);a(r.pid,r.processStartTime)||x(e.lockPath)}(e.paths);let u=0;for(let t=1;t<=D;t+=1){await z(e);let a=await N(y,e);if(a)return a;if(await R(e.paths)){u+=1;continue}let r=L(e.paths);if(!(t<D))break;if(!r.hasInfo&&!r.hasLock){await k(150);continue}}let c=L(e.paths);throw new p("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:y,startupAttempts:D,lockRecoveryCount:u,metadataState:c,hint:function(e,t=f(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(c,e.paths)})}async function N(e,t){let a=Date.now();for(;Date.now()-a<e;){let e=U(t.paths.infoPath);if(e&&await F(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function k(e){await new Promise(t=>setTimeout(t,e))}async function R(e){let t=L(e);if(!t.hasLock||t.hasInfo)return!1;let r=C(e.lockPath);return r&&a(r.pid,r.processStartTime)&&await v(r.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:r.processStartTime}),x(e.lockPath),!0}async function O(e){await v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function U(e){let t=q(e);if(!t||"object"!=typeof t)return null;let a="string"==typeof t.token&&t.token.length>0?t.token:null;if(!a)return null;let r=Number.isInteger(t.port)&&Number(t.port)>0,n=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!r&&!n)return null;let o=t.transport,i="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,d="string"==typeof t.processStartTime?t.processStartTime:void 0,l=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:a,port:r?Number(t.port):void 0,httpPort:n?Number(t.httpPort):void 0,transport:"socket"===o||"http"===o||"dual"===o?o:void 0,pid:l?Number(t.pid):0,version:i,codeSignature:s,processStartTime:d}}function C(e){let t=q(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}function L(e){return{hasInfo:m.existsSync(e.infoPath),hasLock:m.existsSync(e.lockPath)}}function q(e){if(!m.existsSync(e))return null;try{return JSON.parse(m.readFileSync(e,"utf8"))}catch{return null}}function x(e){try{m.existsSync(e)&&m.unlinkSync(e)}catch{}}async function F(e,t){var a;return"http"===G(e,t)?await function(e){let t=e.baseUrl?Q(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let a=new URL(t),r="https:"===a.protocol?i:g,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=r.request({protocol:a.protocol,host:a.hostname,port:a.port,path:a.pathname+a.search,method:"GET",timeout:n},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((a=e.port)?new Promise(e=>{let t=h.createConnection({host:"127.0.0.1",port:a},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function z(e){let t=$(),a=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};r(process.execPath,a,{env:n})}function $(){let e=o(),a=t.join(e,"dist","src","daemon.js"),r=t.join(e,"src","daemon.ts"),n=m.existsSync(a),i=m.existsSync(r);if(!n&&!i)throw new p("COMMAND_FAILED","Daemon entry not found",{distPath:a,srcPath:r});return{root:e,distPath:a,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!n&&i}}async function B(e,t,a){return"http"===G(e,a)?await H(e,t):await j(e,t)}function G(e,t){if(e.baseUrl){if("socket"===t)throw new p("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var a=e,r=t;if(V(a,r))return r;throw new p("COMMAND_FAILED","http"===r?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>V(e,t));if(n)return n;throw new p("COMMAND_FAILED","Daemon metadata has no reachable transport")}function V(e,t){return"http"===t?!!e.httpPort:!!e.port}async function j(e,t){let a=e.port;if(!a)throw new p("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((r,n)=>{let o=h.createConnection({host:"127.0.0.1",port:a},()=>{o.write(`${JSON.stringify(t)}
|
|
2
|
-
`)}),i=setTimeout(()=>{o.destroy();let a=K(),r=W(e,f(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:A,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:a.terminated,timedOutRunnerCleanupError:a.error,daemonPidReset:e.pid,daemonPidForceKilled:r.forcedKill}}),n(new p("COMMAND_FAILED","Daemon request timed out",{timeoutMs:A,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},A),s="";o.setEncoding("utf8"),o.on("data",e=>{let a=(s+=e).indexOf("\n");if(-1===a)return;let d=s.slice(0,a).trim();if(d)try{let e=JSON.parse(d);o.end(),clearTimeout(i),r(e)}catch(e){clearTimeout(i),n(new p("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:d},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(i),u({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),n(new p("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))})})}async function H(t,a){let r=t.baseUrl?new URL(Q(t.baseUrl,"rpc")):t.httpPort?new URL(`http://127.0.0.1:${t.httpPort}/rpc`):null;if(!r)throw new p("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:a.meta?.requestId??e(),method:"agent_device.command",params:a}),o={"content-type":"application/json","content-length":Buffer.byteLength(n)};return t.baseUrl&&t.token&&(o.authorization=`Bearer ${t.token}`,o["x-agent-device-token"]=t.token),await new Promise((e,s)=>{let d=f(a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=("https:"===r.protocol?i:g).request({protocol:r.protocol,host:r.hostname,port:r.port,method:"POST",path:r.pathname+r.search,headers:o},r=>{let n="";r.setEncoding("utf8"),r.on("data",e=>{n+=e}),r.on("end",()=>{clearTimeout(c);try{let r=JSON.parse(n);if(r.error){let e=r.error.data??{};s(new p(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:a.meta?.requestId}));return}if(!r.result||"object"!=typeof r.result)return void s(new p("COMMAND_FAILED","Invalid daemon RPC response",{requestId:a.meta?.requestId}));if(t.baseUrl&&r.result.ok)return void X(t,a,r.result).then(e).catch(s);e(r.result)}catch(e){clearTimeout(c),s(new p("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:n},e instanceof Error?e:void 0))}})}),c=setTimeout(()=>{l.destroy();let e=J(t)?{terminated:0}:K(),r=J(t)?{forcedKill:!1}:W(t,d);u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:A,requestId:a.meta?.requestId,command:a.command,timedOutRunnerPidsTerminated:e.terminated,timedOutRunnerCleanupError:e.error,daemonPidReset:J(t)?void 0:t.pid,daemonPidForceKilled:J(t)?void 0:r.forcedKill,daemonBaseUrl:t.baseUrl}}),s(new p("COMMAND_FAILED","Daemon request timed out",{timeoutMs:A,requestId:a.meta?.requestId,hint:J(t)?"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."}))},A);l.on("error",e=>{clearTimeout(c),u({level:"error",phase:"daemon_request_socket_error",data:{requestId:a.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),s(new p("COMMAND_FAILED","Failed to communicate with daemon",{requestId:a.meta?.requestId,hint:J(t)?"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))}),l.write(n),l.end()})}function K(){let e=0;try{for(let t of b){let a=s("pkill",["-f",t],{allowFailure:!0});0===a.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function W(e,t){let r=!1;try{a(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),r=!0)}catch{v(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{x(t.infoPath),x(t.lockPath)}return{forcedKill:r}}function J(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function Q(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function X(e,a,r){let n=Array.isArray(r.data?.artifacts)?r.data.artifacts:[];if(0===n.length||!e.baseUrl)return r;let o=r.data?{...r.data}:{},i=[];for(let r of n){if(!r||"object"!=typeof r||"string"!=typeof r.artifactId){i.push(r);continue}let n=function(e,a){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return t.resolve(a.meta?.cwd??process.cwd(),r)}(r,a);await Y({baseUrl:e.baseUrl,token:e.token,artifactId:r.artifactId,destinationPath:n,requestId:a.meta?.requestId}),o[r.field]=n,i.push({...r,localPath:n})}return o.artifacts=i,{ok:!0,data:o}}async function Y(e){var a,r;let n,o=new URL((a=e.baseUrl,r=e.artifactId,n=a.endsWith("/")?a:`${a}/`,new URL(`upload/${encodeURIComponent(r)}`,n).toString())),s="https:"===o.protocol?i:g;await m.promises.mkdir(t.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,a)=>{let r=!1,n=e.timeoutMs??A,i=n=>{if(!r){if(r=!0,clearTimeout(l),n)return void m.promises.rm(e.destinationPath,{force:!0}).finally(()=>a(n));t()}},d=s.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 a="";t.setEncoding("utf8"),t.on("data",e=>{a+=e}),t.on("end",()=>{i(new p("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:a}))});return}let a=m.createWriteStream(e.destinationPath);a.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new p("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),a.on("finish",()=>{a.close(()=>i())}),t.pipe(a)}),l=setTimeout(()=>{d.destroy(new p("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);d.on("error",t=>{t instanceof p?i(t):i(new p("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),d.end()})}function Z(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function ee(e,t,a){return{deviceId:t,deviceName:a,..."ios"===e?{udid:t}:{serial:t}}}function et(e,t={}){let a=t.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&a?{serial:e.android?.serial??e.id}:{}}}function ea(e){return{name:e.name,...et(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function er(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function en(e){return{udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted}}function eo(e){return{session:e.session,configured:e.configured,...e.cleared?{cleared:!0}:{},...e.runtime?{runtime:e.runtime}:{}}}function ei(e){return{app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}}}function es(e){return{launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}}}function ed(e){return{session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?et(e.device):{}}}function el(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{}}}function eu(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{}}}function ec(e,t){let a=ey(e,"bundleId"),r=ey(e,"package");return{app:eA(e,"app"),appPath:eA(e,"appPath"),platform:eD(e,"platform"),appId:a??r,bundleId:a,package:r,identifiers:Z({session:t,bundleId:a,packageName:r})}}function ep(e,t){return{session:t,configured:!0===e.configured,cleared:!0===e.cleared||void 0,runtime:eh(e.runtime),identifiers:{session:t}}}function em(e){var t;let a=eg(e),r=eD(a,"platform"),n=eA(a,"id"),o=eA(a,"name");return{platform:r,target:eb(a,"target"),kind:eP(a,t="kind",eT,`Daemon response has invalid "${t}".`),id:n,name:o,booted:"boolean"==typeof a.booted?a.booted:void 0,identifiers:ee(r,n,o),ios:"ios"===r?{udid:n}:void 0,android:"android"===r?{serial:n}:void 0}}function ef(e){var t;let a=eg(e),r=eD(a,"platform"),n=eA(a,"id"),o=eA(a,"name"),i=eb(a,"target"),s=eA(a,"device"),d={session:o,...ee(r,n,s)};return{name:o,createdAt:eP(a,t="createdAt",eS,`Daemon response is missing numeric "${t}".`),device:{platform:r,target:i,id:n,name:s,identifiers:d,ios:"ios"===r?{udid:n,simulatorSetPath:eE(a,"ios_simulator_device_set",e_)}:void 0,android:"android"===r?{serial:n}:void 0},identifiers:d}}function eh(e){if(!ew(e))return;let t=e.platform,a=ey(e,"metroHost"),r="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:a,metroPort:r,bundleUrl:ey(e,"bundleUrl"),launchUrl:ey(e,"launchUrl")}}function eI(e,t){return t??e??"default"}function ev(e){let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}function eg(e){if(!ew(e))throw new p("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function ew(e){return"object"==typeof e&&null!==e}function eA(e,t){return eP(e,t,e_,`Daemon response is missing "${t}".`)}function ey(e,t){return e_(e[t])}function eD(e,t){return eP(e,t,eM,`Daemon response has invalid "${t}".`)}function eb(e,t){return eN(e[t])??"mobile"}function eP(e,t,a,r){let n=a(e[t]);if(void 0===n)throw new p("COMMAND_FAILED",r,{response:e});return n}function eE(e,t,a){let r=e[t];return null===r?null:a(r)}function e_(e){return"string"==typeof e&&e.length>0?e:void 0}function eS(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eM(e){return"ios"===e||"android"===e?e:void 0}function eT(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function eN(e){return"tv"===e?"tv":"mobile"===e?"mobile":void 0}function ek(e={},t={}){let a=t.transport??P,r=async(t,r=[],n={})=>{let o={...e,...n},i=await a({session:eI(e.session,n.session),command:t,positionals:r,flags:ev({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,verbose:o.debug}),runtime:o.runtime,meta:ev({requestId:o.requestId,cwd:o.cwd,debug:o.debug,lockPolicy:o.lockPolicy,lockPlatform:o.lockPlatform,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});if(!i.ok)throw new p(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});return i.data??{}},n=async(e={})=>{let t=await r("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(ef)};return{devices:{list:async(e={})=>{let t=await r("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(em)}},sessions:{list:async(e={})=>await n(e),close:async(t={})=>{let a=eI(e.session,t.session),n=(await r("close",[],t)).shutdown;return{session:a,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:a}}}},simulators:{ensure:async e=>{let{runtime:t,...a}=e,n=await r("ensure-simulator",[],{...a,simulatorRuntimeId:t}),o=eA(n,"udid"),i=eA(n,"device");return{udid:o,device:i,runtime:eA(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:eE(n,"ios_simulator_device_set",e_),identifiers:{deviceId:o,deviceName:i,udid:o}}}},apps:{install:async t=>ec(await r("install",[t.app,t.appPath],t),eI(e.session,t.session)),reinstall:async t=>ec(await r("reinstall",[t.app,t.appPath],t),eI(e.session,t.session)),installFromSource:async t=>(function(e,t){let a=ey(e,"bundleId"),r=ey(e,"packageName"),n=a??r??ey(e,"appId"),o=ey(e,"launchTarget")??r??a??n;if(!o)throw new p("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:ey(e,"appName"),appId:n,bundleId:a,packageName:r,launchTarget:o,installablePath:ey(e,"installablePath"),archivePath:ey(e,"archivePath"),materializationId:ey(e,"materializationId"),materializationExpiresAt:ey(e,"materializationExpiresAt"),identifiers:Z({session:t,bundleId:a,packageName:r,appId:n})}})(await r("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),eI(e.session,t.session)),open:async t=>{let a=eI(e.session,t.session),n=t.url?[t.app,t.url]:[t.app],o=await r("open",n,t),i=function(e){let t=e.platform,a=ey(e,"id"),r=ey(e,"device");if("ios"!==t&&"android"!==t||!a||!r)return;let n=eb(e,"target"),o=ee(t,a,r);return{platform:t,target:n,id:a,name:r,identifiers:o,ios:"ios"===t?{udid:ey(e,"device_udid")??a,simulatorSetPath:eE(e,"ios_simulator_device_set",e_)}:void 0,android:"android"===t?{serial:ey(e,"serial")??a}:void 0}}(o),s=ey(o,"appBundleId");return{session:a,appName:ey(o,"appName"),appBundleId:s,appId:s,startup:function(e){if(ew(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:ey(e,"appTarget"),appBundleId:ey(e,"appBundleId")}}(o.startup),runtime:eh(o.runtime),device:i,identifiers:{session:a,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:s,appBundleId:s}}},close:async(t={})=>{let a=eI(e.session,t.session),n=(await r("close",t.app?[t.app]:[],t)).shutdown;return{session:a,closedApp:t.app,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:a}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await r("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:eA(t,"materializationId"),identifiers:{}}}},runtime:{set:async t=>ep(await r("runtime",["set"],t),eI(e.session,t.session)),show:async(t={})=>ep(await r("runtime",["show"],t),eI(e.session,t.session))},capture:{snapshot:async(t={})=>{var a;let n=eI(e.session,t.session),o=await r("snapshot",[],t),i=ey(o,"appBundleId");return{nodes:Array.isArray(a=o.nodes)?a:[],truncated:!0===o.truncated,appName:ey(o,"appName"),appBundleId:i,identifiers:{session:n,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let a=eI(e.session,t.session);return{path:eA(await r("screenshot",t.path?[t.path]:[],t),"path"),identifiers:{session:a}}}}}}export{ek as createAgentDeviceClient,P as sendToDaemon,el as serializeCloseResult,ei as serializeDeployResult,er as serializeDevice,en as serializeEnsureSimulatorResult,es as serializeInstallFromSourceResult,ed as serializeOpenResult,eo as serializeRuntimeResult,ea as serializeSessionListEntry,eu as serializeSnapshotResult};
|
|
1
|
+
import{createRequestId as e,node_path as t,isAgentDeviceDaemonProcess as r,runCmdDetached as a,readVersion as n,findProjectRoot as o,node_https as i,runCmdSync as s,withDiagnosticTimer as l,resolveDaemonTransportPreference as d,resolveUserPath as u,emitDiagnostic as c,spawn as p,AppError as m,node_fs as h,resolveDaemonPaths as f,node_net as I,resolveDaemonServerMode as g,stopProcessForTakeover as w,node_http as b}from"./331.js";async function y(e){let{localPath:r,baseUrl:a,token:n}=e,o=h.statSync(r).isDirectory(),s=t.basename(r),l=new URL("upload",a.endsWith("/")?a:`${a}/`),d="https:"===l.protocol?i:b,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":s,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,a)=>{let n=d.request({protocol:l.protocol,host:l.hostname,port:l.port,method:"POST",path:l.pathname+l.search,headers:u},t=>{let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{clearTimeout(i);try{let t=JSON.parse(r);if(!t.ok||!t.uploadId)return void a(new m("COMMAND_FAILED",`Upload failed: ${r}`));e(t.uploadId)}catch{a(new m("COMMAND_FAILED",`Invalid upload response: ${r}`))}})}),i=setTimeout(()=>{n.destroy(),a(new m("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(i),a(new m("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=p("tar",["cf","-","-C",t.dirname(r),t.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),a(new m("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),a(new m("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=h.createReadStream(r);e.pipe(n),e.on("error",e=>{n.destroy(),a(new m("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let v=function(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}(),A=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}(),D=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}(),_=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function P(t){let r=t.meta?.requestId??e(),a=!!(t.meta?.debug||t.flags?.verbose),n=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,r=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new m("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new m("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),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,n=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=d(n);if(r&&"socket"===o)throw new m("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:r});let i=g(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===n?"dual":void 0));return{paths:f(t),transportPreference:o,serverMode:i,remoteBaseUrl:r,remoteAuthToken:a}}(t),o=await l("daemon_startup",async()=>await N(n),{requestId:r,session:t.session}),i=await E(t,o),s={...t,positionals:i.positionals,flags:i.flags,token:o.token,meta:{...t.meta??{},requestId:r,debug:a,cwd:t.meta?.cwd,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,lockPolicy:t.meta?.lockPolicy,lockPlatform:t.meta?.lockPlatform,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{},...i.installSource?{installSource:i.installSource}:{}}};return c({level:"info",phase:"daemon_request_prepare",data:{requestId:r,command:t.command,session:t.session}}),await l("daemon_request",async()=>await j(o,s,n.transportPreference),{requestId:r,command:t.command})}async function E(e,r){let a,n=[...e.positionals??[]],o=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,s={};if(X(r)){let l=function(e,r){if("screenshot"===e.command){let t=M(e,"path",".png");return r[0]?{field:"path",localPath:t,positionalIndex:0,positionalPath:k("screenshot",".png")}:{field:"path",localPath:t,positionalIndex:0,flagPath:k("screenshot",".png")}}if("record"===e.command&&"start"===(r[0]??"").toLowerCase()){let r=M(e,"outPath",".mp4",1);return{field:"outPath",localPath:r,positionalIndex:1,positionalPath:k("recording",t.extname(r)||".mp4")}}return null}(e,n);l&&(void 0!==l.positionalPath&&(n[l.positionalIndex]=l.positionalPath),void 0!==l.flagPath&&((o??={}).out=l.flagPath),s[l.field]=l.localPath);let d=await S(e,r);d&&(i=d.installSource,a=d.uploadedArtifactId??a)}if(!X(r)||"install"!==e.command&&"reinstall"!==e.command||n.length<2)return{positionals:n,flags:o,installSource:i,uploadedArtifactId:a,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let l=n[1];if(l.startsWith("remote:"))return n[1]=l.slice(7),{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}};let d=t.isAbsolute(l)?l:t.resolve(e.meta?.cwd??process.cwd(),l);return h.existsSync(d)?{positionals:n,flags:o,installSource:i,uploadedArtifactId:a=await y({localPath:d,baseUrl:r.baseUrl,token:r.token}),...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}:{positionals:n,flags:o,...Object.keys(s).length>0?{clientArtifactPaths:s}:{}}}async function S(e,r){let a=e.meta?.installSource;if("install_source"!==e.command||!a||"path"!==a.kind)return null;let n=a.path.trim();if(!n)return{installSource:a};if(n.startsWith("remote:"))return{installSource:{...a,path:n.slice(7)}};let o=t.isAbsolute(n)?n:t.resolve(e.meta?.cwd??process.cwd(),n);if(!h.existsSync(o))return{installSource:{...a,path:o}};let i=await y({localPath:o,baseUrl:r.baseUrl,token:r.token});return{installSource:{...a,path:o},uploadedArtifactId:i}}function M(e,r,a,n=0){let o=e.positionals?.[n]??e.flags?.out,i=`${"path"===r?"screenshot":"recording"}-${Date.now()}${a}`,s=o&&o.trim().length>0?o:i;return t.isAbsolute(s)?s:t.resolve(e.meta?.cwd??process.cwd(),s)}function k(e,r){let a=r.startsWith(".")?r:`.${r}`;return t.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function N(e){let a;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await q(t,"http"))return t;throw new m("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 i=x(e.paths.infoPath),s=n(),l=function(e,r=o()){try{let a=h.statSync(e),n=t.relative(r,e)||e;return`${n}:${a.size}:${Math.trunc(a.mtimeMs)}`}catch{return"unknown"}}((a=B()).useSrc?a.srcPath:a.distPath,a.root),d=!!i&&await q(i,e.transportPreference);if(i&&i.version===s&&i.codeSignature===l&&d)return i;i&&(i.version!==s||i.codeSignature!==l||!d)&&(await O(i),F(e.paths.infoPath)),function(e){let t=L(e);if(!t.hasLock||t.hasInfo)return;let a=C(e.lockPath);if(!a)return F(e.lockPath);r(a.pid,a.processStartTime)||F(e.lockPath)}(e.paths);let u=0;for(let t=1;t<=D;t+=1){await z(e);let r=await T(A,e);if(r)return r;if(await U(e.paths)){u+=1;continue}let a=L(e.paths);if(!(t<D))break;if(!a.hasInfo&&!a.hasLock){await R(150);continue}}let c=L(e.paths);throw new m("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:A,startupAttempts:D,lockRecoveryCount:u,metadataState:c,hint:function(e,t=f(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(c,e.paths)})}async function T(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=x(t.paths.infoPath);if(e&&await q(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function R(e){await new Promise(t=>setTimeout(t,e))}async function U(e){let t=L(e);if(!t.hasLock||t.hasInfo)return!1;let a=C(e.lockPath);return a&&r(a.pid,a.processStartTime)&&await w(a.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:a.processStartTime}),F(e.lockPath),!0}async function O(e){await w(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function x(e){let t=$(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 a=Number.isInteger(t.port)&&Number(t.port)>0,n=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;if(!a&&!n)return null;let o=t.transport,i="string"==typeof t.version?t.version:void 0,s="string"==typeof t.codeSignature?t.codeSignature:void 0,l="string"==typeof t.processStartTime?t.processStartTime:void 0,d=Number.isInteger(t.pid)&&Number(t.pid)>0;return{token:r,port:a?Number(t.port):void 0,httpPort:n?Number(t.httpPort):void 0,transport:"socket"===o||"http"===o||"dual"===o?o:void 0,pid:d?Number(t.pid):0,version:i,codeSignature:s,processStartTime:l}}function C(e){let t=$(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}function L(e){return{hasInfo:h.existsSync(e.infoPath),hasLock:h.existsSync(e.lockPath)}}function $(e){if(!h.existsSync(e))return null;try{return JSON.parse(h.readFileSync(e,"utf8"))}catch{return null}}function F(e){try{h.existsSync(e)&&h.unlinkSync(e)}catch{}}async function q(e,t){var r;return"http"===G(e,t)?await function(e){let t=e.baseUrl?Y(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),a="https:"===r.protocol?i:b,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},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=I.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function z(e){let t=B(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};a(process.execPath,r,{env:n})}function B(){let e=o(),r=t.join(e,"dist","src","daemon.js"),a=t.join(e,"src","daemon.ts"),n=h.existsSync(r),i=h.existsSync(a);if(!n&&!i)throw new m("COMMAND_FAILED","Daemon entry not found",{distPath:r,srcPath:a});return{root:e,distPath:r,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!n&&i}}async function j(e,t,r){return"http"===G(e,r)?await J(e,t):await H(e,t)}function G(e,t){if(e.baseUrl){if("socket"===t)throw new m("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t||"socket"===t){var r=e,a=t;if(V(r,a))return a;throw new m("COMMAND_FAILED","http"===a?"Daemon HTTP endpoint is unavailable":"Daemon socket endpoint is unavailable")}let n=("socket"===e.transport||"dual"===e.transport?["socket","http"]:["http","socket"]).find(t=>V(e,t));if(n)return n;throw new m("COMMAND_FAILED","Daemon metadata has no reachable transport")}function V(e,t){return"http"===t?!!e.httpPort:!!e.port}async function H(e,t){let r=e.port;if(!r)throw new m("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,n)=>{let o=I.createConnection({host:"127.0.0.1",port:r},()=>{o.write(`${JSON.stringify(t)}
|
|
2
|
+
`)}),i=setTimeout(()=>{o.destroy();let r=K(),a=W(e,f(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));c({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:v,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:r.terminated,timedOutRunnerCleanupError:r.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),n(new m("COMMAND_FAILED","Daemon request timed out",{timeoutMs:v,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},v),s="";o.setEncoding("utf8"),o.on("data",e=>{let r=(s+=e).indexOf("\n");if(-1===r)return;let l=s.slice(0,r).trim();if(l)try{let e=JSON.parse(l);o.end(),clearTimeout(i),a(e)}catch(e){clearTimeout(i),n(new m("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(i),c({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),n(new m("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))})})}async function J(t,r){let a=t.baseUrl?new URL(Y(t.baseUrl,"rpc")):t.httpPort?new URL(`http://127.0.0.1:${t.httpPort}/rpc`):null;if(!a)throw new m("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:r.meta?.requestId??e(),method:"agent_device.command",params:r}),o={"content-type":"application/json","content-length":Buffer.byteLength(n)};return t.baseUrl&&t.token&&(o.authorization=`Bearer ${t.token}`,o["x-agent-device-token"]=t.token),await new Promise((e,s)=>{let l=f(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),d=("https:"===a.protocol?i:b).request({protocol:a.protocol,host:a.hostname,port:a.port,method:"POST",path:a.pathname+a.search,headers:o},a=>{let n="";a.setEncoding("utf8"),a.on("data",e=>{n+=e}),a.on("end",()=>{clearTimeout(u);try{let a=JSON.parse(n);if(a.error){let e=a.error.data??{};s(new m(String(e.code??"COMMAND_FAILED"),String(e.message??a.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:r.meta?.requestId}));return}if(!a.result||"object"!=typeof a.result)return void s(new m("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));if(t.baseUrl&&a.result.ok)return void Q(t,r,a.result).then(e).catch(s);e(a.result)}catch(e){clearTimeout(u),s(new m("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:n},e instanceof Error?e:void 0))}})}),u=setTimeout(()=>{d.destroy();let e=X(t)?{terminated:0}:K(),a=X(t)?{forcedKill:!1}:W(t,l);c({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:v,requestId:r.meta?.requestId,command:r.command,timedOutRunnerPidsTerminated:e.terminated,timedOutRunnerCleanupError:e.error,daemonPidReset:X(t)?void 0:t.pid,daemonPidForceKilled:X(t)?void 0:a.forcedKill,daemonBaseUrl:t.baseUrl}}),s(new m("COMMAND_FAILED","Daemon request timed out",{timeoutMs:v,requestId:r.meta?.requestId,hint:X(t)?"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."}))},v);d.on("error",e=>{clearTimeout(u),c({level:"error",phase:"daemon_request_socket_error",data:{requestId:r.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),s(new m("COMMAND_FAILED","Failed to communicate with daemon",{requestId:r.meta?.requestId,hint:X(t)?"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))}),d.write(n),d.end()})}function K(){let e=0;try{for(let t of _){let r=s("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)}}}function W(e,t){let a=!1;try{r(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{w(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{F(t.infoPath),F(t.lockPath)}return{forcedKill:a}}function X(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function Y(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function Q(e,r,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let o=a.data?{...a.data}:{},i=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){i.push(a);continue}let n=function(e,r){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=e.fileName?.trim()||`${e.field}-${Date.now()}`;return t.resolve(r.meta?.cwd??process.cwd(),a)}(a,r);await Z({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:r.meta?.requestId}),o[a.field]=n,i.push({...a,localPath:n})}return o.artifacts=i,{ok:!0,data:o}}async function Z(e){var r,a;let n,o=new URL((r=e.baseUrl,a=e.artifactId,n=r.endsWith("/")?r:`${r}/`,new URL(`upload/${encodeURIComponent(a)}`,n).toString())),s="https:"===o.protocol?i:b;await h.promises.mkdir(t.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let a=!1,n=e.timeoutMs??v,i=n=>{if(!a){if(a=!0,clearTimeout(d),n)return void h.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(n));t()}},l=s.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 m("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=h.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 m("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),d=setTimeout(()=>{l.destroy(new m("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);l.on("error",t=>{t instanceof m?i(t):i(new m("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),l.end()})}function ee(e){return e.replace(/\/+$/,"")}function et(e){return"string"==typeof e&&e.trim()?ee(e.trim()):""}function er(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function ea(e,t,r){return u(e,{env:t,cwd:r})}function en(e){try{return h.accessSync(e,h.constants.F_OK),!0}catch{return!1}}function eo(e,t,r){if(null==e||""===e)return t;let a=Number.parseInt(String(e),10);return Number.isInteger(a)?Math.max(a,r):t}function ei(e,t){let r;return{platform:t,bundleUrl:((r=new URL(`${ee(e)}/index.bundle`)).searchParams.set("platform",t),r.searchParams.set("dev","true"),r.searchParams.set("minify","false"),r.toString())}}function es(e,t){return{platform:t,metroHost:er(e?.metro_host),metroPort:e?.metro_port,bundleUrl:er(e?.metro_bundle_url),launchUrl:er(e?.launch_url)}}function el(e){return`'${e.replace(/'/g,"'\"'\"'")}'`}async function ed(e){await new Promise(t=>setTimeout(t,e))}async function eu(e,t,r={}){try{let a=await fetch(e,{headers:r,signal:AbortSignal.timeout(t)});return{ok:a.ok,status:a.status,body:await a.text()}}catch(r){if(r instanceof Error&&"TimeoutError"===r.name)throw Error(`Timed out fetching ${e} after ${t}ms`);throw r}}async function ec(e,t){try{let r=await eu(e,t);return r.ok&&r.body.includes("packager-status:running")}catch{return!1}}async function ep(e){var t,r,a;let n;try{n=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 Error(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`);throw t}let o=await n.text(),i=o?JSON.parse(o):{};if(!n.ok)throw Error(`/api/metro/bridge failed (${n.status}): ${JSON.stringify(i)}`);return{enabled:(a=i.data??i).enabled,baseUrl:a.base_url,statusUrl:a.status_url,bundleUrl:a.bundle_url,iosRuntime:es(a.ios_runtime,"ios"),androidRuntime:es(a.android_runtime,"android"),upstream:{bundleUrl:a.upstream.bundle_url,host:a.upstream.host,port:a.upstream.port,statusUrl:a.upstream.status_url},probe:{reachable:a.probe.reachable,statusCode:a.probe.status_code,latencyMs:a.probe.latency_ms,detail:a.probe.detail}}}async function em(e,t,r){let a=Date.now()+t;for(;Date.now()<a;){let t=Math.min(r,Math.max(a-Date.now(),1));if(await ec(e,t))return!0;let n=Math.min(500,Math.max(a-Date.now(),0));n>0&&await ed(n)}return!1}async function eh(e={}){let r=e.env??process.env,a=process.cwd(),n=ea(e.projectRoot??a,r,a),o=function(e,r){if("auto"!==r)return r;let a=function(e){let r=t.join(e,"package.json");if(!en(r))throw new m("INVALID_ARGS",`package.json not found at ${r}`);return JSON.parse(h.readFileSync(r,"utf8"))}(e);return"string"==typeof({...a.dependencies??{},...a.devDependencies??{}}).expo?"expo":"react-native"}(n,e.kind??"auto"),i=function(e,t){if(null==e||""===e)return 8081;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new m("INVALID_ARGS",`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}(e.metroPort??8081,0),l=er(e.listenHost)??"0.0.0.0",d=er(e.statusHost)??"127.0.0.1",u=et(e.publicBaseUrl),c=eo(e.startupTimeoutMs,18e4,3e4),p=eo(e.probeTimeoutMs,1e4,1e3),f=e.reuseExisting??!0,I=e.installDependenciesIfNeeded??!0,g=e.runtimeFilePath?ea(e.runtimeFilePath,r,a):null,w=ea(e.logPath??t.join(n,".agent-device","metro.log"),r,a);if(!u)throw new m("INVALID_ARGS","metro prepare requires --public-base-url <url>.");let{proxyEnabled:b,proxyBaseUrl:y,proxyBearerToken:v}=function(e,t){if(e&&!t)throw new m("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 m("INVALID_ARGS","metro prepare requires --proxy-base-url when proxy auth is provided.");return{proxyEnabled:!!(e&&t),proxyBaseUrl:e,proxyBearerToken:t}}(et(e.proxyBaseUrl),er(e.proxyBearerToken)??""),A=I?function(e,r){if(function(e){try{return h.statSync(e).isDirectory()}catch{return!1}}(t.join(e,"node_modules")))return{installed:!1};let a=en(t.join(e,"pnpm-lock.yaml"))?{command:"pnpm",installArgs:["install"]}:en(t.join(e,"yarn.lock"))?{command:"yarn",installArgs:["install"]}:{command:"npm",installArgs:["install"]};return s(a.command,a.installArgs,{cwd:e,env:r}),{installed:!0,packageManager:a.command}}(n,r):{installed:!1},D=`http://${d}:${i}/status`,_=!1,P=!1,E=0;if(f&&await ec(D,p))P=!0;else if(_=!0,E=function(e,r,a,n,o,i){let l="expo"===r?{command:"npx",installArgs:["expo","start","--host","lan","--port",String(a)]}:{command:"npx",installArgs:["react-native","start","--host",n,"--port",String(a)]};h.mkdirSync(t.dirname(o),{recursive:!0});let d=[el(l.command),...l.installArgs.map(el)].join(" "),u=s("/bin/sh",["-c",`nohup ${d} >> ${el(o)} 2>&1 < /dev/null & echo $!`],{cwd:e,env:i}),c=Number.parseInt(u.stdout.trim(),10);if(!Number.isInteger(c)||c<=0)throw Error(`Failed to start Metro. Expected a child PID in stdout, got "${u.stdout.trim()}".`);return{pid:c}}(n,o,i,l,w,r).pid,!await em(D,c,p))throw Error(`Metro did not become ready at ${D} within ${c}ms. Check ${w}.`);let S=ei(u,"ios"),M=ei(u,"android"),k=null,N=null;if(b)try{k=await ep({baseUrl:y,bearerToken:v,runtime:{metro_bundle_url:S.bundleUrl},timeoutMs:p})}catch(e){N=e instanceof Error?e.message:String(e)}if(b&&(!k||!1===k.probe.reachable)){var T,R;let e;throw Error((T=N,R=k,e=[`Metro bridge is required for this run but could not be configured via ${y}/api/metro/bridge.`],T&&e.push(`bridgeError=${T}`),R?.probe.reachable===!1&&e.push(`bridgeProbe=${R.probe.detail||`unreachable (status ${R.probe.statusCode||0})`}`),e.join(" ")))}let U=k?.iosRuntime??S,O=k?.androidRuntime??M,x={projectRoot:n,kind:o,dependenciesInstalled:A.installed,packageManager:A.packageManager??null,started:_,reused:P,pid:E,logPath:w,statusUrl:D,runtimeFilePath:g,iosRuntime:U,androidRuntime:O,bridge:k};return g&&(h.mkdirSync(t.dirname(g),{recursive:!0}),h.writeFileSync(g,JSON.stringify(x,null,2))),x}function ef(e){let t=e.appId??e.bundleId??e.packageName;return{session:e.session,appId:t,appBundleId:e.bundleId,package:e.packageName}}function eI(e,t,r){return{deviceId:t,deviceName:r,..."ios"===e?{udid:t}:{serial:t}}}function eg(e,t={}){let r=t.includeAndroidSerial??!0;return{platform:e.platform,target:e.target,device:e.name,id:e.id,..."ios"===e.platform?{device_udid:e.ios?.udid??e.id,ios_simulator_device_set:e.ios?.simulatorSetPath??null}:{},..."android"===e.platform&&r?{serial:e.android?.serial??e.id}:{}}}function ew(e){return{name:e.name,...eg(e.device,{includeAndroidSerial:!1}),createdAt:e.createdAt}}function eb(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function ey(e){return{udid:e.udid,device:e.device,runtime:e.runtime,ios_simulator_device_set:e.iosSimulatorDeviceSet??null,created:e.created,booted:e.booted}}function ev(e){return{session:e.session,configured:e.configured,...e.cleared?{cleared:!0}:{},...e.runtime?{runtime:e.runtime}:{}}}function eA(e){return{app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}}}function eD(e){return{launchTarget:e.launchTarget,...e.appName?{appName:e.appName}:{},...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.packageName?{package:e.packageName}:{},...e.installablePath?{installablePath:e.installablePath}:{},...e.archivePath?{archivePath:e.archivePath}:{},...e.materializationId?{materializationId:e.materializationId}:{},...e.materializationExpiresAt?{materializationExpiresAt:e.materializationExpiresAt}:{}}}function e_(e){return{session:e.session,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{},...e.startup?{startup:e.startup}:{},...e.runtime?{runtime:e.runtime}:{},...e.device?eg(e.device):{}}}function eP(e){return{session:e.session,...e.shutdown?{shutdown:e.shutdown}:{}}}function eE(e){return{nodes:e.nodes,truncated:e.truncated,...e.appName?{appName:e.appName}:{},...e.appBundleId?{appBundleId:e.appBundleId}:{}}}function eS(e,t){let r=eL(e,"bundleId"),a=eL(e,"package");return{app:eC(e,"app"),appPath:eC(e,"appPath"),platform:e$(e,"platform"),appId:r??a,bundleId:r,package:a,identifiers:ef({session:t,bundleId:r,packageName:a})}}function eM(e,t){return{session:t,configured:!0===e.configured,cleared:!0===e.cleared||void 0,runtime:eT(e.runtime),identifiers:{session:t}}}function ek(e){var t;let r=eO(e),a=e$(r,"platform"),n=eC(r,"id"),o=eC(r,"name");return{platform:a,target:eF(r,"target"),kind:eq(r,t="kind",eV,`Daemon response has invalid "${t}".`),id:n,name:o,booted:"boolean"==typeof r.booted?r.booted:void 0,identifiers:eI(a,n,o),ios:"ios"===a?{udid:n}:void 0,android:"android"===a?{serial:n}:void 0}}function eN(e){var t;let r=eO(e),a=e$(r,"platform"),n=eC(r,"id"),o=eC(r,"name"),i=eF(r,"target"),s=eC(r,"device"),l={session:o,...eI(a,n,s)};return{name:o,createdAt:eq(r,t="createdAt",ej,`Daemon response is missing numeric "${t}".`),device:{platform:a,target:i,id:n,name:s,identifiers:l,ios:"ios"===a?{udid:n,simulatorSetPath:ez(r,"ios_simulator_device_set",eB)}:void 0,android:"android"===a?{serial:n}:void 0},identifiers:l}}function eT(e){if(!ex(e))return;let t=e.platform,r=eL(e,"metroHost"),a="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:a,bundleUrl:eL(e,"bundleUrl"),launchUrl:eL(e,"launchUrl")}}function eR(e,t){return t??e??"default"}function eU(e){let t={};for(let[r,a]of Object.entries(e))void 0!==a&&(t[r]=a);return t}function eO(e){if(!ex(e))throw new m("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function ex(e){return"object"==typeof e&&null!==e}function eC(e,t){return eq(e,t,eB,`Daemon response is missing "${t}".`)}function eL(e,t){return eB(e[t])}function e$(e,t){return eq(e,t,eG,`Daemon response has invalid "${t}".`)}function eF(e,t){return eH(e[t])??"mobile"}function eq(e,t,r,a){let n=r(e[t]);if(void 0===n)throw new m("COMMAND_FAILED",a,{response:e});return n}function ez(e,t,r){let a=e[t];return null===a?null:r(a)}function eB(e){return"string"==typeof e&&e.length>0?e:void 0}function ej(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function eG(e){return"ios"===e||"android"===e?e:void 0}function eV(e){return"simulator"===e||"emulator"===e||"device"===e?e:void 0}function eH(e){return"tv"===e?"tv":"mobile"===e?"mobile":void 0}function eJ(e={},t={}){let r=t.transport??P,a=async(t,a=[],n={})=>{let o={...e,...n},i=await r({session:eR(e.session,n.session),command:t,positionals:a,flags:eU({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,verbose:o.debug}),runtime:o.runtime,meta:eU({requestId:o.requestId,cwd:o.cwd,debug:o.debug,lockPolicy:o.lockPolicy,lockPlatform:o.lockPlatform,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});if(!i.ok)throw new m(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});return i.data??{}},n=async(e={})=>{let t=await a("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(eN)};return{devices:{list:async(e={})=>{let t=await a("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(ek)}},sessions:{list:async(e={})=>await n(e),close:async(t={})=>{let r=eR(e.session,t.session),n=(await a("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await a("ensure-simulator",[],{...r,simulatorRuntimeId:t}),o=eC(n,"udid"),i=eC(n,"device");return{udid:o,device:i,runtime:eC(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:ez(n,"ios_simulator_device_set",eB),identifiers:{deviceId:o,deviceName:i,udid:o}}}},apps:{install:async t=>eS(await a("install",[t.app,t.appPath],t),eR(e.session,t.session)),reinstall:async t=>eS(await a("reinstall",[t.app,t.appPath],t),eR(e.session,t.session)),installFromSource:async t=>(function(e,t){let r=eL(e,"bundleId"),a=eL(e,"packageName"),n=r??a??eL(e,"appId"),o=eL(e,"launchTarget")??a??r??n;if(!o)throw new m("COMMAND_FAILED",'Daemon response is missing "launchTarget".',{response:e});return{appName:eL(e,"appName"),appId:n,bundleId:r,packageName:a,launchTarget:o,installablePath:eL(e,"installablePath"),archivePath:eL(e,"archivePath"),materializationId:eL(e,"materializationId"),materializationExpiresAt:eL(e,"materializationExpiresAt"),identifiers:ef({session:t,bundleId:r,packageName:a,appId:n})}})(await a("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),eR(e.session,t.session)),open:async t=>{let r=eR(e.session,t.session),n=t.url?[t.app,t.url]:[t.app],o=await a("open",n,t),i=function(e){let t=e.platform,r=eL(e,"id"),a=eL(e,"device");if("ios"!==t&&"android"!==t||!r||!a)return;let n=eF(e,"target"),o=eI(t,r,a);return{platform:t,target:n,id:r,name:a,identifiers:o,ios:"ios"===t?{udid:eL(e,"device_udid")??r,simulatorSetPath:ez(e,"ios_simulator_device_set",eB)}:void 0,android:"android"===t?{serial:eL(e,"serial")??r}:void 0}}(o),s=eL(o,"appBundleId");return{session:r,appName:eL(o,"appName"),appBundleId:s,appId:s,startup:function(e){if(ex(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:eL(e,"appTarget"),appBundleId:eL(e,"appBundleId")}}(o.startup),runtime:eT(o.runtime),device:i,identifiers:{session:r,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:s,appBundleId:s}}},close:async(t={})=>{let r=eR(e.session,t.session),n=(await a("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await a("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:eC(t,"materializationId"),identifiers:{}}}},runtime:{set:async t=>eM(await a("runtime",["set"],t),eR(e.session,t.session)),show:async(t={})=>eM(await a("runtime",["show"],t),eR(e.session,t.session))},metro:{prepare:async t=>await eh({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath})},capture:{snapshot:async(t={})=>{var r;let n=eR(e.session,t.session),o=await a("snapshot",[],t),i=eL(o,"appBundleId");return{nodes:Array.isArray(r=o.nodes)?r:[],truncated:!0===o.truncated,appName:eL(o,"appName"),appBundleId:i,identifiers:{session:n,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let r=eR(e.session,t.session);return{path:eC(await a("screenshot",t.path?[t.path]:[],t),"path"),identifiers:{session:r}}}}}}export{eJ as createAgentDeviceClient,P as sendToDaemon,eP as serializeCloseResult,eA as serializeDeployResult,eb as serializeDevice,ey as serializeEnsureSimulatorResult,eD as serializeInstallFromSourceResult,e_ as serializeOpenResult,ev as serializeRuntimeResult,ew as serializeSessionListEntry,eE as serializeSnapshotResult};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,50 +1,51 @@
|
|
|
1
|
-
import{PNG as e}from"pngjs";import{formatSnapshotLine as t,SETTINGS_USAGE_OVERRIDE as s,styleText as i,parseBatchStepsJson as a,buildSnapshotDisplayLines as r}from"./274.js";import{createRequestId as o,node_path as n,normalizeError as l,resolveUserPath as d,readVersion as p,getDiagnosticsMeta as u,emitDiagnostic as c,promises as g,asAppError as f,expandUserHomePath as m,pathToFileURL as h,AppError as y,node_fs as w,node_os as v,withDiagnosticsScope as b,flushDiagnosticsToSessionFile as $,resolveDaemonPaths as k}from"./331.js";import{serializeOpenResult as A,sendToDaemon as S,serializeSessionListEntry as D,serializeDeployResult as I,serializeSnapshotResult as L,serializeCloseResult as x,serializeRuntimeResult as N,serializeEnsureSimulatorResult as O,serializeInstallFromSourceResult as F,serializeDevice as _,createAgentDeviceClient as E}from"./224.js";let P=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],R=["snapshotDepth","snapshotScope","snapshotRaw"],C=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config 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","android","apple"],usageLabel:"--platform ios|android|apple",usageDescription:"Platform to target (`apple` aliases the iOS/tvOS backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv"],usageLabel:"--target mobile|tv",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:"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:"runtime set: session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"runtime set: session-scoped Metro/debug port hint"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"runtime set: session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"runtime set: 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:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{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:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{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:"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:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{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:"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:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{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)"}],j=new Set(["json","config","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),V={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:["headless"]},open:{description:"Boot device/simulator; optionally launch app or deep link URL",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{description:"Close app or just end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{description:"Install app from binary path without uninstalling first",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{description:"Install app from a URL source through the normal daemon artifact flow",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...P]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",description:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",positionalArgs:["kind"],allowedFlags:[...P,"baseline","threshold","out"]},"ensure-simulator":{description:"Ensure an iOS simulator exists in a device set (create if missing)",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (includes default/system apps by default)",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{description:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},runtime:{usageOverride:"runtime set|show|clear",description:"Manage session-scoped runtime hints",positionalArgs:["set|show|clear"],allowedFlags:["metroHost","metroPort","bundleUrl","launchUrl"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",description:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",description:"Inspect Android keyboard visibility/type or dismiss it",positionalArgs:["action?"],allowedFlags:[]},perf:{description:"Show session performance metrics (startup timing)",positionalArgs:[],allowedFlags:[]},back:{description:"Navigate back (where supported)",positionalArgs:[],allowedFlags:[]},home:{description:"Go to home screen (where supported)",positionalArgs:[],allowedFlags:[]},"app-switcher":{description:"Open app switcher (where supported)",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",description:"Wait for duration, text, ref, or selector to appear",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...R]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...R]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...R]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...R]},longpress:{description:"Long press by coordinates (iOS and Android)",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{description:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{description:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{description:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",description:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...R]},scroll:{description:"Scroll in direction (0-1 amount)",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",description:"Scroll until text appears or a snapshot ref is brought into view",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{description:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{description:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",description:"Trigger app-defined event hook via deep link template",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] | record stop",description:"Start/stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps"]},trace:{usageOverride:"trace start [path] | trace stop [path]",description:"Start/stop trace log capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",description:"Session app log info, start/stop streaming, diagnostics, and markers",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [summary|headers|body|all]",description:"Dump recent HTTP(s) traffic parsed from the session app log",positionalArgs:["dump|log","limit?","include?"],allowedFlags:[]},find:{usageOverride:"find <locator|text> <action> [value]",description:"Find by text/label/value/role/id and run action",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{description:"Assert UI state (visible|hidden|exists|editable|selected|text)",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...R]},settings:{usageOverride:s,description:"Toggle OS settings, appearance, and app permissions (session app scope for permission actions)",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},T=new Map,M=new Map;for(let e of C){for(let t of e.names)T.set(t,e);let t=M.get(e.key);t?t.push(e):M.set(e.key,[e])}function G(e){if(e)return V[e]}function U(){return Object.keys(V)}function B(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function q(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(B),...t.allowedFlags.flatMap(e=>(M.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let J=function(){let e=`agent-device <command> [args] [--json]
|
|
1
|
+
import{PNG as e}from"pngjs";import{formatSnapshotLine as t,SETTINGS_USAGE_OVERRIDE as s,styleText as r,parseBatchStepsJson as o,buildSnapshotDisplayLines as a}from"./274.js";import{createRequestId as i,node_path as n,normalizeError as l,resolveUserPath as p,readVersion as u,getDiagnosticsMeta as d,emitDiagnostic as c,promises as m,asAppError as g,expandUserHomePath as f,pathToFileURL as h,AppError as y,node_fs as w,node_os as b,withDiagnosticsScope as v,flushDiagnosticsToSessionFile as k,resolveDaemonPaths as $}from"./331.js";import{serializeOpenResult as A,sendToDaemon as D,serializeSessionListEntry as S,serializeDeployResult as L,serializeSnapshotResult as I,serializeCloseResult as x,serializeRuntimeResult as N,serializeEnsureSimulatorResult as O,serializeInstallFromSourceResult as E,serializeDevice as _,createAgentDeviceClient as F}from"./224.js";let P=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],R=["snapshotDepth","snapshotScope","snapshotRaw"],j=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config 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","android","apple"],usageLabel:"--platform ios|android|apple",usageDescription:"Platform to target (`apple` aliases the iOS/tvOS backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv"],usageLabel:"--target mobile|tv",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:"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:"runtime set: session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"runtime set: 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 agent-device-proxy base URL for Metro bridging"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: proxy 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:"runtime set: session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"runtime set: 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:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{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:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{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:"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:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{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:"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:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{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)"}],C=new Set(["json","config","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),V={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:["headless"]},open:{description:"Boot device/simulator; optionally launch app or deep link URL",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{description:"Close app or just end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{description:"Install app from binary path without uninstalling first",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{description:"Install app from a URL source through the normal daemon artifact flow",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...P]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",description:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",positionalArgs:["kind"],allowedFlags:[...P,"baseline","threshold","out"]},"ensure-simulator":{description:"Ensure an iOS simulator exists in a device set (create if missing)",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (includes default/system apps by default)",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{description:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},runtime:{usageOverride:"runtime set|show|clear",description:"Manage session-scoped runtime hints",positionalArgs:["set|show|clear"],allowedFlags:["metroHost","metroPort","bundleUrl","launchUrl"],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",description:"Prepare a local Metro runtime and optionally bridge it through agent-device-proxy",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>",description:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",description:"Inspect Android keyboard visibility/type or dismiss it",positionalArgs:["action?"],allowedFlags:[]},perf:{description:"Show session performance metrics (startup timing)",positionalArgs:[],allowedFlags:[]},back:{description:"Navigate back (where supported)",positionalArgs:[],allowedFlags:[]},home:{description:"Go to home screen (where supported)",positionalArgs:[],allowedFlags:[]},"app-switcher":{description:"Open app switcher (where supported)",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",description:"Wait for duration, text, ref, or selector to appear",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...R]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...R]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...R]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...R]},longpress:{description:"Long press by coordinates (iOS and Android)",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{description:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{description:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{description:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",description:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...R]},scroll:{description:"Scroll in direction (0-1 amount)",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",description:"Scroll until text appears or a snapshot ref is brought into view",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{description:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{description:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",description:"Trigger app-defined event hook via deep link template",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] | record stop",description:"Start/stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps"]},trace:{usageOverride:"trace start [path] | trace stop [path]",description:"Start/stop trace log capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",description:"Session app log info, start/stop streaming, diagnostics, and markers",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [summary|headers|body|all]",description:"Dump recent HTTP(s) traffic parsed from the session app log",positionalArgs:["dump|log","limit?","include?"],allowedFlags:[]},find:{usageOverride:"find <locator|text> <action> [value]",description:"Find by text/label/value/role/id and run action",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{description:"Assert UI state (visible|hidden|exists|editable|selected|text)",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...R]},settings:{usageOverride:s,description:"Toggle OS settings, appearance, and app permissions (session app scope for permission actions)",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},T=new Map,M=new Map;for(let e of j){for(let t of e.names)T.set(t,e);let t=M.get(e.key);t?t.push(e):M.set(e.key,[e])}function G(e){if(e)return V[e]}function U(){return Object.keys(V)}function B(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function H(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(B),...t.allowedFlags.flatMap(e=>(M.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let q=function(){let e=`agent-device <command> [args] [--json]
|
|
2
2
|
|
|
3
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=U().map(e=>{let t=V[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:
|
|
5
|
-
${
|
|
4
|
+
`,t=U().map(e=>{let t=V[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:H(e,t)}}),s=Math.max(...t.map(e=>e.usage.length))+2,r=["Commands:"];for(let e of t)r.push(` ${e.usage.padEnd(s)}${e.schema.description}`);let o=W("Flags:",j.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
|
+
${r.join("\n")}
|
|
6
6
|
|
|
7
|
-
${
|
|
8
|
-
`}();function
|
|
9
|
-
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,
|
|
10
|
-
`)}function
|
|
7
|
+
${o}
|
|
8
|
+
`}();function J(e){return j.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function W(e,t){if(0===t.length)return`${e}
|
|
9
|
+
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,r=[e];for(let e of t)r.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return r.join("\n")}let z=new Set(["config","help","version","batchSteps"]),K={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},X=new Set(["1","true","yes","on"]),Z=new Set(["0","false","no","off"]),Y=function(){let e=new Map;for(let t of j){let s=e.get(t.key);s?s.push(t):e.set(t.key,[t])}let t=new Map;for(let e of C)t.set(e,new Set(["*"]));for(let e of U()){let s=G(e);if(s)for(let r of s.allowedFlags){let s=t.get(r);s&&s.has("*")||(s?s.add(e):t.set(r,new Set([e])))}}return[...e.entries()].map(([e,s])=>{var r;return{key:e,flagDefinitions:s,config:{enabled:!z.has(e),key:e},env:{names:[(r=e,`AGENT_DEVICE_${r.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`),...K[e]??[]]},supportsCommand(s){let r=t.get(e);return!!r&&(!!r.has("*")||!!s&&r.has(s))}}}).sort((e,t)=>e.key.localeCompare(t.key))}(),Q=new Map(Y.map(e=>[e.key,e]));function ee(e,t){return Q.get(e)?.supportsCommand(t)??!1}function et(e,t,s,r){let o=function(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let s=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===s.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...s,setValue:void 0,enumValues:t}}return s}(e);if(o.multiple)return(Array.isArray(t)?t:[t]).map(t=>et({...e,flagDefinitions:e.flagDefinitions.map(e=>({...e,multiple:!1}))},t,s,r));if("boolean"===o.type){var a=t,i=s,n=r;if("boolean"==typeof a)return a;if("string"==typeof a){let e=es(a);if(void 0!==e)return e}throw new y("INVALID_ARGS",`Invalid value for "${n}" in ${i}. Expected boolean.`)}if("booleanOrString"===o.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==es(t))return es(t);if("string"==typeof t&&t.trim().length>0)return t;throw new y("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected boolean or non-empty string.`)}if("string"===o.type){if("string"==typeof t&&t.trim().length>0)return t;throw new y("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected non-empty string.`)}if("enum"===o.type){if(void 0!==o.setValue){var l=o,p=t,u=s,d=r;let e=l.setValue;if(p===e)return e;if("string"==typeof p){let t=p.trim();if(""===t||"true"===t||"1"===t)return e;if("false"===t||"0"===t)return}if(!0===p)return e;if(!1!==p)throw new y("INVALID_ARGS",`Invalid value for "${d}" in ${u}. Expected boolean or ${String(e)}.`);return}if("string"!=typeof t||!o.enumValues?.includes(t))throw new y("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected one of: ${o.enumValues?.join(", ")}.`);return t}let c="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(c)||!Number.isInteger(c))throw new y("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected integer.`);if("number"==typeof o.min&&c<o.min)throw new y("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Must be >= ${o.min}.`);if("number"==typeof o.max&&c>o.max)throw new y("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Must be <= ${o.max}.`);return c}function es(e){let t=e.trim().toLowerCase();return!!X.has(t)||!Z.has(t)&&void 0}function er(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function eo(e){return e.replace(/^-+/,"")}function ea(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?er(e):[e,void 0];return void 0!==T.get(t)}function ei(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function en(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}function el(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
|
+
`)}function ep(e,t={}){let s=e instanceof y?l(e):e;process.stderr.write(`Error (${s.code}): ${s.message}
|
|
11
11
|
`),s.hint&&process.stderr.write(`Hint: ${s.hint}
|
|
12
12
|
`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}
|
|
13
13
|
`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}
|
|
14
14
|
`),t.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}
|
|
15
|
-
`)}function
|
|
16
|
-
`:"";if(0===
|
|
17
|
-
`;if(s.raw){let e=
|
|
15
|
+
`)}function eu(e,s={}){let r=e.nodes,o=Array.isArray(r)?r:[],i=!!e.truncated,n="string"==typeof e.appName?e.appName:void 0,l="string"==typeof e.appBundleId?e.appBundleId:void 0,p=[];n&&p.push(`Page: ${n}`),l&&p.push(`App: ${l}`);let u=`Snapshot: ${o.length} nodes${i?" (truncated)":""}`,d=p.length>0?`${p.join("\n")}
|
|
16
|
+
`:"";if(0===o.length)return`${d}${u}
|
|
17
|
+
`;if(s.raw){let e=o.map(e=>JSON.stringify(e));return`${d}${u}
|
|
18
18
|
${e.join("\n")}
|
|
19
|
-
`}if(s.flatten){let e=
|
|
19
|
+
`}if(s.flatten){let e=o.map(e=>t(e,0,!1));return`${d}${u}
|
|
20
20
|
${e.join("\n")}
|
|
21
|
-
`}let c=
|
|
21
|
+
`}let c=a(o).map(e=>e.text);return`${d}${u}
|
|
22
22
|
${c.join("\n")}
|
|
23
|
-
`}function
|
|
24
|
-
`),!0},devices:async({flags:e,client:t})=>{let s=await t.devices.list(eA(e)),
|
|
25
|
-
`),!0},"ensure-simulator":async({flags:e,client:t})=>{if(!e.device)throw new y("INVALID_ARGS","ensure-simulator requires --device <name>");let s=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet}),
|
|
23
|
+
`}function ed(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function ec(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}let em=255*Math.sqrt(3);async function eg(t,s,r={}){await ef(t,"Baseline image not found"),await ef(s,"Current screenshot not found");let o=r.outputPath,[a,i]=await Promise.all([m.readFile(t),m.readFile(s)]),l=eh(a,"baseline"),p=eh(i,"current"),u=r.threshold??.1;if(l.width!==p.width||l.height!==p.height){let e=l.width*l.height;return await ey(r.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:l.width,height:l.height},actual:{width:p.width,height:p.height}}}}let d=l.width*l.height,c=u*em,g=new e({width:l.width,height:l.height}),f=0;for(let e=0;e<l.data.length;e+=4){if(Math.sqrt((l.data[e]-p.data[e])**2+(l.data[e+1]-p.data[e+1])**2+(l.data[e+2]-p.data[e+2])**2)>c){f+=1,g.data[e]=255,g.data[e+1]=0,g.data[e+2]=0,g.data[e+3]=255;continue}let t=Math.round(.3*Math.round((l.data[e]+l.data[e+1]+l.data[e+2])/3));g.data[e]=t,g.data[e+1]=t,g.data[e+2]=t,g.data[e+3]=255}f>0&&o?(await m.mkdir(n.dirname(o),{recursive:!0}),await m.writeFile(o,e.sync.write(g))):await ey(r.outputPath);let h=d>0?Math.round(f/d*1e4)/100:0;return{...f>0&&o?{diffPath:o}:{},totalPixels:d,differentPixels:f,mismatchPercentage:h,match:0===f}}async function ef(e,t){try{await m.access(e)}catch{throw new y("INVALID_ARGS",`${t}: ${e}`)}}function eh(t,s){try{return e.sync.read(t)}catch(e){throw new y("COMMAND_FAILED",`Failed to decode ${s} screenshot as PNG`,{label:s,reason:e instanceof Error?e.message:String(e)})}}async function ey(e){if(e)try{await m.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}async function ew(e){let t=eb[e.command];return!!t&&await t(e)}let eb={session:async({positionals:e,flags:t,client:s})=>{if("list"!==(e[0]??"list"))throw new y("INVALID_ARGS","session only supports list");let r={sessions:(await s.sessions.list()).map(S)};return t.json?el({success:!0,data:r}):process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
24
|
+
`),!0},devices:async({flags:e,client:t})=>{let s=await t.devices.list(eA(e)),r={devices:s.map(_)};return e.json?el({success:!0,data:r}):process.stdout.write(`${s.map(eD).join("\n")}
|
|
25
|
+
`),!0},"ensure-simulator":async({flags:e,client:t})=>{if(!e.device)throw new y("INVALID_ARGS","ensure-simulator requires --device <name>");let s=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet}),r=O(s);if(e.json)el({success:!0,data:r});else{let e=s.created?"Created":"Reused",t=s.booted?" (booted)":"";process.stdout.write(`${e}: ${s.device} ${s.udid}${t}
|
|
26
26
|
`),s.runtime&&process.stdout.write(`Runtime: ${s.runtime}
|
|
27
|
-
`)}return!0},runtime:async({positionals:e,flags:t,client:s})=>{let
|
|
28
|
-
`),!0},
|
|
29
|
-
`
|
|
30
|
-
`
|
|
31
|
-
`);O.
|
|
32
|
-
`)
|
|
33
|
-
`),process.exit(0));let
|
|
27
|
+
`)}return!0},runtime:async({positionals:e,flags:t,client:s})=>{let r=(e[0]??"show").toLowerCase();return"set"===r?(e$(await s.runtime.set({platform:t.platform,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl}),t),!0):"show"===r&&(e$(await s.runtime.show(),t),!0)},metro:async({positionals:e,flags:t,client:s})=>{var r;if("prepare"!==(e[0]??"").toLowerCase())throw new y("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new y("INVALID_ARGS","metro prepare requires --public-base-url <url>.");return r=await s.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}),t.json?el({success:!0,data:r}):process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
28
|
+
`),!0},install:async({positionals:e,flags:t,client:s})=>{let r=await ev("install",e,t,s);return t.json&&el({success:!0,data:L(r)}),!0},reinstall:async({positionals:e,flags:t,client:s})=>{let r=await ev("reinstall",e,t,s);return t.json&&el({success:!0,data:L(r)}),!0},"install-from-source":async({positionals:e,flags:t,client:s})=>{let r=await ek(e,t,s);return t.json&&el({success:!0,data:E(r)}),!0},open:async({positionals:e,flags:t,client:s})=>{if(!e[0])return!1;let r=await s.apps.open({app:e[0],url:e[1],activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,...eA(t)});return t.json&&el({success:!0,data:A(r)}),!0},close:async({positionals:e,flags:t,client:s})=>{let r=e[0]?await s.apps.close({app:e[0],shutdown:t.shutdown}):await s.sessions.close({shutdown:t.shutdown});return t.json&&el({success:!0,data:x(r)}),!0},snapshot:async({flags:e,client:t})=>{let s=I(await t.capture.snapshot({...eA(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return e.json?el({success:!0,data:s}):process.stdout.write(eu(s,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},screenshot:async({positionals:e,flags:t,client:s})=>{let r=await s.capture.screenshot({path:e[0]??t.out}),o={path:r.path};return t.json?el({success:!0,data:o}):process.stdout.write(`${r.path}
|
|
29
|
+
`),!0},diff:async({positionals:e,flags:t,client:s})=>{let o;if("screenshot"!==e[0])return!1;let a=t.baseline;if(!a||"string"!=typeof a)throw new y("INVALID_ARGS","diff screenshot requires --baseline <path>");let i=p(a),l="string"==typeof t.out?p(t.out):void 0,u=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(u=Number(t.threshold))||u<0||u>1))throw new y("INVALID_ARGS","--threshold must be a number between 0 and 1");let d=w.mkdtempSync(n.join(b.tmpdir(),"agent-device-diff-current-")),c=n.join(d,`current-${Date.now()}.png`),m=(await s.capture.screenshot({path:c})).path;try{o=await eg(i,m,{threshold:u,outputPath:l})}finally{try{w.unlinkSync(m)}catch{}try{w.rmSync(d,{recursive:!0,force:!0})}catch{}}return t.json?el({success:!0,data:o}):process.stdout.write(function(e){var t,s;let o=ec(),a=!0===e.match,i=ed(e.differentPixels),l=ed(e.totalPixels),p=ed(e.mismatchPercentage),u=e.diffPath,d=e.dimensionMismatch,c=[];if(a){let e=o?r("green","✓"):"✓";c.push(`${e} Screenshots match.`)}else if(d){let e=o?r("red","✗"):"✗",t=d.expected,s=d.actual;c.push(`${e} Screenshots have different dimensions: expected ${t?.width}x${t?.height}, got ${s?.width}x${s?.height}`)}else{let e=o?r("red","✗"):"✗",t=0===p&&i>0?"<0.01":String(p);c.push(`${e} ${t}% pixels differ`)}if(u&&!a){let e,s,a=(t=u,e=process.cwd(),""!==(s=n.relative(e,t))&&(s.startsWith("..")||n.isAbsolute(s))?t:""===s?".":`.${n.sep}${s}`),i=o?r("dim","Diff image:"):"Diff image:",l=o?r("green",a):a;c.push(` ${i} ${l}`)}if(!a&&!d){let e=o?(s=String(i),r("red",s)):String(i);c.push(` ${e} different / ${l} total pixels`)}return`${c.join("\n")}
|
|
30
|
+
`}(o)),!0}};async function ev(e,t,s,r){let o=t[0],a=t[1];if(!o||!a)throw new y("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let i={app:o,appPath:a,...eA(s)};return"install"===e?await r.apps.install(i):await r.apps.reinstall(i)}async function ek(e,t,s){let r=e[0]?.trim();if(!r)throw new y("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new y("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await s.apps.installFromSource({...eA(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:r,headers:function(e){if(!e||0===e.length)return;let t={};for(let s of e){let e=s.indexOf(":");if(e<=0)throw new y("INVALID_ARGS",`Invalid --header value "${s}". Expected "name:value".`);let r=s.slice(0,e).trim(),o=s.slice(e+1).trim();if(!r)throw new y("INVALID_ARGS",`Invalid --header value "${s}". Header name cannot be empty.`);t[r]=o}return t}(t.header)}})}function e$(e,t){let s=N(e);t.json?el({success:!0,data:s}):e.configured?process.stdout.write(`${JSON.stringify(e.runtime??{},null,2)}
|
|
31
|
+
`):process.stdout.write("No runtime hints configured\n")}function eA(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function eD(e){let t=e.kind?` ${e.kind}`:"",s=e.target?` target=${e.target}`:"",r="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${s})${r}`}function eS(e,t={}){let s=eL(t),r={...e};return s.defaultPlatform&&void 0===r.platform&&(r.platform=s.defaultPlatform),r}function eL(e){var t,s,r,o;let a,i=e.env??process.env,n=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 y("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(i.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??i.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:n,lockPolicy:(s=e.policyOverrides,r=i,o=l,(a=s?.sessionLock??s?.sessionLockConflicts??eI(r.AGENT_DEVICE_SESSION_LOCK)??eI(r.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(s?.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}}(r.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function eI(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new y("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}function ex(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}let eN={sendToDaemon:D};async function eO(e,t=eN){let s=i(),a=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),m=e.includes("--json"),h=function(e){for(let t=0;t<e.length;t+=1){let s=e[t];if(s.startsWith("--session=")){let e=s.slice(10).trim();return e.length>0?e:null}if("--session"===s){let s=e[t+1]?.trim();if(s&&!s.startsWith("-"))return s;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await v({session:h,requestId:s,command:e[0],debug:a},async()=>{var i,h,b,v,A,D,S,L,I,x,N;let O;try{let t,s,r,o,a,l,u;i={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},s=null,r=[],o=[],a=!0;for(let i=0;i<e.length;i+=1){let n=e[i];if(a&&"--"===n){a=!1;continue}if(!a){s?r.push(n):s=ei(n);continue}let l=n.startsWith("--"),p=n.startsWith("-")&&n.length>1;if(!l&&!p){s?r.push(n):s=ei(n);continue}let[u,d]=l?er(n):[n,void 0],c=T.get(u);if(!c){if(function(e,t,s){var r;if(r=s,!/^-\d+(\.\d+)?$/.test(r)||!e)return!1;let o=G(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(s,r,n)){s?r.push(n):s=n;continue}throw new y("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,s,r){if(void 0!==e.setValue){if(void 0!==s)throw new y("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==s)throw new y("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==s){if(0===s.trim().length)throw new y("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===r||ea(r)||!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("\\"))}(r)?{value:!0,consumeNext:!1}:{value:r,consumeNext:!0}}let o=s??r;if(void 0===o||void 0===s&&ea(o))throw new y("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new y("INVALID_ARGS",`Invalid ${eo(t)}: ${o}`);return{value:o,consumeNext:void 0===s}}let a=Number(o);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new y("INVALID_ARGS",`Invalid ${eo(t)}: ${o}`);return{value:Math.floor(a),consumeNext:void 0===s}}(c,u,d,e[i+1]);m.consumeNext&&(i+=1);let g=t[c.key];if(c.multiple){let e=Array.isArray(g)?[...g,m.value]:void 0===g?[m.value]:[g,m.value];t[c.key]=e}else t[c.key]=m.value;o.push({key:c.key,token:u})}return{command:s,positionals:r,flags:t,warnings:[],providedFlags:o}}(e),s=i?.env??process.env,r=i?.cwd??process.cwd(),o=(h={command:t.command,cwd:r,cliFlags:t.flags,env:s}).env??process.env,a=ex({},function(e){let t={};for(let s of e)ex(t,function(e,t){let s,r;if(!w.existsSync(e)){if(t)throw new y("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{s=w.readFileSync(e,"utf8")}catch(t){throw new y("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{r=JSON.parse(s)}catch(t){throw new y("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new y("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let s={};for(let[r,o]of Object.entries(e)){let e=Q.get(r);if(!e)throw new y("INVALID_ARGS",`Unknown config key "${r}" in ${t}.`);if(!e.config.enabled)throw new y("INVALID_ARGS",`Unsupported config key "${r}" in ${t}.`);s[r]=et(e,o,t,r)}return s}(r,`config file ${e}`)}(s.path,s.required));return t}((b=h.cwd,v=h.cliFlags.config,A=o,(u=v??A.AGENT_DEVICE_CONFIG)?[{path:(D=u,S=b,L=A,p(D,{cwd:S,env:L})),required:!0}]:[{path:(I=A,n.join(f("~",{env:I}),".agent-device","config.json")),required:!1},{path:n.resolve(b,"agent-device.json"),required:!1}]))),l=ex(a,function(e,t){let s={};for(let r of Y.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=r.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(s[r.key]=et(r,t.value,`environment variable ${t.name}`,t.name))}return s}(o,h.command)),O=function(e,t){let s=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),r=[...e.warnings],o=en({json:!1,help:!1,version:!1},t?.defaultFlags??{});en(o,e.flags);let a=G(e.command),i=e.providedFlags.filter(t=>!ee(t.key,e.command));if(i.length>0){var n,l;let t=i.map(e=>e.token),a=(n=e.command,l=t,n?1===l.length?`Flag ${l[0]} is not supported for command ${n}.`:`Flags ${l.join(", ")} are not supported for command ${n}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(s)throw new y("INVALID_ARGS",a);for(let e of(r.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),i))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(ee(t,e.command)||delete o[t]);if(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 y("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:e.command,positionals:e.positionals,flags:o,warnings:r}}(t,{strictFlags:i?.strictFlags,defaultFlags:l})}catch(t){c({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=l(t,{diagnosticId:d().diagnosticId,logPath:k({force:!0})??void 0});m?el({success:!1,error:e}):ep(e,{showDetails:a}),process.exit(1);return}for(let e of O.warnings)process.stderr.write(`Warning: ${e}
|
|
32
|
+
`);O.flags.version&&(process.stdout.write(`${u()}
|
|
33
|
+
`),process.exit(0));let E="help"===O.command,_=O.flags.help;if(E||_){E&&O.positionals.length>1&&(ep(new y("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=E?O.positionals[0]:O.command;e||(process.stdout.write(`${q}
|
|
34
|
+
`),process.exit(0));let t=function(e){let t=G(e);if(!t)return null;let s=H(e,t),r=J(new Set(t.allowedFlags)),o=J(C),a=[];return r.length>0&&a.push(W("Command flags:",r)),a.push(W("Global flags:",o)),`agent-device ${s}
|
|
34
35
|
|
|
35
36
|
${t.description}
|
|
36
37
|
|
|
37
38
|
Usage:
|
|
38
39
|
agent-device ${s}
|
|
39
40
|
|
|
40
|
-
${
|
|
41
|
-
`}(
|
|
42
|
-
`),process.exit(1)}O.command||(process.stdout.write(`${
|
|
43
|
-
`),process.exit(1));let{command:P,positionals:R}=O,
|
|
44
|
-
`)),K&&K();return}if(await ew({command:P,positionals:R,flags:V,client:
|
|
45
|
-
`;let c=(function(e,t){if(0===e.length)return e;let s=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===s.length)return e;let
|
|
46
|
-
`:"";if(!
|
|
47
|
-
`;let
|
|
41
|
+
${a.join("\n\n")}
|
|
42
|
+
`}(ei(e));t&&(process.stdout.write(t),process.exit(0)),ep(new y("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${q}
|
|
43
|
+
`),process.exit(1)}O.command||(process.stdout.write(`${q}
|
|
44
|
+
`),process.exit(1));let{command:P,positionals:R}=O,j=eL({policyOverrides:O.flags,configuredPlatform:O.flags.platform,configuredSession:O.flags.session}),V=j.lockPolicy?{...O.flags}:eS(O.flags,{policyOverrides:O.flags,configuredPlatform:O.flags.platform,configuredSession:O.flags.session}),M=function(e){let{json:t,config:s,help:r,version:o,sessionLock:a,sessionLocked:i,sessionLockConflicts:n,...l}=e;return l}(V),U=$(V.stateDir),B=V.session??"default",z=V.daemonBaseUrl,K=!V.verbose||V.json||z?null:function(e){try{let t=0,s=!1,r=setInterval(()=>{if(!s&&w.existsSync(e))try{let s=w.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let r=w.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);w.readSync(r,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{w.closeSync(r)}}catch{}},200);return()=>{s=!0,clearInterval(r)}}catch{return null}}(U.logPath),X=F({session:B,requestId:s,stateDir:V.stateDir,daemonBaseUrl:V.daemonBaseUrl,daemonAuthToken:V.daemonAuthToken,daemonTransport:V.daemonTransport,daemonServerMode:V.daemonServerMode,tenant:V.tenant,sessionIsolation:V.sessionIsolation,runId:V.runId,leaseId:V.leaseId,lockPolicy:j.lockPolicy,lockPlatform:j.defaultPlatform,cwd:process.cwd(),debug:!!V.verbose},{transport:t.sendToDaemon}),Z=async e=>await t.sendToDaemon({session:B,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:s,debug:!!V.verbose,cwd:process.cwd(),tenantId:V.tenant,runId:V.runId,leaseId:V.leaseId,sessionIsolation:V.sessionIsolation,lockPolicy:j.lockPolicy,lockPlatform:j.defaultPlatform}});try{if("batch"===P){let e,t,s;if(R.length>0)throw new y("INVALID_ARGS","batch does not accept positional arguments.");let r=(function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=w.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new y("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return o(t)})(V).map((e,t)=>({...e,flags:j.lockPolicy&&void 0===V.platform?{...e.flags??{}}:eS(e.flags??{},{policyOverrides:V,configuredPlatform:V.platform,configuredSession:V.session,inheritedPlatform:V.platform})})),a={...M,batchSteps:r};delete a.steps,delete a.stepsFile;let i=await Z({command:"batch",positionals:R,flags:a});if(!i.ok)throw new y(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});V.json?el({success:!0,data:i.data??{}}):(x=i.data??{},e="number"==typeof x.total?x.total:0,t="number"==typeof x.executed?x.executed:0,s="number"==typeof x.totalDurationMs?x.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${t}/${e} steps${void 0!==s?` in ${s}ms`:""}
|
|
45
|
+
`)),K&&K();return}if(await ew({command:P,positionals:R,flags:V,client:X})){K&&K();return}let e=await Z({command:P,positionals:R,flags:M});if(e.ok){if(V.json){el({success:!0,data:e.data??{}}),K&&K();return}if("snapshot"===P){process.stdout.write(eu(e.data??{},{raw:V.snapshotRaw,flatten:V.snapshotInteractiveOnly})),K&&K();return}if("diff"===P&&"snapshot"===R[0]){process.stdout.write(function(e){var t,s,o,a;let i=!0===e.baselineInitialized,n=e.summary??{},l=ed(n.additions),p=ed(n.removals),u=ed(n.unchanged),d=ec();if(i)return`Baseline initialized (${u} lines).
|
|
46
|
+
`;let c=(function(e,t){if(0===e.length)return e;let s=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===s.length)return e;let r=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),o=Math.min(e.length-1,t+1);for(let e=s;e<=o;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[],1).map(e=>{var t,s,o,a;let i="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=i.startsWith(" ")?`+${i}`:`+ ${i}`;return d?(t=e,s="green",r(s,t)):e}if("removed"===e.kind){let e=i.startsWith(" ")?`-${i}`:`- ${i}`;return d?(o=e,r("red",o)):e}return d?(a=i,r("dim",a)):i}),m=c.length>0?`${c.join("\n")}
|
|
47
|
+
`:"";if(!d)return`${m}${l} additions, ${p} removals, ${u} unchanged
|
|
48
|
+
`;let g=`${(t=String(l),s="green",r(s,t))} additions, ${(o=String(p),r("red",o))} removals, ${(a=String(u),r("dim",a))} unchanged`;return`${m}${g}
|
|
48
49
|
`}(e.data??{})),K&&K();return}if("get"===P){let t=R[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
|
|
49
50
|
`),K&&K();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
50
51
|
`),K&&K();return}}if("find"===P){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
|
|
@@ -52,34 +53,34 @@ ${r.join("\n\n")}
|
|
|
52
53
|
`),K&&K();return}if(t?.node){process.stdout.write(`${JSON.stringify(t.node,null,2)}
|
|
53
54
|
`),K&&K();return}}if("is"===P){let t=e.data?.predicate??"assertion";process.stdout.write(`Passed: is ${t}
|
|
54
55
|
`),K&&K();return}if("boot"===P){let t=e.data?.platform??"unknown",s=e.data?.device??e.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${t})
|
|
55
|
-
`),K&&K();return}if("ensure-simulator"===P){let t=e.data,s="string"==typeof t?.udid?t.udid:"unknown",
|
|
56
|
-
`),
|
|
57
|
-
`),K&&K();return}if("runtime"===P){let t=e.data,s=t?.cleared===!0,
|
|
56
|
+
`),K&&K();return}if("ensure-simulator"===P){let t=e.data,s="string"==typeof t?.udid?t.udid:"unknown",r="string"==typeof t?.device?t.device:"unknown",o="string"==typeof t?.runtime?t.runtime:"",a=t?.created===!0,i=t?.booted===!0;process.stdout.write(`${a?"Created":"Reused"}: ${r} ${s}${i?" (booted)":""}
|
|
57
|
+
`),o&&process.stdout.write(`Runtime: ${o}
|
|
58
|
+
`),K&&K();return}if("runtime"===P){let t=e.data,s=t?.cleared===!0,r=t?.configured===!0;if(s){process.stdout.write("Runtime hints cleared\n"),K&&K();return}if(!r){process.stdout.write("No runtime hints configured\n"),K&&K();return}process.stdout.write(`${JSON.stringify(t?.runtime??{},null,2)}
|
|
58
59
|
`),K&&K();return}if("screenshot"===P){let t="string"==typeof e.data?.path?e.data.path:"";t&&process.stdout.write(`${t}
|
|
59
60
|
`),K&&K();return}if("record"===P){let t=e.data,s="string"==typeof t?.outPath?t.outPath:"";s&&process.stdout.write(`${s}
|
|
60
61
|
`),K&&K();return}if("logs"===P){let t=e.data,s="string"==typeof t?.path?t.path:"";if(s){process.stdout.write(`${s}
|
|
61
|
-
`);let e="boolean"==typeof t?.active?t.active:void 0,
|
|
62
|
-
`)}if(!V.json&&(
|
|
62
|
+
`);let e="boolean"==typeof t?.active?t.active:void 0,r="string"==typeof t?.state?t.state:void 0,o="string"==typeof t?.backend?t.backend:void 0,a="number"==typeof t?.sizeBytes?t.sizeBytes:void 0,i=t?.started===!0,n=t?.stopped===!0,l=t?.marked===!0,p=t?.cleared===!0,u=t?.restarted===!0,d="number"==typeof t?.removedRotatedFiles?t.removedRotatedFiles:void 0;if(!V.json&&(void 0!==e||r||o||void 0!==a)){let t=[void 0!==e?`active=${e}`:"",r?`state=${r}`:"",o?`backend=${o}`:"",void 0!==a?`sizeBytes=${a}`:""].filter(Boolean).join(" ");t&&process.stderr.write(`${t}
|
|
63
|
+
`)}if(!V.json&&(i||n||l||p||u||void 0!==d)){let e=[i?"started=true":"",n?"stopped=true":"",l?"marked=true":"",p?"cleared=true":"",u?"restarted=true":"",void 0!==d?`removedRotatedFiles=${d}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
63
64
|
`)}if(t?.hint&&!V.json&&process.stderr.write(`${t.hint}
|
|
64
65
|
`),Array.isArray(t?.notes)&&!V.json)for(let e of t.notes)"string"==typeof e&&e.length>0&&process.stderr.write(`${e}
|
|
65
66
|
`)}K&&K();return}if("clipboard"===P){let t=e.data,s=(R[0]??("string"==typeof t?.action?t.action:"")).toLowerCase();if("read"===s){let e="string"==typeof t?.text?t.text:"";process.stdout.write(`${e}
|
|
66
67
|
`),K&&K();return}if("write"===s){process.stdout.write("Clipboard updated\n"),K&&K();return}}if("network"===P){let t=e.data,s="string"==typeof t?.path?t.path:"";s&&process.stdout.write(`${s}
|
|
67
|
-
`);let
|
|
68
|
+
`);let r=Array.isArray(t?.entries)?t.entries:[];if(0===r.length)process.stdout.write("No recent HTTP(s) entries found.\n");else for(let e of r){let t="string"==typeof e.method?e.method:"HTTP",s="string"==typeof e.url?e.url:"<unknown-url>",r="number"==typeof e.status?` status=${e.status}`:"",o="string"==typeof e.timestamp?`${e.timestamp} `:"";process.stdout.write(`${o}${t} ${s}${r}
|
|
68
69
|
`),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
|
|
69
70
|
`),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
|
|
70
71
|
`),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
|
|
71
|
-
`)}let
|
|
72
|
+
`)}let o="boolean"==typeof t?.active?t.active:void 0,a="string"==typeof t?.state?t.state:void 0,i="string"==typeof t?.backend?t.backend:void 0,n="number"==typeof t?.scannedLines?t.scannedLines:void 0,l="number"==typeof t?.matchedLines?t.matchedLines:void 0,p="string"==typeof t?.include?t.include:void 0,u=[void 0!==o?`active=${o}`:"",a?`state=${a}`:"",i?`backend=${i}`:"",p?`include=${p}`:"",void 0!==n?`scannedLines=${n}`:"",void 0!==l?`matchedLines=${l}`:""].filter(Boolean).join(" ");if(u&&process.stderr.write(`${u}
|
|
72
73
|
`),Array.isArray(t?.notes))for(let e of t.notes)"string"==typeof e&&e.length>0&&process.stderr.write(`${e}
|
|
73
|
-
`);K&&K();return}if("click"===P||"press"===P){let t=e.data?.ref??"",s=e.data?.x,
|
|
74
|
-
`),K&&K();return}if(e.data&&"object"==typeof e.data){let t=e.data;if("devices"===P){let e=(Array.isArray(t.devices)?t.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",s=e?.platform??"unknown",
|
|
74
|
+
`);K&&K();return}if("click"===P||"press"===P){let t=e.data?.ref??"",s=e.data?.x,r=e.data?.y;t&&"number"==typeof s&&"number"==typeof r&&process.stdout.write(`Tapped @${t} (${s}, ${r})
|
|
75
|
+
`),K&&K();return}if(e.data&&"object"==typeof e.data){let t=e.data;if("devices"===P){let e=(Array.isArray(t.devices)?t.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",s=e?.platform??"unknown",r=e?.kind?` ${e.kind}`:"",o=e?.target?` target=${e.target}`:"",a="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${r}${o})${a}`});process.stdout.write(`${e.join("\n")}
|
|
75
76
|
`),K&&K();return}if("apps"===P){let e=(Array.isArray(t.apps)?t.apps:[]).map(e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e.bundleId??e.package,s=e.name??e.label;return s&&t?`${s} (${t})`:t?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${e.join("\n")}
|
|
76
|
-
`),K&&K();return}if("appstate"===P){let e=t?.platform,s=t?.appBundleId,
|
|
77
|
+
`),K&&K();return}if("appstate"===P){let e=t?.platform,s=t?.appBundleId,r=t?.appName,o=t?.source,a=t?.package,i=t?.activity;if("ios"===e){process.stdout.write(`Foreground app: ${r??s??"unknown"}
|
|
77
78
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
78
|
-
`),
|
|
79
|
-
`),K&&K();return}if("android"===e){process.stdout.write(`Foreground app: ${
|
|
80
|
-
`),
|
|
79
|
+
`),o&&process.stdout.write(`Source: ${o}
|
|
80
|
+
`),K&&K();return}if("android"===e){process.stdout.write(`Foreground app: ${a??"unknown"}
|
|
81
|
+
`),i&&process.stdout.write(`Activity: ${i}
|
|
81
82
|
`),K&&K();return}}if("perf"===P){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
82
|
-
`),K&&K();return}}K&&K();return}throw new y(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(s){let e=
|
|
83
|
+
`),K&&K();return}}K&&K();return}throw new y(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(s){let e=g(s),t=l(e,{diagnosticId:d().diagnosticId,logPath:k({force:!0})??void 0});if("close"===P&&"COMMAND_FAILED"===(N=e).code&&(N.details?.kind==="daemon_startup_failed"||N.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof N.details?.infoPath||"string"==typeof N.details?.lockPath))){V.json&&el({success:!0,data:{closed:"session",source:"no-daemon"}}),K&&K();return}if(V.json)el({success:!1,error:t});else if(ep(t,{showDetails:V.verbose}),V.verbose)try{let e=U.logPath;if(w.existsSync(e)){let t=w.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
83
84
|
[daemon log]
|
|
84
85
|
${s}
|
|
85
|
-
`)}}catch{}K&&K(),process.exit(1)}})}h(process.argv[1]??"").href===import.meta.url&&eO(process.argv.slice(2)).catch(e=>{
|
|
86
|
+
`)}}catch{}K&&K(),process.exit(1)}})}h(process.argv[1]??"").href===import.meta.url&&eO(process.argv.slice(2)).catch(e=>{ep(l(g(e)),{showDetails:!0}),process.exit(1)}),eO(process.argv.slice(2));
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export type MetroPrepareKind = 'auto' | 'react-native' | 'expo';
|
|
2
|
+
type ResolvedMetroKind = Exclude<MetroPrepareKind, 'auto'>;
|
|
3
|
+
type EnvSource = NodeJS.ProcessEnv | Record<string, string | undefined>;
|
|
4
|
+
export type MetroRuntimeHints = {
|
|
5
|
+
platform?: 'ios' | 'android';
|
|
6
|
+
metroHost?: string;
|
|
7
|
+
metroPort?: number;
|
|
8
|
+
bundleUrl?: string;
|
|
9
|
+
launchUrl?: string;
|
|
10
|
+
};
|
|
11
|
+
export type MetroBridgeResult = {
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
statusUrl: string;
|
|
15
|
+
bundleUrl: string;
|
|
16
|
+
iosRuntime: MetroRuntimeHints;
|
|
17
|
+
androidRuntime: MetroRuntimeHints;
|
|
18
|
+
upstream: {
|
|
19
|
+
bundleUrl: string;
|
|
20
|
+
host: string;
|
|
21
|
+
port: number;
|
|
22
|
+
statusUrl: string;
|
|
23
|
+
};
|
|
24
|
+
probe: {
|
|
25
|
+
reachable: boolean;
|
|
26
|
+
statusCode: number;
|
|
27
|
+
latencyMs: number;
|
|
28
|
+
detail: string;
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
export type PrepareMetroRuntimeOptions = {
|
|
32
|
+
projectRoot?: string;
|
|
33
|
+
kind?: MetroPrepareKind;
|
|
34
|
+
metroPort?: number | string;
|
|
35
|
+
listenHost?: string;
|
|
36
|
+
statusHost?: string;
|
|
37
|
+
publicBaseUrl?: string;
|
|
38
|
+
proxyBaseUrl?: string;
|
|
39
|
+
proxyBearerToken?: string;
|
|
40
|
+
startupTimeoutMs?: number | string;
|
|
41
|
+
probeTimeoutMs?: number | string;
|
|
42
|
+
reuseExisting?: boolean;
|
|
43
|
+
installDependenciesIfNeeded?: boolean;
|
|
44
|
+
runtimeFilePath?: string;
|
|
45
|
+
logPath?: string;
|
|
46
|
+
env?: EnvSource;
|
|
47
|
+
};
|
|
48
|
+
export type PrepareMetroRuntimeResult = {
|
|
49
|
+
projectRoot: string;
|
|
50
|
+
kind: ResolvedMetroKind;
|
|
51
|
+
dependenciesInstalled: boolean;
|
|
52
|
+
packageManager: string | null;
|
|
53
|
+
started: boolean;
|
|
54
|
+
reused: boolean;
|
|
55
|
+
pid: number;
|
|
56
|
+
logPath: string;
|
|
57
|
+
statusUrl: string;
|
|
58
|
+
runtimeFilePath: string | null;
|
|
59
|
+
iosRuntime: MetroRuntimeHints;
|
|
60
|
+
androidRuntime: MetroRuntimeHints;
|
|
61
|
+
bridge: MetroBridgeResult | null;
|
|
62
|
+
};
|
|
63
|
+
export declare function prepareMetroRuntime(input?: PrepareMetroRuntimeOptions): Promise<PrepareMetroRuntimeResult>;
|
|
64
|
+
export {};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { DaemonInstallSource, DaemonLockPolicy, DaemonRequest, DaemonResponse, SessionRuntimeHints } from './daemon/types.ts';
|
|
2
2
|
import type { DeviceKind, DeviceTarget, Platform, PlatformSelector } from './utils/device.ts';
|
|
3
3
|
import type { SnapshotNode } from './utils/snapshot.ts';
|
|
4
|
+
import type { MetroPrepareKind, PrepareMetroRuntimeResult } from './client-metro.ts';
|
|
4
5
|
type DaemonTransportMode = 'auto' | 'socket' | 'http';
|
|
5
6
|
type DaemonServerMode = 'socket' | 'http' | 'dual';
|
|
6
7
|
type SessionIsolationMode = 'none' | 'tenant';
|
|
@@ -187,6 +188,23 @@ export type RuntimeResult = {
|
|
|
187
188
|
runtime?: SessionRuntimeHints;
|
|
188
189
|
identifiers: AgentDeviceIdentifiers;
|
|
189
190
|
};
|
|
191
|
+
export type MetroPrepareOptions = {
|
|
192
|
+
projectRoot?: string;
|
|
193
|
+
kind?: MetroPrepareKind;
|
|
194
|
+
publicBaseUrl: string;
|
|
195
|
+
proxyBaseUrl?: string;
|
|
196
|
+
bearerToken?: string;
|
|
197
|
+
port?: number;
|
|
198
|
+
listenHost?: string;
|
|
199
|
+
statusHost?: string;
|
|
200
|
+
startupTimeoutMs?: number;
|
|
201
|
+
probeTimeoutMs?: number;
|
|
202
|
+
reuseExisting?: boolean;
|
|
203
|
+
installDependenciesIfNeeded?: boolean;
|
|
204
|
+
runtimeFilePath?: string;
|
|
205
|
+
logPath?: string;
|
|
206
|
+
};
|
|
207
|
+
export type MetroPrepareResult = PrepareMetroRuntimeResult;
|
|
190
208
|
export type CaptureSnapshotOptions = AgentDeviceRequestOverrides & AgentDeviceSelectionOptions & {
|
|
191
209
|
interactiveOnly?: boolean;
|
|
192
210
|
compact?: boolean;
|
|
@@ -259,6 +277,9 @@ export type AgentDeviceClient = {
|
|
|
259
277
|
set: (options: RuntimeSetOptions) => Promise<RuntimeResult>;
|
|
260
278
|
show: (options?: RuntimeShowOptions) => Promise<RuntimeResult>;
|
|
261
279
|
};
|
|
280
|
+
metro: {
|
|
281
|
+
prepare: (options: MetroPrepareOptions) => Promise<MetroPrepareResult>;
|
|
282
|
+
};
|
|
262
283
|
capture: {
|
|
263
284
|
snapshot: (options?: CaptureSnapshotOptions) => Promise<CaptureSnapshotResult>;
|
|
264
285
|
screenshot: (options?: CaptureScreenshotOptions) => Promise<CaptureScreenshotResult>;
|
package/dist/src/client.d.ts
CHANGED
|
@@ -2,4 +2,4 @@ import type { AgentDeviceClient, AgentDeviceClientConfig, AgentDeviceDaemonTrans
|
|
|
2
2
|
export declare function createAgentDeviceClient(config?: AgentDeviceClientConfig, deps?: {
|
|
3
3
|
transport?: AgentDeviceDaemonTransport;
|
|
4
4
|
}): AgentDeviceClient;
|
|
5
|
-
export type { AgentDeviceClient, AgentDeviceClientConfig, AgentDeviceDaemonTransport, AgentDeviceDevice, AgentDeviceIdentifiers, AgentDeviceRequestOverrides, AgentDeviceSelectionOptions, AgentDeviceSession, AgentDeviceSessionDevice, AppCloseOptions, AppCloseResult, AppDeployOptions, AppDeployResult, AppInstallFromSourceOptions, AppInstallFromSourceResult, AppOpenOptions, AppOpenResult, CaptureScreenshotOptions, CaptureScreenshotResult, CaptureSnapshotOptions, CaptureSnapshotResult, EnsureSimulatorOptions, EnsureSimulatorResult, MaterializationReleaseOptions, MaterializationReleaseResult, RuntimeResult, RuntimeSetOptions, RuntimeShowOptions, SessionCloseResult, StartupPerfSample, } from './client-types.ts';
|
|
5
|
+
export type { AgentDeviceClient, AgentDeviceClientConfig, AgentDeviceDaemonTransport, AgentDeviceDevice, AgentDeviceIdentifiers, AgentDeviceRequestOverrides, AgentDeviceSelectionOptions, AgentDeviceSession, AgentDeviceSessionDevice, AppCloseOptions, AppCloseResult, AppDeployOptions, AppDeployResult, AppInstallFromSourceOptions, AppInstallFromSourceResult, AppOpenOptions, AppOpenResult, CaptureScreenshotOptions, CaptureScreenshotResult, CaptureSnapshotOptions, CaptureSnapshotResult, EnsureSimulatorOptions, EnsureSimulatorResult, MaterializationReleaseOptions, MaterializationReleaseResult, MetroPrepareOptions, MetroPrepareResult, RuntimeResult, RuntimeSetOptions, RuntimeShowOptions, SessionCloseResult, StartupPerfSample, } from './client-types.ts';
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { createAgentDeviceClient, type AgentDeviceClient, type AgentDeviceClientConfig, type AgentDeviceDevice, type AgentDeviceIdentifiers, type AgentDeviceSelectionOptions, type AgentDeviceSession, type AgentDeviceSessionDevice, type AppCloseOptions, type AppCloseResult, type AppDeployOptions, type AppDeployResult, type AppInstallFromSourceOptions, type AppInstallFromSourceResult, type AppOpenOptions, type AppOpenResult, type CaptureScreenshotOptions, type CaptureScreenshotResult, type CaptureSnapshotOptions, type CaptureSnapshotResult, type EnsureSimulatorOptions, type EnsureSimulatorResult, type MaterializationReleaseOptions, type MaterializationReleaseResult, type RuntimeResult, type RuntimeSetOptions, type RuntimeShowOptions, type SessionCloseResult, type StartupPerfSample, } from './client.ts';
|
|
1
|
+
export { createAgentDeviceClient, type AgentDeviceClient, type AgentDeviceClientConfig, type AgentDeviceDevice, type AgentDeviceIdentifiers, type AgentDeviceSelectionOptions, type AgentDeviceSession, type AgentDeviceSessionDevice, type AppCloseOptions, type AppCloseResult, type AppDeployOptions, type AppDeployResult, type AppInstallFromSourceOptions, type AppInstallFromSourceResult, type AppOpenOptions, type AppOpenResult, type CaptureScreenshotOptions, type CaptureScreenshotResult, type CaptureSnapshotOptions, type CaptureSnapshotResult, type EnsureSimulatorOptions, type EnsureSimulatorResult, type MaterializationReleaseOptions, type MaterializationReleaseResult, type MetroPrepareOptions, type MetroPrepareResult, type RuntimeResult, type RuntimeSetOptions, type RuntimeShowOptions, type SessionCloseResult, type StartupPerfSample, } from './client.ts';
|
|
2
2
|
export { AppError, type NormalizedError } from './utils/errors.ts';
|
|
3
|
+
export type { MetroPrepareKind, MetroRuntimeHints } from './client-metro.ts';
|
|
3
4
|
export type { SessionRuntimeHints } from './daemon/types.ts';
|
|
4
5
|
export type { SnapshotNode } from './utils/snapshot.ts';
|
|
@@ -25,6 +25,19 @@ export type CliFlags = {
|
|
|
25
25
|
runtime?: string;
|
|
26
26
|
metroHost?: string;
|
|
27
27
|
metroPort?: number;
|
|
28
|
+
metroProjectRoot?: string;
|
|
29
|
+
metroKind?: 'auto' | 'react-native' | 'expo';
|
|
30
|
+
metroPublicBaseUrl?: string;
|
|
31
|
+
metroProxyBaseUrl?: string;
|
|
32
|
+
metroBearerToken?: string;
|
|
33
|
+
metroPreparePort?: number;
|
|
34
|
+
metroListenHost?: string;
|
|
35
|
+
metroStatusHost?: string;
|
|
36
|
+
metroStartupTimeoutMs?: number;
|
|
37
|
+
metroProbeTimeoutMs?: number;
|
|
38
|
+
metroRuntimeFile?: string;
|
|
39
|
+
metroNoReuseExisting?: boolean;
|
|
40
|
+
metroNoInstallDeps?: boolean;
|
|
28
41
|
bundleUrl?: string;
|
|
29
42
|
launchUrl?: string;
|
|
30
43
|
boot?: boolean;
|