agent-device 0.6.2 → 0.6.3
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 +24 -1
- package/dist/src/735.js +3 -0
- package/dist/src/bin.js +34 -34
- package/dist/src/daemon.js +25 -22
- package/package.json +1 -1
- package/skills/agent-device/SKILL.md +6 -1
- package/dist/src/350.js +0 -3
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ The project is in early development and considered experimental. Pull requests a
|
|
|
14
14
|
|
|
15
15
|
## Features
|
|
16
16
|
- Platforms: iOS (simulator + physical device core automation) and Android (emulator + device).
|
|
17
|
-
- Core commands: `open`, `back`, `home`, `app-switcher`, `press`, `long-press`, `focus`, `type`, `fill`, `scroll`, `scrollintoview`, `wait`, `alert`, `screenshot`, `close`, `reinstall`.
|
|
17
|
+
- Core commands: `open`, `back`, `home`, `app-switcher`, `press`, `long-press`, `focus`, `type`, `fill`, `scroll`, `scrollintoview`, `wait`, `alert`, `screenshot`, `close`, `reinstall`, `push`.
|
|
18
18
|
- Inspection commands: `snapshot` (accessibility tree), `diff snapshot` (structural baseline diff), `appstate`, `apps`, `devices`.
|
|
19
19
|
- App logs: `logs path` returns session log metadata; `logs start` / `logs stop` stream app output; `logs clear` truncates session app logs; `logs clear --restart` resets and restarts stream in one step; `logs doctor` checks readiness; `logs mark` writes timeline markers.
|
|
20
20
|
- Device tooling: `adb` (Android), `simctl`/`devicectl` (iOS via Xcode).
|
|
@@ -140,6 +140,7 @@ agent-device scrollintoview @e42
|
|
|
140
140
|
|
|
141
141
|
## Command Index
|
|
142
142
|
- `boot`, `open`, `close`, `reinstall`, `home`, `back`, `app-switcher`
|
|
143
|
+
- `push`
|
|
143
144
|
- `batch`
|
|
144
145
|
- `snapshot`, `diff snapshot`, `find`, `get`
|
|
145
146
|
- `press` (alias: `click`), `focus`, `type`, `fill`, `long-press`, `swipe`, `scroll`, `scrollintoview`, `pinch`, `is`
|
|
@@ -147,10 +148,31 @@ agent-device scrollintoview @e42
|
|
|
147
148
|
- `trace start`, `trace stop`
|
|
148
149
|
- `logs path`, `logs start`, `logs stop`, `logs clear`, `logs clear --restart`, `logs doctor`, `logs mark` (session app log file for grep; iOS simulator + iOS device + Android)
|
|
149
150
|
- `settings wifi|airplane|location on|off`
|
|
151
|
+
- `settings appearance light|dark|toggle`
|
|
150
152
|
- `settings faceid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
151
153
|
- `settings permission grant|deny|reset camera|microphone|photos|contacts|notifications [full|limited]`
|
|
152
154
|
- `appstate`, `apps`, `devices`, `session list`
|
|
153
155
|
|
|
156
|
+
Push notification simulation:
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
# iOS simulator: app bundle + payload file
|
|
160
|
+
agent-device push com.example.app ./payload.apns --platform ios --device "iPhone 16"
|
|
161
|
+
|
|
162
|
+
# iOS simulator: inline JSON payload
|
|
163
|
+
agent-device push com.example.app '{"aps":{"alert":"Welcome","badge":1}}' --platform ios
|
|
164
|
+
|
|
165
|
+
# Android: package + payload (action/extras map)
|
|
166
|
+
agent-device push com.example.app '{"action":"com.example.app.PUSH","extras":{"title":"Welcome","unread":3,"promo":true}}' --platform android
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Payload notes:
|
|
170
|
+
- iOS uses `xcrun simctl push <device> <bundle> <payload>` and requires APNs-style JSON object (for example `{"aps":{"alert":"..."}}`).
|
|
171
|
+
- Android uses `adb shell am broadcast` with payload JSON shape:
|
|
172
|
+
`{"action":"<intent-action>","receiver":"<optional component>","extras":{"key":"value","flag":true,"count":3}}`.
|
|
173
|
+
- Android extras support string/boolean/number values.
|
|
174
|
+
- `push` works with session context (uses session device) or explicit device selectors.
|
|
175
|
+
|
|
154
176
|
## iOS Snapshots
|
|
155
177
|
|
|
156
178
|
Notes:
|
|
@@ -299,6 +321,7 @@ Settings helpers:
|
|
|
299
321
|
- `settings wifi on|off`
|
|
300
322
|
- `settings airplane on|off`
|
|
301
323
|
- `settings location on|off` (iOS uses per-app permission for the current session app)
|
|
324
|
+
- `settings appearance light|dark|toggle` (iOS simulator appearance + Android night mode)
|
|
302
325
|
- `settings permission grant|deny|reset <camera|microphone|photos|contacts|notifications> [full|limited]` (session app required)
|
|
303
326
|
Note: iOS supports these only on simulators. iOS wifi/airplane toggles status bar indicators, not actual network state. Airplane off clears status bar overrides.
|
|
304
327
|
- iOS permission targets map to `simctl privacy`: `camera`, `microphone`, `photos` (`full` => `photos`, `limited` => `photos-add`), `contacts`, `notifications`.
|
package/dist/src/735.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r,{promises as n}from"node:fs";import o from"node:os";import i from"node:path";import{fileURLToPath as a,pathToFileURL as s}from"node:url";import{spawn as c,spawnSync as l}from"node:child_process";let d=new e,u=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,f=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function m(){return t.randomBytes(8).toString("hex")}async function p(e,r){let n={...e,diagnosticId:`${Date.now().toString(36)}-${t.randomBytes(4).toString("hex")}`,events:[]};return await d.run(n,r)}function h(){let e=d.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function g(e){let t=d.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?y(e.data):void 0};if(t.events.push(n),!t.debug)return;let o=`[agent-device][diag] ${JSON.stringify(n)}
|
|
2
|
+
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function w(e,t,r){let n=Date.now();try{let o=await t();return g({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw g({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function S(e={}){let t=d.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),n=new Date().toISOString().slice(0,10),a=i.join(o.homedir(),".agent-device","logs",e,n);r.mkdirSync(a,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),c=i.join(a,`${s}-${t.diagnosticId}.ndjson`),l=t.events.map(e=>JSON.stringify(y(e)));return r.writeFileSync(c,`${l.join("\n")}
|
|
3
|
+
`),t.events=[],c}catch{return null}}function y(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&u.test(i)||f.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let a={};for(let[n,o]of Object.entries(t)){if(u.test(n)){a[n]="[REDACTED]";continue}a[n]=e(o,r,n)}return a}(e,new WeakSet)}class A extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function I(e){return e instanceof A?e:e instanceof Error?new A("UNKNOWN",e.message,void 0,e):new A("UNKNOWN","Unknown error",{err:e})}function E(e,t={}){let r=I(e),n=r.details?y(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,a=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,s=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),c=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n),l=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:l,hint:s,diagnosticId:i,logPath:a,details:c}}let v="<wifi|airplane|location> <on|off>",D="appearance <light|dark|toggle>",b="faceid <match|nonmatch|enroll|unenroll>",N="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",$=`settings ${v} | settings ${D} | settings ${b} | settings ${N}`,_=`settings requires ${v}, ${D}, ${b}, or ${N}`;function M(e){let t=[],r=[];for(let n of e){let e=n.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let o=n.label?.trim()||n.value?.trim()||n.identifier?.trim()||"",i=L(n.type??"Element"),a="group"===i&&!o;a&&t.push(e);let s=a?e:Math.max(0,e-t.length);r.push({node:n,depth:s,type:i,text:O(n,s,a,i)})}return r}function O(e,t,r,n){let o=n??L(e.type??"Element"),i=T(e,o),a=" ".repeat(t),s=e.ref?`@${e.ref}`:"",c=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=c?` [${c}]`:"",d=i?` "${i}"`:"";return r?`${a}${s} [${o}]${l}`.trimEnd():`${a}${s} [${o}]${d}${l}`.trimEnd()}function T(e,t){var r,n;let o=e.label?.trim(),i=e.value?.trim();if("text-field"===(r=t)||"text-view"===r||"search"===r){if(i)return i;if(o)return o}else if(o)return o;if(i)return i;let a=e.identifier?.trim();return!a||(n=a,/^[\w.]+:id\/[\w.-]+$/i.test(n)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":a}function L(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 x(){try{let e=C();return JSON.parse(r.readFileSync(i.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function C(){let e=i.dirname(a(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=i.join(t,"package.json");if(r.existsSync(e))return t;t=i.dirname(t)}return e}async function R(e,t,r={}){return new Promise((n,o)=>{let i=c(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",s=r.binaryStdout?Buffer.alloc(0):void 0,l="",d=!1,u=j(r.timeoutMs),f=u?setTimeout(()=>{d=!0,i.kill("SIGKILL")},u):null;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{r.binaryStdout?s=Buffer.concat([s??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),i.stderr.on("data",e=>{l+=e}),i.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?o(new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{f&&clearTimeout(f);let c=i??1;d&&u?o(new A("COMMAND_FAILED",`${e} timed out after ${u}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:c,timeoutMs:u})):0===c||r.allowFailure?n({stdout:a,stderr:l,exitCode:c,stdoutBuffer:s}):o(new A("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:c,processExitError:!0}))})})}async function F(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await R(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function P(e,t,r={}){let n=l(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:j(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new A("COMMAND_FAILED",`${e} timed out after ${j(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:j(r.timeoutMs)},n.error);if("ENOENT"===o)throw new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let o=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,i=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),s=n.status??1;if(0!==s&&!r.allowFailure)throw new A("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:i,stderr:a,exitCode:s,processExitError:!0});return{stdout:i,stderr:a,exitCode:s,stdoutBuffer:o}}function k(e,t,r={}){c(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function B(e,t,r={}){return new Promise((n,o)=>{let i=c(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(i);let a="",s="",l=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{if(r.binaryStdout){l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),i.stderr.on("data",e=>{let t=String(e);s+=t,r.onStderrChunk?.(t)}),i.on("error",r=>{"ENOENT"===r.code?o(new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{let c=i??1;0===c||r.allowFailure?n({stdout:a,stderr:s,exitCode:c,stdoutBuffer:l}):o(new A("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:a,stderr:s,exitCode:c,processExitError:!0}))})})}function G(e,t,r={}){let n=c(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),o="",i="";n.stdout.setEncoding("utf8"),n.stderr.setEncoding("utf8"),n.stdout.on("data",e=>{o+=e}),n.stderr.on("data",e=>{i+=e});let a=new Promise((a,s)=>{n.on("error",r=>{"ENOENT"===r.code?s(new A("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):s(new A("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),n.on("close",n=>{let c=n??1;0===c||r.allowFailure?a({stdout:o,stderr:i,exitCode:c}):s(new A("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:o,stderr:i,exitCode:c,processExitError:!0}))})});return{child:n,wait:a}}function j(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let U=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function V(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function q(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=P("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 H(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=P("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(!V(e))return!1;if(t){let r=q(e);if(!r||r!==t)return!1}let n=H(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&U.some(e=>e.test(r))}function W(e,t){try{return process.kill(e,t),!0}catch(t){let e=t.code;if("ESRCH"===e||"EPERM"===e)return!1;throw t}}async function z(e,t){if(!V(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!V(e))return!0;return!V(e)}async function K(e,t){!J(e,t.expectedStartTime)||!W(e,"SIGTERM")||await z(e,t.termTimeoutMs)||W(e,"SIGKILL")&&await z(e,t.killTimeoutMs)}let X=100,Z=new Set(["batch","replay"]);function Q(e){let t;try{t=JSON.parse(e)}catch{throw new A("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new A("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function Y(e,t){if(!Array.isArray(e)||0===e.length)throw new A("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new A("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let r=[];for(let t=0;t<e.length;t+=1){let n=e[t];if(!n||"object"!=typeof n)throw new A("INVALID_ARGS",`Invalid batch step at index ${t}.`);let o="string"==typeof n.command?n.command.trim().toLowerCase():"";if(!o)throw new A("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(Z.has(o))throw new A("INVALID_ARGS",`Batch step ${t+1} cannot run ${o}.`);if(void 0!==n.positionals&&!Array.isArray(n.positionals))throw new A("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let i=n.positionals??[];if(i.some(e=>"string"!=typeof e))throw new A("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==n.flags&&("object"!=typeof n.flags||Array.isArray(n.flags)||!n.flags))throw new A("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);r.push({command:o,positionals:i,flags:n.flags??{}})}return r}export{default as node_net}from"node:net";export{A as AppError,X as DEFAULT_BATCH_MAX_STEPS,_ as SETTINGS_INVALID_ARGS_MESSAGE,$ as SETTINGS_USAGE_OVERRIDE,I as asAppError,M as buildSnapshotDisplayLines,m as createRequestId,T as displayLabel,g as emitDiagnostic,a as fileURLToPath,C as findProjectRoot,S as flushDiagnosticsToSessionFile,L as formatRole,O as formatSnapshotLine,h as getDiagnosticsMeta,J as isAgentDeviceDaemonProcess,V as isProcessAlive,t as node_crypto,r as node_fs,o as node_os,i as node_path,E as normalizeError,Q as parseBatchStepsJson,s as pathToFileURL,n as promises,H as readProcessCommand,q as readProcessStartTime,x as readVersion,R as runCmd,G as runCmdBackground,k as runCmdDetached,B as runCmdStreaming,P as runCmdSync,c as spawn,K as stopProcessForTakeover,Y as validateAndNormalizeBatchSteps,F as whichCmd,w as withDiagnosticTimer,p as withDiagnosticsScope};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{styleText as e}from"node:util";import{createRequestId as t,node_path as s,buildSnapshotDisplayLines as a,parseBatchStepsJson as r,normalizeError as i,isAgentDeviceDaemonProcess as o,runCmdDetached as n,readVersion as l,findProjectRoot as p,getDiagnosticsMeta as d,runCmdSync as c,withDiagnosticTimer as u,emitDiagnostic as g,asAppError as m,pathToFileURL as f,AppError as h,node_fs as y,node_os as w,node_net as v,withDiagnosticsScope as b,flushDiagnosticsToSessionFile as $,stopProcessForTakeover as k,formatSnapshotLine as S}from"./350.js";let A=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],x=["snapshotDepth","snapshotScope","snapshotRaw"],D=[{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","android"],usageLabel:"--platform ios|android",usageDescription:"Platform to target"},{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:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"}],I=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),F={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:[]},open:{description:"Boot device/simulator; optionally launch app or deep link URL",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{description:"Close app or just end session",positionalArgs:["app?"],allowedFlags:["saveScript"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...A]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[...A]},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (includes default/system apps by default)",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{description:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},back:{description:"Navigate back (where supported)",positionalArgs:[],allowedFlags:[]},home:{description:"Go to home screen (where supported)",positionalArgs:[],allowedFlags:[]},"app-switcher":{description:"Open app switcher (where supported)",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",description:"Wait for duration, text, ref, or selector to appear",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...x]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...x]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...x]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...x]},longpress:{description:"Long press by coordinates (iOS and Android)",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{description:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{description:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{description:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",description:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...x]},scroll:{description:"Scroll in direction (0-1 amount)",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",description:"Scroll until text appears or a snapshot ref is brought into view",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{description:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{description:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},record:{usageOverride:"record start [path] [--fps <n>] | record stop",description:"Start/stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps"]},trace:{usageOverride:"trace start [path] | trace stop [path]",description:"Start/stop trace log capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",description:"Session app log info, start/stop streaming, diagnostics, and markers",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},find:{usageOverride:"find <locator|text> <action> [value]",description:"Find by text/label/value/role/id and run action",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{description:"Assert UI state (visible|hidden|exists|editable|selected|text)",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...x]},settings:{usageOverride:"settings <wifi|airplane|location> <on|off> | settings faceid <match|nonmatch|enroll|unenroll> | settings permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",description:"Toggle OS settings and app permissions (session app scope for permission actions)",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},L=new Map,O=new Map;for(let e of D){for(let t of e.names)L.set(t,e);let t=O.get(e.key);t?t.push(e):O.set(e.key,[e])}function N(e){if(e)return F[e]}function j(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function _(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(j),...t.allowedFlags.flatMap(e=>(O.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let E=function(){let e=`agent-device <command> [args] [--json]
|
|
1
|
+
import{styleText as e}from"node:util";import{buildSnapshotDisplayLines as t,node_path as s,createRequestId as a,parseBatchStepsJson as r,normalizeError as i,isAgentDeviceDaemonProcess as o,runCmdDetached as n,readVersion as l,findProjectRoot as p,getDiagnosticsMeta as d,runCmdSync as c,withDiagnosticTimer as u,emitDiagnostic as g,SETTINGS_USAGE_OVERRIDE as m,asAppError as f,pathToFileURL as h,AppError as y,node_fs as w,node_os as v,node_net as b,withDiagnosticsScope as $,flushDiagnosticsToSessionFile as k,stopProcessForTakeover as S,formatSnapshotLine as A}from"./735.js";let x=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],D=["snapshotDepth","snapshotScope","snapshotRaw"],I=[{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","android"],usageLabel:"--platform ios|android",usageDescription:"Platform to target"},{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:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"}],F=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),L={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:[]},open:{description:"Boot device/simulator; optionally launch app or deep link URL",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{description:"Close app or just end session",positionalArgs:["app?"],allowedFlags:["saveScript"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...x]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[...x]},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (includes default/system apps by default)",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{description:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},back:{description:"Navigate back (where supported)",positionalArgs:[],allowedFlags:[]},home:{description:"Go to home screen (where supported)",positionalArgs:[],allowedFlags:[]},"app-switcher":{description:"Open app switcher (where supported)",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",description:"Wait for duration, text, ref, or selector to appear",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...D]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...D]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...D]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...D]},longpress:{description:"Long press by coordinates (iOS and Android)",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{description:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{description:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{description:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",description:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...D]},scroll:{description:"Scroll in direction (0-1 amount)",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",description:"Scroll until text appears or a snapshot ref is brought into view",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{description:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{description:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},record:{usageOverride:"record start [path] [--fps <n>] | record stop",description:"Start/stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps"]},trace:{usageOverride:"trace start [path] | trace stop [path]",description:"Start/stop trace log capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",description:"Session app log info, start/stop streaming, diagnostics, and markers",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},find:{usageOverride:"find <locator|text> <action> [value]",description:"Find by text/label/value/role/id and run action",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{description:"Assert UI state (visible|hidden|exists|editable|selected|text)",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...D]},settings:{usageOverride:m,description:"Toggle OS settings, appearance, and app permissions (session app scope for permission actions)",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},O=new Map,N=new Map;for(let e of I){for(let t of e.names)O.set(t,e);let t=N.get(e.key);t?t.push(e):N.set(e.key,[e])}function j(e){if(e)return L[e]}function _(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function E(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(_),...t.allowedFlags.flatMap(e=>(N.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let M=function(){let e=`agent-device <command> [args] [--json]
|
|
2
2
|
|
|
3
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=Object.keys(
|
|
4
|
+
`,t=Object.keys(L).map(e=>{let t=L[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:E(e,t)}}),s=Math.max(...t.map(e=>e.usage.length))+2,a=["Commands:"];for(let e of t)a.push(` ${e.usage.padEnd(s)}${e.schema.description}`);let r=P("Flags:",I.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
5
|
${a.join("\n")}
|
|
6
6
|
|
|
7
7
|
${r}
|
|
8
|
-
`}();function
|
|
9
|
-
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,a=[e];for(let e of t)a.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return a.join("\n")}function R(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function
|
|
10
|
-
`)}function
|
|
8
|
+
`}();function T(e){return I.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function P(e,t){if(0===t.length)return`${e}
|
|
9
|
+
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,a=[e];for(let e of t)a.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return a.join("\n")}function R(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function C(e){return e.replace(/^-+/,"")}function V(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?R(e):[e,void 0];return void 0!==O.get(t)}function G(e){return"long-press"===e?"longpress":e}function q(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
|
+
`)}function B(e,t={}){let s=e instanceof y?i(e):e;process.stderr.write(`Error (${s.code}): ${s.message}
|
|
11
11
|
`),s.hint&&process.stderr.write(`Hint: ${s.hint}
|
|
12
12
|
`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}
|
|
13
13
|
`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}
|
|
14
14
|
`),t.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}
|
|
15
|
-
`)}function
|
|
16
|
-
`)}),i=setTimeout(()=>{r.destroy();let s=function(){let e=0;try{for(let t of
|
|
17
|
-
`);
|
|
18
|
-
`),process.exit(0));let b="help"===
|
|
19
|
-
`),process.exit(0));let t=function(e){let t=
|
|
15
|
+
`)}function U(e){return"number"==typeof e&&Number.isFinite(e)?e:0}let W=s.join(v.homedir(),".agent-device"),J=s.join(W,"daemon.json"),z=s.join(W,"daemon.lock"),K=function(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}(),H=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function X(e){let t=e.meta?.requestId??a(),s=!!(e.meta?.debug||e.flags?.verbose),r=await u("daemon_startup",async()=>await Z(),{requestId:t,session:e.session}),i={...e,token:r.token,meta:{requestId:t,debug:s,cwd:e.meta?.cwd}};return g({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await u("daemon_request",async()=>await ep(r,i),{requestId:t,command:e.command})}async function Z(){var e;let t,a=et(),r=l(),i=function(e,t=p()){try{let a=w.statSync(e),r=s.relative(t,e)||e;return`${r}:${a.size}:${Math.trunc(a.mtimeMs)}`}catch{return"unknown"}}((t=el()).useSrc?t.srcPath:t.distPath,t.root),n=!!a&&await eo(a);if(a&&a.version===r&&a.codeSignature===i&&n)return a;a&&(a.version!==r||a.codeSignature!==i||!n)&&(await ee(a),ei(J)),function(){let e=ea();if(!e.hasLock||e.hasInfo)return;let t=es();t&&o(t.pid,t.processStartTime)||ei(z)}(),await en();let d=await Y(5e3);if(d)return d;if(await Q()){await en();let e=await Y(5e3);if(e)return e}throw new y("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:J,lockPath:z,hint:(e=ea()).hasLock&&!e.hasInfo?"Detected ~/.agent-device/daemon.lock without daemon.json. If no agent-device daemon process is running, delete ~/.agent-device/daemon.lock and retry.":e.hasLock&&e.hasInfo?"Daemon metadata may be stale. If no agent-device daemon process is running, delete ~/.agent-device/daemon.json and ~/.agent-device/daemon.lock, then retry.":"Daemon metadata is missing or stale. Delete ~/.agent-device/daemon.json if present and retry."})}async function Y(e){let t=Date.now();for(;Date.now()-t<e;){let e=et();if(e&&await eo(e))return e;await new Promise(e=>setTimeout(e,100))}return null}async function Q(){let e=ea();if(!e.hasLock||e.hasInfo)return!1;let t=es();return t&&o(t.pid,t.processStartTime)&&await S(t.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:t.processStartTime}),ei(z),!0}async function ee(e){await S(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function et(){let e=er(J);return e&&e.port&&e.token?{...e,pid:Number.isInteger(e.pid)&&e.pid>0?e.pid:0}:null}function es(){let e=er(z);return e&&Number.isInteger(e.pid)&&!(e.pid<=0)?e:null}function ea(){return{hasInfo:w.existsSync(J),hasLock:w.existsSync(z)}}function er(e){if(!w.existsSync(e))return null;try{return JSON.parse(w.readFileSync(e,"utf8"))}catch{return null}}function ei(e){try{w.existsSync(e)&&w.unlinkSync(e)}catch{}}async function eo(e){return new Promise(t=>{let s=b.createConnection({host:"127.0.0.1",port:e.port},()=>{s.destroy(),t(!0)});s.on("error",()=>{t(!1)})})}async function en(){let e=el(),t=e.useSrc?["--experimental-strip-types",e.srcPath]:[e.distPath];n(process.execPath,t)}function el(){let e=p(),t=s.join(e,"dist","src","daemon.js"),a=s.join(e,"src","daemon.ts"),r=w.existsSync(t),i=w.existsSync(a);if(!r&&!i)throw new y("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:a});return{root:e,distPath:t,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!r&&i}}async function ep(e,t){return new Promise((s,a)=>{let r=b.createConnection({host:"127.0.0.1",port:e.port},()=>{r.write(`${JSON.stringify(t)}
|
|
16
|
+
`)}),i=setTimeout(()=>{r.destroy();let s=function(){let e=0;try{for(let t of H){let s=c("pkill",["-f",t],{allowFailure:!0});0===s.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),i=function(e){let t=!1;try{o(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),t=!0)}catch{S(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{ei(J),ei(z)}return{forcedKill:t}}(e);g({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:K,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:e.pid,daemonPidForceKilled:i.forcedKill}}),a(new y("COMMAND_FAILED","Daemon request timed out",{timeoutMs:K,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},K),n="";r.setEncoding("utf8"),r.on("data",e=>{let o=(n+=e).indexOf("\n");if(-1===o)return;let l=n.slice(0,o).trim();if(l)try{let e=JSON.parse(l);r.end(),clearTimeout(i),s(e)}catch(e){clearTimeout(i),a(new y("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),r.on("error",e=>{clearTimeout(i),g({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),a(new y("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))})})}let ed={sendToDaemon:X};async function ec(o,n=ed){let p=a(),c=o.includes("--debug")||o.includes("--verbose")||o.includes("-v"),u=o.includes("--json"),m=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}(o)??process.env.AGENT_DEVICE_SESSION??"default";await $({session:m,requestId:p,command:o[0],debug:c},async()=>{var a,m;let h;try{h=function(e,t){let s=(void 0)??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),a={json:!1,help:!1,version:!1},r=null,i=[],o=[],n=[],l=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(l&&"--"===s){l=!1;continue}if(!l){r?i.push(s):r=G(s);continue}let o=s.startsWith("--"),p=s.startsWith("-")&&s.length>1;if(!o&&!p){r?i.push(s):r=G(s);continue}let[d,c]=o?R(s):[s,void 0],u=O.get(d);if(!u){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let r=j(e);return!r||!!r.allowsExtraPositionals||0!==r.positionalArgs.length&&(t.length<r.positionalArgs.length||r.positionalArgs.some(e=>e.includes("?")))}(r,i,s)){r?i.push(s):r=s;continue}throw new y("INVALID_ARGS",`Unknown flag: ${d}`)}let g=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new y("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:e.setValue,consumeNext:!1}}if("boolean"===e.type){if(void 0!==s)throw new y("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}if("booleanOrString"===e.type){if(void 0!==s){if(0===s.trim().length)throw new y("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||V(a)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let r=s??a;if(void 0===r||void 0===s&&V(r))throw new y("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:r,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(r))throw new y("INVALID_ARGS",`Invalid ${C(t)}: ${r}`);return{value:r,consumeNext:void 0===s}}let i=Number(r);if(!Number.isFinite(i)||"number"==typeof e.min&&i<e.min||"number"==typeof e.max&&i>e.max)throw new y("INVALID_ARGS",`Invalid ${C(t)}: ${r}`);return{value:Math.floor(i),consumeNext:void 0===s}}(u,d,c,e[t+1]);g.consumeNext&&(t+=1),a[u.key]=g.value,n.push({key:u.key,token:d})}let p=j(r),d=new Set([...F,...p?.allowedFlags??[]]),c=n.filter(e=>!d.has(e.key));if(c.length>0){var u,g;let e=(u=r,g=c.map(e=>e.token),u?1===g.length?`Flag ${g[0]} is not supported for command ${u}.`:`Flags ${g.join(", ")} are not supported for command ${u}.`:1===g.length?`Flag ${g[0]} requires a command that supports it.`:`Flags ${g.join(", ")} require a command that supports them.`);if(s)throw new y("INVALID_ARGS",e);for(let t of(o.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),c))delete a[t.key]}if(p?.defaults)for(let[e,t]of Object.entries(p.defaults))void 0===a[e]&&(a[e]=t);if("batch"===r&&1!=+!!a.steps+ +!!a.stepsFile)throw new y("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:r,positionals:i,flags:a,warnings:o}}(o)}catch(t){g({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=i(t,{diagnosticId:d().diagnosticId,logPath:k({force:!0})??void 0});u?q({success:!1,error:e}):B(e,{showDetails:c}),process.exit(1);return}for(let e of h.warnings)process.stderr.write(`Warning: ${e}
|
|
17
|
+
`);h.flags.version&&(process.stdout.write(`${l()}
|
|
18
|
+
`),process.exit(0));let b="help"===h.command,$=h.flags.help;if(b||$){b&&h.positionals.length>1&&(B(new y("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=b?h.positionals[0]:h.command;e||(process.stdout.write(`${M}
|
|
19
|
+
`),process.exit(0));let t=function(e){let t=j(e);if(!t)return null;let s=E(e,t),a=T(new Set(t.allowedFlags)),r=T(F),i=[];return a.length>0&&i.push(P("Command flags:",a)),i.push(P("Global flags:",r)),`agent-device ${s}
|
|
20
20
|
|
|
21
21
|
${t.description}
|
|
22
22
|
|
|
@@ -24,43 +24,43 @@ Usage:
|
|
|
24
24
|
agent-device ${s}
|
|
25
25
|
|
|
26
26
|
${i.join("\n\n")}
|
|
27
|
-
`}(
|
|
28
|
-
`),process.exit(1)}
|
|
29
|
-
`),process.exit(1));let{command:
|
|
30
|
-
`)),
|
|
31
|
-
`),
|
|
27
|
+
`}(G(e));t&&(process.stdout.write(t),process.exit(0)),B(new y("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${M}
|
|
28
|
+
`),process.exit(1)}h.command||(process.stdout.write(`${M}
|
|
29
|
+
`),process.exit(1));let{command:S,positionals:x,flags:D}=h,I=function(e){let{json:t,help:s,version:a,...r}=e;return r}(D),L=D.session??process.env.AGENT_DEVICE_SESSION??"default",N=D.verbose&&!D.json?function(){try{let e=s.join(v.homedir(),".agent-device","daemon.log"),t=0,a=!1,r=setInterval(()=>{if(!a&&w.existsSync(e))try{let s=w.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let a=w.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);w.readSync(a,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{w.closeSync(a)}}catch{}},200);return()=>{a=!0,clearInterval(r)}}catch{return null}}():null,_=async e=>await n.sendToDaemon({session:L,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:p,debug:!!D.verbose,cwd:process.cwd()}});try{if("batch"===S){let e,t,s;if(x.length>0)throw new y("INVALID_ARGS","batch does not accept positional arguments.");let i=function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=w.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new y("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return r(t)}(D),o={...I,batchSteps:i};delete o.steps,delete o.stepsFile;let n=await _({command:"batch",positionals:x,flags:o});if(!n.ok)throw new y(n.error.code,n.error.message,{...n.error.details??{},hint:n.error.hint,diagnosticId:n.error.diagnosticId,logPath:n.error.logPath});D.json?q({success:!0,data:n.data??{}}):(a=n.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`:""}
|
|
30
|
+
`)),N&&N();return}if("session"===S){let e=x[0]??"list";if("list"!==e)throw new y("INVALID_ARGS","session only supports list");let t=await _({command:"session_list",positionals:[],flags:I});if(!t.ok)throw new y(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath});D.json?q({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
31
|
+
`),N&&N();return}let s=await _({command:S,positionals:x,flags:I});if(s.ok){if(D.json){q({success:!0,data:s.data??{}}),N&&N();return}if("snapshot"===S){process.stdout.write(function(e,s={}){let a=e.nodes,r=Array.isArray(a)?a:[],i=!!e.truncated,o="string"==typeof e.appName?e.appName:void 0,n="string"==typeof e.appBundleId?e.appBundleId:void 0,l=[];o&&l.push(`Page: ${o}`),n&&l.push(`App: ${n}`);let p=`Snapshot: ${r.length} nodes${i?" (truncated)":""}`,d=l.length>0?`${l.join("\n")}
|
|
32
32
|
`:"";if(0===r.length)return`${d}${p}
|
|
33
|
-
`;if(
|
|
33
|
+
`;if(s.raw){let e=r.map(e=>JSON.stringify(e));return`${d}${p}
|
|
34
34
|
${e.join("\n")}
|
|
35
|
-
`}if(
|
|
35
|
+
`}if(s.flatten){let e=r.map(e=>A(e,0,!1));return`${d}${p}
|
|
36
36
|
${e.join("\n")}
|
|
37
|
-
`}let c=
|
|
37
|
+
`}let c=t(r).map(e=>e.text);return`${d}${p}
|
|
38
38
|
${c.join("\n")}
|
|
39
|
-
`}(s.data??{},{raw:D.snapshotRaw,flatten:D.snapshotInteractiveOnly})),
|
|
39
|
+
`}(s.data??{},{raw:D.snapshotRaw,flatten:D.snapshotInteractiveOnly})),N&&N();return}if("diff"===S&&"snapshot"===x[0]){process.stdout.write(function(t){var s,a,r,i;let o,n=!0===t.baselineInitialized,l=t.summary??{},p=U(l.additions),d=U(l.removals),c=U(l.unchanged),u=(o=process.env.FORCE_COLOR,"string"==typeof o?"0"!==o:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY);if(n)return`Baseline initialized (${c} lines).
|
|
40
40
|
`;let g=(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 a=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),r=Math.min(e.length-1,t+1);for(let e=s;e<=r;e+=1)a[e]=!0}return e.filter((e,t)=>a[t])})(Array.isArray(t.lines)?t.lines:[],1).map(t=>{var s,a,r,i;let o="string"==typeof t.text?t.text:"";if("added"===t.kind){let t=o.startsWith(" ")?`+${o}`:`+ ${o}`;return u?(s=t,a="green",e(a,s)):t}if("removed"===t.kind){let t=o.startsWith(" ")?`-${o}`:`- ${o}`;return u?(r=t,e("red",r)):t}return u?(i=o,e("dim",i)):o}),m=g.length>0?`${g.join("\n")}
|
|
41
41
|
`:"";if(!u)return`${m}${p} additions, ${d} removals, ${c} unchanged
|
|
42
42
|
`;let f=`${(s=String(p),a="green",e(a,s))} additions, ${(r=String(d),e("red",r))} removals, ${(i=String(c),e("dim",i))} unchanged`;return`${m}${f}
|
|
43
|
-
`}(s.data??{})),
|
|
44
|
-
`),
|
|
45
|
-
`),
|
|
46
|
-
`),
|
|
47
|
-
`),
|
|
48
|
-
`),
|
|
49
|
-
`),
|
|
50
|
-
`),
|
|
43
|
+
`}(s.data??{})),N&&N();return}if("get"===S){let e=x[0];if("text"===e){let e=s.data?.text??"";process.stdout.write(`${e}
|
|
44
|
+
`),N&&N();return}if("attrs"===e){let e=s.data?.node??{};process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
45
|
+
`),N&&N();return}}if("find"===S){let e=s.data;if("string"==typeof e?.text){process.stdout.write(`${e.text}
|
|
46
|
+
`),N&&N();return}if("boolean"==typeof e?.found){process.stdout.write(`Found: ${e.found}
|
|
47
|
+
`),N&&N();return}if(e?.node){process.stdout.write(`${JSON.stringify(e.node,null,2)}
|
|
48
|
+
`),N&&N();return}}if("is"===S){let e=s.data?.predicate??"assertion";process.stdout.write(`Passed: is ${e}
|
|
49
|
+
`),N&&N();return}if("boot"===S){let e=s.data?.platform??"unknown",t=s.data?.device??s.data?.id??"unknown";process.stdout.write(`Boot ready: ${t} (${e})
|
|
50
|
+
`),N&&N();return}if("logs"===S){let e=s.data,t="string"==typeof e?.path?e.path:"";if(t){process.stdout.write(`${t}
|
|
51
51
|
`);let s="boolean"==typeof e?.active?e.active:void 0,a="string"==typeof e?.state?e.state:void 0,r="string"==typeof e?.backend?e.backend:void 0,i="number"==typeof e?.sizeBytes?e.sizeBytes:void 0,o=e?.started===!0,n=e?.stopped===!0,l=e?.marked===!0,p=e?.cleared===!0,d=e?.restarted===!0,c="number"==typeof e?.removedRotatedFiles?e.removedRotatedFiles:void 0;if(!D.json&&(void 0!==s||a||r||void 0!==i)){let e=[void 0!==s?`active=${s}`:"",a?`state=${a}`:"",r?`backend=${r}`:"",void 0!==i?`sizeBytes=${i}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
52
52
|
`)}if(!D.json&&(o||n||l||p||d||void 0!==c)){let e=[o?"started=true":"",n?"stopped=true":"",l?"marked=true":"",p?"cleared=true":"",d?"restarted=true":"",void 0!==c?`removedRotatedFiles=${c}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
53
53
|
`)}if(e?.hint&&!D.json&&process.stderr.write(`${e.hint}
|
|
54
54
|
`),Array.isArray(e?.notes)&&!D.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
|
|
55
|
-
`)}
|
|
56
|
-
`),
|
|
57
|
-
`),
|
|
58
|
-
`),
|
|
55
|
+
`)}N&&N();return}if("click"===S||"press"===S){let e=s.data?.ref??"",t=s.data?.x,a=s.data?.y;e&&"number"==typeof t&&"number"==typeof a&&process.stdout.write(`Tapped @${e} (${t}, ${a})
|
|
56
|
+
`),N&&N();return}if(s.data&&"object"==typeof s.data){let e=s.data;if("devices"===S){let t=(Array.isArray(e.devices)?e.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",s=e?.platform??"unknown",a=e?.kind?` ${e.kind}`:"",r="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${a})${r}`});process.stdout.write(`${t.join("\n")}
|
|
57
|
+
`),N&&N();return}if("apps"===S){let t=(Array.isArray(e.apps)?e.apps:[]).map(e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e.bundleId??e.package,s=e.name??e.label;return s&&t?`${s} (${t})`:t?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${t.join("\n")}
|
|
58
|
+
`),N&&N();return}if("appstate"===S){let t=e?.platform,s=e?.appBundleId,a=e?.appName,r=e?.source,i=e?.package,o=e?.activity;if("ios"===t){process.stdout.write(`Foreground app: ${a??s??"unknown"}
|
|
59
59
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
60
60
|
`),r&&process.stdout.write(`Source: ${r}
|
|
61
|
-
`),
|
|
61
|
+
`),N&&N();return}if("android"===t){process.stdout.write(`Foreground app: ${i??"unknown"}
|
|
62
62
|
`),o&&process.stdout.write(`Activity: ${o}
|
|
63
|
-
`),
|
|
63
|
+
`),N&&N();return}}}N&&N();return}throw new y(s.error.code,s.error.message,{...s.error.details??{},hint:s.error.hint,diagnosticId:s.error.diagnosticId,logPath:s.error.logPath})}catch(a){let e=f(a),t=i(e,{diagnosticId:d().diagnosticId,logPath:k({force:!0})??void 0});if("close"===S&&"COMMAND_FAILED"===(m=e).code&&(m.details?.kind==="daemon_startup_failed"||m.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof m.details?.infoPath||"string"==typeof m.details?.lockPath))){D.json&&q({success:!0,data:{closed:"session",source:"no-daemon"}}),N&&N();return}if(D.json)q({success:!1,error:t});else if(B(t,{showDetails:D.verbose}),D.verbose)try{let e=s.join(v.homedir(),".agent-device","daemon.log");if(w.existsSync(e)){let t=w.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
64
64
|
[daemon log]
|
|
65
65
|
${s}
|
|
66
|
-
`)}}catch{}
|
|
66
|
+
`)}}catch{}N&&N(),process.exit(1)}})}h(process.argv[1]??"").href===import.meta.url&&ec(process.argv.slice(2)).catch(e=>{B(i(f(e)),{showDetails:!0}),process.exit(1)}),ec(process.argv.slice(2));
|