agent-device 0.7.0 → 0.7.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 +24 -3
- package/dist/src/678.js +3 -0
- package/dist/src/bin.js +49 -49
- package/dist/src/daemon.js +32 -28
- package/package.json +1 -1
- package/skills/agent-device/SKILL.md +1 -1
- package/dist/src/735.js +0 -3
package/README.md
CHANGED
|
@@ -155,6 +155,8 @@ agent-device scrollintoview @e42
|
|
|
155
155
|
- `settings wifi|airplane|location on|off`
|
|
156
156
|
- `settings appearance light|dark|toggle`
|
|
157
157
|
- `settings faceid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
158
|
+
- `settings touchid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
159
|
+
- `settings fingerprint match|nonmatch` (Android emulator/device where supported)
|
|
158
160
|
- `settings permission grant|deny|reset camera|microphone|photos|contacts|notifications [full|limited]`
|
|
159
161
|
- `appstate`, `apps`, `devices`, `session list`
|
|
160
162
|
- `perf` (alias: `metrics`)
|
|
@@ -209,6 +211,13 @@ Flags:
|
|
|
209
211
|
- `--serial <serial>` (Android)
|
|
210
212
|
- `--activity <component>` (Android app launch only; package/Activity or package/.Activity; not for URL opens)
|
|
211
213
|
- `--session <name>`
|
|
214
|
+
- `--state-dir <path>` daemon state directory override (default: `~/.agent-device`)
|
|
215
|
+
- `--daemon-transport auto|socket|http` daemon client transport preference
|
|
216
|
+
- `--daemon-server-mode socket|http|dual` daemon server mode (`http` and `dual` expose JSON-RPC over HTTP at `/rpc`)
|
|
217
|
+
- `--tenant <id>` tenant identifier used with session isolation
|
|
218
|
+
- `--session-isolation none|tenant` explicit session isolation mode (`tenant` scopes session namespace as `<tenant>:<session>`)
|
|
219
|
+
- `--run-id <id>` run identifier used with tenant-scoped lease admission
|
|
220
|
+
- `--lease-id <id>` active lease identifier used with tenant-scoped lease admission
|
|
212
221
|
- `--count <n>` repeat count for `press`/`swipe`
|
|
213
222
|
- `--interval-ms <ms>` delay between `press` iterations
|
|
214
223
|
- `--hold-ms <ms>` hold duration per `press` iteration
|
|
@@ -260,7 +269,7 @@ Sessions:
|
|
|
260
269
|
- If a session is already open, `open <app|url>` switches the active app or opens a deep link URL.
|
|
261
270
|
- `close` stops the session and releases device resources. Pass an app to close it explicitly, or omit to just close the session.
|
|
262
271
|
- Use `--session <name>` to manage multiple sessions.
|
|
263
|
-
- Session scripts are written to
|
|
272
|
+
- Session scripts are written to `<state-dir>/sessions/<session>-<timestamp>.ad` when recording is enabled with `--save-script`.
|
|
264
273
|
- `--save-script` accepts an optional path: `--save-script ./workflows/my-flow.ad`.
|
|
265
274
|
- For ambiguous bare values, use an explicit form: `--save-script=workflow.ad` or a path-like value such as `./workflow.ad`.
|
|
266
275
|
- Deterministic replay is `.ad`-based; use `replay --update` (`-u`) to update selector drift and rewrite the replay file in place.
|
|
@@ -362,6 +371,9 @@ Settings helpers:
|
|
|
362
371
|
- `settings airplane on|off`
|
|
363
372
|
- `settings location on|off` (iOS uses per-app permission for the current session app)
|
|
364
373
|
- `settings appearance light|dark|toggle` (iOS simulator appearance + Android night mode)
|
|
374
|
+
- `settings faceid|touchid match|nonmatch|enroll|unenroll` (iOS simulator only)
|
|
375
|
+
- `settings fingerprint match|nonmatch` (Android emulator/device where supported)
|
|
376
|
+
On physical Android devices, fingerprint simulation depends on `cmd fingerprint` support.
|
|
365
377
|
- `settings permission grant|deny|reset <camera|microphone|photos|contacts|notifications> [full|limited]` (session app required)
|
|
366
378
|
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
379
|
- iOS permission targets map to `simctl privacy`: `camera`, `microphone`, `photos` (`full` => `photos`, `limited` => `photos-add`), `contacts`, `notifications`.
|
|
@@ -381,7 +393,7 @@ Clipboard:
|
|
|
381
393
|
|
|
382
394
|
## Debug
|
|
383
395
|
|
|
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.
|
|
396
|
+
- **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
397
|
- Use `logs clear --restart` when you want one command to stop an active stream, clear current logs, and immediately resume streaming.
|
|
386
398
|
- `logs start` appends to `app.log` and rotates to `app.log.1` when the file exceeds 5 MB.
|
|
387
399
|
- **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,7 +407,7 @@ Clipboard:
|
|
|
395
407
|
- The trace log includes snapshot logs and XCTest runner logs for the session.
|
|
396
408
|
- Built-in retries cover transient runner connection failures and Android UI dumps.
|
|
397
409
|
- 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
|
|
410
|
+
- 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
411
|
|
|
400
412
|
Boot diagnostics:
|
|
401
413
|
- Boot failures include normalized reason codes in `error.details.reason` (JSON mode) and verbose logs.
|
|
@@ -453,6 +465,15 @@ Environment selectors:
|
|
|
453
465
|
- `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=<udid>`
|
|
454
466
|
- `AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS=<ms>` to adjust iOS simulator boot timeout (default: `120000`, minimum: `5000`).
|
|
455
467
|
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to override daemon request timeout (default `90000`). Increase for slow physical-device setup (for example `120000`).
|
|
468
|
+
- `AGENT_DEVICE_STATE_DIR=<path>` override daemon state directory (metadata, logs, session artifacts).
|
|
469
|
+
- `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).
|
|
470
|
+
- `AGENT_DEVICE_DAEMON_TRANSPORT=auto|socket|http` client preference when connecting to daemon metadata.
|
|
471
|
+
- `AGENT_DEVICE_HTTP_AUTH_HOOK=<module-path>` optional HTTP auth hook module path for JSON-RPC server mode.
|
|
472
|
+
- `AGENT_DEVICE_HTTP_AUTH_EXPORT=<export-name>` optional export name from auth hook module (default: `default`).
|
|
473
|
+
- `AGENT_DEVICE_MAX_SIMULATOR_LEASES=<n>` optional max concurrent simulator leases for HTTP lease allocation (default: unlimited).
|
|
474
|
+
- `AGENT_DEVICE_LEASE_TTL_MS=<ms>` default lease TTL used by `agent_device.lease.allocate` and `agent_device.lease.heartbeat` (default: `60000`).
|
|
475
|
+
- `AGENT_DEVICE_LEASE_MIN_TTL_MS=<ms>` minimum accepted lease TTL (default: `5000`).
|
|
476
|
+
- `AGENT_DEVICE_LEASE_MAX_TTL_MS=<ms>` maximum accepted lease TTL (default: `600000`).
|
|
456
477
|
- `AGENT_DEVICE_IOS_TEAM_ID=<team-id>` optional Team ID override for iOS device runner signing.
|
|
457
478
|
- `AGENT_DEVICE_IOS_SIGNING_IDENTITY=<identity>` optional signing identity override.
|
|
458
479
|
- `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 r,createRequestId as a,parseBatchStepsJson as o,normalizeError as n,isAgentDeviceDaemonProcess as i,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:"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","session","noRecord"]),_={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:[...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"]},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(
|
|
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,r=["Commands:"];for(let e of t)r.push(` ${e.usage.padEnd(s)}${e.schema.description}`);let a=q("Flags:",O.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
|
|
5
5
|
${r.join("\n")}
|
|
6
6
|
|
|
7
7
|
${a}
|
|
8
|
-
`}();function
|
|
9
|
-
(none)`;let s=Math.max(...t.map(e=>(e.usageLabel??"").length))+2,r=[e];for(let e of t)r.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return r.join("\n")}function
|
|
10
|
-
`)}function
|
|
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,r=[e];for(let e of t)r.push(` ${(e.usageLabel??"").padEnd(s)}${e.usageDescription??""}`);return r.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?n(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
|
-
`)}),
|
|
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,r,o,n,i=e.meta?.requestId??a(),l=!!(e.meta?.debug||e.flags?.verbose),d=(t=e,s=t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,o=g(r=t.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT),n=k(t.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===r?"dual":void 0)),{paths:$(s),transportPreference:o,serverMode:n}),p=await m("daemon_startup",async()=>await Z(d),{requestId:i,session:e.session}),u={...e,token:p.token,meta:{requestId:i,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:i,command:e.command,session:e.session}}),await m("daemon_request",async()=>await ed(p,u,d.transportPreference),{requestId:i,command:e.command})}async function Z(e){let t,r=et(e.paths.infoPath),a=d(),o=function(e,t=p()){try{let r=b.statSync(e),a=s.relative(t,e)||e;return`${a}:${r.size}:${Math.trunc(r.mtimeMs)}`}catch{return"unknown"}}((t=el()).useSrc?t.srcPath:t.distPath,t.root),n=!!r&&await en(r,e.transportPreference);if(r&&r.version===a&&r.codeSignature===o&&n)return r;r&&(r.version!==a||r.codeSignature!==o||!n)&&(await ee(r),eo(e.paths.infoPath)),function(e){let t=er(e);if(!t.hasLock||t.hasInfo)return;let s=es(e.lockPath);if(!s)return eo(e.lockPath);i(s.pid,s.processStartTime)||eo(e.lockPath)}(e.paths),await ei(e);let l=await Y(5e3,e);if(l)return l;if(await Q(e.paths)){await ei(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.`}(er(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 en(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function Q(e){let t=er(e);if(!t.hasLock||t.hasInfo)return!1;let s=es(e.lockPath);return s&&i(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=ea(e);if(!t||"string"!=typeof t.token||0===t.token.length)return null;let s=Number.isInteger(t.port)&&Number(t.port)>0,r=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;return s||r?{...t,port:s?Number(t.port):void 0,httpPort:r?Number(t.httpPort):void 0,pid:Number.isInteger(t.pid)&&t.pid>0?t.pid:0}:null}function es(e){let t=ea(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function er(e){return{hasInfo:b.existsSync(e.infoPath),hasLock:b.existsSync(e.lockPath)}}function ea(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 en(e,s){var r,a;return"http"===ep(e,s)?await ((r=e.httpPort)?new Promise(e=>{let s=t.request({host:"127.0.0.1",port:r,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 ((a=e.port)?new Promise(e=>{let t=I.createConnection({host:"127.0.0.1",port:a},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function ei(e){let t=el(),s=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],r={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};l(process.execPath,s,{env:r})}function el(){let e=p(),t=s.join(e,"dist","src","daemon.js"),r=s.join(e,"src","daemon.ts"),a=b.existsSync(t),o=b.existsSync(r);if(!a&&!o)throw new v("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:r});return{root:e,distPath:t,srcPath:r,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!a&&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((r,a)=>{let o=I.createConnection({host:"127.0.0.1",port:s},()=>{o.write(`${JSON.stringify(t)}
|
|
16
|
+
`)}),n=setTimeout(()=>{o.destroy();let s=em(),r=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:r.forcedKill}}),a(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),i="";o.setEncoding("utf8"),o.on("data",e=>{let s=(i+=e).indexOf("\n");if(-1===s)return;let l=i.slice(0,s).trim();if(l)try{let e=JSON.parse(l);o.end(),clearTimeout(n),r(e)}catch(e){clearTimeout(n),a(new v("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(n),f({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),a(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 r=e.httpPort;if(!r)throw new v("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let o=JSON.stringify({jsonrpc:"2.0",id:s.meta?.requestId??a(),method:"agent_device.command",params:s});return await new Promise((a,n)=>{let i=$(s.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=t.request({host:"127.0.0.1",port:r,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??{};n(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 n(new v("COMMAND_FAILED","Invalid daemon RPC response",{requestId:s.meta?.requestId}));a(e.result)}catch(e){clearTimeout(d),n(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(),r=eg(e,i);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:r.forcedKill}}),n(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)}}),n(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{i(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 i=a(),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:i,command:t[0],debug:l},async()=>{var a,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),r={json:!1,help:!1,version:!1},a=null,o=[],n=[],i=[],l=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(l&&"--"===s){l=!1;continue}if(!l){a?o.push(s):a=J(s);continue}let n=s.startsWith("--"),d=s.startsWith("-")&&s.length>1;if(!n&&!d){a?o.push(s):a=J(s);continue}let[p,u]=n?V(s):[s,void 0],c=P.get(p);if(!c){if(function(e,t,s){var r;if(r=s,!/^-\d+(\.\d+)?$/.test(r)||!e)return!1;let a=T(e);return!a||!!a.allowsExtraPositionals||0!==a.positionalArgs.length&&(t.length<a.positionalArgs.length||a.positionalArgs.some(e=>e.includes("?")))}(a,o,s)){a?o.push(s):a=s;continue}throw new v("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,s,r){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===r||B(r)||!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("\\"))}(r)?{value:!0,consumeNext:!1}:{value:r,consumeNext:!0}}let a=s??r;if(void 0===a||void 0===s&&B(a))throw new v("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:a,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(a))throw new v("INVALID_ARGS",`Invalid ${G(t)}: ${a}`);return{value:a,consumeNext:void 0===s}}let o=Number(a);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)}: ${a}`);return{value:Math.floor(o),consumeNext:void 0===s}}(c,p,u,e[t+1]);m.consumeNext&&(t+=1),r[c.key]=m.value,i.push({key:c.key,token:p})}let d=T(a),p=new Set([...F,...d?.allowedFlags??[]]),u=i.filter(e=>!p.has(e.key));if(u.length>0){var c,m;let e=(c=a,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(n.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),u))delete r[t.key]}if(d?.defaults)for(let[e,t]of Object.entries(d.defaults))void 0===r[e]&&(r[e]=t);if("batch"===a&&1!=+!!r.steps+ +!!r.stepsFile)throw new v("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:a,positionals:o,flags:r,warnings:n}}(t)}catch(t){f({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=n(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),r=j(new Set(t.allowedFlags)),a=j(F),o=[];return r.length>0&&o.push(q("Command flags:",r)),o.push(q("Global flags:",a)),`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===a.length)return`${
|
|
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:r,...a}=e;return a}(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,r=setInterval(()=>{if(!s&&b.existsSync(e))try{let s=b.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let r=b.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);b.readSync(r,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{b.closeSync(r)}}catch{}},200);return()=>{s=!0,clearInterval(r)}}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:i,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 r=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),n={...k,batchSteps:r};delete n.steps,delete n.stepsFile;let i=await O({command:"batch",positionals:D,flags:n});if(!i.ok)throw new v(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});I.json?U({success:!0,data:i.data??{}}):(a=i.data??{},e="number"==typeof a.total?a.total:0,t="number"==typeof a.executed?a.executed:0,s="number"==typeof a.totalDurationMs?a.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,a=Array.isArray(s)?s:[],o=!!e.truncated,n="string"==typeof e.appName?e.appName:void 0,i="string"==typeof e.appBundleId?e.appBundleId:void 0,l=[];n&&l.push(`Page: ${n}`),i&&l.push(`App: ${i}`);let d=`Snapshot: ${a.length} nodes${o?" (truncated)":""}`,p=l.length>0?`${l.join("\n")}
|
|
32
|
+
`:"";if(0===a.length)return`${p}${d}
|
|
33
|
+
`;if(t.raw){let e=a.map(e=>JSON.stringify(e));return`${p}${d}
|
|
34
34
|
${e.join("\n")}
|
|
35
|
-
`}if(
|
|
35
|
+
`}if(t.flatten){let e=a.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
|
-
`),
|
|
37
|
+
`}let u=r(a).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,r,a,o;let n,i=!0===t.baselineInitialized,l=t.summary??{},d=z(l.additions),p=z(l.removals),u=z(l.unchanged),c=(n=process.env.FORCE_COLOR,"string"==typeof n?"0"!==n:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY);if(i)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 r=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),a=Math.min(e.length-1,t+1);for(let e=s;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])})(Array.isArray(t.lines)?t.lines:[],1).map(t=>{var s,r,a,o;let n="string"==typeof t.text?t.text:"";if("added"===t.kind){let t=n.startsWith(" ")?`+${n}`:`+ ${n}`;return c?(s=t,r="green",e(r,s)):t}if("removed"===t.kind){let t=n.startsWith(" ")?`-${n}`:`- ${n}`;return c?(a=t,e("red",a)):t}return c?(o=n,e("dim",o)):n}),g=m.length>0?`${m.join("\n")}
|
|
41
|
+
`:"";if(!c)return`${g}${d} additions, ${p} removals, ${u} unchanged
|
|
42
|
+
`;let f=`${(s=String(d),r="green",e(r,s))} additions, ${(a=String(p),e("red",a))} 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,r="string"==typeof e?.state?e.state:void 0,a="string"==typeof e?.backend?e.backend:void 0,o="number"==typeof e?.sizeBytes?e.sizeBytes:void 0,n=e?.started===!0,i=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||r||a||void 0!==o)){let e=[void 0!==t?`active=${t}`:"",r?`state=${r}`:"",a?`backend=${a}`:"",void 0!==o?`sizeBytes=${o}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
|
|
52
|
+
`)}if(!I.json&&(n||i||l||d||p||void 0!==u)){let e=[n?"started=true":"",i?"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
57
|
`);let r=Array.isArray(e?.entries)?e.entries:[];if(0===r.length)process.stdout.write("No recent HTTP(s) entries found.\n");else for(let e of r){let t="string"==typeof e.method?e.method:"HTTP",s="string"==typeof e.url?e.url:"<unknown-url>",r="number"==typeof e.status?` status=${e.status}`:"",a="string"==typeof e.timestamp?`${e.timestamp} `:"";process.stdout.write(`${a}${t} ${s}${r}
|
|
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 a="boolean"==typeof e?.active?e.active:void 0,
|
|
61
|
+
`)}let a="boolean"==typeof e?.active?e.active:void 0,o="string"==typeof e?.state?e.state:void 0,n="string"==typeof e?.backend?e.backend:void 0,i="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!==a?`active=${a}`:"",o?`state=${o}`:"",n?`backend=${n}`:"",d?`include=${d}`:"",void 0!==i?`scannedLines=${i}`:"",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,r=t.data?.y;e&&"number"==typeof s&&"number"==typeof r&&process.stdout.write(`Tapped @${e} (${s}, ${r})
|
|
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",r=e?.kind?` ${e.kind}`:"",a=e?.target?` target=${e.target}`:"",o="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${r}${a})${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,r=e?.appName,a=e?.source,o=e?.package,n=e?.activity;if("ios"===t){process.stdout.write(`Foreground app: ${r??s??"unknown"}
|
|
67
67
|
`),s&&process.stdout.write(`Bundle: ${s}
|
|
68
68
|
`),a&&process.stdout.write(`Source: ${a}
|
|
69
|
-
`),
|
|
70
|
-
`),
|
|
71
|
-
`),
|
|
72
|
-
`),
|
|
69
|
+
`),L&&L();return}if("android"===t){process.stdout.write(`Foreground app: ${o??"unknown"}
|
|
70
|
+
`),n&&process.stdout.write(`Activity: ${n}
|
|
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=n(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(n(y(e)),{showDetails:!0}),process.exit(1)}),eh(process.argv.slice(2));
|