agent-device 0.7.21 → 0.7.22

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.
Files changed (128) hide show
  1. package/README.md +42 -0
  2. package/dist/src/224.js +2 -0
  3. package/dist/src/274.js +1 -0
  4. package/dist/src/331.js +3 -0
  5. package/dist/src/bin.d.ts +1 -0
  6. package/dist/src/bin.js +63 -59
  7. package/dist/src/cli-client-commands.d.ts +8 -0
  8. package/dist/src/cli.d.ts +6 -0
  9. package/dist/src/client-normalizers.d.ts +21 -0
  10. package/dist/src/client-types.d.ts +265 -0
  11. package/dist/src/client.d.ts +5 -0
  12. package/dist/src/core/app-events.d.ts +8 -0
  13. package/dist/src/core/batch.d.ts +17 -0
  14. package/dist/src/core/capabilities.d.ts +3 -0
  15. package/dist/src/core/dispatch-payload.d.ts +1 -0
  16. package/dist/src/core/dispatch-resolve.d.ts +28 -0
  17. package/dist/src/core/dispatch-series.d.ts +7 -0
  18. package/dist/src/core/dispatch.d.ts +34 -0
  19. package/dist/src/core/open-target.d.ts +4 -0
  20. package/dist/src/core/settings-contract.d.ts +8 -0
  21. package/dist/src/daemon/action-utils.d.ts +3 -0
  22. package/dist/src/daemon/app-log-android.d.ts +4 -0
  23. package/dist/src/daemon/app-log-ios.d.ts +6 -0
  24. package/dist/src/daemon/app-log-process.d.ts +15 -0
  25. package/dist/src/daemon/app-log-stream.d.ts +19 -0
  26. package/dist/src/daemon/app-log.d.ts +28 -0
  27. package/dist/src/daemon/artifact-archive.d.ts +12 -0
  28. package/dist/src/daemon/artifact-download.d.ts +12 -0
  29. package/dist/src/daemon/artifact-materialization.d.ts +17 -0
  30. package/dist/src/daemon/artifact-registry.d.ts +12 -0
  31. package/dist/src/daemon/config.d.ts +16 -0
  32. package/dist/src/daemon/context.d.ts +22 -0
  33. package/dist/src/daemon/device-ready.d.ts +6 -0
  34. package/dist/src/daemon/handlers/find.d.ts +40 -0
  35. package/dist/src/daemon/handlers/install-source.d.ts +10 -0
  36. package/dist/src/daemon/handlers/interaction.d.ts +14 -0
  37. package/dist/src/daemon/handlers/lease.d.ts +8 -0
  38. package/dist/src/daemon/handlers/parse-utils.d.ts +3 -0
  39. package/dist/src/daemon/handlers/record-trace.d.ts +15 -0
  40. package/dist/src/daemon/handlers/session-replay-heal.d.ts +8 -0
  41. package/dist/src/daemon/handlers/session-replay-script.d.ts +3 -0
  42. package/dist/src/daemon/handlers/session.d.ts +67 -0
  43. package/dist/src/daemon/handlers/snapshot.d.ts +32 -0
  44. package/dist/src/daemon/http-server.d.ts +26 -0
  45. package/dist/src/daemon/is-predicates.d.ts +14 -0
  46. package/dist/src/daemon/lease-context.d.ts +9 -0
  47. package/dist/src/daemon/lease-registry.d.ts +63 -0
  48. package/dist/src/daemon/materialized-path-registry.d.ts +15 -0
  49. package/dist/src/daemon/network-log.d.ts +32 -0
  50. package/dist/src/daemon/request-cancel.d.ts +9 -0
  51. package/dist/src/daemon/request-router.d.ts +17 -0
  52. package/dist/src/daemon/runtime-hints.d.ts +19 -0
  53. package/dist/src/daemon/script-utils.d.ts +15 -0
  54. package/dist/src/daemon/scroll-planner.d.ts +12 -0
  55. package/dist/src/daemon/selectors.d.ts +65 -0
  56. package/dist/src/daemon/server-lifecycle.d.ts +23 -0
  57. package/dist/src/daemon/session-routing.d.ts +3 -0
  58. package/dist/src/daemon/session-selector.d.ts +3 -0
  59. package/dist/src/daemon/session-store.d.ts +32 -0
  60. package/dist/src/daemon/snapshot-diff.d.ts +20 -0
  61. package/dist/src/daemon/snapshot-processing.d.ts +8 -0
  62. package/dist/src/daemon/transport.d.ts +6 -0
  63. package/dist/src/daemon/types.d.ts +115 -0
  64. package/dist/src/daemon/upload-registry.d.ts +7 -0
  65. package/dist/src/daemon/upload.d.ts +5 -0
  66. package/dist/src/daemon-client.d.ts +38 -0
  67. package/dist/src/daemon.d.ts +1 -0
  68. package/dist/src/daemon.js +36 -36
  69. package/dist/src/index.d.ts +4 -0
  70. package/dist/src/index.js +1 -0
  71. package/dist/src/platforms/android/adb.d.ts +5 -0
  72. package/dist/src/platforms/android/app-lifecycle.d.ts +30 -0
  73. package/dist/src/platforms/android/device-input-state.d.ts +19 -0
  74. package/dist/src/platforms/android/devices.d.ts +22 -0
  75. package/dist/src/platforms/android/index.d.ts +7 -0
  76. package/dist/src/platforms/android/input-actions.d.ts +12 -0
  77. package/dist/src/platforms/android/install-artifact.d.ts +11 -0
  78. package/dist/src/platforms/android/manifest.d.ts +1 -0
  79. package/dist/src/platforms/android/notifications.d.ts +11 -0
  80. package/dist/src/platforms/android/open-target.d.ts +4 -0
  81. package/dist/src/platforms/android/settings.d.ts +3 -0
  82. package/dist/src/platforms/android/snapshot.d.ts +8 -0
  83. package/dist/src/platforms/android/ui-hierarchy.d.ts +21 -0
  84. package/dist/src/platforms/appearance.d.ts +2 -0
  85. package/dist/src/platforms/boot-diagnostics.d.ts +14 -0
  86. package/dist/src/platforms/install-source.d.ts +26 -0
  87. package/dist/src/platforms/ios/apps.d.ts +34 -0
  88. package/dist/src/platforms/ios/config.d.ts +9 -0
  89. package/dist/src/platforms/ios/devicectl.d.ts +13 -0
  90. package/dist/src/platforms/ios/devices.d.ts +39 -0
  91. package/dist/src/platforms/ios/ensure-simulator.d.ts +18 -0
  92. package/dist/src/platforms/ios/index.d.ts +3 -0
  93. package/dist/src/platforms/ios/install-artifact.d.ts +18 -0
  94. package/dist/src/platforms/ios/launch-diagnostics.d.ts +11 -0
  95. package/dist/src/platforms/ios/plist.d.ts +1 -0
  96. package/dist/src/platforms/ios/runner-client.d.ts +36 -0
  97. package/dist/src/platforms/ios/runner-errors.d.ts +20 -0
  98. package/dist/src/platforms/ios/runner-session.d.ts +25 -0
  99. package/dist/src/platforms/ios/runner-transport.d.ts +10 -0
  100. package/dist/src/platforms/ios/runner-xctestrun.d.ts +18 -0
  101. package/dist/src/platforms/ios/screenshot.d.ts +13 -0
  102. package/dist/src/platforms/ios/simctl.d.ts +7 -0
  103. package/dist/src/platforms/ios/simulator.d.ts +11 -0
  104. package/dist/src/platforms/permission-utils.d.ts +9 -0
  105. package/dist/src/upload-client.d.ts +7 -0
  106. package/dist/src/utils/args.d.ts +15 -0
  107. package/dist/src/utils/command-schema.d.ts +93 -0
  108. package/dist/src/utils/device-isolation.d.ts +3 -0
  109. package/dist/src/utils/device.d.ts +27 -0
  110. package/dist/src/utils/diagnostics.d.ts +30 -0
  111. package/dist/src/utils/errors.d.ts +26 -0
  112. package/dist/src/utils/exec.d.ts +32 -0
  113. package/dist/src/utils/finders.d.ts +12 -0
  114. package/dist/src/utils/interactive.d.ts +1 -0
  115. package/dist/src/utils/interactors.d.ts +31 -0
  116. package/dist/src/utils/json-input.d.ts +1 -0
  117. package/dist/src/utils/keyed-lock.d.ts +1 -0
  118. package/dist/src/utils/output.d.ts +25 -0
  119. package/dist/src/utils/payload-input.d.ts +12 -0
  120. package/dist/src/utils/process-identity.d.ts +11 -0
  121. package/dist/src/utils/retry.d.ts +54 -0
  122. package/dist/src/utils/snapshot-lines.d.ts +12 -0
  123. package/dist/src/utils/snapshot.d.ts +42 -0
  124. package/dist/src/utils/timeouts.d.ts +3 -0
  125. package/dist/src/utils/version.d.ts +2 -0
  126. package/package.json +9 -1
  127. package/skills/agent-device/references/session-management.md +1 -1
  128. package/dist/src/678.js +0 -3
package/README.md CHANGED
@@ -35,6 +35,48 @@ Or use it without installing:
35
35
  npx agent-device open SampleApp
