agent-device 0.10.1 → 0.10.2
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 +4 -1
- package/dist/src/331.js +3 -3
- package/dist/src/425.js +1 -0
- package/dist/src/bin.js +28 -28
- package/dist/src/core/dispatch.d.ts +2 -0
- package/dist/src/core/session-surface.d.ts +3 -0
- package/dist/src/core/settings-contract.d.ts +2 -1
- package/dist/src/daemon/app-log-ios.d.ts +2 -1
- package/dist/src/daemon/app-log-process.d.ts +1 -1
- package/dist/src/daemon/app-log.d.ts +1 -1
- package/dist/src/daemon/context.d.ts +2 -0
- package/dist/src/daemon/handlers/interaction-common.d.ts +30 -1
- package/dist/src/daemon/handlers/interaction-read.d.ts +14 -0
- package/dist/src/daemon/handlers/interaction-touch.d.ts +2 -3
- package/dist/src/daemon/handlers/interaction.d.ts +5 -12
- package/dist/src/daemon/handlers/snapshot-capture.d.ts +11 -4
- package/dist/src/daemon/snapshot-processing.d.ts +1 -0
- package/dist/src/daemon/types.d.ts +3 -1
- package/dist/src/daemon.js +39 -39
- package/dist/src/platforms/android/index.d.ts +1 -1
- package/dist/src/platforms/android/input-actions.d.ts +1 -0
- package/dist/src/platforms/android/settings.d.ts +1 -1
- package/dist/src/platforms/ios/apps.d.ts +1 -1
- package/dist/src/platforms/ios/macos-helper.d.ts +69 -0
- package/dist/src/platforms/ios/runner-client.d.ts +1 -1
- package/dist/src/utils/command-schema.d.ts +1 -0
- package/dist/src/utils/interactors.d.ts +1 -1
- package/dist/src/utils/snapshot-lines.d.ts +5 -2
- package/dist/src/utils/snapshot.d.ts +8 -1
- package/dist/src/utils/text-surface.d.ts +19 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +8 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +60 -0
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +1 -1
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +4 -0
- package/macos-helper/Package.swift +18 -0
- package/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +543 -0
- package/macos-helper/Sources/AgentDeviceMacOSHelper/main.swift +545 -0
- package/package.json +4 -1
- package/skills/agent-device/SKILL.md +25 -334
- package/skills/agent-device/references/bootstrap-install.md +167 -0
- package/skills/agent-device/references/coordinate-system.md +24 -4
- package/skills/agent-device/references/debugging.md +115 -0
- package/skills/agent-device/references/exploration.md +193 -0
- package/skills/agent-device/references/macos-desktop.md +55 -57
- package/skills/agent-device/references/remote-tenancy.md +56 -47
- package/skills/agent-device/references/verification.md +103 -0
- package/dist/src/274.js +0 -1
- package/dist/src/daemon/handlers/interaction-fill.d.ts +0 -3
- package/dist/src/daemon/handlers/interaction-press.d.ts +0 -3
- package/skills/agent-device/references/batching.md +0 -79
- package/skills/agent-device/references/logs-and-debug.md +0 -113
- package/skills/agent-device/references/perf-metrics.md +0 -53
- package/skills/agent-device/references/permissions.md +0 -70
- package/skills/agent-device/references/session-management.md +0 -101
- package/skills/agent-device/references/snapshot-refs.md +0 -102
- package/skills/agent-device/references/video-recording.md +0 -49
package/README.md
CHANGED
|
@@ -51,7 +51,8 @@ In practice, most work follows the same pattern:
|
|
|
51
51
|
|
|
52
52
|
## Where To Go Next
|
|
53
53
|
|
|
54
|
-
For people:
|
|
54
|
+
For people:
|
|
55
|
+
|
|
55
56
|
- [Website](https://agent-device.dev/)
|
|
56
57
|
- [Docs](https://incubator.callstack.com/agent-device/docs/introduction)
|
|
57
58
|
|
|
@@ -67,6 +68,8 @@ For agents:
|
|
|
67
68
|
npm install -g agent-device
|
|
68
69
|
```
|
|
69
70
|
|
|
71
|
+
On macOS, `agent-device` includes a local `agent-device-macos-helper` source package that is built on demand for desktop permission checks, alert handling, and helper-backed desktop snapshot surfaces. Release distribution should use a signed/notarized helper build; source checkouts fall back to a local Swift build.
|
|
72
|
+
|
|
70
73
|
## Contributing
|
|
71
74
|
|
|
72
75
|
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
package/dist/src/331.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{URL as e,fileURLToPath as t,pathToFileURL as r}from"node:url";import{spawn as n,spawnSync as o}from"node:child_process";import i from"node:os";import s,{promises as
|
|
2
|
-
`;try{t.logPath&&s.appendFile(t.logPath,n,()=>{}),t.traceLogPath&&s.appendFile(t.traceLogPath,n,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(n)}catch{}}async function
|
|
3
|
-
`),t.events=[],a}catch{return null}}function
|
|
1
|
+
import{URL as e,fileURLToPath as t,pathToFileURL as r}from"node:url";import{spawn as n,spawnSync as o}from"node:child_process";import i from"node:os";import s,{existsSync as a,promises as d}from"node:fs";import u from"node:path";import{AsyncLocalStorage as c}from"node:async_hooks";import l,{createHash as f}from"node:crypto";let m=new c,p=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,h=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function g(){return l.randomBytes(8).toString("hex")}async function w(e,t){let r={...e,diagnosticId:`${Date.now().toString(36)}-${l.randomBytes(4).toString("hex")}`,events:[]};return await m.run(r,t)}function S(){let e=m.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function E(e){let t=m.getStore();if(!t)return;let r={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?y(e.data):void 0};if(t.events.push(r),!t.debug)return;let n=`[agent-device][diag] ${JSON.stringify(r)}
|
|
2
|
+
`;try{t.logPath&&s.appendFile(t.logPath,n,()=>{}),t.traceLogPath&&s.appendFile(t.traceLogPath,n,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(n)}catch{}}async function D(e,t,r){let n=Date.now();try{let o=await t();return E({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw E({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function v(e={}){let t=m.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,"_"),r=new Date().toISOString().slice(0,10),n=u.join(i.homedir(),".agent-device","logs",e,r);s.mkdirSync(n,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),a=u.join(n,`${o}-${t.diagnosticId}.ndjson`),d=t.events.map(e=>JSON.stringify(y(e)));return s.writeFileSync(a,`${d.join("\n")}
|
|
3
|
+
`),t.events=[],a}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&&p.test(i)||h.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 s={};for(let[n,o]of Object.entries(t)){if(p.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(e,new WeakSet)}class I extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function M(e){return e instanceof I?e:e instanceof Error?new I("UNKNOWN",e.message,void 0,e):new I("UNKNOWN","Unknown error",{err:e})}function A(e,t={}){let r=M(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,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,a=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),d=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),u=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:u,hint:a,diagnosticId:i,logPath:s,details:d}}async function N(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",d=r.binaryStdout?Buffer.alloc(0):void 0,u="",c=!1,l=L(r.timeoutMs),f=l?setTimeout(()=>{c=!0,s.kill("SIGKILL")},l):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{r.binaryStdout?d=Buffer.concat([d??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{u+=e}),s.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?i(new I("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new I("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{f&&clearTimeout(f);let s=n??1;c&&l?i(new I("COMMAND_FAILED",`${e} timed out after ${l}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,timeoutMs:l})):0===s||r.allowFailure?o({stdout:a,stderr:u,exitCode:s,stdoutBuffer:d}):i(new I("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,processExitError:!0}))})})}async function O(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 N(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function T(e,t,r={}){let n=o(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:L(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new I("COMMAND_FAILED",`${e} timed out after ${L(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:L(r.timeoutMs)},n.error);if("ENOENT"===o)throw new I("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new I("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let i=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),d=n.status??1;if(0!==d&&!r.allowFailure)throw new I("COMMAND_FAILED",`${e} exited with code ${d}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:d,processExitError:!0});return{stdout:s,stderr:a,exitCode:d,stdoutBuffer:i}}function _(e,t,r={}){n(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function P(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(s);let a="",d="",u=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{if(r.binaryStdout){u=Buffer.concat([u??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),s.stderr.on("data",e=>{let t=String(e);d+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{"ENOENT"===r.code?i(new I("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new I("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{let s=n??1;0===s||r.allowFailure?o({stdout:a,stderr:d,exitCode:s,stdoutBuffer:u}):i(new I("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:d,exitCode:s,processExitError:!0}))})})}function C(e,t,r={}){let o=n(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),i="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",e=>{i+=e}),o.stderr.on("data",e=>{s+=e});let a=new Promise((n,a)=>{o.on("error",r=>{"ENOENT"===r.code?a(new I("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):a(new I("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),o.on("close",o=>{let d=o??1;0===d||r.allowFailure?n({stdout:i,stderr:s,exitCode:d}):a(new I("COMMAND_FAILED",`${e} exited with code ${d}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:d,processExitError:!0}))})});return{child:o,wait:a}}function L(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function F(){try{let e=$();return JSON.parse(s.readFileSync(u.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function $(){let e=u.dirname(t(import.meta.url)),r=e;for(let e=0;e<6;e+=1){let e=u.join(r,"package.json");if(s.existsSync(e))return r;r=u.dirname(r)}return e}let b=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function k(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function x(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=T("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 R(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=T("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 j(e,t){let r;if(!k(e))return!1;if(t){let r=x(e);if(!r||r!==t)return!1}let n=R(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&b.some(e=>e.test(r))}function B(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function U(e,t){if(!k(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!k(e))return!0;return!k(e)}async function H(e,t){!j(e,t.expectedStartTime)||!B(e,"SIGTERM")||await U(e,t.termTimeoutMs)||B(e,"SIGKILL")&&await U(e,t.killTimeoutMs)}function G(e){return e?.HOME?.trim()||i.homedir()}function q(e,t={}){return"~"===e?G(t.env):e.startsWith("~/")?u.join(G(t.env),e.slice(2)):e}function z(e,t={}){let r=q(e,t);return u.isAbsolute(r)?r:u.resolve(t.cwd??process.cwd(),r)}function K(e){let t,r=(t=(e??"").trim())?z(t):u.join(q("~"),".agent-device");return{baseDir:r,infoPath:u.join(r,"daemon.json"),lockPath:u.join(r,"daemon.lock"),logPath:u.join(r,"daemon.log"),sessionsDir:u.join(r,"sessions")}}function V(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function W(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function J(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function Z(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}export{default as node_net}from"node:net";export{default as node_http}from"node:http";export{default as node_https}from"node:https";export{I as AppError,M as asAppError,f as createHash,g as createRequestId,E as emitDiagnostic,a as existsSync,q as expandUserHomePath,e as external_node_url_URL,t as fileURLToPath,$ as findProjectRoot,v as flushDiagnosticsToSessionFile,S as getDiagnosticsMeta,j as isAgentDeviceDaemonProcess,k as isProcessAlive,l as node_crypto,s as node_fs,i as node_os,u as node_path,A as normalizeError,Z as normalizeTenantId,r as pathToFileURL,d as promises,R as readProcessCommand,x as readProcessStartTime,F as readVersion,K as resolveDaemonPaths,V as resolveDaemonServerMode,W as resolveDaemonTransportPreference,J as resolveSessionIsolationMode,z as resolveUserPath,N as runCmd,C as runCmdBackground,_ as runCmdDetached,P as runCmdStreaming,T as runCmdSync,n as spawn,H as stopProcessForTakeover,O as whichCmd,D as withDiagnosticTimer,w as withDiagnosticsScope};
|
package/dist/src/425.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppError as e}from"./331.js";let t="<wifi|airplane|location> <on|off>",r="appearance <light|dark|toggle>",i="faceid <match|nonmatch|enroll|unenroll>",a="touchid <match|nonmatch|enroll|unenroll>",n="fingerprint <match|nonmatch>",s="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",l="permission <grant|reset> <accessibility|screen-recording|input-monitoring>",o=`settings ${t} | settings ${r} | settings ${i} | settings ${a} | settings ${n} | settings ${s} | settings ${l}`,c=`settings requires ${t}, ${r}, ${i}, ${a}, ${n}, ${s}, or ${l}`,u=["app","frontmost-app","desktop","menubar"];function d(t){let r=t?.trim().toLowerCase();if("app"===r||"frontmost-app"===r||"desktop"===r||"menubar"===r)return r;throw new e("INVALID_ARGS",`Invalid surface: ${t}. Use ${u.join("|")}.`)}function p(e){var t;let r,i=f(e.label),a=f(e.value),n=f(e.identifier),s=(t=n)&&!/^[\w.]+:id\/[\w.-]+$/i.test(t)&&!/^_?NS:\d+$/i.test(t)?n:"";return(r=m(e.type??"")).includes("textfield")||r.includes("securetextfield")||r.includes("searchfield")||r.includes("edittext")||r.includes("textview")||r.includes("textarea")?a||i||s:i||a||s}function f(e){return"string"==typeof e?e.trim():""}function m(e){let t=e.trim().replace(/XCUIElementType/gi,"").replace(/^AX/,"").toLowerCase(),r=Math.max(t.lastIndexOf("."),t.lastIndexOf("/"));return -1!==r&&(t=t.slice(r+1)),t}function h(e,t={}){let r=[],i=[];for(let a of e){let e=a.depth??0;for(;r.length>0&&e<=r[r.length-1];)r.pop();let n=a.label?.trim()||a.value?.trim()||a.identifier?.trim()||"",s=x(a.type??"Element"),l="group"===s&&!n;l&&r.push(e);let o=l?e:Math.max(0,e-r.length);i.push({node:a,depth:o,type:s,text:w(a,o,l,s,t)})}return i}function w(e,t,r,i,a={}){var n,s,l,o,c;let u,d,h=i??x(e.type??"Element"),$=(u=p(e),{text:u,isLargeSurface:d=function(e,t){if("text-view"===t||"text-field"===t||"search"===t)return!0;let r=m(e.type??""),i=`${e.role??""} ${e.subrole??""}`.toLowerCase();return r.includes("textview")||r.includes("textarea")||r.includes("textfield")||r.includes("securetextfield")||r.includes("searchfield")||r.includes("edittext")||i.includes("text area")||i.includes("text field")}(e,h),shouldSummarize:d&&!!(n=u)&&(n.length>80||/[\r\n]/.test(n))}),A=(s=e,l=h,o=a,c=$,o.summarizeTextSurfaces&&c.shouldSummarize&&function(e,t,r){let i=f(e.label);if(i&&i!==r)return i;let a=f(e.identifier);if(a&&!S(a)&&a!==r)return a;switch(t){case"text":case"text-view":return"Text view";case"text-field":return"Text field";case"search":return"Search field";default:return""}}(s,l,c.text)||g(s,l)),y=" ".repeat(t),v=e.ref?`@${e.ref}`:"",I=(function(e,t,r,i){let a,n=[];if(!1===e.enabled&&n.push("disabled"),!r.summarizeTextSurfaces||(!0===e.selected&&n.push("selected"),b(t)&&n.push("editable"),function(e,t){if("scroll-area"===t)return!0;let r=(e.type??"").toLowerCase(),i=`${e.role??""} ${e.subrole??""}`.toLowerCase();return r.includes("scroll")||i.includes("scroll")}(e,t)&&n.push("scrollable"),!i.shouldSummarize))return n;return n.push(`preview:"${((a=i.text.replace(/\s+/g," ").trim()).length<=48?a:`${a.slice(0,45)}...`).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`),n.push("truncated"),[...new Set(n)]})(e,h,a,$).map(e=>` [${e}]`).join(""),_=A?` "${A}"`:"";return r?`${y}${v} [${h}]${I}`.trimEnd():`${y}${v} [${h}]${_}${I}`.trimEnd()}function g(e,t){let r=e.label?.trim(),i=e.value?.trim();if(b(t)){if(i)return i;if(r)return r}else if(r)return r;if(i)return i;let a=e.identifier?.trim();return!a||S(a)&&("group"===t||"image"===t||"list"===t||"collection"===t)?"":a}function x(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 b(e){return"text-field"===e||"text-view"===e||"search"===e}function S(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}let $=100,A=new Set(["batch","replay"]);function y(t){let r;try{r=JSON.parse(t)}catch{throw new e("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(r)||0===r.length)throw new e("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return r}function v(t,r){if(!Array.isArray(t)||0===t.length)throw new e("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(t.length>r)throw new e("INVALID_ARGS",`batch has ${t.length} steps; max allowed is ${r}.`);let i=[];for(let r=0;r<t.length;r+=1){let a=t[r];if(!a||"object"!=typeof a)throw new e("INVALID_ARGS",`Invalid batch step at index ${r}.`);let n="string"==typeof a.command?a.command.trim().toLowerCase():"";if(!n)throw new e("INVALID_ARGS",`Batch step ${r+1} requires command.`);if(A.has(n))throw new e("INVALID_ARGS",`Batch step ${r+1} cannot run ${n}.`);if(void 0!==a.positionals&&!Array.isArray(a.positionals))throw new e("INVALID_ARGS",`Batch step ${r+1} positionals must be an array.`);let s=a.positionals??[];if(s.some(e=>"string"!=typeof e))throw new e("INVALID_ARGS",`Batch step ${r+1} positionals must contain only strings.`);if(void 0!==a.flags&&("object"!=typeof a.flags||Array.isArray(a.flags)||!a.flags))throw new e("INVALID_ARGS",`Batch step ${r+1} flags must be an object.`);if(void 0!==a.runtime&&("object"!=typeof a.runtime||Array.isArray(a.runtime)||!a.runtime))throw new e("INVALID_ARGS",`Batch step ${r+1} runtime must be an object.`);i.push({command:n,positionals:s,flags:a.flags??{},runtime:a.runtime})}return i}export{TextDecoder,styleText}from"node:util";export{$ as DEFAULT_BATCH_MAX_STEPS,u as SESSION_SURFACES,c as SETTINGS_INVALID_ARGS_MESSAGE,o as SETTINGS_USAGE_OVERRIDE,h as buildSnapshotDisplayLines,g as displayLabel,p as extractReadableText,x as formatRole,w as formatSnapshotLine,y as parseBatchStepsJson,d as parseSessionSurface,v as validateAndNormalizeBatchSteps};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
let e,t,s,r,o,a,i;import{PNG as n}from"pngjs";import{formatSnapshotLine as l,SETTINGS_USAGE_OVERRIDE as p,styleText as u,parseBatchStepsJson as c,buildSnapshotDisplayLines as d}from"./274.js";import{createRequestId as m,node_path as g,normalizeError as f,resolveUserPath as h,readVersion as y,getDiagnosticsMeta as w,emitDiagnostic as b,promises as v,asAppError as D,expandUserHomePath as k,pathToFileURL as S,AppError as A,node_fs as $,node_os as I,withDiagnosticsScope as L,flushDiagnosticsToSessionFile as x,resolveDaemonPaths as N}from"./331.js";import{serializeOpenResult as O,sendToDaemon as E,serializeSessionListEntry as R,serializeDeployResult as P,serializeSnapshotResult as _,serializeCloseResult as F,serializeEnsureSimulatorResult as C,serializeInstallFromSourceResult as T,serializeDevice as j,createAgentDeviceClient as V}from"./224.js";let M=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],G=["snapshotDepth","snapshotScope","snapshotRaw"],U=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","apple"],usageLabel:"--platform ios|macos|android|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"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:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],B=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),H={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{helpDescription:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...M]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...M,"baseline","threshold","out"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",listUsageOverride:"metro prepare --public-base-url <url>",helpDescription:"Prepare a local Metro runtime and optionally bridge it through a remote host",summary:"Prepare local Metro runtime",positionalArgs:["prepare"],allowedFlags:["metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss it",summary:"Inspect or dismiss Android keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics (startup timing)",summary:"Show startup metrics",positionalArgs:[],allowedFlags:[]},back:{helpDescription:"Navigate back (where supported)",summary:"Go back",positionalArgs:[],allowedFlags:[]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...G]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",helpDescription:"Inspect or handle alert (iOS simulator)",summary:"Inspect or handle iOS alert",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",helpDescription:"Tap/click by coordinates, snapshot ref, or selector",summary:"Tap by coordinates, ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap","clickButton",...G]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return element text/attributes by ref or selector",summary:"Get text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...G]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",summary:"Press by coordinates, ref, or selector",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...G]},longpress:{helpDescription:"Long press by coordinates (iOS and Android)",summary:"Long press by coordinates",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",summary:"Swipe coordinates",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{helpDescription:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{helpDescription:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",helpDescription:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...G]},scroll:{helpDescription:"Scroll in direction (0-1 amount)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",helpDescription:"Scroll until text appears or a snapshot ref is brought into view",summary:"Scroll until text or ref is visible",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{helpDescription:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:[]},find:{usageOverride:"find <locator|text> <action> [value]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...G]},settings:{usageOverride:p,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, appearance, and app permissions (macOS supports only settings appearance; permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",helpDescription:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},q=new Map,J=new Map;for(let e of U){for(let t of e.names)q.set(t,e);let t=J.get(e.key);t?t.push(e):J.set(e.key,[e])}function K(e){if(e)return H[e]}function W(){return Object.keys(H)}function z(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}let X=(e=`agent-device <command> [args] [--json]
|
|
1
|
+
let e,t,s,r,o,a,i;import{PNG as n}from"pngjs";import{formatSnapshotLine as l,SESSION_SURFACES as p,SETTINGS_USAGE_OVERRIDE as u,styleText as c,parseBatchStepsJson as d,buildSnapshotDisplayLines as m}from"./425.js";import{createRequestId as g,node_path as f,normalizeError as h,resolveUserPath as y,readVersion as w,getDiagnosticsMeta as b,emitDiagnostic as v,promises as D,asAppError as k,expandUserHomePath as S,pathToFileURL as A,AppError as $,node_fs as I,node_os as L,withDiagnosticsScope as x,flushDiagnosticsToSessionFile as N,resolveDaemonPaths as O}from"./331.js";import{serializeOpenResult as E,sendToDaemon as R,serializeSessionListEntry as P,serializeDeployResult as _,serializeSnapshotResult as F,serializeCloseResult as C,serializeEnsureSimulatorResult as T,serializeInstallFromSourceResult as j,serializeDevice as V,createAgentDeviceClient as M}from"./224.js";let G=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],U=["snapshotDepth","snapshotScope","snapshotRaw"],B=[{key:"config",names:["--config"],type:"string",usageLabel:"--config <path>",usageDescription:"Load CLI defaults from a specific config file"},{key:"remoteConfig",names:["--remote-config"],type:"string",usageLabel:"--remote-config <path>",usageDescription:"Load remote host + Metro workflow settings from a specific profile file"},{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"sessionLock",names:["--session-lock"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock reject|strip",usageDescription:"Lock bound-session device routing for this CLI invocation and nested batch steps"},{key:"sessionLocked",names:["--session-locked"],type:"boolean",usageLabel:"--session-locked",usageDescription:"Deprecated alias for --session-lock reject"},{key:"sessionLockConflicts",names:["--session-lock-conflicts"],type:"enum",enumValues:["reject","strip"],usageLabel:"--session-lock-conflicts reject|strip",usageDescription:"Deprecated alias for --session-lock"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","macos","android","apple"],usageLabel:"--platform ios|macos|android|apple",usageDescription:"Platform to target (`apple` aliases the Apple automation backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv","desktop"],usageLabel:"--target mobile|tv|desktop",usageDescription:"Device target class to match"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"surface",names:["--surface"],type:"enum",enumValues:p,usageLabel:"--surface app|frontmost-app|desktop|menubar",usageDescription:"macOS session surface for open (defaults to app)"},{key:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"Session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"Session-scoped Metro/debug port hint"},{key:"metroProjectRoot",names:["--project-root"],type:"string",usageLabel:"--project-root <path>",usageDescription:"metro prepare: React Native project root (default: cwd)"},{key:"metroKind",names:["--kind"],type:"enum",enumValues:["auto","react-native","expo"],usageLabel:"--kind auto|react-native|expo",usageDescription:"metro prepare: detect or force the Metro launcher kind"},{key:"metroPublicBaseUrl",names:["--public-base-url"],type:"string",usageLabel:"--public-base-url <url>",usageDescription:"metro prepare: public base URL used to build bundle hints"},{key:"metroProxyBaseUrl",names:["--proxy-base-url"],type:"string",usageLabel:"--proxy-base-url <url>",usageDescription:"metro prepare: optional remote host bridge base URL for Metro access"},{key:"metroBearerToken",names:["--bearer-token"],type:"string",usageLabel:"--bearer-token <token>",usageDescription:"metro prepare: host bridge bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)"},{key:"metroPreparePort",names:["--port"],type:"int",min:1,max:65535,usageLabel:"--port <port>",usageDescription:"metro prepare: local Metro port (default: 8081)"},{key:"metroListenHost",names:["--listen-host"],type:"string",usageLabel:"--listen-host <host>",usageDescription:"metro prepare: host Metro listens on (default: 0.0.0.0)"},{key:"metroStatusHost",names:["--status-host"],type:"string",usageLabel:"--status-host <host>",usageDescription:"metro prepare: host used for local /status polling (default: 127.0.0.1)"},{key:"metroStartupTimeoutMs",names:["--startup-timeout-ms"],type:"int",min:1,usageLabel:"--startup-timeout-ms <ms>",usageDescription:"metro prepare: timeout while waiting for Metro to become ready"},{key:"metroProbeTimeoutMs",names:["--probe-timeout-ms"],type:"int",min:1,usageLabel:"--probe-timeout-ms <ms>",usageDescription:"metro prepare: timeout for /status and proxy bridge calls"},{key:"metroRuntimeFile",names:["--runtime-file"],type:"string",usageLabel:"--runtime-file <path>",usageDescription:"metro prepare: optional file path to persist the JSON result"},{key:"metroNoReuseExisting",names:["--no-reuse-existing"],type:"boolean",usageLabel:"--no-reuse-existing",usageDescription:"metro prepare: always start a fresh Metro process"},{key:"metroNoInstallDeps",names:["--no-install-deps"],type:"boolean",usageLabel:"--no-install-deps",usageDescription:"metro prepare: skip package-manager install when node_modules is missing"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"Session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"Session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"header",names:["--header"],type:"string",multiple:!0,usageLabel:"--header <name:value>",usageDescription:"install-from-source: repeatable HTTP header for URL downloads"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"hideTouches",names:["--hide-touches"],type:"boolean",usageLabel:"--hide-touches",usageDescription:"Record: disable touch overlays in the final video"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"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:"clickButton",names:["--button"],type:"enum",enumValues:["primary","secondary","middle"],usageLabel:"--button primary|secondary|middle",usageDescription:"Click: choose mouse button (middle reserved for future macOS support)"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"retainPaths",names:["--retain-paths"],type:"boolean",usageLabel:"--retain-paths",usageDescription:"install-from-source: keep materialized artifact paths after install"},{key:"retentionMs",names:["--retention-ms"],type:"int",min:1,usageLabel:"--retention-ms <ms>",usageDescription:"install-from-source: retention TTL for materialized artifact paths"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"},{key:"baseline",names:["--baseline","-b"],type:"string",usageLabel:"--baseline, -b <path>",usageDescription:"Diff screenshot: path to baseline image file"},{key:"threshold",names:["--threshold"],type:"string",usageLabel:"--threshold <0-1>",usageDescription:"Diff screenshot: color distance threshold (default 0.1)"}],H=new Set(["json","config","remoteConfig","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","sessionLock","sessionLocked","sessionLockConflicts","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),q={boot:{helpDescription:"Ensure target device/simulator is booted and ready",summary:"Boot target device/simulator",positionalArgs:[],allowedFlags:["headless"]},open:{helpDescription:"Boot device/simulator; optionally launch app or deep link URL (macOS also supports --surface app|frontmost-app|desktop|menubar)",summary:"Open an app, deep link or URL, save replays",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch","surface"]},close:{helpDescription:"Close app or just end session",summary:"Close app or end session",positionalArgs:["app?"],allowedFlags:["saveScript","shutdown"]},reinstall:{helpDescription:"Uninstall + install app from binary path",summary:"Reinstall app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{helpDescription:"Install app from binary path without uninstalling first",summary:"Install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},"install-from-source":{helpDescription:"Install app from a URL source through the normal daemon artifact flow",summary:"Install app from a URL source",positionalArgs:["url"],allowedFlags:["header","retainPaths","retentionMs"]},push:{helpDescription:"Simulate push notification payload delivery",summary:"Deliver push payload",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{helpDescription:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...G]},diff:{usageOverride:"diff snapshot | diff screenshot --baseline <path> [--out <diff.png>] [--threshold <0-1>]",helpDescription:"Diff accessibility snapshot or compare screenshots pixel-by-pixel",summary:"Diff snapshot or screenshot",positionalArgs:["kind"],allowedFlags:[...G,"baseline","threshold","out"]},"ensure-simulator":{helpDescription:"Ensure an iOS simulator exists in a device set (create if missing)",summary:"Ensure iOS simulator exists",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},devices:{helpDescription:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{helpDescription:"List installed apps (includes default/system apps by default)",summary:"List installed apps",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{helpDescription:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},metro:{usageOverride:"metro prepare --public-base-url <url> [--project-root <path>] [--port <port>] [--kind auto|react-native|expo]",listUsageOverride:"metro prepare --public-base-url <url>",helpDescription:"Prepare a local Metro runtime and optionally bridge it through a remote host",summary:"Prepare local Metro runtime",positionalArgs:["prepare"],allowedFlags:["metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",listUsageOverride:"clipboard read | clipboard write <text>",helpDescription:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",helpDescription:"Inspect Android keyboard visibility/type or dismiss it",summary:"Inspect or dismiss Android keyboard",positionalArgs:["action?"],allowedFlags:[]},perf:{helpDescription:"Show session performance metrics (startup timing)",summary:"Show startup metrics",positionalArgs:[],allowedFlags:[]},back:{helpDescription:"Navigate back (where supported)",summary:"Go back",positionalArgs:[],allowedFlags:[]},home:{helpDescription:"Go to home screen (where supported)",summary:"Go home",positionalArgs:[],allowedFlags:[]},"app-switcher":{helpDescription:"Open app switcher (where supported)",summary:"Open app switcher",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",helpDescription:"Wait for duration, text, ref, or selector to appear",summary:"Wait for time, text, ref, or selector",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...U]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",helpDescription:"Inspect or handle alert (iOS simulator and macOS desktop)",summary:"Inspect or handle iOS/macOS alerts",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",helpDescription:"Tap/click by coordinates, snapshot ref, or selector",summary:"Tap by coordinates, ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap","clickButton",...U]},get:{usageOverride:"get text|attrs <@ref|selector>",helpDescription:"Return element text/attributes by ref or selector",summary:"Get text or attrs by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...U]},replay:{helpDescription:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",listUsageOverride:"batch --steps <json> | --steps-file <path>",helpDescription:"Execute multiple commands in one daemon request",summary:"Run multiple commands",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",helpDescription:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",summary:"Press by coordinates, ref, or selector",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...U]},longpress:{helpDescription:"Long press by coordinates (iOS and Android)",summary:"Long press by coordinates",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{helpDescription:"Swipe coordinates with optional repeat pattern",summary:"Swipe coordinates",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{helpDescription:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{helpDescription:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",helpDescription:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...U]},scroll:{helpDescription:"Scroll in direction (0-1 amount)",summary:"Scroll in a direction",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",helpDescription:"Scroll until text appears or a snapshot ref is brought into view",summary:"Scroll until text or ref is visible",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{helpDescription:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{helpDescription:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",helpDescription:"Trigger app-defined event hook via deep link template",summary:"Trigger app event hook",positionalArgs:["event","payloadJson?"],allowedFlags:[]},record:{usageOverride:"record start [path] [--fps <n>] [--hide-touches] | record stop",listUsageOverride:"record start [path] | record stop",helpDescription:"Start/stop screen recording",summary:"Start or stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps","hideTouches"]},trace:{usageOverride:"trace start [path] | trace stop [path]",listUsageOverride:"trace start [path] | trace stop",helpDescription:"Start/stop trace log capture",summary:"Start or stop trace capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",helpDescription:"Session app log info, start/stop streaming, diagnostics, and markers",summary:"Manage session app logs",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [summary|headers|body|all]",helpDescription:"Dump recent HTTP(s) traffic parsed from the session app log",summary:"Show recent HTTP traffic",positionalArgs:["dump|log","limit?","include?"],allowedFlags:[]},find:{usageOverride:"find <locator|text> <action> [value]",helpDescription:"Find by text/label/value/role/id and run action",summary:"Find an element and act",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{helpDescription:"Assert UI state (visible|hidden|exists|editable|selected|text)",summary:"Assert UI state",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...U]},settings:{usageOverride:u,listUsageOverride:"settings [area] [options]",helpDescription:"Toggle OS settings, appearance, and app permissions (macOS supports appearance plus permission <grant|reset> for accessibility|screen-recording|input-monitoring; mobile permission actions use the active session app)",summary:"Change OS settings and app permissions",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",helpDescription:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},J=new Map,K=new Map;for(let e of B){for(let t of e.names)J.set(t,e);let t=K.get(e.key);t?t.push(e):K.set(e.key,[e])}function W(e){if(e)return q[e]}function z(){return Object.keys(q)}function X(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}let Z=(e=`agent-device <command> [args] [--json]
|
|
2
2
|
|
|
3
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=
|
|
4
|
+
`,t=ee("Commands:",z().map(e=>{let t=q[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:function(e,t){if(t.listUsageOverride)return t.listUsageOverride;let s=t.positionalArgs.map(s=>{var r,o,a;let i,n,l,p;return r=e,o=t,n=(i=(a=s).endsWith("?"))?a.slice(0,-1):a,p=(l=/^[a-z-]+(?:\|[a-z-]+)+$/i.test(n))||void 0!==o.usageOverride&&o.usageOverride.startsWith(`${r} ${n}`),i?l?`[${n}]`:p?n:`[${n}]`:p?n:`<${n}>`});return[e,...s].join(" ")}(e,t)}}).map(e=>({label:e.usage,description:e.schema.summary??e.schema.helpDescription}))),s=Q("Flags:",Y(H)),r=[ee("Agent Skills:",[{label:"agent-device",description:"Canonical mobile automation flows"},{label:"dogfood",description:"Exploratory QA and bug hunts"}]),"See `skills/<name>/SKILL.md` in the installed package."].join("\n\n"),o=et("Configuration:",["Default config files: ~/.agent-device/config.json, ./agent-device.json","Use --config <path> or AGENT_DEVICE_CONFIG to load one explicit config file."]),a=ee("Environment:",[{label:"AGENT_DEVICE_SESSION",description:"Default session name"},{label:"AGENT_DEVICE_PLATFORM",description:"Default platform binding"},{label:"AGENT_DEVICE_SESSION_LOCK",description:"Bound-session conflict mode"},{label:"AGENT_DEVICE_DAEMON_BASE_URL",description:"Connect to remote daemon"}]),i=et("Examples:",["agent-device open Settings --platform ios","agent-device open TextEdit --platform macos","agent-device snapshot -i",'agent-device fill @e3 "test@example.com"',"agent-device replay ./session.ad"]),`${e}
|
|
5
5
|
${t}
|
|
6
6
|
|
|
7
7
|
${s}
|
|
@@ -13,33 +13,33 @@ ${o}
|
|
|
13
13
|
${a}
|
|
14
14
|
|
|
15
15
|
${i}
|
|
16
|
-
`);function
|
|
17
|
-
(none)`;let s=Math.max(...t.map(e=>e.label.length))+2,r=[e];for(let e of t)r.push(` ${e.label.padEnd(s)}${e.description}`);return r.join("\n")}function
|
|
18
|
-
(none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let
|
|
19
|
-
`)}function
|
|
16
|
+
`);function Y(e){return B.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function Q(e,t){return ee(e,t.map(e=>({label:e.usageLabel??"",description:e.usageDescription??""})))}function ee(e,t){if(0===t.length)return`${e}
|
|
17
|
+
(none)`;let s=Math.max(...t.map(e=>e.label.length))+2,r=[e];for(let e of t)r.push(` ${e.label.padEnd(s)}${e.description}`);return r.join("\n")}function et(e,t){return 0===t.length?`${e}
|
|
18
|
+
(none)`:[e,...t.map(e=>` ${e}`)].join("\n")}let es=new Set(["config","remoteConfig","help","version","batchSteps"]),er={iosSimulatorDeviceSet:["IOS_SIMULATOR_DEVICE_SET"],androidDeviceAllowlist:["ANDROID_DEVICE_ALLOWLIST"],metroBearerToken:["AGENT_DEVICE_PROXY_TOKEN"]},eo=new Set(["1","true","yes","on"]),ea=new Set(["0","false","no","off"]),ei=function(){let e=new Map;for(let t of B){let s=e.get(t.key);s?s.push(t):e.set(t.key,[t])}let t=new Map;for(let e of H)t.set(e,new Set(["*"]));for(let e of z()){let s=W(e);if(s)for(let r of s.allowedFlags){let s=t.get(r);s&&s.has("*")||(s?s.add(e):t.set(r,new Set([e])))}}return[...e.entries()].map(([e,s])=>{var r;return{key:e,flagDefinitions:s,config:{enabled:!es.has(e),key:e},env:{names:[(r=e,`AGENT_DEVICE_${r.replace(/([A-Z])/g,"_$1").replace(/[^A-Za-z0-9_]/g,"_").toUpperCase()}`),...er[e]??[]]},supportsCommand(s){let r=t.get(e);return!!r&&(!!r.has("*")||!!s&&r.has(s))}}}).sort((e,t)=>e.key.localeCompare(t.key))}(),en=new Map(ei.map(e=>[e.key,e]));function el(e){return en.get(e)}function ep(e,t){return el(e)?.supportsCommand(t)??!1}function eu(e,t,s,r){let o=function(e){let t=e.flagDefinitions.find(e=>void 0===e.setValue);if(t)return t;let s=function(e){let t=e.flagDefinitions[0];if(!t)throw Error(`Missing flag definition for option ${e.key}`);return t}(e);if("enum"===s.type){let t=e.flagDefinitions.map(e=>e.setValue).filter(e=>void 0!==e);return{...s,setValue:void 0,enumValues:t}}return s}(e);if(o.multiple)return(Array.isArray(t)?t:[t]).map(t=>eu({...e,flagDefinitions:e.flagDefinitions.map(e=>({...e,multiple:!1}))},t,s,r));if("boolean"===o.type){var a=t,i=s,n=r;if("boolean"==typeof a)return a;if("string"==typeof a){let e=ec(a);if(void 0!==e)return e}throw new $("INVALID_ARGS",`Invalid value for "${n}" in ${i}. Expected boolean.`)}if("booleanOrString"===o.type){if("boolean"==typeof t)return t;if("string"==typeof t&&void 0!==ec(t))return ec(t);if("string"==typeof t&&t.trim().length>0)return t;throw new $("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected boolean or non-empty string.`)}if("string"===o.type){if("string"==typeof t&&t.trim().length>0)return t;throw new $("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected non-empty string.`)}if("enum"===o.type){if(void 0!==o.setValue){var l=o,p=t,u=s,c=r;let e=l.setValue;if(p===e)return e;if("string"==typeof p){let t=p.trim();if(""===t||"true"===t||"1"===t)return e;if("false"===t||"0"===t)return}if(!0===p)return e;if(!1!==p)throw new $("INVALID_ARGS",`Invalid value for "${c}" in ${u}. Expected boolean or ${String(e)}.`);return}if("string"!=typeof t||!o.enumValues?.includes(t))throw new $("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected one of: ${o.enumValues?.join(", ")}.`);return t}let d="number"==typeof t?t:"string"==typeof t?Number(t):NaN;if(!Number.isFinite(d)||!Number.isInteger(d))throw new $("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Expected integer.`);if("number"==typeof o.min&&d<o.min)throw new $("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Must be >= ${o.min}.`);if("number"==typeof o.max&&d>o.max)throw new $("INVALID_ARGS",`Invalid value for "${r}" in ${s}. Must be <= ${o.max}.`);return d}function ec(e){let t=e.trim().toLowerCase();return!!eo.has(t)||!ea.has(t)&&void 0}function ed(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function em(e){return e.replace(/^-+/,"")}function eg(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?ed(e):[e,void 0];return void 0!==J.get(t)}function ef(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function eh(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}function ey(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
19
|
+
`)}function ew(e,t={}){let s=e instanceof $?h(e):e;process.stderr.write(`Error (${s.code}): ${s.message}
|
|
20
20
|
`),s.hint&&process.stderr.write(`Hint: ${s.hint}
|
|
21
21
|
`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}
|
|
22
22
|
`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}
|
|
23
23
|
`),t.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}
|
|
24
|
-
`)}function
|
|
24
|
+
`)}function eb(e,t={}){let s=e.nodes,r=Array.isArray(s)?s:[],o=!!e.truncated,a="string"==typeof e.appName?e.appName:void 0,i="string"==typeof e.appBundleId?e.appBundleId:void 0,n=[];a&&n.push(`Page: ${a}`),i&&n.push(`App: ${i}`);let p=`Snapshot: ${r.length} nodes${o?" (truncated)":""}`,u=n.length>0?`${n.join("\n")}
|
|
25
25
|
`:"";if(0===r.length)return`${u}${p}
|
|
26
26
|
`;if(t.raw){let e=r.map(e=>JSON.stringify(e));return`${u}${p}
|
|
27
27
|
${e.join("\n")}
|
|
28
|
-
`}if(t.flatten){let e=r.map(e=>l(e,0,!1));return`${u}${p}
|
|
28
|
+
`}if(t.flatten){let e=r.map(e=>l(e,0,!1,void 0,{summarizeTextSurfaces:!0}));return`${u}${p}
|
|
29
29
|
${e.join("\n")}
|
|
30
|
-
`}let c=
|
|
30
|
+
`}let c=m(r,{summarizeTextSurfaces:!0}).map(e=>e.text);return`${u}${p}
|
|
31
31
|
${c.join("\n")}
|
|
32
|
-
`}function
|
|
33
|
-
`),!0},devices:async({flags:e,client:t})=>{let s=await t.devices.list(
|
|
34
|
-
`),!0},"ensure-simulator":async({flags:e,client:t})=>{if(!e.device)throw new
|
|
32
|
+
`}function ev(e){return"number"==typeof e&&Number.isFinite(e)?e:0}function eD(){let e=process.env.FORCE_COLOR;return"string"==typeof e?"0"!==e:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY}let ek=255*Math.sqrt(3);async function eS(e,t,s={}){await eA(e,"Baseline image not found"),await eA(t,"Current screenshot not found");let r=s.outputPath,[o,a]=await Promise.all([D.readFile(e),D.readFile(t)]),i=e$(o,"baseline"),l=e$(a,"current"),p=s.threshold??.1;if(i.width!==l.width||i.height!==l.height){let e=i.width*i.height;return await eI(s.outputPath),{match:!1,mismatchPercentage:100,totalPixels:e,differentPixels:e,dimensionMismatch:{expected:{width:i.width,height:i.height},actual:{width:l.width,height:l.height}}}}let u=i.width*i.height,c=p*ek,d=new n({width:i.width,height:i.height}),m=0;for(let e=0;e<i.data.length;e+=4){if(Math.sqrt((i.data[e]-l.data[e])**2+(i.data[e+1]-l.data[e+1])**2+(i.data[e+2]-l.data[e+2])**2)>c){m+=1,d.data[e]=255,d.data[e+1]=0,d.data[e+2]=0,d.data[e+3]=255;continue}let t=Math.round(.3*Math.round((i.data[e]+i.data[e+1]+i.data[e+2])/3));d.data[e]=t,d.data[e+1]=t,d.data[e+2]=t,d.data[e+3]=255}m>0&&r?(await D.mkdir(f.dirname(r),{recursive:!0}),await D.writeFile(r,n.sync.write(d))):await eI(s.outputPath);let g=u>0?Math.round(m/u*1e4)/100:0;return{...m>0&&r?{diffPath:r}:{},totalPixels:u,differentPixels:m,mismatchPercentage:g,match:0===m}}async function eA(e,t){try{await D.access(e)}catch{throw new $("INVALID_ARGS",`${t}: ${e}`)}}function e$(e,t){try{return n.sync.read(e)}catch(e){throw new $("COMMAND_FAILED",`Failed to decode ${t} screenshot as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}async function eI(e){if(e)try{await D.unlink(e)}catch(e){var t;if(!("object"==typeof(t=e)&&null!==t&&"code"in t&&"ENOENT"===t.code))throw e}}async function eL(e,t){if(!e.remoteConfig)return;let s=e.platform;if("ios"!==s&&"android"!==s)throw new $("INVALID_ARGS",'open --remote-config requires platform "ios" or "android" in the remote config file or CLI flags.');if(!e.metroPublicBaseUrl)throw new $("INVALID_ARGS",'open --remote-config requires "metroPublicBaseUrl" in the remote config file.');let r=await t.metro.prepare({projectRoot:e.metroProjectRoot,kind:e.metroKind,publicBaseUrl:e.metroPublicBaseUrl,proxyBaseUrl:e.metroProxyBaseUrl,bearerToken:e.metroBearerToken,port:e.metroPreparePort,listenHost:e.metroListenHost,statusHost:e.metroStatusHost,startupTimeoutMs:e.metroStartupTimeoutMs,probeTimeoutMs:e.metroProbeTimeoutMs,reuseExisting:!e.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!e.metroNoInstallDeps&&void 0,runtimeFilePath:e.metroRuntimeFile});return"ios"===s?r.iosRuntime:r.androidRuntime}async function ex(e){let t=eN[e.command];return!!t&&await t(e)}let eN={session:async({positionals:e,flags:t,client:s})=>{if("list"!==(e[0]??"list"))throw new $("INVALID_ARGS","session only supports list");let r={sessions:(await s.sessions.list()).map(P)};return t.json?ey({success:!0,data:r}):process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
33
|
+
`),!0},devices:async({flags:e,client:t})=>{let s=await t.devices.list(eR(e)),r={devices:s.map(V)};return e.json?ey({success:!0,data:r}):process.stdout.write(`${s.map(eP).join("\n")}
|
|
34
|
+
`),!0},"ensure-simulator":async({flags:e,client:t})=>{if(!e.device)throw new $("INVALID_ARGS","ensure-simulator requires --device <name>");let s=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet}),r=T(s);if(e.json)ey({success:!0,data:r});else{let e=s.created?"Created":"Reused",t=s.booted?" (booted)":"";process.stdout.write(`${e}: ${s.device} ${s.udid}${t}
|
|
35
35
|
`),s.runtime&&process.stdout.write(`Runtime: ${s.runtime}
|
|
36
|
-
`)}return!0},metro:async({positionals:e,flags:t,client:s})=>{var r;if("prepare"!==(e[0]??"").toLowerCase())throw new
|
|
37
|
-
`),!0},install:async({positionals:e,flags:t,client:s})=>{let r=await
|
|
38
|
-
`),!0},diff:async({positionals:e,flags:t,client:s})=>{let r;if("screenshot"!==e[0])return!1;let o=t.baseline;if(!o||"string"!=typeof o)throw new
|
|
39
|
-
`}(r)),!0}};async function eN(e,t,s,r){let o=t[0],a=t[1];if(!o||!a)throw new A("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let i={app:o,appPath:a,...eE(s)};return"install"===e?await r.apps.install(i):await r.apps.reinstall(i)}async function eO(e,t,s){let r=e[0]?.trim();if(!r)throw new A("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new A("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await s.apps.installFromSource({...eE(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:r,headers:function(e){if(!e||0===e.length)return;let t={};for(let s of e){let e=s.indexOf(":");if(e<=0)throw new A("INVALID_ARGS",`Invalid --header value "${s}". Expected "name:value".`);let r=s.slice(0,e).trim(),o=s.slice(e+1).trim();if(!r)throw new A("INVALID_ARGS",`Invalid --header value "${s}". Header name cannot be empty.`);t[r]=o}return t}(t.header)}})}function eE(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function eR(e){let t=e.kind?` ${e.kind}`:"",s=e.target?` target=${e.target}`:"",r="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${s})${r}`}function eP(e,t={}){let s=e_(t),r={...e};return s.defaultPlatform&&void 0===r.platform&&(r.platform=s.defaultPlatform),r}function e_(e){var t,s,r,o;let a,i=e.env??process.env,n=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new A("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(i.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??i.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:n,lockPolicy:(s=e.policyOverrides,r=i,o=l,(a=s?.sessionLock??s?.sessionLockConflicts??eF(r.AGENT_DEVICE_SESSION_LOCK)??eF(r.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(s?.sessionLocked===!0||function(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;default:return!1}}(r.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function eF(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new A("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}function eC(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}let eT=["stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],ej=new Set(["stateDir","iosSimulatorDeviceSet","metroProjectRoot","metroRuntimeFile"]),eV=["remoteConfig","session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],eM={sendToDaemon:E};async function eG(e,t=eM){let s=m(),r=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),o=e.includes("--json"),a=function(e){for(let t=0;t<e.length;t+=1){let s=e[t];if(s.startsWith("--session=")){let e=s.slice(10).trim();return e.length>0?e:null}if("--session"===s){let s=e[t+1]?.trim();if(s&&!s.startsWith("-"))return s;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await L({session:a,requestId:s,command:e[0],debug:r},async()=>{var a,i,n,l,p,d,m,v,S,I,L;let O;try{let t,s,r,o,u,c,f,y,w;a={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},s=null,r=[],o=[],a=!0;for(let i=0;i<e.length;i+=1){let n=e[i];if(a&&"--"===n){a=!1;continue}if(!a){s?r.push(n):s=eg(n);continue}let l=n.startsWith("--"),p=n.startsWith("-")&&n.length>1;if(!l&&!p){s?r.push(n):s=eg(n);continue}let[u,c]=l?ec(n):[n,void 0],d=q.get(u);if(!d){if(function(e,t,s){var r;if(r=s,!/^-\d+(\.\d+)?$/.test(r)||!e)return!1;let o=K(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(s,r,n)){s?r.push(n):s=n;continue}throw new A("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,s,r){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===r||em(r)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(r)?{value:!0,consumeNext:!1}:{value:r,consumeNext:!0}}let o=s??r;if(void 0===o||void 0===s&&em(o))throw new A("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new A("INVALID_ARGS",`Invalid ${ed(t)}: ${o}`);return{value:o,consumeNext:void 0===s}}let a=Number(o);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new A("INVALID_ARGS",`Invalid ${ed(t)}: ${o}`);return{value:Math.floor(a),consumeNext:void 0===s}}(d,u,c,e[i+1]);m.consumeNext&&(i+=1);let g=t[d.key];if(d.multiple){let e=Array.isArray(g)?[...g,m.value]:void 0===g?[m.value]:[g,m.value];t[d.key]=e}else t[d.key]=m.value;o.push({key:d.key,token:u})}return{command:s,positionals:r,flags:t,warnings:[],providedFlags:o}}(e),s=a?.env??process.env,r=a?.cwd??process.cwd(),o=function(e){if(!e.cliFlags.remoteConfig)return{};let t=function(e,t){let s={};for(let r of t){let t=en(r);if(!t)continue;let o=t.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);o&&(s[r]=ep(t,o.value,`environment variable ${o.name}`,o.name))}return s}(e.env,eV);return function(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r)}(t,function(e){let t,s,r=e.env??process.env,o=h(e.configPath,{cwd:e.cwd,env:r});if(!$.existsSync(o))throw new A("INVALID_ARGS",`Remote config file not found: ${o}`);try{t=$.readFileSync(o,"utf8")}catch(e){throw new A("INVALID_ARGS",`Failed to read remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}try{s=JSON.parse(t)}catch(e){throw new A("INVALID_ARGS",`Invalid JSON in remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new A("INVALID_ARGS",`Remote config file must contain a JSON object: ${o}`);let a={},i=s,n=g.dirname(o);for(let[e,t]of Object.entries(i)){if(!eT.includes(e))throw new A("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${o}.`);let s=en(e);if(!s)throw new A("INVALID_ARGS",`Unknown remote config key "${e}" in remote config file ${o}.`);let i=ep(s,t,`remote config file ${o}`,e);a[e]="string"==typeof i&&ej.has(e)?h(i,{cwd:n,env:r}):i}return a}({configPath:e.cliFlags.remoteConfig,cwd:e.cwd,env:e.env})),t.remoteConfig=e.cliFlags.remoteConfig,t}({cliFlags:t.flags,cwd:r,env:s}),f=function(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}((u=(i={command:t.command,cwd:r,cliFlags:t.flags,env:s}).env??process.env,c=eC({},function(e){let t={};for(let s of e)eC(t,function(e,t){let s,r;if(!$.existsSync(e)){if(t)throw new A("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{s=$.readFileSync(e,"utf8")}catch(t){throw new A("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{r=JSON.parse(s)}catch(t){throw new A("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new A("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let s={};for(let[r,o]of Object.entries(e)){let e=en(r);if(!e)throw new A("INVALID_ARGS",`Unknown config key "${r}" in ${t}.`);if(!e.config.enabled)throw new A("INVALID_ARGS",`Unsupported config key "${r}" in ${t}.`);s[r]=ep(e,o,t,r)}return s}(r,`config file ${e}`)}(s.path,s.required));return t}((n=i.cwd,l=i.cliFlags.config,p=u,(w=l??p.AGENT_DEVICE_CONFIG)?[{path:(d=w,m=n,v=p,h(d,{cwd:m,env:v})),required:!0}]:[{path:(S=p,g.join(k("~",{env:S}),".agent-device","config.json")),required:!1},{path:g.resolve(n,"agent-device.json"),required:!1}]))),eC(c,function(e,t){let s={};for(let r of ea.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=r.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(s[r.key]=ep(r,t.value,`environment variable ${t.name}`,t.name))}return s}(u,i.command))),o),y=function(e,t){let s=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),r=[...e.warnings],o=ef({json:!1,help:!1,version:!1},t?.defaultFlags??{});ef(o,e.flags);let a=K(e.command),i=e.providedFlags.filter(t=>!el(t.key,e.command));if(i.length>0){var n,l;let t=i.map(e=>e.token),a=(n=e.command,l=t,n?1===l.length?`Flag ${l[0]} is not supported for command ${n}.`:`Flags ${l.join(", ")} are not supported for command ${n}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(s)throw new A("INVALID_ARGS",a);for(let e of(r.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),i))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(el(t,e.command)||delete o[t]);if(a?.defaults)for(let[e,t]of Object.entries(a.defaults))void 0===o[e]&&(o[e]=t);if("batch"===e.command&&1!=+!!o.steps+ +!!o.stepsFile)throw new A("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:e.command,positionals:e.positionals,flags:o,warnings:r}}(t,{strictFlags:a?.strictFlags,defaultFlags:f}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&void 0===e[s]&&(e[s]=r)}(y.flags,function(e){let t={};for(let s of eV){let r=e[s];void 0!==r&&(t[s]=r)}return t}(f)),O=y}catch(t){b({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=f(t,{diagnosticId:w().diagnosticId,logPath:x({force:!0})??void 0});o?eh({success:!1,error:e}):ey(e,{showDetails:r}),process.exit(1);return}for(let e of O.warnings)process.stderr.write(`Warning: ${e}
|
|
40
|
-
`);
|
|
41
|
-
`),process.exit(0));let E="help"===
|
|
42
|
-
`),process.exit(0));let t=function(e){var t,s;let r=
|
|
36
|
+
`)}return!0},metro:async({positionals:e,flags:t,client:s})=>{var r;if("prepare"!==(e[0]??"").toLowerCase())throw new $("INVALID_ARGS","metro only supports prepare");if(!t.metroPublicBaseUrl)throw new $("INVALID_ARGS","metro prepare requires --public-base-url <url>.");return r=await s.metro.prepare({projectRoot:t.metroProjectRoot,kind:t.metroKind,port:t.metroPreparePort,listenHost:t.metroListenHost,statusHost:t.metroStatusHost,publicBaseUrl:t.metroPublicBaseUrl,proxyBaseUrl:t.metroProxyBaseUrl,bearerToken:t.metroBearerToken,startupTimeoutMs:t.metroStartupTimeoutMs,probeTimeoutMs:t.metroProbeTimeoutMs,reuseExisting:!t.metroNoReuseExisting&&void 0,installDependenciesIfNeeded:!t.metroNoInstallDeps&&void 0,runtimeFilePath:t.metroRuntimeFile}),t.json?ey({success:!0,data:r}):process.stdout.write(`${JSON.stringify(r,null,2)}
|
|
37
|
+
`),!0},install:async({positionals:e,flags:t,client:s})=>{let r=await eO("install",e,t,s);return t.json&&ey({success:!0,data:_(r)}),!0},reinstall:async({positionals:e,flags:t,client:s})=>{let r=await eO("reinstall",e,t,s);return t.json&&ey({success:!0,data:_(r)}),!0},"install-from-source":async({positionals:e,flags:t,client:s})=>{let r=await eE(e,t,s);return t.json&&ey({success:!0,data:j(r)}),!0},open:async({positionals:e,flags:t,client:s})=>{if(!e[0])return!1;let r=await eL(t,s),o=await s.apps.open({app:e[0],url:e[1],activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,runtime:r,...eR(t)});return t.json&&ey({success:!0,data:E(o)}),!0},close:async({positionals:e,flags:t,client:s})=>{let r=e[0]?await s.apps.close({app:e[0],shutdown:t.shutdown}):await s.sessions.close({shutdown:t.shutdown});return t.json&&ey({success:!0,data:C(r)}),!0},snapshot:async({flags:e,client:t})=>{let s=F(await t.capture.snapshot({...eR(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw}));return e.json?ey({success:!0,data:s}):process.stdout.write(eb(s,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},screenshot:async({positionals:e,flags:t,client:s})=>{let r=await s.capture.screenshot({path:e[0]??t.out}),o={path:r.path};return t.json?ey({success:!0,data:o}):process.stdout.write(`${r.path}
|
|
38
|
+
`),!0},diff:async({positionals:e,flags:t,client:s})=>{let r;if("screenshot"!==e[0])return!1;let o=t.baseline;if(!o||"string"!=typeof o)throw new $("INVALID_ARGS","diff screenshot requires --baseline <path>");let a=y(o),i="string"==typeof t.out?y(t.out):void 0,n=.1;if(null!=t.threshold&&""!==t.threshold&&(Number.isNaN(n=Number(t.threshold))||n<0||n>1))throw new $("INVALID_ARGS","--threshold must be a number between 0 and 1");let l=I.mkdtempSync(f.join(L.tmpdir(),"agent-device-diff-current-")),p=f.join(l,`current-${Date.now()}.png`),u=(await s.capture.screenshot({path:p})).path;try{r=await eS(a,u,{threshold:n,outputPath:i})}finally{try{I.unlinkSync(u)}catch{}try{I.rmSync(l,{recursive:!0,force:!0})}catch{}}return t.json?ey({success:!0,data:r}):process.stdout.write(function(e){var t,s;let r=eD(),o=!0===e.match,a=ev(e.differentPixels),i=ev(e.totalPixels),n=ev(e.mismatchPercentage),l=e.diffPath,p=e.dimensionMismatch,u=[];if(o){let e=r?c("green","✓"):"✓";u.push(`${e} Screenshots match.`)}else if(p){let e=r?c("red","✗"):"✗",t=p.expected,s=p.actual;u.push(`${e} Screenshots have different dimensions: expected ${t?.width}x${t?.height}, got ${s?.width}x${s?.height}`)}else{let e=r?c("red","✗"):"✗",t=0===n&&a>0?"<0.01":String(n);u.push(`${e} ${t}% pixels differ`)}if(l&&!o){let e,s,o=(t=l,e=process.cwd(),""!==(s=f.relative(e,t))&&(s.startsWith("..")||f.isAbsolute(s))?t:""===s?".":`.${f.sep}${s}`),a=r?c("dim","Diff image:"):"Diff image:",i=r?c("green",o):o;u.push(` ${a} ${i}`)}if(!o&&!p){let e=r?(s=String(a),c("red",s)):String(a);u.push(` ${e} different / ${i} total pixels`)}return`${u.join("\n")}
|
|
39
|
+
`}(r)),!0}};async function eO(e,t,s,r){let o=t[0],a=t[1];if(!o||!a)throw new $("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let i={app:o,appPath:a,...eR(s)};return"install"===e?await r.apps.install(i):await r.apps.reinstall(i)}async function eE(e,t,s){let r=e[0]?.trim();if(!r)throw new $("INVALID_ARGS","install-from-source requires: install-from-source <url>");if(e.length>1)throw new $("INVALID_ARGS","install-from-source accepts exactly one positional argument: <url>");return await s.apps.installFromSource({...eR(t),retainPaths:t.retainPaths,retentionMs:t.retentionMs,source:{kind:"url",url:r,headers:function(e){if(!e||0===e.length)return;let t={};for(let s of e){let e=s.indexOf(":");if(e<=0)throw new $("INVALID_ARGS",`Invalid --header value "${s}". Expected "name:value".`);let r=s.slice(0,e).trim(),o=s.slice(e+1).trim();if(!r)throw new $("INVALID_ARGS",`Invalid --header value "${s}". Header name cannot be empty.`);t[r]=o}return t}(t.header)}})}function eR(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function eP(e){let t=e.kind?` ${e.kind}`:"",s=e.target?` target=${e.target}`:"",r="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${s})${r}`}function e_(e,t={}){let s=eF(t),r={...e};return s.defaultPlatform&&void 0===r.platform&&(r.platform=s.defaultPlatform),r}function eF(e){var t,s,r,o;let a,i=e.env??process.env,n=e.inheritedPlatform??e.configuredPlatform??function(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("ios"===t||"android"===t||"apple"===t)return t;throw new $("INVALID_ARGS",`Invalid AGENT_DEVICE_PLATFORM: ${e}. Use ios, android, or apple.`)}}(i.AGENT_DEVICE_PLATFORM),l="string"==typeof(t=e.configuredSession??i.AGENT_DEVICE_SESSION)&&t.trim().length>0;return{defaultPlatform:n,lockPolicy:(s=e.policyOverrides,r=i,o=l,(a=s?.sessionLock??s?.sessionLockConflicts??eC(r.AGENT_DEVICE_SESSION_LOCK)??eC(r.AGENT_DEVICE_SESSION_LOCK_CONFLICTS))||(s?.sessionLocked===!0||function(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"on":return!0;default:return!1}}(r.AGENT_DEVICE_SESSION_LOCKED)||o?"reject":void 0))}}function eC(e){if(void 0===e)return;let t=e.trim().toLowerCase();if(t){if("reject"===t||"strip"===t)return t;throw new $("INVALID_ARGS",`Invalid session lock mode: ${e}. Use reject or strip.`)}}function eT(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}let ej=["stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],eV=new Set(["stateDir","iosSimulatorDeviceSet","metroProjectRoot","metroRuntimeFile"]),eM=["remoteConfig","session","platform","daemonBaseUrl","daemonAuthToken","daemonTransport","metroProjectRoot","metroKind","metroPublicBaseUrl","metroProxyBaseUrl","metroBearerToken","metroPreparePort","metroListenHost","metroStatusHost","metroStartupTimeoutMs","metroProbeTimeoutMs","metroRuntimeFile","metroNoReuseExisting","metroNoInstallDeps"],eG={sendToDaemon:R};async function eU(e,t=eG){let s=g(),r=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),o=e.includes("--json"),a=function(e){for(let t=0;t<e.length;t+=1){let s=e[t];if(s.startsWith("--session=")){let e=s.slice(10).trim();return e.length>0?e:null}if("--session"===s){let s=e[t+1]?.trim();if(s&&!s.startsWith("-"))return s;break}}return null}(e)??process.env.AGENT_DEVICE_SESSION??"default";await x({session:a,requestId:s,command:e[0],debug:r},async()=>{var a,i,n,l,p,u,m,g,D,A,L;let x;try{let t,s,r,o,c,d,h,w,b;a={cwd:process.cwd(),env:process.env},t=function(e){let t={json:!1,help:!1,version:!1},s=null,r=[],o=[],a=!0;for(let i=0;i<e.length;i+=1){let n=e[i];if(a&&"--"===n){a=!1;continue}if(!a){s?r.push(n):s=ef(n);continue}let l=n.startsWith("--"),p=n.startsWith("-")&&n.length>1;if(!l&&!p){s?r.push(n):s=ef(n);continue}let[u,c]=l?ed(n):[n,void 0],d=J.get(u);if(!d){if(function(e,t,s){var r;if(r=s,!/^-\d+(\.\d+)?$/.test(r)||!e)return!1;let o=W(e);return!o||!!o.allowsExtraPositionals||0!==o.positionalArgs.length&&(t.length<o.positionalArgs.length||o.positionalArgs.some(e=>e.includes("?")))}(s,r,n)){s?r.push(n):s=n;continue}throw new $("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,s,r){if(void 0!==e.setValue){if(void 0!==s)throw new $("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 $("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 $("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===r||eg(r)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(r)?{value:!0,consumeNext:!1}:{value:r,consumeNext:!0}}let o=s??r;if(void 0===o||void 0===s&&eg(o))throw new $("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:o,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(o))throw new $("INVALID_ARGS",`Invalid ${em(t)}: ${o}`);return{value:o,consumeNext:void 0===s}}let a=Number(o);if(!Number.isFinite(a)||"number"==typeof e.min&&a<e.min||"number"==typeof e.max&&a>e.max)throw new $("INVALID_ARGS",`Invalid ${em(t)}: ${o}`);return{value:Math.floor(a),consumeNext:void 0===s}}(d,u,c,e[i+1]);m.consumeNext&&(i+=1);let g=t[d.key];if(d.multiple){let e=Array.isArray(g)?[...g,m.value]:void 0===g?[m.value]:[g,m.value];t[d.key]=e}else t[d.key]=m.value;o.push({key:d.key,token:u})}return{command:s,positionals:r,flags:t,warnings:[],providedFlags:o}}(e),s=a?.env??process.env,r=a?.cwd??process.cwd(),o=function(e){if(!e.cliFlags.remoteConfig)return{};let t=function(e,t){let s={};for(let r of t){let t=el(r);if(!t)continue;let o=t.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);o&&(s[r]=eu(t,o.value,`environment variable ${o.name}`,o.name))}return s}(e.env,eM);return function(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r)}(t,function(e){let t,s,r=e.env??process.env,o=y(e.configPath,{cwd:e.cwd,env:r});if(!I.existsSync(o))throw new $("INVALID_ARGS",`Remote config file not found: ${o}`);try{t=I.readFileSync(o,"utf8")}catch(e){throw new $("INVALID_ARGS",`Failed to read remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}try{s=JSON.parse(t)}catch(e){throw new $("INVALID_ARGS",`Invalid JSON in remote config file: ${o}`,{cause:e instanceof Error?e.message:String(e)})}if(!s||"object"!=typeof s||Array.isArray(s))throw new $("INVALID_ARGS",`Remote config file must contain a JSON object: ${o}`);let a={},i=s,n=f.dirname(o);for(let[e,t]of Object.entries(i)){if(!ej.includes(e))throw new $("INVALID_ARGS",`Unsupported remote config key "${e}" in remote config file ${o}.`);let s=el(e);if(!s)throw new $("INVALID_ARGS",`Unknown remote config key "${e}" in remote config file ${o}.`);let i=eu(s,t,`remote config file ${o}`,e);a[e]="string"==typeof i&&eV.has(e)?y(i,{cwd:n,env:r}):i}return a}({configPath:e.cliFlags.remoteConfig,cwd:e.cwd,env:e.env})),t.remoteConfig=e.cliFlags.remoteConfig,t}({cliFlags:t.flags,cwd:r,env:s}),h=function(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&(e[s]=r);return e}((c=(i={command:t.command,cwd:r,cliFlags:t.flags,env:s}).env??process.env,d=eT({},function(e){let t={};for(let s of e)eT(t,function(e,t){let s,r;if(!I.existsSync(e)){if(t)throw new $("INVALID_ARGS",`Config file not found: ${e}`);return{}}try{s=I.readFileSync(e,"utf8")}catch(t){throw new $("INVALID_ARGS",`Failed to read config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}try{r=JSON.parse(s)}catch(t){throw new $("INVALID_ARGS",`Invalid JSON in config file: ${e}`,{cause:t instanceof Error?t.message:String(t)})}if(!r||"object"!=typeof r||Array.isArray(r))throw new $("INVALID_ARGS",`Config file must contain a JSON object: ${e}`);return function(e,t){let s={};for(let[r,o]of Object.entries(e)){let e=el(r);if(!e)throw new $("INVALID_ARGS",`Unknown config key "${r}" in ${t}.`);if(!e.config.enabled)throw new $("INVALID_ARGS",`Unsupported config key "${r}" in ${t}.`);s[r]=eu(e,o,t,r)}return s}(r,`config file ${e}`)}(s.path,s.required));return t}((n=i.cwd,l=i.cliFlags.config,p=c,(b=l??p.AGENT_DEVICE_CONFIG)?[{path:(u=b,m=n,g=p,y(u,{cwd:m,env:g})),required:!0}]:[{path:(D=p,f.join(S("~",{env:D}),".agent-device","config.json")),required:!1},{path:f.resolve(n,"agent-device.json"),required:!1}]))),eT(d,function(e,t){let s={};for(let r of ei.filter(e=>e.config.enabled&&e.supportsCommand(t))){let t=r.env.names.map(t=>({name:t,value:e[t]})).find(e=>"string"==typeof e.value&&e.value.trim().length>0);t&&(s[r.key]=eu(r,t.value,`environment variable ${t.name}`,t.name))}return s}(c,i.command))),o),w=function(e,t){let s=t?.strictFlags??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),r=[...e.warnings],o=eh({json:!1,help:!1,version:!1},t?.defaultFlags??{});eh(o,e.flags);let a=W(e.command),i=e.providedFlags.filter(t=>!ep(t.key,e.command));if(i.length>0){var n,l;let t=i.map(e=>e.token),a=(n=e.command,l=t,n?1===l.length?`Flag ${l[0]} is not supported for command ${n}.`:`Flags ${l.join(", ")} are not supported for command ${n}.`:1===l.length?`Flag ${l[0]} requires a command that supports it.`:`Flags ${l.join(", ")} require a command that supports them.`);if(s)throw new $("INVALID_ARGS",a);for(let e of(r.push(`${a} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),i))delete o[e.key]}for(let t of Object.keys(o))void 0!==o[t]&&(ep(t,e.command)||delete o[t]);if(a?.defaults)for(let[e,t]of Object.entries(a.defaults))void 0===o[e]&&(o[e]=t);if("batch"===e.command&&1!=+!!o.steps+ +!!o.stepsFile)throw new $("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:e.command,positionals:e.positionals,flags:o,warnings:r}}(t,{strictFlags:a?.strictFlags,defaultFlags:h}),"open"===t.command&&t.flags.remoteConfig&&function(e,t){for(let[s,r]of Object.entries(t))void 0!==r&&void 0===e[s]&&(e[s]=r)}(w.flags,function(e){let t={};for(let s of eM){let r=e[s];void 0!==r&&(t[s]=r)}return t}(h)),x=w}catch(t){v({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=h(t,{diagnosticId:b().diagnosticId,logPath:N({force:!0})??void 0});o?ey({success:!1,error:e}):ew(e,{showDetails:r}),process.exit(1);return}for(let e of x.warnings)process.stderr.write(`Warning: ${e}
|
|
40
|
+
`);x.flags.version&&(process.stdout.write(`${w()}
|
|
41
|
+
`),process.exit(0));let E="help"===x.command,R=x.flags.help;if(E||R){E&&x.positionals.length>1&&(ew(new $("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=E?x.positionals[0]:x.command;e||(process.stdout.write(`${Z}
|
|
42
|
+
`),process.exit(0));let t=function(e){var t,s;let r=W(e);if(!r)return null;let o=(t=e,(s=r).usageOverride?s.usageOverride:[t,...s.positionalArgs.map(X),...s.allowedFlags.flatMap(e=>(K.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")),a=Y(new Set(r.allowedFlags)),i=Y(H),n=[];return a.length>0&&n.push(Q("Command flags:",a)),n.push(Q("Global flags:",i)),`agent-device ${o}
|
|
43
43
|
|
|
44
44
|
${r.helpDescription}
|
|
45
45
|
|
|
@@ -47,13 +47,13 @@ Usage:
|
|
|
47
47
|
agent-device ${o}
|
|
48
48
|
|
|
49
49
|
${n.join("\n\n")}
|
|
50
|
-
`}(
|
|
51
|
-
`),process.exit(1)}
|
|
52
|
-
`),process.exit(1));let{command:P,positionals:_}=
|
|
53
|
-
`)),U&&U();return}if("runtime"===P)throw new
|
|
54
|
-
`;let d=(function(e,t){if(0===e.length)return e;let s=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===s.length)return e;let r=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),o=Math.min(e.length-1,t+1);for(let e=s;e<=o;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[],1).map(e=>{var t,s,r,o;let a="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=a.startsWith(" ")?`+${a}`:`+ ${a}`;return
|
|
55
|
-
`:"";if(!
|
|
56
|
-
`;let g=`${(t=String(n),s="green",
|
|
50
|
+
`}(ef(e));t&&(process.stdout.write(t),process.exit(0)),ew(new $("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${Z}
|
|
51
|
+
`),process.exit(1)}x.command||(process.stdout.write(`${Z}
|
|
52
|
+
`),process.exit(1));let{command:P,positionals:_}=x,F=eF({policyOverrides:x.flags,configuredPlatform:x.flags.platform,configuredSession:x.flags.session}),C=F.lockPolicy?{...x.flags}:e_(x.flags,{policyOverrides:x.flags,configuredPlatform:x.flags.platform,configuredSession:x.flags.session}),T=function(e){let{json:t,config:s,remoteConfig:r,help:o,version:a,sessionLock:i,sessionLocked:n,sessionLockConflicts:l,...p}=e;return p}(C),j=O(C.stateDir),V=C.session??"default",G=C.daemonBaseUrl,U=!C.verbose||C.json||G?null:function(e){try{let t=0,s=!1,r=setInterval(()=>{if(!s&&I.existsSync(e))try{let s=I.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let r=I.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);I.readSync(r,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{I.closeSync(r)}}catch{}},200);return()=>{s=!0,clearInterval(r)}}catch{return null}}(j.logPath),B=M({session:V,requestId:s,stateDir:C.stateDir,daemonBaseUrl:C.daemonBaseUrl,daemonAuthToken:C.daemonAuthToken,daemonTransport:C.daemonTransport,daemonServerMode:C.daemonServerMode,tenant:C.tenant,sessionIsolation:C.sessionIsolation,runId:C.runId,leaseId:C.leaseId,lockPolicy:F.lockPolicy,lockPlatform:F.defaultPlatform,cwd:process.cwd(),debug:!!C.verbose},{transport:t.sendToDaemon}),q=async e=>await t.sendToDaemon({session:V,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:s,debug:!!C.verbose,cwd:process.cwd(),tenantId:C.tenant,runId:C.runId,leaseId:C.leaseId,sessionIsolation:C.sessionIsolation,lockPolicy:F.lockPolicy,lockPlatform:F.defaultPlatform}});try{if("batch"===P){let e,t,s;if(_.length>0)throw new $("INVALID_ARGS","batch does not accept positional arguments.");let r=(function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=I.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new $("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return d(t)})(C).map((e,t)=>({...e,flags:F.lockPolicy&&void 0===C.platform?{...e.flags??{}}:e_(e.flags??{},{policyOverrides:C,configuredPlatform:C.platform,configuredSession:C.session,inheritedPlatform:C.platform})})),o={...T,batchSteps:r};delete o.steps,delete o.stepsFile;let a=await q({command:"batch",positionals:_,flags:o});if(!a.ok)throw new $(a.error.code,a.error.message,{...a.error.details??{},hint:a.error.hint,diagnosticId:a.error.diagnosticId,logPath:a.error.logPath});C.json?ey({success:!0,data:a.data??{}}):(A=a.data??{},e="number"==typeof A.total?A.total:0,t="number"==typeof A.executed?A.executed:0,s="number"==typeof A.totalDurationMs?A.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${t}/${e} steps${void 0!==s?` in ${s}ms`:""}
|
|
53
|
+
`)),U&&U();return}if("runtime"===P)throw new $("INVALID_ARGS","runtime command was removed. Use open --remote-config <path> --relaunch for remote Metro launches, or metro prepare --remote-config <path> for inspection.");if(await ex({command:P,positionals:_,flags:C,client:B})){U&&U();return}let e=await q({command:P,positionals:_,flags:T});if(e.ok){if(C.json){ey({success:!0,data:e.data??{}}),U&&U();return}if("snapshot"===P){process.stdout.write(eb(e.data??{},{raw:C.snapshotRaw,flatten:C.snapshotInteractiveOnly})),U&&U();return}if("diff"===P&&"snapshot"===_[0]){process.stdout.write(function(e){var t,s,r,o;let a=!0===e.baselineInitialized,i=e.summary??{},n=ev(i.additions),l=ev(i.removals),p=ev(i.unchanged),u=eD();if(a)return`Baseline initialized (${p} lines).
|
|
54
|
+
`;let d=(function(e,t){if(0===e.length)return e;let s=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===s.length)return e;let r=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),o=Math.min(e.length-1,t+1);for(let e=s;e<=o;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(e.lines)?e.lines:[],1).map(e=>{var t,s,r,o;let a="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=a.startsWith(" ")?`+${a}`:`+ ${a}`;return u?(t=e,s="green",c(s,t)):e}if("removed"===e.kind){let e=a.startsWith(" ")?`-${a}`:`- ${a}`;return u?(r=e,c("red",r)):e}return u?(o=a,c("dim",o)):a}),m=d.length>0?`${d.join("\n")}
|
|
55
|
+
`:"";if(!u)return`${m}${n} additions, ${l} removals, ${p} unchanged
|
|
56
|
+
`;let g=`${(t=String(n),s="green",c(s,t))} additions, ${(r=String(l),c("red",r))} removals, ${(o=String(p),c("dim",o))} unchanged`;return`${m}${g}
|
|
57
57
|
`}(e.data??{})),U&&U();return}if("get"===P){let t=_[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
|
|
58
58
|
`),U&&U();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
59
59
|
`),U&&U();return}}if("find"===P){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
|
|
@@ -87,7 +87,7 @@ ${n.join("\n\n")}
|
|
|
87
87
|
`),U&&U();return}if("android"===e){process.stdout.write(`Foreground app: ${a??"unknown"}
|
|
88
88
|
`),i&&process.stdout.write(`Activity: ${i}
|
|
89
89
|
`),U&&U();return}}if("perf"===P){process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
90
|
-
`),U&&U();return}}U&&U();return}throw new
|
|
90
|
+
`),U&&U();return}}U&&U();return}throw new $(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(s){let e=k(s),t=h(e,{diagnosticId:b().diagnosticId,logPath:N({force:!0})??void 0});if("close"===P&&"COMMAND_FAILED"===(L=e).code&&(L.details?.kind==="daemon_startup_failed"||L.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof L.details?.infoPath||"string"==typeof L.details?.lockPath))){C.json&&ey({success:!0,data:{closed:"session",source:"no-daemon"}}),U&&U();return}if(C.json)ey({success:!1,error:t});else if(ew(t,{showDetails:C.verbose}),C.verbose)try{let e=j.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(`
|
|
91
91
|
[daemon log]
|
|
92
92
|
${s}
|
|
93
|
-
`)}}catch{}U&&U(),process.exit(1)}})}
|
|
93
|
+
`)}}catch{}U&&U(),process.exit(1)}})}A(process.argv[1]??"").href===import.meta.url&&eU(process.argv.slice(2)).catch(e=>{ew(h(k(e)),{showDetails:!0}),process.exit(1)}),eU(process.argv.slice(2));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DeviceInfo } from '../utils/device.ts';
|
|
2
|
+
import type { SessionSurface } from './session-surface.ts';
|
|
2
3
|
import type { CliFlags } from '../utils/command-schema.ts';
|
|
3
4
|
import { shouldUseIosTapSeries, shouldUseIosDragSeries } from './dispatch-series.ts';
|
|
4
5
|
export { resolveTargetDevice } from './dispatch-resolve.ts';
|
|
@@ -32,4 +33,5 @@ export declare function dispatchCommand(device: DeviceInfo, command: string, pos
|
|
|
32
33
|
clickButton?: 'primary' | 'secondary' | 'middle';
|
|
33
34
|
pauseMs?: number;
|
|
34
35
|
pattern?: 'one-way' | 'ping-pong';
|
|
36
|
+
surface?: SessionSurface;
|
|
35
37
|
}): Promise<Record<string, unknown> | void>;
|
|
@@ -4,5 +4,6 @@ export declare const SETTINGS_FACEID_USAGE = "faceid <match|nonmatch|enroll|unen
|
|
|
4
4
|
export declare const SETTINGS_TOUCHID_USAGE = "touchid <match|nonmatch|enroll|unenroll>";
|
|
5
5
|
export declare const SETTINGS_FINGERPRINT_USAGE = "fingerprint <match|nonmatch>";
|
|
6
6
|
export declare const SETTINGS_PERMISSION_USAGE = "permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]";
|
|
7
|
+
export declare const SETTINGS_MACOS_PERMISSION_USAGE = "permission <grant|reset> <accessibility|screen-recording|input-monitoring>";
|
|
7
8
|
export declare const SETTINGS_USAGE_OVERRIDE: string;
|
|
8
|
-
export declare const SETTINGS_INVALID_ARGS_MESSAGE = "settings requires <wifi|airplane|location> <on|off>, appearance <light|dark|toggle>, faceid <match|nonmatch|enroll|unenroll>, touchid <match|nonmatch|enroll|unenroll>, fingerprint <match|nonmatch>,
|
|
9
|
+
export declare const SETTINGS_INVALID_ARGS_MESSAGE = "settings requires <wifi|airplane|location> <on|off>, appearance <light|dark|toggle>, faceid <match|nonmatch|enroll|unenroll>, touchid <match|nonmatch|enroll|unenroll>, 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], or permission <grant|reset> <accessibility|screen-recording|input-monitoring>";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import { type AppLogResult } from './app-log-process.ts';
|
|
3
|
-
export declare function
|
|
3
|
+
export declare function buildAppleLogPredicate(appBundleId: string): string;
|
|
4
4
|
export declare function buildIosDeviceLogStreamArgs(deviceId: string): string[];
|
|
5
5
|
export declare function startIosSimulatorAppLog(appBundleId: string, stream: fs.WriteStream, redactionPatterns: RegExp[], pidPath?: string): Promise<AppLogResult>;
|
|
6
|
+
export declare function startMacOsAppLog(appBundleId: string, stream: fs.WriteStream, redactionPatterns: RegExp[], pidPath?: string): Promise<AppLogResult>;
|
|
6
7
|
export declare function startIosDeviceAppLog(deviceId: string, stream: fs.WriteStream, redactionPatterns: RegExp[], pidPath?: string): Promise<AppLogResult>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export declare const APP_LOG_PID_FILENAME = "app-log.pid";
|
|
2
2
|
export type AppLogResult = {
|
|
3
|
-
backend: 'ios-simulator' | 'ios-device' | 'android';
|
|
3
|
+
backend: 'ios-simulator' | 'ios-device' | 'android' | 'macos';
|
|
4
4
|
getState: () => 'active' | 'failed';
|
|
5
5
|
startedAt: number;
|
|
6
6
|
stop: () => Promise<void>;
|
|
@@ -3,7 +3,7 @@ import type { AppLogResult } from './app-log-process.ts';
|
|
|
3
3
|
export type { AppLogResult } from './app-log-process.ts';
|
|
4
4
|
export { APP_LOG_PID_FILENAME, cleanupStaleAppLogProcesses } from './app-log-process.ts';
|
|
5
5
|
export { assertAndroidPackageArgSafe } from './app-log-android.ts';
|
|
6
|
-
export {
|
|
6
|
+
export { buildAppleLogPredicate, buildIosDeviceLogStreamArgs } from './app-log-ios.ts';
|
|
7
7
|
export type AppLogDoctorResult = {
|
|
8
8
|
checks: Record<string, boolean>;
|
|
9
9
|
notes: string[];
|