agent-device 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -20
- package/dist/src/797.js +1 -1
- package/dist/src/bin.js +32 -32
- package/dist/src/daemon.js +17 -17
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +8 -2
- package/package.json +7 -9
- package/skills/agent-device/SKILL.md +22 -19
- package/skills/agent-device/references/permissions.md +10 -17
- package/skills/agent-device/references/session-management.md +3 -1
- package/skills/agent-device/references/snapshot-refs.md +1 -4
- package/dist/bin/axsnapshot +0 -0
- package/ios-runner/AXSnapshot/Package.swift +0 -18
- package/ios-runner/AXSnapshot/Sources/AXSnapshot/main.swift +0 -444
- package/src/__tests__/cli-help.test.ts +0 -102
- package/src/bin.ts +0 -3
- package/src/cli.ts +0 -289
- package/src/core/__tests__/capabilities.test.ts +0 -74
- package/src/core/__tests__/open-target.test.ts +0 -16
- package/src/core/capabilities.ts +0 -57
- package/src/core/dispatch.ts +0 -360
- package/src/core/open-target.ts +0 -13
- package/src/daemon/__tests__/app-state.test.ts +0 -138
- package/src/daemon/__tests__/is-predicates.test.ts +0 -68
- package/src/daemon/__tests__/selectors.test.ts +0 -261
- package/src/daemon/__tests__/session-routing.test.ts +0 -108
- package/src/daemon/__tests__/session-selector.test.ts +0 -64
- package/src/daemon/__tests__/session-store.test.ts +0 -142
- package/src/daemon/__tests__/snapshot-processing.test.ts +0 -47
- package/src/daemon/action-utils.ts +0 -29
- package/src/daemon/app-state.ts +0 -65
- package/src/daemon/context.ts +0 -48
- package/src/daemon/device-ready.ts +0 -13
- package/src/daemon/handlers/__tests__/find.test.ts +0 -99
- package/src/daemon/handlers/__tests__/interaction.test.ts +0 -22
- package/src/daemon/handlers/__tests__/replay-heal.test.ts +0 -509
- package/src/daemon/handlers/__tests__/session-reinstall.test.ts +0 -219
- package/src/daemon/handlers/__tests__/session.test.ts +0 -343
- package/src/daemon/handlers/__tests__/snapshot-handler.test.ts +0 -92
- package/src/daemon/handlers/__tests__/snapshot.test.ts +0 -128
- package/src/daemon/handlers/find.ts +0 -324
- package/src/daemon/handlers/interaction.ts +0 -550
- package/src/daemon/handlers/parse-utils.ts +0 -8
- package/src/daemon/handlers/record-trace.ts +0 -154
- package/src/daemon/handlers/session.ts +0 -1032
- package/src/daemon/handlers/snapshot.ts +0 -439
- package/src/daemon/is-predicates.ts +0 -46
- package/src/daemon/selectors.ts +0 -540
- package/src/daemon/session-routing.ts +0 -22
- package/src/daemon/session-selector.ts +0 -39
- package/src/daemon/session-store.ts +0 -298
- package/src/daemon/snapshot-processing.ts +0 -131
- package/src/daemon/types.ts +0 -56
- package/src/daemon-client.ts +0 -172
- package/src/daemon.ts +0 -295
- package/src/platforms/__tests__/boot-diagnostics.test.ts +0 -59
- package/src/platforms/android/__tests__/index.test.ts +0 -157
- package/src/platforms/android/devices.ts +0 -196
- package/src/platforms/android/index.ts +0 -754
- package/src/platforms/android/ui-hierarchy.ts +0 -312
- package/src/platforms/boot-diagnostics.ts +0 -128
- package/src/platforms/ios/__tests__/index.test.ts +0 -24
- package/src/platforms/ios/__tests__/runner-client.test.ts +0 -113
- package/src/platforms/ios/ax-snapshot.ts +0 -207
- package/src/platforms/ios/devices.ts +0 -87
- package/src/platforms/ios/index.ts +0 -455
- package/src/platforms/ios/runner-client.ts +0 -938
- package/src/utils/__tests__/args.test.ts +0 -221
- package/src/utils/__tests__/daemon-client.test.ts +0 -78
- package/src/utils/__tests__/exec.test.ts +0 -16
- package/src/utils/__tests__/finders.test.ts +0 -34
- package/src/utils/__tests__/keyed-lock.test.ts +0 -55
- package/src/utils/__tests__/process-identity.test.ts +0 -33
- package/src/utils/__tests__/retry.test.ts +0 -44
- package/src/utils/args.ts +0 -234
- package/src/utils/command-schema.ts +0 -629
- package/src/utils/device.ts +0 -84
- package/src/utils/errors.ts +0 -35
- package/src/utils/exec.ts +0 -339
- package/src/utils/finders.ts +0 -101
- package/src/utils/interactive.ts +0 -4
- package/src/utils/interactors.ts +0 -173
- package/src/utils/keyed-lock.ts +0 -14
- package/src/utils/output.ts +0 -204
- package/src/utils/process-identity.ts +0 -100
- package/src/utils/retry.ts +0 -180
- package/src/utils/snapshot.ts +0 -64
- package/src/utils/version.ts +0 -26
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
|
|
|
@@ -91,18 +91,12 @@ agent-device swipe 540 1500 540 500 120 --count 8 --pause-ms 30 --pattern ping-p
|
|
|
91
91
|
- `settings wifi|airplane|location on|off`
|
|
92
92
|
- `appstate`, `apps`, `devices`, `session list`
|
|
93
93
|
|
|
94
|
-
##
|
|
95
|
-
|
|
96
|
-
| Backend | Speed | Accuracy | Requirements |
|
|
97
|
-
| --- | --- | --- | --- |
|
|
98
|
-
| `xctest` | Fast | High | No Accessibility permission required |
|
|
99
|
-
| `ax` | Fast | Medium | Accessibility permission for the terminal app, not recommended |
|
|
94
|
+
## iOS Snapshots
|
|
100
95
|
|
|
101
96
|
Notes:
|
|
102
|
-
-
|
|
97
|
+
- iOS snapshots use XCTest on simulators and physical devices.
|
|
103
98
|
- Scope snapshots with `-s "<label>"` or `-s @ref`.
|
|
104
99
|
- If XCTest returns 0 nodes (e.g., foreground app changed), agent-device fails explicitly.
|
|
105
|
-
- `ax` backend is simulator-only.
|
|
106
100
|
|
|
107
101
|
Flags:
|
|
108
102
|
- `--version, -V` print version and exit
|
|
@@ -120,7 +114,6 @@ Flags:
|
|
|
120
114
|
- `--pattern one-way|ping-pong` repeat pattern for `swipe`
|
|
121
115
|
- `--verbose` for daemon and runner logs
|
|
122
116
|
- `--json` for structured output
|
|
123
|
-
- `--backend ax|xctest` (snapshot only; defaults to `xctest` on iOS)
|
|
124
117
|
|
|
125
118
|
Pinch:
|
|
126
119
|
- `pinch` is supported on iOS simulators.
|
|
@@ -148,23 +141,28 @@ Sessions:
|
|
|
148
141
|
- `--save-script` accepts an optional path: `--save-script ./workflows/my-flow.ad`.
|
|
149
142
|
- For ambiguous bare values, use an explicit form: `--save-script=workflow.ad` or a path-like value such as `./workflow.ad`.
|
|
150
143
|
- Deterministic replay is `.ad`-based; use `replay --update` (`-u`) to update selector drift and rewrite the replay file in place.
|
|
144
|
+
- On iOS, `appstate` is session-scoped and requires an active session on the target device.
|
|
151
145
|
|
|
152
146
|
Navigation helpers:
|
|
153
147
|
- `boot --platform ios|android` ensures the target is ready without launching an app.
|
|
154
148
|
- Use `boot` mainly when starting a new session and `open` fails because no booted simulator/emulator is available.
|
|
155
|
-
- `open [app|url]` already boots/activates the selected target when needed.
|
|
149
|
+
- `open [app|url] [url]` already boots/activates the selected target when needed.
|
|
156
150
|
- `reinstall <app> <path>` uninstalls and installs the app binary in one command (Android + iOS simulator).
|
|
157
151
|
- `reinstall` accepts package/bundle id style app names and supports `~` in paths.
|
|
158
152
|
|
|
159
153
|
Deep links:
|
|
160
154
|
- `open <url>` supports deep links with `scheme://...`.
|
|
155
|
+
- `open <app> <url>` opens a deep link on iOS.
|
|
161
156
|
- Android opens deep links via `VIEW` intent.
|
|
162
|
-
- iOS deep
|
|
157
|
+
- iOS simulator opens deep links via `simctl openurl`.
|
|
158
|
+
- iOS device opens deep links via `devicectl --payload-url`.
|
|
159
|
+
- 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.
|
|
163
160
|
- `--activity` cannot be combined with URL opens.
|
|
164
161
|
|
|
165
162
|
```bash
|
|
166
163
|
agent-device open "myapp://home" --platform android
|
|
167
|
-
agent-device open "https://example.com" --platform ios
|
|
164
|
+
agent-device open "https://example.com" --platform ios # open link in web browser
|
|
165
|
+
agent-device open MyApp "myapp://screen/to" --platform ios # open deep link to MyApp
|
|
168
166
|
```
|
|
169
167
|
|
|
170
168
|
Find (semantic):
|
|
@@ -217,8 +215,9 @@ Settings helpers:
|
|
|
217
215
|
Note: iOS supports these only on simulators. iOS wifi/airplane toggles status bar indicators, not actual network state. Airplane off clears status bar overrides.
|
|
218
216
|
|
|
219
217
|
App state:
|
|
220
|
-
- `appstate` shows the foreground app/activity (Android).
|
|
221
|
-
-
|
|
218
|
+
- `appstate` shows the foreground app/activity (Android).
|
|
219
|
+
- On iOS, `appstate` returns the currently tracked session app (`source: session`) and requires an active session on the selected device.
|
|
220
|
+
- `apps` includes default/system apps by default (use `--user-installed` to filter).
|
|
222
221
|
|
|
223
222
|
## Debug
|
|
224
223
|
|
|
@@ -227,6 +226,7 @@ App state:
|
|
|
227
226
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
228
227
|
- Built-in retries cover transient runner connection failures and Android UI dumps.
|
|
229
228
|
- For snapshot issues (missing elements), compare with `--raw` flag for unaltered output and scope with `-s "<label>"`.
|
|
229
|
+
- If startup fails with stale metadata hints, remove stale `~/.agent-device/daemon.json` / `~/.agent-device/daemon.lock` and retry.
|
|
230
230
|
|
|
231
231
|
Boot diagnostics:
|
|
232
232
|
- Boot failures include normalized reason codes in `error.details.reason` (JSON mode) and verbose logs.
|
|
@@ -241,9 +241,8 @@ Boot diagnostics:
|
|
|
241
241
|
- Built-in aliases include `Settings` for both platforms.
|
|
242
242
|
|
|
243
243
|
## iOS notes
|
|
244
|
-
- Core runner commands
|
|
245
|
-
- Simulator-only commands: `alert`, `pinch`, `record`, `reinstall`, `
|
|
246
|
-
- iOS deep link open (`open <url>`) is simulator-only.
|
|
244
|
+
- Core runner commands: `snapshot`, `wait`, `click`, `fill`, `get`, `is`, `find`, `press`, `long-press`, `focus`, `type`, `scroll`, `scrollintoview`, `back`, `home`, `app-switcher`.
|
|
245
|
+
- Simulator-only commands: `alert`, `pinch`, `record`, `reinstall`, `settings`.
|
|
247
246
|
- 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`.
|
|
248
247
|
|
|
249
248
|
## Testing
|
|
@@ -270,11 +269,11 @@ Environment selectors:
|
|
|
270
269
|
- `ANDROID_DEVICE=Pixel_9_Pro_XL` or `ANDROID_SERIAL=emulator-5554`
|
|
271
270
|
- `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=<udid>`
|
|
272
271
|
- `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
|
|
272
|
+
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to override daemon request timeout (default `90000`). Increase for slow physical-device setup (for example `120000`).
|
|
274
273
|
- `AGENT_DEVICE_IOS_TEAM_ID=<team-id>` optional Team ID override for iOS device runner signing.
|
|
275
274
|
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
276
275
|
- `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
|
|
276
|
+
- `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.
|
|
278
277
|
- `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.
|
|
279
278
|
|
|
280
279
|
Test screenshots are written to:
|
package/dist/src/797.js
CHANGED
|
@@ -1 +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";
|
|
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";class s extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function d(e){return e instanceof s?e:e instanceof Error?new s("UNKNOWN",e.message,void 0,e):new s("UNKNOWN","Unknown error",{err:e})}function a(){try{let t=l();return JSON.parse(e.readFileSync(r.join(t,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function l(){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 c(e,t,r={}){return new Promise((n,o)=>{let u=i(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"]}),d="",a=r.binaryStdout?Buffer.alloc(0):void 0,l="",c=!1,f=h(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)]):d+=e}),u.stderr.on("data",e=>{l+=e}),u.on("error",r=>{(m&&clearTimeout(m),"ENOENT"===r.code)?o(new s("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new s("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 s("COMMAND_FAILED",`${e} timed out after ${f}ms`,{cmd:e,args:t,stdout:d,stderr:l,exitCode:u,timeoutMs:f})):0===u||r.allowFailure?n({stdout:d,stderr:l,exitCode:u,stdoutBuffer:a}):o(new s("COMMAND_FAILED",`${e} exited with code ${u}`,{cmd:e,args:t,stdout:d,stderr:l,exitCode:u}))})})}async function f(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await c(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function m(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:h(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new s("COMMAND_FAILED",`${e} timed out after ${h(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:h(r.timeoutMs)},n.error);if("ENOENT"===o)throw new s("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new s("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(),d="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),a=n.status??1;if(0!==a&&!r.allowFailure)throw new s("COMMAND_FAILED",`${e} exited with code ${a}`,{cmd:e,args:t,stdout:i,stderr:d,exitCode:a});return{stdout:i,stderr:d,exitCode:a,stdoutBuffer:o}}function w(e,t,r={}){i(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function p(e,t,r={}){return new Promise((n,o)=>{let u=i(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"]}),d="",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);d+=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 s("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new s("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:d,stderr:a,exitCode:u,stdoutBuffer:l}):o(new s("COMMAND_FAILED",`${e} exited with code ${u}`,{cmd:e,args:t,stdout:d,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 d=new Promise((i,d)=>{n.on("error",r=>{"ENOENT"===r.code?d(new s("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):d(new s("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}):d(new s("COMMAND_FAILED",`${e} exited with code ${a}`,{cmd:e,args:t,stdout:o,stderr:u,exitCode:a}))})});return{child:n,wait:d}}function h(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let E=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function S(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=m("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 g(e,t){let r;if(!S(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=m("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")&&E.some(e=>e.test(r))}function A(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(!S(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!S(e))return!0;return!S(e)}async function D(e,t){!g(e,t.expectedStartTime)||!A(e,"SIGTERM")||await I(e,t.termTimeoutMs)||A(e,"SIGKILL")&&await I(e,t.killTimeoutMs)}export{default as node_net}from"node:net";export{default as node_os}from"node:os";export{s as AppError,d as asAppError,n as fileURLToPath,l as findProjectRoot,g as isAgentDeviceDaemonProcess,S as isProcessAlive,e as node_fs,r as node_path,o as pathToFileURL,t as promises,N as readProcessStartTime,a as readVersion,c as runCmd,M as runCmdBackground,w as runCmdDetached,p as runCmdStreaming,D as stopProcessForTakeover,f as whichCmd};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,53 +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"],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:"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"]},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"]},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=k("Flags:",g.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
5
|
${a.join("\n")}
|
|
6
6
|
|
|
7
7
|
${i}
|
|
8
|
-
`}();function
|
|
9
|
-
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,a=[e];for(let e of t)a.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return a.join("\n")}function A(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function
|
|
8
|
+
`}();function $(e){return g.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function k(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
10
|
`)}function F(e){let t=e.details?`
|
|
11
11
|
${JSON.stringify(e.details,null,2)}`:"";process.stderr.write(`Error (${e.code}): ${e.message}${t}
|
|
12
|
-
`)}function
|
|
13
|
-
`)}),
|
|
14
|
-
`);
|
|
15
|
-
`),process.exit(0));let p="help"===
|
|
16
|
-
`),process.exit(0));let t=function(e){let t=
|
|
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.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=V(),a=l(),i=!!t&&await B(t);if(t&&t.version===a&&i)return t;t&&(t.version!==a||!i)&&(await P(t),J(j)),function(){let e=U();if(!e.hasLock||e.hasInfo)return;let t=G();t&&s(t.pid,t.processStartTime)||J(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=U()).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=V();if(e&&await B(e))return e;await new Promise(e=>setTimeout(e,100))}return null}async function R(){let e=U();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}),J(C),!0}async function P(e){await c(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function V(){let e=W(j);return e&&e.port&&e.token?{...e,pid:Number.isInteger(e.pid)&&e.pid>0?e.pid:0}:null}function G(){let e=W(C);return e&&Number.isInteger(e.pid)&&!(e.pid<=0)?e:null}function U(){return{hasInfo:i.existsSync(j),hasLock:i.existsSync(C)}}function W(e){if(!i.existsSync(e))return null;try{return JSON.parse(i.readFileSync(e,"utf8"))}catch{return null}}function J(e){try{i.existsSync(e)&&i.unlinkSync(e)}catch{}}async function B(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=$(new Set(t.allowedFlags)),i=$(m),n=[];return a.length>0&&n.push(k("Command flags:",a)),n.push(k("Global flags:",i)),`agent-device ${s}
|
|
17
17
|
|
|
18
18
|
${t.description}
|
|
19
19
|
|
|
20
20
|
Usage:
|
|
21
21
|
agent-device ${s}
|
|
22
22
|
|
|
23
|
-
${
|
|
24
|
-
`}(e);t&&(process.stdout.write(t),process.exit(0)),F(new o("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${
|
|
25
|
-
`),process.exit(1)}
|
|
26
|
-
`),process.exit(1));let{command:u,positionals:d,flags:
|
|
27
|
-
`),
|
|
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")}
|
|
28
28
|
`:"";if(0===a.length)return`${p}${l}
|
|
29
29
|
`;if(t.raw){let e=a.map(e=>JSON.stringify(e));return`${p}${l}
|
|
30
30
|
${e.join("\n")}
|
|
31
|
-
`}if(t.flatten){let e=a.map(e=>
|
|
31
|
+
`}if(t.flatten){let e=a.map(e=>I(e,0,!1));return`${p}${l}
|
|
32
32
|
${e.join("\n")}
|
|
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"===
|
|
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}
|
|
34
34
|
${u.join("\n")}
|
|
35
|
-
`}(e.data??{},{raw:
|
|
36
|
-
`),
|
|
37
|
-
`),
|
|
38
|
-
`),
|
|
39
|
-
`),
|
|
40
|
-
`),
|
|
41
|
-
`),
|
|
42
|
-
`),
|
|
43
|
-
`),
|
|
44
|
-
`),
|
|
45
|
-
`),
|
|
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"}
|
|
46
46
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
47
47
|
`),i&&process.stdout.write(`Source: ${i}
|
|
48
|
-
`),
|
|
49
|
-
`),
|
|
50
|
-
`),
|
|
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(`
|
|
51
51
|
[daemon log]
|
|
52
|
-
${
|
|
53
|
-
`)}}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));
|