36
36
  ```
37
37
 
38
+ Use the typed daemon client from application code:
39
+
40
+ ```ts
41
+ import { createAgentDeviceClient } from 'agent-device';
42
+
43
+ const client = createAgentDeviceClient({ session: 'qa-ios' });
44
+
45
+ const devices = await client.devices.list({ platform: 'ios' });
46
+ const ensured = await client.simulators.ensure({
47
+ device: 'iPhone 16',
48
+ boot: true,
49
+ });
50
+
51
+ await client.apps.open({
52
+ app: 'com.apple.Preferences',
53
+ platform: 'ios',
54
+ udid: ensured.udid,
55
+ runtime: {
56
+ metroHost: '127.0.0.1',
57
+ metroPort: 8081,
58
+ },
59
+ });
60
+
61
+ const snapshot = await client.capture.snapshot({ interactiveOnly: true });
62
+ const androidClient = createAgentDeviceClient({ session: 'qa-android' });
63
+ const installed = await androidClient.apps.installFromSource({
64
+ platform: 'android',
65
+ retainPaths: true,
66
+ retentionMs: 60_000,
67
+ source: { kind: 'url', url: 'https://example.com/app.apk' },
68
+ });
69
+ await androidClient.apps.open({ app: installed.launchTarget, platform: 'android' });
70
+ console.log(installed.installablePath, installed.materializationId);
71
+ if (installed.materializationId) {
72
+ await androidClient.materializations.release({
73
+ materializationId: installed.materializationId,
74
+ });
75
+ }
76
+ await client.sessions.close();
77
+ await androidClient.sessions.close();
78
+ ```
79
+
38
80
  The skill is also accessible on [ClawHub](https://clawhub.ai/okwasniewski/agent-device).
39
81
  For structured exploratory QA workflows, use the dogfood skill at [skills/dogfood/SKILL.md](skills/dogfood/SKILL.md).
40
82
 
@@ -0,0 +1,2 @@
1
+ import{createRequestId as e,node_path as t,isAgentDeviceDaemonProcess as r,runCmdDetached as a,readVersion as n,findProjectRoot as o,node_https as i,runCmdSync as s,withDiagnosticTimer as d,resolveDaemonTransportPreference as l,emitDiagnostic as u,spawn as c,AppError as m,node_fs as p,resolveDaemonPaths as h,node_net as f,resolveDaemonServerMode as I,stopProcessForTakeover as w,node_http as A}from"./331.js";async function g(e){let{localPath:r,baseUrl:a,token:n}=e,o=p.statSync(r).isDirectory(),s=t.basename(r),d=new URL("upload",a.endsWith("/")?a:`${a}/`),l="https:"===d.protocol?i:A,u={"x-artifact-type":o?"app-bundle":"file","x-artifact-filename":s,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,a)=>{let n=l.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},t=>{let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{clearTimeout(i);try{let t=JSON.parse(r);if(!t.ok||!t.uploadId)return void a(new m("COMMAND_FAILED",`Upload failed: ${r}`));e(t.uploadId)}catch{a(new m("COMMAND_FAILED",`Invalid upload response: ${r}`))}})}),i=setTimeout(()=>{n.destroy(),a(new m("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(n.on("error",e=>{clearTimeout(i),a(new m("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),o){let e=c("tar",["cf","-","-C",t.dirname(r),t.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(n),e.on("error",e=>{n.destroy(),a(new m("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(n.destroy(),a(new m("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=p.createReadStream(r);e.pipe(n),e.on("error",e=>{n.destroy(),a(new m("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let D=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}(),v=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),y=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),E=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function _(t){let r=t.meta?.requestId??e(),a=!!(t.meta?.debug||t.flags?.verbose),n=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,r=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new m("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new m("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,n=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=l(n);if(r&&"socket"===o)throw new m("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:r});let i=I(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===n?"dual":void 0));return{paths:h(t),transportPreference:o,serverMode:i,remoteBaseUrl:r,remoteAuthToken:a}}(t),o=await d("daemon_startup",async()=>await T(n),{requestId:r,session:t.session}),i=await M(t,o),s={...t,positionals:i.positionals,flags:i.flags,token:o.token,meta:{requestId:r,debug:a,cwd:t.meta?.cwd,tenantId:t.meta?.tenantId??t.flags?.tenant,runId:t.meta?.runId??t.flags?.runId,leaseId:t.meta?.leaseId??t.flags?.leaseId,sessionIsolation:t.meta?.sessionIsolation??t.flags?.sessionIsolation,...i.uploadedArtifactId?{uploadedArtifactId:i.uploadedArtifactId}:{},...i.clientArtifactPaths?{clientArtifactPaths:i.clientArtifactPaths}:{}}};return u({level:"info",phase:"daemon_request_prepare",data:{requestId:r,command:t.command,session:t.session}}),await d("daemon_request",async()=>await B(o,s,n.transportPreference),{requestId:r,command:t.command})}async function M(e,r){let a=[...e.positionals??[]],n=e.flags?{...e.flags}:void 0,o={};if(K(r)){let r=function(e,r){if("screenshot"===e.command){let t=P(e,"path",".png");return r[0]?{field:"path",localPath:t,positionalIndex:0,positionalPath:b("screenshot",".png")}:{field:"path",localPath:t,positionalIndex:0,flagPath:b("screenshot",".png")}}if("record"===e.command&&"start"===(r[0]??"").toLowerCase()){let r=P(e,"outPath",".mp4",1);return{field:"outPath",localPath:r,positionalIndex:1,positionalPath:b("recording",t.extname(r)||".mp4")}}return null}(e,a);r&&(void 0!==r.positionalPath&&(a[r.positionalIndex]=r.positionalPath),void 0!==r.flagPath&&((n??={}).out=r.flagPath),o[r.field]=r.localPath)}if(!K(r)||"install"!==e.command&&"reinstall"!==e.command||a.length<2)return{positionals:a,flags:n,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let i=a[1];if(i.startsWith("remote:"))return a[1]=i.slice(7),{positionals:a,flags:n,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let s=t.isAbsolute(i)?i:t.resolve(e.meta?.cwd??process.cwd(),i);return p.existsSync(s)?{positionals:a,flags:n,uploadedArtifactId:await g({localPath:s,baseUrl:r.baseUrl,token:r.token}),...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}:{positionals:a,flags:n,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}}function P(e,r,a,n=0){let o=e.positionals?.[n]??e.flags?.out,i=`${"path"===r?"screenshot":"recording"}-${Date.now()}${a}`,s=o&&o.trim().length>0?o:i;return t.isAbsolute(s)?s:t.resolve(e.meta?.cwd??process.cwd(),s)}function b(e,r){let a=r.startsWith(".")?r:`.${r}`;return t.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${a}`)}async function T(e){let a;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await F(t,"http"))return t;throw new m("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}let i=R(e.paths.infoPath),s=n(),d=function(e,r=o()){try{let a=p.statSync(e),n=t.relative(r,e)||e;return`${n}:${a.size}:${Math.trunc(a.mtimeMs)}`}catch{return"unknown"}}((a=$()).useSrc?a.srcPath:a.distPath,a.root),l=!!i&&await F(i,e.transportPreference);if(i&&i.version===s&&i.codeSignature===d&&l)return i;i&&(i.version!==s||i.codeSignature!==d||!l)&&(await O(i),q(e.paths.infoPath)),function(e){let t=U(e);if(!t.hasLock||t.hasInfo)return;let a=C(e.lockPath);if(!a)return q(e.lockPath);r(a.pid,a.processStartTime)||q(e.lockPath)}(e.paths);let u=0;for(let t=1;t<=y;t+=1){await x(e);let r=await N(v,e);if(r)return r;if(await k(e.paths)){u+=1;continue}let a=U(e.paths);if(!(t<y))break;if(!a.hasInfo&&!a.hasLock){await S(150);continue}}let c=U(e.paths);throw new m("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:v,startupAttempts:y,lockRecoveryCount:u,metadataState:c,hint:function(e,t=h(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.`}(c,e.paths)})}async function N(e,t){let r=Date.now();for(;Date.now()-r<e;){let e=R(t.paths.infoPath);if(e&&await F(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function S(e){await new Promise(t=>setTimeout(t,e))}async function k(e){let t=U(e);if(!t.hasLock||t.hasInfo)return!1;let a=C(e.lockPath);return a&&r(a.pid,a.processStartTime)&&await w(a.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:a.processStartTime}),q(e.lockPath),!0}async function O(e){await w(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function R(e){let t=L(e);if(!t||"string"!=typeof t.token||0===t.token.length)return null;let r=Number.isInteger(t.port)&&Number(t.port)>0,a=Number.isInteger(t.httpPort)&&Number(t.httpPort)>0;return r||a?{...t,port:r?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 C(e){let t=L(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function U(e){return{hasInfo:p.existsSync(e.infoPath),hasLock:p.existsSync(e.lockPath)}}function L(e){if(!p.existsSync(e))return null;try{return JSON.parse(p.readFileSync(e,"utf8"))}catch{return null}}function q(e){try{p.existsSync(e)&&p.unlinkSync(e)}catch{}}async function F(e,t){var r;return"http"===z(e,t)?await function(e){let t=e.baseUrl?J(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve(!1);let r=new URL(t),a="https:"===r.protocol?i:A,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=a.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=f.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function x(e){let t=$(),r=t.useSrc?["--experimental-strip-types",t.srcPath]:[t.distPath],n={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};a(process.execPath,r,{env:n})}function $(){let e=o(),r=t.join(e,"dist","src","daemon.js"),a=t.join(e,"src","daemon.ts"),n=p.existsSync(r),i=p.existsSync(a);if(!n&&!i)throw new m("COMMAND_FAILED","Daemon entry not found",{distPath:r,srcPath:a});return{root:e,distPath:r,srcPath:a,useSrc:process.execArgv.includes("--experimental-strip-types")?i:!n&&i}}async function B(e,t,r){return"http"===z(e,r)?await V(e,t):await G(e,t)}function z(e,t){if(e.baseUrl){if("socket"===t)throw new m("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t){if(!e.httpPort)throw new m("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");return"http"}if("socket"===t){if(!e.port)throw new m("COMMAND_FAILED","Daemon socket endpoint is unavailable");return"socket"}let r=e.transport;if("http"===r&&e.httpPort)return"http";if(("socket"===r||"dual"===r)&&e.port)return"socket";if(e.httpPort)return"http";if(e.port)return"socket";throw new m("COMMAND_FAILED","Daemon metadata has no reachable transport")}async function G(e,t){let r=e.port;if(!r)throw new m("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,n)=>{let o=f.createConnection({host:"127.0.0.1",port:r},()=>{o.write(`${JSON.stringify(t)}
2
+ `)}),i=setTimeout(()=>{o.destroy();let r=j(),a=H(e,h(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:D,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:r.terminated,timedOutRunnerCleanupError:r.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),n(new m("COMMAND_FAILED","Daemon request timed out",{timeoutMs:D,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},D),s="";o.setEncoding("utf8"),o.on("data",e=>{let r=(s+=e).indexOf("\n");if(-1===r)return;let d=s.slice(0,r).trim();if(d)try{let e=JSON.parse(d);o.end(),clearTimeout(i),a(e)}catch(e){clearTimeout(i),n(new m("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:d},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(i),u({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),n(new m("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 V(t,r){let a=t.baseUrl?new URL(J(t.baseUrl,"rpc")):t.httpPort?new URL(`http://127.0.0.1:${t.httpPort}/rpc`):null;if(!a)throw new m("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:r.meta?.requestId??e(),method:"agent_device.command",params:r}),o={"content-type":"application/json","content-length":Buffer.byteLength(n)};return t.baseUrl&&t.token&&(o.authorization=`Bearer ${t.token}`,o["x-agent-device-token"]=t.token),await new Promise((e,s)=>{let d=h(r.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),l=("https:"===a.protocol?i:A).request({protocol:a.protocol,host:a.hostname,port:a.port,method:"POST",path:a.pathname+a.search,headers:o},a=>{let n="";a.setEncoding("utf8"),a.on("data",e=>{n+=e}),a.on("end",()=>{clearTimeout(c);try{let a=JSON.parse(n);if(a.error){let e=a.error.data??{};s(new m(String(e.code??"COMMAND_FAILED"),String(e.message??a.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:r.meta?.requestId}));return}if(!a.result||"object"!=typeof a.result)return void s(new m("COMMAND_FAILED","Invalid daemon RPC response",{requestId:r.meta?.requestId}));if(t.baseUrl&&a.result.ok)return void W(t,r,a.result).then(e).catch(s);e(a.result)}catch(e){clearTimeout(c),s(new m("COMMAND_FAILED","Invalid daemon response",{requestId:r.meta?.requestId,line:n},e instanceof Error?e:void 0))}})}),c=setTimeout(()=>{l.destroy();let e=K(t)?{terminated:0}:j(),a=K(t)?{forcedKill:!1}:H(t,d);u({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:D,requestId:r.meta?.requestId,command:r.command,timedOutRunnerPidsTerminated:e.terminated,timedOutRunnerCleanupError:e.error,daemonPidReset:K(t)?void 0:t.pid,daemonPidForceKilled:K(t)?void 0:a.forcedKill,daemonBaseUrl:t.baseUrl}}),s(new m("COMMAND_FAILED","Daemon request timed out",{timeoutMs:D,requestId:r.meta?.requestId,hint:K(t)?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},D);l.on("error",e=>{clearTimeout(c),u({level:"error",phase:"daemon_request_socket_error",data:{requestId:r.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),s(new m("COMMAND_FAILED","Failed to communicate with daemon",{requestId:r.meta?.requestId,hint:K(t)?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},e))}),l.write(n),l.end()})}function j(){let e=0;try{for(let t of E){let r=s("pkill",["-f",t],{allowFailure:!0});0===r.exitCode&&(e+=1)}return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function H(e,t){let a=!1;try{r(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),a=!0)}catch{w(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{q(t.infoPath),q(t.lockPath)}return{forcedKill:a}}function K(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function J(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function W(e,r,a){let n=Array.isArray(a.data?.artifacts)?a.data.artifacts:[];if(0===n.length||!e.baseUrl)return a;let o=a.data?{...a.data}:{},i=[];for(let a of n){if(!a||"object"!=typeof a||"string"!=typeof a.artifactId){i.push(a);continue}let n=function(e,r){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let a=e.fileName?.trim()||`${e.field}-${Date.now()}`;return t.resolve(r.meta?.cwd??process.cwd(),a)}(a,r);await Q({baseUrl:e.baseUrl,token:e.token,artifactId:a.artifactId,destinationPath:n,requestId:r.meta?.requestId}),o[a.field]=n,i.push({...a,localPath:n})}return o.artifacts=i,{ok:!0,data:o}}async function Q(e){var r,a;let n,o=new URL((r=e.baseUrl,a=e.artifactId,n=r.endsWith("/")?r:`${r}/`,new URL(`upload/${encodeURIComponent(a)}`,n).toString())),s="https:"===o.protocol?i:A;await p.promises.mkdir(t.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,r)=>{let a=!1,n=e.timeoutMs??D,i=n=>{if(!a){if(a=!0,clearTimeout(l),n)return void p.promises.rm(e.destinationPath,{force:!0}).finally(()=>r(n));t()}},d=s.request({protocol:o.protocol,host:o.hostname,port:o.port,method:"GET",path:o.pathname+o.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let r="";t.setEncoding("utf8"),t.on("data",e=>{r+=e}),t.on("end",()=>{i(new m("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:r}))});return}let r=p.createWriteStream(e.destinationPath);r.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{i(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{i(new m("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),r.on("finish",()=>{r.close(()=>i())}),t.pipe(r)}),l=setTimeout(()=>{d.destroy(new m("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n}))},n);d.on("error",t=>{t instanceof m?i(t):i(new m("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:n},t instanceof Error?t:void 0))}),d.end()})}function X(e,t){let r=es(e,"bundleId"),a=es(e,"package"),n=r??a;return{app:ei(e,"app"),appPath:ei(e,"appPath"),platform:el(e,"platform"),appId:n,bundleId:r,package:a,identifiers:{session:t,appId:n,appBundleId:r,package:a}}}function Y(e,t){return{session:t,configured:!0===e.configured,cleared:!0===e.cleared||void 0,runtime:et(e.runtime),identifiers:{session:t}}}function Z(e){let t=en(e),r=el(t,"platform"),a=ei(t,"id");return{platform:r,target:eu(t,"target"),kind:function(e,t){let r=e[t];if("simulator"===r||"emulator"===r||"device"===r)return r;throw new m("COMMAND_FAILED",`Daemon response has invalid "${t}".`,{response:e})}(t,"kind"),id:a,name:ei(t,"name"),booted:"boolean"==typeof t.booted?t.booted:void 0,identifiers:{deviceId:a,deviceName:ei(t,"name"),..."ios"===r?{udid:a}:{serial:a}},ios:"ios"===r?{udid:a}:void 0,android:"android"===r?{serial:a}:void 0}}function ee(e){let t=en(e),r=el(t,"platform"),a=ei(t,"id"),n=ei(t,"name"),o=eu(t,"target"),i=ei(t,"device"),s={session:n,deviceId:a,deviceName:i,..."ios"===r?{udid:a}:{serial:a}};return{name:n,createdAt:function(e,t){let r=e[t];if("number"!=typeof r||!Number.isFinite(r))throw new m("COMMAND_FAILED",`Daemon response is missing numeric "${t}".`,{response:e});return r}(t,"createdAt"),device:{platform:r,target:o,id:a,name:i,identifiers:s,ios:"ios"===r?{udid:a,simulatorSetPath:ed(t,"ios_simulator_device_set")}:void 0,android:"android"===r?{serial:a}:void 0},identifiers:s}}function et(e){if(!eo(e))return;let t=e.platform,r=es(e,"metroHost"),a="number"==typeof e.metroPort?e.metroPort:void 0;return{platform:"ios"===t||"android"===t?t:void 0,metroHost:r,metroPort:a,bundleUrl:es(e,"bundleUrl"),launchUrl:es(e,"launchUrl")}}function er(e,t){return t??e??"default"}function ea(e){let t={};for(let[r,a]of Object.entries(e))void 0!==a&&(t[r]=a);return t}function en(e){if(!eo(e))throw new m("COMMAND_FAILED","Daemon returned an unexpected response shape.",{value:e});return e}function eo(e){return"object"==typeof e&&null!==e}function ei(e,t){let r=e[t];if("string"!=typeof r||0===r.length)throw new m("COMMAND_FAILED",`Daemon response is missing "${t}".`,{response:e});return r}function es(e,t){let r=e[t];return"string"==typeof r&&r.length>0?r:void 0}function ed(e,t){let r=e[t];return null===r?null:"string"==typeof r&&r.length>0?r:void 0}function el(e,t){let r=e[t];if("ios"===r||"android"===r)return r;throw new m("COMMAND_FAILED",`Daemon response has invalid "${t}".`,{response:e})}function eu(e,t){return"tv"===e[t]?"tv":"mobile"}function ec(e={},t={}){let r=t.transport??_,a=async(t,a=[],n={})=>{let o={...e,...n},i=await r({session:er(e.session,n.session),command:t,positionals:a,flags:ea({stateDir:o.stateDir,daemonBaseUrl:o.daemonBaseUrl,daemonAuthToken:o.daemonAuthToken,daemonTransport:o.daemonTransport,daemonServerMode:o.daemonServerMode,tenant:o.tenant,sessionIsolation:o.sessionIsolation,runId:o.runId,leaseId:o.leaseId,platform:o.platform,target:o.target,device:o.device,udid:o.udid,serial:o.serial,iosSimulatorDeviceSet:o.iosSimulatorDeviceSet,androidDeviceAllowlist:o.androidDeviceAllowlist,runtime:o.simulatorRuntimeId,boot:o.boot,reuseExisting:o.reuseExisting,activity:o.activity,relaunch:o.relaunch,shutdown:o.shutdown,saveScript:o.saveScript,noRecord:o.noRecord,metroHost:o.metroHost,metroPort:o.metroPort,bundleUrl:o.bundleUrl,launchUrl:o.launchUrl,snapshotInteractiveOnly:o.interactiveOnly,snapshotCompact:o.compact,snapshotDepth:o.depth,snapshotScope:o.scope,snapshotRaw:o.raw,verbose:o.debug}),runtime:o.runtime,meta:ea({requestId:o.requestId,cwd:o.cwd,debug:o.debug,tenantId:o.tenant,runId:o.runId,leaseId:o.leaseId,sessionIsolation:o.sessionIsolation,installSource:o.installSource,retainMaterializedPaths:o.retainMaterializedPaths,materializedPathRetentionMs:o.materializedPathRetentionMs,materializationId:o.materializationId})});if(!i.ok)throw new m(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});return i.data??{}},n=async(e={})=>{let t=await a("session_list",[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(ee)};return{devices:{list:async(e={})=>{let t=await a("devices",[],e);return(Array.isArray(t.devices)?t.devices:[]).map(Z)}},sessions:{list:async(e={})=>await n(e),close:async(t={})=>{let r=er(e.session,t.session),n=(await a("close",[],t)).shutdown;return{session:r,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},simulators:{ensure:async e=>{let{runtime:t,...r}=e,n=await a("ensure-simulator",[],{...r,simulatorRuntimeId:t}),o=ei(n,"udid"),i=ei(n,"device");return{udid:o,device:i,runtime:ei(n,"runtime"),created:!0===n.created,booted:!0===n.booted,iosSimulatorDeviceSet:ed(n,"ios_simulator_device_set"),identifiers:{deviceId:o,deviceName:i,udid:o}}}},apps:{install:async t=>X(await a("install",[t.app,t.appPath],t),er(e.session,t.session)),reinstall:async t=>X(await a("reinstall",[t.app,t.appPath],t),er(e.session,t.session)),installFromSource:async t=>{var r,n;let o,i,s;return r=await a("install_source",[],{...t,installSource:t.source,retainMaterializedPaths:t.retainPaths,materializedPathRetentionMs:t.retentionMs}),n=er(e.session,t.session),o=es(r,"bundleId"),i=es(r,"packageName"),s=o??i,{appName:es(r,"appName"),appId:s,bundleId:o,packageName:i,launchTarget:ei(r,"launchTarget"),installablePath:es(r,"installablePath"),archivePath:es(r,"archivePath"),materializationId:es(r,"materializationId"),materializationExpiresAt:es(r,"materializationExpiresAt"),identifiers:{session:n,appId:s,appBundleId:o,package:i}}},open:async t=>{let r=er(e.session,t.session),n=t.url?[t.app,t.url]:[t.app],o=await a("open",n,t),i=function(e){let t=e.platform,r=es(e,"id"),a=es(e,"device");if("ios"!==t&&"android"!==t||!r||!a)return;let n=eu(e,"target"),o={deviceId:r,deviceName:a,..."ios"===t?{udid:r}:{serial:r}};return{platform:t,target:n,id:r,name:a,identifiers:o,ios:"ios"===t?{udid:es(e,"device_udid")??r,simulatorSetPath:ed(e,"ios_simulator_device_set")}:void 0,android:"android"===t?{serial:es(e,"serial")??r}:void 0}}(o),s=es(o,"appBundleId");return{session:r,appName:es(o,"appName"),appBundleId:s,appId:s,startup:function(e){if(eo(e)&&"number"==typeof e.durationMs&&"string"==typeof e.measuredAt&&"string"==typeof e.method)return{durationMs:e.durationMs,measuredAt:e.measuredAt,method:e.method,appTarget:es(e,"appTarget"),appBundleId:es(e,"appBundleId")}}(o.startup),runtime:et(o.runtime),device:i,identifiers:{session:r,deviceId:i?.id,deviceName:i?.name,udid:i?.ios?.udid,serial:i?.android?.serial,appId:s,appBundleId:s}}},close:async(t={})=>{let r=er(e.session,t.session),n=(await a("close",t.app?[t.app]:[],t)).shutdown;return{session:r,closedApp:t.app,shutdown:"object"==typeof n&&null!==n?n:void 0,identifiers:{session:r}}}},materializations:{release:async e=>{var t;return{released:!0===(t=await a("release_materialized_paths",[],{...e,materializationId:e.materializationId})).released,materializationId:ei(t,"materializationId"),identifiers:{}}}},runtime:{set:async t=>Y(await a("runtime",["set"],t),er(e.session,t.session)),show:async(t={})=>Y(await a("runtime",["show"],t),er(e.session,t.session))},capture:{snapshot:async(t={})=>{var r;let n=er(e.session,t.session),o=await a("snapshot",[],t),i=es(o,"appBundleId");return{nodes:Array.isArray(r=o.nodes)?r:[],truncated:!0===o.truncated,appName:es(o,"appName"),appBundleId:i,identifiers:{session:n,appId:i,appBundleId:i}}},screenshot:async(t={})=>{let r=er(e.session,t.session);return{path:ei(await a("screenshot",t.path?[t.path]:[],t),"path"),identifiers:{session:r}}}}}}export{ec as createAgentDeviceClient,_ as sendToDaemon};
@@ -0,0 +1 @@
1
+ import{AppError as e}from"./331.js";let t="<wifi|airplane|location> <on|off>",r="appearance <light|dark|toggle>",a="faceid <match|nonmatch|enroll|unenroll>",i="touchid <match|nonmatch|enroll|unenroll>",n="fingerprint <match|nonmatch>",s="permission <grant|deny|reset> <camera|microphone|photos|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> [full|limited]",o=`settings ${t} | settings ${r} | settings ${a} | settings ${i} | settings ${n} | settings ${s}`,l=`settings requires ${t}, ${r}, ${a}, ${i}, ${n}, or ${s}`;function c(e){let t=[],r=[];for(let a of e){let e=a.depth??0;for(;t.length>0&&e<=t[t.length-1];)t.pop();let i=a.label?.trim()||a.value?.trim()||a.identifier?.trim()||"",n=d(a.type??"Element"),s="group"===n&&!i;s&&t.push(e);let o=s?e:Math.max(0,e-t.length);r.push({node:a,depth:o,type:n,text:u(a,o,s,n)})}return r}function u(e,t,r,a){let i=a??d(e.type??"Element"),n=m(e,i),s=" ".repeat(t),o=e.ref?`@${e.ref}`:"",l=[!1===e.enabled?"disabled":null].filter(Boolean).join(", "),c=l?` [${l}]`:"",u=n?` "${n}"`:"";return r?`${s}${o} [${i}]${c}`.trimEnd():`${s}${o} [${i}]${u}${c}`.trimEnd()}function m(e,t){var r,a;let i=e.label?.trim(),n=e.value?.trim();if("text-field"===(r=t)||"text-view"===r||"search"===r){if(n)return n;if(i)return i}else if(i)return i;if(n)return n;let s=e.identifier?.trim();return!s||(a=s,/^[\w.]+:id\/[\w.-]+$/i.test(a)&&("group"===t||"image"===t||"list"===t||"collection"===t))?"":s}function d(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"}}let p=100,h=new Set(["batch","replay"]);function f(t){let r;try{r=JSON.parse(t)}catch{throw new e("INVALID_ARGS","Batch steps must be valid JSON.")}if(!Array.isArray(r)||0===r.length)throw new e("INVALID_ARGS","Batch steps must be a non-empty JSON array.");return r}function w(t,r){if(!Array.isArray(t)||0===t.length)throw new e("INVALID_ARGS","batch requires a non-empty batchSteps array.");if(t.length>r)throw new e("INVALID_ARGS",`batch has ${t.length} steps; max allowed is ${r}.`);let a=[];for(let r=0;r<t.length;r+=1){let i=t[r];if(!i||"object"!=typeof i)throw new e("INVALID_ARGS",`Invalid batch step at index ${r}.`);let n="string"==typeof i.command?i.command.trim().toLowerCase():"";if(!n)throw new e("INVALID_ARGS",`Batch step ${r+1} requires command.`);if(h.has(n))throw new e("INVALID_ARGS",`Batch step ${r+1} cannot run ${n}.`);if(void 0!==i.positionals&&!Array.isArray(i.positionals))throw new e("INVALID_ARGS",`Batch step ${r+1} positionals must be an array.`);let s=i.positionals??[];if(s.some(e=>"string"!=typeof e))throw new e("INVALID_ARGS",`Batch step ${r+1} positionals must contain only strings.`);if(void 0!==i.flags&&("object"!=typeof i.flags||Array.isArray(i.flags)||!i.flags))throw new e("INVALID_ARGS",`Batch step ${r+1} flags must be an object.`);if(void 0!==i.runtime&&("object"!=typeof i.runtime||Array.isArray(i.runtime)||!i.runtime))throw new e("INVALID_ARGS",`Batch step ${r+1} runtime must be an object.`);a.push({command:n,positionals:s,flags:i.flags??{},runtime:i.runtime})}return a}export{TextDecoder,styleText}from"node:util";export{p as DEFAULT_BATCH_MAX_STEPS,l as SETTINGS_INVALID_ARGS_MESSAGE,o as SETTINGS_USAGE_OVERRIDE,c as buildSnapshotDisplayLines,m as displayLabel,d as formatRole,u as formatSnapshotLine,f as parseBatchStepsJson,w as validateAndNormalizeBatchSteps};
@@ -0,0 +1,3 @@
1
+ import{URL as e,fileURLToPath as t,pathToFileURL as r}from"node:url";import{spawn as n,spawnSync as o}from"node:child_process";import i from"node:os";import s,{promises as a}from"node:fs";import d from"node:path";import{AsyncLocalStorage as u}from"node:async_hooks";import c from"node:crypto";let l=new u,f=/(token|secret|password|authorization|cookie|api[_-]?key|access[_-]?key|private[_-]?key)/i,m=/(bearer\s+[a-z0-9._-]+|(?:api[_-]?key|token|secret|password)\s*[=:]\s*\S+)/i;function p(){return c.randomBytes(8).toString("hex")}async function h(e,t){let r={...e,diagnosticId:`${Date.now().toString(36)}-${c.randomBytes(4).toString("hex")}`,events:[]};return await l.run(r,t)}function g(){let e=l.getStore();return e?{diagnosticId:e.diagnosticId,requestId:e.requestId,session:e.session,command:e.command,debug:e.debug}:{}}function w(e){let t=l.getStore();if(!t)return;let r={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?D(e.data):void 0};if(t.events.push(r),!t.debug)return;let n=`[agent-device][diag] ${JSON.stringify(r)}
2
+ `;try{t.logPath&&s.appendFile(t.logPath,n,()=>{}),t.traceLogPath&&s.appendFile(t.traceLogPath,n,()=>{}),t.logPath||t.traceLogPath||process.stderr.write(n)}catch{}}async function S(e,t,r){let n=Date.now();try{let o=await t();return w({level:"info",phase:e,durationMs:Date.now()-n,data:r}),o}catch(t){throw w({level:"error",phase:e,durationMs:Date.now()-n,data:{...r??{},error:t instanceof Error?t.message:String(t)}}),t}}function E(e={}){let t=l.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,"_"),r=new Date().toISOString().slice(0,10),n=d.join(i.homedir(),".agent-device","logs",e,r);s.mkdirSync(n,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),a=d.join(n,`${o}-${t.diagnosticId}.ndjson`),u=t.events.map(e=>JSON.stringify(D(e)));return s.writeFileSync(a,`${u.join("\n")}
3
+ `),t.events=[],a}catch{return null}}function D(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&&f.test(i)||m.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 s={};for(let[n,o]of Object.entries(t)){if(f.test(n)){s[n]="[REDACTED]";continue}s[n]=e(o,r,n)}return s}(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 y(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=y(e),n=r.details?D(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,s=(n&&"string"==typeof n.logPath?n.logPath:void 0)??t.logPath,a=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),d=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),u=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:u,hint:a,diagnosticId:i,logPath:s,details:d}}async function M(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached}),a="",d=r.binaryStdout?Buffer.alloc(0):void 0,u="",c=!1,l=C(r.timeoutMs),f=l?setTimeout(()=>{c=!0,s.kill("SIGKILL")},l):null;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{r.binaryStdout?d=Buffer.concat([d??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]):a+=e}),s.stderr.on("data",e=>{u+=e}),s.on("error",r=>{(f&&clearTimeout(f),"ENOENT"===r.code)?i(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{f&&clearTimeout(f);let s=n??1;c&&l?i(new v("COMMAND_FAILED",`${e} timed out after ${l}ms`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,timeoutMs:l})):0===s||r.allowFailure?o({stdout:a,stderr:u,exitCode:s,stdoutBuffer:d}):i(new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:u,exitCode:s,processExitError:!0}))})})}async function A(e){try{var t;let{shell:r,args:n}=(t=e,"win32"===process.platform?{shell:"cmd.exe",args:["/c","where",t]}:{shell:"bash",args:["-lc",`command -v ${t}`]}),o=await M(r,n,{allowFailure:!0});return 0===o.exitCode&&o.stdout.trim().length>0}catch{return!1}}function N(e,t,r={}){let n=o(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],encoding:r.binaryStdout?void 0:"utf8",input:r.stdin,timeout:C(r.timeoutMs)});if(n.error){let o=n.error.code;if("ETIMEDOUT"===o)throw new v("COMMAND_FAILED",`${e} timed out after ${C(r.timeoutMs)}ms`,{cmd:e,args:t,timeoutMs:C(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 i=r.binaryStdout?Buffer.isBuffer(n.stdout)?n.stdout:Buffer.from(n.stdout??""):void 0,s=r.binaryStdout?"":"string"==typeof n.stdout?n.stdout:(n.stdout??"").toString(),a="string"==typeof n.stderr?n.stderr:(n.stderr??"").toString(),d=n.status??1;if(0!==d&&!r.allowFailure)throw new v("COMMAND_FAILED",`${e} exited with code ${d}`,{cmd:e,args:t,stdout:s,stderr:a,exitCode:d,processExitError:!0});return{stdout:s,stderr:a,exitCode:d,stdoutBuffer:i}}function O(e,t,r={}){n(e,t,{cwd:r.cwd,env:r.env,stdio:"ignore",detached:!0}).unref()}async function T(e,t,r={}){return new Promise((o,i)=>{let s=n(e,t,{cwd:r.cwd,env:r.env,stdio:["pipe","pipe","pipe"],detached:r.detached});r.onSpawn?.(s);let a="",d="",u=r.binaryStdout?Buffer.alloc(0):void 0;r.binaryStdout||s.stdout.setEncoding("utf8"),s.stderr.setEncoding("utf8"),void 0!==r.stdin&&s.stdin.write(r.stdin),s.stdin.end(),s.stdout.on("data",e=>{if(r.binaryStdout){u=Buffer.concat([u??Buffer.alloc(0),Buffer.isBuffer(e)?e:Buffer.from(e)]);return}let t=String(e);a+=t,r.onStdoutChunk?.(t)}),s.stderr.on("data",e=>{let t=String(e);d+=t,r.onStderrChunk?.(t)}),s.on("error",r=>{"ENOENT"===r.code?i(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):i(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),s.on("close",n=>{let s=n??1;0===s||r.allowFailure?o({stdout:a,stderr:d,exitCode:s,stdoutBuffer:u}):i(new v("COMMAND_FAILED",`${e} exited with code ${s}`,{cmd:e,args:t,stdout:a,stderr:d,exitCode:s,processExitError:!0}))})})}function _(e,t,r={}){let o=n(e,t,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"],detached:r.detached}),i="",s="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",e=>{i+=e}),o.stderr.on("data",e=>{s+=e});let a=new Promise((n,a)=>{o.on("error",r=>{"ENOENT"===r.code?a(new v("TOOL_MISSING",`${e} not found in PATH`,{cmd:e},r)):a(new v("COMMAND_FAILED",`Failed to run ${e}`,{cmd:e,args:t},r))}),o.on("close",o=>{let d=o??1;0===d||r.allowFailure?n({stdout:i,stderr:s,exitCode:d}):a(new v("COMMAND_FAILED",`${e} exited with code ${d}`,{cmd:e,args:t,stdout:i,stderr:s,exitCode:d,processExitError:!0}))})});return{child:o,wait:a}}function C(e){if(!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t}function P(){try{let e=L();return JSON.parse(s.readFileSync(d.join(e,"package.json"),"utf8")).version??"0.0.0"}catch{return"0.0.0"}}function L(){let e=d.dirname(t(import.meta.url)),r=e;for(let e=0;e<6;e+=1){let e=d.join(r,"package.json");if(s.existsSync(e))return r;r=d.dirname(r)}return e}let F=[/(^|[\/\s"'=])dist\/src\/daemon\.js($|[\s"'])/,/(^|[\/\s"'=])src\/daemon\.ts($|[\s"'])/];function $(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return"EPERM"===e.code}}function k(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=N("ps",["-p",String(e),"-o","lstart="],{allowFailure:!0,timeoutMs:1e3});if(0!==t.exitCode)return null;let r=t.stdout.trim();return r.length>0?r:null}catch{return null}}function b(e){if(!Number.isInteger(e)||e<=0)return null;try{let t=N("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 x(e,t){let r;if(!$(e))return!1;if(t){let r=k(e);if(!r||r!==t)return!1}let n=b(e);return!!n&&!!(r=n.toLowerCase().replaceAll("\\","/")).includes("agent-device")&&F.some(e=>e.test(r))}function R(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 j(e,t){if(!$(e))return!0;let r=Date.now();for(;Date.now()-r<t;)if(await new Promise(e=>setTimeout(e,50)),!$(e))return!0;return!$(e)}async function B(e,t){!x(e,t.expectedStartTime)||!R(e,"SIGTERM")||await j(e,t.termTimeoutMs)||R(e,"SIGKILL")&&await j(e,t.killTimeoutMs)}function U(e){let t,r=(t=(e??"").trim())?"~"===t?i.homedir():t.startsWith("~/")?d.join(i.homedir(),t.slice(2)):d.resolve(t):d.join(i.homedir(),".agent-device");return{baseDir:r,infoPath:d.join(r,"daemon.json"),lockPath:d.join(r,"daemon.lock"),logPath:d.join(r,"daemon.log"),sessionsDir:d.join(r,"sessions")}}function G(e){let t=(e??"").trim().toLowerCase();return"http"===t?"http":"dual"===t?"dual":"socket"}function q(e){let t=(e??"").trim().toLowerCase();return"auto"===t?"auto":"socket"===t?"socket":"http"===t?"http":"auto"}function H(e){return"tenant"===(e??"").trim().toLowerCase()?"tenant":"none"}function z(e){if(!e)return;let t=e.trim();if(t&&/^[a-zA-Z0-9._-]{1,128}$/.test(t))return t}export{default as node_net}from"node:net";export{default as node_http}from"node:http";export{default as node_https}from"node:https";export{v as AppError,y as asAppError,p as createRequestId,w as emitDiagnostic,e as external_node_url_URL,t as fileURLToPath,L as findProjectRoot,E as flushDiagnosticsToSessionFile,g as getDiagnosticsMeta,x as isAgentDeviceDaemonProcess,$ as isProcessAlive,c as node_crypto,s as node_fs,i as node_os,d as node_path,I as normalizeError,z as normalizeTenantId,r as pathToFileURL,a as promises,b as readProcessCommand,k as readProcessStartTime,P as readVersion,U as resolveDaemonPaths,G as resolveDaemonServerMode,q as resolveDaemonTransportPreference,H as resolveSessionIsolationMode,M as runCmd,_ as runCmdBackground,O as runCmdDetached,T as runCmdStreaming,N as runCmdSync,n as spawn,B as stopProcessForTakeover,A as whichCmd,S as withDiagnosticTimer,h as withDiagnosticsScope};
@@ -0,0 +1 @@
1
+ export {};
package/dist/src/bin.js CHANGED
@@ -1,22 +1,35 @@
1
- import{styleText as e}from"node:util";import t from"node:https";import{node_http as s,node_path as a,buildSnapshotDisplayLines as r,createRequestId as o,parseBatchStepsJson as n,normalizeError as i,isAgentDeviceDaemonProcess as l,runCmdDetached as d,readVersion as p,findProjectRoot as u,getDiagnosticsMeta as c,runCmdSync as m,withDiagnosticTimer as g,resolveDaemonTransportPreference as f,emitDiagnostic as h,SETTINGS_USAGE_OVERRIDE as y,asAppError as w,spawn as v,pathToFileURL as b,AppError as A,node_fs as I,withDiagnosticsScope as D,node_net as k,flushDiagnosticsToSessionFile as $,resolveDaemonServerMode as S,resolveDaemonPaths as E,stopProcessForTakeover as L,formatSnapshotLine as x}from"./678.js";let _=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],O=["snapshotDepth","snapshotScope","snapshotRaw"],P=[{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{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:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"runtime set: session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"runtime set: session-scoped Metro/debug port hint"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"runtime set: session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"runtime set: session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{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:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{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"}],T=new Set(["json","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),N={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","shutdown"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{description:"Install app from binary path without uninstalling first",positionalArgs:["app","path"],allowedFlags:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[..._]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[..._]},"ensure-simulator":{description:"Ensure an iOS simulator exists in a device set (create if missing)",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},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},runtime:{usageOverride:"runtime set|show|clear",description:"Manage session-scoped runtime hints",positionalArgs:["set|show|clear"],allowedFlags:["metroHost","metroPort","bundleUrl","launchUrl"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",description:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",description:"Inspect Android keyboard visibility/type or dismiss it",positionalArgs:["action?"],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:[...O]},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",...O]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...O]},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",...O]},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:[...O]},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:[...O]},settings:{usageOverride:y,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}},M=new Map,F=new Map;for(let e of P){for(let t of e.names)M.set(t,e);let t=F.get(e.key);t?t.push(e):F.set(e.key,[e])}function R(e){if(e)return N[e]}function C(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function U(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(C),...t.allowedFlags.flatMap(e=>(F.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let j=function(){let e=`agent-device <command> [args] [--json]
1
+ import{formatSnapshotLine as e,SETTINGS_USAGE_OVERRIDE as t,styleText as s,parseBatchStepsJson as a,buildSnapshotDisplayLines as i}from"./274.js";import{createRequestId as o,asAppError as r,normalizeError as n,pathToFileURL as l,AppError as p,readVersion as d,node_fs as u,withDiagnosticsScope as c,getDiagnosticsMeta as g,flushDiagnosticsToSessionFile as m,resolveDaemonPaths as f,emitDiagnostic as h}from"./331.js";import{createAgentDeviceClient as y,sendToDaemon as v}from"./224.js";let w=["snapshotInteractiveOnly","snapshotCompact","snapshotDepth","snapshotScope","snapshotRaw"],b=["snapshotDepth","snapshotScope","snapshotRaw"],$=[{key:"stateDir",names:["--state-dir"],type:"string",usageLabel:"--state-dir <path>",usageDescription:"Daemon state directory (defaults to ~/.agent-device)"},{key:"daemonBaseUrl",names:["--daemon-base-url"],type:"string",usageLabel:"--daemon-base-url <url>",usageDescription:"Explicit remote HTTP daemon base URL (skip local daemon discovery/startup)"},{key:"daemonAuthToken",names:["--daemon-auth-token"],type:"string",usageLabel:"--daemon-auth-token <token>",usageDescription:"Remote HTTP daemon auth token (sent as request token and bearer header)"},{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:"runtime",names:["--runtime"],type:"string",usageLabel:"--runtime <id>",usageDescription:"ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)"},{key:"metroHost",names:["--metro-host"],type:"string",usageLabel:"--metro-host <host>",usageDescription:"runtime set: session-scoped Metro/debug host hint"},{key:"metroPort",names:["--metro-port"],type:"int",min:1,max:65535,usageLabel:"--metro-port <port>",usageDescription:"runtime set: session-scoped Metro/debug port hint"},{key:"bundleUrl",names:["--bundle-url"],type:"string",usageLabel:"--bundle-url <url>",usageDescription:"runtime set: session-scoped bundle URL hint"},{key:"launchUrl",names:["--launch-url"],type:"string",usageLabel:"--launch-url <url>",usageDescription:"runtime set: session-scoped deep link / launch URL hint"},{key:"boot",names:["--boot"],type:"boolean",usageLabel:"--boot",usageDescription:"ensure-simulator: boot the simulator after ensuring it exists"},{key:"reuseExisting",names:["--reuse-existing"],type:"boolean",usageLabel:"--reuse-existing",usageDescription:"ensure-simulator: reuse an existing simulator (default: true)"},{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:"shutdown",names:["--shutdown"],type:"boolean",usageLabel:"--shutdown",usageDescription:"close: shutdown associated iOS simulator after ending session"},{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"}],k=new Set(["json","stateDir","daemonBaseUrl","daemonAuthToken","daemonTransport","daemonServerMode","tenant","sessionIsolation","runId","leaseId","help","version","verbose","platform","target","device","udid","serial","iosSimulatorDeviceSet","androidDeviceAllowlist","session","noRecord"]),A={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","shutdown"]},reinstall:{description:"Uninstall + install app from binary path",positionalArgs:["app","path"],allowedFlags:[]},install:{description:"Install app from binary path without uninstalling first",positionalArgs:["app","path"],allowedFlags:[]},push:{description:"Simulate push notification payload delivery",positionalArgs:["bundleOrPackage","payloadOrJson"],allowedFlags:[]},snapshot:{description:"Capture accessibility tree",positionalArgs:[],allowedFlags:[...w]},diff:{usageOverride:"diff snapshot",description:"Diff current accessibility snapshot against previous baseline",positionalArgs:["kind"],allowedFlags:[...w]},"ensure-simulator":{description:"Ensure an iOS simulator exists in a device set (create if missing)",positionalArgs:[],allowedFlags:["runtime","boot","reuseExisting"],skipCapabilityCheck:!0},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},runtime:{usageOverride:"runtime set|show|clear",description:"Manage session-scoped runtime hints",positionalArgs:["set|show|clear"],allowedFlags:["metroHost","metroPort","bundleUrl","launchUrl"],skipCapabilityCheck:!0},clipboard:{usageOverride:"clipboard read | clipboard write <text>",description:"Read or write device clipboard text",positionalArgs:["read|write","text?"],allowsExtraPositionals:!0,allowedFlags:[]},keyboard:{usageOverride:"keyboard [status|get|dismiss]",description:"Inspect Android keyboard visibility/type or dismiss it",positionalArgs:["action?"],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:[...b]},alert:{usageOverride:"alert [get|accept|dismiss|wait] [timeout]",description:"Inspect or handle alert (iOS simulator)",positionalArgs:["action?","timeout?"],allowedFlags:[]},click:{usageOverride:"click <x y|@ref|selector>",description:"Tap/click by coordinates, snapshot ref, or selector",positionalArgs:["target"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...b]},get:{usageOverride:"get text|attrs <@ref|selector>",description:"Return element text/attributes by ref or selector",positionalArgs:["subcommand","target"],allowedFlags:[...b]},replay:{description:"Replay a recorded session",positionalArgs:["path"],allowedFlags:["replayUpdate"],skipCapabilityCheck:!0},batch:{usageOverride:"batch [--steps <json> | --steps-file <path>]",description:"Execute multiple commands in one daemon request",positionalArgs:[],allowedFlags:["steps","stepsFile","batchOnError","batchMaxSteps","out"],skipCapabilityCheck:!0},press:{usageOverride:"press <x y|@ref|selector>",description:"Tap/press by coordinates, snapshot ref, or selector (supports repeated series)",positionalArgs:["targetOrX","y?"],allowsExtraPositionals:!0,allowedFlags:["count","intervalMs","holdMs","jitterPx","doubleTap",...b]},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:[...b]},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:[...b]},settings:{usageOverride:t,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}},S=new Map,D=new Map;for(let e of $){for(let t of e.names)S.set(t,e);let t=D.get(e.key);t?t.push(e):D.set(e.key,[e])}function x(e){if(e)return A[e]}function I(e){let t=e.endsWith("?"),s=t?e.slice(0,-1):e;return t?`[${s}]`:`<${s}>`}function L(e,t){return t.usageOverride?t.usageOverride:[e,...t.positionalArgs.map(I),...t.allowedFlags.flatMap(e=>(D.get(e)??[]).map(e=>e.usageLabel??e.names[0])).map(e=>`[${e}]`)].join(" ")}let F=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(N).map(e=>{let t=N[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:U(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=V("Flags:",P.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
4
+ `,t=Object.keys(A).map(e=>{let t=A[e];if(!t)throw Error(`Missing command schema for ${e}`);return{name:e,schema:t,usage:L(e,t)}}),s=Math.max(...t.map(e=>e.usage.length))+2,a=["Commands:"];for(let e of t)a.push(` ${e.usage.padEnd(s)}${e.schema.description}`);let i=N("Flags:",$.filter(e=>e.usageLabel&&e.usageDescription));return`${e}
5
5
  ${a.join("\n")}
6
6
 
7
- ${r}
8
- `}();function q(e){return P.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function V(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 G(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function B(e){return e.replace(/^-+/,"")}function J(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?G(e):[e,void 0];return void 0!==M.get(t)}function W(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function z(e){process.stdout.write(`${JSON.stringify(e,null,2)}
10
- `)}function H(e,t={}){let s=e instanceof A?i(e):e;process.stderr.write(`Error (${s.code}): ${s.message}
7
+ ${i}
8
+ `}();function O(e){return $.filter(t=>e.has(t.key)&&void 0!==t.usageLabel&&void 0!==t.usageDescription)}function N(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 _(e){let t=e.indexOf("=");return -1===t?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function R(e){return e.replace(/^-+/,"")}function j(e){if(!e.startsWith("-")||"-"===e)return!1;let[t]=e.startsWith("--")?_(e):[e,void 0];return void 0!==S.get(t)}function E(e){return"long-press"===e?"longpress":"metrics"===e?"perf":e}function C(e){process.stdout.write(`${JSON.stringify(e,null,2)}
10
+ `)}function P(e,t={}){let s=e instanceof p?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 K(e){return"number"==typeof e&&Number.isFinite(e)?e:0}async function X(e){let{localPath:r,baseUrl:o,token:n}=e,i=I.statSync(r).isDirectory(),l=a.basename(r),d=new URL("upload",o.endsWith("/")?o:`${o}/`),p="https:"===d.protocol?t:s,u={"x-artifact-type":i?"app-bundle":"file","x-artifact-filename":l,"transfer-encoding":"chunked"};return n&&(u.authorization=`Bearer ${n}`,u["x-agent-device-token"]=n),new Promise((e,t)=>{let s=p.request({protocol:d.protocol,host:d.hostname,port:d.port,method:"POST",path:d.pathname+d.search,headers:u},s=>{let a="";s.setEncoding("utf8"),s.on("data",e=>{a+=e}),s.on("end",()=>{clearTimeout(o);try{let s=JSON.parse(a);if(!s.ok||!s.uploadId)return void t(new A("COMMAND_FAILED",`Upload failed: ${a}`));e(s.uploadId)}catch{t(new A("COMMAND_FAILED",`Invalid upload response: ${a}`))}})}),o=setTimeout(()=>{s.destroy(),t(new A("COMMAND_FAILED","Artifact upload timed out",{timeoutMs:3e5,hint:"The upload to the remote daemon exceeded the 5-minute timeout."}))},3e5);if(s.on("error",e=>{clearTimeout(o),t(new A("COMMAND_FAILED","Failed to upload artifact to remote daemon",{hint:"Verify the remote daemon is reachable and supports artifact uploads."},e))}),i){let e=v("tar",["cf","-","-C",a.dirname(r),a.basename(r)],{stdio:["ignore","pipe","pipe"]});e.stdout.pipe(s),e.on("error",e=>{s.destroy(),t(new A("COMMAND_FAILED","Failed to create tar archive for app bundle",{},e))}),e.on("close",e=>{0!==e&&(s.destroy(),t(new A("COMMAND_FAILED",`tar failed with exit code ${e}`)))})}else{let e=I.createReadStream(r);e.pipe(s),e.on("error",e=>{s.destroy(),t(new A("COMMAND_FAILED","Failed to read local artifact",{},e))})}})}let Z=function(e=process.env.AGENT_DEVICE_DAEMON_TIMEOUT_MS){if(!e)return 9e4;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):9e4}(),Y=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS){if(!e)return 15e3;let t=Number(e);return Number.isFinite(t)?Math.max(1e3,Math.floor(t)):15e3}(),Q=function(e=process.env.AGENT_DEVICE_DAEMON_STARTUP_ATTEMPTS){if(!e)return 2;let t=Number(e);return Number.isFinite(t)?Math.min(5,Math.max(1,Math.floor(t))):2}(),ee=["xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand","xcodebuild .*AgentDeviceRunner\\.env\\.session-","xcodebuild build-for-testing .*ios-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj"];async function et(e){let t=e.meta?.requestId??o(),s=!!(e.meta?.debug||e.flags?.verbose),a=function(e){let t=e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR,s=function(e){let t;if(e){try{t=new URL(e)}catch(t){throw new A("INVALID_ARGS","Invalid daemon base URL",{daemonBaseUrl:e},t instanceof Error?t:void 0)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw new A("INVALID_ARGS","Daemon base URL must use http or https",{daemonBaseUrl:e});return t.toString().replace(/\/+$/,"")}}(e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL),a=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN,r=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,o=f(r);if(s&&"socket"===o)throw new A("INVALID_ARGS","Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.",{daemonBaseUrl:s});let n=S(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??("dual"===r?"dual":void 0));return{paths:E(t),transportPreference:o,serverMode:n,remoteBaseUrl:s,remoteAuthToken:a}}(e),r=await g("daemon_startup",async()=>await eo(a),{requestId:t,session:e.session}),n=await es(e,r),i={...e,positionals:n.positionals,flags:n.flags,token:r.token,meta:{requestId:t,debug:s,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,...n.uploadedArtifactId?{uploadedArtifactId:n.uploadedArtifactId}:{},...n.clientArtifactPaths?{clientArtifactPaths:n.clientArtifactPaths}:{}}};return h({level:"info",phase:"daemon_request_prepare",data:{requestId:t,command:e.command,session:e.session}}),await g("daemon_request",async()=>await ew(r,i,a.transportPreference),{requestId:t,command:e.command})}async function es(e,t){let s=[...e.positionals??[]],r=e.flags?{...e.flags}:void 0,o={};if(ek(t)){let t=function(e,t){if("screenshot"===e.command){let s=ea(e,"path",".png");return t[0]?{field:"path",localPath:s,positionalIndex:0,positionalPath:er("screenshot",".png")}:{field:"path",localPath:s,positionalIndex:0,flagPath:er("screenshot",".png")}}if("record"===e.command&&"start"===(t[0]??"").toLowerCase()){let t=ea(e,"outPath",".mp4",1);return{field:"outPath",localPath:t,positionalIndex:1,positionalPath:er("recording",a.extname(t)||".mp4")}}return null}(e,s);t&&(void 0!==t.positionalPath&&(s[t.positionalIndex]=t.positionalPath),void 0!==t.flagPath&&((r??={}).out=t.flagPath),o[t.field]=t.localPath)}if(!ek(t)||"install"!==e.command&&"reinstall"!==e.command||s.length<2)return{positionals:s,flags:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let n=s[1];if(n.startsWith("remote:"))return s[1]=n.slice(7),{positionals:s,flags:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}};let i=a.isAbsolute(n)?n:a.resolve(e.meta?.cwd??process.cwd(),n);return I.existsSync(i)?{positionals:s,flags:r,uploadedArtifactId:await X({localPath:i,baseUrl:t.baseUrl,token:t.token}),...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}:{positionals:s,flags:r,...Object.keys(o).length>0?{clientArtifactPaths:o}:{}}}function ea(e,t,s,r=0){let o=e.positionals?.[r]??e.flags?.out,n=`${"path"===t?"screenshot":"recording"}-${Date.now()}${s}`,i=o&&o.trim().length>0?o:n;return a.isAbsolute(i)?i:a.resolve(e.meta?.cwd??process.cwd(),i)}function er(e,t){let s=t.startsWith(".")?t:`.${t}`;return a.posix.join("/tmp",`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${s}`)}async function eo(e){let t;if(e.remoteBaseUrl){let t={transport:"http",token:e.remoteAuthToken??"",pid:0,baseUrl:e.remoteBaseUrl};if(await ef(t,"http"))return t;throw new A("COMMAND_FAILED","Remote daemon is unavailable",{daemonBaseUrl:e.remoteBaseUrl,hint:"Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc."})}let s=ep(e.paths.infoPath),r=p(),o=function(e,t=u()){try{let s=I.statSync(e),r=a.relative(t,e)||e;return`${r}:${s.size}:${Math.trunc(s.mtimeMs)}`}catch{return"unknown"}}((t=ey()).useSrc?t.srcPath:t.distPath,t.root),n=!!s&&await ef(s,e.transportPreference);if(s&&s.version===r&&s.codeSignature===o&&n)return s;s&&(s.version!==r||s.codeSignature!==o||!n)&&(await ed(s),eg(e.paths.infoPath)),function(e){let t=ec(e);if(!t.hasLock||t.hasInfo)return;let s=eu(e.lockPath);if(!s)return eg(e.lockPath);l(s.pid,s.processStartTime)||eg(e.lockPath)}(e.paths);let i=0;for(let t=1;t<=Q;t+=1){await eh(e);let s=await en(Y,e);if(s)return s;if(await el(e.paths)){i+=1;continue}let a=ec(e.paths);if(!(t<Q))break;if(!a.hasInfo&&!a.hasLock){await ei(150);continue}}let d=ec(e.paths);throw new A("COMMAND_FAILED","Failed to start daemon",{kind:"daemon_startup_failed",infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,startupTimeoutMs:Y,startupAttempts:Q,lockRecoveryCount:i,metadataState:d,hint:function(e,t=E(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.`}(d,e.paths)})}async function en(e,t){let s=Date.now();for(;Date.now()-s<e;){let e=ep(t.paths.infoPath);if(e&&await ef(e,t.transportPreference))return e;await new Promise(e=>setTimeout(e,100))}return null}async function ei(e){await new Promise(t=>setTimeout(t,e))}async function el(e){let t=ec(e);if(!t.hasLock||t.hasInfo)return!1;let s=eu(e.lockPath);return s&&l(s.pid,s.processStartTime)&&await L(s.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:s.processStartTime}),eg(e.lockPath),!0}async function ed(e){await L(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}function ep(e){let t=em(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 eu(e){let t=em(e);return t&&Number.isInteger(t.pid)&&!(t.pid<=0)?t:null}function ec(e){return{hasInfo:I.existsSync(e.infoPath),hasLock:I.existsSync(e.lockPath)}}function em(e){if(!I.existsSync(e))return null;try{return JSON.parse(I.readFileSync(e,"utf8"))}catch{return null}}function eg(e){try{I.existsSync(e)&&I.unlinkSync(e)}catch{}}async function ef(e,a){var r;return"http"===ev(e,a)?await function(e){let a=e.baseUrl?e$(e.baseUrl,"health"):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!a)return Promise.resolve(!1);let r=new URL(a),o="https:"===r.protocol?t:s,n=e.baseUrl?3e3:500;return new Promise(e=>{let t=o.request({protocol:r.protocol,host:r.hostname,port:r.port,path:r.pathname+r.search,method:"GET",timeout:n},t=>{t.resume(),e((t.statusCode??500)<500)});t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{e(!1)}),t.end()})}(e):await ((r=e.port)?new Promise(e=>{let t=k.createConnection({host:"127.0.0.1",port:r},()=>{t.destroy(),e(!0)});t.on("error",()=>{e(!1)})}):Promise.resolve(!1))}async function eh(e){let t=ey(),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};d(process.execPath,s,{env:a})}function ey(){let e=u(),t=a.join(e,"dist","src","daemon.js"),s=a.join(e,"src","daemon.ts"),r=I.existsSync(t),o=I.existsSync(s);if(!r&&!o)throw new A("COMMAND_FAILED","Daemon entry not found",{distPath:t,srcPath:s});return{root:e,distPath:t,srcPath:s,useSrc:process.execArgv.includes("--experimental-strip-types")?o:!r&&o}}async function ew(e,t,s){return"http"===ev(e,s)?await eA(e,t):await eb(e,t)}function ev(e,t){if(e.baseUrl){if("socket"===t)throw new A("COMMAND_FAILED","Remote daemon endpoint only supports HTTP transport",{daemonBaseUrl:e.baseUrl});return"http"}if("http"===t){if(!e.httpPort)throw new A("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");return"http"}if("socket"===t){if(!e.port)throw new A("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 A("COMMAND_FAILED","Daemon metadata has no reachable transport")}async function eb(e,t){let s=e.port;if(!s)throw new A("COMMAND_FAILED","Daemon socket endpoint is unavailable");return new Promise((a,r)=>{let o=k.createConnection({host:"127.0.0.1",port:s},()=>{o.write(`${JSON.stringify(t)}
16
- `)}),n=setTimeout(()=>{o.destroy();let s=eI(),a=eD(e,E(t.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR));h({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:Z,requestId:t.meta?.requestId,command:t.command,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:e.pid,daemonPidForceKilled:a.forcedKill}}),r(new A("COMMAND_FAILED","Daemon request timed out",{timeoutMs:Z,requestId:t.meta?.requestId,hint:"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},Z),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),a(e)}catch(e){clearTimeout(n),r(new A("COMMAND_FAILED","Invalid daemon response",{requestId:t.meta?.requestId,line:l},e instanceof Error?e:void 0))}}),o.on("error",e=>{clearTimeout(n),h({level:"error",phase:"daemon_request_socket_error",data:{requestId:t.meta?.requestId,message:e instanceof Error?e.message:String(e)}}),r(new A("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 eA(e,a){let r=e.baseUrl?new URL(e$(e.baseUrl,"rpc")):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!r)throw new A("COMMAND_FAILED","Daemon HTTP endpoint is unavailable");let n=JSON.stringify({jsonrpc:"2.0",id:a.meta?.requestId??o(),method:"agent_device.command",params:a}),i={"content-type":"application/json","content-length":Buffer.byteLength(n)};return e.baseUrl&&e.token&&(i.authorization=`Bearer ${e.token}`,i["x-agent-device-token"]=e.token),await new Promise((o,l)=>{let d=E(a.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR),p=("https:"===r.protocol?t:s).request({protocol:r.protocol,host:r.hostname,port:r.port,method:"POST",path:r.pathname+r.search,headers:i},t=>{let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{clearTimeout(u);try{let t=JSON.parse(s);if(t.error){let e=t.error.data??{};l(new A(String(e.code??"COMMAND_FAILED"),String(e.message??t.error.message??"Daemon RPC request failed"),{..."object"==typeof e.details&&e.details?e.details:{},hint:"string"==typeof e.hint?e.hint:void 0,diagnosticId:"string"==typeof e.diagnosticId?e.diagnosticId:void 0,logPath:"string"==typeof e.logPath?e.logPath:void 0,requestId:a.meta?.requestId}));return}if(!t.result||"object"!=typeof t.result)return void l(new A("COMMAND_FAILED","Invalid daemon RPC response",{requestId:a.meta?.requestId}));if(e.baseUrl&&t.result.ok)return void eS(e,a,t.result).then(o).catch(l);o(t.result)}catch(e){clearTimeout(u),l(new A("COMMAND_FAILED","Invalid daemon response",{requestId:a.meta?.requestId,line:s},e instanceof Error?e:void 0))}})}),u=setTimeout(()=>{p.destroy();let t=ek(e)?{terminated:0}:eI(),s=ek(e)?{forcedKill:!1}:eD(e,d);h({level:"error",phase:"daemon_request_timeout",data:{timeoutMs:Z,requestId:a.meta?.requestId,command:a.command,timedOutRunnerPidsTerminated:t.terminated,timedOutRunnerCleanupError:t.error,daemonPidReset:ek(e)?void 0:e.pid,daemonPidForceKilled:ek(e)?void 0:s.forcedKill,daemonBaseUrl:e.baseUrl}}),l(new A("COMMAND_FAILED","Daemon request timed out",{timeoutMs:Z,requestId:a.meta?.requestId,hint:ek(e)?"Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.":"Retry with --debug and check daemon diagnostics logs. Timed-out iOS runner xcodebuild processes were terminated when detected."}))},Z);p.on("error",t=>{clearTimeout(u),h({level:"error",phase:"daemon_request_socket_error",data:{requestId:a.meta?.requestId,message:t instanceof Error?t.message:String(t)}}),l(new A("COMMAND_FAILED","Failed to communicate with daemon",{requestId:a.meta?.requestId,hint:ek(e)?"Retry command. If this persists, verify the remote daemon URL, auth token, and remote host reachability.":"Retry command. If this persists, clean stale daemon metadata and start a fresh session."},t))}),p.write(n),p.end()})}function eI(){let e=0;try{for(let t of ee){let s=m("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 eD(e,t){let s=!1;try{l(e.pid,e.processStartTime)&&(process.kill(e.pid,"SIGKILL"),s=!0)}catch{L(e.pid,{termTimeoutMs:3e3,killTimeoutMs:1e3,expectedStartTime:e.processStartTime})}finally{eg(t.infoPath),eg(t.lockPath)}return{forcedKill:s}}function ek(e){return"string"==typeof e.baseUrl&&e.baseUrl.length>0}function e$(e,t){return new URL(t,e.endsWith("/")?e:`${e}/`).toString()}async function eS(e,t,s){let r=Array.isArray(s.data?.artifacts)?s.data.artifacts:[];if(0===r.length||!e.baseUrl)return s;let o=s.data?{...s.data}:{},n=[];for(let s of r){if(!s||"object"!=typeof s||"string"!=typeof s.artifactId){n.push(s);continue}let r=function(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let s=e.fileName?.trim()||`${e.field}-${Date.now()}`;return a.resolve(t.meta?.cwd??process.cwd(),s)}(s,t);await eE({baseUrl:e.baseUrl,token:e.token,artifactId:s.artifactId,destinationPath:r,requestId:t.meta?.requestId}),o[s.field]=r,n.push({...s,localPath:r})}return o.artifacts=n,{ok:!0,data:o}}async function eE(e){var r,o;let n,i=new URL((r=e.baseUrl,o=e.artifactId,n=r.endsWith("/")?r:`${r}/`,new URL(`upload/${encodeURIComponent(o)}`,n).toString())),l="https:"===i.protocol?t:s;await I.promises.mkdir(a.dirname(e.destinationPath),{recursive:!0}),await new Promise((t,s)=>{let a=!1,r=e.timeoutMs??Z,o=r=>{if(!a){if(a=!0,clearTimeout(d),r)return void I.promises.rm(e.destinationPath,{force:!0}).finally(()=>s(r));t()}},n=l.request({protocol:i.protocol,host:i.hostname,port:i.port,method:"GET",path:i.pathname+i.search,headers:e.token?{authorization:`Bearer ${e.token}`,"x-agent-device-token":e.token}:void 0},t=>{if((t.statusCode??500)>=400){let s="";t.setEncoding("utf8"),t.on("data",e=>{s+=e}),t.on("end",()=>{o(new A("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,statusCode:t.statusCode,requestId:e.requestId,body:s}))});return}let s=I.createWriteStream(e.destinationPath);s.on("error",e=>{o(e instanceof Error?e:Error(String(e)))}),t.on("error",e=>{o(e instanceof Error?e:Error(String(e)))}),t.on("aborted",()=>{o(new A("COMMAND_FAILED","Remote artifact download was interrupted",{artifactId:e.artifactId,requestId:e.requestId}))}),s.on("finish",()=>{s.close(()=>o())}),t.pipe(s)}),d=setTimeout(()=>{n.destroy(new A("COMMAND_FAILED","Remote artifact download timed out",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:r}))},r);n.on("error",t=>{t instanceof A?o(t):o(new A("COMMAND_FAILED","Failed to download remote artifact",{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:r},t instanceof Error?t:void 0))}),n.end()})}let eL={sendToDaemon:et};async function ex(t,s=eL){let a=o(),l=t.includes("--debug")||t.includes("--verbose")||t.includes("-v"),d=t.includes("--json"),u=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:u,requestId:a,command:t[0],debug:l},async()=>{var o,u;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=[],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){r?o.push(s):r=W(s);continue}let n=s.startsWith("--"),d=s.startsWith("-")&&s.length>1;if(!n&&!d){r?o.push(s):r=W(s);continue}let[p,u]=n?G(s):[s,void 0],c=M.get(p);if(!c){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let r=R(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 A("INVALID_ARGS",`Unknown flag: ${p}`)}let m=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new A("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 A("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 A("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||J(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&&J(r))throw new A("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 A("INVALID_ARGS",`Invalid ${B(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 A("INVALID_ARGS",`Invalid ${B(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,i.push({key:c.key,token:p})}let d=R(r),p=new Set([...T,...d?.allowedFlags??[]]),u=i.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 A("INVALID_ARGS",e);for(let t of(n.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 A("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:r,positionals:o,flags:a,warnings:n}}(t)}catch(t){h({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=i(t,{diagnosticId:c().diagnosticId,logPath:$({force:!0})??void 0});d?z({success:!1,error:e}):H(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(`${p()}
18
- `),process.exit(0));let g="help"===m.command,f=m.flags.help;if(g||f){g&&m.positionals.length>1&&(H(new A("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=g?m.positionals[0]:m.command;e||(process.stdout.write(`${j}
19
- `),process.exit(0));let t=function(e){let t=R(e);if(!t)return null;let s=U(e,t),a=q(new Set(t.allowedFlags)),r=q(T),o=[];return a.length>0&&o.push(V("Command flags:",a)),o.push(V("Global flags:",r)),`agent-device ${s}
15
+ `)}function T(t,s={}){let a=t.nodes,o=Array.isArray(a)?a:[],r=!!t.truncated,n="string"==typeof t.appName?t.appName:void 0,l="string"==typeof t.appBundleId?t.appBundleId:void 0,p=[];n&&p.push(`Page: ${n}`),l&&p.push(`App: ${l}`);let d=`Snapshot: ${o.length} nodes${r?" (truncated)":""}`,u=p.length>0?`${p.join("\n")}
16
+ `:"";if(0===o.length)return`${u}${d}
17
+ `;if(s.raw){let e=o.map(e=>JSON.stringify(e));return`${u}${d}
18
+ ${e.join("\n")}
19
+ `}if(s.flatten){let t=o.map(t=>e(t,0,!1));return`${u}${d}
20
+ ${t.join("\n")}
21
+ `}let c=i(o).map(e=>e.text);return`${u}${d}
22
+ ${c.join("\n")}
23
+ `}function M(e){return"number"==typeof e&&Number.isFinite(e)?e:0}async function B(e){let t=V[e.command];return!!t&&await t(e)}let V={session:async({positionals:e,flags:t,client:s})=>{if("list"!==(e[0]??"list"))throw new p("INVALID_ARGS","session only supports list");let a={sessions:(await s.sessions.list()).map(W)};return t.json?C({success:!0,data:a}):process.stdout.write(`${JSON.stringify(a,null,2)}
24
+ `),!0},devices:async({flags:e,client:t})=>{let s=await t.devices.list(J(e)),a={devices:s.map(q)};return e.json?C({success:!0,data:a}):process.stdout.write(`${s.map(H).join("\n")}
25
+ `),!0},"ensure-simulator":async({flags:e,client:t})=>{var s;if(!e.device)throw new p("INVALID_ARGS","ensure-simulator requires --device <name>");let a=await t.simulators.ensure({device:e.device,runtime:e.runtime,boot:e.boot,reuseExisting:e.reuseExisting,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet}),i={udid:(s=a).udid,device:s.device,runtime:s.runtime,ios_simulator_device_set:s.iosSimulatorDeviceSet??null,created:s.created,booted:s.booted};if(e.json)C({success:!0,data:i});else{let e=a.created?"Created":"Reused",t=a.booted?" (booted)":"";process.stdout.write(`${e}: ${a.device} ${a.udid}${t}
26
+ `),a.runtime&&process.stdout.write(`Runtime: ${a.runtime}
27
+ `)}return!0},runtime:async({positionals:e,flags:t,client:s})=>{let a=(e[0]??"show").toLowerCase();return"set"===a?(G(await s.runtime.set({platform:t.platform,metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,launchUrl:t.launchUrl}),t),!0):"show"===a&&(G(await s.runtime.show(),t),!0)},install:async({positionals:e,flags:t,client:s})=>{let a=await U("install",e,t,s);return t.json&&C({success:!0,data:z(a)}),!0},reinstall:async({positionals:e,flags:t,client:s})=>{let a=await U("reinstall",e,t,s);return t.json&&C({success:!0,data:z(a)}),!0},open:async({positionals:e,flags:t,client:s})=>{var a;if(!e[0])return!1;let i=await s.apps.open({app:e[0],url:e[1],activity:t.activity,relaunch:t.relaunch,saveScript:t.saveScript,noRecord:t.noRecord,...J(t)});return t.json&&C({success:!0,data:{session:(a=i).session,...a.appName?{appName:a.appName}:{},...a.appBundleId?{appBundleId:a.appBundleId}:{},...a.startup?{startup:a.startup}:{},...a.runtime?{runtime:a.runtime}:{},...a.device?{platform:a.device.platform,target:a.device.target,device:a.device.name,id:a.device.id}:{},...a.device?.platform==="ios"?{device_udid:a.device.ios?.udid??a.device.id,ios_simulator_device_set:a.device.ios?.simulatorSetPath??null}:{},...a.device?.platform==="android"?{serial:a.device.android?.serial??a.device.id}:{}}}),!0},close:async({positionals:e,flags:t,client:s})=>{var a;let i=e[0]?await s.apps.close({app:e[0],shutdown:t.shutdown}):await s.sessions.close({shutdown:t.shutdown});return t.json&&C({success:!0,data:{session:(a=i).session,...a.shutdown?{shutdown:a.shutdown}:{}}}),!0},snapshot:async({flags:e,client:t})=>{var s;let a={nodes:(s=await t.capture.snapshot({...J(e),interactiveOnly:e.snapshotInteractiveOnly,compact:e.snapshotCompact,depth:e.snapshotDepth,scope:e.snapshotScope,raw:e.snapshotRaw})).nodes,truncated:s.truncated,...s.appName?{appName:s.appName}:{},...s.appBundleId?{appBundleId:s.appBundleId}:{}};return e.json?C({success:!0,data:a}):process.stdout.write(T(a,{raw:e.snapshotRaw,flatten:e.snapshotInteractiveOnly})),!0},screenshot:async({positionals:e,flags:t,client:s})=>{let a=await s.capture.screenshot({path:e[0]??t.out}),i={path:a.path};return t.json?C({success:!0,data:i}):process.stdout.write(`${a.path}
28
+ `),!0}};async function U(e,t,s,a){let i=t[0],o=t[1];if(!i||!o)throw new p("INVALID_ARGS",`${e} requires: ${e} <app> <path-to-app-binary>`);let r={app:i,appPath:o,...J(s)};return"install"===e?await a.apps.install(r):await a.apps.reinstall(r)}function G(e,t){var s;let a={session:(s=e).session,configured:s.configured,...s.cleared?{cleared:!0}:{},...s.runtime?{runtime:s.runtime}:{}};t.json?C({success:!0,data:a}):e.configured?process.stdout.write(`${JSON.stringify(e.runtime??{},null,2)}
29
+ `):process.stdout.write("No runtime hints configured\n")}function J(e){return{platform:e.platform,target:e.target,device:e.device,udid:e.udid,serial:e.serial,iosSimulatorDeviceSet:e.iosSimulatorDeviceSet,androidDeviceAllowlist:e.androidDeviceAllowlist}}function W(e){return{name:e.name,platform:e.device.platform,target:e.device.target,device:e.device.name,id:e.device.id,createdAt:e.createdAt,..."ios"===e.device.platform&&{device_udid:e.device.ios?.udid??e.device.id,ios_simulator_device_set:e.device.ios?.simulatorSetPath??null}}}function q(e){return{platform:e.platform,id:e.id,name:e.name,kind:e.kind,target:e.target,..."boolean"==typeof e.booted?{booted:e.booted}:{}}}function H(e){let t=e.kind?` ${e.kind}`:"",s=e.target?` target=${e.target}`:"",a="boolean"==typeof e.booted?` booted=${e.booted}`:"";return`${e.name} (${e.platform}${t}${s})${a}`}function z(e){return{app:e.app,appPath:e.appPath,platform:e.platform,...e.appId?{appId:e.appId}:{},...e.bundleId?{bundleId:e.bundleId}:{},...e.package?{package:e.package}:{}}}let K={sendToDaemon:v};async function X(e,t=K){let i=o(),l=e.includes("--debug")||e.includes("--verbose")||e.includes("-v"),v=e.includes("--json"),w=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}(e)??process.env.AGENT_DEVICE_SESSION??"default";await c({session:w,requestId:i,command:e[0],debug:l},async()=>{var o,c;let w;try{w=function(e,t){let s=(void 0)??function(e){if(!e)return!1;let t=e.trim().toLowerCase();return"1"===t||"true"===t||"yes"===t||"on"===t}(process.env.AGENT_DEVICE_STRICT_FLAGS),a={json:!1,help:!1,version:!1},i=null,o=[],r=[],n=[],l=!0;for(let t=0;t<e.length;t+=1){let s=e[t];if(l&&"--"===s){l=!1;continue}if(!l){i?o.push(s):i=E(s);continue}let r=s.startsWith("--"),d=s.startsWith("-")&&s.length>1;if(!r&&!d){i?o.push(s):i=E(s);continue}let[u,c]=r?_(s):[s,void 0],g=S.get(u);if(!g){if(function(e,t,s){var a;if(a=s,!/^-\d+(\.\d+)?$/.test(a)||!e)return!1;let i=x(e);return!i||!!i.allowsExtraPositionals||0!==i.positionalArgs.length&&(t.length<i.positionalArgs.length||i.positionalArgs.some(e=>e.includes("?")))}(i,o,s)){i?o.push(s):i=s;continue}throw new p("INVALID_ARGS",`Unknown flag: ${u}`)}let m=function(e,t,s,a){if(void 0!==e.setValue){if(void 0!==s)throw new p("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 p("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 p("INVALID_ARGS",`Flag ${t} requires a non-empty value when provided.`);return{value:s,consumeNext:!1}}return void 0===a||j(a)||!function(e){let t=e.trim();return!(!t||/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(t))&&!!(t.startsWith("./")||t.startsWith("../")||t.startsWith("~/")||t.startsWith("/")||t.includes("/")||t.includes("\\"))}(a)?{value:!0,consumeNext:!1}:{value:a,consumeNext:!0}}let i=s??a;if(void 0===i||void 0===s&&j(i))throw new p("INVALID_ARGS",`Flag ${t} requires a value.`);if("string"===e.type)return{value:i,consumeNext:void 0===s};if("enum"===e.type){if(!e.enumValues?.includes(i))throw new p("INVALID_ARGS",`Invalid ${R(t)}: ${i}`);return{value:i,consumeNext:void 0===s}}let o=Number(i);if(!Number.isFinite(o)||"number"==typeof e.min&&o<e.min||"number"==typeof e.max&&o>e.max)throw new p("INVALID_ARGS",`Invalid ${R(t)}: ${i}`);return{value:Math.floor(o),consumeNext:void 0===s}}(g,u,c,e[t+1]);m.consumeNext&&(t+=1),a[g.key]=m.value,n.push({key:g.key,token:u})}let d=x(i),u=new Set([...k,...d?.allowedFlags??[]]),c=n.filter(e=>!u.has(e.key));if(c.length>0){var g,m;let e=(g=i,m=c.map(e=>e.token),g?1===m.length?`Flag ${m[0]} is not supported for command ${g}.`:`Flags ${m.join(", ")} are not supported for command ${g}.`: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 p("INVALID_ARGS",e);for(let t of(r.push(`${e} Enable AGENT_DEVICE_STRICT_FLAGS=1 to fail fast.`),c))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"===i&&1!=+!!a.steps+ +!!a.stepsFile)throw new p("INVALID_ARGS","batch requires exactly one step source: --steps or --steps-file.");return{command:i,positionals:o,flags:a,warnings:r}}(e)}catch(t){h({level:"error",phase:"cli_parse_failed",data:{error:t instanceof Error?t.message:String(t)}});let e=n(t,{diagnosticId:g().diagnosticId,logPath:m({force:!0})??void 0});v?C({success:!1,error:e}):P(e,{showDetails:l}),process.exit(1);return}for(let e of w.warnings)process.stderr.write(`Warning: ${e}
30
+ `);w.flags.version&&(process.stdout.write(`${d()}
31
+ `),process.exit(0));let b="help"===w.command,$=w.flags.help;if(b||$){b&&w.positionals.length>1&&(P(new p("INVALID_ARGS","help accepts at most one command.")),process.exit(1));let e=b?w.positionals[0]:w.command;e||(process.stdout.write(`${F}
32
+ `),process.exit(0));let t=function(e){let t=x(e);if(!t)return null;let s=L(e,t),a=O(new Set(t.allowedFlags)),i=O(k),o=[];return a.length>0&&o.push(N("Command flags:",a)),o.push(N("Global flags:",i)),`agent-device ${s}
20
33
 
21
34
  ${t.description}
22
35
 
@@ -24,57 +37,48 @@ Usage:
24
37
  agent-device ${s}
25
38
 
26
39
  ${o.join("\n\n")}
27
- `}(W(e));t&&(process.stdout.write(t),process.exit(0)),H(new A("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${j}
28
- `),process.exit(1)}m.command||(process.stdout.write(`${j}
29
- `),process.exit(1));let{command:y,positionals:v,flags:b}=m,D=function(e){let{json:t,help:s,version:a,...r}=e;return r}(b),k=E(b.stateDir??process.env.AGENT_DEVICE_STATE_DIR),S=b.session??process.env.AGENT_DEVICE_SESSION??"default",L=b.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL,_=!b.verbose||b.json||L?null:function(e){try{let t=0,s=!1,a=setInterval(()=>{if(!s&&I.existsSync(e))try{let s=I.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let a=I.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);I.readSync(a,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{I.closeSync(a)}}catch{}},200);return()=>{s=!0,clearInterval(a)}}catch{return null}}(k.logPath),O=async e=>await s.sendToDaemon({session:S,command:e.command,positionals:e.positionals,flags:e.flags,meta:{requestId:a,debug:!!b.verbose,cwd:process.cwd(),tenantId:b.tenant,runId:b.runId,leaseId:b.leaseId,sessionIsolation:b.sessionIsolation}});try{if("batch"===y){let e,t,s;if(v.length>0)throw new A("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=I.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new A("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return n(t)}(b),r={...D,batchSteps:a};delete r.steps,delete r.stepsFile;let i=await O({command:"batch",positionals:v,flags:r});if(!i.ok)throw new A(i.error.code,i.error.message,{...i.error.details??{},hint:i.error.hint,diagnosticId:i.error.diagnosticId,logPath:i.error.logPath});b.json?z({success:!0,data:i.data??{}}):(o=i.data??{},e="number"==typeof o.total?o.total:0,t="number"==typeof o.executed?o.executed:0,s="number"==typeof o.totalDurationMs?o.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${t}/${e} steps${void 0!==s?` in ${s}ms`:""}
30
- `)),_&&_();return}if("session"===y){let e=v[0]??"list";if("list"!==e)throw new A("INVALID_ARGS","session only supports list");let t=await O({command:"session_list",positionals:[],flags:D});if(!t.ok)throw new A(t.error.code,t.error.message,{...t.error.details??{},hint:t.error.hint,diagnosticId:t.error.diagnosticId,logPath:t.error.logPath});b.json?z({success:!0,data:t.data??{}}):process.stdout.write(`${JSON.stringify(t.data??{},null,2)}
31
- `),_&&_();return}let t=await O({command:y,positionals:v,flags:D});if(t.ok){if(b.json){z({success:!0,data:t.data??{}}),_&&_();return}if("snapshot"===y){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
- ${e.join("\n")}
35
- `}if(t.flatten){let e=a.map(e=>x(e,0,!1));return`${p}${d}
36
- ${e.join("\n")}
37
- `}let u=r(a).map(e=>e.text);return`${p}${d}
38
- ${u.join("\n")}
39
- `}(t.data??{},{raw:b.snapshotRaw,flatten:b.snapshotInteractiveOnly})),_&&_();return}if("diff"===y&&"snapshot"===v[0]){process.stdout.write(function(t){var s,a,r,o;let n,i=!0===t.baselineInitialized,l=t.summary??{},d=K(l.additions),p=K(l.removals),u=K(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 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 n="string"==typeof t.text?t.text:"";if("added"===t.kind){let t=n.startsWith(" ")?`+${n}`:`+ ${n}`;return c?(s=t,a="green",e(a,s)):t}if("removed"===t.kind){let t=n.startsWith(" ")?`-${n}`:`- ${n}`;return c?(r=t,e("red",r)):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),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??{})),_&&_();return}if("get"===y){let e=v[0];if("text"===e){let e=t.data?.text??"";process.stdout.write(`${e}
44
- `),_&&_();return}if("attrs"===e){let e=t.data?.node??{};process.stdout.write(`${JSON.stringify(e,null,2)}
45
- `),_&&_();return}}if("find"===y){let e=t.data;if("string"==typeof e?.text){process.stdout.write(`${e.text}
46
- `),_&&_();return}if("boolean"==typeof e?.found){process.stdout.write(`Found: ${e.found}
47
- `),_&&_();return}if(e?.node){process.stdout.write(`${JSON.stringify(e.node,null,2)}
48
- `),_&&_();return}}if("is"===y){let e=t.data?.predicate??"assertion";process.stdout.write(`Passed: is ${e}
49
- `),_&&_();return}if("boot"===y){let e=t.data?.platform??"unknown",s=t.data?.device??t.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${e})
50
- `),_&&_();return}if("ensure-simulator"===y){let e=t.data,s="string"==typeof e?.udid?e.udid:"unknown",a="string"==typeof e?.device?e.device:"unknown",r="string"==typeof e?.runtime?e.runtime:"",o=e?.created===!0,n=e?.booted===!0;process.stdout.write(`${o?"Created":"Reused"}: ${a} ${s}${n?" (booted)":""}
51
- `),r&&process.stdout.write(`Runtime: ${r}
52
- `),_&&_();return}if("runtime"===y){let e=t.data,s=e?.cleared===!0,a=e?.configured===!0;if(s){process.stdout.write("Runtime hints cleared\n"),_&&_();return}if(!a){process.stdout.write("No runtime hints configured\n"),_&&_();return}process.stdout.write(`${JSON.stringify(e?.runtime??{},null,2)}
53
- `),_&&_();return}if("screenshot"===y){let e="string"==typeof t.data?.path?t.data.path:"";e&&process.stdout.write(`${e}
54
- `),_&&_();return}if("record"===y){let e=t.data,s="string"==typeof e?.outPath?e.outPath:"";s&&process.stdout.write(`${s}
55
- `),_&&_();return}if("logs"===y){let e=t.data,s="string"==typeof e?.path?e.path:"";if(s){process.stdout.write(`${s}
56
- `);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,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(!b.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}
57
- `)}if(!b.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}
58
- `)}if(e?.hint&&!b.json&&process.stderr.write(`${e.hint}
59
- `),Array.isArray(e?.notes)&&!b.json)for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
60
- `)}_&&_();return}if("clipboard"===y){let e=t.data,s=(v[0]??("string"==typeof e?.action?e.action:"")).toLowerCase();if("read"===s){let t="string"==typeof e?.text?e.text:"";process.stdout.write(`${t}
61
- `),_&&_();return}if("write"===s){process.stdout.write("Clipboard updated\n"),_&&_();return}}if("network"===y){let e=t.data,s="string"==typeof e?.path?e.path:"";s&&process.stdout.write(`${s}
62
- `);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}
40
+ `}(E(e));t&&(process.stdout.write(t),process.exit(0)),P(new p("INVALID_ARGS",`Unknown command: ${e}`)),process.stdout.write(`${F}
41
+ `),process.exit(1)}w.command||(process.stdout.write(`${F}
42
+ `),process.exit(1));let{command:A,positionals:D,flags:I}=w,V=function(e){let{json:t,help:s,version:a,...i}=e;return i}(I),U=f(I.stateDir??process.env.AGENT_DEVICE_STATE_DIR),G=I.session??process.env.AGENT_DEVICE_SESSION??"default",J=I.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL,W=!I.verbose||I.json||J?null:function(e){try{let t=0,s=!1,a=setInterval(()=>{if(!s&&u.existsSync(e))try{let s=u.statSync(e);if(s.size<t&&(t=0),s.size<=t)return;let a=u.openSync(e,"r");try{let e=Buffer.alloc(s.size-t);u.readSync(a,e,0,e.length,t),t=s.size,e.length>0&&process.stdout.write(e.toString("utf8"))}finally{u.closeSync(a)}}catch{}},200);return()=>{s=!0,clearInterval(a)}}catch{return null}}(U.logPath),q=y({session:G,requestId:i,stateDir:I.stateDir,daemonBaseUrl:I.daemonBaseUrl,daemonAuthToken:I.daemonAuthToken,daemonTransport:I.daemonTransport,daemonServerMode:I.daemonServerMode,tenant:I.tenant,sessionIsolation:I.sessionIsolation,runId:I.runId,leaseId:I.leaseId,cwd:process.cwd(),debug:!!I.verbose},{transport:t.sendToDaemon}),H=async e=>await t.sendToDaemon({session:G,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"===A){let e,t,s;if(D.length>0)throw new p("INVALID_ARGS","batch does not accept positional arguments.");let i=function(e){let t="";if(e.steps)t=e.steps;else if(e.stepsFile)try{t=u.readFileSync(e.stepsFile,"utf8")}catch(s){let t=s instanceof Error?s.message:String(s);throw new p("INVALID_ARGS",`Failed to read --steps-file ${e.stepsFile}: ${t}`)}return a(t)}(I),r={...V,batchSteps:i};delete r.steps,delete r.stepsFile;let n=await H({command:"batch",positionals:D,flags:r});if(!n.ok)throw new p(n.error.code,n.error.message,{...n.error.details??{},hint:n.error.hint,diagnosticId:n.error.diagnosticId,logPath:n.error.logPath});I.json?C({success:!0,data:n.data??{}}):(o=n.data??{},e="number"==typeof o.total?o.total:0,t="number"==typeof o.executed?o.executed:0,s="number"==typeof o.totalDurationMs?o.totalDurationMs:void 0,process.stdout.write(`Batch completed: ${t}/${e} steps${void 0!==s?` in ${s}ms`:""}
43
+ `)),W&&W();return}if(await B({command:A,positionals:D,flags:I,client:q})){W&&W();return}let e=await H({command:A,positionals:D,flags:V});if(e.ok){if(I.json){C({success:!0,data:e.data??{}}),W&&W();return}if("snapshot"===A){process.stdout.write(T(e.data??{},{raw:I.snapshotRaw,flatten:I.snapshotInteractiveOnly})),W&&W();return}if("diff"===A&&"snapshot"===D[0]){process.stdout.write(function(e){var t,a,i,o;let r,n=!0===e.baselineInitialized,l=e.summary??{},p=M(l.additions),d=M(l.removals),u=M(l.unchanged),c=(r=process.env.FORCE_COLOR,"string"==typeof r?"0"!==r:"string"!=typeof process.env.NO_COLOR&&!!process.stdout.isTTY);if(n)return`Baseline initialized (${u} lines).
44
+ `;let g=(function(e,t){if(0===e.length)return e;let s=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>"added"===e.kind||"removed"===e.kind).map(e=>e.index);if(0===s.length)return e;let a=Array(e.length).fill(!1);for(let t of s){let s=Math.max(0,t-1),i=Math.min(e.length-1,t+1);for(let e=s;e<=i;e+=1)a[e]=!0}return e.filter((e,t)=>a[t])})(Array.isArray(e.lines)?e.lines:[],1).map(e=>{var t,a,i,o;let r="string"==typeof e.text?e.text:"";if("added"===e.kind){let e=r.startsWith(" ")?`+${r}`:`+ ${r}`;return c?(t=e,a="green",s(a,t)):e}if("removed"===e.kind){let e=r.startsWith(" ")?`-${r}`:`- ${r}`;return c?(i=e,s("red",i)):e}return c?(o=r,s("dim",o)):r}),m=g.length>0?`${g.join("\n")}
45
+ `:"";if(!c)return`${m}${p} additions, ${d} removals, ${u} unchanged
46
+ `;let f=`${(t=String(p),a="green",s(a,t))} additions, ${(i=String(d),s("red",i))} removals, ${(o=String(u),s("dim",o))} unchanged`;return`${m}${f}
47
+ `}(e.data??{})),W&&W();return}if("get"===A){let t=D[0];if("text"===t){let t=e.data?.text??"";process.stdout.write(`${t}
48
+ `),W&&W();return}if("attrs"===t){let t=e.data?.node??{};process.stdout.write(`${JSON.stringify(t,null,2)}
49
+ `),W&&W();return}}if("find"===A){let t=e.data;if("string"==typeof t?.text){process.stdout.write(`${t.text}
50
+ `),W&&W();return}if("boolean"==typeof t?.found){process.stdout.write(`Found: ${t.found}
51
+ `),W&&W();return}if(t?.node){process.stdout.write(`${JSON.stringify(t.node,null,2)}
52
+ `),W&&W();return}}if("is"===A){let t=e.data?.predicate??"assertion";process.stdout.write(`Passed: is ${t}
53
+ `),W&&W();return}if("boot"===A){let t=e.data?.platform??"unknown",s=e.data?.device??e.data?.id??"unknown";process.stdout.write(`Boot ready: ${s} (${t})
54
+ `),W&&W();return}if("ensure-simulator"===A){let t=e.data,s="string"==typeof t?.udid?t.udid:"unknown",a="string"==typeof t?.device?t.device:"unknown",i="string"==typeof t?.runtime?t.runtime:"",o=t?.created===!0,r=t?.booted===!0;process.stdout.write(`${o?"Created":"Reused"}: ${a} ${s}${r?" (booted)":""}
55
+ `),i&&process.stdout.write(`Runtime: ${i}
56
+ `),W&&W();return}if("runtime"===A){let t=e.data,s=t?.cleared===!0,a=t?.configured===!0;if(s){process.stdout.write("Runtime hints cleared\n"),W&&W();return}if(!a){process.stdout.write("No runtime hints configured\n"),W&&W();return}process.stdout.write(`${JSON.stringify(t?.runtime??{},null,2)}
57
+ `),W&&W();return}if("screenshot"===A){let t="string"==typeof e.data?.path?e.data.path:"";t&&process.stdout.write(`${t}
58
+ `),W&&W();return}if("record"===A){let t=e.data,s="string"==typeof t?.outPath?t.outPath:"";s&&process.stdout.write(`${s}
59
+ `),W&&W();return}if("logs"===A){let t=e.data,s="string"==typeof t?.path?t.path:"";if(s){process.stdout.write(`${s}
60
+ `);let e="boolean"==typeof t?.active?t.active:void 0,a="string"==typeof t?.state?t.state:void 0,i="string"==typeof t?.backend?t.backend:void 0,o="number"==typeof t?.sizeBytes?t.sizeBytes:void 0,r=t?.started===!0,n=t?.stopped===!0,l=t?.marked===!0,p=t?.cleared===!0,d=t?.restarted===!0,u="number"==typeof t?.removedRotatedFiles?t.removedRotatedFiles:void 0;if(!I.json&&(void 0!==e||a||i||void 0!==o)){let t=[void 0!==e?`active=${e}`:"",a?`state=${a}`:"",i?`backend=${i}`:"",void 0!==o?`sizeBytes=${o}`:""].filter(Boolean).join(" ");t&&process.stderr.write(`${t}
61
+ `)}if(!I.json&&(r||n||l||p||d||void 0!==u)){let e=[r?"started=true":"",n?"stopped=true":"",l?"marked=true":"",p?"cleared=true":"",d?"restarted=true":"",void 0!==u?`removedRotatedFiles=${u}`:""].filter(Boolean).join(" ");e&&process.stderr.write(`${e}
62
+ `)}if(t?.hint&&!I.json&&process.stderr.write(`${t.hint}
63
+ `),Array.isArray(t?.notes)&&!I.json)for(let e of t.notes)"string"==typeof e&&e.length>0&&process.stderr.write(`${e}
64
+ `)}W&&W();return}if("clipboard"===A){let t=e.data,s=(D[0]??("string"==typeof t?.action?t.action:"")).toLowerCase();if("read"===s){let e="string"==typeof t?.text?t.text:"";process.stdout.write(`${e}
65
+ `),W&&W();return}if("write"===s){process.stdout.write("Clipboard updated\n"),W&&W();return}}if("network"===A){let t=e.data,s="string"==typeof t?.path?t.path:"";s&&process.stdout.write(`${s}
66
+ `);let a=Array.isArray(t?.entries)?t.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}`:"",i="string"==typeof e.timestamp?`${e.timestamp} `:"";process.stdout.write(`${i}${t} ${s}${a}
63
67
  `),"string"==typeof e.headers&&process.stdout.write(` headers: ${e.headers}
64
68
  `),"string"==typeof e.requestBody&&process.stdout.write(` request: ${e.requestBody}
65
69
  `),"string"==typeof e.responseBody&&process.stdout.write(` response: ${e.responseBody}
66
- `)}let r="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!==r?`active=${r}`:"",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}
67
- `),Array.isArray(e?.notes))for(let t of e.notes)"string"==typeof t&&t.length>0&&process.stderr.write(`${t}
68
- `);_&&_();return}if("click"===y||"press"===y){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})
69
- `),_&&_();return}if(t.data&&"object"==typeof t.data){let e=t.data;if("devices"===y){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")}
70
- `),_&&_();return}if("apps"===y){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")}
71
- `),_&&_();return}if("appstate"===y){let t=e?.platform,s=e?.appBundleId,a=e?.appName,r=e?.source,o=e?.package,n=e?.activity;if("ios"===t){process.stdout.write(`Foreground app: ${a??s??"unknown"}
70
+ `)}let i="boolean"==typeof t?.active?t.active:void 0,o="string"==typeof t?.state?t.state:void 0,r="string"==typeof t?.backend?t.backend:void 0,n="number"==typeof t?.scannedLines?t.scannedLines:void 0,l="number"==typeof t?.matchedLines?t.matchedLines:void 0,p="string"==typeof t?.include?t.include:void 0,d=[void 0!==i?`active=${i}`:"",o?`state=${o}`:"",r?`backend=${r}`:"",p?`include=${p}`:"",void 0!==n?`scannedLines=${n}`:"",void 0!==l?`matchedLines=${l}`:""].filter(Boolean).join(" ");if(d&&process.stderr.write(`${d}
71
+ `),Array.isArray(t?.notes))for(let e of t.notes)"string"==typeof e&&e.length>0&&process.stderr.write(`${e}
72
+ `);W&&W();return}if("click"===A||"press"===A){let t=e.data?.ref??"",s=e.data?.x,a=e.data?.y;t&&"number"==typeof s&&"number"==typeof a&&process.stdout.write(`Tapped @${t} (${s}, ${a})
73
+ `),W&&W();return}if(e.data&&"object"==typeof e.data){let t=e.data;if("devices"===A){let e=(Array.isArray(t.devices)?t.devices:[]).map(e=>{let t=e?.name??e?.id??"unknown",s=e?.platform??"unknown",a=e?.kind?` ${e.kind}`:"",i=e?.target?` target=${e.target}`:"",o="boolean"==typeof e?.booted?` booted=${e.booted}`:"";return`${t} (${s}${a}${i})${o}`});process.stdout.write(`${e.join("\n")}
74
+ `),W&&W();return}if("apps"===A){let e=(Array.isArray(t.apps)?t.apps:[]).map(e=>{if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e.bundleId??e.package,s=e.name??e.label;return s&&t?`${s} (${t})`:t?String(t):JSON.stringify(e)}return String(e)});process.stdout.write(`${e.join("\n")}
75
+ `),W&&W();return}if("appstate"===A){let e=t?.platform,s=t?.appBundleId,a=t?.appName,i=t?.source,o=t?.package,r=t?.activity;if("ios"===e){process.stdout.write(`Foreground app: ${a??s??"unknown"}
72
76
  `),s&&process.stdout.write(`Bundle: ${s}
73
- `),r&&process.stdout.write(`Source: ${r}
74
- `),_&&_();return}if("android"===t){process.stdout.write(`Foreground app: ${o??"unknown"}
75
- `),n&&process.stdout.write(`Activity: ${n}
76
- `),_&&_();return}}if("perf"===y){process.stdout.write(`${JSON.stringify(e,null,2)}
77
- `),_&&_();return}}_&&_();return}throw new A(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=w(s),t=i(e,{diagnosticId:c().diagnosticId,logPath:$({force:!0})??void 0});if("close"===y&&"COMMAND_FAILED"===(u=e).code&&(u.details?.kind==="daemon_startup_failed"||u.message.toLowerCase().includes("failed to start daemon")&&("string"==typeof u.details?.infoPath||"string"==typeof u.details?.lockPath))){b.json&&z({success:!0,data:{closed:"session",source:"no-daemon"}}),_&&_();return}if(b.json)z({success:!1,error:t});else if(H(t,{showDetails:b.verbose}),b.verbose)try{let e=k.logPath;if(I.existsSync(e)){let t=I.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
77
+ `),i&&process.stdout.write(`Source: ${i}
78
+ `),W&&W();return}if("android"===e){process.stdout.write(`Foreground app: ${o??"unknown"}
79
+ `),r&&process.stdout.write(`Activity: ${r}
80
+ `),W&&W();return}}if("perf"===A){process.stdout.write(`${JSON.stringify(t,null,2)}
81
+ `),W&&W();return}}W&&W();return}throw new p(e.error.code,e.error.message,{...e.error.details??{},hint:e.error.hint,diagnosticId:e.error.diagnosticId,logPath:e.error.logPath})}catch(s){let e=r(s),t=n(e,{diagnosticId:g().diagnosticId,logPath:m({force:!0})??void 0});if("close"===A&&"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&&C({success:!0,data:{closed:"session",source:"no-daemon"}}),W&&W();return}if(I.json)C({success:!1,error:t});else if(P(t,{showDetails:I.verbose}),I.verbose)try{let e=U.logPath;if(u.existsSync(e)){let t=u.readFileSync(e,"utf8").split("\n"),s=t.slice(Math.max(0,t.length-200)).join("\n");s.trim().length>0&&process.stderr.write(`
78
82
  [daemon log]
79
83
  ${s}
80
- `)}}catch{}_&&_(),process.exit(1)}})}b(process.argv[1]??"").href===import.meta.url&&ex(process.argv.slice(2)).catch(e=>{H(i(w(e)),{showDetails:!0}),process.exit(1)}),ex(process.argv.slice(2));
84
+ `)}}catch{}W&&W(),process.exit(1)}})}l(process.argv[1]??"").href===import.meta.url&&X(process.argv.slice(2)).catch(e=>{P(n(r(e)),{showDetails:!0}),process.exit(1)}),X(process.argv.slice(2));
@@ -0,0 +1,8 @@
1
+ import type { CliFlags } from './utils/command-schema.ts';
2
+ import type { AgentDeviceClient } from './client.ts';
3
+ export declare function tryRunClientBackedCommand(params: {
4
+ command: string;
5
+ positionals: string[];
6
+ flags: CliFlags;
7
+ client: AgentDeviceClient;
8
+ }): Promise<boolean>;
@@ -0,0 +1,6 @@
1
+ import { sendToDaemon } from './daemon-client.ts';
2
+ type CliDeps = {
3
+ sendToDaemon: typeof sendToDaemon;
4
+ };
5
+ export declare function runCli(argv: string[], deps?: CliDeps): Promise<void>;
6
+ export {};