agent-device 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +57 -4
- package/dist/src/678.js +3 -0
- package/dist/src/bin.js +53 -53
- package/dist/src/daemon.js +32 -28
- package/package.json +1 -1
- package/skills/agent-device/SKILL.md +51 -1
- package/skills/agent-device/references/remote-tenancy.md +77 -0
- package/skills/agent-device/references/session-management.md +24 -0
- package/dist/src/735.js +0 -3
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ The project is in early development and considered experimental. Pull requests a
|
|
|
14
14
|
|
|
15
15
|
## Features
|
|
16
16
|
- Platforms: iOS/tvOS (simulator + physical device core automation) and Android/AndroidTV (emulator + device).
|
|
17
|
-
- Core commands: `open`, `back`, `home`, `app-switcher`, `press`, `long-press`, `focus`, `type`, `fill`, `scroll`, `scrollintoview`, `wait`, `alert`, `screenshot`, `close`, `reinstall`, `push`.
|
|
17
|
+
- Core commands: `open`, `back`, `home`, `app-switcher`, `press`, `long-press`, `focus`, `type`, `fill`, `scroll`, `scrollintoview`, `wait`, `alert`, `screenshot`, `close`, `reinstall`, `push`, `trigger-app-event`.
|
|
18
18
|
- Inspection commands: `snapshot` (accessibility tree), `diff snapshot` (structural baseline diff), `appstate`, `apps`, `devices`.
|
|
19
19
|
- Clipboard commands: `clipboard read`, `clipboard write <text>`.
|
|
20
20
|
- Performance command: `perf` (alias: `metrics`) returns a metrics JSON blob for the active session; startup timing is currently sampled.
|
|
@@ -148,6 +148,7 @@ agent-device scrollintoview @e42
|
|
|
148
148
|
- `snapshot`, `diff snapshot`, `find`, `get`
|
|
149
149
|
- `press` (alias: `click`), `focus`, `type`, `fill`, `long-press`, `swipe`, `scroll`, `scrollintoview`, `pinch`, `is`
|
|
150
150
|
- `alert`, `wait`, `screenshot`
|
|
151
|
+
- `trigger-app-event <event> [payloadJson]`
|
|
151
152
|
- `trace start`, `trace stop`
|
|
152
153
|
- `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)
|
|
153
154
|
- `clipboard read`, `clipboard write <text>` (iOS simulator + Android)
|
|
@@ -155,6 +156,8 @@ agent-device scrollintoview @e42
|
|
|
155
156
|
- `settings wifi|airplane|location on|off`
|
|
156
157
|
- `settings appearance light|dark|toggle`
|
|
157
158
|
- `settings faceid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
159
|
+
- `settings touchid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
160
|
+
- `settings fingerprint match|nonmatch` (Android emulator/device where supported)
|
|
158
161
|
- `settings permission grant|deny|reset camera|microphone|photos|contacts|notifications [full|limited]`
|
|
159
162
|
- `appstate`, `apps`, `devices`, `session list`
|
|
160
163
|
- `perf` (alias: `metrics`)
|
|
@@ -179,6 +182,25 @@ Payload notes:
|
|
|
179
182
|
- Android extras support string/boolean/number values.
|
|
180
183
|
- `push` works with session context (uses session device) or explicit device selectors.
|
|
181
184
|
|
|
185
|
+
App event triggers (app hook):
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
agent-device trigger-app-event screenshot_taken '{"source":"qa"}'
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
- `trigger-app-event` dispatches an app event via deep link and requires an app-side test/debug hook.
|
|
192
|
+
- `trigger-app-event` requires either an active session or explicit device selectors (`--platform`, `--device`, `--udid`, `--serial`).
|
|
193
|
+
- On iOS physical devices, custom-scheme deep links require active app context (open the app in-session first).
|
|
194
|
+
- Configure one of:
|
|
195
|
+
- `AGENT_DEVICE_APP_EVENT_URL_TEMPLATE`
|
|
196
|
+
- `AGENT_DEVICE_IOS_APP_EVENT_URL_TEMPLATE`
|
|
197
|
+
- `AGENT_DEVICE_ANDROID_APP_EVENT_URL_TEMPLATE`
|
|
198
|
+
- Template placeholders: `{event}`, `{payload}`, `{platform}`.
|
|
199
|
+
- Example template: `myapp://agent-device/event?name={event}&payload={payload}`.
|
|
200
|
+
- `payloadJson` must be a JSON object.
|
|
201
|
+
- This is app-hook-based simulation, not an OS-global notification injector.
|
|
202
|
+
- Canonical trigger contract lives in [`website/docs/docs/commands.md`](website/docs/docs/commands.md) under **App event triggers**.
|
|
203
|
+
|
|
182
204
|
## iOS Snapshots
|
|
183
205
|
|
|
184
206
|
Notes:
|
|
@@ -207,8 +229,17 @@ Flags:
|
|
|
207
229
|
- `--device <name>`
|
|
208
230
|
- `--udid <udid>` (iOS)
|
|
209
231
|
- `--serial <serial>` (Android)
|
|
232
|
+
- `--ios-simulator-device-set <path>` constrain iOS simulator discovery/commands to one simulator set (`xcrun simctl --set`)
|
|
233
|
+
- `--android-device-allowlist <serials>` constrain Android discovery/selection to comma/space-separated serials
|
|
210
234
|
- `--activity <component>` (Android app launch only; package/Activity or package/.Activity; not for URL opens)
|
|
211
235
|
- `--session <name>`
|
|
236
|
+
- `--state-dir <path>` daemon state directory override (default: `~/.agent-device`)
|
|
237
|
+
- `--daemon-transport auto|socket|http` daemon client transport preference
|
|
238
|
+
- `--daemon-server-mode socket|http|dual` daemon server mode (`http` and `dual` expose JSON-RPC over HTTP at `/rpc`)
|
|
239
|
+
- `--tenant <id>` tenant identifier used with session isolation
|
|
240
|
+
- `--session-isolation none|tenant` explicit session isolation mode (`tenant` scopes session namespace as `<tenant>:<session>`)
|
|
241
|
+
- `--run-id <id>` run identifier used with tenant-scoped lease admission
|
|
242
|
+
- `--lease-id <id>` active lease identifier used with tenant-scoped lease admission
|
|
212
243
|
- `--count <n>` repeat count for `press`/`swipe`
|
|
213
244
|
- `--interval-ms <ms>` delay between `press` iterations
|
|
214
245
|
- `--hold-ms <ms>` hold duration per `press` iteration
|
|
@@ -223,6 +254,11 @@ Flags:
|
|
|
223
254
|
- `--on-error stop` batch: stop when a step fails
|
|
224
255
|
- `--max-steps <n>` batch: max allowed steps per request
|
|
225
256
|
|
|
257
|
+
Isolation precedence:
|
|
258
|
+
- Discovery scope (`--ios-simulator-device-set`, `--android-device-allowlist`) is applied before selector matching (`--device`, `--udid`, `--serial`).
|
|
259
|
+
- If a selector points outside the scoped set/allowlist, command resolution fails with `DEVICE_NOT_FOUND` (no host-global fallback).
|
|
260
|
+
- When `--ios-simulator-device-set` is set (or its env equivalent), iOS discovery is simulator-set only (physical iOS devices are not enumerated).
|
|
261
|
+
|
|
226
262
|
TV targets:
|
|
227
263
|
- Use `--target tv` together with `--platform ios|android|apple`.
|
|
228
264
|
- TV target selection supports both simulator/emulator and connected physical devices (AppleTV + AndroidTV).
|
|
@@ -260,7 +296,7 @@ Sessions:
|
|
|
260
296
|
- If a session is already open, `open <app|url>` switches the active app or opens a deep link URL.
|
|
261
297
|
- `close` stops the session and releases device resources. Pass an app to close it explicitly, or omit to just close the session.
|
|
262
298
|
- Use `--session <name>` to manage multiple sessions.
|
|
263
|
-
- Session scripts are written to
|
|
299
|
+
- Session scripts are written to `<state-dir>/sessions/<session>-<timestamp>.ad` when recording is enabled with `--save-script`.
|
|
264
300
|
- `--save-script` accepts an optional path: `--save-script ./workflows/my-flow.ad`.
|
|
265
301
|
- For ambiguous bare values, use an explicit form: `--save-script=workflow.ad` or a path-like value such as `./workflow.ad`.
|
|
266
302
|
- Deterministic replay is `.ad`-based; use `replay --update` (`-u`) to update selector drift and rewrite the replay file in place.
|
|
@@ -362,6 +398,9 @@ Settings helpers:
|
|
|
362
398
|
- `settings airplane on|off`
|
|
363
399
|
- `settings location on|off` (iOS uses per-app permission for the current session app)
|
|
364
400
|
- `settings appearance light|dark|toggle` (iOS simulator appearance + Android night mode)
|
|
401
|
+
- `settings faceid|touchid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
402
|
+
- `settings fingerprint match|nonmatch` (Android emulator/device where supported)
|
|
403
|
+
On physical Android devices, fingerprint simulation depends on `cmd fingerprint` support.
|
|
365
404
|
- `settings permission grant|deny|reset <camera|microphone|photos|contacts|notifications> [full|limited]` (session app required)
|
|
366
405
|
Note: iOS supports these only on simulators. iOS wifi/airplane toggles status bar indicators, not actual network state. Airplane off clears status bar overrides.
|
|
367
406
|
- iOS permission targets map to `simctl privacy`: `camera`, `microphone`, `photos` (`full` => `photos`, `limited` => `photos-add`), `contacts`, `notifications`.
|
|
@@ -381,7 +420,7 @@ Clipboard:
|
|
|
381
420
|
|
|
382
421
|
## Debug
|
|
383
422
|
|
|
384
|
-
- **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.
|
|
423
|
+
- **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. `<state-dir>/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.
|
|
385
424
|
- Use `logs clear --restart` when you want one command to stop an active stream, clear current logs, and immediately resume streaming.
|
|
386
425
|
- `logs start` appends to `app.log` and rotates to `app.log.1` when the file exceeds 5 MB.
|
|
387
426
|
- **Network dump (best-effort):** `network dump [limit] [summary|headers|body|all]` parses recent HTTP(s) lines from the same session app log file and returns method/url/status with optional headers/bodies. `network log ...` is an alias. Current limits: scans up to 4000 recent log lines, returns up to 200 entries, truncates payload/header fields at 2048 characters.
|
|
@@ -395,13 +434,15 @@ Clipboard:
|
|
|
395
434
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
396
435
|
- Built-in retries cover transient runner connection failures and Android UI dumps.
|
|
397
436
|
- For snapshot issues (missing elements), compare with `--raw` flag for unaltered output and scope with `-s "<label>"`.
|
|
398
|
-
- If startup fails with stale metadata hints, remove stale
|
|
437
|
+
- If startup fails with stale metadata hints, remove stale `<state-dir>/daemon.json` / `<state-dir>/daemon.lock` and retry (state dir defaults to `~/.agent-device` unless overridden).
|
|
399
438
|
|
|
400
439
|
Boot diagnostics:
|
|
401
440
|
- Boot failures include normalized reason codes in `error.details.reason` (JSON mode) and verbose logs.
|
|
402
441
|
- Reason codes: `IOS_BOOT_TIMEOUT`, `IOS_RUNNER_CONNECT_TIMEOUT`, `ANDROID_BOOT_TIMEOUT`, `ADB_TRANSPORT_UNAVAILABLE`, `CI_RESOURCE_STARVATION_SUSPECTED`, `BOOT_COMMAND_FAILED`, `UNKNOWN`.
|
|
403
442
|
- Android boot waits fail fast for permission/tooling issues and do not always collapse into timeout errors.
|
|
404
443
|
- Use `agent-device boot --platform ios|android|apple` when starting a new session only if `open` cannot find/connect to an available target.
|
|
444
|
+
- Android emulator boot by AVD name (GUI): `agent-device boot --platform android --device Pixel_9_Pro_XL`.
|
|
445
|
+
- Android headless emulator boot: `agent-device boot --platform android --device Pixel_9_Pro_XL --headless`.
|
|
405
446
|
- `--debug` captures retry telemetry in diagnostics logs.
|
|
406
447
|
- Set `AGENT_DEVICE_RETRY_LOGS=1` to also print retry telemetry directly to stderr (ad-hoc troubleshooting).
|
|
407
448
|
|
|
@@ -451,8 +492,20 @@ pnpm build
|
|
|
451
492
|
Environment selectors:
|
|
452
493
|
- `ANDROID_DEVICE=Pixel_9_Pro_XL` or `ANDROID_SERIAL=emulator-5554`
|
|
453
494
|
- `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=<udid>`
|
|
495
|
+
- `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET=<path>` (or `IOS_SIMULATOR_DEVICE_SET=<path>`) to scope all iOS simulator discovery/commands to one simulator set.
|
|
496
|
+
- `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST=<serials>` (or `ANDROID_DEVICE_ALLOWLIST=<serials>`) to scope Android discovery to allowlisted serials.
|
|
497
|
+
- CLI flags `--ios-simulator-device-set` / `--android-device-allowlist` override environment values.
|
|
454
498
|
- `AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS=<ms>` to adjust iOS simulator boot timeout (default: `120000`, minimum: `5000`).
|
|
455
499
|
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to override daemon request timeout (default `90000`). Increase for slow physical-device setup (for example `120000`).
|
|
500
|
+
- `AGENT_DEVICE_STATE_DIR=<path>` override daemon state directory (metadata, logs, session artifacts).
|
|
501
|
+
- `AGENT_DEVICE_DAEMON_SERVER_MODE=socket|http|dual` daemon server mode. `http` and `dual` expose JSON-RPC 2.0 at `POST /rpc` (`GET /health` available for liveness).
|
|
502
|
+
- `AGENT_DEVICE_DAEMON_TRANSPORT=auto|socket|http` client preference when connecting to daemon metadata.
|
|
503
|
+
- `AGENT_DEVICE_HTTP_AUTH_HOOK=<module-path>` optional HTTP auth hook module path for JSON-RPC server mode.
|
|
504
|
+
- `AGENT_DEVICE_HTTP_AUTH_EXPORT=<export-name>` optional export name from auth hook module (default: `default`).
|
|
505
|
+
- `AGENT_DEVICE_MAX_SIMULATOR_LEASES=<n>` optional max concurrent simulator leases for HTTP lease allocation (default: unlimited).
|
|
506
|
+
- `AGENT_DEVICE_LEASE_TTL_MS=<ms>` default lease TTL used by `agent_device.lease.allocate` and `agent_device.lease.heartbeat` (default: `60000`).
|
|
507
|
+
- `AGENT_DEVICE_LEASE_MIN_TTL_MS=<ms>` minimum accepted lease TTL (default: `5000`).
|
|
508
|
+
- `AGENT_DEVICE_LEASE_MAX_TTL_MS=<ms>` maximum accepted lease TTL (default: `600000`).
|
|
456
509
|
- `AGENT_DEVICE_IOS_TEAM_ID=<team-id>` optional Team ID override for iOS device runner signing.
|
|
457
510
|
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
458
511
|
- `AGENT_DEVICE_IOS_PROVISIONING_PROFILE=<profile>` optional provisioning profile specifier for iOS device runner signing.
|
package/dist/src/678.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 g(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 w(e,t,r){let n=Date.now();try{let o=await t();return g({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw g({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),l=function(e,t,r){if("COMMAND_FAILED"!==e||r?.processExitError!==!0)return t;let n=function(e){let t=[/^an error was encountered processing the command/i,/^underlying error\b/i,/^simulator device failed to complete the requested operation/i];for(let r of e.split("\n")){let e=r.trim();if(e&&!t.some(t=>t.test(e)))return e.length>200?`${e.slice(0,200)}...`:e}return null}("string"==typeof r?.stderr?r.stderr:"");return n||t}(r.code,r.message,n);return{code:r.code,message:l,hint:s,diagnosticId:i,logPath:a,details:c}}let E="<wifi|airplane|location> <on|off>",D="appearance <light|dark|toggle>",$="faceid <match|nonmatch|enroll|unenroll>",b="touchid <match|nonmatch|enroll|unenroll>",N="fingerprint <match|nonmatch>",_="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",M=`settings ${E} | settings ${D} | settings ${$} | settings ${b} | settings ${N} | settings ${_}`,T=`settings requires ${E}, ${D}, ${$}, ${b}, ${N}, or ${_}`;function O(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=C(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:L(n,s,a,i)})}return r}function L(e,t,r,n){let o=n??C(e.type??"Element"),i=x(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 x(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 C(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 P(){try{let e=k();return JSON.parse(r.readFileSync(i.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function k(){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 R(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=V(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,processExitError:!0}))})})}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 R(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function B(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:V(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new v("COMMAND_FAILED",`${e} timed out after ${V(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:V(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,processExitError:!0});return{stdout:i,stderr:a,exitCode:s,stdoutBuffer:o}}function j(e,t,r={}){c(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function G(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,processExitError:!0}))})})}function U(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,processExitError:!0}))})});return{child:n,wait:a}}function V(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}let q=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function H(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function z(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=B("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 J(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=B("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 W(e,t){let r;if(!H(e))return!1;if(t){let r=z(e);if(!r||r!==t)return!1}let n=J(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&q.some(e=>e.test(r))}function K(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 Z(e,t){if(!H(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!H(e))return!0;return!H(e)}async function X(e,t){!W(e,t.expectedStartTime)||!K(e,"SIGTERM")||await Z(e,t.termTimeoutMs)||K(e,"SIGKILL")&&await Z(e,t.killTimeoutMs)}function Q(e){let t,r=(t=(e??"").trim())?"~"===t?o.homedir():t.startsWith("~/")?i.join(o.homedir(),t.slice(2)):i.resolve(t):i.join(o.homedir(),".agent-device");return{baseDir:r,infoPath:i.join(r,"daemon.json"),lockPath:i.join(r,"daemon.lock"),logPath:i.join(r,"daemon.log"),sessionsDir:i.join(r,"sessions")}}function Y(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function ee(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function et(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function er(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}let en=100,eo=new Set(["batch","replay"]);function ei(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 ea(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(eo.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{default as node_http}from"node:http";export{v as AppError,en as DEFAULT_BATCH_MAX_STEPS,T as SETTINGS_INVALID_ARGS_MESSAGE,M as SETTINGS_USAGE_OVERRIDE,A as asAppError,O as buildSnapshotDisplayLines,m as createRequestId,x as displayLabel,g as emitDiagnostic,a as fileURLToPath,k as findProjectRoot,S as flushDiagnosticsToSessionFile,C as formatRole,L as formatSnapshotLine,h as getDiagnosticsMeta,W as isAgentDeviceDaemonProcess,H as isProcessAlive,t as node_crypto,r as node_fs,o as node_os,i as node_path,I as normalizeError,er as normalizeTenantId,ei as parseBatchStepsJson,s as pathToFileURL,n as promises,J as readProcessCommand,z as readProcessStartTime,P as readVersion,Q as resolveDaemonPaths,Y as resolveDaemonServerMode,ee as resolveDaemonTransportPreference,et as resolveSessionIsolationMode,R as runCmd,U as runCmdBackground,j as runCmdDetached,G as runCmdStreaming,B as runCmdSync,c as spawn,X as stopProcessForTakeover,ea as validateAndNormalizeBatchSteps,F as whichCmd,w as withDiagnosticTimer,p as withDiagnosticsScope};
|
package/dist/src/bin.js
CHANGED
|
@@ -1,75 +1,75 @@
|
|
|
1
|
-
import{styleText as e}from"node:util";import{buildSnapshotDisplayLines as t,node_path as s,createRequestId as r,parseBatchStepsJson as a,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,SETTINGS_USAGE_OVERRIDE as m,asAppError as f,pathToFileURL as h,AppError as y,node_fs as w,node_os as v,node_net as b,withDiagnosticsScope as $,flushDiagnosticsToSessionFile as k,stopProcessForTakeover as A,formatSnapshotLine as S}from"./735.js";let x=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],D=["snapshotDepth","snapshotScope","snapshotRaw"],I=[{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","android","apple"],usageLabel:"--platform ios|android|apple",usageDescription:"Platform to target (`apple` aliases the iOS/tvOS backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv"],usageLabel:"--target mobile|tv",usageDescription:"Device target class to match"},{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"}],F=new Set(["json","help","version","verbose","platform","target","device","udid","serial","session","noRecord"]),L={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:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],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},clipboard:{usageOverride:"clipboard read | clipboard write <text>",description:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},perf:{description:"Show session performance metrics (startup timing)",positionalArgs:[],allowedFlags:[]},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 <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...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},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",...D]},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:[...D]},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"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [summary|headers|body|all]",description:"Dump recent HTTP(s) traffic parsed from the session app log",positionalArgs:["dump|log","limit?","include?"],allowedFlags:[]},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:{usageOverride:m,description:"Toggle OS settings, appearance, and app permissions (session app scope for permission actions)",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},O=new Map,N=new Map;for(let e of I){for(let t of e.names)O.set(t,e);let t=N.get(e.key);t?t.push(e):N.set(e.key,[e])}function j(e){if(e)return L[e]}function _(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function E(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(_),...t.allowedFlags.flatMap(e=>(N.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let T=function(){let e=`agent-device <command> [args] [--json]
|
|
1
|
+
import{styleText as e}from"node:util";import{node_http as t,node_path as s,buildSnapshotDisplayLines as a,createRequestId as r,parseBatchStepsJson as o,normalizeError as i,isAgentDeviceDaemonProcess as n,runCmdDetached as l,readVersion as d,findProjectRoot as p,getDiagnosticsMeta as u,runCmdSync as c,withDiagnosticTimer as m,resolveDaemonTransportPreference as g,emitDiagnostic as f,SETTINGS_USAGE_OVERRIDE as h,asAppError as y,pathToFileURL as w,AppError as v,node_fs as b,withDiagnosticsScope as D,node_net as I,flushDiagnosticsToSessionFile as A,resolveDaemonServerMode as k,resolveDaemonPaths as $,stopProcessForTakeover as S,formatSnapshotLine as x}from"./678.js";let E=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],L=["snapshotDepth","snapshotScope","snapshotRaw"],O=[{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonTransport",names:["--daemon-transport"],type:"enum",enumValues:["auto","socket","http"],usageLabel:"--daemon-transport auto|socket|http",usageDescription:"Daemon client transport preference"},{key:"daemonServerMode",names:["--daemon-server-mode"],type:"enum",enumValues:["socket","http","dual"],usageLabel:"--daemon-server-mode socket|http|dual",usageDescription:"Daemon server mode used when spawning daemon"},{key:"tenant",names:["--tenant"],type:"string",usageLabel:"--tenant <id>",usageDescription:"Tenant scope identifier for isolated daemon sessions"},{key:"sessionIsolation",names:["--session-isolation"],type:"enum",enumValues:["none","tenant"],usageLabel:"--session-isolation none|tenant",usageDescription:"Session isolation strategy (tenant prefixes session namespace)"},{key:"runId",names:["--run-id"],type:"string",usageLabel:"--run-id <id>",usageDescription:"Run identifier used for tenant lease admission checks"},{key:"leaseId",names:["--lease-id"],type:"string",usageLabel:"--lease-id <id>",usageDescription:"Lease identifier bound to tenant/run admission scope"},{key:"platform",names:["--platform"],type:"enum",enumValues:["ios","android","apple"],usageLabel:"--platform ios|android|apple",usageDescription:"Platform to target (`apple` aliases the iOS/tvOS backend)"},{key:"target",names:["--target"],type:"enum",enumValues:["mobile","tv"],usageLabel:"--target mobile|tv",usageDescription:"Device target class to match"},{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:"headless",names:["--headless"],type:"boolean",usageLabel:"--headless",usageDescription:"Boot: launch Android emulator without a GUI window"},{key:"iosSimulatorDeviceSet",names:["--ios-simulator-device-set"],type:"string",usageLabel:"--ios-simulator-device-set <path>",usageDescription:"Scope iOS simulator discovery/commands to this simulator device set"},{key:"androidDeviceAllowlist",names:["--android-device-allowlist"],type:"string",usageLabel:"--android-device-allowlist <serials>",usageDescription:"Comma/space separated Android serial allowlist for discovery/selection"},{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"}],F=new Set(["json","stateDir","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),_={boot:{description:"Ensure target device/simulator is booted and ready",positionalArgs:[],allowedFlags:["headless"]},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:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...E]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[...E]},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},clipboard:{usageOverride:"clipboard read | clipboard write <text>",description:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},perf:{description:"Show session performance metrics (startup timing)",positionalArgs:[],allowedFlags:[]},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:[...L]},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",...L]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...L]},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",...L]},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:[...L]},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"]},"trigger-app-event":{usageOverride:"trigger-app-event <event> [payloadJson]",description:"Trigger app-defined event hook via deep link template",positionalArgs:["event","payloadJson?"],allowedFlags:[]},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"]},network:{usageOverride:"network dump [limit] [summary|headers|body|all] | network log [limit] [summary|headers|body|all]",description:"Dump recent HTTP(s) traffic parsed from the session app log",positionalArgs:["dump|log","limit?","include?"],allowedFlags:[]},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:[...L]},settings:{usageOverride:h,description:"Toggle OS settings, appearance, and app permissions (session app scope for permission actions)",positionalArgs:["setting","state","target?","mode?"],allowedFlags:[]},session:{usageOverride:"session list",description:"List active sessions",positionalArgs:["list?"],allowedFlags:[],skipCapabilityCheck:!0}},P=new Map,N=new Map;for(let e of O){for(let t of e.names)P.set(t,e);let t=N.get(e.key);t?t.push(e):N.set(e.key,[e])}function T(e){if(e)return _[e]}function M(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function C(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(M),...t.allowedFlags.flatMap(e=>(N.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let R=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(
|
|
5
|
-
${
|
|
4
|
+
`,t=Object.keys(_).map(e=>{let t=_[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:C(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=q("Flags:",O.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
|
+
${a.join("\n")}
|
|
6
6
|
|
|
7
|
-
${
|
|
8
|
-
`}();function
|
|
9
|
-
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,
|
|
10
|
-
`)}function
|
|
7
|
+
${r}
|
|
8
|
+
`}();function j(e){return O.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function q(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 V(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function G(e){return e.replace(/^-+/,"")}function B(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?V(e):[e,void 0];return void 0!==P.get(t)}function J(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function U(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
10
|
+
`)}function W(e,t={}){let s=e instanceof v?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(()=>{
|
|
17
|
-
`);
|
|
18
|
-
`),process.exit(0));let
|
|
19
|
-
`),process.exit(0));let t=function(e){let t=
|
|
15
|
+
`)}function z(e){return"number"==typeof e&&Number.isFinite(e)?e:0}let H=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 X(e){var t;let s,a,o,i,n=e.meta?.requestId??r(),l=!!(e.meta?.debug||e.flags?.verbose),d=(t=e,s=t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,o=g(a=t.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT),i=k(t.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===a?"dual":void 0)),{paths:$(s),transportPreference:o,serverMode:i}),p=await m("daemon_startup",async()=>await Z(d),{requestId:n,session:e.session}),u={...e,token:p.token,meta:{requestId:n,debug:l,cwd:e.meta?.cwd,tenantId:e.meta?.tenantId??e.flags?.tenant,runId:e.meta?.runId??e.flags?.runId,leaseId:e.meta?.leaseId??e.flags?.leaseId,sessionIsolation:e.meta?.sessionIsolation??e.flags?.sessionIsolation}};return f({level:"info",phase:"daemon_request_prepare",data:{requestId:n,command:e.command,session:e.session}}),await m("daemon_request",async()=>await ed(p,u,d.transportPreference),{requestId:n,command:e.command})}async function Z(e){let t,a=et(e.paths.infoPath),r=d(),o=function(e,t=p()){try{let a=b.statSync(e),r=s.relative(t,e)||e;return`${r}:${a.size}:${Math.trunc(a.mtimeMs)}`}catch{return"unknown"}}((t=el()).useSrc?t.srcPath:t.distPath,t.root),i=!!a&&await ei(a,e.transportPreference);if(a&&a.version===r&&a.codeSignature===o&&i)return a;a&&(a.version!==r||a.codeSignature!==o||!i)&&(await ee(a),eo(e.paths.infoPath)),function(e){let t=ea(e);if(!t.hasLock||t.hasInfo)return;let s=es(e.lockPath);if(!s)return eo(e.lockPath);n(s.pid,s.processStartTime)||eo(e.lockPath)}(e.paths),await en(e);let l=await Y(5e3,e);if(l)return l;if(await Q(e.paths)){await en(e);let t=await Y(5e3,e);if(t)return t}throw new v("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,hint:function(e,t=$(process.env.AGENT_DEVICE_STATE_DIR)){return e.hasLock&&!e.hasInfo?`Detected ${t.lockPath} without ${t.infoPath}. If no agent-device daemon process is running, delete ${t.lockPath} and retry.`:e.hasLock&&e.hasInfo?`Daemon metadata may be stale. If no agent-device daemon process is running, delete ${t.infoPath} and ${t.lockPath}, then retry.`:`Daemon metadata is missing or stale. Delete ${t.infoPath} if present and retry.`}(ea(e.paths),e.paths)})}async function Y(e,t){let s=Date.now();for(;Date.now()-s<e;){let e=et(t.paths.infoPath);if(e&&await ei(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function Q(e){let t=ea(e);if(!t.hasLock||t.hasInfo)return!1;let s=es(e.lockPath);return s&&n(s.pid,s.processStartTime)&&await S(s.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:s.processStartTime}),eo(e.lockPath),!0}async function ee(e){await S(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function et(e){let t=er(e);if(!t||"string"!=typeof t.token||0===t.token.length)return null;let s=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;return s||a?{...t,port:s?Number(t.port):void 0,httpPort:a?Number(t.httpPort):void 0,pid:Number.isInteger(t.pid)&&t.pid>0?t.pid:0}:null}function es(e){let t=er(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function ea(e){return{hasInfo:b.existsSync(e.infoPath),hasLock:b.existsSync(e.lockPath)}}function er(e){if(!b.existsSync(e))return null;try{return JSON.parse(b.readFileSync(e,"utf8"))}catch{return null}}function eo(e){try{b.existsSync(e)&&b.unlinkSync(e)}catch{}}async function ei(e,s){var a,r;return"http"===ep(e,s)?await ((a=e.httpPort)?new Promise(e=>{let s=t.request({host:"127.0.0.1",port:a,path:"/health",method:"GET",timeout:500},t=>{t.resume(),e((t.statusCode??500)<500)});s.on("timeout",()=>{s.destroy(),e(!1)}),s.on("error",()=>{e(!1)}),s.end()}):Promise.resolve(!1)):await ((r=e.port)?new Promise(e=>{let t=I.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function en(e){let t=el(),s=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],a={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};l(process.execPath,s,{env:a})}function el(){let e=p(),t=s.join(e,"dist","src","daemon.js"),a=s.join(e,"src","daemon.ts"),r=b.existsSync(t),o=b.existsSync(a);if(!r&&!o)throw new v("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:a});return{root:e,distPath:t,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!r&&o}}async function ed(e,t,s){return"http"===ep(e,s)?await ec(e,t):await eu(e,t)}function ep(e,t){if("http"===t){if(!e.httpPort)throw new v("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");return"http"}if("socket"===t){if(!e.port)throw new v("COMMAND_FAILED","Daemon socket endpoint is unavailable");return"socket"}let s=e.transport;if("http"===s&&e.httpPort)return"http";if(("socket"===s||"dual"===s)&&e.port)return"socket";if(e.httpPort)return"http";if(e.port)return"socket";throw new v("COMMAND_FAILED","Daemon metadata has no reachable transport")}async function eu(e,t){let s=e.port;if(!s)throw new v("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,r)=>{let o=I.createConnection({host:"127.0.0.1",port:s},()=>{o.write(`${JSON.stringify(t)}
|
|
16
|
+
`)}),i=setTimeout(()=>{o.destroy();let s=em(),a=eg(e,$(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));f({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:H,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),r(new v("COMMAND_FAILED","Daemon request timed out",{timeoutMs:H,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},H),n="";o.setEncoding("utf8"),o.on("data",e=>{let s=(n+=e).indexOf("\n");if(-1===s)return;let l=n.slice(0,s).trim();if(l)try{let e=JSON.parse(l);o.end(),clearTimeout(i),a(e)}catch(e){clearTimeout(i),r(new v("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(i),f({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),r(new v("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))})})}async function ec(e,s){let a=e.httpPort;if(!a)throw new v("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let o=JSON.stringify({jsonrpc:"2.0",id:s.meta?.requestId??r(),method:"agent_device.command",params:s});return await new Promise((r,i)=>{let n=$(s.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=t.request({host:"127.0.0.1",port:a,method:"POST",path:"/rpc",headers:{"content-type":"application/json","content-length":Buffer.byteLength(o)}},e=>{let t="";e.setEncoding("utf8"),e.on("data",e=>{t+=e}),e.on("end",()=>{clearTimeout(d);try{let e=JSON.parse(t);if(e.error){let t=e.error.data??{};i(new v(String(t.code??"COMMAND_FAILED"),String(t.message??e.error.message??"Daemon RPC request failed"),{..."object"==typeof t.details&&t.details?t.details:{},hint:"string"==typeof t.hint?t.hint:void 0,diagnosticId:"string"==typeof t.diagnosticId?t.diagnosticId:void 0,logPath:"string"==typeof t.logPath?t.logPath:void 0,requestId:s.meta?.requestId}));return}if(!e.result||"object"!=typeof e.result)return void i(new v("COMMAND_FAILED","Invalid daemon RPC response",{requestId:s.meta?.requestId}));r(e.result)}catch(e){clearTimeout(d),i(new v("COMMAND_FAILED","Invalid daemon response",{requestId:s.meta?.requestId,line:t},e instanceof Error?e:void 0))}})}),d=setTimeout(()=>{l.destroy();let t=em(),a=eg(e,n);f({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:H,requestId:s.meta?.requestId,command:s.command,timedOutRunnerPidsTerminated:t.terminated,timedOutRunnerCleanupError:t.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),i(new v("COMMAND_FAILED","Daemon request timed out",{timeoutMs:H,requestId:s.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},H);l.on("error",e=>{clearTimeout(d),f({level:"error",phase:"daemon_request_socket_error",data:{requestId:s.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),i(new v("COMMAND_FAILED","Failed to communicate with daemon",{requestId:s.meta?.requestId,hint:"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))}),l.write(o),l.end()})}function em(){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)}}}function eg(e,t){let s=!1;try{n(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),s=!0)}catch{S(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{eo(t.infoPath),eo(t.lockPath)}return{forcedKill:s}}let ef={sendToDaemon:X};async function eh(t,s=ef){let n=r(),l=t.includes("--debug")||t.includes("--verbose")||t.includes("-v"),p=t.includes("--json"),c=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}(t)??process.env.AGENT_DEVICE_SESSION??"default";await D({session:c,requestId:n,command:t[0],debug:l},async()=>{var r,c;let m;try{m=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,o=[],i=[],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?o.push(s):r=J(s);continue}let i=s.startsWith("--"),d=s.startsWith("-")&&s.length>1;if(!i&&!d){r?o.push(s):r=J(s);continue}let[p,u]=i?V(s):[s,void 0],c=P.get(p);if(!c){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let r=T(e);return!r||!!r.allowsExtraPositionals||0!==r.positionalArgs.length&&(t.length<r.positionalArgs.length||r.positionalArgs.some(e=>e.includes("?")))}(r,o,s)){r?o.push(s):r=s;continue}throw new v("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new v("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 v("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 v("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||B(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&&B(r))throw new v("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 v("INVALID_ARGS",`Invalid ${G(t)}: ${r}`);return{value:r,consumeNext:void 0===s}}let o=Number(r);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new v("INVALID_ARGS",`Invalid ${G(t)}: ${r}`);return{value:Math.floor(o),consumeNext:void 0===s}}(c,p,u,e[t+1]);m.consumeNext&&(t+=1),a[c.key]=m.value,n.push({key:c.key,token:p})}let d=T(r),p=new Set([...F,...d?.allowedFlags??[]]),u=n.filter(e=>!p.has(e.key));if(u.length>0){var c,m;let e=(c=r,m=u.map(e=>e.token),c?1===m.length?`Flag ${m[0]} is not supported for command ${c}.`:`Flags ${m.join(", ")} are not supported for command ${c}.`:1===m.length?`Flag ${m[0]} requires a command that supports it.`:`Flags ${m.join(", ")} require a command that supports them.`);if(s)throw new v("INVALID_ARGS",e);for(let t of(i.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),u))delete a[t.key]}if(d?.defaults)for(let[e,t]of Object.entries(d.defaults))void 0===a[e]&&(a[e]=t);if("batch"===r&&1!=+!!a.steps+ +!!a.stepsFile)throw new v("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:r,positionals:o,flags:a,warnings:i}}(t)}catch(t){f({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=i(t,{diagnosticId:u().diagnosticId,logPath:A({force:!0})??void 0});p?U({success:!1,error:e}):W(e,{showDetails:l}),process.exit(1);return}for(let e of m.warnings)process.stderr.write(`Warning: ${e}
|
|
17
|
+
`);m.flags.version&&(process.stdout.write(`${d()}
|
|
18
|
+
`),process.exit(0));let g="help"===m.command,h=m.flags.help;if(g||h){g&&m.positionals.length>1&&(W(new v("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=g?m.positionals[0]:m.command;e||(process.stdout.write(`${R}
|
|
19
|
+
`),process.exit(0));let t=function(e){let t=T(e);if(!t)return null;let s=C(e,t),a=j(new Set(t.allowedFlags)),r=j(F),o=[];return a.length>0&&o.push(q("Command flags:",a)),o.push(q("Global flags:",r)),`agent-device ${s}
|
|
20
20
|
|
|
21
21
|
${t.description}
|
|
22
22
|
|
|
23
23
|
Usage:
|
|
24
24
|
agent-device ${s}
|
|
25
25
|
|
|
26
|
-
${
|
|
27
|
-
`}(
|
|
28
|
-
`),process.exit(1)}
|
|
29
|
-
`),process.exit(1));let{command:
|
|
30
|
-
`)),
|
|
31
|
-
`),
|
|
32
|
-
`:"";if(0===
|
|
33
|
-
`;if(
|
|
26
|
+
${o.join("\n\n")}
|
|
27
|
+
`}(J(e));t&&(process.stdout.write(t),process.exit(0)),W(new v("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${R}
|
|
28
|
+
`),process.exit(1)}m.command||(process.stdout.write(`${R}
|
|
29
|
+
`),process.exit(1));let{command:w,positionals:D,flags:I}=m,k=function(e){let{json:t,help:s,version:a,...r}=e;return r}(I),S=$(I.stateDir??process.env.AGENT_DEVICE_STATE_DIR),E=I.session??process.env.AGENT_DEVICE_SESSION??"default",L=I.verbose&&!I.json?function(e){try{let t=0,s=!1,a=setInterval(()=>{if(!s&&b.existsSync(e))try{let s=b.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let a=b.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);b.readSync(a,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{b.closeSync(a)}}catch{}},200);return()=>{s=!0,clearInterval(a)}}catch{return null}}(S.logPath):null,O=async e=>await s.sendToDaemon({session:E,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:n,debug:!!I.verbose,cwd:process.cwd(),tenantId:I.tenant,runId:I.runId,leaseId:I.leaseId,sessionIsolation:I.sessionIsolation}});try{if("batch"===w){let e,t,s;if(D.length>0)throw new v("INVALID_ARGS","batch does not accept positional arguments.");let a=function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=b.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new v("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return o(t)}(I),i={...k,batchSteps:a};delete i.steps,delete i.stepsFile;let n=await O({command:"batch",positionals:D,flags:i});if(!n.ok)throw new v(n.error.code,n.error.message,{...n.error.details??{},hint:n.error.hint,diagnosticId:n.error.diagnosticId,logPath:n.error.logPath});I.json?U({success:!0,data:n.data??{}}):(r=n.data??{},e="number"==typeof r.total?r.total:0,t="number"==typeof r.executed?r.executed:0,s="number"==typeof r.totalDurationMs?r.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${t}/${e} steps${void 0!==s?` in ${s}ms`:""}
|
|
30
|
+
`)),L&&L();return}if("session"===w){let e=D[0]??"list";if("list"!==e)throw new v("INVALID_ARGS","session only supports list");let t=await O({command:"session_list",positionals:[],flags:k});if(!t.ok)throw new v(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath});I.json?U({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
|
|
31
|
+
`),L&&L();return}let t=await O({command:w,positionals:D,flags:k});if(t.ok){if(I.json){U({success:!0,data:t.data??{}}),L&&L();return}if("snapshot"===w){process.stdout.write(function(e,t={}){let s=e.nodes,r=Array.isArray(s)?s:[],o=!!e.truncated,i="string"==typeof e.appName?e.appName:void 0,n="string"==typeof e.appBundleId?e.appBundleId:void 0,l=[];i&&l.push(`Page: ${i}`),n&&l.push(`App: ${n}`);let d=`Snapshot: ${r.length} nodes${o?" (truncated)":""}`,p=l.length>0?`${l.join("\n")}
|
|
32
|
+
`:"";if(0===r.length)return`${p}${d}
|
|
33
|
+
`;if(t.raw){let e=r.map(e=>JSON.stringify(e));return`${p}${d}
|
|
34
34
|
${e.join("\n")}
|
|
35
|
-
`}if(
|
|
35
|
+
`}if(t.flatten){let e=r.map(e=>x(e,0,!1));return`${p}${d}
|
|
36
36
|
${e.join("\n")}
|
|
37
|
-
`}let
|
|
38
|
-
${
|
|
39
|
-
`}(
|
|
40
|
-
`;let
|
|
41
|
-
`:"";if(!
|
|
42
|
-
`;let f=`${(s=String(
|
|
43
|
-
`}(
|
|
44
|
-
`),
|
|
45
|
-
`),
|
|
46
|
-
`),
|
|
47
|
-
`),
|
|
48
|
-
`),
|
|
49
|
-
`),
|
|
50
|
-
`),
|
|
51
|
-
`);let
|
|
52
|
-
`)}if(!
|
|
53
|
-
`)}if(e?.hint&&!
|
|
54
|
-
`),Array.isArray(e?.notes)&&!
|
|
55
|
-
`)}
|
|
56
|
-
`),
|
|
57
|
-
`);let
|
|
37
|
+
`}let u=a(r).map(e=>e.text);return`${p}${d}
|
|
38
|
+
${u.join("\n")}
|
|
39
|
+
`}(t.data??{},{raw:I.snapshotRaw,flatten:I.snapshotInteractiveOnly})),L&&L();return}if("diff"===w&&"snapshot"===D[0]){process.stdout.write(function(t){var s,a,r,o;let i,n=!0===t.baselineInitialized,l=t.summary??{},d=z(l.additions),p=z(l.removals),u=z(l.unchanged),c=(i=process.env.FORCE_COLOR,"string"==typeof i?"0"!==i:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY);if(n)return`Baseline initialized (${u} lines).
|
|
40
|
+
`;let m=(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,o;let i="string"==typeof t.text?t.text:"";if("added"===t.kind){let t=i.startsWith(" ")?`+${i}`:`+ ${i}`;return c?(s=t,a="green",e(a,s)):t}if("removed"===t.kind){let t=i.startsWith(" ")?`-${i}`:`- ${i}`;return c?(r=t,e("red",r)):t}return c?(o=i,e("dim",o)):i}),g=m.length>0?`${m.join("\n")}
|
|
41
|
+
`:"";if(!c)return`${g}${d} additions, ${p} removals, ${u} unchanged
|
|
42
|
+
`;let f=`${(s=String(d),a="green",e(a,s))} additions, ${(r=String(p),e("red",r))} removals, ${(o=String(u),e("dim",o))} unchanged`;return`${g}${f}
|
|
43
|
+
`}(t.data??{})),L&&L();return}if("get"===w){let e=D[0];if("text"===e){let e=t.data?.text??"";process.stdout.write(`${e}
|
|
44
|
+
`),L&&L();return}if("attrs"===e){let e=t.data?.node??{};process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
45
|
+
`),L&&L();return}}if("find"===w){let e=t.data;if("string"==typeof e?.text){process.stdout.write(`${e.text}
|
|
46
|
+
`),L&&L();return}if("boolean"==typeof e?.found){process.stdout.write(`Found: ${e.found}
|
|
47
|
+
`),L&&L();return}if(e?.node){process.stdout.write(`${JSON.stringify(e.node,null,2)}
|
|
48
|
+
`),L&&L();return}}if("is"===w){let e=t.data?.predicate??"assertion";process.stdout.write(`Passed: is ${e}
|
|
49
|
+
`),L&&L();return}if("boot"===w){let e=t.data?.platform??"unknown",s=t.data?.device??t.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${e})
|
|
50
|
+
`),L&&L();return}if("logs"===w){let e=t.data,s="string"==typeof e?.path?e.path:"";if(s){process.stdout.write(`${s}
|
|
51
|
+
`);let t="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,o="number"==typeof e?.sizeBytes?e.sizeBytes:void 0,i=e?.started===!0,n=e?.stopped===!0,l=e?.marked===!0,d=e?.cleared===!0,p=e?.restarted===!0,u="number"==typeof e?.removedRotatedFiles?e.removedRotatedFiles:void 0;if(!I.json&&(void 0!==t||a||r||void 0!==o)){let e=[void 0!==t?`active=${t}`:"",a?`state=${a}`:"",r?`backend=${r}`:"",void 0!==o?`sizeBytes=${o}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
52
|
+
`)}if(!I.json&&(i||n||l||d||p||void 0!==u)){let e=[i?"started=true":"",n?"stopped=true":"",l?"marked=true":"",d?"cleared=true":"",p?"restarted=true":"",void 0!==u?`removedRotatedFiles=${u}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
53
|
+
`)}if(e?.hint&&!I.json&&process.stderr.write(`${e.hint}
|
|
54
|
+
`),Array.isArray(e?.notes)&&!I.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
|
|
55
|
+
`)}L&&L();return}if("clipboard"===w){let e=t.data,s=(D[0]??("string"==typeof e?.action?e.action:"")).toLowerCase();if("read"===s){let t="string"==typeof e?.text?e.text:"";process.stdout.write(`${t}
|
|
56
|
+
`),L&&L();return}if("write"===s){process.stdout.write("Clipboard updated\n"),L&&L();return}}if("network"===w){let e=t.data,s="string"==typeof e?.path?e.path:"";s&&process.stdout.write(`${s}
|
|
57
|
+
`);let a=Array.isArray(e?.entries)?e.entries:[];if(0===a.length)process.stdout.write("No recent HTTP(s) entries found.\n");else for(let e of a){let t="string"==typeof e.method?e.method:"HTTP",s="string"==typeof e.url?e.url:"<unknown-url>",a="number"==typeof e.status?` status=${e.status}`:"",r="string"==typeof e.timestamp?`${e.timestamp} `:"";process.stdout.write(`${r}${t} ${s}${a}
|
|
58
58
|
`),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
|
|
59
59
|
`),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
|
|
60
60
|
`),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
|
|
61
|
-
`)}let
|
|
61
|
+
`)}let r="boolean"==typeof e?.active?e.active:void 0,o="string"==typeof e?.state?e.state:void 0,i="string"==typeof e?.backend?e.backend:void 0,n="number"==typeof e?.scannedLines?e.scannedLines:void 0,l="number"==typeof e?.matchedLines?e.matchedLines:void 0,d="string"==typeof e?.include?e.include:void 0,p=[void 0!==r?`active=${r}`:"",o?`state=${o}`:"",i?`backend=${i}`:"",d?`include=${d}`:"",void 0!==n?`scannedLines=${n}`:"",void 0!==l?`matchedLines=${l}`:""].filter(Boolean).join(" ");if(p&&process.stderr.write(`${p}
|
|
62
62
|
`),Array.isArray(e?.notes))for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
|
|
63
|
-
`);
|
|
64
|
-
`),
|
|
65
|
-
`),
|
|
66
|
-
`),
|
|
63
|
+
`);L&&L();return}if("click"===w||"press"===w){let e=t.data?.ref??"",s=t.data?.x,a=t.data?.y;e&&"number"==typeof s&&"number"==typeof a&&process.stdout.write(`Tapped @${e} (${s}, ${a})
|
|
64
|
+
`),L&&L();return}if(t.data&&"object"==typeof t.data){let e=t.data;if("devices"===w){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=e?.target?` target=${e.target}`:"",o="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${a}${r})${o}`});process.stdout.write(`${t.join("\n")}
|
|
65
|
+
`),L&&L();return}if("apps"===w){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")}
|
|
66
|
+
`),L&&L();return}if("appstate"===w){let t=e?.platform,s=e?.appBundleId,a=e?.appName,r=e?.source,o=e?.package,i=e?.activity;if("ios"===t){process.stdout.write(`Foreground app: ${a??s??"unknown"}
|
|
67
67
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
68
|
-
`),
|
|
69
|
-
`),
|
|
70
|
-
`),
|
|
71
|
-
`),
|
|
72
|
-
`),
|
|
68
|
+
`),r&&process.stdout.write(`Source: ${r}
|
|
69
|
+
`),L&&L();return}if("android"===t){process.stdout.write(`Foreground app: ${o??"unknown"}
|
|
70
|
+
`),i&&process.stdout.write(`Activity: ${i}
|
|
71
|
+
`),L&&L();return}}if("perf"===w){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
72
|
+
`),L&&L();return}}L&&L();return}throw new v(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath})}catch(s){let e=y(s),t=i(e,{diagnosticId:u().diagnosticId,logPath:A({force:!0})??void 0});if("close"===w&&"COMMAND_FAILED"===(c=e).code&&(c.details?.kind==="daemon_startup_failed"||c.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof c.details?.infoPath||"string"==typeof c.details?.lockPath))){I.json&&U({success:!0,data:{closed:"session",source:"no-daemon"}}),L&&L();return}if(I.json)U({success:!1,error:t});else if(W(t,{showDetails:I.verbose}),I.verbose)try{let e=S.logPath;if(b.existsSync(e)){let t=b.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
|
|
73
73
|
[daemon log]
|
|
74
74
|
${s}
|
|
75
|
-
`)}}catch{}
|
|
75
|
+
`)}}catch{}L&&L(),process.exit(1)}})}w(process.argv[1]??"").href===import.meta.url&&eh(process.argv.slice(2)).catch(e=>{W(i(y(e)),{showDetails:!0}),process.exit(1)}),eh(process.argv.slice(2));
|