agent-device 0.3.5 → 0.4.0
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 +45 -14
- package/dist/src/bin.js +35 -97
- package/dist/src/daemon.js +16 -15
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +24 -0
- package/ios-runner/README.md +1 -1
- package/package.json +1 -1
- package/skills/agent-device/SKILL.md +21 -11
- package/skills/agent-device/references/permissions.md +15 -1
- package/skills/agent-device/references/session-management.md +1 -0
- package/skills/agent-device/references/snapshot-refs.md +2 -0
- package/skills/agent-device/references/video-recording.md +2 -0
- package/src/cli.ts +7 -3
- package/src/core/__tests__/capabilities.test.ts +11 -6
- package/src/core/capabilities.ts +26 -20
- package/src/core/dispatch.ts +109 -31
- package/src/daemon/__tests__/app-state.test.ts +138 -0
- package/src/daemon/app-state.ts +37 -38
- package/src/daemon/context.ts +12 -0
- package/src/daemon/handlers/__tests__/interaction.test.ts +22 -0
- package/src/daemon/handlers/__tests__/session.test.ts +8 -5
- package/src/daemon/handlers/__tests__/snapshot-handler.test.ts +92 -0
- package/src/daemon/handlers/interaction.ts +37 -0
- package/src/daemon/handlers/record-trace.ts +1 -1
- package/src/daemon/handlers/session.ts +1 -1
- package/src/daemon/handlers/snapshot.ts +21 -3
- package/src/daemon-client.ts +14 -6
- package/src/daemon.ts +1 -1
- package/src/platforms/android/__tests__/index.test.ts +46 -1
- package/src/platforms/android/index.ts +23 -0
- package/src/platforms/ios/__tests__/runner-client.test.ts +113 -0
- package/src/platforms/ios/devices.ts +40 -18
- package/src/platforms/ios/index.ts +2 -2
- package/src/platforms/ios/runner-client.ts +323 -44
- package/src/utils/__tests__/args.test.ts +161 -0
- package/src/utils/args.ts +174 -218
- package/src/utils/command-schema.ts +591 -0
- package/src/utils/interactors.ts +11 -1
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ CLI to control iOS and Android devices for AI agents influenced by Vercel’s [a
|
|
|
13
13
|
The project is in early development and considered experimental. Pull requests are welcome!
|
|
14
14
|
|
|
15
15
|
## Features
|
|
16
|
-
- Platforms: iOS (simulator +
|
|
16
|
+
- Platforms: iOS (simulator + physical device core automation) and Android (emulator + device).
|
|
17
17
|
- Core commands: `open`, `back`, `home`, `app-switcher`, `press`, `long-press`, `focus`, `type`, `fill`, `scroll`, `scrollintoview`, `wait`, `alert`, `screenshot`, `close`, `reinstall`.
|
|
18
18
|
- Inspection commands: `snapshot` (accessibility tree).
|
|
19
19
|
- Device tooling: `adb` (Android), `simctl`/`devicectl` (iOS via Xcode).
|
|
@@ -71,13 +71,21 @@ agent-device trace stop ./trace.log
|
|
|
71
71
|
```
|
|
72
72
|
|
|
73
73
|
Coordinates:
|
|
74
|
-
- All coordinate-based commands (`press`, `long-press`, `focus`, `fill`) use device coordinates with origin at top-left.
|
|
74
|
+
- All coordinate-based commands (`press`, `long-press`, `swipe`, `focus`, `fill`) use device coordinates with origin at top-left.
|
|
75
75
|
- X increases to the right, Y increases downward.
|
|
76
76
|
|
|
77
|
+
Gesture series examples:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
agent-device press 300 500 --count 12 --interval-ms 45
|
|
81
|
+
agent-device press 300 500 --count 6 --hold-ms 120 --interval-ms 30 --jitter-px 2
|
|
82
|
+
agent-device swipe 540 1500 540 500 120 --count 8 --pause-ms 30 --pattern ping-pong
|
|
83
|
+
```
|
|
84
|
+
|
|
77
85
|
## Command Index
|
|
78
86
|
- `boot`, `open`, `close`, `reinstall`, `home`, `back`, `app-switcher`
|
|
79
87
|
- `snapshot`, `find`, `get`
|
|
80
|
-
- `click`, `focus`, `type`, `fill`, `press`, `long-press`, `scroll`, `scrollintoview`, `is`
|
|
88
|
+
- `click`, `focus`, `type`, `fill`, `press`, `long-press`, `swipe`, `scroll`, `scrollintoview`, `pinch`, `is`
|
|
81
89
|
- `alert`, `wait`, `screenshot`
|
|
82
90
|
- `trace start`, `trace stop`
|
|
83
91
|
- `settings wifi|airplane|location on|off`
|
|
@@ -91,9 +99,10 @@ Coordinates:
|
|
|
91
99
|
| `ax` | Fast | Medium | Accessibility permission for the terminal app, not recommended |
|
|
92
100
|
|
|
93
101
|
Notes:
|
|
94
|
-
- Default backend is `xctest` on iOS.
|
|
102
|
+
- Default backend is `xctest` on iOS simulators and iOS devices.
|
|
95
103
|
- Scope snapshots with `-s "<label>"` or `-s @ref`.
|
|
96
|
-
- If XCTest returns 0 nodes (e.g., foreground app changed), agent-device
|
|
104
|
+
- If XCTest returns 0 nodes (e.g., foreground app changed), agent-device fails explicitly.
|
|
105
|
+
- `ax` backend is simulator-only.
|
|
97
106
|
|
|
98
107
|
Flags:
|
|
99
108
|
- `--version, -V` print version and exit
|
|
@@ -103,10 +112,25 @@ Flags:
|
|
|
103
112
|
- `--serial <serial>` (Android)
|
|
104
113
|
- `--activity <component>` (Android app launch only; package/Activity or package/.Activity; not for URL opens)
|
|
105
114
|
- `--session <name>`
|
|
115
|
+
- `--count <n>` repeat count for `press`/`swipe`
|
|
116
|
+
- `--interval-ms <ms>` delay between `press` iterations
|
|
117
|
+
- `--hold-ms <ms>` hold duration per `press` iteration
|
|
118
|
+
- `--jitter-px <n>` deterministic coordinate jitter for `press`
|
|
119
|
+
- `--pause-ms <ms>` delay between `swipe` iterations
|
|
120
|
+
- `--pattern one-way|ping-pong` repeat pattern for `swipe`
|
|
106
121
|
- `--verbose` for daemon and runner logs
|
|
107
122
|
- `--json` for structured output
|
|
108
123
|
- `--backend ax|xctest` (snapshot only; defaults to `xctest` on iOS)
|
|
109
124
|
|
|
125
|
+
Pinch:
|
|
126
|
+
- `pinch` is supported on iOS simulators.
|
|
127
|
+
- On Android, `pinch` currently returns `UNSUPPORTED_OPERATION` in the adb backend.
|
|
128
|
+
|
|
129
|
+
Swipe timing:
|
|
130
|
+
- `swipe` accepts optional `durationMs` (default `250`, range `16..10000`).
|
|
131
|
+
- Android uses requested swipe duration directly.
|
|
132
|
+
- iOS uses a safe normalized duration to avoid long-press side effects.
|
|
133
|
+
|
|
110
134
|
## Skills
|
|
111
135
|
Install the automation skills listed in [SKILL.md](skills/agent-device/SKILL.md).
|
|
112
136
|
|
|
@@ -127,13 +151,13 @@ Navigation helpers:
|
|
|
127
151
|
- `boot --platform ios|android` ensures the target is ready without launching an app.
|
|
128
152
|
- Use `boot` mainly when starting a new session and `open` fails because no booted simulator/emulator is available.
|
|
129
153
|
- `open [app|url]` already boots/activates the selected target when needed.
|
|
130
|
-
- `reinstall <app> <path>` uninstalls and installs the app binary in one command (Android + iOS simulator
|
|
154
|
+
- `reinstall <app> <path>` uninstalls and installs the app binary in one command (Android + iOS simulator).
|
|
131
155
|
- `reinstall` accepts package/bundle id style app names and supports `~` in paths.
|
|
132
156
|
|
|
133
157
|
Deep links:
|
|
134
158
|
- `open <url>` supports deep links with `scheme://...`.
|
|
135
159
|
- Android opens deep links via `VIEW` intent.
|
|
136
|
-
- iOS deep link open is simulator-only
|
|
160
|
+
- iOS deep link open is simulator-only.
|
|
137
161
|
- `--activity` cannot be combined with URL opens.
|
|
138
162
|
|
|
139
163
|
```bash
|
|
@@ -184,14 +208,14 @@ Android fill reliability:
|
|
|
184
208
|
- If value does not match, agent-device clears the field and retries once with slower typing.
|
|
185
209
|
- This reduces IME-related character swaps on long strings (e.g. emails and IDs).
|
|
186
210
|
|
|
187
|
-
Settings helpers
|
|
211
|
+
Settings helpers:
|
|
188
212
|
- `settings wifi on|off`
|
|
189
213
|
- `settings airplane on|off`
|
|
190
214
|
- `settings location on|off` (iOS uses per-app permission for the current session app)
|
|
191
|
-
Note: iOS wifi/airplane toggles status bar indicators, not actual network state. Airplane off clears status bar overrides.
|
|
215
|
+
Note: iOS supports these only on simulators. iOS wifi/airplane toggles status bar indicators, not actual network state. Airplane off clears status bar overrides.
|
|
192
216
|
|
|
193
217
|
App state:
|
|
194
|
-
- `appstate` shows the foreground app/activity (Android). On iOS it uses the current session app when available, otherwise it
|
|
218
|
+
- `appstate` shows the foreground app/activity (Android). On iOS it uses the current session app when available, otherwise it resolves via XCTest snapshot.
|
|
195
219
|
- `apps --metadata` returns app list with minimal metadata.
|
|
196
220
|
|
|
197
221
|
## Debug
|
|
@@ -199,7 +223,7 @@ App state:
|
|
|
199
223
|
- `agent-device trace start`
|
|
200
224
|
- `agent-device trace stop ./trace.log`
|
|
201
225
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
202
|
-
- Built-in retries cover transient runner connection failures
|
|
226
|
+
- Built-in retries cover transient runner connection failures and Android UI dumps.
|
|
203
227
|
- For snapshot issues (missing elements), compare with `--raw` flag for unaltered output and scope with `-s "<label>"`.
|
|
204
228
|
|
|
205
229
|
Boot diagnostics:
|
|
@@ -215,9 +239,10 @@ Boot diagnostics:
|
|
|
215
239
|
- Built-in aliases include `Settings` for both platforms.
|
|
216
240
|
|
|
217
241
|
## iOS notes
|
|
218
|
-
-
|
|
219
|
-
- `alert`
|
|
220
|
-
-
|
|
242
|
+
- Core runner commands (`snapshot`, `wait`, `click`, `fill`, `get`, `is`, `find`, `press`, `long-press`, `focus`, `type`, `scroll`, `scrollintoview`, `back`, `home`, `app-switcher`) support iOS simulators and iOS devices.
|
|
243
|
+
- Simulator-only commands: `alert`, `pinch`, `record`, `reinstall`, `apps`, `settings`.
|
|
244
|
+
- iOS deep link open (`open <url>`) is simulator-only.
|
|
245
|
+
- iOS device runs require valid signing/provisioning (Automatic Signing recommended). Optional overrides: `AGENT_DEVICE_IOS_TEAM_ID`, `AGENT_DEVICE_IOS_SIGNING_IDENTITY`, `AGENT_DEVICE_IOS_PROVISIONING_PROFILE`.
|
|
221
246
|
|
|
222
247
|
## Testing
|
|
223
248
|
|
|
@@ -243,6 +268,12 @@ Environment selectors:
|
|
|
243
268
|
- `ANDROID_DEVICE=Pixel_9_Pro_XL` or `ANDROID_SERIAL=emulator-5554`
|
|
244
269
|
- `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=<udid>`
|
|
245
270
|
- `AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS=<ms>` to adjust iOS simulator boot timeout (default: `120000`, minimum: `5000`).
|
|
271
|
+
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to increase daemon request timeout for slow first-run iOS device setup (for example `180000`).
|
|
272
|
+
- `AGENT_DEVICE_IOS_TEAM_ID=<team-id>` optional Team ID override for iOS device runner signing.
|
|
273
|
+
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
274
|
+
- `AGENT_DEVICE_IOS_PROVISIONING_PROFILE=<profile>` optional provisioning profile specifier for iOS device runner signing.
|
|
275
|
+
- `AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH=<path>` optional override for iOS runner derived data root. By default, agent-device separates caches by target kind (`.../derived/simulator` and `.../derived/device`). If you set this override, use separate paths per kind to avoid simulator/device artifact collisions.
|
|
276
|
+
- `AGENT_DEVICE_IOS_CLEAN_DERIVED=1` rebuild iOS runner artifacts from scratch. When `AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH` is set, cleanup is blocked by default; set `AGENT_DEVICE_IOS_ALLOW_OVERRIDE_DERIVED_CLEAN=1` only for trusted custom paths.
|
|
246
277
|
|
|
247
278
|
Test screenshots are written to:
|
|
248
279
|
- `test/screenshots/android-settings.png`
|
package/dist/src/bin.js
CHANGED
|
@@ -1,104 +1,42 @@
|
|
|
1
|
-
import{node_path as e,asAppError as t,pathToFileURL as
|
|
2
|
-
`)}function u(e){let t=e.details?`
|
|
3
|
-
${JSON.stringify(e.details,null,2)}`:"";process.stderr.write(`Error (${e.code}): ${e.message}${t}
|
|
4
|
-
`)}function p(e,t,r){let n=f(e.type??"Element"),a=function(e,t){var r,n;let a=e.label?.trim(),i=e.value?.trim();if("text-field"===(r=t)||"text-view"===r||"search"===r){if(i)return i;if(a)return a}else if(a)return a;if(i)return i;let s=e.identifier?.trim();return!s||(n=s,/^[\w.]+:id\/[\w.-]+$/i.test(n)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":s}(e,n),i=" ".repeat(t),s=e.ref?`@${e.ref}`:"",o=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=o?` [${o}]`:"",c=a?` "${a}"`:"";return r?`${i}${s} [${n}]${l}`.trimEnd():`${i}${s} [${n}]${c}${l}`.trimEnd()}function f(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),r=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.startsWith("ax")&&(t=t.replace(/^ax/,"")),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"}}let m=e.join(i.homedir(),".agent-device"),h=e.join(m,"daemon.json"),w=function(){let e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS;if(!e)return 6e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):6e4}();async function y(e){let t=await v(),r={...e,token:t.token};return await $(t,r)}async function v(){let e=g(),t=l();if(e&&e.version===t&&await b(e))return e;e&&(e.version!==t||!await b(e))&&a.existsSync(h)&&a.unlinkSync(h),await x();let r=Date.now();for(;Date.now()-r<5e3;){let e=g();if(e&&await b(e))return e;await new Promise(e=>setTimeout(e,100))}throw new o("COMMAND_FAILED","Failed to start daemon",{infoPath:h,hint:"Run pnpm build, or delete ~/.agent-device/daemon.json if stale."})}function g(){if(!a.existsSync(h))return null;try{let e=JSON.parse(a.readFileSync(h,"utf8"));if(!e.port||!e.token)return null;return e}catch{return null}}async function b(e){return new Promise(t=>{let r=s.createConnection({host:"127.0.0.1",port:e.port},()=>{r.destroy(),t(!0)});r.on("error",()=>{t(!1)})})}async function x(){let t=c(),r=e.join(t,"dist","src","daemon.js"),i=e.join(t,"src","daemon.ts"),s=a.existsSync(r);if(!s&&!a.existsSync(i))throw new o("COMMAND_FAILED","Daemon entry not found",{distPath:r,srcPath:i});let l=s?[r]:["--experimental-strip-types",i];n(process.execPath,l)}async function $(e,t){return new Promise((r,n)=>{let a=s.createConnection({host:"127.0.0.1",port:e.port},()=>{a.write(`${JSON.stringify(t)}
|
|
5
|
-
`)}),i=setTimeout(()=>{a.destroy(),n(new o("COMMAND_FAILED","Daemon request timed out",{timeoutMs:w}))},w),l="";a.setEncoding("utf8"),a.on("data",e=>{let t=(l+=e).indexOf("\n");if(-1===t)return;let s=l.slice(0,t).trim();if(s)try{let e=JSON.parse(s);a.end(),clearTimeout(i),r(e)}catch(e){clearTimeout(i),n(e)}}),a.on("error",e=>{clearTimeout(i),n(e)})})}async function S(r){let n=function(e){let t={json:!1,help:!1,version:!1},r=[];for(let n=0;n<e.length;n+=1){let a=e[n];if("--json"===a){t.json=!0;continue}if("--help"===a||"-h"===a){t.help=!0;continue}if("--version"===a||"-V"===a){t.version=!0;continue}if("--verbose"===a||"-v"===a){t.verbose=!0;continue}if("-i"===a){t.snapshotInteractiveOnly=!0;continue}if("-c"===a){t.snapshotCompact=!0;continue}if("--raw"===a){t.snapshotRaw=!0;continue}if("--no-record"===a){t.noRecord=!0;continue}if("--save-script"===a){t.saveScript=!0;continue}if("--relaunch"===a){t.relaunch=!0;continue}if("--update"===a||"-u"===a){t.replayUpdate=!0;continue}if("--user-installed"===a){t.appsFilter="user-installed";continue}if("--all"===a){t.appsFilter="all";continue}if("--metadata"===a){t.appsMetadata=!0;continue}if(a.startsWith("--backend")){let r=a.includes("=")?a.split("=")[1]:e[n+1];if(a.includes("=")||(n+=1),"ax"!==r&&"xctest"!==r)throw new o("INVALID_ARGS",`Invalid backend: ${r}`);t.snapshotBackend=r;continue}if(a.startsWith("--")){let[r,i]=a.split("="),s=i??e[n+1];switch(!i&&(n+=1),r){case"--platform":if("ios"!==s&&"android"!==s)throw new o("INVALID_ARGS",`Invalid platform: ${s}`);t.platform=s;break;case"--depth":{let e=Number(s);if(!Number.isFinite(e)||e<0)throw new o("INVALID_ARGS",`Invalid depth: ${s}`);t.snapshotDepth=Math.floor(e);break}case"--scope":t.snapshotScope=s;break;case"--device":t.device=s;break;case"--udid":t.udid=s;break;case"--serial":t.serial=s;break;case"--out":t.out=s;break;case"--session":t.session=s;break;case"--activity":t.activity=s;break;default:throw new o("INVALID_ARGS",`Unknown flag: ${r}`)}continue}if("-d"===a){let r=e[n+1];n+=1;let a=Number(r);if(!Number.isFinite(a)||a<0)throw new o("INVALID_ARGS",`Invalid depth: ${r}`);t.snapshotDepth=Math.floor(a);continue}if("-s"===a){let r=e[n+1];n+=1,t.snapshotScope=r;continue}r.push(a)}return{command:r.shift()??null,positionals:r,flags:t}}(r);n.flags.version&&(process.stdout.write(`${l()}
|
|
6
|
-
`),process.exit(0)),(n.flags.help||!n.command)&&(process.stdout.write(`agent-device <command> [args] [--json]
|
|
1
|
+
import{node_path as e,asAppError as t,pathToFileURL as s,runCmdDetached as a,node_fs as i,node_os as r,node_net as o,errors_AppError as n,readVersion as l,findProjectRoot as p}from"./274.js";let c=["snapshotDepth","snapshotScope","snapshotRaw","snapshotBackend"],u=[{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:"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:"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:["--verbose","-v"],type:"boolean",usageLabel:"--verbose",usageDescription:"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:"boolean",usageLabel:"--save-script",usageDescription:"Save session script (.ad) on close"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{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:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed packages (Android only)"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all packages (Android only)"},{key:"appsMetadata",names:["--metadata"],type:"boolean",usageLabel:"--metadata",usageDescription:"Apps: return metadata objects"},{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:"snapshotBackend",names:["--backend"],type:"enum",enumValues:["ax","xctest"],usageLabel:"--backend ax|xctest",usageDescription:"Snapshot backend (iOS): ax or xctest"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"}],d=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),g={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?"],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:["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw","snapshotBackend"]},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (Android launchable by default, iOS simulator)",positionalArgs:[],allowedFlags:["appsFilter","appsMetadata"]},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:[...c]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <@ref|selector>",description:"Click element by snapshot ref or selector",positionalArgs:["target"],allowedFlags:[...c]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...c]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},press:{description:"Tap/press at coordinates (supports repeated gesture series)",positionalArgs:["x","y"],allowedFlags:["count","intervalMs","holdMs","jitterPx"]},"long-press":{description:"Long press (where supported)",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:[...c]},scroll:{description:"Scroll in direction (0-1 amount)",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{description:"Scroll until text appears",positionalArgs:["text"],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] | record stop",description:"Start/stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:[]},trace:{usageOverride:"trace start [path] | trace stop [path]",description:"Start/stop trace log capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},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","snapshotBackend"]},is:{description:"Assert UI state (visible|hidden|exists|editable|selected|text)",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...c]},settings:{description:"Toggle OS settings (simulators)",positionalArgs:["setting","state"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},m=new Map,f=new Map;for(let e of u){for(let t of e.names)m.set(t,e);let t=f.get(e.key);t?t.push(e):f.set(e.key,[e])}function h(e){if(e)return g[e]}function y(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}let w=function(){let e=`agent-device <command> [args] [--json]
|
|
7
2
|
|
|
8
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
+
`,t=Object.keys(g).map(e=>{var t,s;let a=g[e];if(!a)throw Error(`Missing command schema for ${e}`);return{name:e,schema:a,usage:(t=e,(s=a).usageOverride?s.usageOverride:[t,...s.positionalArgs.map(y),...s.allowedFlags.flatMap(e=>(f.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" "))}}),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 i=u.filter(e=>e.usageLabel&&e.usageDescription),r=Math.max(...i.map(e=>(e.usageLabel??"").length))+2,o=["Flags:"];for(let e of i)o.push(` ${(e.usageLabel??"").padEnd(r)}${e.usageDescription??""}`);return`${e}
|
|
5
|
+
${a.join("\n")}
|
|
9
6
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
--backend ax|xctest xctest: default; XCTest snapshot (slower, no permissions)
|
|
23
|
-
ax: macOS Accessibility tree (fast, needs permissions)
|
|
24
|
-
devices List available devices
|
|
25
|
-
apps [--user-installed|--all|--metadata] List installed apps (Android launchable by default, iOS simulator)
|
|
26
|
-
appstate Show foreground app/activity
|
|
27
|
-
back Navigate back (where supported)
|
|
28
|
-
home Go to home screen (where supported)
|
|
29
|
-
app-switcher Open app switcher (where supported)
|
|
30
|
-
wait <ms>|text <text>|@ref|<selector> [timeoutMs]
|
|
31
|
-
Wait for duration, text, ref, or selector to appear
|
|
32
|
-
alert [get|accept|dismiss|wait] [timeout] Inspect or handle alert (iOS simulator)
|
|
33
|
-
click <@ref|selector> Click element by snapshot ref or selector
|
|
34
|
-
get text <@ref|selector> Return element text by ref or selector
|
|
35
|
-
get attrs <@ref|selector> Return element attributes by ref or selector
|
|
36
|
-
replay <path> [--update|-u] Replay a recorded session
|
|
37
|
-
press <x> <y> Tap at coordinates
|
|
38
|
-
long-press <x> <y> [durationMs] Long press (where supported)
|
|
39
|
-
focus <x> <y> Focus input at coordinates
|
|
40
|
-
type <text> Type text in focused field
|
|
41
|
-
fill <x> <y> <text> | fill <@ref|selector> <text>
|
|
42
|
-
Tap then type
|
|
43
|
-
scroll <direction> [amount] Scroll in direction (0-1 amount)
|
|
44
|
-
scrollintoview <text> Scroll until text appears (Android only)
|
|
45
|
-
screenshot [path] Capture screenshot
|
|
46
|
-
record start [path] Start screen recording
|
|
47
|
-
record stop Stop screen recording
|
|
48
|
-
trace start [path] Start trace log capture
|
|
49
|
-
trace stop [path] Stop trace log capture
|
|
50
|
-
find <text> <action> [value] Find by any text (label/value/id)
|
|
51
|
-
find text <text> <action> [value] Find by text content
|
|
52
|
-
find label <label> <action> [value] Find by label
|
|
53
|
-
find value <value> <action> [value] Find by value
|
|
54
|
-
find role <role> <action> [value] Find by role/type
|
|
55
|
-
find id <id> <action> [value] Find by identifier/resource-id
|
|
56
|
-
is <predicate> <selector> [value] Assert UI state (visible|hidden|exists|editable|selected|text)
|
|
57
|
-
settings <wifi|airplane|location> <on|off> Toggle OS settings (simulators)
|
|
58
|
-
session list List active sessions
|
|
59
|
-
|
|
60
|
-
Flags:
|
|
61
|
-
--platform ios|android Platform to target
|
|
62
|
-
--device <name> Device name to target
|
|
63
|
-
--udid <udid> iOS device UDID
|
|
64
|
-
--serial <serial> Android device serial
|
|
65
|
-
--activity <component> Android app launch activity (package/Activity); not for URL opens
|
|
66
|
-
--session <name> Named session
|
|
67
|
-
--verbose Stream daemon/runner logs
|
|
68
|
-
--json JSON output
|
|
69
|
-
--save-script Save session script (.ad) on close
|
|
70
|
-
--relaunch open: terminate app process before launching it
|
|
71
|
-
--no-record Do not record this action
|
|
72
|
-
--update, -u Replay: update selectors and rewrite replay file in place
|
|
73
|
-
--user-installed Apps: list user-installed packages (Android only)
|
|
74
|
-
--all Apps: list all packages (Android only)
|
|
75
|
-
--version, -V Print version and exit
|
|
76
|
-
|
|
77
|
-
`),process.exit(+!n.flags.help));let{command:s,positionals:c,flags:m}=n,h=m.session??process.env.AGENT_DEVICE_SESSION??"default",w=m.verbose&&!m.json?function(){try{let t=e.join(i.homedir(),".agent-device","daemon.log"),r=0,n=!1,s=setInterval(()=>{if(n||!a.existsSync(t))return;let e=a.statSync(t);if(e.size<=r)return;let i=a.openSync(t,"r"),s=Buffer.alloc(e.size-r);a.readSync(i,s,0,s.length,r),a.closeSync(i),r=e.size,s.length>0&&process.stdout.write(s.toString("utf8"))},200);return()=>{n=!0,clearInterval(s)}}catch{return null}}():null;try{if("session"===s){let e=c[0]??"list";if("list"!==e)throw new o("INVALID_ARGS","session only supports list");let t=await y({session:h,command:"session_list",positionals:[],flags:{}});if(!t.ok)throw new o(t.error.code,t.error.message);m.json?d({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
78
|
-
`),w&&w();return}let e=await y({session:h,command:s,positionals:c,flags:m});if(e.ok){if(m.json){d({success:!0,data:e.data??{}}),w&&w();return}if("snapshot"===s){process.stdout.write(function(e,t={}){let r=e.nodes,n=Array.isArray(r)?r:[],a=!!e.truncated,i="string"==typeof e.appName?e.appName:void 0,s="string"==typeof e.appBundleId?e.appBundleId:void 0,o=[];i&&o.push(`Page: ${i}`),s&&o.push(`App: ${s}`);let l=`Snapshot: ${n.length} nodes${a?" (truncated)":""}`,c=o.length>0?`${o.join("\n")}
|
|
79
|
-
`:"";if(0===n.length)return`${c}${l}
|
|
80
|
-
`;if(t.raw){let e=n.map(e=>JSON.stringify(e));return`${c}${l}
|
|
7
|
+
${o.join("\n")}
|
|
8
|
+
`}();function v(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function b(e){return e.replace(/^-+/,"")}function x(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
9
|
+
`)}function $(e){let t=e.details?`
|
|
10
|
+
${JSON.stringify(e.details,null,2)}`:"";process.stderr.write(`Error (${e.code}): ${e.message}${t}
|
|
11
|
+
`)}function k(e,t,s){let a=A(e.type??"Element"),i=function(e,t){var s,a;let i=e.label?.trim(),r=e.value?.trim();if("text-field"===(s=t)||"text-view"===s||"search"===s){if(r)return r;if(i)return i}else if(i)return i;if(r)return r;let o=e.identifier?.trim();return!o||(a=o,/^[\w.]+:id\/[\w.-]+$/i.test(a)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":o}(e,a),r=" ".repeat(t),o=e.ref?`@${e.ref}`:"",n=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=n?` [${n}]`:"",p=i?` "${i}"`:"";return s?`${r}${o} [${a}]${l}`.trimEnd():`${r}${o} [${a}]${p}${l}`.trimEnd()}function A(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),s=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.startsWith("ax")&&(t=t.replace(/^ax/,"")),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 s?"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"}}let S=e.join(r.homedir(),".agent-device"),D=e.join(S,"daemon.json"),F=function(){let e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS;if(!e)return 6e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):6e4}();async function L(e){let t=await O(),s={...e,token:t.token};return await E(t,s)}async function O(){let e=j(),t=l(),s=!!e&&await I(e);if(e&&e.version===t&&s)return e;e&&(e.version!==t||!s)&&function(){try{i.existsSync(D)&&i.unlinkSync(D)}catch{}}(),await N();let a=Date.now();for(;Date.now()-a<5e3;){let e=j();if(e&&await I(e))return e;await new Promise(e=>setTimeout(e,100))}throw new n("COMMAND_FAILED","Failed to start daemon",{infoPath:D,hint:"Run pnpm build, or delete ~/.agent-device/daemon.json if stale."})}function j(){if(!i.existsSync(D))return null;try{let e=JSON.parse(i.readFileSync(D,"utf8"));if(!e.port||!e.token)return null;return e}catch{return null}}async function I(e){return new Promise(t=>{let s=o.createConnection({host:"127.0.0.1",port:e.port},()=>{s.destroy(),t(!0)});s.on("error",()=>{t(!1)})})}async function N(){let t=p(),s=e.join(t,"dist","src","daemon.js"),r=e.join(t,"src","daemon.ts"),o=i.existsSync(s),l=i.existsSync(r);if(!o&&!l)throw new n("COMMAND_FAILED","Daemon entry not found",{distPath:s,srcPath:r});let c=(process.execArgv.includes("--experimental-strip-types")?l:!o&&l)?["--experimental-strip-types",r]:[s];a(process.execPath,c)}async function E(e,t){return new Promise((s,a)=>{let i=o.createConnection({host:"127.0.0.1",port:e.port},()=>{i.write(`${JSON.stringify(t)}
|
|
12
|
+
`)}),r=setTimeout(()=>{i.destroy(),a(new n("COMMAND_FAILED","Daemon request timed out",{timeoutMs:F}))},F),l="";i.setEncoding("utf8"),i.on("data",e=>{let t=(l+=e).indexOf("\n");if(-1===t)return;let o=l.slice(0,t).trim();if(o)try{let e=JSON.parse(o);i.end(),clearTimeout(r),s(e)}catch(e){clearTimeout(r),a(e)}}),i.on("error",e=>{clearTimeout(r),a(e)})})}async function C(s){let a=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},i=null,r=[],o=[],l=[],p=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(p&&"--"===s){p=!1;continue}if(!p){i?r.push(s):i=s;continue}let o=s.startsWith("--"),c=s.startsWith("-")&&s.length>1;if(!o&&!c){i?r.push(s):i=s;continue}let[u,d]=o?v(s):[s,void 0],g=m.get(u);if(!g){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let i=h(e);return!i||!!i.allowsExtraPositionals||0!==i.positionalArgs.length&&(t.length<i.positionalArgs.length||i.positionalArgs.some(e=>e.includes("?")))}(i,r,s)){i?r.push(s):i=s;continue}throw new n("INVALID_ARGS",`Unknown flag: ${u}`)}let f=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new n("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 n("INVALID_ARGS",`Flag ${t} does not take a value.`);return{value:!0,consumeNext:!1}}let i=s??a;if(void 0===i||void 0===s&&function(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?v(e):[e,void 0];return void 0!==m.get(t)}(i))throw new n("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:i,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(i))throw new n("INVALID_ARGS",`Invalid ${b(t)}: ${i}`);return{value:i,consumeNext:void 0===s}}let r=Number(i);if(!Number.isFinite(r)||"number"==typeof e.min&&r<e.min||"number"==typeof e.max&&r>e.max)throw new n("INVALID_ARGS",`Invalid ${b(t)}: ${i}`);return{value:Math.floor(r),consumeNext:void 0===s}}(g,u,d,e[t+1]);f.consumeNext&&(t+=1),a[g.key]=f.value,l.push({key:g.key,token:u})}let c=h(i),u=new Set([...d,...c?.allowedFlags??[]]),g=l.filter(e=>!u.has(e.key));if(g.length>0){var f,y;let e=(f=i,y=g.map(e=>e.token),f?1===y.length?`Flag ${y[0]} is not supported for command ${f}.`:`Flags ${y.join(", ")} are not supported for command ${f}.`:1===y.length?`Flag ${y[0]} requires a command that supports it.`:`Flags ${y.join(", ")} require a command that supports them.`);if(s)throw new n("INVALID_ARGS",e);for(let t of(o.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),g))delete a[t.key]}if(c?.defaults)for(let[e,t]of Object.entries(c.defaults))void 0===a[e]&&(a[e]=t);return{command:i,positionals:r,flags:a,warnings:o}}(s);for(let e of a.warnings)process.stderr.write(`Warning: ${e}
|
|
13
|
+
`);a.flags.version&&(process.stdout.write(`${l()}
|
|
14
|
+
`),process.exit(0)),(a.flags.help||!a.command)&&(process.stdout.write(`${w}
|
|
15
|
+
`),process.exit(+!a.flags.help));let{command:o,positionals:p,flags:c}=a,u=function(e){let{json:t,help:s,version:a,...i}=e;return i}(c),g=c.session??process.env.AGENT_DEVICE_SESSION??"default",f=c.verbose&&!c.json?function(){try{let t=e.join(r.homedir(),".agent-device","daemon.log"),s=0,a=!1,o=setInterval(()=>{if(a||!i.existsSync(t))return;let e=i.statSync(t);if(e.size<=s)return;let r=i.openSync(t,"r"),o=Buffer.alloc(e.size-s);i.readSync(r,o,0,o.length,s),i.closeSync(r),s=e.size,o.length>0&&process.stdout.write(o.toString("utf8"))},200);return()=>{a=!0,clearInterval(o)}}catch{return null}}():null;try{if("session"===o){let e=p[0]??"list";if("list"!==e)throw new n("INVALID_ARGS","session only supports list");let t=await L({session:g,command:"session_list",positionals:[],flags:u});if(!t.ok)throw new n(t.error.code,t.error.message);c.json?x({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
16
|
+
`),f&&f();return}let e=await L({session:g,command:o,positionals:p,flags:u});if(e.ok){if(c.json){x({success:!0,data:e.data??{}}),f&&f();return}if("snapshot"===o){process.stdout.write(function(e,t={}){let s=e.nodes,a=Array.isArray(s)?s:[],i=!!e.truncated,r="string"==typeof e.appName?e.appName:void 0,o="string"==typeof e.appBundleId?e.appBundleId:void 0,n=[];r&&n.push(`Page: ${r}`),o&&n.push(`App: ${o}`);let l=`Snapshot: ${a.length} nodes${i?" (truncated)":""}`,p=n.length>0?`${n.join("\n")}
|
|
17
|
+
`:"";if(0===a.length)return`${p}${l}
|
|
18
|
+
`;if(t.raw){let e=a.map(e=>JSON.stringify(e));return`${p}${l}
|
|
81
19
|
${e.join("\n")}
|
|
82
|
-
`}if(t.flatten){let e=
|
|
20
|
+
`}if(t.flatten){let e=a.map(e=>k(e,0,!1));return`${p}${l}
|
|
83
21
|
${e.join("\n")}
|
|
84
|
-
`}let
|
|
22
|
+
`}let c=[],u=[];for(let e of a){let t=e.depth??0;for(;c.length>0&&t<=c[c.length-1];)c.pop();let s=e.label?.trim()||e.value?.trim()||e.identifier?.trim()||"",a="group"===A(e.type??"Element")&&!s;a&&c.push(t);let i=a?t:Math.max(0,t-c.length);u.push(k(e,i,a))}return`${p}${l}
|
|
85
23
|
${u.join("\n")}
|
|
86
|
-
`}(e.data??{},{raw:
|
|
87
|
-
`),
|
|
88
|
-
`),
|
|
89
|
-
`),
|
|
90
|
-
`),
|
|
91
|
-
`),
|
|
92
|
-
`),
|
|
93
|
-
`),
|
|
94
|
-
`),
|
|
95
|
-
`),
|
|
96
|
-
`),
|
|
97
|
-
`),
|
|
98
|
-
`),
|
|
99
|
-
`),
|
|
100
|
-
`),
|
|
101
|
-
`),
|
|
24
|
+
`}(e.data??{},{raw:c.snapshotRaw,flatten:c.snapshotInteractiveOnly})),f&&f();return}if("get"===o){let t=p[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
|
|
25
|
+
`),f&&f();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
26
|
+
`),f&&f();return}}if("find"===o){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
|
|
27
|
+
`),f&&f();return}if("boolean"==typeof t?.found){process.stdout.write(`Found: ${t.found}
|
|
28
|
+
`),f&&f();return}if(t?.node){process.stdout.write(`${JSON.stringify(t.node,null,2)}
|
|
29
|
+
`),f&&f();return}}if("is"===o){let t=e.data?.predicate??"assertion";process.stdout.write(`Passed: is ${t}
|
|
30
|
+
`),f&&f();return}if("boot"===o){let t=e.data?.platform??"unknown",s=e.data?.device??e.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${t})
|
|
31
|
+
`),f&&f();return}if("click"===o){let t=e.data?.ref??"",s=e.data?.x,a=e.data?.y;t&&"number"==typeof s&&"number"==typeof a&&process.stdout.write(`Clicked @${t} (${s}, ${a})
|
|
32
|
+
`),f&&f();return}if(e.data&&"object"==typeof e.data){let t=e.data;if("devices"===o){let e=(Array.isArray(t.devices)?t.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",s=e?.platform??"unknown",a=e?.kind?` ${e.kind}`:"",i="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${a})${i}`});process.stdout.write(`${e.join("\n")}
|
|
33
|
+
`),f&&f();return}if("apps"===o){let e=(Array.isArray(t.apps)?t.apps:[]).map(e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e.bundleId??e.package,s=e.name??e.label;return s&&t?`${s} (${t})`:t&&"boolean"==typeof e.launchable?`${t} (launchable=${e.launchable})`:t?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${e.join("\n")}
|
|
34
|
+
`),f&&f();return}if("appstate"===o){let e=t?.platform,s=t?.appBundleId,a=t?.appName,i=t?.source,r=t?.package,o=t?.activity;if("ios"===e){process.stdout.write(`Foreground app: ${a??s}
|
|
35
|
+
`),s&&process.stdout.write(`Bundle: ${s}
|
|
36
|
+
`),i&&process.stdout.write(`Source: ${i}
|
|
37
|
+
`),f&&f();return}if("android"===e){process.stdout.write(`Foreground app: ${r??"unknown"}
|
|
38
|
+
`),o&&process.stdout.write(`Activity: ${o}
|
|
39
|
+
`),f&&f();return}}}f&&f();return}throw new n(e.error.code,e.error.message,e.error.details)}catch(s){let e=t(s);if(c.json)x({success:!1,error:{code:e.code,message:e.message,details:e.details}});else if($(e),c.verbose)try{let e=await import("node:fs"),t=await import("node:os"),s=(await import("node:path")).join(t.homedir(),".agent-device","daemon.log");if(e.existsSync(s)){let t=e.readFileSync(s,"utf8").split("\n"),a=t.slice(Math.max(0,t.length-200)).join("\n");a.trim().length>0&&process.stderr.write(`
|
|
102
40
|
[daemon log]
|
|
103
|
-
${
|
|
104
|
-
`)}}catch{}
|
|
41
|
+
${a}
|
|
42
|
+
`)}}catch{}f&&f(),process.exit(1)}}s(process.argv[1]??"").href===import.meta.url&&C(process.argv.slice(2)).catch(e=>{$(t(e)),process.exit(1)}),C(process.argv.slice(2));
|