agent-device 0.18.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.2.apk → agent-device-android-multitouch-helper-0.19.0.apk} +0 -0
  2. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.19.0.apk.sha256 +1 -0
  3. package/android-multitouch-helper/dist/{agent-device-android-multitouch-helper-0.18.2.manifest.json → agent-device-android-multitouch-helper-0.19.0.manifest.json} +4 -4
  4. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.2.apk → agent-device-android-snapshot-helper-0.19.0.apk} +0 -0
  5. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.19.0.apk.sha256 +1 -0
  6. package/android-snapshot-helper/dist/{agent-device-android-snapshot-helper-0.18.2.manifest.json → agent-device-android-snapshot-helper-0.19.0.manifest.json} +6 -6
  7. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +28 -0
  8. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +9 -120
  9. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +132 -66
  10. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +155 -0
  11. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +67 -0
  12. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +20 -74
  13. package/dist/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +64 -0
  14. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +0 -177
  15. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +81 -48
  16. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +102 -129
  17. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +208 -46
  18. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +82 -11
  19. package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +72 -0
  20. package/dist/src/agent-browser-tool.js +1 -0
  21. package/dist/src/android-adb.d.ts +64 -234
  22. package/dist/src/android-adb.js +1 -1
  23. package/dist/src/android.js +1 -5
  24. package/dist/src/app-lifecycle.js +7 -0
  25. package/dist/src/apple-runner-options.js +1 -0
  26. package/dist/src/apps.js +5 -11
  27. package/dist/src/artifacts.d.ts +4 -3
  28. package/dist/src/artifacts.js +1 -1
  29. package/dist/src/audio-probe.js +1 -1
  30. package/dist/src/batch.d.ts +2 -177
  31. package/dist/src/batch.js +1 -1
  32. package/dist/src/cli-help.js +64 -38
  33. package/dist/src/cli-output.js +1 -1
  34. package/dist/src/cli-runner.js +2 -0
  35. package/dist/src/cli.js +12 -41
  36. package/dist/src/client-metro-companion.js +1 -0
  37. package/dist/src/client.js +3 -0
  38. package/dist/src/command-metadata.js +1 -0
  39. package/dist/src/command-schema.js +22 -0
  40. package/dist/src/command-surface.js +1 -1
  41. package/dist/src/contracts.d.ts +2 -213
  42. package/dist/src/contracts.js +1 -1
  43. package/dist/src/debug-symbols.js +5 -3
  44. package/dist/src/device-input-state.js +2 -0
  45. package/dist/src/device-rotation.js +14 -0
  46. package/dist/src/devices.js +1 -1
  47. package/dist/src/devices2.js +1 -0
  48. package/dist/src/devices3.js +1 -0
  49. package/dist/src/find.js +1 -1
  50. package/dist/src/finders.d.ts +2 -81
  51. package/dist/src/finders.js +1 -1
  52. package/dist/src/generic.js +1 -1
  53. package/dist/src/handler-utils.js +1 -1
  54. package/dist/src/helper.js +2 -0
  55. package/dist/src/host-process.js +2 -0
  56. package/dist/src/index.d.ts +1265 -1768
  57. package/dist/src/index.js +1 -1
  58. package/dist/src/input-actions.js +3 -1
  59. package/dist/src/input-actions2.js +1 -0
  60. package/dist/src/install-source.d.ts +13 -14
  61. package/dist/src/install-source.js +1 -1
  62. package/dist/src/install-source2.js +1 -0
  63. package/dist/src/interaction-snapshot.js +1 -0
  64. package/dist/src/interaction.js +1 -1
  65. package/dist/src/interactor.js +2 -1
  66. package/dist/src/internal/bin.d.ts +1 -1
  67. package/dist/src/internal/bin.js +2 -5
  68. package/dist/src/internal/companion-tunnel.d.ts +1 -1
  69. package/dist/src/internal/companion-tunnel.js +1 -1
  70. package/dist/src/internal/daemon.d.ts +1 -1
  71. package/dist/src/internal/daemon.js +16 -1
  72. package/dist/src/internal/png-worker.d.ts +29 -26
  73. package/dist/src/internal/png-worker.js +1 -1
  74. package/dist/src/internal/update-check-entry.d.ts +1 -1
  75. package/dist/src/internal/update-check-entry.js +1 -1
  76. package/dist/src/io.d.ts +2 -85
  77. package/dist/src/io.js +1 -1
  78. package/dist/src/lease.js +1 -1
  79. package/dist/src/linux.js +1 -1
  80. package/dist/src/logcat.js +6 -0
  81. package/dist/src/manifest.js +1 -0
  82. package/dist/src/metro.d.ts +70 -113
  83. package/dist/src/metro.js +1 -1
  84. package/dist/src/metro2.js +1 -0
  85. package/dist/src/notifications.js +1 -1
  86. package/dist/src/output-path.js +1 -0
  87. package/dist/src/path-resolution.js +1 -0
  88. package/dist/src/png-worker-contract.js +1 -0
  89. package/dist/src/points.js +4 -0
  90. package/dist/src/project-runtime.js +1 -0
  91. package/dist/src/provider.js +1 -1
  92. package/dist/src/providers.js +1 -0
  93. package/dist/src/react-native.js +1 -1
  94. package/dist/src/record-trace-recording.js +2 -5
  95. package/dist/src/record-trace.js +1 -1
  96. package/dist/src/recording-provider.js +1 -1
  97. package/dist/src/registry.js +37 -0
  98. package/dist/src/remote-config.d.ts +2 -83
  99. package/dist/src/reporting.js +9 -0
  100. package/dist/src/rolldown-runtime.js +1 -0
  101. package/dist/src/runner-client.js +1 -0
  102. package/dist/src/runner-provider.js +1 -0
  103. package/dist/src/runner-sequence.js +1 -1
  104. package/dist/src/runtime-transport.js +1 -0
  105. package/dist/src/runtime.js +3 -0
  106. package/dist/src/scoped-provider.js +1 -0
  107. package/dist/src/sdk-android-adb.d.ts +144 -0
  108. package/dist/src/sdk-android-adb.js +4 -0
  109. package/dist/src/sdk-app-inventory.d.ts +4 -0
  110. package/dist/src/sdk-app-inventory.js +1 -0
  111. package/dist/src/sdk-batch-runner.d.ts +40 -0
  112. package/dist/src/sdk-batch-runner.js +2 -0
  113. package/dist/src/sdk-batch.js +2 -0
  114. package/dist/src/sdk-contracts.d.ts +386 -0
  115. package/dist/src/sdk-contracts.js +2 -0
  116. package/dist/src/sdk-finders.d.ts +61 -0
  117. package/dist/src/sdk-finders.js +1 -0
  118. package/dist/src/sdk-io.d.ts +79 -0
  119. package/dist/src/sdk-io.js +1 -0
  120. package/dist/src/sdk-remote-config.d.ts +140 -0
  121. package/dist/src/sdk-remote-config.js +1 -0
  122. package/dist/src/sdk-selectors.js +1 -0
  123. package/dist/src/selector-runtime.js +1 -1
  124. package/dist/src/selectors.d.ts +39 -137
  125. package/dist/src/selectors.js +1 -1
  126. package/dist/src/selectors2.js +1 -0
  127. package/dist/src/server.js +3 -2
  128. package/dist/src/session.js +10 -11
  129. package/dist/src/setting-state.js +1 -0
  130. package/dist/src/simctl.js +1 -0
  131. package/dist/src/simulator.js +1 -2
  132. package/dist/src/snapshot-diagnostics.js +3 -0
  133. package/dist/src/snapshot-helper.js +5 -0
  134. package/dist/src/snapshot-quality.js +1 -0
  135. package/dist/src/snapshot.js +1 -2
  136. package/dist/src/snapshot2.js +2 -0
  137. package/dist/src/{5560.js → timeouts.js} +1 -1
  138. package/dist/src/tool-provider.js +3 -0
  139. package/dist/src/tool-provider2.js +1 -0
  140. package/dist/src/ttl-memo.js +1 -0
  141. package/dist/src/update-check.js +1 -0
  142. package/dist/src/url.js +1 -0
  143. package/dist/src/version.js +1 -0
  144. package/dist/src/web.js +1 -1
  145. package/dist/src/xml.js +2 -0
  146. package/package.json +12 -19
  147. package/server.json +2 -2
  148. package/skills/agent-device/SKILL.md +2 -0
  149. package/android-multitouch-helper/dist/agent-device-android-multitouch-helper-0.18.2.apk.sha256 +0 -1
  150. package/android-snapshot-helper/dist/agent-device-android-snapshot-helper-0.18.2.apk.sha256 +0 -1
  151. package/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +0 -443
  152. package/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+FlatSnapshotFiltering.swift +0 -169
  153. package/apple-runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +0 -220
  154. package/dist/src/1404.js +0 -1
  155. package/dist/src/1986.js +0 -1
  156. package/dist/src/2748.js +0 -1
  157. package/dist/src/2948.js +0 -30
  158. package/dist/src/3006.js +0 -1
  159. package/dist/src/314.js +0 -1
  160. package/dist/src/3340.js +0 -8
  161. package/dist/src/4418.js +0 -1
  162. package/dist/src/4428.js +0 -3
  163. package/dist/src/485.js +0 -1
  164. package/dist/src/4917.js +0 -1
  165. package/dist/src/495.js +0 -5
  166. package/dist/src/5448.js +0 -3
  167. package/dist/src/5484.js +0 -1
  168. package/dist/src/5643.js +0 -1
  169. package/dist/src/587.js +0 -1
  170. package/dist/src/5913.js +0 -4
  171. package/dist/src/6849.js +0 -1
  172. package/dist/src/6918.js +0 -1
  173. package/dist/src/6967.js +0 -1
  174. package/dist/src/760.js +0 -1
  175. package/dist/src/7871.js +0 -1
  176. package/dist/src/8184.js +0 -1
  177. package/dist/src/8225.js +0 -1
  178. package/dist/src/8391.js +0 -1
  179. package/dist/src/8404.js +0 -2
  180. package/dist/src/8414.js +0 -2
  181. package/dist/src/8875.js +0 -4
  182. package/dist/src/893.js +0 -1
  183. package/dist/src/8936.js +0 -1
  184. package/dist/src/9414.js +0 -1
  185. package/dist/src/9581.js +0 -22
  186. package/dist/src/9612.js +0 -1
  187. package/dist/src/9624.js +0 -1
  188. package/dist/src/9722.js +0 -38
  189. package/dist/src/devices~1.js +0 -1
  190. package/dist/src/devices~2.js +0 -1
  191. package/dist/src/input-actions~1.js +0 -1
  192. package/dist/src/rslib-runtime.js +0 -1
  193. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner/AgentDeviceRunnerApp.m +0 -0
  194. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.pbxproj +0 -0
  195. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -0
  196. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunner.xcodeproj/xcshareddata/xcschemes/AgentDeviceRunner.xcscheme +0 -0
  197. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests-Bridging-Header.h +0 -0
  198. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/AgentDeviceRunnerUITests.entitlements +0 -0
  199. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +0 -0
  200. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +0 -0
  201. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.h +0 -0
  202. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerObjCExceptionCatcher.m +0 -0
  203. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.h +0 -0
  204. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSynthesizedGesture.m +0 -0
  205. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +0 -0
  206. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +0 -0
  207. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +0 -0
  208. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +0 -0
  209. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +0 -0
  210. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +0 -0
  211. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +0 -0
  212. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +0 -0
  213. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan +0 -0
  214. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +0 -0
  215. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/RecordingScripts/recording-resize.swift +0 -0
  216. /package/{apple-runner → dist/apple-runner}/AgentDeviceRunner/RecordingScripts/recording-trim.swift +0 -0
