agent-device 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -12
- package/dist/src/797.js +1 -0
- package/dist/src/bin.js +40 -29
- package/dist/src/daemon.js +21 -17
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +8 -2
- package/package.json +2 -2
- package/skills/agent-device/SKILL.md +23 -14
- package/skills/agent-device/references/permissions.md +7 -2
- package/skills/agent-device/references/session-management.md +5 -1
- package/src/__tests__/cli-close.test.ts +155 -0
- package/src/__tests__/cli-help.test.ts +102 -0
- package/src/cli.ts +68 -22
- package/src/core/__tests__/capabilities.test.ts +2 -1
- package/src/core/__tests__/dispatch-open.test.ts +25 -0
- package/src/core/__tests__/open-target.test.ts +40 -1
- package/src/core/capabilities.ts +1 -1
- package/src/core/dispatch.ts +22 -0
- package/src/core/open-target.ts +14 -0
- package/src/daemon/__tests__/device-ready.test.ts +52 -0
- package/src/daemon/__tests__/session-store.test.ts +23 -0
- package/src/daemon/device-ready.ts +146 -4
- package/src/daemon/handlers/__tests__/session.test.ts +477 -0
- package/src/daemon/handlers/session.ts +198 -93
- package/src/daemon/handlers/snapshot.ts +210 -185
- package/src/daemon/session-store.ts +16 -6
- package/src/daemon/types.ts +2 -1
- package/src/daemon-client.ts +138 -17
- package/src/daemon.ts +99 -9
- package/src/platforms/android/__tests__/index.test.ts +118 -1
- package/src/platforms/android/index.ts +77 -47
- package/src/platforms/ios/__tests__/index.test.ts +292 -4
- package/src/platforms/ios/__tests__/runner-client.test.ts +42 -0
- package/src/platforms/ios/apps.ts +358 -0
- package/src/platforms/ios/config.ts +28 -0
- package/src/platforms/ios/devicectl.ts +134 -0
- package/src/platforms/ios/devices.ts +15 -2
- package/src/platforms/ios/index.ts +20 -455
- package/src/platforms/ios/runner-client.ts +171 -69
- package/src/platforms/ios/simulator.ts +164 -0
- package/src/utils/__tests__/args.test.ts +66 -2
- package/src/utils/__tests__/daemon-client.test.ts +95 -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 +37 -1
- package/src/utils/command-schema.ts +58 -27
- package/src/utils/interactors.ts +2 -2
- package/src/utils/keyed-lock.ts +14 -0
- package/src/utils/process-identity.ts +100 -0
- package/src/utils/timeouts.ts +9 -0
- package/dist/src/274.js +0 -1
- package/src/daemon/__tests__/app-state.test.ts +0 -138
- package/src/daemon/app-state.ts +0 -65
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ The project is in early development and considered experimental. Pull requests a
|
|
|
15
15
|
## Features
|
|
16
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
|
-
- Inspection commands: `snapshot` (accessibility tree)
|
|
18
|
+
- Inspection commands: `snapshot` (accessibility tree), `appstate`, `apps`, `devices`.
|
|
19
19
|
- Device tooling: `adb` (Android), `simctl`/`devicectl` (iOS via Xcode).
|
|
20
20
|
- Minimal dependencies; TypeScript executed directly on Node 22+ (no build step).
|
|
21
21
|
|
|
@@ -99,7 +99,7 @@ agent-device swipe 540 1500 540 500 120 --count 8 --pause-ms 30 --pattern ping-p
|
|
|
99
99
|
| `ax` | Fast | Medium | Accessibility permission for the terminal app, not recommended |
|
|
100
100
|
|
|
101
101
|
Notes:
|
|
102
|
-
- Default backend is `xctest
|
|
102
|
+
- Default backend is `xctest`.
|
|
103
103
|
- Scope snapshots with `-s "<label>"` or `-s @ref`.
|
|
104
104
|
- If XCTest returns 0 nodes (e.g., foreground app changed), agent-device fails explicitly.
|
|
105
105
|
- `ax` backend is simulator-only.
|
|
@@ -145,24 +145,31 @@ Sessions:
|
|
|
145
145
|
- `close` stops the session and releases device resources. Pass an app to close it explicitly, or omit to just close the session.
|
|
146
146
|
- Use `--session <name>` to manage multiple sessions.
|
|
147
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`.
|
|
148
150
|
- Deterministic replay is `.ad`-based; use `replay --update` (`-u`) to update selector drift and rewrite the replay file in place.
|
|
151
|
+
- On iOS, `appstate` is session-scoped and requires an active session on the target device.
|
|
149
152
|
|
|
150
153
|
Navigation helpers:
|
|
151
154
|
- `boot --platform ios|android` ensures the target is ready without launching an app.
|
|
152
155
|
- Use `boot` mainly when starting a new session and `open` fails because no booted simulator/emulator is available.
|
|
153
|
-
- `open [app|url]` already boots/activates the selected target when needed.
|
|
156
|
+
- `open [app|url] [url]` already boots/activates the selected target when needed.
|
|
154
157
|
- `reinstall <app> <path>` uninstalls and installs the app binary in one command (Android + iOS simulator).
|
|
155
158
|
- `reinstall` accepts package/bundle id style app names and supports `~` in paths.
|
|
156
159
|
|
|
157
160
|
Deep links:
|
|
158
161
|
- `open <url>` supports deep links with `scheme://...`.
|
|
162
|
+
- `open <app> <url>` opens a deep link on iOS.
|
|
159
163
|
- Android opens deep links via `VIEW` intent.
|
|
160
|
-
- iOS deep
|
|
164
|
+
- iOS simulator opens deep links via `simctl openurl`.
|
|
165
|
+
- iOS device opens deep links via `devicectl --payload-url`.
|
|
166
|
+
- On iOS devices, `http(s)://` URLs open in Safari when no app is active. Custom scheme URLs (`myapp://`) require an active app in the session.
|
|
161
167
|
- `--activity` cannot be combined with URL opens.
|
|
162
168
|
|
|
163
169
|
```bash
|
|
164
170
|
agent-device open "myapp://home" --platform android
|
|
165
|
-
agent-device open "https://example.com" --platform ios
|
|
171
|
+
agent-device open "https://example.com" --platform ios # open link in web browser
|
|
172
|
+
agent-device open MyApp "myapp://screen/to" --platform ios # open deep link to MyApp
|
|
166
173
|
```
|
|
167
174
|
|
|
168
175
|
Find (semantic):
|
|
@@ -215,8 +222,9 @@ Settings helpers:
|
|
|
215
222
|
Note: iOS supports these only on simulators. iOS wifi/airplane toggles status bar indicators, not actual network state. Airplane off clears status bar overrides.
|
|
216
223
|
|
|
217
224
|
App state:
|
|
218
|
-
- `appstate` shows the foreground app/activity (Android).
|
|
219
|
-
-
|
|
225
|
+
- `appstate` shows the foreground app/activity (Android).
|
|
226
|
+
- On iOS, `appstate` returns the currently tracked session app (`source: session`) and requires an active session on the selected device.
|
|
227
|
+
- `apps` includes default/system apps by default (use `--user-installed` to filter).
|
|
220
228
|
|
|
221
229
|
## Debug
|
|
222
230
|
|
|
@@ -225,6 +233,7 @@ App state:
|
|
|
225
233
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
226
234
|
- Built-in retries cover transient runner connection failures and Android UI dumps.
|
|
227
235
|
- For snapshot issues (missing elements), compare with `--raw` flag for unaltered output and scope with `-s "<label>"`.
|
|
236
|
+
- If startup fails with stale metadata hints, remove stale `~/.agent-device/daemon.json` / `~/.agent-device/daemon.lock` and retry.
|
|
228
237
|
|
|
229
238
|
Boot diagnostics:
|
|
230
239
|
- Boot failures include normalized reason codes in `error.details.reason` (JSON mode) and verbose logs.
|
|
@@ -239,9 +248,8 @@ Boot diagnostics:
|
|
|
239
248
|
- Built-in aliases include `Settings` for both platforms.
|
|
240
249
|
|
|
241
250
|
## iOS notes
|
|
242
|
-
- Core runner commands
|
|
243
|
-
- Simulator-only commands: `alert`, `pinch`, `record`, `reinstall`, `
|
|
244
|
-
- iOS deep link open (`open <url>`) is simulator-only.
|
|
251
|
+
- Core runner commands: `snapshot`, `wait`, `click`, `fill`, `get`, `is`, `find`, `press`, `long-press`, `focus`, `type`, `scroll`, `scrollintoview`, `back`, `home`, `app-switcher`.
|
|
252
|
+
- Simulator-only commands: `alert`, `pinch`, `record`, `reinstall`, `settings`.
|
|
245
253
|
- 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`.
|
|
246
254
|
|
|
247
255
|
## Testing
|
|
@@ -268,11 +276,11 @@ Environment selectors:
|
|
|
268
276
|
- `ANDROID_DEVICE=Pixel_9_Pro_XL` or `ANDROID_SERIAL=emulator-5554`
|
|
269
277
|
- `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=<udid>`
|
|
270
278
|
- `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
|
|
279
|
+
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to override daemon request timeout (default `90000`). Increase for slow physical-device setup (for example `120000`).
|
|
272
280
|
- `AGENT_DEVICE_IOS_TEAM_ID=<team-id>` optional Team ID override for iOS device runner signing.
|
|
273
281
|
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
274
282
|
- `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
|
|
283
|
+
- `AGENT_DEVICE_IOS_RUNNER_DERIVED_PATH=<path>` optional override for iOS runner derived data root. By default, simulator uses `~/.agent-device/ios-runner/derived` and physical device uses `~/.agent-device/ios-runner/derived/device`. If you set this override, use separate paths per kind to avoid simulator/device artifact collisions.
|
|
276
284
|
- `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.
|
|
277
285
|
|
|
278
286
|
Test screenshots are written to:
|
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,42 +1,53 @@
|
|
|
1
|
-
import{node_path as e,asAppError as t,
|
|
1
|
+
import{node_path as e,asAppError as t,isAgentDeviceDaemonProcess as s,runCmdDetached as a,node_fs as i,node_os as n,node_net as r,AppError as o,readVersion as l,findProjectRoot as p,stopProcessForTakeover as c,pathToFileURL as u}from"./797.js";let d=["snapshotDepth","snapshotScope","snapshotRaw","snapshotBackend"],g=[{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 apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"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"}],m=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),f={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:[]},open:{description:"Boot device/simulator; optionally launch app or deep link URL",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{description:"Close app or just end session",positionalArgs:["app?"],allowedFlags:["saveScript"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw","snapshotBackend"]},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (includes default/system apps by default)",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{description:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},back:{description:"Navigate back (where supported)",positionalArgs:[],allowedFlags:[]},home:{description:"Go to home screen (where supported)",positionalArgs:[],allowedFlags:[]},"app-switcher":{description:"Open app switcher (where supported)",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",description:"Wait for duration, text, ref, or selector to appear",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...d]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <@ref|selector>",description:"Click element by snapshot ref or selector",positionalArgs:["target"],allowedFlags:[...d]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...d]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},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:[...d]},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:[...d]},settings:{description:"Toggle OS settings (simulators)",positionalArgs:["setting","state"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},h=new Map,y=new Map;for(let e of g){for(let t of e.names)h.set(t,e);let t=y.get(e.key);t?t.push(e):y.set(e.key,[e])}function w(e){if(e)return f[e]}function v(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function b(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(v),...t.allowedFlags.flatMap(e=>(y.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let x=function(){let e=`agent-device <command> [args] [--json]
|
|
2
2
|
|
|
3
3
|
CLI to control iOS and Android devices for AI agents.
|
|
4
|
-
`,t=Object.keys(
|
|
4
|
+
`,t=Object.keys(f).map(e=>{let t=f[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:b(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:",g.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
5
|
${a.join("\n")}
|
|
6
6
|
|
|
7
|
-
${
|
|
8
|
-
`}();function
|
|
9
|
-
`)}function
|
|
7
|
+
${i}
|
|
8
|
+
`}();function k(e){return g.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 S(e){return e.replace(/^-+/,"")}function D(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?A(e):[e,void 0];return void 0!==h.get(t)}function L(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
|
+
`)}function F(e){let t=e.details?`
|
|
10
11
|
${JSON.stringify(e.details,null,2)}`:"";process.stderr.write(`Error (${e.code}): ${e.message}${t}
|
|
11
|
-
`)}function
|
|
12
|
-
`)}),
|
|
13
|
-
`);
|
|
14
|
-
`),process.exit(0)),
|
|
15
|
-
`),process.exit(
|
|
16
|
-
|
|
12
|
+
`)}function I(e,t,s){let a=N(e.type??"Element"),i=function(e,t){var s,a;let i=e.label?.trim(),n=e.value?.trim();if("text-field"===(s=t)||"text-view"===s||"search"===s){if(n)return n;if(i)return i}else if(i)return i;if(n)return n;let r=e.identifier?.trim();return!r||(a=r,/^[\w.]+:id\/[\w.-]+$/i.test(a)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":r}(e,a),n=" ".repeat(t),r=e.ref?`@${e.ref}`:"",o=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=o?` [${o}]`:"",p=i?` "${i}"`:"";return s?`${n}${r} [${a}]${l}`.trimEnd():`${n}${r} [${a}]${p}${l}`.trimEnd()}function N(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 O=e.join(n.homedir(),".agent-device"),j=e.join(O,"daemon.json"),C=e.join(O,"daemon.lock"),E=function(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}();async function M(e){let t=await _(),s={...e,token:t.token};return await q(t,s)}async function _(){var e;let t=P(),a=l(),i=!!t&&await J(t);if(t&&t.version===a&&i)return t;t&&(t.version!==a||!i)&&(await V(t),B(j)),function(){let e=W();if(!e.hasLock||e.hasInfo)return;let t=G();t&&s(t.pid,t.processStartTime)||B(C)}(),await z();let n=await T(5e3);if(n)return n;if(await R()){await z();let e=await T(5e3);if(e)return e}throw new o("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:j,lockPath:C,hint:(e=W()).hasLock&&!e.hasInfo?"Detected ~/.agent-device/daemon.lock without daemon.json. If no agent-device daemon process is running, delete ~/.agent-device/daemon.lock and retry.":e.hasLock&&e.hasInfo?"Daemon metadata may be stale. If no agent-device daemon process is running, delete ~/.agent-device/daemon.json and ~/.agent-device/daemon.lock, then retry.":"Daemon metadata is missing or stale. Delete ~/.agent-device/daemon.json if present and retry."})}async function T(e){let t=Date.now();for(;Date.now()-t<e;){let e=P();if(e&&await J(e))return e;await new Promise(e=>setTimeout(e,100))}return null}async function R(){let e=W();if(!e.hasLock||e.hasInfo)return!1;let t=G();return t&&s(t.pid,t.processStartTime)&&await c(t.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:t.processStartTime}),B(C),!0}async function V(e){await c(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function P(){let e=U(j);return e&&e.port&&e.token?{...e,pid:Number.isInteger(e.pid)&&e.pid>0?e.pid:0}:null}function G(){let e=U(C);return e&&Number.isInteger(e.pid)&&!(e.pid<=0)?e:null}function W(){return{hasInfo:i.existsSync(j),hasLock:i.existsSync(C)}}function U(e){if(!i.existsSync(e))return null;try{return JSON.parse(i.readFileSync(e,"utf8"))}catch{return null}}function B(e){try{i.existsSync(e)&&i.unlinkSync(e)}catch{}}async function J(e){return new Promise(t=>{let s=r.createConnection({host:"127.0.0.1",port:e.port},()=>{s.destroy(),t(!0)});s.on("error",()=>{t(!1)})})}async function z(){let t=p(),s=e.join(t,"dist","src","daemon.js"),n=e.join(t,"src","daemon.ts"),r=i.existsSync(s),l=i.existsSync(n);if(!r&&!l)throw new o("COMMAND_FAILED","Daemon entry not found",{distPath:s,srcPath:n});let c=(process.execArgv.includes("--experimental-strip-types")?l:!r&&l)?["--experimental-strip-types",n]:[s];a(process.execPath,c)}async function q(e,t){return new Promise((s,a)=>{let i=r.createConnection({host:"127.0.0.1",port:e.port},()=>{i.write(`${JSON.stringify(t)}
|
|
13
|
+
`)}),n=setTimeout(()=>{i.destroy(),a(new o("COMMAND_FAILED","Daemon request timed out",{timeoutMs:E}))},E),l="";i.setEncoding("utf8"),i.on("data",e=>{let t=(l+=e).indexOf("\n");if(-1===t)return;let r=l.slice(0,t).trim();if(r)try{let e=JSON.parse(r);i.end(),clearTimeout(n),s(e)}catch(e){clearTimeout(n),a(e)}}),i.on("error",e=>{clearTimeout(n),a(e)})})}let K={sendToDaemon:M};async function X(s,a=K){let r=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,n=[],r=[],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?n.push(s):i=s;continue}let r=s.startsWith("--"),c=s.startsWith("-")&&s.length>1;if(!r&&!c){i?n.push(s):i=s;continue}let[u,d]=r?A(s):[s,void 0],g=h.get(u);if(!g){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let i=w(e);return!i||!!i.allowsExtraPositionals||0!==i.positionalArgs.length&&(t.length<i.positionalArgs.length||i.positionalArgs.some(e=>e.includes("?")))}(i,n,s)){i?n.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||D(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&&D(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 ${S(t)}: ${i}`);return{value:i,consumeNext:void 0===s}}let n=Number(i);if(!Number.isFinite(n)||"number"==typeof e.min&&n<e.min||"number"==typeof e.max&&n>e.max)throw new o("INVALID_ARGS",`Invalid ${S(t)}: ${i}`);return{value:Math.floor(n),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=w(i),u=new Set([...m,...c?.allowedFlags??[]]),d=l.filter(e=>!u.has(e.key));if(d.length>0){var g,f;let e=(g=i,f=d.map(e=>e.token),g?1===f.length?`Flag ${f[0]} is not supported for command ${g}.`:`Flags ${f.join(", ")} are not supported for command ${g}.`:1===f.length?`Flag ${f[0]} requires a command that supports it.`:`Flags ${f.join(", ")} require a command that supports them.`);if(s)throw new o("INVALID_ARGS",e);for(let t of(r.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:n,flags:a,warnings:r}}(s);for(let e of r.warnings)process.stderr.write(`Warning: ${e}
|
|
14
|
+
`);r.flags.version&&(process.stdout.write(`${l()}
|
|
15
|
+
`),process.exit(0));let p="help"===r.command,c=r.flags.help;if(p||c){p&&r.positionals.length>1&&(F(new o("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=p?r.positionals[0]:r.command;e||(process.stdout.write(`${x}
|
|
16
|
+
`),process.exit(0));let t=function(e){let t=w(e);if(!t)return null;let s=b(e,t),a=k(new Set(t.allowedFlags)),i=k(m),n=[];return a.length>0&&n.push($("Command flags:",a)),n.push($("Global flags:",i)),`agent-device ${s}
|
|
17
|
+
|
|
18
|
+
${t.description}
|
|
19
|
+
|
|
20
|
+
Usage:
|
|
21
|
+
agent-device ${s}
|
|
22
|
+
|
|
23
|
+
${n.join("\n\n")}
|
|
24
|
+
`}(e);t&&(process.stdout.write(t),process.exit(0)),F(new o("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${x}
|
|
25
|
+
`),process.exit(1)}r.command||(process.stdout.write(`${x}
|
|
26
|
+
`),process.exit(1));let{command:u,positionals:d,flags:g}=r,f=function(e){let{json:t,help:s,version:a,...i}=e;return i}(g),y=g.session??process.env.AGENT_DEVICE_SESSION??"default",v=g.verbose&&!g.json?function(){try{let t=e.join(n.homedir(),".agent-device","daemon.log"),s=0,a=!1,r=setInterval(()=>{if(!a&&i.existsSync(t))try{let e=i.statSync(t);if(e.size<s&&(s=0),e.size<=s)return;let a=i.openSync(t,"r");try{let t=Buffer.alloc(e.size-s);i.readSync(a,t,0,t.length,s),s=e.size,t.length>0&&process.stdout.write(t.toString("utf8"))}finally{i.closeSync(a)}}catch{}},200);return()=>{a=!0,clearInterval(r)}}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:y,command:"session_list",positionals:[],flags:f});if(!t.ok)throw new o(t.error.code,t.error.message);g.json?L({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
27
|
+
`),v&&v();return}let e=await a.sendToDaemon({session:y,command:u,positionals:d,flags:f});if(e.ok){if(g.json){L({success:!0,data:e.data??{}}),v&&v();return}if("snapshot"===u){process.stdout.write(function(e,t={}){let s=e.nodes,a=Array.isArray(s)?s:[],i=!!e.truncated,n="string"==typeof e.appName?e.appName:void 0,r="string"==typeof e.appBundleId?e.appBundleId:void 0,o=[];n&&o.push(`Page: ${n}`),r&&o.push(`App: ${r}`);let l=`Snapshot: ${a.length} nodes${i?" (truncated)":""}`,p=o.length>0?`${o.join("\n")}
|
|
17
28
|
`:"";if(0===a.length)return`${p}${l}
|
|
18
29
|
`;if(t.raw){let e=a.map(e=>JSON.stringify(e));return`${p}${l}
|
|
19
30
|
${e.join("\n")}
|
|
20
|
-
`}if(t.flatten){let e=a.map(e=>
|
|
31
|
+
`}if(t.flatten){let e=a.map(e=>I(e,0,!1));return`${p}${l}
|
|
21
32
|
${e.join("\n")}
|
|
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"===
|
|
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"===N(e.type??"Element")&&!s;a&&c.push(t);let i=a?t:Math.max(0,t-c.length);u.push(I(e,i,a))}return`${p}${l}
|
|
23
34
|
${u.join("\n")}
|
|
24
|
-
`}(e.data??{},{raw:
|
|
25
|
-
`),
|
|
26
|
-
`),
|
|
27
|
-
`),
|
|
28
|
-
`),
|
|
29
|
-
`),
|
|
30
|
-
`),
|
|
31
|
-
`),
|
|
32
|
-
`),
|
|
33
|
-
`),
|
|
34
|
-
`),
|
|
35
|
+
`}(e.data??{},{raw:g.snapshotRaw,flatten:g.snapshotInteractiveOnly})),v&&v();return}if("get"===u){let t=d[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
|
|
36
|
+
`),v&&v();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
37
|
+
`),v&&v();return}}if("find"===u){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
|
|
38
|
+
`),v&&v();return}if("boolean"==typeof t?.found){process.stdout.write(`Found: ${t.found}
|
|
39
|
+
`),v&&v();return}if(t?.node){process.stdout.write(`${JSON.stringify(t.node,null,2)}
|
|
40
|
+
`),v&&v();return}}if("is"===u){let t=e.data?.predicate??"assertion";process.stdout.write(`Passed: is ${t}
|
|
41
|
+
`),v&&v();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
|
+
`),v&&v();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
|
+
`),v&&v();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
|
+
`),v&&v();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?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${e.join("\n")}
|
|
45
|
+
`),v&&v();return}if("appstate"===u){let e=t?.platform,s=t?.appBundleId,a=t?.appName,i=t?.source,n=t?.package,r=t?.activity;if("ios"===e){process.stdout.write(`Foreground app: ${a??s??"unknown"}
|
|
35
46
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
36
47
|
`),i&&process.stdout.write(`Source: ${i}
|
|
37
|
-
`),
|
|
38
|
-
`),
|
|
39
|
-
`),
|
|
48
|
+
`),v&&v();return}if("android"===e){process.stdout.write(`Foreground app: ${n??"unknown"}
|
|
49
|
+
`),r&&process.stdout.write(`Activity: ${r}
|
|
50
|
+
`),v&&v();return}}}v&&v();return}throw new o(e.error.code,e.error.message,e.error.details)}catch(a){var O;let s=t(a);if("close"===u&&"COMMAND_FAILED"===(O=s).code&&(O.details?.kind==="daemon_startup_failed"||O.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof O.details?.infoPath||"string"==typeof O.details?.lockPath))){g.json&&L({success:!0,data:{closed:"session",source:"no-daemon"}}),v&&v();return}if(g.json)L({success:!1,error:{code:s.code,message:s.message,details:s.details}});else if(F(s),g.verbose)try{let t=e.join(n.homedir(),".agent-device","daemon.log");if(i.existsSync(t)){let e=i.readFileSync(t,"utf8").split("\n"),s=e.slice(Math.max(0,e.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
40
51
|
[daemon log]
|
|
41
|
-
${
|
|
42
|
-
`)}}catch{}
|
|
52
|
+
${s}
|
|
53
|
+
`)}}catch{}v&&v(),process.exit(1)}}u(process.argv[1]??"").href===import.meta.url&&X(process.argv.slice(2)).catch(e=>{F(t(e)),process.exit(1)}),X(process.argv.slice(2));
|