agent-device 0.5.5 → 0.6.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 +44 -7
- package/dist/src/350.js +3 -0
- package/dist/src/bin.js +43 -34
- package/dist/src/daemon.js +19 -16
- package/ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +618 -97
- package/package.json +2 -2
- package/skills/agent-device/SKILL.md +67 -204
- package/skills/agent-device/references/logs-and-debug.md +92 -0
- package/skills/agent-device/references/snapshot-refs.md +20 -0
- package/dist/src/407.js +0 -3
package/README.md
CHANGED
|
@@ -15,7 +15,8 @@ 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), `appstate`, `apps`, `devices`.
|
|
18
|
+
- Inspection commands: `snapshot` (accessibility tree), `diff snapshot` (structural baseline diff), `appstate`, `apps`, `devices`.
|
|
19
|
+
- App logs: `logs path` returns session log metadata; `logs start` / `logs stop` stream app output; `logs clear` truncates session app logs; `logs clear --restart` resets and restarts stream in one step; `logs doctor` checks readiness; `logs mark` writes timeline markers.
|
|
19
20
|
- Device tooling: `adb` (Android), `simctl`/`devicectl` (iOS via Xcode).
|
|
20
21
|
- Minimal dependencies; TypeScript executed directly on Node 22+ (no build step).
|
|
21
22
|
|
|
@@ -31,6 +32,8 @@ Or use it without installing:
|
|
|
31
32
|
npx agent-device open SampleApp
|
|
32
33
|
```
|
|
33
34
|
|
|
35
|
+
The skill is also accessible on [ClawHub](https://clawhub.ai/okwasniewski/agent-device).
|
|
36
|
+
|
|
34
37
|
## Quick Start
|
|
35
38
|
|
|
36
39
|
Use refs for agent-driven exploration and normal automation flows.
|
|
@@ -40,6 +43,7 @@ Use `press` as the canonical tap command; `click` is an equivalent alias.
|
|
|
40
43
|
agent-device open Contacts --platform ios # creates session on iOS Simulator
|
|
41
44
|
agent-device snapshot
|
|
42
45
|
agent-device press @e5
|
|
46
|
+
agent-device diff snapshot # subsequent runs compare against previous baseline
|
|
43
47
|
agent-device fill @e6 "John"
|
|
44
48
|
agent-device fill @e7 "Doe"
|
|
45
49
|
agent-device press @e3
|
|
@@ -118,7 +122,7 @@ agent-device trace stop ./trace.log
|
|
|
118
122
|
```
|
|
119
123
|
|
|
120
124
|
Coordinates:
|
|
121
|
-
- All coordinate-based commands (`press`, `
|
|
125
|
+
- All coordinate-based commands (`press`, `longpress`, `swipe`, `focus`, `fill`) use device coordinates with origin at top-left.
|
|
122
126
|
- X increases to the right, Y increases downward.
|
|
123
127
|
- `press` is the canonical tap command.
|
|
124
128
|
- `click` is an equivalent alias and accepts the same targets (`x y`, `@ref`, selector) and flags.
|
|
@@ -130,15 +134,18 @@ agent-device press 300 500 --count 12 --interval-ms 45
|
|
|
130
134
|
agent-device press 300 500 --count 6 --hold-ms 120 --interval-ms 30 --jitter-px 2
|
|
131
135
|
agent-device press @e5 --count 5 --double-tap
|
|
132
136
|
agent-device swipe 540 1500 540 500 120 --count 8 --pause-ms 30 --pattern ping-pong
|
|
137
|
+
agent-device scrollintoview "Sign in"
|
|
138
|
+
agent-device scrollintoview @e42
|
|
133
139
|
```
|
|
134
140
|
|
|
135
141
|
## Command Index
|
|
136
142
|
- `boot`, `open`, `close`, `reinstall`, `home`, `back`, `app-switcher`
|
|
137
143
|
- `batch`
|
|
138
|
-
- `snapshot`, `find`, `get`
|
|
144
|
+
- `snapshot`, `diff snapshot`, `find`, `get`
|
|
139
145
|
- `press` (alias: `click`), `focus`, `type`, `fill`, `long-press`, `swipe`, `scroll`, `scrollintoview`, `pinch`, `is`
|
|
140
146
|
- `alert`, `wait`, `screenshot`
|
|
141
147
|
- `trace start`, `trace stop`
|
|
148
|
+
- `logs path`, `logs start`, `logs stop`, `logs clear`, `logs clear --restart`, `logs doctor`, `logs mark` (session app log file for grep; iOS simulator + iOS device + Android)
|
|
142
149
|
- `settings wifi|airplane|location on|off`
|
|
143
150
|
- `settings faceid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
144
151
|
- `appstate`, `apps`, `devices`, `session list`
|
|
@@ -149,6 +156,20 @@ Notes:
|
|
|
149
156
|
- iOS snapshots use XCTest on simulators and physical devices.
|
|
150
157
|
- Scope snapshots with `-s "<label>"` or `-s @ref`.
|
|
151
158
|
- If XCTest returns 0 nodes (e.g., foreground app changed), agent-device fails explicitly.
|
|
159
|
+
- `diff snapshot` uses the same snapshot flags and compares the current capture with the previous session baseline, then updates baseline.
|
|
160
|
+
|
|
161
|
+
Diff snapshots:
|
|
162
|
+
- Run `diff snapshot` once to initialize baseline for the current session.
|
|
163
|
+
- Run `diff snapshot` again after UI changes to get unified-style output (`-` removed, `+` added, unchanged context).
|
|
164
|
+
- Use `--json` to get `{ mode, baselineInitialized, summary, lines }`.
|
|
165
|
+
|
|
166
|
+
Efficient snapshot usage:
|
|
167
|
+
- Default to `snapshot -i` for iterative agent loops.
|
|
168
|
+
- Add `-s "<label>"` (or `-s @ref`) for screen-local work to reduce payload size.
|
|
169
|
+
- Add `-d <depth>` when lower tree levels are not needed.
|
|
170
|
+
- Re-snapshot after UI mutations before reusing refs.
|
|
171
|
+
- Use `diff snapshot` for low-noise structural change verification between adjacent states.
|
|
172
|
+
- Reserve `--raw` for troubleshooting and parser/debug investigations.
|
|
152
173
|
|
|
153
174
|
Flags:
|
|
154
175
|
- `--version, -V` print version and exit
|
|
@@ -179,7 +200,8 @@ Pinch:
|
|
|
179
200
|
Swipe timing:
|
|
180
201
|
- `swipe` accepts optional `durationMs` (default `250`, range `16..10000`).
|
|
181
202
|
- Android uses requested swipe duration directly.
|
|
182
|
-
- iOS
|
|
203
|
+
- iOS clamps swipe duration to a safe range (`16..60ms`) to avoid longpress side effects.
|
|
204
|
+
- `scrollintoview` accepts either plain text or a snapshot ref (`@eN`); ref mode uses best-effort geometry-based scrolling without post-scroll verification. Run `snapshot` again before follow-up `@ref` commands.
|
|
183
205
|
|
|
184
206
|
## Skills
|
|
185
207
|
Install the automation skills listed in [SKILL.md](skills/agent-device/SKILL.md).
|
|
@@ -278,6 +300,14 @@ App state:
|
|
|
278
300
|
|
|
279
301
|
## Debug
|
|
280
302
|
|
|
303
|
+
- **App logs (token-efficient):** Logging is off by default in normal flows. Enable it on demand when debugging. With an active session, run `logs path` to get path + state metadata (e.g. `~/.agent-device/sessions/<session>/app.log`). Run `logs start` to stream app output to that file; use `logs stop` to stop. Run `logs clear` to truncate `app.log` (and remove rotated `app.log.N` files) before a new repro window. Run `logs doctor` for tool/runtime checks and `logs mark "step"` to insert timeline markers. Grep the file when you need to inspect errors (e.g. `grep -n "Error\|Exception" <path>`) instead of pulling full logs into context. Supported on iOS simulator, iOS physical device, and Android.
|
|
304
|
+
- Use `logs clear --restart` when you want one command to stop an active stream, clear current logs, and immediately resume streaming.
|
|
305
|
+
- `logs start` appends to `app.log` and rotates to `app.log.1` when the file exceeds 5 MB.
|
|
306
|
+
- Android log streaming automatically rebinds to the app PID after process restarts.
|
|
307
|
+
- Detailed playbook: `skills/agent-device/references/logs-and-debug.md`
|
|
308
|
+
- iOS log capture relies on Unified Logging signals (for example `os_log`); plain stdout/stderr output may be limited depending on app/runtime.
|
|
309
|
+
- Retention knobs: set `AGENT_DEVICE_APP_LOG_MAX_BYTES` and `AGENT_DEVICE_APP_LOG_MAX_FILES` to override rotation limits.
|
|
310
|
+
- Optional write-time redaction patterns: set `AGENT_DEVICE_APP_LOG_REDACT_PATTERNS` to a comma-separated regex list.
|
|
281
311
|
- `agent-device trace start`
|
|
282
312
|
- `agent-device trace stop ./trace.log`
|
|
283
313
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
@@ -304,8 +334,15 @@ Diagnostics files:
|
|
|
304
334
|
- Built-in aliases include `Settings` for both platforms.
|
|
305
335
|
|
|
306
336
|
## iOS notes
|
|
307
|
-
- Core runner commands: `snapshot`, `wait`, `click`, `fill`, `get`, `is`, `find`, `press`, `
|
|
308
|
-
- Simulator-only commands: `alert`, `pinch`, `
|
|
337
|
+
- Core runner commands: `snapshot`, `wait`, `click`, `fill`, `get`, `is`, `find`, `press`, `longpress`, `focus`, `type`, `scroll`, `scrollintoview`, `back`, `home`, `app-switcher`.
|
|
338
|
+
- Simulator-only commands: `alert`, `pinch`, `settings`.
|
|
339
|
+
- `record` supports iOS simulators and physical iOS devices.
|
|
340
|
+
- iOS simulator recording uses native `simctl io ... recordVideo`.
|
|
341
|
+
- Physical iOS device recording is runner-based and built from repeated `XCUIScreen.main.screenshot()` frames (no native video stream/audio capture).
|
|
342
|
+
- Physical iOS device recording requires an active app session context (`open <app>` first) so capture targets your app instead of the runner host app.
|
|
343
|
+
- Physical iOS device capture is best-effort: dropped frames are expected and true 60 FPS is not guaranteed even with `--fps 60`.
|
|
344
|
+
- Physical iOS device recording defaults to uncapped (max available) FPS.
|
|
345
|
+
- Use `agent-device record start [path] --fps <n>` (1-120) to set an explicit FPS cap on physical iOS devices.
|
|
309
346
|
- 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`.
|
|
310
347
|
|
|
311
348
|
## Testing
|
|
@@ -337,7 +374,7 @@ Environment selectors:
|
|
|
337
374
|
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
338
375
|
- `AGENT_DEVICE_IOS_PROVISIONING_PROFILE=<profile>` optional provisioning profile specifier for iOS device runner signing.
|
|
339
376
|
- `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.
|
|
340
|
-
- `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.
|
|
377
|
+
- `AGENT_DEVICE_IOS_CLEAN_DERIVED=1` rebuild iOS runner artifacts from scratch for runtime daemon-triggered builds (`pnpm ad ...`) on the selected path. `pnpm build:xcuitest`/`pnpm build:all` already clear `~/.agent-device/ios-runner/derived/device` and do not require this variable. 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.
|
|
341
378
|
|
|
342
379
|
Test screenshots are written to:
|
|
343
380
|
- `test/screenshots/android-settings.png`
|
package/dist/src/350.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{AsyncLocalStorage as e}from"node:async_hooks";import t from"node:crypto";import r,{promises as n}from"node:fs";import o from"node:os";import i from"node:path";import{fileURLToPath as a,pathToFileURL as s}from"node:url";import{spawn as c,spawnSync as l}from"node:child_process";let d=new e,u=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,f=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function m(){return t.randomBytes(8).toString("hex")}async function p(e,r){let n={...e,diagnosticId:`${Date.now().toString(36)}-${t.randomBytes(4).toString("hex")}`,events:[]};return await d.run(n,r)}function h(){let e=d.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function w(e){let t=d.getStore();if(!t)return;let n={ts:new Date().toISOString(),level:e.level??"info",phase:e.phase,session:t.session,requestId:t.requestId,command:t.command,durationMs:e.durationMs,data:e.data?y(e.data):void 0};if(t.events.push(n),!t.debug)return;let o=`[agent-device][diag] ${JSON.stringify(n)}
|
|
2
|
+
`;try{t.logPath&&r.appendFile(t.logPath,o,()=>{}),t.traceLogPath&&r.appendFile(t.traceLogPath,o,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(o)}catch{}}async function g(e,t,r){let n=Date.now();try{let o=await t();return w({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw w({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function S(e={}){let t=d.getStore();if(!t||!e.force&&!t.debug||0===t.events.length)return null;try{let e=(t.session??"default").replace(/[^a-zA-Z0-9._-]/g,"_"),n=new Date().toISOString().slice(0,10),a=i.join(o.homedir(),".agent-device","logs",e,n);r.mkdirSync(a,{recursive:!0});let s=new Date().toISOString().replace(/[:.]/g,"-"),c=i.join(a,`${s}-${t.diagnosticId}.ndjson`),l=t.events.map(e=>JSON.stringify(y(e)));return r.writeFileSync(c,`${l.join("\n")}
|
|
3
|
+
`),t.events=[],c}catch{return null}}function y(e){return function e(t,r,n){if(null==t)return t;if("string"==typeof t){var o=t,i=n;let e=o.trim();if(!e)return o;if(i&&u.test(i)||f.test(e))return"[REDACTED]";let r=function(e){try{let t=new URL(e);return t.search&&(t.search="?REDACTED"),(t.username||t.password)&&(t.username="REDACTED",t.password="REDACTED"),t.toString()}catch{return null}}(e);return r||(e.length>400?`${e.slice(0,200)}...<truncated>`:e)}if("object"!=typeof t)return t;if(r.has(t))return"[Circular]";if(r.add(t),Array.isArray(t))return t.map(t=>e(t,r));let a={};for(let[n,o]of Object.entries(t)){if(u.test(n)){a[n]="[REDACTED]";continue}a[n]=e(o,r,n)}return a}(e,new WeakSet)}class v extends Error{code;details;cause;constructor(e,t,r,n){super(t),this.code=e,this.details=r,this.cause=n}}function A(e){return e instanceof v?e:e instanceof Error?new v("UNKNOWN",e.message,void 0,e):new v("UNKNOWN","Unknown error",{err:e})}function I(e,t={}){let r=A(e),n=r.details?y(r.details):void 0,o=n&&"string"==typeof n.hint?n.hint:void 0,i=(n&&"string"==typeof n.diagnosticId?n.diagnosticId:void 0)??t.diagnosticId,a=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,s=o??function(e){switch(e){case"INVALID_ARGS":return"Check command arguments and run --help for usage examples.";case"SESSION_NOT_FOUND":return"Run open first or pass an explicit device selector.";case"TOOL_MISSING":return"Install required platform tooling and ensure it is available in PATH.";case"DEVICE_NOT_FOUND":return"Verify the target device is booted/connected and selectors match.";case"UNSUPPORTED_OPERATION":return"This command is not available for the selected platform/device.";case"COMMAND_FAILED":default:return"Retry with --debug and inspect diagnostics log for details.";case"UNAUTHORIZED":return"Refresh daemon metadata and retry the command."}}(r.code),c=function(e){if(!e)return;let t={...e};return delete t.hint,delete t.diagnosticId,delete t.logPath,Object.keys(t).length>0?t:void 0}(n);return{code:r.code,message:r.message,hint:s,diagnosticId:i,logPath:a,details:c}}function D(e){let t=[],r=[];for(let n of e){let e=n.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let o=n.label?.trim()||n.value?.trim()||n.identifier?.trim()||"",i=N(n.type??"Element"),a="group"===i&&!o;a&&t.push(e);let s=a?e:Math.max(0,e-t.length);r.push({node:n,depth:s,type:i,text:b(n,s,a,i)})}return r}function b(e,t,r,n){let o=n??N(e.type??"Element"),i=E(e,o),a=" ".repeat(t),s=e.ref?`@${e.ref}`:"",c=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),l=c?` [${c}]`:"",d=i?` "${i}"`:"";return r?`${a}${s} [${o}]${l}`.trimEnd():`${a}${s} [${o}]${d}${l}`.trimEnd()}function E(e,t){var r,n;let o=e.label?.trim(),i=e.value?.trim();if("text-field"===(r=t)||"text-view"===r||"search"===r){if(i)return i;if(o)return o}else if(o)return o;if(i)return i;let a=e.identifier?.trim();return!a||(n=a,/^[\w.]+:id\/[\w.-]+$/i.test(n)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":a}function N(e){let t=e.replace(/XCUIElementType/gi,"").toLowerCase(),r=e.includes(".")&&(e.startsWith("android.")||e.startsWith("androidx.")||e.startsWith("com."));switch(t.includes(".")&&(t=t.replace(/^android\.widget\./,"").replace(/^android\.view\./,"").replace(/^android\.webkit\./,"").replace(/^androidx\./,"").replace(/^com\.google\.android\./,"").replace(/^com\.android\./,"")),t){case"application":return"application";case"navigationbar":return"navigation-bar";case"tabbar":return"tab-bar";case"button":case"imagebutton":return"button";case"link":return"link";case"cell":return"cell";case"statictext":case"checkedtextview":return"text";case"textfield":case"edittext":return"text-field";case"textview":return r?"text":"text-view";case"textarea":return"text-view";case"switch":return"switch";case"slider":return"slider";case"image":case"imageview":return"image";case"webview":return"webview";case"framelayout":case"linearlayout":case"relativelayout":case"constraintlayout":case"viewgroup":case"view":case"group":return"group";case"listview":case"recyclerview":return"list";case"collectionview":return"collection";case"searchfield":return"search";case"segmentedcontrol":return"segmented-control";case"window":return"window";case"checkbox":return"checkbox";case"radio":return"radio";case"menuitem":return"menu-item";case"toolbar":return"toolbar";case"scrollarea":case"scrollview":case"nestedscrollview":return"scroll-area";case"table":return"table";default:return t||"element"}}function $(){try{let e=_();return JSON.parse(r.readFileSync(i.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function _(){let e=i.dirname(a(import.meta.url)),t=e;for(let e=0;e<6;e+=1){let e=i.join(t,"package.json");if(r.existsSync(e))return t;t=i.dirname(t)}return e}async function M(e,t,r={}){return new Promise((n,o)=>{let i=c(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",s=r.binaryStdout?Buffer.alloc(0):void 0,l="",d=!1,u=F(r.timeoutMs),f=u?setTimeout(()=>{d=!0,i.kill("SIGKILL")},u):null;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{r.binaryStdout?s=Buffer.concat([s??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),i.stderr.on("data",e=>{l+=e}),i.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?o(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{f&&clearTimeout(f);let c=i??1;d&&u?o(new v("COMMAND_FAILED",`${e} timed out after ${u}ms`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:c,timeoutMs:u})):0===c||r.allowFailure?n({stdout:a,stderr:l,exitCode:c,stdoutBuffer:s}):o(new v("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:a,stderr:l,exitCode:c}))})})}async function O(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 M(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function T(e,t,r={}){let n=l(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:F(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new v("COMMAND_FAILED",`${e} timed out after ${F(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:F(r.timeoutMs)},n.error);if("ENOENT"===o)throw new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},n.error);throw new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},n.error)}let o=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,i=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),s=n.status??1;if(0!==s&&!r.allowFailure)throw new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:i,stderr:a,exitCode:s});return{stdout:i,stderr:a,exitCode:s,stdoutBuffer:o}}function L(e,t,r={}){c(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function x(e,t,r={}){return new Promise((n,o)=>{let i=c(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(i);let a="",s="",l=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),void 0!==r.stdin&&i.stdin.write(r.stdin),i.stdin.end(),i.stdout.on("data",e=>{if(r.binaryStdout){l=Buffer.concat([l??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),i.stderr.on("data",e=>{let t=String(e);s+=t,r.onStderrChunk?.(t)}),i.on("error",r=>{"ENOENT"===r.code?o(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):o(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),i.on("close",i=>{let c=i??1;0===c||r.allowFailure?n({stdout:a,stderr:s,exitCode:c,stdoutBuffer:l}):o(new v("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:a,stderr:s,exitCode:c}))})})}function C(e,t,r={}){let n=c(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),o="",i="";n.stdout.setEncoding("utf8"),n.stderr.setEncoding("utf8"),n.stdout.on("data",e=>{o+=e}),n.stderr.on("data",e=>{i+=e});let a=new Promise((a,s)=>{n.on("error",r=>{"ENOENT"===r.code?s(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):s(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),n.on("close",n=>{let c=n??1;0===c||r.allowFailure?a({stdout:o,stderr:i,exitCode:c}):s(new v("COMMAND_FAILED",`${e} exited with code ${c}`,{cmd:e,args:t,stdout:o,stderr:i,exitCode:c}))})});return{child:n,wait:a}}function F(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let P=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function R(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function k(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=T("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 B(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=T("ps",["-p",String(e),"-o","command="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function G(e,t){let r;if(!R(e))return!1;if(t){let r=k(e);if(!r||r!==t)return!1}let n=B(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&P.some(e=>e.test(r))}function j(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 U(e,t){if(!R(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!R(e))return!0;return!R(e)}async function V(e,t){!G(e,t.expectedStartTime)||!j(e,"SIGTERM")||await U(e,t.termTimeoutMs)||j(e,"SIGKILL")&&await U(e,t.killTimeoutMs)}let q=100,H=new Set(["batch","replay"]);function J(e){let t;try{t=JSON.parse(e)}catch{throw new v("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(t)||0===t.length)throw new v("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return t}function W(e,t){if(!Array.isArray(e)||0===e.length)throw new v("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(e.length>t)throw new v("INVALID_ARGS",`batch has ${e.length} steps; max allowed is ${t}.`);let r=[];for(let t=0;t<e.length;t+=1){let n=e[t];if(!n||"object"!=typeof n)throw new v("INVALID_ARGS",`Invalid batch step at index ${t}.`);let o="string"==typeof n.command?n.command.trim().toLowerCase():"";if(!o)throw new v("INVALID_ARGS",`Batch step ${t+1} requires command.`);if(H.has(o))throw new v("INVALID_ARGS",`Batch step ${t+1} cannot run ${o}.`);if(void 0!==n.positionals&&!Array.isArray(n.positionals))throw new v("INVALID_ARGS",`Batch step ${t+1} positionals must be an array.`);let i=n.positionals??[];if(i.some(e=>"string"!=typeof e))throw new v("INVALID_ARGS",`Batch step ${t+1} positionals must contain only strings.`);if(void 0!==n.flags&&("object"!=typeof n.flags||Array.isArray(n.flags)||!n.flags))throw new v("INVALID_ARGS",`Batch step ${t+1} flags must be an object.`);r.push({command:o,positionals:i,flags:n.flags??{}})}return r}export{default as node_net}from"node:net";export{v as AppError,q as DEFAULT_BATCH_MAX_STEPS,A as asAppError,D as buildSnapshotDisplayLines,m as createRequestId,E as displayLabel,w as emitDiagnostic,a as fileURLToPath,_ as findProjectRoot,S as flushDiagnosticsToSessionFile,N as formatRole,b as formatSnapshotLine,h as getDiagnosticsMeta,G as isAgentDeviceDaemonProcess,R as isProcessAlive,t as node_crypto,r as node_fs,o as node_os,i as node_path,I as normalizeError,J as parseBatchStepsJson,s as pathToFileURL,n as promises,B as readProcessCommand,k as readProcessStartTime,$ as readVersion,M as runCmd,C as runCmdBackground,L as runCmdDetached,x as runCmdStreaming,T as runCmdSync,c as spawn,V as stopProcessForTakeover,W as validateAndNormalizeBatchSteps,O as whichCmd,g as withDiagnosticTimer,p as withDiagnosticsScope};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{createRequestId as e,node_path as t,parseBatchStepsJson as s,normalizeError as a,isAgentDeviceDaemonProcess as r,runCmdDetached as i,readVersion as o,findProjectRoot as n,getDiagnosticsMeta as l,withDiagnosticTimer as c,emitDiagnostic as p,asAppError as d,pathToFileURL as u,AppError as g,node_fs as m,node_os as f,flushDiagnosticsToSessionFile as h,node_net as w,withDiagnosticsScope as y,stopProcessForTakeover as v}from"./407.js";let b=["snapshotDepth","snapshotScope","snapshotRaw"],x=[{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:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"}],$=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),k={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:[...b]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...b]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...b]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...b]},"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:[...b]},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:[...b]},settings:{usageOverride:"settings <wifi|airplane|location|faceid> <on|off|match|nonmatch|enroll|unenroll>",description:"Toggle OS settings (simulators), including Face ID on iOS simulators",positionalArgs:["setting","state"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},A=new Map,S=new Map;for(let e of x){for(let t of e.names)A.set(t,e);let t=S.get(e.key);t?t.push(e):S.set(e.key,[e])}function D(e){if(e)return k[e]}function I(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function F(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(I),...t.allowedFlags.flatMap(e=>(S.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let L=function(){let e=`agent-device <command> [args] [--json]
|
|
1
|
+
import{styleText as e}from"node:util";import{createRequestId as t,node_path as s,buildSnapshotDisplayLines as a,parseBatchStepsJson as r,normalizeError as i,isAgentDeviceDaemonProcess as o,runCmdDetached as n,readVersion as l,findProjectRoot as p,getDiagnosticsMeta as d,runCmdSync as c,withDiagnosticTimer as u,emitDiagnostic as g,asAppError as m,pathToFileURL as f,AppError as h,node_fs as y,node_os as w,node_net as v,withDiagnosticsScope as b,flushDiagnosticsToSessionFile as k,stopProcessForTakeover as $,formatSnapshotLine as A}from"./350.js";let x=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],S=["snapshotDepth","snapshotScope","snapshotRaw"],D=[{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","android"],usageLabel:"--platform ios|android",usageDescription:"Platform to target"},{key:"device",names:["--device"],type:"string",usageLabel:"--device <name>",usageDescription:"Device name to target"},{key:"udid",names:["--udid"],type:"string",usageLabel:"--udid <udid>",usageDescription:"iOS device UDID"},{key:"serial",names:["--serial"],type:"string",usageLabel:"--serial <serial>",usageDescription:"Android device serial"},{key:"activity",names:["--activity"],type:"string",usageLabel:"--activity <component>",usageDescription:"Android app launch activity (package/Activity); not for URL opens"},{key:"session",names:["--session"],type:"string",usageLabel:"--session <name>",usageDescription:"Named session"},{key:"count",names:["--count"],type:"int",min:1,max:200,usageLabel:"--count <n>",usageDescription:"Repeat count for press/swipe series"},{key:"fps",names:["--fps"],type:"int",min:1,max:120,usageLabel:"--fps <n>",usageDescription:"Record: target frames per second (iOS physical device runner)"},{key:"intervalMs",names:["--interval-ms"],type:"int",min:0,max:1e4,usageLabel:"--interval-ms <ms>",usageDescription:"Delay between press iterations"},{key:"holdMs",names:["--hold-ms"],type:"int",min:0,max:1e4,usageLabel:"--hold-ms <ms>",usageDescription:"Press hold duration for each iteration"},{key:"jitterPx",names:["--jitter-px"],type:"int",min:0,max:100,usageLabel:"--jitter-px <n>",usageDescription:"Deterministic coordinate jitter radius for press"},{key:"doubleTap",names:["--double-tap"],type:"boolean",usageLabel:"--double-tap",usageDescription:"Use double-tap gesture per press iteration"},{key:"pauseMs",names:["--pause-ms"],type:"int",min:0,max:1e4,usageLabel:"--pause-ms <ms>",usageDescription:"Delay between swipe iterations"},{key:"pattern",names:["--pattern"],type:"enum",enumValues:["one-way","ping-pong"],usageLabel:"--pattern one-way|ping-pong",usageDescription:"Swipe repeat pattern"},{key:"verbose",names:["--debug","--verbose","-v"],type:"boolean",usageLabel:"--debug, --verbose, -v",usageDescription:"Enable debug diagnostics and stream daemon/runner logs"},{key:"json",names:["--json"],type:"boolean",usageLabel:"--json",usageDescription:"JSON output"},{key:"help",names:["--help","-h"],type:"boolean",usageLabel:"--help, -h",usageDescription:"Print help and exit"},{key:"version",names:["--version","-V"],type:"boolean",usageLabel:"--version, -V",usageDescription:"Print version and exit"},{key:"saveScript",names:["--save-script"],type:"booleanOrString",usageLabel:"--save-script [path]",usageDescription:"Save session script (.ad) on close; optional custom output path"},{key:"relaunch",names:["--relaunch"],type:"boolean",usageLabel:"--relaunch",usageDescription:"open: terminate app process before launching it"},{key:"restart",names:["--restart"],type:"boolean",usageLabel:"--restart",usageDescription:"logs clear: stop active stream, clear logs, then start streaming again"},{key:"noRecord",names:["--no-record"],type:"boolean",usageLabel:"--no-record",usageDescription:"Do not record this action"},{key:"replayUpdate",names:["--update","-u"],type:"boolean",usageLabel:"--update, -u",usageDescription:"Replay: update selectors and rewrite replay file in place"},{key:"steps",names:["--steps"],type:"string",usageLabel:"--steps <json>",usageDescription:"Batch: JSON array of steps"},{key:"stepsFile",names:["--steps-file"],type:"string",usageLabel:"--steps-file <path>",usageDescription:"Batch: read steps JSON from file"},{key:"batchOnError",names:["--on-error"],type:"enum",enumValues:["stop"],usageLabel:"--on-error stop",usageDescription:"Batch: stop when a step fails"},{key:"batchMaxSteps",names:["--max-steps"],type:"int",min:1,max:1e3,usageLabel:"--max-steps <n>",usageDescription:"Batch: maximum number of allowed steps"},{key:"appsFilter",names:["--user-installed"],type:"enum",setValue:"user-installed",usageLabel:"--user-installed",usageDescription:"Apps: list user-installed apps"},{key:"appsFilter",names:["--all"],type:"enum",setValue:"all",usageLabel:"--all",usageDescription:"Apps: list all apps (include system/default apps)"},{key:"snapshotInteractiveOnly",names:["-i"],type:"boolean",usageLabel:"-i",usageDescription:"Snapshot: interactive elements only"},{key:"snapshotCompact",names:["-c"],type:"boolean",usageLabel:"-c",usageDescription:"Snapshot: compact output (drop empty structure)"},{key:"snapshotDepth",names:["--depth","-d"],type:"int",min:0,usageLabel:"--depth, -d <depth>",usageDescription:"Snapshot: limit snapshot depth"},{key:"snapshotScope",names:["--scope","-s"],type:"string",usageLabel:"--scope, -s <scope>",usageDescription:"Snapshot: scope snapshot to label/identifier"},{key:"snapshotRaw",names:["--raw"],type:"boolean",usageLabel:"--raw",usageDescription:"Snapshot: raw node output"},{key:"out",names:["--out"],type:"string",usageLabel:"--out <path>",usageDescription:"Output path"}],I=new Set(["json","help","version","verbose","platform","device","udid","serial","session","noRecord"]),F={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:[]},open:{description:"Boot device/simulator; optionally launch app or deep link URL",positionalArgs:["appOrUrl?","url?"],allowedFlags:["activity","saveScript","relaunch"]},close:{description:"Close app or just end session",positionalArgs:["app?"],allowedFlags:["saveScript"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...x]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[...x]},devices:{description:"List available devices",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},apps:{description:"List installed apps (includes default/system apps by default)",positionalArgs:[],allowedFlags:["appsFilter"],defaults:{appsFilter:"all"}},appstate:{description:"Show foreground app/activity",positionalArgs:[],allowedFlags:[],skipCapabilityCheck:!0},back:{description:"Navigate back (where supported)",positionalArgs:[],allowedFlags:[]},home:{description:"Go to home screen (where supported)",positionalArgs:[],allowedFlags:[]},"app-switcher":{description:"Open app switcher (where supported)",positionalArgs:[],allowedFlags:[]},wait:{usageOverride:"wait <ms>|text <text>|@ref|<selector> [timeoutMs]",description:"Wait for duration, text, ref, or selector to appear",positionalArgs:["durationOrSelector","timeoutMs?"],allowsExtraPositionals:!0,allowedFlags:[...S]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...S]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...S]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...S]},longpress:{description:"Long press by coordinates (iOS and Android)",positionalArgs:["x","y","durationMs?"],allowedFlags:[]},swipe:{description:"Swipe coordinates with optional repeat pattern",positionalArgs:["x1","y1","x2","y2","durationMs?"],allowedFlags:["count","pauseMs","pattern"]},focus:{description:"Focus input at coordinates",positionalArgs:["x","y"],allowedFlags:[]},type:{description:"Type text in focused field",positionalArgs:["text"],allowsExtraPositionals:!0,allowedFlags:[]},fill:{usageOverride:"fill <x> <y> <text> | fill <@ref|selector> <text>",description:"Tap then type",positionalArgs:["targetOrX","yOrText","text?"],allowsExtraPositionals:!0,allowedFlags:[...S]},scroll:{description:"Scroll in direction (0-1 amount)",positionalArgs:["direction","amount?"],allowedFlags:[]},scrollintoview:{usageOverride:"scrollintoview <text|@ref>",description:"Scroll until text appears or a snapshot ref is brought into view",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:[]},pinch:{description:"Pinch/zoom gesture (iOS simulator)",positionalArgs:["scale","x?","y?"],allowedFlags:[]},screenshot:{description:"Capture screenshot",positionalArgs:["path?"],allowedFlags:["out"]},record:{usageOverride:"record start [path] [--fps <n>] | record stop",description:"Start/stop screen recording",positionalArgs:["start|stop","path?"],allowedFlags:["fps"]},trace:{usageOverride:"trace start [path] | trace stop [path]",description:"Start/stop trace log capture",positionalArgs:["start|stop","path?"],allowedFlags:[],skipCapabilityCheck:!0},logs:{usageOverride:"logs path | logs start | logs stop | logs clear [--restart] | logs doctor | logs mark [message...]",description:"Session app log info, start/stop streaming, diagnostics, and markers",positionalArgs:["path|start|stop|clear|doctor|mark","message?"],allowsExtraPositionals:!0,allowedFlags:["restart"]},find:{usageOverride:"find <locator|text> <action> [value]",description:"Find by text/label/value/role/id and run action",positionalArgs:["query","action","value?"],allowsExtraPositionals:!0,allowedFlags:["snapshotDepth","snapshotRaw"]},is:{description:"Assert UI state (visible|hidden|exists|editable|selected|text)",positionalArgs:["predicate","selector","value?"],allowsExtraPositionals:!0,allowedFlags:[...S]},settings:{usageOverride:"settings <wifi|airplane|location|faceid> <on|off|match|nonmatch|enroll|unenroll>",description:"Toggle OS settings (simulators), including Face ID on iOS simulators",positionalArgs:["setting","state"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},L=new Map,O=new Map;for(let e of D){for(let t of e.names)L.set(t,e);let t=O.get(e.key);t?t.push(e):O.set(e.key,[e])}function N(e){if(e)return F[e]}function j(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function _(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(j),...t.allowedFlags.flatMap(e=>(O.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let E=function(){let e=`agent-device <command> [args] [--json]
|
|
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:_(e,t)}}),s=Math.max(...t.map(e=>e.usage.length))+2,a=["Commands:"];for(let e of t)a.push(` ${e.usage.padEnd(s)}${e.schema.description}`);let r=T("Flags:",D.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
5
|
${a.join("\n")}
|
|
6
6
|
|
|
7
7
|
${r}
|
|
8
|
-
`}();function
|
|
9
|
-
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,a=[e];for(let e of t)a.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return a.join("\n")}function
|
|
10
|
-
`)}function
|
|
8
|
+
`}();function M(e){return D.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function T(e,t){if(0===t.length)return`${e}
|
|
9
|
+
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,a=[e];for(let e of t)a.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return a.join("\n")}function R(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function C(e){return e.replace(/^-+/,"")}function P(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?R(e):[e,void 0];return void 0!==L.get(t)}function V(e){return"long-press"===e?"longpress":e}function G(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
|
+
`)}function q(e,t={}){let s=e instanceof h?i(e):e;process.stderr.write(`Error (${s.code}): ${s.message}
|
|
11
11
|
`),s.hint&&process.stderr.write(`Hint: ${s.hint}
|
|
12
12
|
`),s.diagnosticId&&process.stderr.write(`Diagnostic ID: ${s.diagnosticId}
|
|
13
13
|
`),s.logPath&&process.stderr.write(`Diagnostics Log: ${s.logPath}
|
|
14
14
|
`),t.showDetails&&s.details&&process.stderr.write(`${JSON.stringify(s.details,null,2)}
|
|
15
|
-
`)}function
|
|
16
|
-
`)}),i=setTimeout(()=>{r.destroy(),
|
|
17
|
-
`);
|
|
18
|
-
`),process.exit(0));let
|
|
19
|
-
`),process.exit(0));let t=function(e){let t=
|
|
15
|
+
`)}function B(e){return"number"==typeof e&&Number.isFinite(e)?e:0}let U=s.join(w.homedir(),".agent-device"),W=s.join(U,"daemon.json"),J=s.join(U,"daemon.lock"),z=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}(),K=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function H(e){let s=e.meta?.requestId??t(),a=!!(e.meta?.debug||e.flags?.verbose),r=await u("daemon_startup",async()=>await X(),{requestId:s,session:e.session}),i={...e,token:r.token,meta:{requestId:s,debug:a,cwd:e.meta?.cwd}};return g({level:"info",phase:"daemon_request_prepare",data:{requestId:s,command:e.command,session:e.session}}),await u("daemon_request",async()=>await en(r,i),{requestId:s,command:e.command})}async function X(){var e;let t=ee(),s=l(),a=!!t&&await ei(t);if(t&&t.version===s&&a)return t;t&&(t.version!==s||!a)&&(await Q(t),er(W)),function(){let e=es();if(!e.hasLock||e.hasInfo)return;let t=et();t&&o(t.pid,t.processStartTime)||er(J)}(),await eo();let r=await Z(5e3);if(r)return r;if(await Y()){await eo();let e=await Z(5e3);if(e)return e}throw new h("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:W,lockPath:J,hint:(e=es()).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 Z(e){let t=Date.now();for(;Date.now()-t<e;){let e=ee();if(e&&await ei(e))return e;await new Promise(e=>setTimeout(e,100))}return null}async function Y(){let e=es();if(!e.hasLock||e.hasInfo)return!1;let t=et();return t&&o(t.pid,t.processStartTime)&&await $(t.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:t.processStartTime}),er(J),!0}async function Q(e){await $(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function ee(){let e=ea(W);return e&&e.port&&e.token?{...e,pid:Number.isInteger(e.pid)&&e.pid>0?e.pid:0}:null}function et(){let e=ea(J);return e&&Number.isInteger(e.pid)&&!(e.pid<=0)?e:null}function es(){return{hasInfo:y.existsSync(W),hasLock:y.existsSync(J)}}function ea(e){if(!y.existsSync(e))return null;try{return JSON.parse(y.readFileSync(e,"utf8"))}catch{return null}}function er(e){try{y.existsSync(e)&&y.unlinkSync(e)}catch{}}async function ei(e){return new Promise(t=>{let s=v.createConnection({host:"127.0.0.1",port:e.port},()=>{s.destroy(),t(!0)});s.on("error",()=>{t(!1)})})}async function eo(){let e=p(),t=s.join(e,"dist","src","daemon.js"),a=s.join(e,"src","daemon.ts"),r=y.existsSync(t),i=y.existsSync(a);if(!r&&!i)throw new h("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:a});let o=(process.execArgv.includes("--experimental-strip-types")?i:!r&&i)?["--experimental-strip-types",a]:[t];n(process.execPath,o)}async function en(e,t){return new Promise((s,a)=>{let r=v.createConnection({host:"127.0.0.1",port:e.port},()=>{r.write(`${JSON.stringify(t)}
|
|
16
|
+
`)}),i=setTimeout(()=>{r.destroy();let s=function(){let e=0;try{for(let t of K){let s=c("pkill",["-f",t],{allowFailure:!0});0===s.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}(),i=function(e){let t=!1;try{o(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),t=!0)}catch{$(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{er(W),er(J)}return{forcedKill:t}}(e);g({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:z,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:e.pid,daemonPidForceKilled:i.forcedKill}}),a(new h("COMMAND_FAILED","Daemon request timed out",{timeoutMs:z,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},z),n="";r.setEncoding("utf8"),r.on("data",e=>{let o=(n+=e).indexOf("\n");if(-1===o)return;let l=n.slice(0,o).trim();if(l)try{let e=JSON.parse(l);r.end(),clearTimeout(i),s(e)}catch(e){clearTimeout(i),a(new h("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),r.on("error",e=>{clearTimeout(i),g({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),a(new h("COMMAND_FAILED","Failed to communicate with daemon",{requestId:t.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))})})}let el={sendToDaemon:H};async function ep(o,n=el){let p=t(),c=o.includes("--debug")||o.includes("--verbose")||o.includes("-v"),u=o.includes("--json"),f=function(e){for(let t=0;t<e.length;t+=1){let s=e[t];if(s.startsWith("--session=")){let e=s.slice(10).trim();return e.length>0?e:null}if("--session"===s){let s=e[t+1]?.trim();if(s&&!s.startsWith("-"))return s;break}}return null}(o)??process.env.AGENT_DEVICE_SESSION??"default";await b({session:f,requestId:p,command:o[0],debug:c},async()=>{var t,f;let v;try{v=function(e,t){let s=(void 0)??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),a={json:!1,help:!1,version:!1},r=null,i=[],o=[],n=[],l=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(l&&"--"===s){l=!1;continue}if(!l){r?i.push(s):r=V(s);continue}let o=s.startsWith("--"),p=s.startsWith("-")&&s.length>1;if(!o&&!p){r?i.push(s):r=V(s);continue}let[d,c]=o?R(s):[s,void 0],u=L.get(d);if(!u){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let r=N(e);return!r||!!r.allowsExtraPositionals||0!==r.positionalArgs.length&&(t.length<r.positionalArgs.length||r.positionalArgs.some(e=>e.includes("?")))}(r,i,s)){r?i.push(s):r=s;continue}throw new h("INVALID_ARGS",`Unknown flag: ${d}`)}let g=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new h("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 h("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 h("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||P(a)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let r=s??a;if(void 0===r||void 0===s&&P(r))throw new h("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:r,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(r))throw new h("INVALID_ARGS",`Invalid ${C(t)}: ${r}`);return{value:r,consumeNext:void 0===s}}let i=Number(r);if(!Number.isFinite(i)||"number"==typeof e.min&&i<e.min||"number"==typeof e.max&&i>e.max)throw new h("INVALID_ARGS",`Invalid ${C(t)}: ${r}`);return{value:Math.floor(i),consumeNext:void 0===s}}(u,d,c,e[t+1]);g.consumeNext&&(t+=1),a[u.key]=g.value,n.push({key:u.key,token:d})}let p=N(r),d=new Set([...I,...p?.allowedFlags??[]]),c=n.filter(e=>!d.has(e.key));if(c.length>0){var u,g;let e=(u=r,g=c.map(e=>e.token),u?1===g.length?`Flag ${g[0]} is not supported for command ${u}.`:`Flags ${g.join(", ")} are not supported for command ${u}.`:1===g.length?`Flag ${g[0]} requires a command that supports it.`:`Flags ${g.join(", ")} require a command that supports them.`);if(s)throw new h("INVALID_ARGS",e);for(let t of(o.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),c))delete a[t.key]}if(p?.defaults)for(let[e,t]of Object.entries(p.defaults))void 0===a[e]&&(a[e]=t);if("batch"===r&&1!=+!!a.steps+ +!!a.stepsFile)throw new h("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:r,positionals:i,flags:a,warnings:o}}(o)}catch(t){g({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=i(t,{diagnosticId:d().diagnosticId,logPath:k({force:!0})??void 0});u?G({success:!1,error:e}):q(e,{showDetails:c}),process.exit(1);return}for(let e of v.warnings)process.stderr.write(`Warning: ${e}
|
|
17
|
+
`);v.flags.version&&(process.stdout.write(`${l()}
|
|
18
|
+
`),process.exit(0));let b="help"===v.command,$=v.flags.help;if(b||$){b&&v.positionals.length>1&&(q(new h("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=b?v.positionals[0]:v.command;e||(process.stdout.write(`${E}
|
|
19
|
+
`),process.exit(0));let t=function(e){let t=N(e);if(!t)return null;let s=_(e,t),a=M(new Set(t.allowedFlags)),r=M(I),i=[];return a.length>0&&i.push(T("Command flags:",a)),i.push(T("Global flags:",r)),`agent-device ${s}
|
|
20
20
|
|
|
21
21
|
${t.description}
|
|
22
22
|
|
|
@@ -24,34 +24,43 @@ Usage:
|
|
|
24
24
|
agent-device ${s}
|
|
25
25
|
|
|
26
26
|
${i.join("\n\n")}
|
|
27
|
-
`}(e);t&&(process.stdout.write(t),process.exit(0)),
|
|
28
|
-
`),process.exit(1)}
|
|
29
|
-
`),process.exit(1));let{command:x,positionals:
|
|
30
|
-
`)),
|
|
31
|
-
`),
|
|
32
|
-
`:"";if(0===
|
|
33
|
-
`;if(t.raw){let e=
|
|
27
|
+
`}(V(e));t&&(process.stdout.write(t),process.exit(0)),q(new h("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${E}
|
|
28
|
+
`),process.exit(1)}v.command||(process.stdout.write(`${E}
|
|
29
|
+
`),process.exit(1));let{command:x,positionals:S,flags:D}=v,F=function(e){let{json:t,help:s,version:a,...r}=e;return r}(D),O=D.session??process.env.AGENT_DEVICE_SESSION??"default",j=D.verbose&&!D.json?function(){try{let e=s.join(w.homedir(),".agent-device","daemon.log"),t=0,a=!1,r=setInterval(()=>{if(!a&&y.existsSync(e))try{let s=y.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let a=y.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);y.readSync(a,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{y.closeSync(a)}}catch{}},200);return()=>{a=!0,clearInterval(r)}}catch{return null}}():null,U=async e=>await n.sendToDaemon({session:O,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:p,debug:!!D.verbose,cwd:process.cwd()}});try{if("batch"===x){let e,s,a;if(S.length>0)throw new h("INVALID_ARGS","batch does not accept positional arguments.");let i=function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=y.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new h("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return r(t)}(D),o={...F,batchSteps:i};delete o.steps,delete o.stepsFile;let n=await U({command:"batch",positionals:S,flags:o});if(!n.ok)throw new h(n.error.code,n.error.message,{...n.error.details??{},hint:n.error.hint,diagnosticId:n.error.diagnosticId,logPath:n.error.logPath});D.json?G({success:!0,data:n.data??{}}):(t=n.data??{},e="number"==typeof t.total?t.total:0,s="number"==typeof t.executed?t.executed:0,a="number"==typeof t.totalDurationMs?t.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${s}/${e} steps${void 0!==a?` in ${a}ms`:""}
|
|
30
|
+
`)),j&&j();return}if("session"===x){let e=S[0]??"list";if("list"!==e)throw new h("INVALID_ARGS","session only supports list");let t=await U({command:"session_list",positionals:[],flags:F});if(!t.ok)throw new h(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath});D.json?G({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
31
|
+
`),j&&j();return}let s=await U({command:x,positionals:S,flags:F});if(s.ok){if(D.json){G({success:!0,data:s.data??{}}),j&&j();return}if("snapshot"===x){process.stdout.write(function(e,t={}){let s=e.nodes,r=Array.isArray(s)?s:[],i=!!e.truncated,o="string"==typeof e.appName?e.appName:void 0,n="string"==typeof e.appBundleId?e.appBundleId:void 0,l=[];o&&l.push(`Page: ${o}`),n&&l.push(`App: ${n}`);let p=`Snapshot: ${r.length} nodes${i?" (truncated)":""}`,d=l.length>0?`${l.join("\n")}
|
|
32
|
+
`:"";if(0===r.length)return`${d}${p}
|
|
33
|
+
`;if(t.raw){let e=r.map(e=>JSON.stringify(e));return`${d}${p}
|
|
34
34
|
${e.join("\n")}
|
|
35
|
-
`}if(t.flatten){let e=
|
|
35
|
+
`}if(t.flatten){let e=r.map(e=>A(e,0,!1));return`${d}${p}
|
|
36
36
|
${e.join("\n")}
|
|
37
|
-
`}let
|
|
38
|
-
${
|
|
39
|
-
`}(
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
`),
|
|
44
|
-
`),
|
|
45
|
-
`),
|
|
46
|
-
`),
|
|
47
|
-
`),
|
|
48
|
-
`),
|
|
49
|
-
`),
|
|
37
|
+
`}let c=a(r).map(e=>e.text);return`${d}${p}
|
|
38
|
+
${c.join("\n")}
|
|
39
|
+
`}(s.data??{},{raw:D.snapshotRaw,flatten:D.snapshotInteractiveOnly})),j&&j();return}if("diff"===x&&"snapshot"===S[0]){process.stdout.write(function(t){var s,a,r,i;let o,n=!0===t.baselineInitialized,l=t.summary??{},p=B(l.additions),d=B(l.removals),c=B(l.unchanged),u=(o=process.env.FORCE_COLOR,"string"==typeof o?"0"!==o:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY);if(n)return`Baseline initialized (${c} lines).
|
|
40
|
+
`;let g=(function(e,t){if(0===e.length)return e;let s=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===s.length)return e;let a=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),r=Math.min(e.length-1,t+1);for(let e=s;e<=r;e+=1)a[e]=!0}return e.filter((e,t)=>a[t])})(Array.isArray(t.lines)?t.lines:[],1).map(t=>{var s,a,r,i;let o="string"==typeof t.text?t.text:"";if("added"===t.kind){let t=o.startsWith(" ")?`+${o}`:`+ ${o}`;return u?(s=t,a="green",e(a,s)):t}if("removed"===t.kind){let t=o.startsWith(" ")?`-${o}`:`- ${o}`;return u?(r=t,e("red",r)):t}return u?(i=o,e("dim",i)):o}),m=g.length>0?`${g.join("\n")}
|
|
41
|
+
`:"";if(!u)return`${m}${p} additions, ${d} removals, ${c} unchanged
|
|
42
|
+
`;let f=`${(s=String(p),a="green",e(a,s))} additions, ${(r=String(d),e("red",r))} removals, ${(i=String(c),e("dim",i))} unchanged`;return`${m}${f}
|
|
43
|
+
`}(s.data??{})),j&&j();return}if("get"===x){let e=S[0];if("text"===e){let e=s.data?.text??"";process.stdout.write(`${e}
|
|
44
|
+
`),j&&j();return}if("attrs"===e){let e=s.data?.node??{};process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
45
|
+
`),j&&j();return}}if("find"===x){let e=s.data;if("string"==typeof e?.text){process.stdout.write(`${e.text}
|
|
46
|
+
`),j&&j();return}if("boolean"==typeof e?.found){process.stdout.write(`Found: ${e.found}
|
|
47
|
+
`),j&&j();return}if(e?.node){process.stdout.write(`${JSON.stringify(e.node,null,2)}
|
|
48
|
+
`),j&&j();return}}if("is"===x){let e=s.data?.predicate??"assertion";process.stdout.write(`Passed: is ${e}
|
|
49
|
+
`),j&&j();return}if("boot"===x){let e=s.data?.platform??"unknown",t=s.data?.device??s.data?.id??"unknown";process.stdout.write(`Boot ready: ${t} (${e})
|
|
50
|
+
`),j&&j();return}if("logs"===x){let e=s.data,t="string"==typeof e?.path?e.path:"";if(t){process.stdout.write(`${t}
|
|
51
|
+
`);let s="boolean"==typeof e?.active?e.active:void 0,a="string"==typeof e?.state?e.state:void 0,r="string"==typeof e?.backend?e.backend:void 0,i="number"==typeof e?.sizeBytes?e.sizeBytes:void 0,o=e?.started===!0,n=e?.stopped===!0,l=e?.marked===!0,p=e?.cleared===!0,d=e?.restarted===!0,c="number"==typeof e?.removedRotatedFiles?e.removedRotatedFiles:void 0;if(!D.json&&(void 0!==s||a||r||void 0!==i)){let e=[void 0!==s?`active=${s}`:"",a?`state=${a}`:"",r?`backend=${r}`:"",void 0!==i?`sizeBytes=${i}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
52
|
+
`)}if(!D.json&&(o||n||l||p||d||void 0!==c)){let e=[o?"started=true":"",n?"stopped=true":"",l?"marked=true":"",p?"cleared=true":"",d?"restarted=true":"",void 0!==c?`removedRotatedFiles=${c}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
53
|
+
`)}if(e?.hint&&!D.json&&process.stderr.write(`${e.hint}
|
|
54
|
+
`),Array.isArray(e?.notes)&&!D.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
|
|
55
|
+
`)}j&&j();return}if("click"===x||"press"===x){let e=s.data?.ref??"",t=s.data?.x,a=s.data?.y;e&&"number"==typeof t&&"number"==typeof a&&process.stdout.write(`Tapped @${e} (${t}, ${a})
|
|
56
|
+
`),j&&j();return}if(s.data&&"object"==typeof s.data){let e=s.data;if("devices"===x){let t=(Array.isArray(e.devices)?e.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",s=e?.platform??"unknown",a=e?.kind?` ${e.kind}`:"",r="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${a})${r}`});process.stdout.write(`${t.join("\n")}
|
|
57
|
+
`),j&&j();return}if("apps"===x){let t=(Array.isArray(e.apps)?e.apps:[]).map(e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e.bundleId??e.package,s=e.name??e.label;return s&&t?`${s} (${t})`:t?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${t.join("\n")}
|
|
58
|
+
`),j&&j();return}if("appstate"===x){let t=e?.platform,s=e?.appBundleId,a=e?.appName,r=e?.source,i=e?.package,o=e?.activity;if("ios"===t){process.stdout.write(`Foreground app: ${a??s??"unknown"}
|
|
50
59
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
51
60
|
`),r&&process.stdout.write(`Source: ${r}
|
|
52
|
-
`),
|
|
61
|
+
`),j&&j();return}if("android"===t){process.stdout.write(`Foreground app: ${i??"unknown"}
|
|
53
62
|
`),o&&process.stdout.write(`Activity: ${o}
|
|
54
|
-
`),
|
|
63
|
+
`),j&&j();return}}}j&&j();return}throw new h(s.error.code,s.error.message,{...s.error.details??{},hint:s.error.hint,diagnosticId:s.error.diagnosticId,logPath:s.error.logPath})}catch(a){let e=m(a),t=i(e,{diagnosticId:d().diagnosticId,logPath:k({force:!0})??void 0});if("close"===x&&"COMMAND_FAILED"===(f=e).code&&(f.details?.kind==="daemon_startup_failed"||f.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof f.details?.infoPath||"string"==typeof f.details?.lockPath))){D.json&&G({success:!0,data:{closed:"session",source:"no-daemon"}}),j&&j();return}if(D.json)G({success:!1,error:t});else if(q(t,{showDetails:D.verbose}),D.verbose)try{let e=s.join(w.homedir(),".agent-device","daemon.log");if(y.existsSync(e)){let t=y.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
55
64
|
[daemon log]
|
|
56
65
|
${s}
|
|
57
|
-
`)}}catch{}
|
|
66
|
+
`)}}catch{}j&&j(),process.exit(1)}})}f(process.argv[1]??"").href===import.meta.url&&ep(process.argv.slice(2)).catch(e=>{q(i(m(e)),{showDetails:!0}),process.exit(1)}),ep(process.argv.slice(2));
|