@@ -0,0 +1,3 @@
1
+ import{t as e}from"./rolldown-runtime.js";import{F as t,H as n,a as r}from"./sdk-contracts.js";import{A as i,C as a,F as o,b as s,j as c,v as l,x as u}from"./sdk-android-adb.js";import{C as d,p as f,w as p}from"./sdk-batch.js";import{i as ee,n as te}from"./output-path.js";import{C as ne,D as re,S as m,_ as h,c as ie,h as ae,l as oe,m as se,n as ce,o as le,p as ue,v as de,w as fe,y as pe}from"./snapshot-diagnostics.js";import{n as g,t as me}from"./version.js";import{n as he}from"./path-resolution.js";import{t as _}from"./timeouts.js";import{u as ge}from"./host-process.js";import{Dn as _e,Sn as ve,on as ye}from"./device-rotation.js";import{C as be,D as xe,E as Se,M as Ce,O as we,S as Te,T as Ee,_ as De,b as Oe,d as ke,i as Ae,l as je,u as Me,v as Ne,w as Pe,x as Fe,y as Ie}from"./registry.js";import{l as Le,m as v,v as y}from"./sdk-batch-runner.js";import{n as Re,t as ze}from"./url.js";import{t as Be}from"./client-metro-companion.js";import{n as Ve,r as He}from"./project-runtime.js";import{t as Ue}from"./runtime-transport.js";import{t as We}from"./command-metadata.js";import{createHash as Ge,randomUUID as Ke}from"node:crypto";import b from"node:fs";import qe from"node:os";import x from"node:path";import S from"node:http";import C from"node:https";import{pipeline as w}from"node:stream/promises";import{Transform as Je,Writable as Ye}from"node:stream";import T from"node:net";const Xe=`/agent-device`;function Ze(e){return E(e,Xe)}function E(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(t.replace(/^\/+/,``),n).toString()}function D(e){let t=e?.trim();return t?{authorization:`Bearer ${t}`,"x-agent-device-token":t}:{}}async function Qe(e,t){let n=b.statSync(e),r=x.basename(e),i=n.isDirectory(),a=tt(t)??et(e,n),o=[];try{let t=i?await $e(e,o):e,n=b.statSync(t);return{payloadPath:t,fileName:r,artifactType:i?`app-bundle`:`file`,platform:a,contentType:i?`application/gzip`:`application/octet-stream`,sha256:await rt(t),sizeBytes:n.size,cleanup:()=>nt(o)}}catch(e){throw nt(o),e}}async function $e(e,t){let n=b.mkdtempSync(x.join(qe.tmpdir(),`agent-device-upload-${Ke()}-`));t.push(n);let r=x.join(n,`${x.basename(e)}.tar.gz`);return await l(`tar`,[`czf`,r,`-C`,x.dirname(e),x.basename(e)],{env:{...process.env,COPYFILE_DISABLE:`1`}}),r}function et(e,t){let n=e.toLowerCase();if(t.isDirectory()&&n.endsWith(`.app`)||n.endsWith(`.ipa`))return`ios`;if(n.endsWith(`.apk`)||n.endsWith(`.aab`))return`android`}function tt(e){return e===`ios`||e===`android`?e:void 0}function nt(e){for(let t of e)b.rmSync(t,{recursive:!0,force:!0})}async function rt(e){let n=Ge(`sha256`),r=new Ye({write(e,t,r){n.update(e),r()}});return await w(b.createReadStream(e),r).catch(e=>{throw new t(`COMMAND_FAILED`,`Failed to read local artifact`,{},e instanceof Error?e:void 0)}),n.digest(`hex`)}function it(e){let{stage:t,fileName:n,startOffset:r,totalBytes:i,onProgress:a}=e,o=r,s=st(i),c=Math.min(i,r+s);return new Je({transform(e,r,l){o=Math.min(i,o+e.byteLength),o>=c&&(a?.({type:`progress`,stage:t,fileName:n,transferredBytes:o,totalBytes:i}),c=Math.min(i,o+s)),l(null,e)}})}function at(){if(!(process.stderr.isTTY!==!0||process.env.CI))return e=>{process.stderr.write(`${ot(e)}\n`)}}function ot(e){switch(e.type){case`start`:return`Uploading ${e.fileName} (${O(e.totalBytes)}) via ${ct(e.stage)} upload`;case`resume`:return`Resuming ${e.fileName} at ${O(e.transferredBytes)} of ${O(e.totalBytes)}`;case`progress`:return`Uploaded ${O(e.transferredBytes)} of ${O(e.totalBytes)} (${lt(e.transferredBytes,e.totalBytes)})`;case`fallback`:return`Direct upload did not complete; retrying ${e.fileName} with ${ct(e.to)} upload`}}function st(e){return Math.max(8388608,Math.ceil(e*.05))}function ct(e){return e===`direct`?`direct`:`legacy`}function lt(e,t){return t<=0?`100%`:`${Math.min(100,Math.floor(e/t*100))}%`}function O(e){if(e<1024)return`${e} B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)} KiB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MiB`:`${(n/1024).toFixed(1)} GiB`}const ut=300*1e3,dt=`uploadStreamRetryable`;async function ft(e){return await k({...e,url:e.url,redirectCount:0,startOffset:0})}function pt(e){return e instanceof t&&e.details?.[dt]===!0}async function k(e){let n=e.url.protocol===`https:`?C:S,r=b.statSync(e.payloadPath).size,i=gt(e.headers,e.startOffset,r);return ht(e.progress,e.startOffset,r),await new Promise((a,o)=>{let s=!1,c=n.request({protocol:e.url.protocol,host:e.url.hostname,port:e.url.port,method:e.method,path:e.url.pathname+e.url.search,headers:i},n=>{s=!0,re(n).then(i=>{clearTimeout(l);let s=n.statusCode??500,c=n.headers.location;if(c&&_t(s)){if(e.redirectCount>=5){o(new t(`COMMAND_FAILED`,`Artifact upload exceeded redirect limit`,{maxRedirects:5,url:e.url.toString()}));return}let n=new URL(c,e.url);k({...e,url:n,redirectCount:e.redirectCount+1}).then(a,o);return}let u=vt(s)?yt(n.headers,r):void 0;if(u!==void 0){if(u>=r){a({statusCode:200,statusMessage:`Upload already complete`,body:``});return}if(u<=e.startOffset){o(new t(`COMMAND_FAILED`,`Artifact upload resume did not advance`,{offset:u,previousOffset:e.startOffset,url:e.url.toString()}));return}k({...e,startOffset:u}).then(a,o);return}a({statusCode:s,statusMessage:n.statusMessage,body:i})}).catch(o)}),l=setTimeout(()=>{c.destroy(),o(new t(`COMMAND_FAILED`,e.timeoutMessage,{timeoutMs:ut,...e.timeoutHint?{hint:e.timeoutHint}:{},...mt(e)}))},ut);c.on(`error`,n=>{s||(clearTimeout(l),o(new t(`COMMAND_FAILED`,e.errorMessage,{...e.errorHint?{hint:e.errorHint}:{},...mt(e)},n)))}),c.on(`close`,()=>clearTimeout(l)),w(b.createReadStream(e.payloadPath,{start:e.startOffset}),it({stage:e.progress?.stage??`legacy`,fileName:e.progress?.fileName??x.basename(e.payloadPath),startOffset:e.startOffset,totalBytes:r,onProgress:e.progress?.onProgress}),c).catch(e=>{s||(c.destroy(),o(new t(`COMMAND_FAILED`,`Failed to read local artifact`,{},e instanceof Error?e:Error(String(e)))))})})}function mt(e){return e.retryable===!0?{[dt]:!0}:{}}function ht(e,t,n){e?.onProgress?.({type:t>0?`resume`:`start`,stage:e.stage,fileName:e.fileName,transferredBytes:t,totalBytes:n})}function gt(e,t,n){return t<=0?e:{...e,"content-length":Math.max(n-t,0),"content-range":`bytes ${t}-${n-1}/${n}`}}function _t(e){return[301,302,303,307,308].includes(e)}function vt(e){return e===308}function yt(e,t){let n=bt(e[`x-upload-offset`]??e[`upload-offset`]);if(n!==void 0)return Math.min(n,t);let r=xt(e.range)?.match(/^bytes=0-(\d+)$/);if(!r)return;let i=Number(r[1]);if(!(!Number.isSafeInteger(i)||i<0))return Math.min(i+1,t)}function bt(e){let t=xt(e);if(t===void 0)return;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:void 0}function xt(e){return Array.isArray(e)?e[0]:e}const St=30*1e3;async function Ct(e){let t=await Qe(e.localPath,e.platform),n=e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`,r=Ke();try{let i=await Dt({normalizedBase:n,token:e.token,artifact:t,uploadAttemptId:r});return i?.kind===`cache-hit`?i.uploadId:i?.kind===`direct-upload`?await wt({normalizedBase:n,token:e.token,artifact:t,preflight:i,uploadAttemptId:r,onProgress:e.onProgress})||(e.onProgress?.({type:`fallback`,from:`direct`,to:`legacy`,fileName:t.fileName}),await Et({normalizedBase:n,token:e.token,artifact:t,onProgress:e.onProgress})):await Et({normalizedBase:n,token:e.token,artifact:t,onProgress:e.onProgress})}finally{t.cleanup()}}async function wt(e){let t=async t=>(await At(e.artifact,t,e.onProgress),await jt({normalizedBase:e.normalizedBase,token:e.token,uploadId:t.uploadId}));try{return await t(e.preflight)}catch(n){if(!Tt(n))return;let r=await Dt({normalizedBase:e.normalizedBase,token:e.token,artifact:e.artifact,uploadAttemptId:e.uploadAttemptId});if(r?.kind===`cache-hit`)return r.uploadId;if(r?.kind===`direct-upload`)try{return await t(r)}catch{return}return}}function Tt(e){return e instanceof t?pt(e):!0}async function Et(e){let{normalizedBase:n,token:r,artifact:i}=e,a=new URL(`upload`,n),o={"content-type":i.contentType,"x-artifact-type":i.artifactType,"x-artifact-filename":i.fileName,"x-artifact-hash":i.sha256,"x-artifact-hash-algorithm":`sha256`,"transfer-encoding":`chunked`};Object.assign(o,D(r));let s=await ft({url:a,method:`POST`,headers:o,payloadPath:i.payloadPath,timeoutMessage:`Artifact upload timed out`,timeoutHint:`The upload to the remote daemon exceeded the 5-minute timeout.`,errorMessage:`Failed to upload artifact to remote daemon`,errorHint:`Verify the remote daemon is reachable and supports artifact uploads.`,progress:{stage:`legacy`,fileName:i.fileName,onProgress:e.onProgress}});try{let e=JSON.parse(s.body);if(!e.ok||!e.uploadId)throw new t(`COMMAND_FAILED`,`Upload failed: ${s.body}`);return e.uploadId}catch(e){throw e instanceof t?e:new t(`COMMAND_FAILED`,`Invalid upload response: ${s.body}`)}}async function Dt(e){let t=new URL(`upload/preflight`,e.normalizedBase),n={"content-type":`application/json`};Object.assign(n,D(e.token));let r=await fetch(t,{method:`POST`,headers:n,signal:AbortSignal.timeout(St),body:JSON.stringify({uploadAttemptId:e.uploadAttemptId,sha256:e.artifact.sha256,fileName:e.artifact.fileName,sizeBytes:e.artifact.sizeBytes,artifactType:e.artifact.artifactType,...e.artifact.platform?{platform:e.artifact.platform}:{},contentType:e.artifact.contentType})}).catch(()=>void 0);if(r?.ok)return Ot(await r.json().catch(()=>void 0))}function Ot(e){if(!e||typeof e!=`object`)return;let t=e;if(t.ok!==!0||typeof t.uploadId!=`string`)return;if(t.cacheHit===!0)return{kind:`cache-hit`,uploadId:t.uploadId};let n=t.upload;if(!n||typeof n.url!=`string`)return;let r=n.headers??{};if(kt(r))return{kind:`direct-upload`,uploadId:t.uploadId,url:n.url,headers:r}}function kt(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}async function At(e,n,r){let i=await ft({url:new URL(n.url),method:`PUT`,headers:n.headers,payloadPath:e.payloadPath,timeoutMessage:`Direct artifact upload timed out`,timeoutHint:`The direct upload ticket did not accept the artifact within the timeout.`,errorMessage:`Failed to upload artifact with direct upload ticket`,retryable:!0,progress:{stage:`direct`,fileName:e.fileName,onProgress:r}});if(i.statusCode<200||i.statusCode>=300)throw new t(`COMMAND_FAILED`,`Direct artifact upload failed`,{statusCode:i.statusCode,statusMessage:i.statusMessage})}async function jt(e){let n=new URL(`upload/finalize`,e.normalizedBase),r={"content-type":`application/json`};Object.assign(r,D(e.token));let i=await fetch(n,{method:`POST`,headers:r,signal:AbortSignal.timeout(St),body:JSON.stringify({uploadId:e.uploadId})}).catch(e=>{throw new t(`COMMAND_FAILED`,`Failed to finalize direct artifact upload`,{},e)});if(!i.ok)throw new t(`COMMAND_FAILED`,`Direct artifact upload finalize failed`,{status:i.status,statusText:i.statusText});let a=await i.json().catch(()=>void 0);if(!a?.ok||!a.uploadId)throw new t(`COMMAND_FAILED`,`Invalid upload finalize response`);return a.uploadId}async function Mt(e,t){let n=[...e.positionals??[]],r=e.flags?{...e.flags}:void 0,i=e.meta?.installSource,a={},o,s=at();if(!qt(t))return A({positionals:n,flags:r,installSource:i,uploadedArtifactId:o,clientArtifactPaths:a});r=Pt(e,n,r,a);let c=await Lt(e,t,s);return c&&(i=c.installSource,o=c.uploadedArtifactId??o),e.command!==`install`&&e.command!==`reinstall`||(o=await Nt(e,t,n,s)??o),A({positionals:n,flags:r,installSource:i,uploadedArtifactId:o,clientArtifactPaths:a})}async function Nt(e,t,n,r){let i=n.length===1?0:1,a=n[i];if(a===void 0)return;if(a.startsWith(`remote:`)){n[i]=a.slice(7);return}let o=It(a,e.meta?.cwd);if(o)return await Ct({localPath:o,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform,onProgress:r})}function Pt(e,t,n,r){let i=Rt(e,t);if(!i)return n;i.positionalPath!==void 0&&(t[i.positionalIndex]=i.positionalPath);let a=Ft(n,i.flagPath);return r[i.field]=i.localPath,a}function Ft(e,t){return t===void 0?e:{...e??{},out:t}}function It(e,t){let n=x.isAbsolute(e)?e:x.resolve(t??process.cwd(),e);return b.existsSync(n)?n:void 0}function A(e){return{positionals:e.positionals,flags:e.flags,installSource:e.installSource,uploadedArtifactId:e.uploadedArtifactId,...Object.keys(e.clientArtifactPaths).length>0?{clientArtifactPaths:e.clientArtifactPaths}:{}}}async function Lt(e,t,n){let r=e.meta?.installSource;if(e.command!==`install_source`||!r||r.kind!==`path`)return null;let i=r.path.trim();if(!i)return{installSource:r};if(i.startsWith(`remote:`))return{installSource:{...r,path:i.slice(7)}};let a=x.isAbsolute(i)?i:x.resolve(e.meta?.cwd??process.cwd(),i);if(!b.existsSync(a))return{installSource:{...r,path:a}};let o=await Ct({localPath:a,baseUrl:t.baseUrl,token:t.token,platform:e.flags?.platform,onProgress:n});return{installSource:{...r,path:a},uploadedArtifactId:o}}function Rt(e,t){if(e.command===`screenshot`){let n=Ht(e,`path`,`.png`);return t[0]?{field:`path`,localPath:n,positionalIndex:0,positionalPath:M(`screenshot`,`.png`)}:{field:`path`,localPath:n,positionalIndex:0,flagPath:M(`screenshot`,`.png`)}}if(e.command===`record`&&(t[0]??``).toLowerCase()===`start`){if(!Bt(e)&&e.flags?.platform===void 0)return null;let t=zt(e),n=Vt(Ht(e,`outPath`,t,1),e);return{field:`outPath`,localPath:n,positionalIndex:1,positionalPath:M(`recording`,x.extname(n)||t)}}return null}function zt(e){return ee(e.flags?.platform)}function Bt(e){return j(e.positionals?.[1])||j(e.flags?.out)}function Vt(e,t){return t.flags?.platform===`web`?te(e,zt(t)):e}function Ht(e,t,n,r=0){let i=e.positionals?.[r]??e.flags?.out,a=`${t===`path`?`screenshot`:`recording`}-${Date.now()}${n}`,o=j(i)?i:a;return x.isAbsolute(o)?o:x.resolve(e.meta?.cwd??process.cwd(),o)}function j(e){return typeof e==`string`&&e.trim().length>0}function M(e,t){let n=t.startsWith(`.`)?t:`.${t}`;return x.posix.join(`/tmp`,`agent-device-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}${n}`)}async function Ut(e,t,n){let r=Array.isArray(n.data?.artifacts)?n.data.artifacts:[];if(r.length===0||!e.baseUrl)return n;let i=n.data?{...n.data}:{},a=[];for(let n of r){if(!n||typeof n!=`object`||typeof n.artifactId!=`string`){a.push(n);continue}let r=Wt(n,t);await Gt({baseUrl:e.baseUrl,token:e.token,artifactId:n.artifactId,destinationPath:r,requestId:t.meta?.requestId}),i[n.field]=r,a.push({...n,localPath:r})}return i.artifacts=a,{ok:!0,data:i}}function Wt(e,t){if(e.localPath&&e.localPath.trim().length>0)return e.localPath;let n=t.meta?.clientArtifactPaths?.[e.field];if(n&&n.trim().length>0)return n;let r=e.fileName?.trim()||`${e.field}-${Date.now()}`;return x.resolve(t.meta?.cwd??process.cwd(),r)}async function Gt(e){let n=new URL(Kt(e.baseUrl,e.artifactId)),r=n.protocol===`https:`?C:S;await b.promises.mkdir(x.dirname(e.destinationPath),{recursive:!0}),await new Promise((i,a)=>{let o=!1,s=e.timeoutMs??9e4,c=t=>{if(!o){if(o=!0,clearTimeout(u),t){b.promises.rm(e.destinationPath,{force:!0}).finally(()=>a(t));return}i()}},l=r.request({protocol:n.protocol,host:n.hostname,port:n.port,method:`GET`,path:n.pathname+n.search,headers:D(e.token)},n=>{if((n.statusCode??500)>=400){let r=``;n.setEncoding(`utf8`),n.on(`data`,e=>{r+=e}),n.on(`end`,()=>{c(new t(`COMMAND_FAILED`,`Failed to download remote artifact`,{artifactId:e.artifactId,statusCode:n.statusCode,requestId:e.requestId,body:r}))});return}n.on(`aborted`,()=>{c(new t(`COMMAND_FAILED`,`Remote artifact download was interrupted`,{artifactId:e.artifactId,requestId:e.requestId}))}),w(n,b.createWriteStream(e.destinationPath)).then(()=>c(),e=>c(e instanceof Error?e:Error(String(e))))}),u=setTimeout(()=>{let n=new t(`COMMAND_FAILED`,`Remote artifact download timed out`,{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:s});c(n),l.destroy(n)},s);l.on(`error`,n=>{if(n instanceof t){c(n);return}c(new t(`COMMAND_FAILED`,`Failed to download remote artifact`,{artifactId:e.artifactId,requestId:e.requestId,timeoutMs:s},n instanceof Error?n:void 0))}),l.end()})}function Kt(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return new URL(`artifacts/${encodeURIComponent(t)}`,n).toString()}function qt(e){return typeof e.baseUrl==`string`&&e.baseUrl.length>0}const Jt=3e3,Yt=1e3;function N(e){let t=an(e);if(!t||typeof t!=`object`)return null;let n=t,r=Xt(n);if(!r)return null;let i=Zt(n);return i?{token:r,...i,transport:Qt(n.transport),pid:F(n.pid)??0,version:P(n.version),codeSignature:P(n.codeSignature),processStartTime:P(n.processStartTime)}:null}function Xt(e){return typeof e.token==`string`&&e.token.length>0?e.token:null}function Zt(e){let t=F(e.port),n=F(e.httpPort);return t===void 0&&n===void 0?null:{port:t,httpPort:n}}function Qt(e){return e===`socket`||e===`http`||e===`dual`?e:void 0}function P(e){return typeof e==`string`?e:void 0}function F(e){return Number.isInteger(e)&&Number(e)>0?Number(e):void 0}function I(e){let t=an(e);if(!t||typeof t!=`object`)return null;let n=t;return Number.isInteger(n.pid)&&Number(n.pid)>0?{pid:Number(n.pid),processStartTime:typeof n.processStartTime==`string`?n.processStartTime:void 0,startedAt:typeof n.startedAt==`number`?n.startedAt:void 0}:null}function L(e){on(e)}function R(e){on(e)}function $t(e){let t=B(e);if(!t.hasLock||t.hasInfo)return;let n=I(e.lockPath);if(!n){R(e.lockPath);return}h(n.pid,n.processStartTime)||R(e.lockPath)}async function z(e,t,n={}){let r=n.stopLiveProcesses??!0,i={reason:t,removedInfo:!1,removedLock:!1,stoppedInfoProcess:!1,stoppedLockProcess:!1};try{let t=b.existsSync(e.infoPath),n=N(e.infoPath);if(n){let t=h(n.pid,n.processStartTime);t&&!r?i.retainedInfoProcess=!0:(t&&(await V(n),i.stoppedInfoProcess=!0),L(e.infoPath),i.removedInfo=!0)}else t&&(L(e.infoPath),i.removedInfo=!0);let a=b.existsSync(e.lockPath),o=I(e.lockPath);if(o){let t=h(o.pid,o.processStartTime);t&&!r?i.retainedLockProcess=!0:(t&&(await de(o.pid,{termTimeoutMs:Jt,killTimeoutMs:Yt,expectedStartTime:o.processStartTime}),i.stoppedLockProcess=!0),R(e.lockPath),i.removedLock=!0)}else a&&(R(e.lockPath),i.removedLock=!0)}catch(e){i.error=e instanceof Error?e.message:String(e)}return c({level:i.error?`warn`:`info`,phase:`daemon_startup_metadata_cleanup`,data:i}),i}function B(e){return{hasInfo:b.existsSync(e.infoPath),hasLock:b.existsSync(e.lockPath)}}async function en(e){let t=B(e);if(!t.hasLock||t.hasInfo)return!1;let n=I(e.lockPath);return!n||!h(n.pid,n.processStartTime)?(R(e.lockPath),!0):!1}async function V(e){await de(e.pid,{termTimeoutMs:Jt,killTimeoutMs:Yt,expectedStartTime:e.processStartTime})}function tn(e){return typeof e.baseUrl==`string`&&e.baseUrl.length>0}function nn(e,t=m(process.env.AGENT_DEVICE_STATE_DIR)){let n=rn(t);return e.hasLock&&!e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.lockPath} still exists without ${t.infoPath}. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${n}`:e.hasLock&&e.hasInfo?`agent-device attempted to clean stale daemon metadata automatically, but ${t.infoPath} and ${t.lockPath} still remain. Retry with --debug; if this persists after confirming no agent-device daemon process is running, run: ${n}`:e.hasInfo?`agent-device did not observe reachable daemon metadata after retrying, and ${t.infoPath} still remains. Stale metadata was cleaned automatically when safe; retry with --debug. If this persists after confirming no agent-device daemon process is running, run: ${n}`:`agent-device did not observe reachable daemon metadata after retrying. Stale metadata was cleaned automatically when safe; retry with --debug and check daemon diagnostics logs. If stale metadata returns after confirming no agent-device daemon process is running, run: ${n}`}function rn(e){return`rm -f ${ae(e.infoPath)} ${ae(e.lockPath)}`}function an(e){if(!b.existsSync(e))return null;try{return JSON.parse(b.readFileSync(e,`utf8`))}catch{return null}}function on(e){try{b.existsSync(e)&&b.unlinkSync(e)}catch{}}function sn(e,t){if(t.onProgress){t.onProgress(e);return}e.type===`command`&&(t.req.command===`doctor`&&Ce(),process.stderr.write(`${e.message}\n`))}function H(e,n,r){return new t(`COMMAND_FAILED`,`Invalid daemon response`,{requestId:e.meta?.requestId,line:n},r instanceof Error?r:void 0)}function cn(e){let t=t=>(e.onError(t),!0);return{handleLine(n){let r;try{r=JSON.parse(n)}catch(r){return t(H(e.req,n,r))}if(ie(r))try{return sn(r.event,{req:e.req,onProgress:e.onProgress}),!1}catch(e){return t(e)}return oe(r)?(e.onResponse(r.response),!0):e.responseFormat===`socket-legacy`?(e.onResponse(r),!0):t(H(e.req,n,Error(`Missing daemon progress response envelope`)))}}}function ln(e,t){return ue(e)&&String(Array.isArray(t)?t.join(`,`):t??``).includes(`application/x-ndjson`)}function un(e,t){let{req:n,isSettled:r,resolve:i,reject:a,clearTimeout:o}=t,s=``,c=cn({req:n,onProgress:t.onProgress,responseFormat:`socket-legacy`,onResponse(t){o(),i(t),e.end()},onError(e){o(),a(e)}});e.setEncoding(`utf8`),e.on(`data`,e=>{if(r())return;let t=se(s,e);s=t.buffer;for(let e of t.lines)if(c.handleLine(e))return})}function dn(e,n){let{req:r,handleResponseBody:i,reject:a,clearTimeout:o}=n,s=``,c=!1,l=cn({req:r,onProgress:n.onProgress,responseFormat:`ndjson-envelope`,onResponse(e){c=!0,o(),i(JSON.stringify(e))},onError(e){c=!0,o(),a(e)}});e.setEncoding(`utf8`),e.on(`data`,e=>{if(c)return;let t=se(s,e);s=t.buffer;for(let e of t.lines)if(e&&l.handleLine(e))return}),e.on(`end`,()=>{if(c)return;let e=s.trim();e&&l.handleLine(e)||(c=!0,o(),a(H(r,e)))}),e.on(`error`,e=>{c||(c=!0,o(),a(new t(`COMMAND_FAILED`,`Failed to read daemon response`,{requestId:r.meta?.requestId},e instanceof Error?e:void 0)))})}function fn(e,n){let{info:r,req:i,resolve:a,reject:o}=n;try{let n=pn(e);if(n.error){o(mn(n.error,i.meta?.requestId));return}if(!n.result||typeof n.result!=`object`){o(new t(`COMMAND_FAILED`,`Invalid daemon RPC response`,{requestId:i.meta?.requestId}));return}hn(r,i,n.result,a,o)}catch(n){o(new t(`COMMAND_FAILED`,`Invalid daemon response`,{requestId:i.meta?.requestId,line:e},n instanceof Error?n:void 0))}}function pn(e){return JSON.parse(e)}function mn(e,r){let i=e.data??{};return new t(n(i.code==null?void 0:String(i.code),`COMMAND_FAILED`),String(i.message??e.message??`Daemon RPC request failed`),{...typeof i.details==`object`&&i.details?i.details:{},hint:typeof i.hint==`string`?i.hint:void 0,diagnosticId:typeof i.diagnosticId==`string`?i.diagnosticId:void 0,logPath:typeof i.logPath==`string`?i.logPath:void 0,retriable:typeof i.retriable==`boolean`?i.retriable:void 0,supportedOn:typeof i.supportedOn==`string`?i.supportedOn:void 0,requestId:r})}async function hn(e,t,n,r,i){try{r(e.baseUrl&&n.ok?await Ut(e,t,n):n)}catch(e){i(e)}}function gn(e,t){let n=e.meta?.requestId??i();return _n(e.command)?{jsonrpc:`2.0`,id:n,method:vn(e.command),params:yn(e,e.command,t)}:{jsonrpc:`2.0`,id:n,method:`agent_device.command`,params:e}}function _n(e){return e===`lease_allocate`||e===`lease_heartbeat`||e===`lease_release`}function vn(e){switch(e){case`lease_allocate`:return`agent_device.lease.allocate`;case`lease_heartbeat`:return`agent_device.lease.heartbeat`;case`lease_release`:return`agent_device.lease.release`}}function yn(e,t,n){return _e(ve(e),t,{includeTokenParam:n.includeTokenParam,token:e.token,session:e.session})}const bn=[`xcodebuild .*AgentDeviceRunnerUITests/RunnerTests/testCommand`,`xcodebuild .*AgentDeviceRunner\\.env\\.session-`,`xcodebuild build-for-testing .*apple-runner/AgentDeviceRunner/AgentDeviceRunner\\.xcodeproj`];function xn(e){let t=f(e.command);if(t.envelopeMs===`unbounded`)return;let n={...t,envelopeMs:t.envelopeMs};return Sn(n,e.positionals??[])??Cn(n,e.flags)??n.envelopeMs}function Sn(e,t){if(e.budget.source!==`positional-parser`)return;let n=e.budget.parser(t);return n===null?void 0:Tn(e,n)}function Cn(e,t){if(e.budget.source===`flag`)return e.budget.envelope===`widen`?wn(e,e.budget,t):typeof t?.timeoutMs==`number`?t.timeoutMs:e.envelopeMs}function wn(e,t,n){if(n?.settle!==!0)return e.envelopeMs;let r=typeof n.timeoutMs==`number`?n.timeoutMs:t.defaultBudgetMs;return typeof r==`number`?En(e,r):e.envelopeMs}function Tn(e,t){return Math.max(e.envelopeMs,t+Mn)}function En(e,t){return Math.max(e.envelopeMs,e.envelopeMs+t+Mn)}function Dn(e,n,r,i,a,o){let s=a?{terminated:0}:An(),l=!a&&On(i),u=l?jn(e,n):{forcedKill:!1};return c({level:`error`,phase:`daemon_request_timeout`,data:{timeoutMs:o,requestId:r,command:i,timedOutRunnerPidsTerminated:s.terminated,timedOutRunnerCleanupError:s.error,daemonPidReset:l?e.pid:void 0,daemonPidForceKilled:l?u.forcedKill:void 0,daemonPreservedAfterTimeout:!a&&!l,daemonBaseUrl:e.baseUrl}}),new t(`COMMAND_FAILED`,`Daemon request timed out`,{timeoutMs:o,requestId:r,hint:kn({remote:a,resetDaemon:l,command:i})})}function On(e){return f(e).onTimeout===`reset-daemon`}function kn(e){let{remote:t,resetDaemon:n,command:r}=e;if(t)return`Retry with --debug and verify the remote daemon URL, auth token, and remote host logs.`;if(!n){let e=r===p.snapshot?` If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.`:``;return`Retry with --debug and check daemon diagnostics logs. The timed-out ${r??`request`} request was canceled and Apple runner work was aborted when detected; the daemon was kept alive so the session can still be closed or inspected.${e}`}return`Retry with --debug and check daemon diagnostics logs. Timed-out Apple runner xcodebuild processes were terminated when detected.`}function An(){let e=0;try{for(let t of bn)a(`pkill`,[`-f`,t],{allowFailure:!0}).exitCode===0&&(e+=1);return{terminated:e}}catch(t){return{terminated:e,error:t instanceof Error?t.message:String(t)}}}function jn(e,t){let n=!1;try{h(e.pid,e.processStartTime)&&(process.kill(e.pid,`SIGKILL`),n=!0)}catch{V(e)}finally{L(t.infoPath),R(t.lockPath)}return{forcedKill:n}}const Mn=3e4,Nn=`Daemon HTTP endpoint is unavailable`,Pn=`Daemon socket endpoint is unavailable`;async function U(e,t){let n=Un(e,t);if(await Fn(e,n))return!0;let r=Wn(e,t,n);return r?await Fn(e,r):!1}async function Fn(e,t){return t===`http`?await Ln(e):await In(e.port)}function In(e){return e?new Promise(t=>{let n=!1,r=T.createConnection({host:`127.0.0.1`,port:e},()=>{i(!0)}),i=e=>{n||(n=!0,r.destroy(),t(e))};r.setTimeout(500),r.on(`timeout`,()=>{i(!1)}),r.on(`error`,()=>{i(!1)})}):Promise.resolve(!1)}function Ln(e){return zn(e).then(e=>e.reachable)}async function Rn(e){let n=await zn(e);if(!e.baseUrl||!n.reachable)return n;if(typeof n.rpcProtocolVersion==`number`&&n.rpcProtocolVersion!==1)throw new t(`COMMAND_FAILED`,`Remote daemon RPC protocol is incompatible`,{daemonBaseUrl:e.baseUrl,clientVersion:g(),remoteVersion:n.version,remoteService:n.service,supportedRpcProtocolVersion:1,remoteRpcProtocolVersion:n.rpcProtocolVersion,hint:`Upgrade agent-device on the client or remote host so both support the same daemon RPC protocol.`});return n}function zn(e){let t=e.baseUrl?E(e.baseUrl,`health`):e.httpPort?`http://127.0.0.1:${e.httpPort}/health`:null;if(!t)return Promise.resolve({reachable:!1});let n=new URL(t),r=n.protocol===`https:`?C:S,i=e.baseUrl?3e3:500;return new Promise(t=>{let a=e.baseUrl?D(e.token):{},o=r.request({protocol:n.protocol,host:n.hostname,port:n.port,path:n.pathname+n.search,method:`GET`,timeout:i,headers:a},e=>{let n=``;e.setEncoding(`utf8`),e.on(`data`,e=>{n+=e}),e.on(`end`,()=>{let r=e.statusCode??500;t({reachable:r<500,statusCode:r,...Bn(n)})})});o.on(`timeout`,()=>{o.destroy(),t({reachable:!1})}),o.on(`error`,()=>{t({reachable:!1})}),o.end()})}function Bn(e){try{let t=JSON.parse(e);return{service:typeof t.service==`string`?t.service:void 0,version:typeof t.version==`string`?t.version:void 0,rpcProtocolVersion:typeof t.rpcProtocolVersion==`number`?t.rpcProtocolVersion:void 0}}catch{return{}}}async function Vn(e,t,n,r,i,a={}){let o=Un(e,n);try{return await Hn(e,t,r,i,o,a)}catch(s){let c=Wn(e,n,o);if(!c||!Gn(s,o))throw s;return await Hn(e,t,r,i,c,a)}}async function Hn(e,t,n,r,i,a){return i===`http`?await Yn(e,t,n,r,a):await Jn(e,t,n,r,a)}function Un(e,n){if(e.baseUrl){if(n===`socket`)throw new t(`COMMAND_FAILED`,`Remote daemon endpoint only supports HTTP transport`,{daemonBaseUrl:e.baseUrl});return`http`}if(n===`http`||n===`socket`)return Kn(e,n);let r=(e.transport===`socket`||e.transport===`dual`?[`socket`,`http`]:[`http`,`socket`]).find(t=>W(e,t));if(r)return r;throw new t(`COMMAND_FAILED`,`Daemon metadata has no reachable transport`)}function W(e,t){return t===`http`?!!e.httpPort:!!e.port}function Wn(e,t,n){if(t!==`auto`||e.baseUrl)return null;let r=n===`socket`?`http`:`socket`;return W(e,r)?r:null}function Gn(e,n){return n===`socket`&&e instanceof t&&e.code===`COMMAND_FAILED`&&e.message===`Failed to communicate with daemon`&&e.details?.daemonSocketRequestWritten===!1}function Kn(e,n){if(W(e,n))return n;throw new t(`COMMAND_FAILED`,n===`http`?Nn:Pn)}function qn(e,n,r,i={}){return c({level:`error`,phase:`daemon_request_socket_error`,data:{requestId:n,message:e instanceof Error?e.message:String(e)}}),new t(`COMMAND_FAILED`,`Failed to communicate with daemon`,{...i,requestId:n,hint:r?`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 instanceof Error?e:void 0)}async function Jn(e,n,r,i,a){let o=e.port;if(!o)throw new t(`COMMAND_FAILED`,Pn);return new Promise((t,s)=>{let c=!1,l=T.createConnection({host:`127.0.0.1`,port:o},()=>{c=!0,l.write(`${JSON.stringify(n)}\n`)}),u=!1,d=typeof i==`number`?setTimeout(()=>{u=!0,l.destroy(),s(Dn(e,r,n.meta?.requestId,n.command,!1,i))},i):void 0;un(l,{req:n,onProgress:a.onProgress,isSettled:()=>u,clearTimeout:()=>{d&&clearTimeout(d)},resolve:e=>{u=!0,t(e)},reject:e=>{u=!0,s(e)}}),l.on(`error`,e=>{u||(u=!0,d&&clearTimeout(d),s(qn(e,n.meta?.requestId,!1,{daemonSocketRequestWritten:c})))})})}async function Yn(e,n,r,i,a){let o=e.baseUrl?new URL(E(e.baseUrl,`rpc`)):e.httpPort?new URL(`http://127.0.0.1:${e.httpPort}/rpc`):null;if(!o)throw new t(`COMMAND_FAILED`,Nn);let s=JSON.stringify(gn(n,{includeTokenParam:!e.baseUrl})),c={"content-type":`application/json`,"content-length":Buffer.byteLength(s)};return e.baseUrl&&Object.assign(c,D(e.token)),await new Promise((l,u)=>{let d=(o.protocol===`https:`?C:S).request({protocol:o.protocol,host:o.hostname,port:o.port,method:`POST`,path:o.pathname+o.search,headers:c},r=>{if(ln(n,r.headers?.[`content-type`])){dn(r,{req:n,onProgress:a.onProgress,reject:u,clearTimeout:()=>{p&&clearTimeout(p)},handleResponseBody:t=>fn(t,{info:e,req:n,resolve:l,reject:u})});return}re(r).then(t=>{p&&clearTimeout(p),fn(t,{info:e,req:n,resolve:l,reject:u})}).catch(e=>{p&&clearTimeout(p),u(new t(`COMMAND_FAILED`,`Failed to read daemon response`,{requestId:n.meta?.requestId},e instanceof Error?e:void 0))})}),f=tn(e),p=typeof i==`number`?setTimeout(()=>{d.destroy(),u(Dn(e,r,n.meta?.requestId,n.command,f,i))},i):void 0;d.on(`error`,e=>{p&&clearTimeout(p),u(qn(e,n.meta?.requestId,f))}),d.write(s),d.end()})}const G=15e3,K=new T.BlockList;K.addSubnet(`127.0.0.0`,8,`ipv4`),K.addAddress(`::1`,`ipv6`),K.addSubnet(`::ffff:127.0.0.0`,104,`ipv6`);function Xn(e){let t=Zn(e),n=Qn(e),r=$n(e,n.remoteBaseUrl),i=er(e,t,n.rawBaseUrl);return{paths:m(i?tr():t),transportPreference:r.preference,serverMode:r.serverMode,ownedStateDir:i,remoteBaseUrl:n.remoteBaseUrl,remoteAuthToken:n.authToken}}function Zn(e){return e.flags?.stateDir??process.env.AGENT_DEVICE_STATE_DIR}function Qn(e){let t=e.flags?.daemonBaseUrl??process.env.AGENT_DEVICE_DAEMON_BASE_URL,n=yr(t),r=e.flags?.daemonAuthToken??process.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;return br(n,r),{rawBaseUrl:t,remoteBaseUrl:n,authToken:r}}function $n(e,n){let r=e.flags?.daemonTransport??process.env.AGENT_DEVICE_DAEMON_TRANSPORT,i=fe(r);if(n&&i===`socket`)throw new t(`INVALID_ARGS`,`Remote daemon base URL only supports HTTP transport. Remove --daemon-transport socket.`,{daemonBaseUrl:n});return{preference:i,serverMode:ne(e.flags?.daemonServerMode??process.env.AGENT_DEVICE_DAEMON_SERVER_MODE??(r===`dual`?`dual`:void 0))}}function er(e,t,n){return fr(e.command)&&!t&&!n}function tr(){return b.mkdtempSync(x.join(qe.tmpdir(),`agent-device-replay-daemon-`))}async function nr(e){if(e.remoteBaseUrl)return await rr(e);let t=await ir(e);return t?{info:t,startedByClient:!1}:($t(e.paths),await ur(e))}async function rr(e){let n={transport:`http`,token:e.remoteAuthToken??``,pid:0,baseUrl:e.remoteBaseUrl};if((await Rn(n)).reachable)return{info:n,startedByClient:!1};throw new t(`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. If this CLI was connected with connect proxy, run agent-device disconnect to return to the local daemon.`})}async function ir(e){let t=N(e.paths.infoPath);if(!t)return null;let n=await ar(t,e.transportPreference);return sr(t,n)?t:(cr(t,n,e.paths.baseDir),await V(t),L(e.paths.infoPath),null)}async function ar(e,t){try{return await U(e,t)}catch(e){if(or(e))return!1;throw e}}function or(e){return e instanceof t&&e.code===`COMMAND_FAILED`&&(e.message===`Daemon HTTP endpoint is unavailable`||e.message===`Daemon socket endpoint is unavailable`)}function sr(e,t){return e.version===g()&&e.codeSignature===gr()&&t}function cr(e,t,n){try{let r=e.version?`pid ${e.pid}, v${e.version}`:`pid ${e.pid}`,i=lr(e,t);process.stderr.write(`Replacing daemon (${r}) in ${n}: ${i}\n`)}catch{}}function lr(e,t){return e.version===g()?e.codeSignature===gr()?t?`not reusable`:`unreachable`:`code-signature mismatch`:`version mismatch (client v${g()})`}async function ur(e){let n=0,r=[],i,a;for(let t=1;t<=2;t+=1){let o;try{o=mr(e),a={pid:o.pid}}catch(n){if(i=n instanceof Error?n.message:String(n),r.push(await z(e.paths,`start_error`)),t<2){await _(150);continue}break}let s=await pr(G,e,o);if(s.kind===`ready`)return{info:s.info,startedByClient:!0};if(s.kind===`early_exit`){if(a=s.exit,i=_r(s.exit),r.push(await z(e.paths,`start_error`)),t<2){await _(150);continue}break}if(await en(e.paths)){n+=1;continue}let c=B(e.paths),l=t<2,u=await z(e.paths,`startup_timeout`,{stopLiveProcesses:!1});if(r.push(u),u.retainedInfoProcess||u.retainedLockProcess){let t=await pr(G,e,o);if(t.kind===`ready`)return{info:t.info,startedByClient:!0};t.kind===`early_exit`&&(a=t.exit,i=_r(t.exit));break}if(!l)break;!c.hasInfo&&!c.hasLock&&await _(150)}let o=B(e.paths),s=vr(e.paths.logPath);throw new t(`COMMAND_FAILED`,`Failed to start daemon`,{kind:`daemon_startup_failed`,stateDir:e.paths.baseDir,infoPath:e.paths.infoPath,lockPath:e.paths.lockPath,logPath:e.paths.logPath,startupTimeoutMs:G,startupAttempts:2,lockRecoveryCount:n,cleanupResults:r,startError:i,daemonProcess:a,...s?{daemonLogTail:s}:{},metadataState:o,hint:nn(o,e.paths)})}async function dr(e,t,n){if(!fr(e.command)||!t.startedByClient&&!n.ownedStateDir||tn(t.info))return;let r={pid:t.info.pid,removedInfo:!1,removedLock:!1,removedStateDir:!1,error:void 0};try{await V(t.info)}catch(e){r.error=e instanceof Error?e.message:String(e)}finally{let e=b.existsSync(n.paths.infoPath);L(n.paths.infoPath),r.removedInfo=e&&!b.existsSync(n.paths.infoPath);let t=b.existsSync(n.paths.lockPath);R(n.paths.lockPath),r.removedLock=t&&!b.existsSync(n.paths.lockPath),n.ownedStateDir&&(b.rmSync(n.paths.baseDir,{recursive:!0,force:!0}),r.removedStateDir=!b.existsSync(n.paths.baseDir))}c({level:r.error?`warn`:`info`,phase:`daemon_replay_cleanup`,data:r})}function fr(e){return e===p.replay||e===p.test}async function pr(e,t,n){let r=Date.now(),i;for(n.exited.then(e=>{i=e});Date.now()-r<e;){if(i)return{kind:`early_exit`,exit:i};let e=N(t.paths.infoPath);if(e&&await U(e,t.transportPreference))return{kind:`ready`,info:e};if(i)return{kind:`early_exit`,exit:i};await _(100)}return{kind:`timeout`}}function mr(e){let t=hr(),n=t.useSrc?[`--experimental-strip-types`,t.srcPath]:[t.distPath],r={...process.env,AGENT_DEVICE_STATE_DIR:e.paths.baseDir,AGENT_DEVICE_DAEMON_SERVER_MODE:e.serverMode};b.mkdirSync(e.paths.baseDir,{recursive:!0});let i=b.openSync(e.paths.logPath,`a`),a=b.openSync(e.paths.logPath,`a`);try{return u(process.execPath,n,{env:r,stdio:[`ignore`,i,a]})}finally{b.closeSync(i),b.closeSync(a)}}function hr(){let e=me(),n=[x.join(e,`dist`,`src`,`internal`,`daemon.js`),x.join(e,`dist`,`src`,`daemon.js`)],r=n[0];if(r===void 0)throw new t(`COMMAND_FAILED`,`Daemon dist path list is empty`);let i=n.find(e=>b.existsSync(e))??r,a=x.join(e,`src`,`daemon.ts`),o=n.some(e=>b.existsSync(e)),s=b.existsSync(a);if(!o&&!s)throw new t(`COMMAND_FAILED`,`Daemon entry not found`,{distPaths:n,srcPath:a});return{root:e,distPath:i,distPaths:n,srcPath:a,useSrc:(process.execArgv.includes(`--experimental-strip-types`)||!o)&&s}}function gr(){let e=hr();return pe(e.useSrc?e.srcPath:e.distPath,e.root)}function _r(e){return e.error?`daemon process ${e.pid} failed to start: ${e.error}`:e.signal?`daemon process ${e.pid} exited before readiness with signal ${e.signal}`:`daemon process ${e.pid} exited before readiness with code ${e.exitCode??0}`}function vr(e){try{if(!b.existsSync(e))return;let t=b.statSync(e);if(t.size<=0)return;let n=Math.min(t.size,64e3),r=b.openSync(e,`r`);try{let e=Buffer.alloc(n);b.readSync(r,e,0,n,t.size-n);let i=e.toString(`utf8`).trim();return i.length>0?i:void 0}finally{b.closeSync(r)}}catch{return}}function yr(e){if(!e)return;let n;try{n=new URL(e)}catch(n){throw new t(`INVALID_ARGS`,`Invalid daemon base URL`,{daemonBaseUrl:e},n instanceof Error?n:void 0)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw new t(`INVALID_ARGS`,`Daemon base URL must use http or https`,{daemonBaseUrl:e});return n.toString().replace(/\/+$/,``)}function br(e,n){if(!e)return;let r=new URL(e).hostname;if(!xr(r)&&!(typeof n==`string`&&n.trim().length>0))throw new t(`INVALID_ARGS`,`Remote daemon base URL for non-loopback hosts requires daemon authentication`,{daemonBaseUrl:e,hint:`Provide --daemon-auth-token or AGENT_DEVICE_DAEMON_AUTH_TOKEN when using a non-loopback remote daemon URL.`})}function xr(e){let t=e.trim().toLowerCase().replace(/^\[(.*)\]$/,`$1`);return t===`localhost`?!0:T.isIPv4(t)?K.check(t,`ipv4`):T.isIPv6(t)?K.check(t,`ipv6`):!1}async function Sr(e,t={}){let n=e.meta?.requestId??i(),r=!!(e.meta?.debug||e.flags?.verbose),a=Xn(e),s=xn(e),l=await o(`daemon_startup`,async()=>await nr(a),{requestId:n,session:e.session}),u=l.info,d=await Mt(e,u);Cr(e.command);let f={...e,positionals:d.positionals,flags:d.flags,token:u.token,meta:{...e.meta??{},requestId:n,debug:r,includeCost:e.meta?.includeCost,cwd:e.meta?.cwd,sessionExplicit:e.meta?.sessionExplicit,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,lockPolicy:e.meta?.lockPolicy,lockPlatform:e.meta?.lockPlatform,...d.uploadedArtifactId?{uploadedArtifactId:d.uploadedArtifactId}:{},...d.clientArtifactPaths?{clientArtifactPaths:d.clientArtifactPaths}:{},...d.installSource?{installSource:d.installSource}:{}}};c({level:`info`,phase:`daemon_request_prepare`,data:{requestId:n,command:e.command,session:e.session}});try{return await o(`daemon_request`,async()=>await Vn(u,f,a.transportPreference,a.paths,s,t),{requestId:n,command:e.command})}finally{await dr(e,l,a)}}function Cr(e){!wr(e)||process.stderr.isTTY!==!0||process.env.CI||process.stderr.write(e===p.reinstall?`Reinstalling...
2
+ `:`Installing...
3
+ `)}function wr(e){return e===p.install||e===p.reinstall||e===d.installSource}const Tr=8081;function Er(e){return typeof e==`string`&&e.trim()?Re(e.trim()):``}function q(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function J(e,t,n){return he(e,{env:t,cwd:n})}function Dr(e){try{return b.accessSync(e,b.constants.F_OK),!0}catch{return!1}}function Or(e){try{return b.statSync(e).isDirectory()}catch{return!1}}function kr(e){let n=x.join(e,`package.json`),r=He(e);if(!r)throw new t(`INVALID_ARGS`,`package.json not found at ${n}`);return r}function Ar(e){return Dr(x.join(e,`pnpm-lock.yaml`))?{command:`pnpm`,installArgs:[`install`]}:Dr(x.join(e,`yarn.lock`))?{command:`yarn`,installArgs:[`install`]}:{command:`npm`,installArgs:[`install`]}}function jr(e,t){return t===`auto`?Ve(kr(e))===`expo`?`expo`:`react-native`:t}function Y(e,t,n){if(e==null||e===``)return t;let r=Number.parseInt(String(e),10);return Number.isInteger(r)?Math.max(r,n):t}function Mr(e,n){if(e==null||e===``)return n;let r=Number.parseInt(String(e),10);if(!Number.isInteger(r)||r<1||r>65535)throw new t(`INVALID_ARGS`,`Invalid Metro port: ${String(e)}. Use 1-65535.`);return r}function Nr(e,t){return{platform:t,bundleUrl:ze(e,t)}}function Pr(e,t){return{platform:t,metroHost:q(e?.metro_host),metroPort:e?.metro_port,bundleUrl:q(e?.metro_bundle_url),launchUrl:q(e?.launch_url)}}function Fr(e,t){if(Or(x.join(e,`node_modules`)))return{installed:!1};let n=Ar(e);return a(n.command,n.installArgs,{cwd:e,env:t}),{installed:!0,packageManager:n.command}}async function Ir(e){await _(e)}async function Lr(e,n,r={}){try{let t=await fetch(e,{headers:r,signal:AbortSignal.timeout(n)});return{ok:t.ok,status:t.status,body:await t.text()}}catch(r){throw r instanceof Error&&r.name===`TimeoutError`?new t(`COMMAND_FAILED`,`Timed out fetching ${e} after ${n}ms`):r}}async function Rr(e,t){try{let n=await Lr(e,t);return n.ok&&n.body.includes(`packager-status:running`)}catch{return!1}}function zr(e,t){let n=new URL(`${e.scheme}://localhost`);return n.hostname=e.host,n.port=String(e.port),n.pathname=t,n.toString()}function Br(e){let t=q(e);if(!t)return`/reload`;let n=new URL(t).pathname.replace(/\/+$/,``);return n.endsWith(`/index.bundle`)?`${n.slice(0,-13)}/reload`:`/reload`}function Vr(e,t,n){return q(e.metroHost)??(t?void 0:q(e.runtime?.metroHost))??(n?void 0:`localhost`)}function Hr(e,t,n){if(e.metroPort!==void 0)return Mr(e.metroPort,Tr);if(!t)return e.runtime?.metroPort??(n?void 0:Tr)}function Ur(e){let n=q(e.bundleUrl),r=n??e.runtime?.bundleUrl,i=!!n,a=!!q(r),o=Ue({metroHost:Vr(e,i,a),metroPort:Hr(e,i,a),bundleUrl:r});if(!o)throw new t(`INVALID_ARGS`,`Unable to resolve Metro host and port for reload.`);return zr(o,Br(r))}function Wr(e,t,n){return e===`expo`?{command:`npx`,installArgs:[`expo`,`start`,`--host`,`lan`,`--port`,String(t)]}:{command:`npx`,installArgs:[`react-native`,`start`,`--host`,n,`--port`,String(t)]}}function Gr(e,n,r,i,a,o){let c=Wr(n,r,i);b.mkdirSync(x.dirname(a),{recursive:!0});let l=b.openSync(a,`a`),u=0;try{u=s(c.command,c.installArgs,{cwd:e,env:o,stdio:[`ignore`,l,l]})}finally{b.closeSync(l)}if(!Number.isInteger(u)||u<=0)throw new t(`COMMAND_FAILED`,`Failed to start Metro. Expected a detached child PID.`);return{pid:u}}async function Kr(e){if(!(!Number.isInteger(e)||e<=0)){try{process.kill(e,`SIGTERM`)}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return;throw e}if(!await ge(e,1e3)){try{process.kill(e,`SIGKILL`)}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return;throw e}await ge(e,1e3)}}}function qr(e,t){return{Authorization:`Bearer ${t}`,"Content-Type":`application/json`,...e.includes(`ngrok`)?{"ngrok-skip-browser-warning":`1`}:{}}}function X(e,n){let r=new t(`COMMAND_FAILED`,e);return r.retryable=n,r}function Jr(e,t){return!!(e>=500||e===408||e===425||e===429||JSON.stringify(t).includes(`Metro companion is not connected`))}function Yr(e){return!!(e&&typeof e==`object`&&`retryable`in e&&e.retryable===!0)}async function Xr(e){let t;try{t=await fetch(`${e.baseUrl}/api/metro/bridge`,{method:`POST`,headers:qr(e.baseUrl,e.bearerToken),body:JSON.stringify({...e.scope,...e.runtime?{ios_runtime:e.runtime}:{},timeout_ms:e.timeoutMs}),signal:AbortSignal.timeout(e.timeoutMs)})}catch(t){throw t instanceof Error&&t.name===`TimeoutError`?X(`/api/metro/bridge timed out after ${e.timeoutMs}ms calling ${e.baseUrl}/api/metro/bridge`,!0):X(t instanceof Error?t.message:String(t),!0)}let n=Zr(await t.text(),t.status,e.baseUrl);if(!t.ok)throw X(`/api/metro/bridge failed (${t.status}): ${JSON.stringify(n)}`,Jr(t.status,n));return $r(n)}function Zr(e,t,n){if(!e)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Expected a JSON object`);return t}catch(r){let i=e.slice(0,200);throw X(`/api/metro/bridge returned invalid JSON (${t}) from ${n}: ${r instanceof Error?r.message:String(r)}. body=${JSON.stringify(i)}`,Jr(t,e))}}function Qr(e){return{enabled:e.enabled,baseUrl:e.base_url,statusUrl:e.status_url??``,bundleUrl:e.bundle_url??``,iosRuntime:Pr(e.ios_runtime,`ios`),androidRuntime:Pr(e.android_runtime,`android`),upstream:{bundleUrl:e.upstream.bundle_url??``,host:e.upstream.host??``,port:e.upstream.port??0,statusUrl:e.upstream.status_url??``},probe:{reachable:e.probe.reachable,statusCode:e.probe.status_code,latencyMs:e.probe.latency_ms,detail:e.probe.detail}}}function $r(e){let t=e.data??e;if(!t||typeof t!=`object`||Array.isArray(t))throw X(`/api/metro/bridge returned malformed descriptor: Expected a JSON object.`,!1);try{return Qr(t)}catch(e){throw X(`/api/metro/bridge returned malformed descriptor: ${e instanceof Error?e.message:String(e)}`,!1)}}function Z(e,t,n,r,i){let a=[`Metro bridge is required for this run but could not be configured via ${e}/api/metro/bridge.`];return t&&a.push(`bridgeError=${t}`),n?.probe.reachable===!1&&a.push(`bridgeProbe=${n.probe.detail||`unreachable (status ${n.probe.statusCode||0})`}`),r&&r!==t&&a.push(`initialBridgeError=${r}`),i&&a.push(`metroCompanionLog=${i}`),a.join(` `)}function ei(e,n){if(!n?.iosRuntime.bundleUrl)throw new t(`COMMAND_FAILED`,Z(e,`bridge descriptor is missing ios_runtime.metro_bundle_url`,n))}function ti(e,n,r){let i=n||q(r.AGENT_DEVICE_METRO_BEARER_TOKEN)||``,a=i||e&&q(r.AGENT_DEVICE_DAEMON_AUTH_TOKEN)||``;if(e&&!a)throw new t(`INVALID_ARGS`,`metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_METRO_BEARER_TOKEN or AGENT_DEVICE_DAEMON_AUTH_TOKEN.`);if(!e&&i)throw new t(`INVALID_ARGS`,`metro prepare requires --proxy-base-url when proxy auth is provided.`);return{proxyEnabled:!!(e&&a),proxyBaseUrl:e,proxyBearerToken:a}}function ni(e){if(!e?.tenantId||!e.runId||!e.leaseId)throw new t(`INVALID_ARGS`,`metro prepare with proxy requires tenantId, runId, and leaseId bridge scope.`);return e}function ri(e,n){if(!(e||n))throw new t(`INVALID_ARGS`,`metro prepare requires --public-base-url <url> or --proxy-base-url <url>.`)}function ii(e,t,n){return e.runtimeFilePath?J(e.runtimeFilePath,t,n):null}function ai(e,t,n,r){return J(e.logPath??x.join(r,`.agent-device`,`metro.log`),t,n)}function oi(e){let t=e.env??process.env,n=process.cwd(),r=J(e.projectRoot??n,t,n),i=Er(e.publicBaseUrl),a=Er(e.proxyBaseUrl);ri(i,a);let{proxyEnabled:o,proxyBaseUrl:s,proxyBearerToken:c}=ti(a,q(e.proxyBearerToken)??``,t);return{env:t,projectRoot:r,kind:jr(r,e.kind??`auto`),metroPort:Mr(e.metroPort??8081,8081),listenHost:q(e.listenHost)??`0.0.0.0`,statusHost:q(e.statusHost)??`127.0.0.1`,publicBaseUrl:i,proxyBaseUrl:s,proxyBearerToken:c,bridgeScope:o?ni(e.bridgeScope):null,startupTimeoutMs:Y(e.startupTimeoutMs,18e4,3e4),probeTimeoutMs:Y(e.probeTimeoutMs,1e4,1e3),reuseExisting:e.reuseExisting??!0,installProjectDeps:e.installDependenciesIfNeeded??!0,runtimeFilePath:ii(e,t,n),logPath:ai(e,t,n,r)}}async function si(e,t,n){let r=Date.now()+t;for(;Date.now()<r;){let t=r-Date.now();if(await Rr(e,Math.min(n,Math.max(t,1))))return!0;let i=Math.min(500,Math.max(r-Date.now(),0));i>0&&await Ir(i)}return!1}async function ci(e){let n=Date.now()+e.startupTimeoutMs,r=null,i=null;for(;Date.now()<n;){try{let t=await Xr({baseUrl:e.baseUrl,bearerToken:e.bearerToken,scope:e.scope,runtime:e.runtime,timeoutMs:e.probeTimeoutMs});if(t.probe.reachable!==!1)return t;r=t,i=null}catch(n){if(i=n instanceof Error?n.message:String(n),!Yr(n))throw new t(`COMMAND_FAILED`,Z(e.baseUrl,i,r,e.initialBridgeError,e.companionLogPath),void 0,n)}let a=Math.min(1e3,Math.max(n-Date.now(),0));a>0&&await Ir(a)}throw new t(`COMMAND_FAILED`,Z(e.baseUrl,i,r,e.initialBridgeError,e.companionLogPath))}async function li(e){let n=`http://${e.statusHost}:${e.metroPort}/status`;if(e.reuseExisting&&await Rr(n,e.probeTimeoutMs))return{started:!1,reused:!0,pid:0,statusUrl:n};let r=Gr(e.projectRoot,e.kind,e.metroPort,e.listenHost,e.logPath,e.env);if(await si(n,e.startupTimeoutMs,e.probeTimeoutMs))return{started:!0,reused:!1,pid:r.pid,statusUrl:n};throw await Kr(r.pid).catch(()=>{}),new t(`COMMAND_FAILED`,`Metro did not become ready at ${n} within ${e.startupTimeoutMs}ms. Check ${e.logPath}.`,{logPath:e.logPath})}async function ui(e,t){let n=t.bridgeScope;if(!n)return null;let r=null,i=null;try{r=await Xr({baseUrl:t.proxyBaseUrl,bearerToken:t.proxyBearerToken,scope:n,timeoutMs:t.probeTimeoutMs})}catch(e){if(!Yr(e))throw e;i=e instanceof Error?e.message:String(e)}return(!r||r.probe.reachable===!1)&&(r=await di(e,t,n,r,i)),ei(t.proxyBaseUrl,r),r}async function di(e,n,r,i,a){let o;try{o=(await Be({projectRoot:n.projectRoot,serverBaseUrl:n.proxyBaseUrl,bearerToken:n.proxyBearerToken,bridgeScope:r,localBaseUrl:`http://${n.statusHost}:${n.metroPort}`,launchUrl:q(e.launchUrl),profileKey:q(e.companionProfileKey),consumerKey:q(e.companionConsumerKey),env:n.env})).logPath}catch(e){throw new t(`COMMAND_FAILED`,Z(n.proxyBaseUrl,e instanceof Error?e.message:String(e),i,a),void 0,e)}try{return await ci({baseUrl:n.proxyBaseUrl,bearerToken:n.proxyBearerToken,scope:r,probeTimeoutMs:n.probeTimeoutMs,startupTimeoutMs:n.startupTimeoutMs,initialBridgeError:a,companionLogPath:o})}catch(e){throw e instanceof Error?e:Error(String(e))}}function fi(e){return{baseIosRuntime:e?Nr(e,`ios`):{platform:`ios`},baseAndroidRuntime:e?Nr(e,`android`):{platform:`android`}}}function pi(e,t){e&&(b.mkdirSync(x.dirname(e),{recursive:!0}),b.writeFileSync(e,JSON.stringify(t,null,2)))}async function mi(e={}){let t=oi(e),n=t.installProjectDeps?Fr(t.projectRoot,t.env):{installed:!1},r=await li(t),{baseIosRuntime:i,baseAndroidRuntime:a}=fi(t.publicBaseUrl),o=await ui(e,t),s=o?.iosRuntime??i,c=o?.androidRuntime??a,l={projectRoot:t.projectRoot,kind:t.kind,dependenciesInstalled:n.installed,packageManager:n.packageManager??null,started:r.started,reused:r.reused,pid:r.pid,logPath:t.logPath,statusUrl:r.statusUrl,runtimeFilePath:t.runtimeFilePath,iosRuntime:s,androidRuntime:c,bridge:o};return pi(t.runtimeFilePath,l),l}async function hi(e={}){let n=Y(e.timeoutMs,1e4,1e3),r=Ur(e),i=await Lr(r,n);if(!i.ok)throw new t(`COMMAND_FAILED`,`Metro reload failed (${i.status}).`,{reloadUrl:r,status:i.status,body:i.body,hint:`Verify Metro is running and the target React Native app is connected to this Metro instance.`});return{reloaded:!0,reloadUrl:r,status:i.status,body:i.body}}const gi={...Ae(),batch:je(_i)};function _i(e,n,r){let i=gi[e];if(!i)throw Error(`Missing daemon writer for batch command: ${e}`);let a=We(e);if(!a)throw Error(`Missing command metadata for batch command: ${e}`);try{return yi(i,a,a.readInput(n))}catch(n){throw new t(`INVALID_ARGS`,`Batch step ${r} ${e} input is invalid: ${n instanceof Error?n.message:String(n)}`,void 0,n)}}function vi(e,t){let n=gi[e];if(!n)throw Error(`Missing daemon writer for command: ${e}`);return yi(n,We(e),t)}function yi(e,t,n){let r=e(n);return{...r,...t?{metadataFlags:ke(t,r.options)}:{}}}function bi(e){throw new t(n(e.code),e.message,{...e.details??{},hint:e.hint,diagnosticId:e.diagnosticId,logPath:e.logPath,retriable:e.retriable,supportedOn:e.supportedOn})}var xi=e({createAgentDeviceClient:()=>Si});function Si(e={},t={}){let n=t.transport??Sr,i=t=>r(t.responseLevel??e.responseLevel),a=async(t,r=[],i={},a)=>{let o=$(e,i),s=await n({session:we(o.session),command:t,positionals:r,flags:Me(o,a),runtime:o.runtime,meta:De(o)});return s.ok||bi(s.error),s.data??{}},o=async(e={})=>{let t=await a(d.sessionList,[],e);return(Array.isArray(t.sessions)?t.sessions:[]).map(Pe)},s=async(e,t={})=>{let n=vi(e,t);return await a(n.command,n.positionals,n.options,n.metadataFlags)},c=(t={})=>we($(e,t).session);return{command:{wait:async e=>await s(`wait`,e),alert:async(e={})=>await s(`alert`,e),appState:async(e={})=>await s(`appstate`,e),back:async(e={})=>await s(`back`,e),home:async(e={})=>await s(`home`,e),rotate:async e=>await s(`rotate`,e),appSwitcher:async(e={})=>await s(`app-switcher`,e),keyboard:async(e={})=>await s(`keyboard`,e),clipboard:async e=>await s(`clipboard`,e),reactNative:async e=>await s(`react-native`,e),doctor:async(e={})=>await s(`doctor`,e),prepare:async e=>await s(`prepare`,e),viewport:async e=>await s(`viewport`,e)},devices:{list:async(e={})=>{let t=await s(`devices`,e);return(Array.isArray(t.devices)?t.devices:[]).map(Ie)},capabilities:async(e={})=>{let t=await s(`capabilities`,e),n=Array.isArray(t.availableCommands)?t.availableCommands.filter(e=>typeof e==`string`):[];return{device:Ie(t.device),availableCommands:n}},boot:async(e={})=>await s(`boot`,e),shutdown:async(e={})=>await s(`shutdown`,e)},sessions:{list:async(e={})=>await o(e),stateDir:async(t={})=>m($(e,t).stateDir??process.env.AGENT_DEVICE_STATE_DIR).baseDir,close:async(e={})=>{let t=c(e),n=await s(`close`,e);return{session:t,shutdown:Se(n.shutdown),provider:Q(n.provider),identifiers:{session:t}}},artifacts:async(e={})=>await s(`artifacts`,e)},apps:{install:async e=>Ne(await s(`install`,e),c(e)),reinstall:async e=>Ne(await s(`reinstall`,e),c(e)),installFromSource:async e=>Oe(await s(`install-from-source`,e),c(e)),list:async(e={})=>{let t=await s(`apps`,e);return Array.isArray(t.apps)?t.apps.filter(e=>typeof e==`string`):[]},open:async e=>{let t=c(e),n=await s(`open`,e),r=Te(n),i=v(n,`appBundleId`),a=i;return{session:t,sessionStateDir:v(n,`sessionStateDir`),appName:v(n,`appName`),appBundleId:i,appId:a,startup:Ee(n.startup),runtime:be(n.runtime),device:r,identifiers:{session:t,deviceId:r?.id,deviceName:r?.name,udid:r?.ios?.udid,serial:r?.android?.serial,appId:a,appBundleId:i}}},close:async(e={})=>{let t=c(e),n=await s(`close`,e);return{session:t,closedApp:e.app,shutdown:Se(n.shutdown),identifiers:{session:t}}},push:async e=>await s(`push`,e),triggerEvent:async e=>await s(`trigger-app-event`,e)},materializations:{release:async e=>Fe(await a(d.releaseMaterializedPaths,[],{...e,materializationId:e.materializationId}))},leases:{allocate:async e=>Ti(await a(d.leaseAllocate,[],{...e,leaseId:void 0})),heartbeat:async e=>Ti(await a(d.leaseHeartbeat,[],e)),release:async e=>{let t=await a(d.leaseRelease,[],e);return{released:t.released===!0,provider:Q(t.provider)}}},metro:{prepare:async t=>await mi({projectRoot:t.projectRoot??e.cwd,kind:t.kind,publicBaseUrl:t.publicBaseUrl,proxyBaseUrl:t.proxyBaseUrl,proxyBearerToken:t.bearerToken,bridgeScope:t.bridgeScope,launchUrl:t.launchUrl,companionProfileKey:t.companionProfileKey,companionConsumerKey:t.companionConsumerKey,metroPort:t.port,listenHost:t.listenHost,statusHost:t.statusHost,startupTimeoutMs:t.startupTimeoutMs,probeTimeoutMs:t.probeTimeoutMs,reuseExisting:t.reuseExisting,installDependenciesIfNeeded:t.installDependenciesIfNeeded,runtimeFilePath:t.runtimeFilePath,logPath:t.logPath}),reload:async(t={})=>await hi({metroHost:t.metroHost,metroPort:t.metroPort,bundleUrl:t.bundleUrl,runtime:e.runtime,timeoutMs:t.timeoutMs})},capture:{snapshot:async(e={})=>{let t=c(e),n=await s(`snapshot`,e);return i(e)?n:Ci(n,t)},screenshot:async(e={})=>{let t=c(e),n=await s(`screenshot`,e);if(i(e))return n;let r=le(n);return{path:y(n,`path`),overlayRefs:r?.overlayRefs,identifiers:{session:t}}},diff:async e=>await s(`diff`,e)},interactions:{click:async e=>await s(`click`,e),press:async e=>await s(`press`,e),longPress:async e=>await s(`longpress`,e),swipe:async e=>await s(`swipe`,e),pan:async e=>await s(`gesture-pan`,e),fling:async e=>await s(`gesture-fling`,e),swipeGesture:async e=>await s(`gesture-swipe`,e),focus:async e=>await s(`focus`,e),type:async e=>await s(`type`,e),fill:async e=>await s(`fill`,e),scroll:async e=>await s(`scroll`,e),pinch:async e=>await s(`gesture-pinch`,e),rotateGesture:async e=>await s(`gesture-rotate`,e),transformGesture:async e=>await s(`gesture-transform`,e),get:async e=>await s(`get`,e),is:async e=>await s(`is`,e),find:async e=>await s(`find`,e)},replay:{run:async e=>await s(`replay`,e),test:async e=>await s(`test`,e)},batch:{run:async e=>await s(`batch`,e)},observability:{perf:async(e={})=>await s(`perf`,e),logs:async(e={})=>await s(`logs`,e),network:async(e={})=>await s(`network`,e),audio:async(e={})=>await s(`audio`,e)},debug:{symbols:async t=>{let{symbolicateCrashArtifact:n}=await import(`./debug-symbols.js`);return n({cwd:t.cwd??e.cwd,...t})}},recording:{record:async e=>await s(`record`,e),trace:async e=>await s(`trace`,e)},settings:{update:async e=>await s(`settings`,e)}}}function Ci(e,t){let n=v(e,`appBundleId`);return{nodes:xe(e.nodes),truncated:e.truncated===!0,appName:v(e,`appName`),appBundleId:n,...wi(e),identifiers:{session:t,appId:n,appBundleId:n}}}function wi(e){let t=Q(e.visibility),n=Q(e.unchanged),r=ce(e.snapshotDiagnostics);return{...t?{visibility:t}:{},...ye(e),...n?{unchanged:n}:{},...r?{snapshotDiagnostics:r}:{}}}function Q(e){return Le(e)?e:void 0}function $(e,t){return{...e,...t}}function Ti(e){let t=e.lease;if(!Le(t))throw Error(`Invalid lease response from daemon`);return{leaseId:y(t,`leaseId`),tenantId:y(t,`tenantId`),runId:y(t,`runId`),backend:y(t,`backend`),leaseProvider:v(t,`leaseProvider`),clientId:v(t,`clientId`),deviceKey:v(t,`deviceKey`),createdAt:typeof t.createdAt==`number`?t.createdAt:void 0,heartbeatAt:typeof t.heartbeatAt==`number`?t.heartbeatAt:void 0,expiresAt:typeof t.expiresAt==`number`?t.expiresAt:void 0}}export{Xn as a,Ze as c,nr as i,E as l,Si as n,Xe as o,Sr as r,D as s,xi as t};
@@ -0,0 +1 @@
1
+ import{f as e}from"./sdk-batch.js";import{o as t}from"./registry.js";const n=t(),r=new Map(n.map(e=>[e.name,e]));function i(){return[...n]}function a(){return e().map(e=>{let t=s(e);if(!t)throw Error(`Missing command metadata for MCP-exposed command: ${e}`);return t})}function o(e){return r.has(e)}function s(e){return r.get(e)}export{a as i,o as n,i as r,s as t};
@@ -0,0 +1,22 @@
1
+ import{f as e,m as t,r as n}from"./registry.js";import{r}from"./command-metadata.js";const i={cdp:{usageOverride:`cdp [...args]`,listUsageOverride:`cdp`,helpDescription:`Run CDP commands for React Native diagnostics, JS heap usage, heap snapshots, and leak analysis`,summary:`Inspect React Native CDP targets, JS heap growth, heap snapshots, retainers, and leak signals`,positionalArgs:[`args?`],allowsExtraPositionals:!0,supportedFlags:e},auth:{usageOverride:`auth status|login|logout`,listUsageOverride:`auth`,helpDescription:`Manage cloud login state used by remote daemon and cloud device workflows.`,summary:`Manage cloud login state used by remote daemon and cloud device workflows`,positionalArgs:[`status|login|logout`],supportedFlags:[`remoteConfig`,`stateDir`]},connect:{usageOverride:`connect [cloud|proxy|browserstack|aws-device-farm] [--remote-config <path>] [--daemon-base-url <url>] [--tenant <id>] [--run-id <id>] [--lease-id <id>] [--lease-backend <backend>] [--force] [--no-login]`,helpDescription:`Connect to a remote daemon, authenticate when needed, and save remote session state. AGENT_DEVICE_CLOUD_BASE_URL is the bridge/control-plane API origin; use AGENT_DEVICE_DAEMON_AUTH_TOKEN=adc_live_... for CI/service-token automation.`,listUsageOverride:`connect`,summary:`Attach CLI commands to a saved remote daemon/cloud lease; inspect for remote runs, tenants, or service-token CI`,allowedFlags:[`remoteConfig`,`daemonBaseUrl`,`tenant`,`runId`,`leaseId`,`leaseBackend`,`providerApp`,`providerOsVersion`,`providerProject`,`providerBuild`,`providerSessionName`,`awsProjectArn`,`awsDeviceArn`,`awsAppArn`,`awsRegion`,`awsInteractionMode`,`force`,`noLogin`],supportedFlags:[`stateDir`,`daemonAuthToken`,`session`,`platform`,`device`,...t,`launchUrl`]},connection:{usageOverride:`connection status`,listUsageOverride:`connection`,helpDescription:`Inspect active remote connection state`,summary:`Inspect the active saved remote connection before assuming commands are local`,positionalArgs:[`status`],supportedFlags:[`remoteConfig`,`stateDir`,`session`]},disconnect:{helpDescription:`Disconnect remote daemon state, stop owned Metro companion, and release lease`,listUsageOverride:`disconnect`,summary:`Clear remote connection state, stop owned Metro companions, and release remote leases`,allowedFlags:[`shutdown`],supportedFlags:[`remoteConfig`,`stateDir`,`session`]},mcp:{helpDescription:`Start the official stdio MCP server. It exposes structured command tools backed by the agent-device client.`,summary:`Start MCP server`},proxy:{usageOverride:`proxy [--host <host>] [--port <port>] [--daemon-auth-token <token>] [--state-dir <path>]`,listUsageOverride:`proxy`,helpDescription:`Expose the local daemon HTTP contract through a tunnel-friendly reverse proxy.
2
+
3
+ Run this on the host that has access to simulators/devices, expose the printed local proxy URL through a tunnel, then point another machine at the tunnel URL with connect proxy.
4
+
5
+ The proxy starts or reuses a local HTTP daemon, accepts /health, /rpc, /upload and resumable /upload/* routes, and /artifacts plus /artifacts/*, and also accepts the same routes under /agent-device/*. Health is unauthenticated for reachability probes. Other routes require the generated bearer token printed at startup, or the explicit --daemon-auth-token value when provided. The proxy rewrites authorized client requests to the upstream daemon token instead of exposing the local daemon token.
6
+
7
+ Use the /agent-device base path when connecting through cloudflared, ngrok, or another shared origin. Treat the bearer token as a secret; anyone with it can control the proxied daemon. This direct proxy flow does not use agent-device auth.
8
+
9
+ Examples:
10
+ agent-device proxy --port 4310
11
+ cloudflared tunnel --url http://127.0.0.1:4310
12
+ agent-device connect proxy --daemon-base-url https://example.trycloudflare.com/agent-device --daemon-auth-token <token>`,summary:`Expose a local daemon through cloudflared, ngrok, or another HTTP tunnel`,allowedFlags:[`proxyHost`,`proxyPort`,`daemonAuthToken`,`stateDir`]},"react-devtools":{usageOverride:`react-devtools [...args]`,listUsageOverride:`react-devtools`,helpDescription:`Run pinned agent-react-devtools commands for React Native performance profiling, component trees, props/state/hooks, and render analysis`,summary:`Inspect React Native components, props, hooks, errors, slow renders, and rerender profiles`,positionalArgs:[`args?`],allowsExtraPositionals:!0,supportedFlags:e},web:{usageOverride:`web setup | web doctor`,listUsageOverride:`web setup|doctor`,helpDescription:`Install and inspect the managed web automation backend used by --platform web.
13
+
14
+ First-run flow:
15
+ agent-device web setup
16
+ agent-device open "https://example.com" --platform web
17
+ agent-device snapshot -i --platform web
18
+ agent-device close --platform web
19
+
20
+ Runtime web commands do not install the backend implicitly. If the managed backend is missing, run agent-device web setup. The backend is resolved only from the managed install in the effective agent-device state dir.
21
+
22
+ Use web setup to install or reuse the pinned backend. Use web doctor after setup to verify browser backend health.`,summary:`Manage web automation backend`,positionalArgs:[`setup|doctor`],supportedFlags:[`stateDir`]}},a=n();function o(e){return Object.hasOwn(i,e)?i[e]:void 0}function s(e){return Object.hasOwn(a,e)?a[e]:void 0}const c=new Map(r().map(t=>[t.name,{helpDescription:t.description,supportedFlags:e}]));function l(e){if(e)return d(e)}function u(e){let t=d(e);if(!t)throw Error(`Missing command schema for ${e}`);return t}function d(e){let t=o(e);if(t)return t;let n=c.get(e),r=s(e);if(n)return r?{...n,...r}:n}function f(e,t){let n=l(e);if(!n?.defaults)return!1;let r=!1;for(let[e,i]of Object.entries(n.defaults))t[e]===void 0&&(t[e]=i,r=!0);return r}export{u as n,l as r,f as t};
@@ -1 +1 @@
1
- import{listCommandFamilyDefinitions as n}from"./2948.js";let a=new Map(n().map(n=>[n.name,n]));async function e(n,e,r){var t;return await (t=e,a.get(t)).invoke(n,r)}export{e as runCommand};
1
+ import{t as e}from"./rolldown-runtime.js";import{a as t}from"./registry.js";var n=e({runCommand:()=>a});const r=t(),i=new Map(r.map(e=>[e.name,e]));async function a(e,t,n){return await o(t).invoke(e,n)}function o(e){return i.get(e)}export{a as n,n as t};
@@ -1,213 +1,2 @@
1
- export declare function centerOfRect(rect: Rect): Point;
2
-
3
- declare const DAEMON_LOCK_POLICIES: readonly ['reject', 'strip'];
4
-
5
- declare type DaemonArtifact = {
6
- field: string;
7
- artifactId?: string;
8
- fileName?: string;
9
- localPath?: string;
10
- path?: string;
11
- };
12
-
13
- export declare type DaemonError = {
14
- code: string;
15
- message: string;
16
- hint?: string;
17
- diagnosticId?: string;
18
- logPath?: string;
19
- details?: Record<string, unknown>;
20
- /**
21
- * Machine-readable typed-error signals (Phase 2). Additive: present only when
22
- * derivable, so the default error wire shape is unchanged.
23
- *
24
- * `retriable` flags a transient failure an agent should retry (vs. a
25
- * deterministic one where a retry is wasted). `supportedOn` lists the platform
26
- * families that DO support the command (derived from the capability matrix),
27
- * surfaced on platform-mismatch errors so an agent self-corrects without a
28
- * wasted round-trip.
29
- */
30
- retriable?: boolean;
31
- supportedOn?: string;
32
- };
33
-
34
- export declare type DaemonInstallSource = {
35
- kind: 'url';
36
- url: string;
37
- headers?: Record<string, string>;
38
- } | {
39
- kind: 'path';
40
- path: string;
41
- } | ({
42
- kind: 'github-actions-artifact';
43
- owner: string;
44
- repo: string;
45
- } & ({
46
- artifactId: number;
47
- } | {
48
- runId: number;
49
- artifactName: string;
50
- } | {
51
- artifactName: string;
52
- }));
53
-
54
- declare type DaemonLockPolicy = (typeof DAEMON_LOCK_POLICIES)[number];
55
-
56
- export declare type DaemonRequest = {
57
- token?: string;
58
- session?: string;
59
- command: string;
60
- positionals: string[];
61
- flags?: Record<string, unknown>;
62
- runtime?: SessionRuntimeHints;
63
- meta?: DaemonRequestMeta;
64
- };
65
-
66
- declare type DaemonRequestMeta = {
67
- requestId?: string;
68
- debug?: boolean;
69
- includeCost?: boolean;
70
- responseLevel?: ResponseLevel;
71
- cwd?: string;
72
- sessionExplicit?: boolean;
73
- tenantId?: string;
74
- runId?: string;
75
- leaseId?: string;
76
- leaseTtlMs?: number;
77
- leaseBackend?: LeaseBackend;
78
- leaseProvider?: string;
79
- deviceKey?: string;
80
- clientId?: string;
81
- sessionIsolation?: SessionIsolationMode;
82
- uploadedArtifactId?: string;
83
- clientArtifactPaths?: Record<string, string>;
84
- installSource?: DaemonInstallSource;
85
- retainMaterializedPaths?: boolean;
86
- materializedPathRetentionMs?: number;
87
- materializationId?: string;
88
- lockPolicy?: DaemonLockPolicy;
89
- lockPlatform?: PlatformSelector;
90
- requestProgress?: 'replay-test' | 'command';
91
- };
92
-
93
- export declare type DaemonResponse = {
94
- ok: true;
95
- data?: DaemonResponseData;
96
- } | {
97
- ok: false;
98
- error: DaemonError;
99
- };
100
-
101
- export declare type DaemonResponseData = Record<string, unknown> & {
102
- artifacts?: DaemonArtifact[];
103
- cost?: ResponseCost;
104
- };
105
-
106
- export declare function defaultHintForCode(code: string): string | undefined;
107
-
108
- export declare type JsonRpcId = string | number | null;
109
-
110
- export declare type JsonRpcRequestEnvelope<TParams = unknown> = {
111
- jsonrpc?: string;
112
- id?: JsonRpcId;
113
- method?: string;
114
- params?: TParams;
115
- };
116
-
117
- declare const LEASE_BACKENDS: readonly ['ios-simulator', 'ios-instance', 'android-instance'];
118
-
119
- export declare type LeaseAllocatePayload = {
120
- token?: string;
121
- session?: string;
122
- tenantId?: string;
123
- tenant?: string;
124
- runId?: string;
125
- ttlMs?: number;
126
- backend?: LeaseBackend;
127
- leaseProvider?: string;
128
- deviceKey?: string;
129
- clientId?: string;
130
- };
131
-
132
- export declare type LeaseBackend = (typeof LEASE_BACKENDS)[number];
133
-
134
- export declare type LeaseHeartbeatPayload = {
135
- token?: string;
136
- session?: string;
137
- tenantId?: string;
138
- tenant?: string;
139
- runId?: string;
140
- leaseId?: string;
141
- ttlMs?: number;
142
- backend?: LeaseBackend;
143
- leaseProvider?: string;
144
- deviceKey?: string;
145
- clientId?: string;
146
- };
147
-
148
- export declare type LeaseReleasePayload = {
149
- token?: string;
150
- session?: string;
151
- tenantId?: string;
152
- tenant?: string;
153
- runId?: string;
154
- leaseId?: string;
155
- backend?: LeaseBackend;
156
- leaseProvider?: string;
157
- deviceKey?: string;
158
- clientId?: string;
159
- };
160
-
161
- declare type NormalizedError = {
162
- code: string;
163
- message: string;
164
- hint?: string;
165
- diagnosticId?: string;
166
- logPath?: string;
167
- details?: Record<string, unknown>;
168
- };
169
-
170
- export declare function normalizeError(err: unknown, context?: {
171
- diagnosticId?: string;
172
- logPath?: string;
173
- }): NormalizedError;
174
-
175
- declare const PLATFORM_SELECTORS: readonly ["apple", "android", "linux", "web", "ios", "macos"];
176
-
177
- declare type PlatformSelector = (typeof PLATFORM_SELECTORS)[number];
178
-
179
- declare type Point = {
180
- x: number;
181
- y: number;
182
- };
183
-
184
- declare type Rect = {
185
- x: number;
186
- y: number;
187
- width: number;
188
- height: number;
189
- };
190
-
191
- declare const RESPONSE_LEVELS: readonly ['digest', 'default', 'full'];
192
-
193
- declare type ResponseCost = {
194
- wallClockMs: number;
195
- runnerRoundTrips: number;
196
- nodeCount?: number;
197
- };
198
-
199
- declare type ResponseLevel = (typeof RESPONSE_LEVELS)[number];
200
-
201
- declare const SESSION_ISOLATION_MODES: readonly ['none', 'tenant'];
202
-
203
- declare type SessionIsolationMode = (typeof SESSION_ISOLATION_MODES)[number];
204
-
205
- export declare type SessionRuntimeHints = {
206
- platform?: 'ios' | 'android';
207
- metroHost?: string;
208
- metroPort?: number;
209
- bundleUrl?: string;
210
- launchUrl?: string;
211
- };
212
-
213
- export { }
1
+ import { D as centerOfRect, F as normalizeError, M as defaultHintForCode, a as DaemonRequest, d as JsonRpcRequestEnvelope, f as LeaseAllocatePayload, h as LeaseReleasePayload, m as LeaseHeartbeatPayload, n as DaemonError, o as DaemonResponse, p as LeaseBackend, r as DaemonInstallSource, s as DaemonResponseData, u as JsonRpcId, y as SessionRuntimeHints } from "./sdk-contracts.js";
2
+ export { type DaemonError, type DaemonInstallSource, type DaemonRequest, type DaemonResponse, type DaemonResponseData, type JsonRpcId, type JsonRpcRequestEnvelope, type LeaseAllocatePayload, type LeaseBackend, type LeaseHeartbeatPayload, type LeaseReleasePayload, type SessionRuntimeHints, centerOfRect, defaultHintForCode, normalizeError };
@@ -1 +1 @@
1
- export{centerOfRect}from"./6849.js";export{defaultHintForCode,normalizeError}from"./485.js";
1
+ import{B as e,L as t,O as n}from"./sdk-contracts.js";export{n as centerOfRect,t as defaultHintForCode,e as normalizeError};
@@ -1,3 +1,5 @@
1
- import e from"node:fs/promises";import t from"node:path";import{AppError as r}from"./485.js";import{isRecord as a}from"./1986.js";import{runCmd as n}from"./8875.js";let i=/^[0-9a-fA-F-]{32,36}$/;function s(e){if(e&&i.test(e))return e.replaceAll("-","").toUpperCase()}function o(e,t){return`${e.uuid}:${d(t)}`}function d(e){return`0x${e.toString(16)}`}function l(e){return"string"==typeof e&&e.length>0?e:void 0}function u(...e){for(let t of e){let e=l(t);if(e)return e}}function c(e){try{let t=JSON.parse(e);return a(t)?t:null}catch{return null}}function m(e){if("number"==typeof e&&Number.isSafeInteger(e))return e;if("string"==typeof e){let t=e.startsWith("0x")?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function f(e,t,r){var a;if(!Object.hasOwn(e,t))return;let n="bigint"==typeof(a=e[t])?a:"number"==typeof a&&Number.isSafeInteger(a)?BigInt(a):"string"!=typeof a?void 0:/^(?:0x[0-9a-fA-F]+|\d+)$/.test(a)?BigInt(a):void 0;if(void 0!==n)return n;h(r,t)}function h(e,t){throw new r("INVALID_ARGS",`Invalid ${e} numeric field: ${t}`,{hint:"Crash artifact numeric fields must be integer numbers or integer numeric strings."})}function p(e){return[...new Set(e)]}let y=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;async function g(e){return e.dsym&&e.searchPath?[v(e.cwd,e.dsym),...await w(v(e.cwd,e.searchPath))]:e.dsym?[v(e.cwd,e.dsym)]:e.searchPath?await w(v(e.cwd,e.searchPath)):[]}async function w(a){let n=[],i=0;async function s(o){if(!(n.length>=200)){if((i+=1)>1e4)throw new r("COMMAND_FAILED","debug symbols search-path scan exceeded bounds.",{searchPath:a,maxEntries:1e4,hint:"Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory."});if(!(await b(o,a)).isDirectory()){o===a&&function(e){throw new r("INVALID_ARGS",`debug symbols search path is not a directory: ${e}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}(a);return}if(o.endsWith(".dSYM"))return void n.push(o);for(let r of(await e.readdir(o,{withFileTypes:!0})))r.isDirectory()&&await s(t.join(o,r.name))}}return await s(a),n}async function b(t,a){try{return await e.stat(t)}catch{throw new r("INVALID_ARGS",`debug symbols search path does not exist: ${a}`,{hint:"Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly."})}}async function I(e,t){let a=(await Promise.all(p(e).map(e=>A(e,t)))).flat();if(0===a.length)throw new r("COMMAND_FAILED","No UUIDs found in dSYM bundle.",{hint:"Verify the path points to a built .dSYM bundle with DWARF contents."});return a}async function A(e,t){var a;await S(e);let i=await n(t,["--uuid",e],{timeoutMs:15e3,allowFailure:!0});if(0!==i.exitCode)throw new r("COMMAND_FAILED",`Failed to inspect dSYM UUIDs: ${e}`,{stderr:i.stderr,hint:"Verify the dSYM bundle is valid and readable."});return a=e,i.stdout.split("\n").flatMap(e=>{let t=e.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=s(t?.[1]);return t&&r?[{dsymPath:a,uuid:r,arch:t[2],binaryPath:t[3].trim()}]:[]})}async function S(t){let a=await e.stat(t).catch(()=>null);if(!(a?.isDirectory()&&t.endsWith(".dSYM")))throw new r("INVALID_ARGS",`Not a .dSYM bundle: ${t}`,{hint:"Pass the .dSYM bundle path, not the DWARF executable inside it."})}function v(e,r){return t.resolve(e,r)}function x(e,t){let r=`${t}:`,a=e.find(e=>e.trimStart().startsWith(r));return a&&a.slice(a.indexOf(":")+1).trim()||void 0}function M(e,t,r,a){return{index:e,image:t.name,address:d(r),symbol:a.get(o(t,r))?.text}}function $(e){var t;let r;return[(r=(t=e).topFrames.find(e=>e.symbol))?`Start with ${r.symbol} in ${r.image}; it is the first symbolicated frame captured on the crashed thread.`:t.topFrames.length>0?"No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.":void 0,e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}async function N(e,t,r){let a=new Map;for(let n of(function(e,t){let r=new Map;for(let a of e){let e=t.get(a.image.uuid);if(!e)continue;let n=`${a.image.uuid}:${e.dsym.binaryPath}`,i=r.get(n)??{...e,addresses:[]};i.addresses.push(a.address),r.set(n,i)}return r})(e,t).values())for(let e of(await _(r,n)))a.set(o(e.image,e.address),e);return a}async function _(e,t){var a,i,s,o;let l,u,c=p(t.addresses.map(d)),m=await n(e,(a=t,i=c,["-arch",a.image.arch??a.dsym.arch??"arm64","-o",a.dsym.binaryPath,"-l",d(a.image.base),...i]),{timeoutMs:3e4,allowFailure:!0});return 0!==m.exitCode&&function(e){throw new r("COMMAND_FAILED","atos failed while symbolicating crash frames.",{stderr:e,hint:"Verify the crash artifact and dSYM were produced from the same build and architecture."})}(m.stderr),s=t.image,o=c,u=(""===(l=m.stdout.split(/\r?\n/)).at(-1)&&l.pop(),l),o.map((e,t)=>{let r=u[t]?.trim();return{image:s,address:BigInt(e),text:!function(e,t){if(!e)return!1;let r=e.trim().toLowerCase();return!!r&&"??"!==r&&r!==t.toLowerCase()&&!r.startsWith("0x")}(r,e)?void 0:r}})}async function D(){return{dwarfdump:await F("dwarfdump"),atos:await F("atos")}}async function F(e){try{let t=await n("xcrun",["--find",e],{timeoutMs:5e3,allowFailure:!0}),r=t.stdout.trim();if(0===t.exitCode&&r.length>0)return r}catch{}throw new r("TOOL_MISSING",`Apple symbolication tool not found: ${e}`,{hint:"Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed."})}async function P(n){var i,d,w,b,A,S,v,_,F,P,U,Y,T,L,O,E,V,B,G,W,j,k,K,z,H,J,q,X;let Q,Z,ee,et,er,ea,en,ei,es,eo,ed;if(void 0!==n.action&&"symbols"!==n.action)throw new r("INVALID_ARGS","debug supports only the symbols workflow.",{hint:"Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>."});let el=n.cwd??process.cwd(),eu=R(el,n.artifact),ec=R(el,n.out??(d=eu,Z=(Q=t.extname(d))?d.slice(0,-Q.length):d,`${Z}-symbolicated${Q||".log"}`)),em=function(e){var r;let n,i=function(e){let t=c(e);if(t)return{payload:t};let r=e.indexOf("\n");if(-1===r)return null;let a=e.slice(0,r),n=c(e.slice(r+1));return n?{header:a,payload:n}:null}(e);if(!i)return null;let d=(Array.isArray(i.payload.usedImages)?i.payload.usedImages:[]).flatMap((e,r)=>(function(e,r){if(!a(e))return[];let n=s(l(e.uuid)),i=f(e,"base","IPS usedImages");if(!n||void 0===i)return[];let o=l(e.path);return[{index:r,name:l(e.name)??(o?t.basename(o):`image-${r}`),uuid:n,arch:l(e.arch),base:i,path:o}]})(e,r));if(0===d.length)return null;let u=(r=Array.isArray(i.payload.threads)?i.payload.threads:[],n=new Map(d.map(e=>[e.index,e])),r.flatMap((e,t)=>{var r;return(a(r=e)&&Array.isArray(r.frames)?r.frames.filter(a):[]).flatMap((e,r)=>(function(e,t,r,a){let n=function(e,t,r){if(!Object.hasOwn(e,t))return;let a=m(e[t]);if(void 0!==a)return a;h(r,t)}(e,"imageIndex","IPS frame"),i=f(e,"imageOffset","IPS frame");if(void 0===n||void 0===i)return[];let s=t.get(n);return s?[{frame:e,frameIndex:a,threadIndex:r,image:s,address:s.base+i}]:[]})(e,n,t,r))}));return{format:"ips",images:d,addresses:u.map(({frame:e,...t})=>t),document:i,frameMatches:u,write:e=>(function(e,t,r){for(let e of t){let t=r.get(o(e.image,e.address))?.text;t&&function(e,t){let r,a=(r=t.match(/^(.*) \+ (\d+)$/))?{symbol:r[1],location:Number(r[2])}:{symbol:t};e.symbol=a.symbol,void 0!==a.location&&(e.symbolLocation=a.location)}(e.frame,t)}e.payload.agentDeviceSymbolication={tool:"agent-device debug symbols",symbolicatedFrames:[...r.values()].filter(e=>e.text).length};let a=`${JSON.stringify(e.payload,null,2)}
2
- `;return e.header?`${e.header}
3
- ${a}`:a})(i,u,e)}}(i=await C(eu,"crash artifact"))??function(e){let r=e.split("\n"),a=function(e){let r=[],a=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(-1===a)return r;for(let n of e.slice(a+1)){let e=function(e){let r=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!r)return null;let a=s(r[4]);if(!a)return null;let n=function(e,r){let a=e.split(/\s+/),n=a.at(-1);if(n&&y.test(n))return{name:a.slice(0,-1).join(" ").trim(),arch:n};let i=t.basename(r);return{name:e.startsWith(i)?i:e}}(r[3].trim(),r[5].trim());return{name:n.name,arch:n.arch,uuid:a,base:BigInt(r[1]),end:BigInt(r[2]),path:r[5].trim()}}(n);e&&r.push(e)}return r}(r);if(0===a.length)return null;let n=function(e,t){let r,a=[];for(let[n,i]of e.entries()){let e=i.match(/^Thread\s+(\d+)\s+Crashed:/);e?r=Number(e[1]):(0===i.trim().length||/^Thread\s+\d+/.test(i))&&(r=void 0);let s=function(e,t){let r=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!r)return null;let a=r[1].trim(),n=BigInt(r[2]),i=function(e,t,r){let a=e.filter(e=>e.name===t);return a.find(e=>{var t,a;return t=e,a=r,void 0!==t.end&&t.base<=a&&a<=t.end})??(1===a.length?a[0]:void 0)}(t,a,n);return i?{image:i,address:n}:null}(i,t),o=i.match(/^\s*(\d+)/);s&&o&&a.push({...s,frameIndex:Number(o[1]),lineIndex:n,threadIndex:r})}return a}(r,a);return{format:"text",images:a,addresses:n,lines:r,frameMatches:n,write(e){let t=new Map(n.map(e=>[e.lineIndex,e]));return r.map((r,a)=>{let n=t.get(a);if(!n)return r;let i=e.get(o(n.image,n.address))?.text;return!i||r.includes(i)?r:`${r} // ${i}`}).join("\n")}}}(i);em||function(){throw new r("UNSUPPORTED_OPERATION","debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.",{hint:"For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added."})}();let ef=await g({cwd:el,dsym:n.dsym,searchPath:n.searchPath});if(0===ef.length)throw new r("INVALID_ARGS","debug symbols requires --dsym or --search-path.",{hint:"Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs."});let eh=await D(),ep=await I(ef,eh.dwarfdump),ey=function(e,t,a){let n=new Map;for(let r of e){let e=t.find(e=>e.uuid===r.uuid&&(void 0===r.arch||void 0===e.arch||e.arch===r.arch));e&&n.set(r.uuid,{image:r,dsym:e})}if(n.size>0)return n;let i=p(e.map(e=>e.uuid)),s=p(t.map(e=>e.uuid));throw new r("COMMAND_FAILED",a?"dSYM UUID does not match any Apple image in the crash artifact.":"No matching dSYM UUID found under search path.",{artifactUuidCount:i.length,artifactUuidSample:i.slice(0,5),dsymUuidCount:s.length,dsymUuidSample:s.slice(0,5),hint:"Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path."})}(em.images,ep,!!n.dsym),eg=await N(em.addresses,ey,eh.atos),ew=em.write(eg);await e.mkdir(t.dirname(ec),{recursive:!0}),await e.writeFile(ec,ew,"utf8");let eb=[...ey.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),eI=[...eg.values()].filter(e=>e.text).length,eA=em.images.length-eb.length,eS=eA>0?[`${eA} Apple image${1===eA?"":"s"} had no matching dSYM and were left unchanged.`]:void 0;return{kind:"debugSymbols",platform:"apple",artifactPath:eu,outPath:ec,crash:"ips"===em.format?(w=em.document,b=em.frameMatches,A=eg,en=function(e){let t=m(e.faultingThread);if(void 0!==t)return t;let r=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>a(e)&&!0===e.triggered);return -1===r?void 0:r}(w.payload),{...ei={format:"ips",...(ee=(S=w).payload,et=(v=S.header)?c(v):null,{appName:(_=ee,F=et,u(_.procName,F?.app_name,F?.name)),bundleId:(P=ee,U=et,er=a(P.bundleInfo)?P.bundleInfo:void 0,u(er?.CFBundleIdentifier,U?.bundleID)),version:(Y=ee,T=et,ea=a(Y.bundleInfo)?Y.bundleInfo:void 0,u(ea?.CFBundleShortVersionString,T?.app_version)),incident:(L=ee,O=et,u(L.incident,O?.incident_id)),timestamp:(E=ee,V=et,u(E.captureTime,V?.timestamp)),exceptionType:a(B=ee.exception)?l(B.type):void 0,exceptionCodes:a(G=ee.exception)?u(G.codes,G.rawCodes):void 0,terminationReason:function(e){if(a(e)){let t;return(t=[l(e.namespace),l(e.code),l(e.reason)].filter(e=>!!e)).length>0?t.join(" "):void 0}}(ee.termination)}),crashedThread:en,topFrames:(W=b,j=en,k=A,W.filter(e=>void 0===j||e.threadIndex===j).slice(0,5).map(e=>M(e.frameIndex,e.image,e.address,k))),findings:[]},findings:$(ei)}):(K=em.lines,z=em.frameMatches,H=eg,eo=function(e){let t=x(e,"Triggered by Thread"),r=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(r))return r;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}(K),{...ed={format:"text",appName:(es=x(K,"Process"),es?.replace(/\s+\[\d+\]$/,"")),bundleId:x(K,"Identifier"),version:x(K,"Version"),incident:x(K,"Incident Identifier"),timestamp:x(K,"Date/Time"),exceptionType:x(K,"Exception Type"),exceptionCodes:x(K,"Exception Codes"),terminationReason:x(K,"Termination Reason"),crashedThread:eo,topFrames:(J=z,q=eo,X=H,void 0===q?[]:J.filter(e=>e.threadIndex===q).slice(0,5).map(e=>M(e.frameIndex,e.image,e.address,X))),findings:[]},findings:$(ed)}),matchedImages:eb,symbolicatedFrames:eI,skippedImages:eA,warnings:eS,message:`Symbolicated ${eI} frame${1===eI?"":"s"} -> ${ec}`}}async function C(t,a){await U(t,a);try{return await e.readFile(t,"utf8")}catch(e){throw new r("INVALID_ARGS",`Failed to read ${a}: ${t}`,{message:e instanceof Error?e.message:String(e)})}}async function U(t,a){try{let n=await e.stat(t);if(n.size<=0x4000000)return;throw new r("INVALID_ARGS",`${a} is too large: ${t}`,{actualBytes:n.size,maxBytes:0x4000000,hint:"Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context."})}catch(e){if(e instanceof r)throw e;throw new r("INVALID_ARGS",`Failed to read ${a}: ${t}`,{message:e instanceof Error?e.message:String(e)})}}function R(e,r){return t.resolve(e,r)}export{P as symbolicateCrashArtifact};
1
+ import{F as e}from"./sdk-contracts.js";import{h as t,v as n}from"./sdk-android-adb.js";import{l as r}from"./sdk-batch-runner.js";import i from"node:path";import a from"node:fs/promises";const o=/^[0-9a-fA-F-]{32,36}$/;function s(e){if(!(!e||!o.test(e)))return e.replaceAll(`-`,``).toUpperCase()}function c(e,t){return`${e.uuid}:${l(t)}`}function l(e){return`0x${e.toString(16)}`}function u(e){return typeof e==`string`&&e.length>0?e:void 0}function d(...e){for(let t of e){let e=u(t);if(e)return e}}function f(e){let t=e.filter(e=>!!e);return t.length>0?t.join(` `):void 0}function p(e){try{let t=JSON.parse(e);return r(t)?t:null}catch{return null}}function m(e){if(typeof e==`number`&&Number.isSafeInteger(e))return e;if(typeof e==`string`){let t=e.startsWith(`0x`)?Number.parseInt(e,16):Number(e);return Number.isSafeInteger(t)?t:void 0}}function h(e,t,n){if(!Object.hasOwn(e,t))return;let r=m(e[t]);if(r!==void 0)return r;v(n,t)}function g(e,t,n){if(!Object.hasOwn(e,t))return;let r=_(e[t]);if(r!==void 0)return r;v(n,t)}function _(e){if(typeof e==`bigint`)return e;if(typeof e==`number`&&Number.isSafeInteger(e)||typeof e==`string`&&/^(?:0x[0-9a-fA-F]+|\d+)$/.test(e))return BigInt(e)}function v(t,n){throw new e(`INVALID_ARGS`,`Invalid ${t} numeric field: ${n}`,{hint:`Crash artifact numeric fields must be integer numbers or integer numeric strings.`})}function y(e){return e.length===1?e[0]:void 0}function b(e){return[...new Set(e)]}function x(e){let t=e.match(/^(.*) \+ (\d+)$/);return t?{symbol:t[1],location:Number(t[2])}:{symbol:e}}const S=/^(?:arm64e?|arm64_32|x86_64|armv7[sk]?|i386)$/;function ee(e){return te(e)??w(e)}function te(e){let t=ne(e);if(!t)return null;let n=(Array.isArray(t.payload.usedImages)?t.payload.usedImages:[]).flatMap((e,t)=>C(e,t));if(n.length===0)return null;let r=re(Array.isArray(t.payload.threads)?t.payload.threads:[],n);return{format:`ips`,images:n,addresses:r.map(({frame:e,...t})=>t),document:t,frameMatches:r,write:e=>oe(t,r,e)}}function ne(e){let t=p(e);if(t)return{payload:t};let n=e.indexOf(`
2
+ `);if(n===-1)return null;let r=e.slice(0,n),i=p(e.slice(n+1));return i?{header:r,payload:i}:null}function re(e,t){let n=new Map(t.map(e=>[e.index,e]));return e.flatMap((e,t)=>ie(e).flatMap((e,r)=>ae(e,n,t,r)))}function ie(e){return!r(e)||!Array.isArray(e.frames)?[]:e.frames.filter(r)}function ae(e,t,n,r){let i=h(e,`imageIndex`,`IPS frame`),a=g(e,`imageOffset`,`IPS frame`);if(i===void 0||a===void 0)return[];let o=t.get(i);return o?[{frame:e,frameIndex:r,threadIndex:n,image:o,address:o.base+a}]:[]}function oe(e,t,n){for(let e of t){let t=n.get(c(e.image,e.address))?.text;t&&se(e.frame,t)}e.payload.agentDeviceSymbolication={tool:`agent-device debug symbols`,symbolicatedFrames:[...n.values()].filter(e=>e.text).length};let r=`${JSON.stringify(e.payload,null,2)}\n`;return e.header?`${e.header}\n${r}`:r}function se(e,t){let n=x(t);e.symbol=n.symbol,n.location!==void 0&&(e.symbolLocation=n.location)}function C(e,t){if(!r(e))return[];let n=s(u(e.uuid)),a=g(e,`base`,`IPS usedImages`);if(!n||a===void 0)return[];let o=u(e.path);return[{index:t,name:u(e.name)??(o?i.basename(o):`image-${t}`),uuid:n,arch:u(e.arch),base:a,path:o}]}function w(e){let t=e.split(`
3
+ `),n=T(t);if(n.length===0)return null;let r=O(t,n);return{format:`text`,images:n,addresses:r,lines:t,frameMatches:r,write(e){let n=new Map(r.map(e=>[e.lineIndex,e]));return t.map((t,r)=>{let i=n.get(r);if(!i)return t;let a=e.get(c(i.image,i.address))?.text;return!a||t.includes(a)?t:`${t} // ${a}`}).join(`
4
+ `)}}}function T(e){let t=[],n=e.findIndex(e=>/^Binary Images:/i.test(e.trim()));if(n===-1)return t;for(let r of e.slice(n+1)){let e=E(r);e&&t.push(e)}return t}function E(e){let t=e.match(/^\s*(0x[0-9a-fA-F]+)\s*-\s*(0x[0-9a-fA-F]+)\s+\+?(.+?)\s+<([0-9a-fA-F-]{32,36})>\s+(.+)$/);if(!t)return null;let n=s(t[4]);if(!n)return null;let r=D(t[3].trim(),t[5].trim());return{name:r.name,arch:r.arch,uuid:n,base:BigInt(t[1]),end:BigInt(t[2]),path:t[5].trim()}}function D(e,t){let n=e.split(/\s+/),r=n.at(-1);if(r&&S.test(r))return{name:n.slice(0,-1).join(` `).trim(),arch:r};let a=i.basename(t);return{name:e.startsWith(a)?a:e}}function O(e,t){let n=[],r;for(let[i,a]of e.entries()){let e=a.match(/^Thread\s+(\d+)\s+Crashed:/);e?r=Number(e[1]):(a.trim().length===0||/^Thread\s+\d+/.test(a))&&(r=void 0);let o=k(a,t),s=a.match(/^\s*(\d+)/);o&&s&&n.push({...o,frameIndex:Number(s[1]),lineIndex:i,threadIndex:r})}return n}function k(e,t){let n=e.match(/^\s*\d+\s+(.+?)\s+(0x[0-9a-fA-F]+)\b/);if(!n)return null;let r=n[1].trim(),i=BigInt(n[2]),a=A(t,r,i);return a?{image:a,address:i}:null}function A(e,t,n){let r=e.filter(e=>e.name===t);return r.find(e=>j(e,n))??y(r)}function j(e,t){return e.end!==void 0&&e.base<=t&&t<=e.end}const M=1e4;async function N(e){return e.dsym&&e.searchPath?[H(e.cwd,e.dsym),...await P(H(e.cwd,e.searchPath))]:e.dsym?[H(e.cwd,e.dsym)]:e.searchPath?await P(H(e.cwd,e.searchPath)):[]}async function P(t){let n=[],r=0;async function o(s){if(n.length>=200)return;if(r+=1,r>M)throw new e(`COMMAND_FAILED`,`debug symbols search-path scan exceeded bounds.`,{searchPath:t,maxEntries:M,hint:`Pass --dsym <App.dSYM> directly or narrow --search-path to the build products directory.`});if(!(await F(s,t)).isDirectory()){s===t&&I(t);return}if(s.endsWith(`.dSYM`)){n.push(s);return}let c=await a.readdir(s,{withFileTypes:!0});for(let e of c)e.isDirectory()&&await o(i.join(s,e.name))}return await o(t),n}async function F(t,n){try{return await a.stat(t)}catch{throw new e(`INVALID_ARGS`,`debug symbols search path does not exist: ${n}`,{hint:`Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly.`})}}function I(t){throw new e(`INVALID_ARGS`,`debug symbols search path is not a directory: ${t}`,{hint:`Pass an existing build products directory to --search-path, or pass --dsym <App.dSYM> directly.`})}async function L(t,n){let r=(await Promise.all(b(t).map(e=>R(e,n)))).flat();if(r.length===0)throw new e(`COMMAND_FAILED`,`No UUIDs found in dSYM bundle.`,{hint:`Verify the path points to a built .dSYM bundle with DWARF contents.`});return r}async function R(e,r){return await z(e),B(e,t(await n(r,[`--uuid`,e],{timeoutMs:15e3,allowFailure:!0}),`Failed to inspect dSYM UUIDs: ${e}`,{hint:`Verify the dSYM bundle is valid and readable.`}).stdout)}async function z(t){if(!((await a.stat(t).catch(()=>null))?.isDirectory()&&t.endsWith(`.dSYM`)))throw new e(`INVALID_ARGS`,`Not a .dSYM bundle: ${t}`,{hint:`Pass the .dSYM bundle path, not the DWARF executable inside it.`})}function B(e,t){return t.split(`
5
+ `).flatMap(t=>{let n=t.match(/^UUID:\s+([0-9a-fA-F-]{32,36})\s+\(([^)]+)\)\s+(.+)$/),r=s(n?.[1]);return n&&r?[{dsymPath:e,uuid:r,arch:n[2],binaryPath:n[3].trim()}]:[]})}function V(t,n,r){let i=new Map;for(let e of t){let t=n.find(t=>t.uuid===e.uuid&&(e.arch===void 0||t.arch===void 0||t.arch===e.arch));t&&i.set(e.uuid,{image:e,dsym:t})}if(i.size>0)return i;let a=b(t.map(e=>e.uuid)),o=b(n.map(e=>e.uuid));throw new e(`COMMAND_FAILED`,r?`dSYM UUID does not match any Apple image in the crash artifact.`:`No matching dSYM UUID found under search path.`,{artifactUuidCount:a.length,artifactUuidSample:a.slice(0,5),dsymUuidCount:o.length,dsymUuidSample:o.slice(0,5),hint:`Use dwarfdump --uuid <App.dSYM> and compare it with the crash Binary Images or usedImages UUID, then pass the matching dSYM/search path.`})}function H(e,t){return i.resolve(e,t)}function U(e,t){return e.format===`ips`?W(e.document,e.frameMatches,t):ve(e.lines,e.frameMatches,t)}function W(e,t,n){let r=me(e.payload),i={format:`ips`,...G(e),crashedThread:r,topFrames:_e(t,r,n),findings:[]};return{...i,findings:Y(i)}}function G(e){let t=e.payload,n=pe(e.header);return{appName:K(t,n),bundleId:ce(t,n),version:le(t,n),incident:ue(t,n),timestamp:de(t,n),exceptionType:fe(t.exception),exceptionCodes:he(t.exception),terminationReason:ge(t.termination)}}function K(e,t){return d(e.procName,t?.app_name,t?.name)}function ce(e,t){return d((r(e.bundleInfo)?e.bundleInfo:void 0)?.CFBundleIdentifier,t?.bundleID)}function le(e,t){return d((r(e.bundleInfo)?e.bundleInfo:void 0)?.CFBundleShortVersionString,t?.app_version)}function ue(e,t){return d(e.incident,t?.incident_id)}function de(e,t){return d(e.captureTime,t?.timestamp)}function fe(e){return r(e)?u(e.type):void 0}function pe(e){return e?p(e):null}function me(e){let t=m(e.faultingThread);if(t!==void 0)return t;let n=(Array.isArray(e.threads)?e.threads:[]).findIndex(e=>r(e)&&e.triggered===!0);return n===-1?void 0:n}function he(e){return r(e)?d(e.codes,e.rawCodes):void 0}function ge(e){if(r(e))return f([u(e.namespace),u(e.code),u(e.reason)])}function _e(e,t,n){return e.filter(e=>t===void 0||e.threadIndex===t).slice(0,5).map(e=>J(e.frameIndex,e.image,e.address,n))}function ve(e,t,n){let r=be(e),i={format:`text`,appName:ye(e),bundleId:q(e,`Identifier`),version:q(e,`Version`),incident:q(e,`Incident Identifier`),timestamp:q(e,`Date/Time`),exceptionType:q(e,`Exception Type`),exceptionCodes:q(e,`Exception Codes`),terminationReason:q(e,`Termination Reason`),crashedThread:r,topFrames:xe(t,r,n),findings:[]};return{...i,findings:Y(i)}}function ye(e){return q(e,`Process`)?.replace(/\s+\[\d+\]$/,``)}function q(e,t){let n=`${t}:`,r=e.find(e=>e.trimStart().startsWith(n));return r&&r.slice(r.indexOf(`:`)+1).trim()||void 0}function be(e){let t=q(e,`Triggered by Thread`),n=t?Number.parseInt(t,10):NaN;if(Number.isSafeInteger(n))return n;for(let t of e){let e=t.match(/^Thread\s+(\d+)\s+Crashed:/);if(e)return Number(e[1])}}function xe(e,t,n){return t===void 0?[]:e.filter(e=>e.threadIndex===t).slice(0,5).map(e=>J(e.frameIndex,e.image,e.address,n))}function J(e,t,n,r){return{index:e,image:t.name,address:l(n),symbol:r.get(c(t,n))?.text}}function Y(e){return[Se(e),e.exceptionType?`Exception: ${e.exceptionType}`:void 0,e.terminationReason?`Termination: ${e.terminationReason}`:void 0].filter(e=>!!e).slice(0,3)}function Se(e){let t=e.topFrames.find(e=>e.symbol);return t?`Start with ${t.symbol} in ${t.image}; it is the first symbolicated frame captured on the crashed thread.`:e.topFrames.length>0?`No symbolicated frame was found on the crashed thread; verify matching dSYMs for the top images.`:void 0}async function Ce(e,t,n){let r=new Map;for(let i of we(e,t).values())for(let e of await Te(n,i))r.set(c(e.image,e.address),e);return r}function we(e,t){let n=new Map;for(let r of e){let e=t.get(r.image.uuid);if(!e)continue;let i=`${r.image.uuid}:${e.dsym.binaryPath}`,a=n.get(i)??{...e,addresses:[]};a.addresses.push(r.address),n.set(i,a)}return n}async function Te(e,r){let i=b(r.addresses.map(l)),a=t(await n(e,Ee(r,i),{timeoutMs:3e4,allowFailure:!0}),`atos failed while symbolicating crash frames.`,{hint:`Verify the crash artifact and dSYM were produced from the same build and architecture.`});return De(r.image,i,a.stdout)}function Ee(e,t){return[`-arch`,e.image.arch??e.dsym.arch??`arm64`,`-o`,e.dsym.binaryPath,`-l`,l(e.image.base),...t]}function De(e,t,n){let r=Oe(n);return t.map((t,n)=>{let i=r[n]?.trim();return{image:e,address:BigInt(t),text:ke(i,t)?i:void 0}})}function Oe(e){let t=e.split(/\r?\n/);return t.at(-1)===``&&t.pop(),t}function ke(e,t){if(!e)return!1;let n=e.trim().toLowerCase();return!n||n===`??`||n===t.toLowerCase()?!1:!n.startsWith(`0x`)}async function Ae(){return{dwarfdump:await X(`dwarfdump`),atos:await X(`atos`)}}async function X(t){try{let e=await n(`xcrun`,[`--find`,t],{timeoutMs:5e3,allowFailure:!0}),r=e.stdout.trim();if(e.exitCode===0&&r.length>0)return r}catch{}throw new e(`TOOL_MISSING`,`Apple symbolication tool not found: ${t}`,{hint:`Install Xcode Command Line Tools and verify xcrun --find dwarfdump and xcrun --find atos succeed.`})}const Z=64*1024*1024;async function je(t){if(t.action!==void 0&&t.action!==`symbols`)throw new e(`INVALID_ARGS`,`debug supports only the symbols workflow.`,{hint:`Use debug symbols --artifact <crash.ips|crash.log> --dsym <App.dSYM> or --search-path <dir> --out <path>.`});let n=t.cwd??process.cwd(),r=$(n,t.artifact),o=$(n,t.out??Pe(r)),s=ee(await Me(r,`crash artifact`));s||Q();let c=await N({cwd:n,dsym:t.dsym,searchPath:t.searchPath});if(c.length===0)throw new e(`INVALID_ARGS`,`debug symbols requires --dsym or --search-path.`,{hint:`Pass a matching .dSYM bundle directly, or pass --search-path <dir> so agent-device can match crash image UUIDs to local dSYMs.`});let l=await Ae(),u=await L(c,l.dwarfdump),d=V(s.images,u,!!t.dsym),f=await Ce(s.addresses,d,l.atos),p=s.write(f);await a.mkdir(i.dirname(o),{recursive:!0}),await a.writeFile(o,p,`utf8`);let m=[...d.values()].map(({image:e,dsym:t})=>({name:e.name,uuid:e.uuid,arch:e.arch??t.arch,dsymPath:t.dsymPath,binaryPath:t.binaryPath})),h=[...f.values()].filter(e=>e.text).length,g=s.images.length-m.length,_=g>0?[`${g} Apple image${g===1?``:`s`} had no matching dSYM and were left unchanged.`]:void 0;return{kind:`debugSymbols`,platform:`apple`,artifactPath:r,outPath:o,crash:U(s,f),matchedImages:m,symbolicatedFrames:h,skippedImages:g,warnings:_,message:`Symbolicated ${h} frame${h===1?``:`s`} -> ${o}`}}function Q(){throw new e(`UNSUPPORTED_OPERATION`,`debug symbols currently supports Apple crash artifacts with Binary Images or IPS usedImages.`,{hint:`For Android Java/R8 crashes, use retrace with mapping.txt. For Android native crashes, use ndk-stack or addr2line with unstripped .so symbols. Capture the crash with logs, then symbolicate externally until Android support is added.`})}async function Me(t,n){await Ne(t,n);try{return await a.readFile(t,`utf8`)}catch(r){let i=r instanceof Error?r.message:String(r);throw new e(`INVALID_ARGS`,`Failed to read ${n}: ${t}`,{message:i})}}async function Ne(t,n){try{let r=await a.stat(t);if(r.size<=Z)return;throw new e(`INVALID_ARGS`,`${n} is too large: ${t}`,{actualBytes:r.size,maxBytes:Z,hint:`Pass a bounded Apple .ips/.crash artifact. For very large logs, first narrow the log to the crash report, or use logs grep/tail for lead-up context.`})}catch(r){if(r instanceof e)throw r;let i=r instanceof Error?r.message:String(r);throw new e(`INVALID_ARGS`,`Failed to read ${n}: ${t}`,{message:i})}}function $(e,t){return i.resolve(e,t)}function Pe(e){let t=i.extname(e);return`${t?e.slice(0,-t.length):e}-symbolicated${t||`.log`}`}export{je as symbolicateCrashArtifact};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./rolldown-runtime.js";import{F as t}from"./sdk-contracts.js";import{c as n,j as r,n as i}from"./sdk-android-adb.js";import{t as a}from"./timeouts.js";import{o}from"./logcat.js";const s=new Set([`com.google.android.inputmethod.latin`,`com.samsung.android.honeyboard`,`com.touchtype.swiftkey`,`com.microsoft.swiftkey`]);function c(e){let t=g(e.packageName),n=(e.resourceId??``).toLowerCase(),r=g(e.activeInputMethodPackage);if(t&&r&&t===r)return{inputMethodOwned:!0,source:`active-input-method`};if(r&&n.startsWith(`${r}:id/`))return{inputMethodOwned:!0,source:`active-input-method-resource`};if(t&&s.has(t))return{inputMethodOwned:!0,source:`known-ime-package`};for(let e of s)if(n.startsWith(`${e}:id/`))return{inputMethodOwned:!0,source:`known-ime-resource`};return{inputMethodOwned:!1,source:`app`}}function l(e,t,n){return c({packageName:e,resourceId:t,activeInputMethodPackage:n}).inputMethodOwned}function u(e){return c(e).inputMethodOwned}function d(e){let t=g(e);return!!(t&&s.has(t))}function f(e){let t=(e??``).toLowerCase();for(let e of s)if(t.startsWith(`${e}:id/`))return!0;return!1}function p(e,t,n){return!e&&!t?`unknown`:l(e,t,n)?`ime`:`app`}function m(e){for(let t of[/\bmCurMethodId=([^\s]+)/i,/\bmCurId=([^\s]+)/i,/\bmCurrentInputMethodId=([^\s]+)/i,/\bcurMethodId=([^\s]+)/i]){let n=h(e.match(t)?.[1]);if(n)return n}}function h(e){let t=(e??``).trim();if(t)return g((t.split(`/`)[0]??``).match(/[a-zA-Z0-9_.]+/)?.[0])}function g(e){return(e??``).trim().toLowerCase()||void 0}var _=e({dismissAndroidKeyboard:()=>w,dismissAndroidKeyboardWithAdb:()=>T,getAndroidKeyboardState:()=>S,getAndroidKeyboardStatusWithAdb:()=>C,readAndroidClipboardText:()=>I,readAndroidClipboardWithAdb:()=>L,writeAndroidClipboardText:()=>R,writeAndroidClipboardWithAdb:()=>z});const v=[`mInputShown`,`mIsInputViewShown`,`isInputViewShown`,`mDecorViewVisible`,`mWindowVisible`,`mInShowWindow`],y=new Map([[2,`number`],[3,`phone`],[4,`datetime`]]),b=new Set([32,208]),x=new Set([128,224,144]);async function S(e){return await C(n(e))}async function C(e){let t=await e([`shell`,`dumpsys`,`input_method`],{allowFailure:!0});if(t.exitCode!==0)throw i(`Failed to query Android keyboard state`,t);return E(t.stdout)}async function w(e){return await T(n(e))}async function T(e){let n=await C(e),r=n,i=0;for(;r.visible&&i<2;)await e([`shell`,`input`,`keyevent`,`111`]),i+=1,await a(120),r=await C(e);if(n.visible&&r.visible)throw new t(`UNSUPPORTED_OPERATION`,`Android keyboard dismiss is unavailable for the current IME without back navigation.`,{attempts:i,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,inputOwner:r.inputOwner});return{attempts:i,wasVisible:n.visible,dismissed:n.visible&&!r.visible,visible:r.visible,inputType:r.inputType,type:r.type,inputMethodPackage:r.inputMethodPackage,focusedPackage:r.focusedPackage,focusedResourceId:r.focusedResourceId,inputOwner:r.inputOwner}}function E(e){let t=j(e)??D(e),n=O(e),r=k(e,/\bpackageName=([A-Za-z0-9_.]+)\b/g),i=k(e,/\b(?:resourceId|resource-id)=([^\s,}]+)/g),a=m(e),o=p(r,i,a);return A(r,i,a),{visible:t??!1,inputType:n,type:n?F(n):void 0,inputMethodPackage:a,focusedPackage:r,focusedResourceId:i,inputOwner:o}}function D(e){let t=e.match(/\bmImeWindowVis=0x([0-9a-fA-F]+)\b/)?.[1];if(!t)return null;let n=Number.parseInt(t,16);return Number.isNaN(n)?null:(n&1)!=0}function O(e){let t=k(e,/\binputType=0x([0-9a-fA-F]+)\b/gi);return t?`0x${t.toLowerCase()}`:void 0}function k(e,t){let n;for(let r of e.matchAll(t))n=r[1];return n}function A(e,t,n){n||!d(e)&&!f(t)||r({level:`warn`,phase:`android_input_ownership_fallback`,data:{focusedPackage:e,focusedResourceId:t}})}function j(e){return N(M(e,v))}function M(e,t){let n=new Map,r=RegExp(`\\b(${t.join(`|`)})=([a-zA-Z]+)\\b`,`g`);for(let t of e.matchAll(r)){let e=t[1],r=t[2]?.toLowerCase();!e||r!==`true`&&r!==`false`||n.set(e,r===`true`)}return n}function N(e){if(e.size===0)return null;let t=P(e,[`mWindowVisible`,`mDecorViewVisible`,`mInShowWindow`]);if(t!==void 0)return t;let n=e.get(`mInputShown`);return n===void 0?P(e,[`mIsInputViewShown`,`isInputViewShown`])??null:n}function P(e,t){for(let n of t){let t=e.get(n);if(t!==void 0)return t}}function F(e){let t=Number.parseInt(e.replace(/^0x/i,``),16);if(Number.isNaN(t))return`unknown`;let n=t&15,r=y.get(n);if(r)return r;if(n!==1)return`unknown`;let i=t&4080;return b.has(i)?`email`:x.has(i)?`password`:`text`}async function I(e){return await L(n(e))}async function L(e){return V(await B(e,[`shell`,`cmd`,`clipboard`,`get`,`text`],`read`))}async function R(e,t){await z(n(e),t)}async function z(e,t){await B(e,[`shell`,`cmd`,`clipboard`,`set`,`text`,t],`write`)}async function B(e,n,r){let a=await e(n,{allowFailure:!0});if(o(a.stdout,a.stderr))throw new t(`UNSUPPORTED_OPERATION`,`Android shell clipboard ${r} is not supported on this device.`);if(a.exitCode!==0)throw i(`Failed to ${r} Android clipboard text`,a);return a.stdout}function V(e){let t=e.replace(/\r\n/g,`
2
+ `).replace(/\n$/,``),n=t.match(/^clipboard text:\s*(.*)$/i);return n?n[1]??``:t.trim().toLowerCase()===`null`?``:t}export{I as a,z as c,C as i,u as l,T as n,L as o,S as r,R as s,_ as t};