agent-device 0.7.10 → 0.7.12
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/678.js +3 -3
- package/dist/src/bin.js +14 -11
- package/dist/src/daemon.js +33 -31
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -314,6 +314,8 @@ Navigation helpers:
|
|
|
314
314
|
- `reinstall <app> <path>` uninstalls and installs the app binary in one command (Android + iOS simulator/device).
|
|
315
315
|
- `install`/`reinstall` accept package/bundle id style app names and support `~` in paths.
|
|
316
316
|
- When `AGENT_DEVICE_DAEMON_BASE_URL` targets a remote daemon, local `.apk`/`.aab`/`.ipa` files and `.app` bundles are uploaded automatically before `install`/`reinstall`.
|
|
317
|
+
- 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"`.
|
|
318
|
+
- Remote daemon screenshots and recordings are materialized back to the caller path instead of returning host-local daemon paths.
|
|
317
319
|
- To force a daemon-side path instead of uploading a local file, prefix it with `remote:`, for example `remote:/srv/builds/MyApp.app`.
|
|
318
320
|
- Supported binary formats for `install`/`reinstall`: Android `.apk` and `.aab`, iOS `.app` and `.ipa`.
|
|
319
321
|
- `.aab` requires `bundletool` in `PATH`, or `AGENT_DEVICE_BUNDLETOOL_JAR=<path-to-bundletool-all.jar>` (with `java` in `PATH`).
|
package/dist/src/678.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r,{promises as n}from"node:fs";import o from"node:os";import i from"node:path";import{
|
|
2
|
-
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function
|
|
3
|
-
`),t.events=[],c}catch{return null}}function y(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&u.test(i)||f.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let a={};for(let[n,o]of Object.entries(t)){if(u.test(n)){a[n]="[REDACTED]";continue}a[n]=e(o,r,n)}return a}(e,new WeakSet)}class v extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function A(e){return e instanceof v?e:e instanceof Error?new v("UNKNOWN",e.message,void 0,e):new v("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=A(e),n=r.details?y(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,a=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,s=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),c=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),l=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:l,hint:s,diagnosticId:i,logPath:a,details:c}}let E="<wifi|airplane|location> <on|off>",D="appearance <light|dark|toggle>",$="faceid <match|nonmatch|enroll|unenroll>",b="touchid <match|nonmatch|enroll|unenroll>",N="fingerprint <match|nonmatch>",_="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",M=`settings ${E} | settings ${D} | settings ${$} | settings ${b} | settings ${N} | settings ${_}`,T=`settings requires ${E}, ${D}, ${$}, ${b}, ${N}, or ${_}`;function O(e){let t=[],r=[];for(let n of e){let e=n.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let o=n.label?.trim()||n.value?.trim()||n.identifier?.trim()||"",i=C(n.type??"Element"),a="group"===i&&!o;a&&t.push(e);let s=a?e:Math.max(0,e-t.length);r.push({node:n,depth:s,type:i,text:L(n,s,a,i)})}return r}function L(e,t,r,n){let o=n??C(e.type??"Element"),i=x(e,o),a=" ".repeat(t),s=e.ref?`@${e.ref}`:"",c=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=c?` [${c}]`:"",d=i?` "${i}"`:"";return r?`${a}${s} [${o}]${l}`.trimEnd():`${a}${s} [${o}]${d}${l}`.trimEnd()}function x(e,t){var r,n;let o=e.label?.trim(),i=e.value?.trim();if("text-field"===(r=t)||"text-view"===r||"search"===r){if(i)return i;if(o)return o}else if(o)return o;if(i)return i;let a=e.identifier?.trim();return!a||(n=a,/^[\w.]+:id\/[\w.-]+$/i.test(n)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":a}function C(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),r=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,"")),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return r?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function P(){try{let e=k();return JSON.parse(r.readFileSync(i.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function k(){let e=i.dirname(a(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=i.join(t,"package.json");if(r.existsSync(e))return t;t=i.dirname(t)}return e}async function R(e,t,r={}){return new Promise((n,o)=>{let i=c(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",s=r.binaryStdout?Buffer.alloc(0):void 0,l="",d=!1,u=V(r.timeoutMs),f=u?setTimeout(()=>{d=!0,i.kill("SIGKILL")},u):null;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{r.binaryStdout?s=Buffer.concat([s??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),i.stderr.on("data",e=>{l+=e}),i.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?o(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{f&&clearTimeout(f);let c=i??1;d&&u?o(new v("COMMAND_FAILED",`${e} timed out after ${u}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:c,timeoutMs:u})):0===c||r.allowFailure?n({stdout:a,stderr:l,exitCode:c,stdoutBuffer:s}):o(new v("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:c,processExitError:!0}))})})}async function F(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await R(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function B(e,t,r={}){let n=l(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:V(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new v("COMMAND_FAILED",`${e} timed out after ${V(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:V(r.timeoutMs)},n.error);if("ENOENT"===o)throw new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let o=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,i=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),s=n.status??1;if(0!==s&&!r.allowFailure)throw new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:i,stderr:a,exitCode:s,processExitError:!0});return{stdout:i,stderr:a,exitCode:s,stdoutBuffer:o}}function j(e,t,r={}){c(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function G(e,t,r={}){return new Promise((n,o)=>{let i=c(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(i);let a="",s="",l=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{if(r.binaryStdout){l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),i.stderr.on("data",e=>{let t=String(e);s+=t,r.onStderrChunk?.(t)}),i.on("error",r=>{"ENOENT"===r.code?o(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{let c=i??1;0===c||r.allowFailure?n({stdout:a,stderr:s,exitCode:c,stdoutBuffer:l}):o(new v("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:a,stderr:s,exitCode:c,processExitError:!0}))})})}function U(e,t,r={}){let n=c(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),o="",i="";n.stdout.setEncoding("utf8"),n.stderr.setEncoding("utf8"),n.stdout.on("data",e=>{o+=e}),n.stderr.on("data",e=>{i+=e});let a=new Promise((a,s)=>{n.on("error",r=>{"ENOENT"===r.code?s(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):s(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),n.on("close",n=>{let c=n??1;0===c||r.allowFailure?a({stdout:o,stderr:i,exitCode:c}):s(new v("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:o,stderr:i,exitCode:c,processExitError:!0}))})});return{child:n,wait:a}}function V(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let q=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function H(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function z(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=B("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function J(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=B("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function W(e,t){let r;if(!H(e))return!1;if(t){let r=z(e);if(!r||r!==t)return!1}let n=J(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&q.some(e=>e.test(r))}function K(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function Z(e,t){if(!H(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!H(e))return!0;return!H(e)}async function X(e,t){!W(e,t.expectedStartTime)||!K(e,"SIGTERM")||await Z(e,t.termTimeoutMs)||K(e,"SIGKILL")&&await Z(e,t.killTimeoutMs)}function Q(e){let t,r=(t=(e??"").trim())?"~"===t?o.homedir():t.startsWith("~/")?i.join(o.homedir(),t.slice(2)):i.resolve(t):i.join(o.homedir(),".agent-device");return{baseDir:r,infoPath:i.join(r,"daemon.json"),lockPath:i.join(r,"daemon.lock"),logPath:i.join(r,"daemon.log"),sessionsDir:i.join(r,"sessions")}}function Y(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function ee(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function et(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function er(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let en=100,eo=new Set(["batch","replay"]);function ei(e){let t;try{t=JSON.parse(e)}catch{throw new v("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new v("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function ea(e,t){if(!Array.isArray(e)||0===e.length)throw new v("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new v("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let r=[];for(let t=0;t<e.length;t+=1){let n=e[t];if(!n||"object"!=typeof n)throw new v("INVALID_ARGS",`Invalid batch step at index ${t}.`);let o="string"==typeof n.command?n.command.trim().toLowerCase():"";if(!o)throw new v("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(eo.has(o))throw new v("INVALID_ARGS",`Batch step ${t+1} cannot run ${o}.`);if(void 0!==n.positionals&&!Array.isArray(n.positionals))throw new v("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let i=n.positionals??[];if(i.some(e=>"string"!=typeof e))throw new v("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==n.flags&&("object"!=typeof n.flags||Array.isArray(n.flags)||!n.flags))throw new v("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);r.push({command:o,positionals:i,flags:n.flags??{}})}return r}export{default as node_net}from"node:net";export{default as node_http}from"node:http";export{v as AppError,en as DEFAULT_BATCH_MAX_STEPS,T as SETTINGS_INVALID_ARGS_MESSAGE,M as SETTINGS_USAGE_OVERRIDE,A as asAppError,O as buildSnapshotDisplayLines,m as createRequestId,x as displayLabel,g as emitDiagnostic,a as fileURLToPath,k as findProjectRoot,S as flushDiagnosticsToSessionFile,C as formatRole,L as formatSnapshotLine,h as getDiagnosticsMeta,W as isAgentDeviceDaemonProcess,H as isProcessAlive,t as node_crypto,r as node_fs,o as node_os,i as node_path,I as normalizeError,er as normalizeTenantId,ei as parseBatchStepsJson,s as pathToFileURL,n as promises,J as readProcessCommand,z as readProcessStartTime,P as readVersion,Q as resolveDaemonPaths,Y as resolveDaemonServerMode,ee as resolveDaemonTransportPreference,et as resolveSessionIsolationMode,R as runCmd,U as runCmdBackground,j as runCmdDetached,G as runCmdStreaming,B as runCmdSync,c as spawn,X as stopProcessForTakeover,ea as validateAndNormalizeBatchSteps,F as whichCmd,w as withDiagnosticTimer,p as withDiagnosticsScope};
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r,{promises as n}from"node:fs";import o from"node:os";import i from"node:path";import{URL as a,fileURLToPath as s,pathToFileURL as c}from"node:url";import{spawn as l,spawnSync as d}from"node:child_process";let u=new e,f=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,m=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function p(){return t.randomBytes(8).toString("hex")}async function h(e,r){let n={...e,diagnosticId:`${Date.now().toString(36)}-${t.randomBytes(4).toString("hex")}`,events:[]};return await u.run(n,r)}function g(){let e=u.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function w(e){let t=u.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?v(e.data):void 0};if(t.events.push(n),!t.debug)return;let o=`[agent-device][diag] ${JSON.stringify(n)}
|
|
2
|
+
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function S(e,t,r){let n=Date.now();try{let o=await t();return w({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw w({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function y(e={}){let t=u.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),n=new Date().toISOString().slice(0,10),a=i.join(o.homedir(),".agent-device","logs",e,n);r.mkdirSync(a,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),c=i.join(a,`${s}-${t.diagnosticId}.ndjson`),l=t.events.map(e=>JSON.stringify(v(e)));return r.writeFileSync(c,`${l.join("\n")}
|
|
3
|
+
`),t.events=[],c}catch{return null}}function v(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&f.test(i)||m.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let a={};for(let[n,o]of Object.entries(t)){if(f.test(n)){a[n]="[REDACTED]";continue}a[n]=e(o,r,n)}return a}(e,new WeakSet)}class A extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function I(e){return e instanceof A?e:e instanceof Error?new A("UNKNOWN",e.message,void 0,e):new A("UNKNOWN","Unknown error",{err:e})}function E(e,t={}){let r=I(e),n=r.details?v(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,a=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,s=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),c=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),l=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:l,hint:s,diagnosticId:i,logPath:a,details:c}}let D="<wifi|airplane|location> <on|off>",$="appearance <light|dark|toggle>",b="faceid <match|nonmatch|enroll|unenroll>",N="touchid <match|nonmatch|enroll|unenroll>",_="fingerprint <match|nonmatch>",M="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",L=`settings ${D} | settings ${$} | settings ${b} | settings ${N} | settings ${_} | settings ${M}`,T=`settings requires ${D}, ${$}, ${b}, ${N}, ${_}, or ${M}`;function O(e){let t=[],r=[];for(let n of e){let e=n.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let o=n.label?.trim()||n.value?.trim()||n.identifier?.trim()||"",i=P(n.type??"Element"),a="group"===i&&!o;a&&t.push(e);let s=a?e:Math.max(0,e-t.length);r.push({node:n,depth:s,type:i,text:x(n,s,a,i)})}return r}function x(e,t,r,n){let o=n??P(e.type??"Element"),i=C(e,o),a=" ".repeat(t),s=e.ref?`@${e.ref}`:"",c=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=c?` [${c}]`:"",d=i?` "${i}"`:"";return r?`${a}${s} [${o}]${l}`.trimEnd():`${a}${s} [${o}]${d}${l}`.trimEnd()}function C(e,t){var r,n;let o=e.label?.trim(),i=e.value?.trim();if("text-field"===(r=t)||"text-view"===r||"search"===r){if(i)return i;if(o)return o}else if(o)return o;if(i)return i;let a=e.identifier?.trim();return!a||(n=a,/^[\w.]+:id\/[\w.-]+$/i.test(n)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":a}function P(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),r=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,"")),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return r?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function R(){try{let e=k();return JSON.parse(r.readFileSync(i.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function k(){let e=i.dirname(s(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=i.join(t,"package.json");if(r.existsSync(e))return t;t=i.dirname(t)}return e}async function F(e,t,r={}){return new Promise((n,o)=>{let i=l(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",s=r.binaryStdout?Buffer.alloc(0):void 0,c="",d=!1,u=q(r.timeoutMs),f=u?setTimeout(()=>{d=!0,i.kill("SIGKILL")},u):null;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{r.binaryStdout?s=Buffer.concat([s??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),i.stderr.on("data",e=>{c+=e}),i.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?o(new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{f&&clearTimeout(f);let l=i??1;d&&u?o(new A("COMMAND_FAILED",`${e} timed out after ${u}ms`,{cmd:e,args:t,stdout:a,stderr:c,exitCode:l,timeoutMs:u})):0===l||r.allowFailure?n({stdout:a,stderr:c,exitCode:l,stdoutBuffer:s}):o(new A("COMMAND_FAILED",`${e} exited with code ${l}`,{cmd:e,args:t,stdout:a,stderr:c,exitCode:l,processExitError:!0}))})})}async function B(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await F(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function j(e,t,r={}){let n=d(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:q(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new A("COMMAND_FAILED",`${e} timed out after ${q(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:q(r.timeoutMs)},n.error);if("ENOENT"===o)throw new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let o=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,i=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),s=n.status??1;if(0!==s&&!r.allowFailure)throw new A("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:i,stderr:a,exitCode:s,processExitError:!0});return{stdout:i,stderr:a,exitCode:s,stdoutBuffer:o}}function G(e,t,r={}){l(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function U(e,t,r={}){return new Promise((n,o)=>{let i=l(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(i);let a="",s="",c=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{if(r.binaryStdout){c=Buffer.concat([c??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),i.stderr.on("data",e=>{let t=String(e);s+=t,r.onStderrChunk?.(t)}),i.on("error",r=>{"ENOENT"===r.code?o(new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{let l=i??1;0===l||r.allowFailure?n({stdout:a,stderr:s,exitCode:l,stdoutBuffer:c}):o(new A("COMMAND_FAILED",`${e} exited with code ${l}`,{cmd:e,args:t,stdout:a,stderr:s,exitCode:l,processExitError:!0}))})})}function V(e,t,r={}){let n=l(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),o="",i="";n.stdout.setEncoding("utf8"),n.stderr.setEncoding("utf8"),n.stdout.on("data",e=>{o+=e}),n.stderr.on("data",e=>{i+=e});let a=new Promise((a,s)=>{n.on("error",r=>{"ENOENT"===r.code?s(new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):s(new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),n.on("close",n=>{let c=n??1;0===c||r.allowFailure?a({stdout:o,stderr:i,exitCode:c}):s(new A("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:o,stderr:i,exitCode:c,processExitError:!0}))})});return{child:n,wait:a}}function q(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let H=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function z(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function J(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=j("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function W(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=j("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function K(e,t){let r;if(!z(e))return!1;if(t){let r=J(e);if(!r||r!==t)return!1}let n=W(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&H.some(e=>e.test(r))}function Z(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function X(e,t){if(!z(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!z(e))return!0;return!z(e)}async function Q(e,t){!K(e,t.expectedStartTime)||!Z(e,"SIGTERM")||await X(e,t.termTimeoutMs)||Z(e,"SIGKILL")&&await X(e,t.killTimeoutMs)}function Y(e){let t,r=(t=(e??"").trim())?"~"===t?o.homedir():t.startsWith("~/")?i.join(o.homedir(),t.slice(2)):i.resolve(t):i.join(o.homedir(),".agent-device");return{baseDir:r,infoPath:i.join(r,"daemon.json"),lockPath:i.join(r,"daemon.lock"),logPath:i.join(r,"daemon.log"),sessionsDir:i.join(r,"sessions")}}function ee(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function et(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function er(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function en(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let eo=100,ei=new Set(["batch","replay"]);function ea(e){let t;try{t=JSON.parse(e)}catch{throw new A("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new A("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function es(e,t){if(!Array.isArray(e)||0===e.length)throw new A("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new A("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let r=[];for(let t=0;t<e.length;t+=1){let n=e[t];if(!n||"object"!=typeof n)throw new A("INVALID_ARGS",`Invalid batch step at index ${t}.`);let o="string"==typeof n.command?n.command.trim().toLowerCase():"";if(!o)throw new A("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(ei.has(o))throw new A("INVALID_ARGS",`Batch step ${t+1} cannot run ${o}.`);if(void 0!==n.positionals&&!Array.isArray(n.positionals))throw new A("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let i=n.positionals??[];if(i.some(e=>"string"!=typeof e))throw new A("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==n.flags&&("object"!=typeof n.flags||Array.isArray(n.flags)||!n.flags))throw new A("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);r.push({command:o,positionals:i,flags:n.flags??{}})}return r}export{default as node_net}from"node:net";export{default as node_http}from"node:http";export{A as AppError,eo as DEFAULT_BATCH_MAX_STEPS,T as SETTINGS_INVALID_ARGS_MESSAGE,L as SETTINGS_USAGE_OVERRIDE,I as asAppError,O as buildSnapshotDisplayLines,p as createRequestId,C as displayLabel,w as emitDiagnostic,a as external_node_url_URL,s as fileURLToPath,k as findProjectRoot,y as flushDiagnosticsToSessionFile,P as formatRole,x as formatSnapshotLine,g as getDiagnosticsMeta,K as isAgentDeviceDaemonProcess,z as isProcessAlive,t as node_crypto,r as node_fs,o as node_os,i as node_path,E as normalizeError,en as normalizeTenantId,ea as parseBatchStepsJson,c as pathToFileURL,n as promises,W as readProcessCommand,J as readProcessStartTime,R as readVersion,Y as resolveDaemonPaths,ee as resolveDaemonServerMode,et as resolveDaemonTransportPreference,er as resolveSessionIsolationMode,F as runCmd,V as runCmdBackground,G as runCmdDetached,U as runCmdStreaming,j as runCmdSync,l as spawn,Q as stopProcessForTakeover,es as validateAndNormalizeBatchSteps,B as whichCmd,S as withDiagnosticTimer,h as withDiagnosticsScope};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{styleText as e}from"node:util";import t from"node:https";import{node_http as s,node_path as a,buildSnapshotDisplayLines as r,createRequestId as o,parseBatchStepsJson as n,normalizeError as i,isAgentDeviceDaemonProcess as l,runCmdDetached as d,readVersion as p,findProjectRoot as u,getDiagnosticsMeta as c,runCmdSync as m,withDiagnosticTimer as g,resolveDaemonTransportPreference as f,emitDiagnostic as h,SETTINGS_USAGE_OVERRIDE as y,asAppError as w,spawn as v,pathToFileURL as b,AppError as A,node_fs as D,withDiagnosticsScope as k,node_net as I,flushDiagnosticsToSessionFile as S,resolveDaemonServerMode as $,resolveDaemonPaths as E,stopProcessForTakeover as L,formatSnapshotLine as x}from"./678.js";let _=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],T=["snapshotDepth","snapshotScope","snapshotRaw"],O=[{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:"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:"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:"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:"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"}],N=new Set(["json","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),F={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:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[..._]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[..._]},"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},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:[...T]},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",...T]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...T]},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",...T]},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:[...T]},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:[...T]},settings:{usageOverride:y,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}},M=new Map,P=new Map;for(let e of O){for(let t of e.names)M.set(t,e);let t=P.get(e.key);t?t.push(e):P.set(e.key,[e])}function R(e){if(e)return F[e]}function C(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function U(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(C),...t.allowedFlags.flatMap(e=>(P.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{styleText as e}from"node:util";import t from"node:https";import{node_http as s,node_path as a,buildSnapshotDisplayLines as r,createRequestId as o,parseBatchStepsJson as n,normalizeError as i,isAgentDeviceDaemonProcess as l,runCmdDetached as d,readVersion as p,findProjectRoot as u,getDiagnosticsMeta as c,runCmdSync as m,withDiagnosticTimer as g,resolveDaemonTransportPreference as f,emitDiagnostic as h,SETTINGS_USAGE_OVERRIDE as y,asAppError as w,spawn as v,pathToFileURL as b,AppError as A,node_fs as I,withDiagnosticsScope as D,node_net as k,flushDiagnosticsToSessionFile as $,resolveDaemonServerMode as S,resolveDaemonPaths as E,stopProcessForTakeover as L,formatSnapshotLine as x}from"./678.js";let _=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],O=["snapshotDepth","snapshotScope","snapshotRaw"],P=[{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:"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:"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:"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"}],T=new Set(["json","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),N={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:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[..._]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[..._]},"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:[...O]},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",...O]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...O]},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",...O]},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:[...O]},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:[...O]},settings:{usageOverride:y,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}},M=new Map,F=new Map;for(let e of P){for(let t of e.names)M.set(t,e);let t=F.get(e.key);t?t.push(e):F.set(e.key,[e])}function R(e){if(e)return N[e]}function C(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function U(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(C),...t.allowedFlags.flatMap(e=>(F.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let j=function(){let e=`agent-device <command> [args] [--json]
|
|
2
2
|
|
|
3
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=Object.keys(
|
|
4
|
+
`,t=Object.keys(N).map(e=>{let t=N[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:U(e,t)}}),s=Math.max(...t.map(e=>e.usage.length))+2,a=["Commands:"];for(let e of t)a.push(` ${e.usage.padEnd(s)}${e.schema.description}`);let r=V("Flags:",P.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
5
|
${a.join("\n")}
|
|
6
6
|
|
|
7
7
|
${r}
|
|
8
|
-
`}();function
|
|
8
|
+
`}();function q(e){return P.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function V(e,t){if(0===t.length)return`${e}
|
|
9
9
|
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,a=[e];for(let e of t)a.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return a.join("\n")}function G(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function B(e){return e.replace(/^-+/,"")}function J(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?G(e):[e,void 0];return void 0!==M.get(t)}function W(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function z(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
10
|
`)}function H(e,t={}){let s=e instanceof A?i(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 K(e){return"number"==typeof e&&Number.isFinite(e)?e:0}async function X(e){let{localPath:r,baseUrl:o,token:n}=e,i=D.statSync(r).isDirectory(),l=a.basename(r),d=new URL("upload",o.endsWith("/")?o:`${o}/`),p="https:"===d.protocol?t:s,u={"x-artifact-type":i?"app-bundle":"file","x-artifact-filename":l,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,t)=>{let s=p.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},s=>{let a="";s.setEncoding("utf8"),s.on("data",e=>{a+=e}),s.on("end",()=>{clearTimeout(o);try{let s=JSON.parse(a);if(!s.ok||!s.uploadId)return void t(new A("COMMAND_FAILED",`Upload failed: ${a}`));e(s.uploadId)}catch{t(new A("COMMAND_FAILED",`Invalid upload response: ${a}`))}})}),o=setTimeout(()=>{s.destroy(),t(new A("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(o),t(new A("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),i){let e=v("tar",["cf","-","-C",a.dirname(r),a.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),t(new A("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),t(new A("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=D.createReadStream(r);e.pipe(s),e.on("error",e=>{s.destroy(),t(new A("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let Z=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}(),Q=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}(),ee=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function et(e){let t=e.meta?.requestId??o(),s=!!(e.meta?.debug||e.flags?.verbose),a=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,s=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new A("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new A("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,r=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=f(r);if(s&&"socket"===o)throw new A("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:s});let n=$(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===r?"dual":void 0));return{paths:E(t),transportPreference:o,serverMode:n,remoteBaseUrl:s,remoteAuthToken:a}}(e),r=await g("daemon_startup",async()=>await ea(a),{requestId:t,session:e.session}),n=await es(e,r),i={...e,positionals:n.positionals,token:r.token,meta:{requestId:t,debug:s,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,...n.uploadedArtifactId?{uploadedArtifactId:n.uploadedArtifactId}:{}}};return h({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await g("daemon_request",async()=>await eh(r,i,a.transportPreference),{requestId:t,command:e.command})}async function es(e,t){let s=[...e.positionals??[]];if(!eD(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s};let r=s[1];if(r.startsWith("remote:"))return s[1]=r.slice(7),{positionals:s};let o=a.isAbsolute(r)?r:a.resolve(e.meta?.cwd??process.cwd(),r);return D.existsSync(o)?{positionals:s,uploadedArtifactId:await X({localPath:o,baseUrl:t.baseUrl,token:t.token})}:{positionals:s}}async function ea(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await em(t,"http"))return t;throw new A("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 s=el(e.paths.infoPath),r=p(),o=function(e,t=u()){try{let s=D.statSync(e),r=a.relative(t,e)||e;return`${r}:${s.size}:${Math.trunc(s.mtimeMs)}`}catch{return"unknown"}}((t=ef()).useSrc?t.srcPath:t.distPath,t.root),n=!!s&&await em(s,e.transportPreference);if(s&&s.version===r&&s.codeSignature===o&&n)return s;s&&(s.version!==r||s.codeSignature!==o||!n)&&(await ei(s),ec(e.paths.infoPath)),function(e){let t=ep(e);if(!t.hasLock||t.hasInfo)return;let s=ed(e.lockPath);if(!s)return ec(e.lockPath);l(s.pid,s.processStartTime)||ec(e.lockPath)}(e.paths);let i=0;for(let t=1;t<=Q;t+=1){await eg(e);let s=await er(Y,e);if(s)return s;if(await en(e.paths)){i+=1;continue}let a=ep(e.paths);if(!(t<Q))break;if(!a.hasInfo&&!a.hasLock){await eo(150);continue}}let d=ep(e.paths);throw new A("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:Y,startupAttempts:Q,lockRecoveryCount:i,metadataState:d,hint:function(e,t=E(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(d,e.paths)})}async function er(e,t){let s=Date.now();for(;Date.now()-s<e;){let e=el(t.paths.infoPath);if(e&&await em(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function eo(e){await new Promise(t=>setTimeout(t,e))}async function en(e){let t=ep(e);if(!t.hasLock||t.hasInfo)return!1;let s=ed(e.lockPath);return s&&l(s.pid,s.processStartTime)&&await L(s.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:s.processStartTime}),ec(e.lockPath),!0}async function ei(e){await L(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function el(e){let t=eu(e);if(!t||"string"!=typeof t.token||0===t.token.length)return null;let s=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;return s||a?{...t,port:s?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,pid:Number.isInteger(t.pid)&&t.pid>0?t.pid:0}:null}function ed(e){let t=eu(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function ep(e){return{hasInfo:D.existsSync(e.infoPath),hasLock:D.existsSync(e.lockPath)}}function eu(e){if(!D.existsSync(e))return null;try{return JSON.parse(D.readFileSync(e,"utf8"))}catch{return null}}function ec(e){try{D.existsSync(e)&&D.unlinkSync(e)}catch{}}async function em(e,a){var r;return"http"===ey(e,a)?await function(e){let a=e.baseUrl?ek(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!a)return Promise.resolve(!1);let r=new URL(a),o="https:"===r.protocol?t:s,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=o.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 eg(e){let t=ef(),s=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],a={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};d(process.execPath,s,{env:a})}function ef(){let e=u(),t=a.join(e,"dist","src","daemon.js"),s=a.join(e,"src","daemon.ts"),r=D.existsSync(t),o=D.existsSync(s);if(!r&&!o)throw new A("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:s});return{root:e,distPath:t,srcPath:s,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!r&&o}}async function eh(e,t,s){return"http"===ey(e,s)?await ev(e,t):await ew(e,t)}function ey(e,t){if(e.baseUrl){if("socket"===t)throw new A("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t){if(!e.httpPort)throw new A("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");return"http"}if("socket"===t){if(!e.port)throw new A("COMMAND_FAILED","Daemon socket endpoint is unavailable");return"socket"}let s=e.transport;if("http"===s&&e.httpPort)return"http";if(("socket"===s||"dual"===s)&&e.port)return"socket";if(e.httpPort)return"http";if(e.port)return"socket";throw new A("COMMAND_FAILED","Daemon metadata has no reachable transport")}async function ew(e,t){let s=e.port;if(!s)throw new A("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,r)=>{let o=I.createConnection({host:"127.0.0.1",port:s},()=>{o.write(`${JSON.stringify(t)}
|
|
16
|
-
`)}),n=setTimeout(()=>{o.destroy();let s=eb(),a=eA(e,E(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));h({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:Z,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),r(new A("COMMAND_FAILED","Daemon request timed out",{timeoutMs:Z,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},Z),i="";o.setEncoding("utf8"),o.on("data",e=>{let s=(i+=e).indexOf("\n");if(-1===s)return;let l=i.slice(0,s).trim();if(l)try{let e=JSON.parse(l);o.end(),clearTimeout(n),a(e)}catch(e){clearTimeout(n),r(new A("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(n),h({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),r(new A("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 ev(e,a){let r=e.baseUrl?new URL(ek(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!r)throw new A("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:a.meta?.requestId??o(),method:"agent_device.command",params:a}),i={"content-type":"application/json","content-length":Buffer.byteLength(n)};return e.baseUrl&&e.token&&(i.authorization=`Bearer ${e.token}`,i["x-agent-device-token"]=e.token),await new Promise((o,l)=>{let d=E(a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),p=("https:"===r.protocol?t:s).request({protocol:r.protocol,host:r.hostname,port:r.port,method:"POST",path:r.pathname+r.search,headers:i},e=>{let t="";e.setEncoding("utf8"),e.on("data",e=>{t+=e}),e.on("end",()=>{clearTimeout(u);try{let e=JSON.parse(t);if(e.error){let t=e.error.data??{};l(new A(String(t.code??"COMMAND_FAILED"),String(t.message??e.error.message??"Daemon RPC request failed"),{..."object"==typeof t.details&&t.details?t.details:{},hint:"string"==typeof t.hint?t.hint:void 0,diagnosticId:"string"==typeof t.diagnosticId?t.diagnosticId:void 0,logPath:"string"==typeof t.logPath?t.logPath:void 0,requestId:a.meta?.requestId}));return}if(!e.result||"object"!=typeof e.result)return void l(new A("COMMAND_FAILED","Invalid daemon RPC response",{requestId:a.meta?.requestId}));o(e.result)}catch(e){clearTimeout(u),l(new A("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:t},e instanceof Error?e:void 0))}})}),u=setTimeout(()=>{p.destroy();let t=eD(e)?{terminated:0}:eb(),s=eD(e)?{forcedKill:!1}:eA(e,d);h({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:Z,requestId:a.meta?.requestId,command:a.command,timedOutRunnerPidsTerminated:t.terminated,timedOutRunnerCleanupError:t.error,daemonPidReset:eD(e)?void 0:e.pid,daemonPidForceKilled:eD(e)?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),l(new A("COMMAND_FAILED","Daemon request timed out",{timeoutMs:Z,requestId:a.meta?.requestId,hint:eD(e)?"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."}))},Z);p.on("error",t=>{clearTimeout(u),h({level:"error",phase:"daemon_request_socket_error",data:{requestId:a.meta?.requestId,message:t instanceof Error?t.message:String(t)}}),l(new A("COMMAND_FAILED","Failed to communicate with daemon",{requestId:a.meta?.requestId,hint:eD(e)?"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."},t))}),p.write(n),p.end()})}function eb(){let e=0;try{for(let t of ee){let s=m("pkill",["-f",t],{allowFailure:!0});0===s.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function eA(e,t){let s=!1;try{l(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),s=!0)}catch{L(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{ec(t.infoPath),ec(t.lockPath)}return{forcedKill:s}}function eD(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function ek(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}let eI={sendToDaemon:et};async function eS(t,s=eI){let a=o(),l=t.includes("--debug")||t.includes("--verbose")||t.includes("-v"),d=t.includes("--json"),u=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}(t)??process.env.AGENT_DEVICE_SESSION??"default";await k({session:u,requestId:a,command:t[0],debug:l},async()=>{var o,u;let m;try{m=function(e,t){let s=(void 0)??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),a={json:!1,help:!1,version:!1},r=null,o=[],n=[],i=[],l=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(l&&"--"===s){l=!1;continue}if(!l){r?o.push(s):r=W(s);continue}let n=s.startsWith("--"),d=s.startsWith("-")&&s.length>1;if(!n&&!d){r?o.push(s):r=W(s);continue}let[p,u]=n?G(s):[s,void 0],c=M.get(p);if(!c){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let r=R(e);return!r||!!r.allowsExtraPositionals||0!==r.positionalArgs.length&&(t.length<r.positionalArgs.length||r.positionalArgs.some(e=>e.includes("?")))}(r,o,s)){r?o.push(s):r=s;continue}throw new A("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new A("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 A("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 A("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||J(a)||!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("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let r=s??a;if(void 0===r||void 0===s&&J(r))throw new A("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:r,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(r))throw new A("INVALID_ARGS",`Invalid ${B(t)}: ${r}`);return{value:r,consumeNext:void 0===s}}let o=Number(r);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new A("INVALID_ARGS",`Invalid ${B(t)}: ${r}`);return{value:Math.floor(o),consumeNext:void 0===s}}(c,p,u,e[t+1]);m.consumeNext&&(t+=1),a[c.key]=m.value,i.push({key:c.key,token:p})}let d=R(r),p=new Set([...N,...d?.allowedFlags??[]]),u=i.filter(e=>!p.has(e.key));if(u.length>0){var c,m;let e=(c=r,m=u.map(e=>e.token),c?1===m.length?`Flag ${m[0]} is not supported for command ${c}.`:`Flags ${m.join(", ")} are not supported for command ${c}.`:1===m.length?`Flag ${m[0]} requires a command that supports it.`:`Flags ${m.join(", ")} require a command that supports them.`);if(s)throw new A("INVALID_ARGS",e);for(let t of(n.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),u))delete a[t.key]}if(d?.defaults)for(let[e,t]of Object.entries(d.defaults))void 0===a[e]&&(a[e]=t);if("batch"===r&&1!=+!!a.steps+ +!!a.stepsFile)throw new A("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:r,positionals:o,flags:a,warnings:n}}(t)}catch(t){h({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=i(t,{diagnosticId:c().diagnosticId,logPath:S({force:!0})??void 0});d?z({success:!1,error:e}):H(e,{showDetails:l}),process.exit(1);return}for(let e of m.warnings)process.stderr.write(`Warning: ${e}
|
|
15
|
+
`)}function K(e){return"number"==typeof e&&Number.isFinite(e)?e:0}async function X(e){let{localPath:r,baseUrl:o,token:n}=e,i=I.statSync(r).isDirectory(),l=a.basename(r),d=new URL("upload",o.endsWith("/")?o:`${o}/`),p="https:"===d.protocol?t:s,u={"x-artifact-type":i?"app-bundle":"file","x-artifact-filename":l,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,t)=>{let s=p.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},s=>{let a="";s.setEncoding("utf8"),s.on("data",e=>{a+=e}),s.on("end",()=>{clearTimeout(o);try{let s=JSON.parse(a);if(!s.ok||!s.uploadId)return void t(new A("COMMAND_FAILED",`Upload failed: ${a}`));e(s.uploadId)}catch{t(new A("COMMAND_FAILED",`Invalid upload response: ${a}`))}})}),o=setTimeout(()=>{s.destroy(),t(new A("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(o),t(new A("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),i){let e=v("tar",["cf","-","-C",a.dirname(r),a.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),t(new A("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),t(new A("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=I.createReadStream(r);e.pipe(s),e.on("error",e=>{s.destroy(),t(new A("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let Z=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}(),Q=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}(),ee=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function et(e){let t=e.meta?.requestId??o(),s=!!(e.meta?.debug||e.flags?.verbose),a=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,s=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new A("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new A("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,r=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=f(r);if(s&&"socket"===o)throw new A("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:s});let n=S(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===r?"dual":void 0));return{paths:E(t),transportPreference:o,serverMode:n,remoteBaseUrl:s,remoteAuthToken:a}}(e),r=await g("daemon_startup",async()=>await eo(a),{requestId:t,session:e.session}),n=await es(e,r),i={...e,positionals:n.positionals,flags:n.flags,token:r.token,meta:{requestId:t,debug:s,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation,...n.uploadedArtifactId?{uploadedArtifactId:n.uploadedArtifactId}:{},...n.clientArtifactPaths?{clientArtifactPaths:n.clientArtifactPaths}:{}}};return h({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await g("daemon_request",async()=>await ew(r,i,a.transportPreference),{requestId:t,command:e.command})}async function es(e,t){let s=[...e.positionals??[]],r=e.flags?{...e.flags}:void 0,o={};if(ek(t)){let t=function(e,t){if("screenshot"===e.command){let s=ea(e,"path",".png");return t[0]?{field:"path",localPath:s,positionalIndex:0,positionalPath:er("screenshot",".png")}:{field:"path",localPath:s,positionalIndex:0,flagPath:er("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=ea(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:er("recording",a.extname(t)||".mp4")}}return null}(e,s);t&&(void 0!==t.positionalPath&&(s[t.positionalIndex]=t.positionalPath),void 0!==t.flagPath&&((r??={}).out=t.flagPath),o[t.field]=t.localPath)}if(!ek(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s,flags:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let n=s[1];if(n.startsWith("remote:"))return s[1]=n.slice(7),{positionals:s,flags:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let i=a.isAbsolute(n)?n:a.resolve(e.meta?.cwd??process.cwd(),n);return I.existsSync(i)?{positionals:s,flags:r,uploadedArtifactId:await X({localPath:i,baseUrl:t.baseUrl,token:t.token}),...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}:{positionals:s,flags:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}}function ea(e,t,s,r=0){let o=e.positionals?.[r]??e.flags?.out,n=`${"path"===t?"screenshot":"recording"}-${Date.now()}${s}`,i=o&&o.trim().length>0?o:n;return a.isAbsolute(i)?i:a.resolve(e.meta?.cwd??process.cwd(),i)}function er(e,t){let s=t.startsWith(".")?t:`.${t}`;return a.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${s}`)}async function eo(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await ef(t,"http"))return t;throw new A("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 s=ep(e.paths.infoPath),r=p(),o=function(e,t=u()){try{let s=I.statSync(e),r=a.relative(t,e)||e;return`${r}:${s.size}:${Math.trunc(s.mtimeMs)}`}catch{return"unknown"}}((t=ey()).useSrc?t.srcPath:t.distPath,t.root),n=!!s&&await ef(s,e.transportPreference);if(s&&s.version===r&&s.codeSignature===o&&n)return s;s&&(s.version!==r||s.codeSignature!==o||!n)&&(await ed(s),eg(e.paths.infoPath)),function(e){let t=ec(e);if(!t.hasLock||t.hasInfo)return;let s=eu(e.lockPath);if(!s)return eg(e.lockPath);l(s.pid,s.processStartTime)||eg(e.lockPath)}(e.paths);let i=0;for(let t=1;t<=Q;t+=1){await eh(e);let s=await en(Y,e);if(s)return s;if(await el(e.paths)){i+=1;continue}let a=ec(e.paths);if(!(t<Q))break;if(!a.hasInfo&&!a.hasLock){await ei(150);continue}}let d=ec(e.paths);throw new A("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:Y,startupAttempts:Q,lockRecoveryCount:i,metadataState:d,hint:function(e,t=E(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(d,e.paths)})}async function en(e,t){let s=Date.now();for(;Date.now()-s<e;){let e=ep(t.paths.infoPath);if(e&&await ef(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function ei(e){await new Promise(t=>setTimeout(t,e))}async function el(e){let t=ec(e);if(!t.hasLock||t.hasInfo)return!1;let s=eu(e.lockPath);return s&&l(s.pid,s.processStartTime)&&await L(s.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:s.processStartTime}),eg(e.lockPath),!0}async function ed(e){await L(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function ep(e){let t=em(e);if(!t||"string"!=typeof t.token||0===t.token.length)return null;let s=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;return s||a?{...t,port:s?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,pid:Number.isInteger(t.pid)&&t.pid>0?t.pid:0}:null}function eu(e){let t=em(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function ec(e){return{hasInfo:I.existsSync(e.infoPath),hasLock:I.existsSync(e.lockPath)}}function em(e){if(!I.existsSync(e))return null;try{return JSON.parse(I.readFileSync(e,"utf8"))}catch{return null}}function eg(e){try{I.existsSync(e)&&I.unlinkSync(e)}catch{}}async function ef(e,a){var r;return"http"===ev(e,a)?await function(e){let a=e.baseUrl?e$(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!a)return Promise.resolve(!1);let r=new URL(a),o="https:"===r.protocol?t:s,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=o.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=k.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function eh(e){let t=ey(),s=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],a={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};d(process.execPath,s,{env:a})}function ey(){let e=u(),t=a.join(e,"dist","src","daemon.js"),s=a.join(e,"src","daemon.ts"),r=I.existsSync(t),o=I.existsSync(s);if(!r&&!o)throw new A("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:s});return{root:e,distPath:t,srcPath:s,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!r&&o}}async function ew(e,t,s){return"http"===ev(e,s)?await eA(e,t):await eb(e,t)}function ev(e,t){if(e.baseUrl){if("socket"===t)throw new A("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t){if(!e.httpPort)throw new A("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");return"http"}if("socket"===t){if(!e.port)throw new A("COMMAND_FAILED","Daemon socket endpoint is unavailable");return"socket"}let s=e.transport;if("http"===s&&e.httpPort)return"http";if(("socket"===s||"dual"===s)&&e.port)return"socket";if(e.httpPort)return"http";if(e.port)return"socket";throw new A("COMMAND_FAILED","Daemon metadata has no reachable transport")}async function eb(e,t){let s=e.port;if(!s)throw new A("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,r)=>{let o=k.createConnection({host:"127.0.0.1",port:s},()=>{o.write(`${JSON.stringify(t)}
|
|
16
|
+
`)}),n=setTimeout(()=>{o.destroy();let s=eI(),a=eD(e,E(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));h({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:Z,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),r(new A("COMMAND_FAILED","Daemon request timed out",{timeoutMs:Z,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},Z),i="";o.setEncoding("utf8"),o.on("data",e=>{let s=(i+=e).indexOf("\n");if(-1===s)return;let l=i.slice(0,s).trim();if(l)try{let e=JSON.parse(l);o.end(),clearTimeout(n),a(e)}catch(e){clearTimeout(n),r(new A("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(n),h({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),r(new A("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 eA(e,a){let r=e.baseUrl?new URL(e$(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!r)throw new A("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:a.meta?.requestId??o(),method:"agent_device.command",params:a}),i={"content-type":"application/json","content-length":Buffer.byteLength(n)};return e.baseUrl&&e.token&&(i.authorization=`Bearer ${e.token}`,i["x-agent-device-token"]=e.token),await new Promise((o,l)=>{let d=E(a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),p=("https:"===r.protocol?t:s).request({protocol:r.protocol,host:r.hostname,port:r.port,method:"POST",path:r.pathname+r.search,headers:i},t=>{let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{clearTimeout(u);try{let t=JSON.parse(s);if(t.error){let e=t.error.data??{};l(new A(String(e.code??"COMMAND_FAILED"),String(e.message??t.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:a.meta?.requestId}));return}if(!t.result||"object"!=typeof t.result)return void l(new A("COMMAND_FAILED","Invalid daemon RPC response",{requestId:a.meta?.requestId}));if(e.baseUrl&&t.result.ok)return void eS(e,a,t.result).then(o).catch(l);o(t.result)}catch(e){clearTimeout(u),l(new A("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:s},e instanceof Error?e:void 0))}})}),u=setTimeout(()=>{p.destroy();let t=ek(e)?{terminated:0}:eI(),s=ek(e)?{forcedKill:!1}:eD(e,d);h({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:Z,requestId:a.meta?.requestId,command:a.command,timedOutRunnerPidsTerminated:t.terminated,timedOutRunnerCleanupError:t.error,daemonPidReset:ek(e)?void 0:e.pid,daemonPidForceKilled:ek(e)?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),l(new A("COMMAND_FAILED","Daemon request timed out",{timeoutMs:Z,requestId:a.meta?.requestId,hint:ek(e)?"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."}))},Z);p.on("error",t=>{clearTimeout(u),h({level:"error",phase:"daemon_request_socket_error",data:{requestId:a.meta?.requestId,message:t instanceof Error?t.message:String(t)}}),l(new A("COMMAND_FAILED","Failed to communicate with daemon",{requestId:a.meta?.requestId,hint:ek(e)?"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."},t))}),p.write(n),p.end()})}function eI(){let e=0;try{for(let t of ee){let s=m("pkill",["-f",t],{allowFailure:!0});0===s.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function eD(e,t){let s=!1;try{l(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),s=!0)}catch{L(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{eg(t.infoPath),eg(t.lockPath)}return{forcedKill:s}}function ek(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function e$(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function eS(e,t,s){let r=Array.isArray(s.data?.artifacts)?s.data.artifacts:[];if(0===r.length||!e.baseUrl)return s;let o=s.data?{...s.data}:{},n=[];for(let s of r){if(!s||"object"!=typeof s||"string"!=typeof s.artifactId){n.push(s);continue}let r=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let s=e.fileName?.trim()||`${e.field}-${Date.now()}`;return a.resolve(t.meta?.cwd??process.cwd(),s)}(s,t);await eE({baseUrl:e.baseUrl,token:e.token,artifactId:s.artifactId,destinationPath:r,requestId:t.meta?.requestId}),o[s.field]=r,n.push({...s,localPath:r})}return o.artifacts=n,{ok:!0,data:o}}async function eE(e){var r,o;let n,i=new URL((r=e.baseUrl,o=e.artifactId,n=r.endsWith("/")?r:`${r}/`,new URL(`artifacts/${encodeURIComponent(o)}`,n).toString())),l="https:"===i.protocol?t:s;await I.promises.mkdir(a.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,s)=>{let a=!1,r=e.timeoutMs??Z,o=r=>{if(!a){if(a=!0,clearTimeout(d),r)return void I.promises.rm(e.destinationPath,{force:!0}).finally(()=>s(r));t()}},n=l.request({protocol:i.protocol,host:i.hostname,port:i.port,method:"GET",path:i.pathname+i.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{o(new A("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:s}))});return}let s=I.createWriteStream(e.destinationPath);s.on("error",e=>{o(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{o(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{o(new A("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),s.on("finish",()=>{s.close(()=>o())}),t.pipe(s)}),d=setTimeout(()=>{n.destroy(new A("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:r}))},r);n.on("error",t=>{t instanceof A?o(t):o(new A("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:r},t instanceof Error?t:void 0))}),n.end()})}let eL={sendToDaemon:et};async function ex(t,s=eL){let a=o(),l=t.includes("--debug")||t.includes("--verbose")||t.includes("-v"),d=t.includes("--json"),u=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}(t)??process.env.AGENT_DEVICE_SESSION??"default";await D({session:u,requestId:a,command:t[0],debug:l},async()=>{var o,u;let m;try{m=function(e,t){let s=(void 0)??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),a={json:!1,help:!1,version:!1},r=null,o=[],n=[],i=[],l=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(l&&"--"===s){l=!1;continue}if(!l){r?o.push(s):r=W(s);continue}let n=s.startsWith("--"),d=s.startsWith("-")&&s.length>1;if(!n&&!d){r?o.push(s):r=W(s);continue}let[p,u]=n?G(s):[s,void 0],c=M.get(p);if(!c){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let r=R(e);return!r||!!r.allowsExtraPositionals||0!==r.positionalArgs.length&&(t.length<r.positionalArgs.length||r.positionalArgs.some(e=>e.includes("?")))}(r,o,s)){r?o.push(s):r=s;continue}throw new A("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new A("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 A("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 A("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||J(a)||!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("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let r=s??a;if(void 0===r||void 0===s&&J(r))throw new A("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:r,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(r))throw new A("INVALID_ARGS",`Invalid ${B(t)}: ${r}`);return{value:r,consumeNext:void 0===s}}let o=Number(r);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new A("INVALID_ARGS",`Invalid ${B(t)}: ${r}`);return{value:Math.floor(o),consumeNext:void 0===s}}(c,p,u,e[t+1]);m.consumeNext&&(t+=1),a[c.key]=m.value,i.push({key:c.key,token:p})}let d=R(r),p=new Set([...T,...d?.allowedFlags??[]]),u=i.filter(e=>!p.has(e.key));if(u.length>0){var c,m;let e=(c=r,m=u.map(e=>e.token),c?1===m.length?`Flag ${m[0]} is not supported for command ${c}.`:`Flags ${m.join(", ")} are not supported for command ${c}.`:1===m.length?`Flag ${m[0]} requires a command that supports it.`:`Flags ${m.join(", ")} require a command that supports them.`);if(s)throw new A("INVALID_ARGS",e);for(let t of(n.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),u))delete a[t.key]}if(d?.defaults)for(let[e,t]of Object.entries(d.defaults))void 0===a[e]&&(a[e]=t);if("batch"===r&&1!=+!!a.steps+ +!!a.stepsFile)throw new A("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:r,positionals:o,flags:a,warnings:n}}(t)}catch(t){h({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=i(t,{diagnosticId:c().diagnosticId,logPath:$({force:!0})??void 0});d?z({success:!1,error:e}):H(e,{showDetails:l}),process.exit(1);return}for(let e of m.warnings)process.stderr.write(`Warning: ${e}
|
|
17
17
|
`);m.flags.version&&(process.stdout.write(`${p()}
|
|
18
18
|
`),process.exit(0));let g="help"===m.command,f=m.flags.help;if(g||f){g&&m.positionals.length>1&&(H(new A("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=g?m.positionals[0]:m.command;e||(process.stdout.write(`${j}
|
|
19
|
-
`),process.exit(0));let t=function(e){let t=R(e);if(!t)return null;let s=U(e,t),a=
|
|
19
|
+
`),process.exit(0));let t=function(e){let t=R(e);if(!t)return null;let s=U(e,t),a=q(new Set(t.allowedFlags)),r=q(T),o=[];return a.length>0&&o.push(V("Command flags:",a)),o.push(V("Global flags:",r)),`agent-device ${s}
|
|
20
20
|
|
|
21
21
|
${t.description}
|
|
22
22
|
|
|
@@ -26,9 +26,9 @@ Usage:
|
|
|
26
26
|
${o.join("\n\n")}
|
|
27
27
|
`}(W(e));t&&(process.stdout.write(t),process.exit(0)),H(new A("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${j}
|
|
28
28
|
`),process.exit(1)}m.command||(process.stdout.write(`${j}
|
|
29
|
-
`),process.exit(1));let{command:y,positionals:v,flags:b}=m,
|
|
30
|
-
`)),_&&_();return}if("session"===y){let e=v[0]??"list";if("list"!==e)throw new A("INVALID_ARGS","session only supports list");let t=await
|
|
31
|
-
`),_&&_();return}let t=await
|
|
29
|
+
`),process.exit(1));let{command:y,positionals:v,flags:b}=m,D=function(e){let{json:t,help:s,version:a,...r}=e;return r}(b),k=E(b.stateDir??process.env.AGENT_DEVICE_STATE_DIR),S=b.session??process.env.AGENT_DEVICE_SESSION??"default",L=b.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL,_=!b.verbose||b.json||L?null:function(e){try{let t=0,s=!1,a=setInterval(()=>{if(!s&&I.existsSync(e))try{let s=I.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let a=I.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);I.readSync(a,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{I.closeSync(a)}}catch{}},200);return()=>{s=!0,clearInterval(a)}}catch{return null}}(k.logPath),O=async e=>await s.sendToDaemon({session:S,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:a,debug:!!b.verbose,cwd:process.cwd(),tenantId:b.tenant,runId:b.runId,leaseId:b.leaseId,sessionIsolation:b.sessionIsolation}});try{if("batch"===y){let e,t,s;if(v.length>0)throw new A("INVALID_ARGS","batch does not accept positional arguments.");let a=function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=I.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new A("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return n(t)}(b),r={...D,batchSteps:a};delete r.steps,delete r.stepsFile;let i=await O({command:"batch",positionals:v,flags:r});if(!i.ok)throw new A(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});b.json?z({success:!0,data:i.data??{}}):(o=i.data??{},e="number"==typeof o.total?o.total:0,t="number"==typeof o.executed?o.executed:0,s="number"==typeof o.totalDurationMs?o.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${t}/${e} steps${void 0!==s?` in ${s}ms`:""}
|
|
30
|
+
`)),_&&_();return}if("session"===y){let e=v[0]??"list";if("list"!==e)throw new A("INVALID_ARGS","session only supports list");let t=await O({command:"session_list",positionals:[],flags:D});if(!t.ok)throw new A(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath});b.json?z({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
31
|
+
`),_&&_();return}let t=await O({command:y,positionals:v,flags:D});if(t.ok){if(b.json){z({success:!0,data:t.data??{}}),_&&_();return}if("snapshot"===y){process.stdout.write(function(e,t={}){let s=e.nodes,a=Array.isArray(s)?s:[],o=!!e.truncated,n="string"==typeof e.appName?e.appName:void 0,i="string"==typeof e.appBundleId?e.appBundleId:void 0,l=[];n&&l.push(`Page: ${n}`),i&&l.push(`App: ${i}`);let d=`Snapshot: ${a.length} nodes${o?" (truncated)":""}`,p=l.length>0?`${l.join("\n")}
|
|
32
32
|
`:"";if(0===a.length)return`${p}${d}
|
|
33
33
|
`;if(t.raw){let e=a.map(e=>JSON.stringify(e));return`${p}${d}
|
|
34
34
|
${e.join("\n")}
|
|
@@ -49,6 +49,9 @@ ${u.join("\n")}
|
|
|
49
49
|
`),_&&_();return}if("boot"===y){let e=t.data?.platform??"unknown",s=t.data?.device??t.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${e})
|
|
50
50
|
`),_&&_();return}if("ensure-simulator"===y){let e=t.data,s="string"==typeof e?.udid?e.udid:"unknown",a="string"==typeof e?.device?e.device:"unknown",r="string"==typeof e?.runtime?e.runtime:"",o=e?.created===!0,n=e?.booted===!0;process.stdout.write(`${o?"Created":"Reused"}: ${a} ${s}${n?" (booted)":""}
|
|
51
51
|
`),r&&process.stdout.write(`Runtime: ${r}
|
|
52
|
+
`),_&&_();return}if("runtime"===y){let e=t.data,s=e?.cleared===!0,a=e?.configured===!0;if(s){process.stdout.write("Runtime hints cleared\n"),_&&_();return}if(!a){process.stdout.write("No runtime hints configured\n"),_&&_();return}process.stdout.write(`${JSON.stringify(e?.runtime??{},null,2)}
|
|
53
|
+
`),_&&_();return}if("screenshot"===y){let e="string"==typeof t.data?.path?t.data.path:"";e&&process.stdout.write(`${e}
|
|
54
|
+
`),_&&_();return}if("record"===y){let e=t.data,s="string"==typeof e?.outPath?e.outPath:"";s&&process.stdout.write(`${s}
|
|
52
55
|
`),_&&_();return}if("logs"===y){let e=t.data,s="string"==typeof e?.path?e.path:"";if(s){process.stdout.write(`${s}
|
|
53
56
|
`);let t="boolean"==typeof e?.active?e.active:void 0,a="string"==typeof e?.state?e.state:void 0,r="string"==typeof e?.backend?e.backend:void 0,o="number"==typeof e?.sizeBytes?e.sizeBytes:void 0,n=e?.started===!0,i=e?.stopped===!0,l=e?.marked===!0,d=e?.cleared===!0,p=e?.restarted===!0,u="number"==typeof e?.removedRotatedFiles?e.removedRotatedFiles:void 0;if(!b.json&&(void 0!==t||a||r||void 0!==o)){let e=[void 0!==t?`active=${t}`:"",a?`state=${a}`:"",r?`backend=${r}`:"",void 0!==o?`sizeBytes=${o}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
54
57
|
`)}if(!b.json&&(n||i||l||d||p||void 0!==u)){let e=[n?"started=true":"",i?"stopped=true":"",l?"marked=true":"",d?"cleared=true":"",p?"restarted=true":"",void 0!==u?`removedRotatedFiles=${u}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
@@ -71,7 +74,7 @@ ${u.join("\n")}
|
|
|
71
74
|
`),_&&_();return}if("android"===t){process.stdout.write(`Foreground app: ${o??"unknown"}
|
|
72
75
|
`),n&&process.stdout.write(`Activity: ${n}
|
|
73
76
|
`),_&&_();return}}if("perf"===y){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
74
|
-
`),_&&_();return}}_&&_();return}throw new A(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath})}catch(s){let e=w(s),t=i(e,{diagnosticId:c().diagnosticId,logPath
|
|
77
|
+
`),_&&_();return}}_&&_();return}throw new A(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath})}catch(s){let e=w(s),t=i(e,{diagnosticId:c().diagnosticId,logPath:$({force:!0})??void 0});if("close"===y&&"COMMAND_FAILED"===(u=e).code&&(u.details?.kind==="daemon_startup_failed"||u.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof u.details?.infoPath||"string"==typeof u.details?.lockPath))){b.json&&z({success:!0,data:{closed:"session",source:"no-daemon"}}),_&&_();return}if(b.json)z({success:!1,error:t});else if(H(t,{showDetails:b.verbose}),b.verbose)try{let e=k.logPath;if(I.existsSync(e)){let t=I.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
75
78
|
[daemon log]
|
|
76
79
|
${s}
|
|
77
|
-
`)}}catch{}_&&_(),process.exit(1)}})}b(process.argv[1]??"").href===import.meta.url&&
|
|
80
|
+
`)}}catch{}_&&_(),process.exit(1)}})}b(process.argv[1]??"").href===import.meta.url&&ex(process.argv.slice(2)).catch(e=>{H(i(w(e)),{showDetails:!0}),process.exit(1)}),ex(process.argv.slice(2));
|