agent-device 0.3.5 → 0.4.1
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 +47 -14
- package/dist/src/797.js +1 -0
- package/dist/src/bin.js +44 -95
- package/dist/src/daemon.js +18 -17
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +24 -0
- package/ios-runner/README.md +1 -1
- package/package.json +2 -2
- package/skills/agent-device/SKILL.md +25 -12
- package/skills/agent-device/references/permissions.md +15 -1
- package/skills/agent-device/references/session-management.md +3 -0
- package/skills/agent-device/references/snapshot-refs.md +2 -0
- package/skills/agent-device/references/video-recording.md +2 -0
- package/src/__tests__/cli-help.test.ts +102 -0
- package/src/cli.ts +42 -8
- 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/__tests__/session-store.test.ts +23 -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 +3 -3
- package/src/daemon/handlers/snapshot.ts +230 -187
- package/src/daemon/session-store.ts +16 -4
- package/src/daemon/types.ts +2 -1
- package/src/daemon-client.ts +42 -13
- package/src/daemon.ts +99 -9
- 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 +418 -93
- package/src/utils/__tests__/args.test.ts +208 -1
- package/src/utils/__tests__/daemon-client.test.ts +78 -0
- package/src/utils/__tests__/keyed-lock.test.ts +55 -0
- package/src/utils/__tests__/process-identity.test.ts +33 -0
- package/src/utils/args.ts +202 -215
- package/src/utils/command-schema.ts +629 -0
- package/src/utils/interactors.ts +11 -1
- package/src/utils/keyed-lock.ts +14 -0
- package/src/utils/process-identity.ts +100 -0
- package/dist/src/274.js +0 -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
|
|
|
@@ -121,19 +145,21 @@ Sessions:
|
|
|
121
145
|
- `close` stops the session and releases device resources. Pass an app to close it explicitly, or omit to just close the session.
|
|
122
146
|
- Use `--session <name>` to manage multiple sessions.
|
|
123
147
|
- Session scripts are written to `~/.agent-device/sessions/<session>-<timestamp>.ad` when recording is enabled with `--save-script`.
|
|
148
|
+
- `--save-script` accepts an optional path: `--save-script ./workflows/my-flow.ad`.
|
|
149
|
+
- For ambiguous bare values, use an explicit form: `--save-script=workflow.ad` or a path-like value such as `./workflow.ad`.
|
|
124
150
|
- Deterministic replay is `.ad`-based; use `replay --update` (`-u`) to update selector drift and rewrite the replay file in place.
|
|
125
151
|
|
|
126
152
|
Navigation helpers:
|
|
127
153
|
- `boot --platform ios|android` ensures the target is ready without launching an app.
|
|
128
154
|
- Use `boot` mainly when starting a new session and `open` fails because no booted simulator/emulator is available.
|
|
129
155
|
- `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
|
|
156
|
+
- `reinstall <app> <path>` uninstalls and installs the app binary in one command (Android + iOS simulator).
|
|
131
157
|
- `reinstall` accepts package/bundle id style app names and supports `~` in paths.
|
|
132
158
|
|
|
133
159
|
Deep links:
|
|
134
160
|
- `open <url>` supports deep links with `scheme://...`.
|
|
135
161
|
- Android opens deep links via `VIEW` intent.
|
|
136
|
-
- iOS deep link open is simulator-only
|
|
162
|
+
- iOS deep link open is simulator-only.
|
|
137
163
|
- `--activity` cannot be combined with URL opens.
|
|
138
164
|
|
|
139
165
|
```bash
|
|
@@ -184,14 +210,14 @@ Android fill reliability:
|
|
|
184
210
|
- If value does not match, agent-device clears the field and retries once with slower typing.
|
|
185
211
|
- This reduces IME-related character swaps on long strings (e.g. emails and IDs).
|
|
186
212
|
|
|
187
|
-
Settings helpers
|
|
213
|
+
Settings helpers:
|
|
188
214
|
- `settings wifi on|off`
|
|
189
215
|
- `settings airplane on|off`
|
|
190
216
|
- `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.
|
|
217
|
+
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
218
|
|
|
193
219
|
App state:
|
|
194
|
-
- `appstate` shows the foreground app/activity (Android). On iOS it uses the current session app when available, otherwise it
|
|
220
|
+
- `appstate` shows the foreground app/activity (Android). On iOS it uses the current session app when available, otherwise it resolves via XCTest snapshot.
|
|
195
221
|
- `apps --metadata` returns app list with minimal metadata.
|
|
196
222
|
|
|
197
223
|
## Debug
|
|
@@ -199,7 +225,7 @@ App state:
|
|
|
199
225
|
- `agent-device trace start`
|
|
200
226
|
- `agent-device trace stop ./trace.log`
|
|
201
227
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
202
|
-
- Built-in retries cover transient runner connection failures
|
|
228
|
+
- Built-in retries cover transient runner connection failures and Android UI dumps.
|
|
203
229
|
- For snapshot issues (missing elements), compare with `--raw` flag for unaltered output and scope with `-s "<label>"`.
|
|
204
230
|
|
|
205
231
|
Boot diagnostics:
|
|
@@ -215,9 +241,10 @@ Boot diagnostics:
|
|
|
215
241
|
- Built-in aliases include `Settings` for both platforms.
|
|
216
242
|
|
|
217
243
|
## iOS notes
|
|
218
|
-
-
|
|
219
|
-
- `alert`
|
|
220
|
-
-
|
|
244
|
+
- 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.
|
|
245
|
+
- Simulator-only commands: `alert`, `pinch`, `record`, `reinstall`, `apps`, `settings`.
|
|
246
|
+
- iOS deep link open (`open <url>`) is simulator-only.
|
|
247
|
+
- 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
248
|
|
|
222
249
|
## Testing
|
|
223
250
|
|
|
@@ -243,6 +270,12 @@ Environment selectors:
|
|
|
243
270
|
- `ANDROID_DEVICE=Pixel_9_Pro_XL` or `ANDROID_SERIAL=emulator-5554`
|
|
244
271
|
- `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=<udid>`
|
|
245
272
|
- `AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS=<ms>` to adjust iOS simulator boot timeout (default: `120000`, minimum: `5000`).
|
|
273
|
+
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to increase daemon request timeout for slow first-run iOS device setup (for example `180000`).
|
|
274
|
+
- `AGENT_DEVICE_IOS_TEAM_ID=<team-id>` optional Team ID override for iOS device runner signing.
|
|
275
|
+
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
276
|
+
- `AGENT_DEVICE_IOS_PROVISIONING_PROFILE=<profile>` optional provisioning profile specifier for iOS device runner signing.
|
|
277
|
+
- `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.
|
|
278
|
+
- `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
279
|
|
|
247
280
|
Test screenshots are written to:
|
|
248
281
|
- `test/screenshots/android-settings.png`
|
package/dist/src/797.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e,{promises as t}from"node:fs";import r from"node:path";import{fileURLToPath as n,pathToFileURL as o}from"node:url";import{spawn as i,spawnSync as u}from"node:child_process";function s(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class d extends Error{constructor(e,t,r,n){super(t),s(this,"code",void 0),s(this,"details",void 0),s(this,"cause",void 0),this.code=e,this.details=r,this.cause=n}}function a(e){return e instanceof d?e:e instanceof Error?new d("UNKNOWN",e.message,void 0,e):new d("UNKNOWN","Unknown error",{err:e})}function l(){try{let t=c();return JSON.parse(e.readFileSync(r.join(t,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function c(){let t=r.dirname(n(import.meta.url)),o=t;for(let t=0;t<6;t+=1){let t=r.join(o,"package.json");if(e.existsSync(t))return o;o=r.dirname(o)}return t}async function f(e,t,r={}){return new Promise((n,o)=>{let u=i(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"]}),s="",a=r.binaryStdout?Buffer.alloc(0):void 0,l="",c=!1,f=E(r.timeoutMs),m=f?setTimeout(()=>{c=!0,u.kill("SIGKILL")},f):null;r.binaryStdout||u.stdout.setEncoding("utf8"),u.stderr.setEncoding("utf8"),void 0!==r.stdin&&u.stdin.write(r.stdin),u.stdin.end(),u.stdout.on("data",e=>{r.binaryStdout?a=Buffer.concat([a??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):s+=e}),u.stderr.on("data",e=>{l+=e}),u.on("error",r=>{(m&&clearTimeout(m),"ENOENT"===r.code)?o(new d("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new d("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),u.on("close",i=>{m&&clearTimeout(m);let u=i??1;c&&f?o(new d("COMMAND_FAILED",`${e} timed out after ${f}ms`,{cmd:e,args:t,stdout:s,stderr:l,exitCode:u,timeoutMs:f})):0===u||r.allowFailure?n({stdout:s,stderr:l,exitCode:u,stdoutBuffer:a}):o(new d("COMMAND_FAILED",`${e} exited with code ${u}`,{cmd:e,args:t,stdout:s,stderr:l,exitCode:u}))})})}async function m(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await f(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function w(e,t,r={}){let n=u(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:E(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new d("COMMAND_FAILED",`${e} timed out after ${E(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:E(r.timeoutMs)},n.error);if("ENOENT"===o)throw new d("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new d("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(),s="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),a=n.status??1;if(0!==a&&!r.allowFailure)throw new d("COMMAND_FAILED",`${e} exited with code ${a}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:a});return{stdout:i,stderr:s,exitCode:a,stdoutBuffer:o}}function p(e,t,r={}){i(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function h(e,t,r={}){return new Promise((n,o)=>{let u=i(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"]}),s="",a="",l=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||u.stdout.setEncoding("utf8"),u.stderr.setEncoding("utf8"),void 0!==r.stdin&&u.stdin.write(r.stdin),u.stdin.end(),u.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);s+=t,r.onStdoutChunk?.(t)}),u.stderr.on("data",e=>{let t=String(e);a+=t,r.onStderrChunk?.(t)}),u.on("error",r=>{"ENOENT"===r.code?o(new d("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new d("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),u.on("close",i=>{let u=i??1;0===u||r.allowFailure?n({stdout:s,stderr:a,exitCode:u,stdoutBuffer:l}):o(new d("COMMAND_FAILED",`${e} exited with code ${u}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:u}))})})}function M(e,t,r={}){let n=i(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]}),o="",u="";n.stdout.setEncoding("utf8"),n.stderr.setEncoding("utf8"),n.stdout.on("data",e=>{o+=e}),n.stderr.on("data",e=>{u+=e});let s=new Promise((i,s)=>{n.on("error",r=>{"ENOENT"===r.code?s(new d("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):s(new d("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),n.on("close",n=>{let a=n??1;0===a||r.allowFailure?i({stdout:o,stderr:u,exitCode:a}):s(new d("COMMAND_FAILED",`${e} exited with code ${a}`,{cmd:e,args:t,stdout:o,stderr:u,exitCode:a}))})});return{child:n,wait:s}}function E(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let S=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function g(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function N(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=w("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 A(e,t){let r;if(!g(e))return!1;if(t){let r=N(e);if(!r||r!==t)return!1}let n=function(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=w("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}}(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&S.some(e=>e.test(r))}function v(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 I(e,t){if(!g(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!g(e))return!0;return!g(e)}async function O(e,t){!A(e,t.expectedStartTime)||!v(e,"SIGTERM")||await I(e,t.termTimeoutMs)||v(e,"SIGKILL")&&await I(e,t.killTimeoutMs)}export{default as node_net}from"node:net";export{default as node_os}from"node:os";export{d as AppError,a as asAppError,n as fileURLToPath,c as findProjectRoot,A as isAgentDeviceDaemonProcess,g as isProcessAlive,e as node_fs,r as node_path,o as pathToFileURL,t as promises,N as readProcessStartTime,l as readVersion,f as runCmd,M as runCmdBackground,p as runCmdDetached,h as runCmdStreaming,O as stopProcessForTakeover,m as whichCmd};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,104 +1,53 @@
|
|
|
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 n,AppError as o,readVersion as l,findProjectRoot as p,stopProcessForTakeover as c}from"./797.js";let u=["snapshotDepth","snapshotScope","snapshotRaw","snapshotBackend"],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:"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:"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:"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"}],g=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),m={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:[...u]},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:[...u]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...u]},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:[...u]},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:[...u]},settings:{description:"Toggle OS settings (simulators)",positionalArgs:["setting","state"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},f=new Map,h=new Map;for(let e of d){for(let t of e.names)f.set(t,e);let t=h.get(e.key);t?t.push(e):h.set(e.key,[e])}function y(e){if(e)return m[e]}function w(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function v(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(w),...t.allowedFlags.flatMap(e=>(h.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let b=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(m).map(e=>{let t=m[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:v(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 i=$("Flags:",d.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
|
+
${a.join("\n")}
|
|
6
|
+
|
|
7
|
+
${i}
|
|
8
|
+
`}();function x(e){return d.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function $(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 A(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function k(e){return e.replace(/^-+/,"")}function S(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?A(e):[e,void 0];return void 0!==f.get(t)}function D(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
|
+
`)}function F(e){let t=e.details?`
|
|
11
|
+
${JSON.stringify(e.details,null,2)}`:"";process.stderr.write(`Error (${e.code}): ${e.message}${t}
|
|
12
|
+
`)}function L(e,t,s){let a=I(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 n=e.identifier?.trim();return!n||(a=n,/^[\w.]+:id\/[\w.-]+$/i.test(a)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":n}(e,a),r=" ".repeat(t),n=e.ref?`@${e.ref}`:"",o=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=o?` [${o}]`:"",p=i?` "${i}"`:"";return s?`${r}${n} [${a}]${l}`.trimEnd():`${r}${n} [${a}]${p}${l}`.trimEnd()}function I(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 N=e.join(r.homedir(),".agent-device"),O=e.join(N,"daemon.json"),j=function(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 18e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):18e4}();async function E(){let e=M(),t=l(),s=!!e&&await _(e);if(e&&e.version===t&&s)return e;e&&(e.version!==t||!s)&&(await C(e),function(){try{i.existsSync(O)&&i.unlinkSync(O)}catch{}}()),await R();let a=Date.now();for(;Date.now()-a<5e3;){let e=M();if(e&&await _(e))return e;await new Promise(e=>setTimeout(e,100))}throw new o("COMMAND_FAILED","Failed to start daemon",{infoPath:O,hint:"Run pnpm build, or delete ~/.agent-device/daemon.json if stale."})}async function C(e){await c(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function M(){if(!i.existsSync(O))return null;try{let e=JSON.parse(i.readFileSync(O,"utf8"));if(!e.port||!e.token)return null;return{...e,pid:Number.isInteger(e.pid)&&e.pid>0?e.pid:0}}catch{return null}}async function _(e){return new Promise(t=>{let s=n.createConnection({host:"127.0.0.1",port:e.port},()=>{s.destroy(),t(!0)});s.on("error",()=>{t(!1)})})}async function R(){let t=p(),s=e.join(t,"dist","src","daemon.js"),r=e.join(t,"src","daemon.ts"),n=i.existsSync(s),l=i.existsSync(r);if(!n&&!l)throw new o("COMMAND_FAILED","Daemon entry not found",{distPath:s,srcPath:r});let c=(process.execArgv.includes("--experimental-strip-types")?l:!n&&l)?["--experimental-strip-types",r]:[s];a(process.execPath,c)}async function T(e,t){return new Promise((s,a)=>{let i=n.createConnection({host:"127.0.0.1",port:e.port},()=>{i.write(`${JSON.stringify(t)}
|
|
13
|
+
`)}),r=setTimeout(()=>{i.destroy(),a(new o("COMMAND_FAILED","Daemon request timed out",{timeoutMs:j}))},j),l="";i.setEncoding("utf8"),i.on("data",e=>{let t=(l+=e).indexOf("\n");if(-1===t)return;let n=l.slice(0,t).trim();if(n)try{let e=JSON.parse(n);i.end(),clearTimeout(r),s(e)}catch(e){clearTimeout(r),a(e)}}),i.on("error",e=>{clearTimeout(r),a(e)})})}let V={sendToDaemon:async function e(e){let t=await E(),s={...e,token:t.token};return await T(t,s)}};async function P(s,a=V){let n=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=[],n=[],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 n=s.startsWith("--"),c=s.startsWith("-")&&s.length>1;if(!n&&!c){i?r.push(s):i=s;continue}let[u,d]=n?A(s):[s,void 0],g=f.get(u);if(!g){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let i=y(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 o("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new o("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 o("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 o("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||S(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 i=s??a;if(void 0===i||void 0===s&&S(i))throw new o("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 o("INVALID_ARGS",`Invalid ${k(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 o("INVALID_ARGS",`Invalid ${k(t)}: ${i}`);return{value:Math.floor(r),consumeNext:void 0===s}}(g,u,d,e[t+1]);m.consumeNext&&(t+=1),a[g.key]=m.value,l.push({key:g.key,token:u})}let c=y(i),u=new Set([...g,...c?.allowedFlags??[]]),d=l.filter(e=>!u.has(e.key));if(d.length>0){var m,h;let e=(m=i,h=d.map(e=>e.token),m?1===h.length?`Flag ${h[0]} is not supported for command ${m}.`:`Flags ${h.join(", ")} are not supported for command ${m}.`:1===h.length?`Flag ${h[0]} requires a command that supports it.`:`Flags ${h.join(", ")} require a command that supports them.`);if(s)throw new o("INVALID_ARGS",e);for(let t of(n.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),d))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:n}}(s);for(let e of n.warnings)process.stderr.write(`Warning: ${e}
|
|
14
|
+
`);n.flags.version&&(process.stdout.write(`${l()}
|
|
15
|
+
`),process.exit(0));let p="help"===n.command,c=n.flags.help;if(p||c){p&&n.positionals.length>1&&(F(new o("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=p?n.positionals[0]:n.command;e||(process.stdout.write(`${b}
|
|
16
|
+
`),process.exit(0));let t=function(e){let t=y(e);if(!t)return null;let s=v(e,t),a=x(new Set(t.allowedFlags)),i=x(g),r=[];return a.length>0&&r.push($("Command flags:",a)),r.push($("Global flags:",i)),`agent-device ${s}
|
|
9
17
|
|
|
10
|
-
|
|
11
|
-
boot Ensure target device/simulator is booted and ready
|
|
12
|
-
open [app|url] Boot device/simulator; optionally launch app or deep link URL
|
|
13
|
-
close [app] Close app or just end session
|
|
14
|
-
reinstall <app> <path> Uninstall + install app from binary path
|
|
15
|
-
snapshot [-i] [-c] [-d <depth>] [-s <scope>] [--raw] [--backend ax|xctest]
|
|
16
|
-
Capture accessibility tree
|
|
17
|
-
-i Interactive elements only
|
|
18
|
-
-c Compact output (drop empty structure)
|
|
19
|
-
-d <depth> Limit snapshot depth
|
|
20
|
-
-s <scope> Scope snapshot to label/identifier
|
|
21
|
-
--raw Raw node output
|
|
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
|
|
18
|
+
${t.description}
|
|
59
19
|
|
|
60
|
-
|
|
61
|
-
|
|
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
|
|
20
|
+
Usage:
|
|
21
|
+
agent-device ${s}
|
|
76
22
|
|
|
77
|
-
|
|
78
|
-
`
|
|
79
|
-
|
|
80
|
-
|
|
23
|
+
${r.join("\n\n")}
|
|
24
|
+
`}(e);t&&(process.stdout.write(t),process.exit(0)),F(new o("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${b}
|
|
25
|
+
`),process.exit(1)}n.command||(process.stdout.write(`${b}
|
|
26
|
+
`),process.exit(1));let{command:u,positionals:d,flags:m}=n,h=function(e){let{json:t,help:s,version:a,...i}=e;return i}(m),w=m.session??process.env.AGENT_DEVICE_SESSION??"default",N=m.verbose&&!m.json?function(){try{let t=e.join(r.homedir(),".agent-device","daemon.log"),s=0,a=!1,n=setInterval(()=>{if(a||!i.existsSync(t))return;let e=i.statSync(t);if(e.size<=s)return;let r=i.openSync(t,"r"),n=Buffer.alloc(e.size-s);i.readSync(r,n,0,n.length,s),i.closeSync(r),s=e.size,n.length>0&&process.stdout.write(n.toString("utf8"))},200);return()=>{a=!0,clearInterval(n)}}catch{return null}}():null;try{if("session"===u){let e=d[0]??"list";if("list"!==e)throw new o("INVALID_ARGS","session only supports list");let t=await a.sendToDaemon({session:w,command:"session_list",positionals:[],flags:h});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)}
|
|
27
|
+
`),N&&N();return}let e=await a.sendToDaemon({session:w,command:u,positionals:d,flags:h});if(e.ok){if(m.json){D({success:!0,data:e.data??{}}),N&&N();return}if("snapshot"===u){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,n="string"==typeof e.appBundleId?e.appBundleId:void 0,o=[];r&&o.push(`Page: ${r}`),n&&o.push(`App: ${n}`);let l=`Snapshot: ${a.length} nodes${i?" (truncated)":""}`,p=o.length>0?`${o.join("\n")}
|
|
28
|
+
`:"";if(0===a.length)return`${p}${l}
|
|
29
|
+
`;if(t.raw){let e=a.map(e=>JSON.stringify(e));return`${p}${l}
|
|
81
30
|
${e.join("\n")}
|
|
82
|
-
`}if(t.flatten){let e=
|
|
31
|
+
`}if(t.flatten){let e=a.map(e=>L(e,0,!1));return`${p}${l}
|
|
83
32
|
${e.join("\n")}
|
|
84
|
-
`}let
|
|
33
|
+
`}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"===I(e.type??"Element")&&!s;a&&c.push(t);let i=a?t:Math.max(0,t-c.length);u.push(L(e,i,a))}return`${p}${l}
|
|
85
34
|
${u.join("\n")}
|
|
86
|
-
`}(e.data??{},{raw:m.snapshotRaw,flatten:m.snapshotInteractiveOnly})),
|
|
87
|
-
`),
|
|
88
|
-
`),
|
|
89
|
-
`),
|
|
90
|
-
`),
|
|
91
|
-
`),
|
|
92
|
-
`),
|
|
93
|
-
`),
|
|
94
|
-
`),
|
|
95
|
-
`),
|
|
96
|
-
`),
|
|
97
|
-
`),
|
|
98
|
-
`),
|
|
99
|
-
`),
|
|
100
|
-
`),
|
|
101
|
-
`),
|
|
35
|
+
`}(e.data??{},{raw:m.snapshotRaw,flatten:m.snapshotInteractiveOnly})),N&&N();return}if("get"===u){let t=d[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
|
|
36
|
+
`),N&&N();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
37
|
+
`),N&&N();return}}if("find"===u){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
|
|
38
|
+
`),N&&N();return}if("boolean"==typeof t?.found){process.stdout.write(`Found: ${t.found}
|
|
39
|
+
`),N&&N();return}if(t?.node){process.stdout.write(`${JSON.stringify(t.node,null,2)}
|
|
40
|
+
`),N&&N();return}}if("is"===u){let t=e.data?.predicate??"assertion";process.stdout.write(`Passed: is ${t}
|
|
41
|
+
`),N&&N();return}if("boot"===u){let t=e.data?.platform??"unknown",s=e.data?.device??e.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${t})
|
|
42
|
+
`),N&&N();return}if("click"===u){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})
|
|
43
|
+
`),N&&N();return}if(e.data&&"object"==typeof e.data){let t=e.data;if("devices"===u){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")}
|
|
44
|
+
`),N&&N();return}if("apps"===u){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")}
|
|
45
|
+
`),N&&N();return}if("appstate"===u){let e=t?.platform,s=t?.appBundleId,a=t?.appName,i=t?.source,r=t?.package,n=t?.activity;if("ios"===e){process.stdout.write(`Foreground app: ${a??s}
|
|
46
|
+
`),s&&process.stdout.write(`Bundle: ${s}
|
|
47
|
+
`),i&&process.stdout.write(`Source: ${i}
|
|
48
|
+
`),N&&N();return}if("android"===e){process.stdout.write(`Foreground app: ${r??"unknown"}
|
|
49
|
+
`),n&&process.stdout.write(`Activity: ${n}
|
|
50
|
+
`),N&&N();return}}}N&&N();return}throw new o(e.error.code,e.error.message,e.error.details)}catch(s){let e=t(s);if(m.json)D({success:!1,error:{code:e.code,message:e.message,details:e.details}});else if(F(e),m.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
51
|
[daemon log]
|
|
103
|
-
${
|
|
104
|
-
`)}}catch{}
|
|
52
|
+
${a}
|
|
53
|
+
`)}}catch{}N&&N(),process.exit(1)}}s(process.argv[1]??"").href===import.meta.url&&P(process.argv.slice(2)).catch(e=>{F(t(e)),process.exit(1)}),P(process.argv.slice(2));
|