rnxsim 0.1.312 → 0.1.314

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 (299) hide show
  1. package/LICENSE +11 -10
  2. package/README.md +5 -0
  3. package/cli/app-config.ts +65 -0
  4. package/cli/app-fonts.ts +408 -0
  5. package/cli/app-project.ts +231 -0
  6. package/cli/app-splash.ts +185 -0
  7. package/cli/app-state-reset.ts +24 -0
  8. package/cli/auth.ts +155 -0
  9. package/cli/bin.ts +594 -0
  10. package/cli/bridge-diagnostics.ts +226 -0
  11. package/cli/bridge-flow-runner.ts +2830 -0
  12. package/cli/browser-evals.ts +96 -0
  13. package/cli/commands/agent-wrapper.ts +986 -0
  14. package/cli/commands/agent.ts +423 -0
  15. package/cli/commands/app-fonts.ts +98 -0
  16. package/cli/commands/assert.ts +541 -0
  17. package/cli/commands/auth.ts +59 -0
  18. package/cli/commands/camera.ts +266 -0
  19. package/cli/commands/cleanup.ts +169 -0
  20. package/cli/commands/compat.ts +87 -0
  21. package/cli/commands/config.ts +32 -0
  22. package/cli/commands/control.ts +2142 -0
  23. package/cli/commands/cpu-profile.ts +269 -0
  24. package/cli/commands/daemon-mac-app.ts +169 -0
  25. package/cli/commands/daemon.ts +874 -0
  26. package/cli/commands/debug.ts +719 -0
  27. package/cli/commands/desktop.ts +39 -0
  28. package/cli/commands/detect.ts +197 -0
  29. package/cli/commands/detox.ts +385 -0
  30. package/cli/commands/device.ts +133 -0
  31. package/cli/commands/diagnose.ts +589 -0
  32. package/cli/commands/electron.ts +95 -0
  33. package/cli/commands/film.ts +379 -0
  34. package/cli/commands/flow.ts +1124 -0
  35. package/cli/commands/inspect/actions.ts +622 -0
  36. package/cli/commands/inspect/core.ts +2405 -0
  37. package/cli/commands/inspect/count.ts +17 -0
  38. package/cli/commands/inspect/describe.ts +192 -0
  39. package/cli/commands/inspect/env.ts +23 -0
  40. package/cli/commands/inspect/find.ts +171 -0
  41. package/cli/commands/inspect/get-layout.ts +39 -0
  42. package/cli/commands/inspect/keyboard.ts +52 -0
  43. package/cli/commands/inspect/list.ts +58 -0
  44. package/cli/commands/inspect/memory.ts +215 -0
  45. package/cli/commands/inspect/redaction.ts +39 -0
  46. package/cli/commands/inspect/resolve-target.ts +82 -0
  47. package/cli/commands/inspect/screens.ts +78 -0
  48. package/cli/commands/inspect/settle.ts +22 -0
  49. package/cli/commands/inspect/settling.ts +158 -0
  50. package/cli/commands/inspect/shared.ts +353 -0
  51. package/cli/commands/inspect/sleep.ts +14 -0
  52. package/cli/commands/inspect/tree.ts +32 -0
  53. package/cli/commands/inspect/url.ts +17 -0
  54. package/cli/commands/inspect/wait-event.ts +210 -0
  55. package/cli/commands/inspect/wait-idle.ts +24 -0
  56. package/cli/commands/inspect/wait-ready.ts +74 -0
  57. package/cli/commands/inspect/wait-selector.ts +54 -0
  58. package/cli/commands/inspect/wait.ts +31 -0
  59. package/cli/commands/inspect.ts +4519 -0
  60. package/cli/commands/install-desktop.ts +351 -0
  61. package/cli/commands/login.ts +331 -0
  62. package/cli/commands/logout.ts +31 -0
  63. package/cli/commands/maestro-generate.ts +361 -0
  64. package/cli/commands/maestro.ts +453 -0
  65. package/cli/commands/mode.ts +57 -0
  66. package/cli/commands/no-bridge-hint.ts +80 -0
  67. package/cli/commands/perf.ts +66 -0
  68. package/cli/commands/permissions.ts +203 -0
  69. package/cli/commands/profile.ts +108 -0
  70. package/cli/commands/react.ts +353 -0
  71. package/cli/commands/record.ts +1434 -0
  72. package/cli/commands/report-issue.ts +305 -0
  73. package/cli/commands/reset.ts +85 -0
  74. package/cli/commands/runtime.ts +351 -0
  75. package/cli/commands/screenshot-command.ts +106 -0
  76. package/cli/commands/screenshot-layers.ts +143 -0
  77. package/cli/commands/screenshot-mode.ts +37 -0
  78. package/cli/commands/screenshot.ts +488 -0
  79. package/cli/commands/screenshots-capture.ts +607 -0
  80. package/cli/commands/screenshots.ts +127 -0
  81. package/cli/commands/serve.ts +168 -0
  82. package/cli/commands/setup.ts +545 -0
  83. package/cli/commands/shell-boolean-mode.ts +81 -0
  84. package/cli/commands/skills.ts +467 -0
  85. package/cli/commands/slides.ts +361 -0
  86. package/cli/commands/state.ts +87 -0
  87. package/cli/commands/storage.ts +58 -0
  88. package/cli/commands/telemetry.ts +54 -0
  89. package/cli/commands/three-mode.ts +763 -0
  90. package/cli/commands/timeline.ts +122 -0
  91. package/cli/commands/upgrade.ts +208 -0
  92. package/cli/commands/upload.ts +1225 -0
  93. package/cli/commands/version.ts +54 -0
  94. package/cli/commands/what-happened.ts +327 -0
  95. package/cli/current-sim.ts +204 -0
  96. package/cli/desktop-companion.ts +300 -0
  97. package/cli/drivers/electron.ts +70 -0
  98. package/cli/drivers/index.ts +20 -0
  99. package/cli/drivers/playwright-provisioning.ts +180 -0
  100. package/cli/drivers/playwright.ts +698 -0
  101. package/cli/drivers/registry.ts +65 -0
  102. package/cli/drivers/types.ts +102 -0
  103. package/cli/flow-file.ts +142 -0
  104. package/cli/flow-live-status.ts +120 -0
  105. package/cli/flow-session.ts +187 -0
  106. package/cli/help.ts +80 -0
  107. package/cli/hidden-runtime-alias.ts +19 -0
  108. package/cli/hints.ts +216 -0
  109. package/cli/inspect-notice-state.ts +114 -0
  110. package/cli/maestro-js.ts +334 -0
  111. package/cli/open-url.ts +8 -0
  112. package/cli/parent-pid.ts +204 -0
  113. package/cli/parse-args.ts +211 -0
  114. package/cli/prompt.ts +51 -0
  115. package/cli/recording-access.ts +107 -0
  116. package/cli/registry.ts +1 -0
  117. package/cli/resolve-assets.ts +63 -0
  118. package/cli/run-registry.ts +226 -0
  119. package/cli/runtime-notes.ts +66 -0
  120. package/cli/runtime-summary.ts +25 -0
  121. package/cli/setup-repository.ts +187 -0
  122. package/cli/telemetry.ts +187 -0
  123. package/cli/ws-bridge.ts +798 -0
  124. package/dist-cli/bin.js +5 -5
  125. package/dist-cli/chunks/{agent-NXVDDCFG.js → agent-7YBDCYMA.js} +2 -2
  126. package/dist-cli/chunks/{agent-wrapper-DXJCFKL3.js → agent-wrapper-2GHFBHCR.js} +2 -2
  127. package/dist-cli/chunks/{app-fonts-W5AJZQJF.js → app-fonts-RSNVPQSU.js} +2 -2
  128. package/dist-cli/chunks/{assert-3LOJEUDT.js → assert-XCMX3XJX.js} +2 -2
  129. package/dist-cli/chunks/{auth-MFTYYPNX.js → auth-B442HRAX.js} +2 -2
  130. package/dist-cli/chunks/{beta-GT3NN67B.js → beta-XJ55JK3M.js} +2 -2
  131. package/dist-cli/chunks/camera-UGYSSLIK.js +33 -0
  132. package/dist-cli/chunks/{chunk-EUAVBTKU.js → chunk-277AEQZX.js} +2 -2
  133. package/dist-cli/chunks/{chunk-5OX7ANRA.js → chunk-2JNSK774.js} +2 -2
  134. package/dist-cli/chunks/{chunk-L24Z3CRS.js → chunk-32WOTSTR.js} +3 -3
  135. package/dist-cli/chunks/{chunk-BKNOLP3J.js → chunk-3S753SNQ.js} +2 -2
  136. package/dist-cli/chunks/{chunk-N6A3SXMR.js → chunk-46ZOLOYA.js} +2 -2
  137. package/dist-cli/chunks/{chunk-GZDHEONW.js → chunk-5L7ELDQL.js} +8 -9
  138. package/dist-cli/chunks/{chunk-YZRFF4YA.js → chunk-7OOPFSQS.js} +2 -2
  139. package/dist-cli/chunks/{chunk-TBMVBI26.js → chunk-7SV3RPRW.js} +2 -2
  140. package/dist-cli/chunks/{chunk-JG6S4RSH.js → chunk-7ZC35MOU.js} +1 -1
  141. package/dist-cli/chunks/chunk-AMG5E6CC.js +9 -0
  142. package/dist-cli/chunks/{chunk-MENV7VLD.js → chunk-APWNH3A4.js} +1 -1
  143. package/dist-cli/chunks/chunk-B57XUKY3.js +4 -0
  144. package/dist-cli/chunks/{chunk-3D57IBPC.js → chunk-C2NL26TD.js} +1 -1
  145. package/dist-cli/chunks/chunk-D2FNUWAB.js +15 -0
  146. package/dist-cli/chunks/{chunk-4BXCZHAU.js → chunk-E5T4XSJ3.js} +2 -2
  147. package/dist-cli/chunks/{chunk-FTC4M26Q.js → chunk-EAC34EQS.js} +1 -1
  148. package/dist-cli/chunks/{chunk-NPVGMH2N.js → chunk-EG32ML36.js} +2 -2
  149. package/dist-cli/chunks/{chunk-DM6KUAOZ.js → chunk-FXUAC6D5.js} +1 -1
  150. package/dist-cli/chunks/chunk-GQSL4USA.js +6 -0
  151. package/dist-cli/chunks/{chunk-U4PN6JOT.js → chunk-HAXW27SS.js} +2 -2
  152. package/dist-cli/chunks/{chunk-ZMZTHU7V.js → chunk-IZAHPAN6.js} +1 -1
  153. package/dist-cli/chunks/{chunk-SI3BUTQR.js → chunk-J62KM5TB.js} +2 -2
  154. package/dist-cli/chunks/{chunk-Y2FSZSO7.js → chunk-JEMCD5E4.js} +1 -1
  155. package/dist-cli/chunks/{chunk-T4FT6CM7.js → chunk-JZS3Q37N.js} +2 -2
  156. package/dist-cli/chunks/{chunk-2SA2VTGP.js → chunk-KR4JON7D.js} +1 -1
  157. package/dist-cli/chunks/chunk-KWCYKQIQ.js +4 -0
  158. package/dist-cli/chunks/{chunk-HG7ORJMT.js → chunk-MCWPL644.js} +2 -2
  159. package/dist-cli/chunks/chunk-MJYK3N2I.js +4 -0
  160. package/dist-cli/chunks/{chunk-YRV7HR3P.js → chunk-O6TRIZNS.js} +2 -2
  161. package/dist-cli/chunks/{chunk-WBT32R6N.js → chunk-P7XL2E73.js} +3 -3
  162. package/dist-cli/chunks/{chunk-MNGQ42QE.js → chunk-PFQTUKQ4.js} +62 -87
  163. package/dist-cli/chunks/{chunk-Q3RGLERJ.js → chunk-PG5RZCTN.js} +2 -2
  164. package/dist-cli/chunks/{chunk-OR3XTXEB.js → chunk-QGRI2Z4M.js} +2 -2
  165. package/dist-cli/chunks/chunk-QLXXE7GE.js +125 -0
  166. package/dist-cli/chunks/{chunk-KZW5WBGU.js → chunk-QOJJJWJE.js} +89 -133
  167. package/dist-cli/chunks/{chunk-BRIZOR4K.js → chunk-RWZY5427.js} +2 -2
  168. package/dist-cli/chunks/{chunk-TYE3WBSR.js → chunk-RZKU2K3J.js} +2 -2
  169. package/dist-cli/chunks/{chunk-7VWOSTD5.js → chunk-SBV4IK4H.js} +1 -1
  170. package/dist-cli/chunks/{chunk-FWYYCUAZ.js → chunk-SGMVFFMK.js} +1 -1
  171. package/dist-cli/chunks/{chunk-LDQ7HVCW.js → chunk-TAX4UT2N.js} +1 -1
  172. package/dist-cli/chunks/{chunk-G74YIEVS.js → chunk-TUOFAWXT.js} +1 -1
  173. package/dist-cli/chunks/{chunk-274UD5FD.js → chunk-UHZLOHGP.js} +1 -1
  174. package/dist-cli/chunks/{chunk-37I5AIS7.js → chunk-VC7V76U3.js} +1 -1
  175. package/dist-cli/chunks/{chunk-B7KMNHX7.js → chunk-VQVMLW4U.js} +1 -1
  176. package/dist-cli/chunks/{chunk-VZBLFMYC.js → chunk-VUKKYPZN.js} +2 -2
  177. package/dist-cli/chunks/{chunk-VUFRB347.js → chunk-WGGRJDRE.js} +1 -1
  178. package/dist-cli/chunks/chunk-X6H76EKP.js +15 -0
  179. package/dist-cli/chunks/chunk-XLZ5FNRT.js +27 -0
  180. package/dist-cli/chunks/{chunk-TCWQJILS.js → chunk-XULEACM4.js} +2 -2
  181. package/dist-cli/chunks/{chunk-XRGEEPJ5.js → chunk-YFSDM7AX.js} +4 -4
  182. package/dist-cli/chunks/chunk-YWI3UEVX.js +5 -0
  183. package/dist-cli/chunks/{chunk-TGQNQ6XT.js → chunk-ZBSJO4NB.js} +10 -9
  184. package/dist-cli/chunks/{cleanup-H3GWQB63.js → cleanup-EYLGCA6Z.js} +2 -2
  185. package/dist-cli/chunks/cli-version-LL2UGIHE.js +4 -0
  186. package/dist-cli/chunks/{compat-5WG2XJV7.js → compat-TLJYHB4E.js} +2 -2
  187. package/dist-cli/chunks/{config-ANMBVVLL.js → config-4JWUOEXK.js} +2 -2
  188. package/dist-cli/chunks/{control-NSGNQFJG.js → control-HPAOYF4N.js} +2 -2
  189. package/dist-cli/chunks/daemon-OYLASXLE.js +4 -0
  190. package/dist-cli/chunks/{debug-CHV2O2KF.js → debug-4BKXF6KI.js} +5 -5
  191. package/dist-cli/chunks/{desktop-FIPIK4CH.js → desktop-ZQ6ZD2S6.js} +3 -3
  192. package/dist-cli/chunks/{detox-CVUJP7K6.js → detox-WNPASSS3.js} +2 -2
  193. package/dist-cli/chunks/{device-6WCUM4W6.js → device-BXLXVG3V.js} +2 -2
  194. package/dist-cli/chunks/{diagnose-I6EMWEII.js → diagnose-3QX7W5RW.js} +2 -2
  195. package/dist-cli/chunks/{disk-cleanup-P27CYFTN.js → disk-cleanup-KSWKI7WB.js} +2 -2
  196. package/dist-cli/chunks/drivers-EPIEFF7P.js +4 -0
  197. package/dist-cli/chunks/{film-UOQFFYNF.js → film-GDMR33VO.js} +3 -3
  198. package/dist-cli/chunks/flow-NKMPBYCJ.js +4 -0
  199. package/dist-cli/chunks/help-OGCBHOKA.js +4 -0
  200. package/dist-cli/chunks/{hidden-runtime-alias-NJYFSJKZ.js → hidden-runtime-alias-S2GTDX3T.js} +2 -2
  201. package/dist-cli/chunks/home-paths-QRCDLTTV.js +4 -0
  202. package/dist-cli/chunks/inspect-FUYMOZPY.js +4 -0
  203. package/dist-cli/chunks/install-desktop-FR6YKW7Y.js +4 -0
  204. package/dist-cli/chunks/{login-BPFQENCX.js → login-IJAPUZHI.js} +4 -4
  205. package/dist-cli/chunks/{logout-5A45ZGY7.js → logout-QMXDFU2X.js} +2 -2
  206. package/dist-cli/chunks/{maestro-E4CSDMLM.js → maestro-ZXU3YCVX.js} +3 -3
  207. package/dist-cli/chunks/{maestro-generate-CKMOJQX2.js → maestro-generate-PYB5QY7K.js} +3 -3
  208. package/dist-cli/chunks/{mode-SZYNMIQF.js → mode-WGUCL5FZ.js} +2 -2
  209. package/dist-cli/chunks/{optional-demo-registry-FRH4SFVG.js → optional-demo-registry-WH2O6H36.js} +2 -2
  210. package/dist-cli/chunks/{perf-VXU2XJAX.js → perf-TOD3UFAH.js} +2 -2
  211. package/dist-cli/chunks/{permissions-IRIAOVND.js → permissions-I5BRJGTB.js} +2 -2
  212. package/dist-cli/chunks/{record-RY7FPLLH.js → record-ZYL2FYSK.js} +3 -3
  213. package/dist-cli/chunks/{report-issue-KNWXOE53.js → report-issue-TAI6DYZO.js} +2 -2
  214. package/dist-cli/chunks/reset-7YGYKQPQ.js +4 -0
  215. package/dist-cli/chunks/runtime-B4JO6QRI.js +4 -0
  216. package/dist-cli/chunks/{screenshot-command-QLALR6GY.js → screenshot-command-7ANLODZY.js} +7 -7
  217. package/dist-cli/chunks/{screenshot-layers-OQFMFVRL.js → screenshot-layers-A7FYXSVU.js} +3 -3
  218. package/dist-cli/chunks/{screenshots-capture-6TSRJFGB.js → screenshots-capture-WT2ZY6CB.js} +2 -2
  219. package/dist-cli/chunks/serve-TG5WKA4V.js +44 -0
  220. package/dist-cli/chunks/{setup-7V6UKX4U.js → setup-PCWLD22V.js} +2 -2
  221. package/dist-cli/chunks/{skills-QQBOSETH.js → skills-27ZHWCQS.js} +2 -2
  222. package/dist-cli/chunks/state-ZQVY46ZO.js +14 -0
  223. package/dist-cli/chunks/{storage-TAPMKK5O.js → storage-OYC57C4X.js} +6 -6
  224. package/dist-cli/chunks/store-32HSPZHI.js +4 -0
  225. package/dist-cli/chunks/telemetry-PBJR7XHR.js +4 -0
  226. package/dist-cli/chunks/{timeline-IAM564NA.js → timeline-RAJJFQT6.js} +2 -2
  227. package/dist-cli/chunks/{upgrade-CD55QXIX.js → upgrade-OEFNZRIP.js} +2 -2
  228. package/dist-cli/chunks/upload-LQJITLKK.js +4 -0
  229. package/dist-cli/chunks/version-NIXTY6PL.js +6 -0
  230. package/dist-cli/chunks/{web-6NW6YLPI.js → web-XBUTBVGR.js} +2 -2
  231. package/dist-cli/chunks/{what-happened-CZZDOOVG.js → what-happened-YNHRFUDX.js} +3 -3
  232. package/dist-lib/agent-daemon-client.cjs +1 -1
  233. package/dist-lib/agent-events.cjs +1 -1
  234. package/dist-lib/agent-identity.cjs +1 -1
  235. package/dist-lib/agent-sessions.cjs +1 -1
  236. package/dist-lib/attached-projects.cjs +1 -1
  237. package/dist-lib/auth/shared-session.cjs +1 -1
  238. package/dist-lib/backend-origin.cjs +1 -1
  239. package/dist-lib/beta.cjs +1 -1
  240. package/dist-lib/beta.mjs +1 -1
  241. package/dist-lib/bridge-constants.cjs +1 -1
  242. package/dist-lib/bridge-contract.cjs +20 -0
  243. package/dist-lib/cli-constants.cjs +1 -1
  244. package/dist-lib/config.cjs +1 -1
  245. package/dist-lib/detox/index.cjs +1 -1
  246. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  247. package/dist-lib/home-paths.cjs +67 -28
  248. package/dist-lib/host/bridge-host.cjs +140 -12
  249. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  250. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  251. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  252. package/dist-lib/host/websocket-proxy.cjs +1 -1
  253. package/dist-lib/index.cjs +2815 -40
  254. package/dist-lib/jump-to-source-babel.cjs +1 -1
  255. package/dist-lib/menu.cjs +1 -1
  256. package/dist-lib/menu.mjs +1 -1
  257. package/dist-lib/metro.cjs +1 -1
  258. package/dist-lib/profiles.cjs +1 -1
  259. package/dist-lib/public-brand.cjs +1 -1
  260. package/dist-lib/render-mode.cjs +1 -1
  261. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  262. package/dist-lib/sdk.cjs +2549 -2061
  263. package/dist-lib/sdk.mjs +2543 -2061
  264. package/dist-lib/skills.cjs +493 -282
  265. package/dist-lib/vite.cjs +1 -1
  266. package/package.json +8 -2
  267. package/src/bridge-constants.ts +3 -4
  268. package/src/bridge-contract.ts +251 -0
  269. package/src/connect.ts +83 -0
  270. package/src/disk-cleanup.ts +30 -0
  271. package/src/home-paths.ts +81 -38
  272. package/src/host/bridge-host.ts +134 -6
  273. package/src/index.ts +27 -1
  274. package/src/sdk.ts +8 -0
  275. package/src/sim-client.ts +660 -0
  276. package/dist-cli/chunks/camera-6EAK7CUL.js +0 -22
  277. package/dist-cli/chunks/chunk-33FKQH54.js +0 -5
  278. package/dist-cli/chunks/chunk-66NF2KNG.js +0 -9
  279. package/dist-cli/chunks/chunk-6UKJB2VC.js +0 -125
  280. package/dist-cli/chunks/chunk-7INBNA3U.js +0 -26
  281. package/dist-cli/chunks/chunk-AY47WKS5.js +0 -23
  282. package/dist-cli/chunks/chunk-HMDOLCKG.js +0 -15
  283. package/dist-cli/chunks/chunk-KR5BGMBZ.js +0 -4
  284. package/dist-cli/chunks/chunk-NLEMQ4PY.js +0 -6
  285. package/dist-cli/chunks/chunk-PEPUGJVI.js +0 -4
  286. package/dist-cli/chunks/cli-version-3QPAJ3LC.js +0 -4
  287. package/dist-cli/chunks/daemon-JHF4BJ3U.js +0 -4
  288. package/dist-cli/chunks/drivers-HQ6AKZT6.js +0 -4
  289. package/dist-cli/chunks/flow-N27MRRNL.js +0 -4
  290. package/dist-cli/chunks/help-SF6FEGEE.js +0 -4
  291. package/dist-cli/chunks/home-paths-XOV44JEF.js +0 -4
  292. package/dist-cli/chunks/inspect-CWFRFQTY.js +0 -4
  293. package/dist-cli/chunks/install-desktop-KLQDNXZQ.js +0 -4
  294. package/dist-cli/chunks/runtime-AR3GJTGK.js +0 -4
  295. package/dist-cli/chunks/serve-F54J2NQO.js +0 -44
  296. package/dist-cli/chunks/store-7NX3S43H.js +0 -4
  297. package/dist-cli/chunks/telemetry-E7BUK6RA.js +0 -4
  298. package/dist-cli/chunks/upload-GZ6LIMYM.js +0 -4
  299. package/dist-cli/chunks/version-3DYJ5AS3.js +0 -6
@@ -1,15 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as I,b as ce,c as Ne}from"./chunk-SI3BUTQR.js";import{m as A}from"./chunk-XRGEEPJ5.js";import{m as Ee,p as Ue}from"./chunk-TGQNQ6XT.js";import{b as Le,j as Ve}from"./chunk-GZDHEONW.js";import{a as We,b as Ke,d as qe}from"./chunk-T4FT6CM7.js";import{a as De,b as L,c as ae,d as le,e as Be,f as Ae,h as je,i as K,j as He}from"./chunk-YZRFF4YA.js";import{a as Fe}from"./chunk-AY47WKS5.js";import{a as de}from"./chunk-3D57IBPC.js";import{b as _e,c as Te,d as ie,f as Oe,g as Me,h as U,i as P,j as _}from"./chunk-7INBNA3U.js";import{f as Ie}from"./chunk-U4PN6JOT.js";import{b as se,d as ke}from"./chunk-5OX7ANRA.js";import{b as Ce,g as Re,h as D,i as $,j as B}from"./chunk-33FKQH54.js";import{H as re,K as oe,M,O as Pe,l as ne}from"./chunk-66NF2KNG.js";import{a as te}from"./chunk-ZMZTHU7V.js";import{spawn as Ze,spawnSync as Xe}from"node:child_process";import T from"node:fs";import kt from"node:os";import C from"node:path";import{WebSocket as ue}from"ws";function ze(e){return new Error(`could not resolve a native bundle for ${e}. pass an explicit bundle URL or open Connect and choose the app there.`)}function yt(e,n){return e?.includes("/one/metro-entry.bundle")?"one":typeof n=="string"&&n?"expo":"unknown"}function Je(e,n,t){return`${e}//${n}:${t}`}function St(e){if(typeof window>"u")return!1;try{let n=new URL(e);return I(n.hostname)&&I(window.location.hostname)&&n.origin!==window.location.origin}catch{return!1}}async function Ge(e,n){let t={...n,cache:n?.cache??"no-store"};return St(e)?fetch(`/__fetch-proxy?url=${encodeURIComponent(e)}`,t):fetch(e,t)}function xt(e){return e==="https:"?443:80}function $t(e){let n=e.pathname||"/";return(n==="/"||n==="")&&!e.search&&!e.hash}async function Pt(e){try{let n=await fetch("/__server-scan",{cache:"no-store"});if(!n.ok||!(n.headers.get("content-type")||"").toLowerCase().includes("json"))return null;let t=await n.json();if(!Array.isArray(t))return null;let r=t.find(o=>!!o&&typeof o=="object"&&o.port===e&&typeof o.bundleUrl=="string");return r?{bundleUrl:le(r.bundleUrl),port:e,framework:typeof r.framework=="string"?r.framework:"unknown",projectName:typeof r.projectName=="string"?r.projectName:void 0}:null}catch{return null}}async function Qe(e,n){let t=e.replace(/\/+$/,"");try{if(I(new URL(t).hostname)){let r=await Pt(n);if(r)return r}}catch{}try{let r=await Ge(`${t}/`,{headers:{"expo-platform":"ios"}});if(r.ok){let o=await r.json(),s=o?.extra?.expoClient||o?.extra||{},i=typeof o?.launchAsset?.url=="string"?o.launchAsset.url:void 0;if(i||s.name)return{bundleUrl:le(i||`${t}${ae}`),port:n,framework:yt(i,s.sdkVersion),projectName:s.name}}}catch{}try{let r=await Ge(`${t}/status`);if(r.ok&&(await r.text()).includes("packager-status:running"))return{bundleUrl:`${t}${ae}`,port:n,framework:"metro"}}catch{}return null}async function It(e){return Qe(Je("http:","localhost",e),e)}async function Ye(e){let n=e.trim();if(/^\d+$/.test(n)){let a=parseInt(n,10),l=await It(a);if(l)return l;throw ze(`localhost:${a}`)}let t=n.startsWith("http")?n:`http://${n}`,r;try{r=new URL(t)}catch{throw new Error(`could not parse "${e}". pass a dev-server port, a dev-server base URL, or a full bundle URL.`)}let o=r.protocol||"http:",s=r.port?parseInt(r.port,10):xt(o),i=Je(o,r.hostname,s);if($t(r)){let a=await Qe(i,s);if(a)return a;throw ze(i)}return{bundleUrl:r.toString(),port:s,framework:"unknown"}}var Ct=12e4,et=100,Rt=5e3,tt=1e4,Et={rn:"/rn",connectrn:"/rn","connect-rn":"/rn",clock:"/app/clock","native-ui":"/app/native-ui",tamagui:"/app/tamagui",settings:"/app/settings",photos:"/app/photos",camera:"/app/camera"};function y(e){return new Promise(n=>setTimeout(n,e))}function nt(e){let n=process.env[e]?.trim();if(!n)return null;let t=Number(n);return Number.isInteger(t)&&t>0?t:null}function Ut(){let e=nt("SOOTSIM_DRIVER_CONNECT_TIMEOUT_MS")??nt("SOOTSIM_PW_CONNECT_TIMEOUT_MS")??Ct;return{timeoutMs:e,hostTimeoutMs:e+Rt,intervalMs:et,attempts:Math.max(1,Math.ceil(e/et))}}function rt(e){return e==="electron"||e==="playwright"}function me(e,n){return n==="playwright"?e.meta?.sootsimHostDriver==="playwright":e.userAgent?.includes("Electron/")===!0}function _t(e,n){return e.includes("--headless")?!0:e.includes("--headed")?!1:n==="playwright"&&process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY?(console.error(" no display detected \u2192 running playwright headless (override with --headed)"),!0):!1}function z(e){return e.trim()}var dt=/^[A-Za-z][A-Za-z0-9+.-]*:/;function Tt(e){let n=e.trim();if(!n)throw new Error("expected <url-or-route>");return dt.test(n)||n.startsWith("/")?n:`/${n}`}function Ot(e){return e!==null&&typeof e=="object"}function Mt(e){let n=e.trim();return n?n.startsWith("/")?!0:dt.test(n)?!/^https?:\/\//i.test(n):!1:!1}async function Dt(e,n=!1){if(await V(e,250))return e;let t=oe();if(ot(e,n,t),t&&M(t)&&await V(t.bridgePort,500))return t.bridgePort;if(t&&M(t))throw new Error(`rnx bridge lockfile is fresh (port ${t.bridgePort}) but the bridge is not reachable. run \`rnxsim daemon restart\` or \`rnxsim daemon uninstall\`.`);await Bt();let r=At(["serve","--quiet","--port",String(e)]),o=null;r.once("exit",(i,a)=>{o=String(i??a??"unknown")}),r.unref();let s=Date.now()+tt;for(;Date.now()<s;){let i=oe();if(ot(e,n,i),i&&M(i)&&await V(i.bridgePort,250))return console.error(` started local bridge on port ${i.bridgePort}; run \`sootsim setup\` to install the background daemon`),i.bridgePort;if(await V(e,250))return console.error(` started local bridge on port ${e}; run \`sootsim setup\` to install the background daemon`),e;if(o)throw new Error(`rnx bridge exited before becoming ready (exit ${o})`);await y(150)}throw new Error(`rnx bridge did not start within ${Math.round(tt/1e3)}s`)}function ot(e,n,t){if(!(!n||!t||!M(t)||t.bridgePort===e))throw new Error(`${te.commandName} open: requested bridge port ${e}, but the active daemon owns port ${t.bridgePort}. explicit --port never selects another bridge; stop that daemon or use an isolated SOOTSIM_HOME.`)}async function Bt(){let e=re();if(e&&T.existsSync(ne(e)))return;console.error(" installing rnx engine runtime...");let{runRuntime:n}=await import("./runtime-AR3GJTGK.js");await n(["install"],{})}function At(e){let n=process.argv[1];return n&&T.existsSync(n)?Ze(process.execPath,[n,...e],{detached:!0,stdio:"ignore",env:process.env}):Ze(te.commandName,e,{detached:!0,stdio:"ignore",env:process.env})}function V(e,n){return new Promise(t=>{let r=new ue(`ws://127.0.0.1:${e}`,{handshakeTimeout:n}),o=!1,s=i=>{o||(o=!0,r.readyState===ue.OPEN?r.close():r.readyState===ue.CONNECTING&&r.terminate(),t(i))};r.once("open",()=>s(!0)),r.on("error",()=>s(!1)),setTimeout(()=>s(!1),n)})}function fe(e){try{let n=new URL(e),t=n.pathname.replace(/\/+$/,"")||"/";return n.searchParams.has("open")||n.searchParams.has("port")||n.searchParams.has("bundle")||n.searchParams.has("demo")||n.pathname.includes("/sootsim/index.html")||t==="/sootsim"||n.pathname==="/__soot"||n.pathname==="/__soot/"||t==="/rn"||/^\/rn\/[^/]+$/i.test(t)||/^\/app\/[^/]+$/i.test(t)||t==="/__soot/rn"||/^\/__soot\/rn\/[^/]+$/i.test(t)||/^\/__soot\/app\/[^/]+$/i.test(t)}catch{return!1}}function Lt(e){try{let n=new URL(e,"http://sootsim.local");if(n.origin!=="http://sootsim.local")return!1;let t=n.pathname.replace(/\/+$/,"")||"/";return t==="/rn"||/^\/rn\/[^/]+$/i.test(t)||/^\/app\/[^/]+$/i.test(t)||t==="/__soot/rn"||/^\/__soot\/rn\/[^/]+$/i.test(t)||/^\/__soot\/app\/[^/]+$/i.test(t)}catch{return!1}}function Nt(e,n){let t=new URL(e,"http://sootsim.local"),r=new URL(n),o=G(r.pathname),s=t.pathname.startsWith("/__soot/")?t.pathname.slice(7):t.pathname;return r.pathname=`${o}${s}`,r.search=t.search,r.hash=t.hash,r.toString()}function Ft(e){try{let n=new URL(e).pathname.replace(/\/+$/,"")||"/";return/^\/preview\/[^/]+$/.test(n)||/^\/build\/.+/.test(n)}catch{return!1}}async function Gn(e){let n=z(e);return(await he(n)).bundleUrl}function jt(e){try{let n=new URL(e.startsWith("http")?e:`http://${e}`),t=n.pathname||"/";if(t!=="/"&&t!==""||n.search||n.hash||!I(n.hostname))return null;let r=n.port?Number(n.port):n.protocol==="https:"?443:80;return Number.isFinite(r)&&r>0?r:null}catch{return null}}async function he(e){let n=z(e),t=/^\d+$/.test(n)?Number(n):jt(n);if(t&&t>0){let r=await Ae(t);if(r)return{bundleUrl:r.bundleUrl,port:r.port,framework:r.framework,projectName:r.projectName}}return Ye(n)}function G(e){let n=e.replace(/\/+$/,"")||"/";return n==="/__soot"||n.startsWith("/__soot/")?"/__soot":""}function Ht(e,n){let t=z(e),r=new URL(n),o=G(r.pathname);return r.pathname=`${o}/rn`,r.searchParams.delete("bundle"),r.searchParams.delete("demo"),r.searchParams.delete("app"),r.searchParams.delete("open"),r.searchParams.delete("port"),/^\d+$/.test(t)?r.pathname=`${o}/rn/${t}`:(r.pathname=`${o}/rn`,r.searchParams.set("open",t)),r.toString()}function ut(e){let n=z(e);return/^\d+$/.test(n)||/^https?:\/\//i.test(n)?!0:/^(localhost|127\.0\.0\.1|\[::1\]|[^/]+\.localhost):\d+(?:\/.*)?$/i.test(n)}async function Wt(e,n,t={}){let r=t.resolvedBundle??await he(e),o=new URL(n),s=G(o.pathname);o.pathname=`${s}/rn`,o.searchParams.delete("open"),o.searchParams.delete("port"),o.searchParams.delete("demo"),o.searchParams.delete("app");let i=t.hot===void 0?r.bundleUrl:Be(r.bundleUrl,t.hot);return o.searchParams.set("bundle",i),o.toString()}function Kt(e){return e.startsWith("~/")?C.join(kt.homedir(),e.slice(2)):C.isAbsolute(e)?e:C.resolve(process.cwd(),e)}function Vt(e){let n={},t={};for(let o=0;o<e.length;o++){if(e[o]==="--replace"){let s=e[o+1];s||(console.error(" rnxsim open: --replace expects <module>=<file>"),process.exit(1));let i=s.indexOf("=");(i<=0||i===s.length-1)&&(console.error(" rnxsim open: --replace expects <module>=<file>"),process.exit(1));let a=s.slice(0,i).trim(),l=Kt(s.slice(i+1).trim());T.existsSync(l)||(console.error(` rnxsim open: replacement file not found: ${l}`),process.exit(1)),n[a]={file:l},o++;continue}if(e[o]==="--remap"){let s=e[o+1],i=s?s.indexOf("="):-1;(!s||i<=0||i===s.length-1)&&(console.error(" rnxsim open: --remap expects <host:port>=<host:port>"),process.exit(1)),t[s.slice(0,i).trim()]=s.slice(i+1).trim(),o++;continue}}let r={};return Object.keys(n).length>0&&(r.modules=n),Object.keys(t).length>0&&(r.network={remap:t}),r.modules||r.network?r:void 0}async function qt(e){if(e){let n=await K(e.bundleUrl);if(n)return de(n,{trustStart:!0})}return de(process.env.CONTRAST_REPO_DIR||process.cwd())}async function zt(e){if(T.existsSync(C.join(ne(e),"index.html")))return;console.error(` installing configured engine runtime ${e}...`);let n=await Ie.install({version:e,setActive:!1,protectVersions:Pe()});console.error(` installed engine runtime ${n.version}`)}function Gt(e,n){let t=n??(ce()?void 0:re()??void 0);if(!t)return e;let r=new URL(e);if(!I(r.hostname)){if(!n)return e;throw new Error(`runtimeVersion ${t} requires a local rnx host; got ${r.origin}`)}return r.hostname=Ne(t),r.toString()}function mt(){return _e().shellBaseUrl}function Jt(e){return Te(e)?.shellBaseUrl??Ce(e)??mt()}async function Qt(e,n){try{let t=new URL(e),r=t.searchParams.get("bundle")||"";if(!r)return e;let o=n?.appDir??await K(r)??void 0,s=je({bundleUrl:r,repoDir:o,exactProjectDir:!!n||!!o});if(s.length===0)return e;let i=await Yt(s);return i.length===0?e:(t.searchParams.set("appFonts",He(i)),t.toString())}catch{return e}}async function Yt(e){let n=await Promise.all(e.map(async r=>{let o=new AbortController,s=setTimeout(()=>o.abort(),1500);try{let i=await fetch(r.url,{method:"HEAD",signal:o.signal});return i.status>=200&&i.status<400?r:null}catch{return null}finally{clearTimeout(s)}})),t=[];for(let r of n)r!==null&&t.push(r);return t}async function Zt(e,n,t={}){if(!e)return new URL(n).toString();if(fe(e))return new URL(e).toString();if(Lt(e))return Nt(e,n);let r=Et[e.toLowerCase()];if(r){let o=new URL(n),s=G(o.pathname);return o.pathname=`${s}${r}`,o.toString()}return ut(e)?Wt(e,n,t):Ht(e,n)}async function Xt(e,n){try{let t=new URL(e),r=t.searchParams.get("bundle")||"";if(!r)return e;let o=n?.appDir??await K(r)??void 0,s=We({bundleUrl:r,repoDir:o,exactProjectDir:!!n||!!o});return!s||s.imageUrl&&!await en(s.imageUrl)?e:(t.searchParams.set("appSplash",Ke(s)),t.toString())}catch{return e}}async function en(e){let n=new AbortController,t=setTimeout(()=>n.abort(),1500);try{let r=await fetch(e,{method:"HEAD",signal:n.signal});return r.status>=200&&r.status<400}catch{return!1}finally{clearTimeout(t)}}async function q(e,n=mt(),t={}){let r=await Zt(e,n,t),o=await Xt(await Qt(r,t.project),t.project);if(!t.device)return o;let s=new URL(o);return s.searchParams.set("device",t.device),s.toString()}function st(e,n){let t=e?.url||e?.origin||n;try{let r=new URL(t);return r.searchParams.delete("bundle"),r.searchParams.delete("demo"),r.searchParams.delete("app"),r.searchParams.delete("open"),r.searchParams.delete("port"),r.searchParams.delete("inspectOpen"),r.searchParams.delete("appFonts"),r.searchParams.delete("appSplash"),r.toString()}catch{return n}}async function tn(e,n,t,r={}){let o=new URL(await q(e,n,r));return o.searchParams.set("inspectOpen",t),o.toString()}async function nn(e,n,t,r={}){let o=r.attempts??30,s=r.intervalMs??500,i=r.minNodeCount??10;for(let a=0;a<o;a++){let l=P(e,{commandTimeoutMs:n,simId:t,simIdSource:"flag"});try{let d=await l.send({type:"evaluate",code:"(async () => (await window.__sootsimTest?.getNodeCount()) || 0)()"});if(typeof d=="number"&&d>i)return{bridge:l,count:d}}catch{}l.close(),await y(s)}return null}function rn(e){if(!e)return null;try{let n=new URL(e);if(n.searchParams.has("bundle")){let t=n.searchParams.get("bundle")||"";try{let r=new URL(t),o=r.pathname.length>36?`...${r.pathname.slice(-36)}`:r.pathname;return`bundle ${r.host}${o}`}catch{return"bundle"}}return n.searchParams.has("port")?`connect :${n.searchParams.get("port")||""}`:n.searchParams.has("open")?`connect ${n.searchParams.get("open")||""}`:n.searchParams.has("demo")?`demo ${n.searchParams.get("demo")||"default"}`:n.pathname.includes("/sootsim/index.html")||n.pathname==="/sootsim/"||n.pathname==="/sootsim"?"embedded rnx":null}catch{return null}}function on(e){let n=e.indexOf(":");if(n<=0)return e.length>24?`${e.slice(0,21)}\u2026`:e;let t=e.slice(0,n),r=e.slice(n+1),o=r.length>12?`${r.slice(0,8)}\u2026`:r;return t==="TM_SESSION"||t==="CLAUDE_CODE_SESSION_ID"||t==="CODEX_THREAD_ID"?`agent ${o}`:`${t} ${o}`}function Jn(e,n){if(e.length===0){console.log(" no sims connected");return}console.log(` connected sims (${e.length}):
5
- `);for(let t of e){let r=t.lockedBy&&t.lockExpiresAt?`locked by ${on(t.lockedBy)} (${Math.max(0,Math.round((t.lockExpiresAt-Date.now())/1e3))}s)`:"",o=[t.isPrimary?"primary":"",t.id===n?"selected":"",t.readyState,t.userVisible===!1?"hidden":t.userVisible===!0?"visible":"",t.attachedCliCount&&t.attachedCliCount>0?"in use":"",t.userFocused?"focused":"",r].filter(Boolean);console.log(` ${t.id}${o.length?` [${o.join(", ")}]`:""}`);let s=rn(t.url);if(s)console.log(` loaded: ${s}`);else if(t.url){let a=t.url.length>96?`${t.url.slice(0,93)}\u2026`:t.url;console.log(` url: ${a}`)}else t.origin&&console.log(` origin: ${t.origin}`);let i=sn(t);i&&console.log(` engine: ${i}`),t.title&&console.log(` title: ${t.title}`),t.visibilityState&&t.visibilityState!=="visible"&&console.log(` visibility: ${t.visibilityState}`),console.log(` connected: ${it(Date.now()-t.connectedAt)}`),t.lastActiveAt&&t.lastActiveAt>0&&console.log(` last active: ${it(Date.now()-t.lastActiveAt)}`)}}function sn(e){let n=e.url||e.origin||"";if(!n)return null;try{let t=new URL(n).port;return t==="5173"?"dev \u2014 local source (:5173)":t==="3000"?"Contrast app embedded (:3000)":ce()?`dev \u2014 local build (:${t||"?"})`:`runtime \u2014 published engine (:${t||"?"})`}catch{return null}}function it(e){let n=Math.max(0,Math.round(e/1e3));return n<60?`${n}s ago`:n<3600?`${Math.round(n/60)}m ago`:n<86400?`${Math.round(n/3600)}h ago`:`${Math.round(n/86400)}d ago`}async function Qn(e,n,t,r={}){let o=r.attempts??30,s=r.intervalMs??500;for(let i=0;i<o;i++){let a=P(e,{commandTimeoutMs:n});try{let d=(await a.listSims()).find(t);if(d)return d}catch{}finally{a.close()}await y(s)}return null}async function an(e,n,t,r,o={}){let s=o.attempts??30,i=o.intervalMs??500,a=!!r&&Number.isInteger(r)&&r>1,l=()=>a&&r!==void 0&&!ge(r);for(let d=0;d<s;d++){if(l())return{kind:"host-exit"};let c=P(e,{commandTimeoutMs:n});try{let g=(await c.listSims()).find(t);if(g)return l()?{kind:"host-exit"}:{kind:"match",sim:g}}catch{}finally{c.close()}if(l())return{kind:"host-exit"};await y(i)}return{kind:"timeout"}}async function ln(e,n,t,r={}){let o=r.attempts??20,s=r.intervalMs??250;for(let i=0;i<o;i++){let a=P(e,{commandTimeoutMs:n});try{let d=(await a.listSims()).find(c=>c.id===t);if(!d||d.readyState!=="open")return!0}catch{return!0}finally{a.close()}await y(s)}return!1}function cn(e){let n=e.meta;if(!n||n.sootsimHostDriver!=="playwright")return null;let t=Number(n.sootsimHostPid);return!Number.isInteger(t)||t<=1||t===process.pid?null:t}function dn(e){if(!e.connectAckFile)return!1;try{return T.writeFileSync(e.connectAckFile,`${JSON.stringify({connectedAt:Date.now(),pid:e.pid??null})}
6
- `,{flag:"w"}),!0}catch{return!1}}function at(e){if(e.diagnosticLogPath)try{let n=T.readFileSync(e.diagnosticLogPath,"utf8").trim();if(!n){console.error(` ${C.basename(e.diagnosticLogPath)} was empty`);return}let t=n.length>4e3?`\u2026
7
- ${n.slice(-4e3)}`:n;console.error(` ${C.basename(e.diagnosticLogPath)}:`),console.error(t)}catch(n){let t=n instanceof Error?n.message:String(n);console.error(` failed to read ${C.basename(e.diagnosticLogPath)}: ${t}`)}}function ge(e){try{return process.kill(e,0),!0}catch(n){return n?.code==="EPERM"}}async function un(e,n=2500){let t=Date.now()+n;for(;Date.now()<t;){if(!ge(e))return!0;await y(100)}return!ge(e)}function mn(e){let n=Xe("ps",["-o","command=","-p",String(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}),t=Xe("ps",["eww","-o","command=","-p",String(e)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(n.status!==0||t.status!==0)return!1;let r=(n.stdout||"").trimEnd(),o=(t.stdout||"").trimEnd();return(o.startsWith(r)?o.slice(r.length):o).includes("SOOTSIM_PW_URL=")}async function pe(e,n){let t=new Set(n),r=new Set;for(let o of e){if(!t.has(o.id))continue;let s=cn(o);s&&r.add(s)}for(let o of r){if(!mn(o)){console.log(` skipped pid ${o}: not a rnx playwright host (stale sim record)`);continue}try{process.kill(o,"SIGTERM")}catch{}if(await un(o)){console.log(` closed playwright host process ${o}`);continue}try{process.kill(o,"SIGKILL"),console.log(` force-closed playwright host process ${o}`)}catch{}}}function J(e,n){if(n){let o=n.trim(),s=e.find(i=>i.id===o);if(!s)throw new Error(`no sim connected with id ${o}`);return s}let t=e.find(o=>o.isPrimary&&o.readyState==="open");if(t)return t;let r=e.find(o=>o.readyState==="open");if(r)return r;throw new Error("no sim connected")}function lt(e,n,t){console.log(` ${t==="current sim"?"loaded":"opened"}: ${e} [${t}]`),console.log(` current sim: ${n.id}`),console.log(JSON.stringify({simId:n.id,url:n.url},null,2))}async function ct(e,n,t){if(t.includes("--no-describe"))return;let r=process.env.SOOTSIM_QUIET_TARGET_NOTICE;process.env.SOOTSIM_QUIET_TARGET_NOTICE="1";try{await pn(e,n,{stableMs:150,maxMs:400});let o=P(e,{commandTimeoutMs:3e3,simId:n,cliLabel:"open --describe",simIdSource:"flag"});try{let s=null;try{s=await o.send({type:"evaluate",code:Ee})}catch{}if(s&&!(s.flag===!0&&!s.loadingText&&Ue(s))){let c=s.loadingText?`still showing "${s.loadingText}"`:s.flag!==!0?"guest ready event has not fired":s.targets<=0?"no visible app content is inspectable yet":"app tree is still stabilizing";console.log(` app still loading: ${c} (nodes: ${s.nodes}, targets: ${s.targets})`),console.log(" before interacting, run: rnxsim wait ready --max-ms 120000")}let a=`(async () => {
8
- const t = window.__sootsimTest
9
- const ms = window.SootSim?.bridges?.mainShell
10
- if (!t) return null
11
- let shell = null
12
- try { shell = ms?.getState ? await ms.getState() : null } catch {}
13
- const tree = await t.dumpTree(12, ${JSON.stringify({describe:!0,verbose:!1,filter:""})})
14
- return { tree, shell }
15
- })()`,l=await o.send({type:"evaluate",code:a});if(!l?.tree)return;if(console.log(""),l.shell?.state){let d=[`state=${l.shell.state}`,l.shell.activeApp?`app=${l.shell.activeApp}`:null].filter(Boolean);console.log(` shell: ${d.join(" ")}`)}console.log(l.tree)}finally{o.close()}}catch{}finally{r===void 0?delete process.env.SOOTSIM_QUIET_TARGET_NOTICE:process.env.SOOTSIM_QUIET_TARGET_NOTICE=r}}async function pn(e,n,t){let r=Date.now()+t.maxMs,o="(async () => (await window.__sootsimTest?.getNodeCount?.()) || 0)()",s=P(e,{commandTimeoutMs:2e3,simId:n,simIdSource:"flag"});try{let i=-1,a=0;for(;Date.now()<r;){let l=-1;try{let d=await s.send({type:"evaluate",code:o});typeof d=="number"&&(l=d)}catch{}if(l>=0&&l===i){if(Date.now()-a>=t.stableMs)return}else i=l,a=Date.now();await y(50)}}finally{s.close()}}async function fn(e,n={}){let t=U(e,{port:n.port,commandTimeoutMs:n.timeoutMs});t.positional.length!==1&&(console.error(" rnxsim open: expected exactly one <url-or-route>"),console.error(" examples: rnxsim open /settings | rnxsim open myapp://settings"),process.exit(1));let r;try{r=Tt(t.positional[0]??"")}catch(i){console.error(` rnxsim open: ${i instanceof Error?i.message:String(i)}`),process.exit(1)}let o=_(t),s=t.simId?` --sim ${t.simId}`:"";try{let i=await o.send({type:"call",path:"SootSim.bridges.test.openDeepLink",args:[r]});if(Ot(i)&&i.ok===!1)throw new Error(typeof i.error=="string"?i.error:"deep-link dispatch failed");console.log(` opened deep link: ${r}`)}catch(i){console.error(` link failed: ${i instanceof Error?i.message:String(i)}`),await A(o,{errorsCommand:`rnxsim get errors 5${s}`,warningsCommand:`rnxsim get warnings 5${s}`,requestsCommand:`rnxsim get requests 5${s}`}),process.exit(1)}finally{o.close()}}async function Yn(e,n={}){let t=U(e,{port:n.port,commandTimeoutMs:n.timeoutMs,stripBooleanFlags:["--new","--headless","--headed","--ephemeral","--hot","--no-hmr","--no-describe"],stripValueFlags:["--base-url","--replace","--driver","--profile","--cdp-port","--device"]}),r=e.find((f,m)=>e[m-1]==="--profile"),o=e.includes("--ephemeral"),s=e.find((f,m)=>e[m-1]==="--cdp-port"),i=s?Number(s):void 0;s&&(!Number.isFinite(i)||i<=0)&&(console.error(` rnxsim open: --cdp-port must be a positive port number, got "${s}"`),process.exit(1)),r&&o&&(console.error(" rnxsim open: --profile cannot be combined with --ephemeral"),process.exit(1));let a=r?Le(r).id:void 0,l=e.includes("--new")||!!a||o,d=Vt(e);l&&t.simIdSource==="flag"&&(console.error(" rnxsim open: --new, --profile, and --ephemeral cannot be combined with --sim"),process.exit(1));let c=t.positional[0]||"";if(Mt(c)){l&&(console.error(" rnxsim open: deep links target the current app; remove --new, --profile, or --ephemeral"),process.exit(1)),await fn(e,n);return}if(Ft(c)){let f=(()=>{try{return I(new URL(c).hostname)}catch{return!1}})();console.log(" that\u2019s an rnxsim preview/build link \u2014 a full player page, not a driveable sim."),console.log(" opening it in your browser for viewing\u2026");try{await qe(c,{background:!1})}catch(m){console.error(` could not launch a browser: ${m instanceof Error?m.message:String(m)}`),console.error(` open it yourself: ${c}`),process.exit(1)}console.log(f?" to drive it under the CLI, point `rnxsim open` at the app\u2019s dev port instead (e.g. `rnxsim open 8081`).":" the CLI can\u2019t drive a remote preview (the engine only attaches to the local bridge from localhost). to drive the app, run it locally and `rnxsim open <port>`.");return}let u=ut(c)?await he(c):void 0,g=await qt(u),O=await Fe(g),N=O?.runtimeVersion,F=De(O?{...O,runtimeVersion:void 0}:void 0,d);N&&await zt(N);let Q=e.find((f,m)=>e[m-1]==="--base-url");if(Q&&!t.explicitPort){let f=ie(Q);f&&(t.wsPort=f)}t.wsPort=await Dt(t.wsPort,t.explicitPort);let R=e.find((f,m)=>e[m-1]==="--driver")||"";R&&!rt(R)&&(console.error(` unknown driver "${R}" \u2014 run \`rnxsim list --drivers\``),process.exit(1));let S=rt(R)?R:"playwright",ft=_t(e,S);i&&S!=="playwright"&&(console.error(" rnxsim open: --cdp-port is only honored by the playwright driver"),process.exit(1));let we=e.includes("--hot"),be=e.includes("--no-hmr");we&&be&&(console.error(" rnxsim open: --hot and --no-hmr cannot be combined"),process.exit(1));let gt=we?!0:be?!1:R!=="playwright",k=e.find((f,m)=>e[m-1]==="--device");k&&!(k in se)&&(console.error(` rnxsim open: unknown device "${k}"`),console.error(` known devices: ${ke().join(", ")}`),process.exit(1));let Y=k?se[k]:void 0,j={hot:gt,device:k,resolvedBundle:u,project:g},ht=N?`http://localhost:${t.wsPort}/`:Q||Jt(t.wsPort),x=Gt(ht,N),ve=e.includes("--base-url");Oe(t.wsPort,x);let wt=D();if(!l){let f=_(t),m=t.simId?` --sim ${t.simId}`:"",ee=!1;try{let p=null,W=null;try{let h=await f.listSims();if(t.simIdSource==="saved")p=h.find(w=>w.id===wt&&w.readyState==="open"&&me(w,S))??null,p||B();else if(t.simIdSource==="flag"&&(p=J(h,t.simId),!me(p,S)))throw new Error(`sim ${p.id} is not managed by the ${S} driver`);if(!p&&t.simIdSource!=="flag"){W=await q(c,L(x,F),j);let w=new URL(W);w.searchParams.delete("inspectOpen"),p=h.find(v=>{if(v.readyState!=="open"||!v.url||!me(v,S))return!1;try{let $e=new URL(v.url);return $e.searchParams.delete("inspectOpen"),$e.toString()===w.toString()}catch{return!1}})??null}if(!p)if(t.simIdSource!=="flag")ee=!0;else throw new Error("no sim connected");if(!ee&&p){let w=ve||fe(c)?x:st(p,x),v=W??await q(c,L(w,F),j);f.send({type:"evaluate",simId:p.id,code:`window.location.href = ${JSON.stringify(v)}`}).catch(()=>{})}}catch(h){console.error(` open failed: ${h instanceof Error?h.message:String(h)}`),await A(f,{errorsCommand:`rnxsim get errors 5${m}`,warningsCommand:`rnxsim get warnings 5${m}`,requestsCommand:`rnxsim get requests 5${m}`}),process.exit(1)}if(!ee&&p){await y(1500);let h=await nn(t.wsPort,t.commandTimeoutMs,p.id);h||(console.error(" timed out waiting for current sim to load target"),process.exit(1)),h.bridge.close(),$(p.id);let w=ve||fe(c)?x:st(p,x),v=W??await q(c,L(w,F),j);lt(v,{...p,url:v},"current sim"),await ct(t.wsPort,p.id,e);return}}finally{f.close()}}let bt=L(x,F),ye=`cli-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,Se=await tn(c,bt,ye,j),xe=Re();xe||(console.error(" could not resolve a stable owning process; refusing unsupervised sim host"),process.exit(1));let vt=f=>f.url?.includes(`inspectOpen=${ye}`)??!1,E=Ve(S);E||(console.error(` unknown driver "${S}" \u2014 run \`rnxsim list --drivers\``),process.exit(1));let H=Ut(),b=await E.launch({url:Se,bridgePort:ie(x)??t.wsPort,headless:ft,profileId:a,ephemeralProfile:o,cdpPort:i,device:k,ownerPid:xe,viewport:Y?{width:Y.width+120,height:Y.height+60}:void 0,connectTimeoutMs:H.hostTimeoutMs});b.launched||(console.error(` ${E.name} driver: ${b.message}`),process.exit(1));let Z=await an(t.wsPort,t.commandTimeoutMs,vt,b.pid,{attempts:H.attempts,intervalMs:H.intervalMs});if(Z.kind==="host-exit"&&(at(b),console.error(` ${E.name} host crashed \u2014 sim is no longer attached`),process.exit(1)),Z.kind==="timeout"){if(b.pid)try{process.kill(b.pid,"SIGTERM"),console.error(` closed ${E.name} host process ${b.pid}`)}catch{}at(b),console.error(` timed out after ${H.timeoutMs}ms waiting for opened sim to connect`),process.exit(1)}let X=Z.sim;$(X.id),dn(b),lt(Se,X,`${E.name} driver`),await ct(t.wsPort,X.id,e)}async function pt(e,n={}){let t=U(e,{port:n.port,commandTimeoutMs:n.timeoutMs,stripBooleanFlags:["--force"]}),r=e.includes("--force"),o=_(t),s=t.simId?` --sim ${t.simId}`:"";try{try{let i=await o.listSims(),a=J(i,t.positional[0]||t.simId);if(a.lockedBy&&a.lockExpiresAt&&a.lockExpiresAt>Date.now()){let l=Math.max(0,Math.round((a.lockExpiresAt-Date.now())/1e3));a.lockedByKind==="user-active"&&(console.error(` refused: ${a.id} is locked by the active user (${l}s) \u2014 that's a live human tab`),console.error(" run `rnxsim open --new` for a fresh investigation sim"),process.exit(1)),r||(console.error(` refused: ${a.id} is leased by ${a.lockedBy} (${l}s)`),console.error(` \`sootsim use ${a.id} --force\` to take it, or \`rnxsim open --new\` for a fresh sim`),process.exit(1))}await o.focusSim(a.id),$(a.id),console.log(` using: ${a.id}`)}catch(i){console.error(` use failed: ${i instanceof Error?i.message:String(i)}`),await A(o,{errorsCommand:`rnxsim get errors 5${s}`,warningsCommand:`rnxsim get warnings 5${s}`,requestsCommand:`rnxsim get requests 5${s}`}),process.exit(1)}}finally{o.close()}}async function Zn(e,n={}){await pt(e,n)}async function Xn(e,n={}){await pt(e,n)}async function er(e,n={}){let t=U(e,{port:n.port,commandTimeoutMs:n.timeoutMs,stripBooleanFlags:["--force"]}),r=e.includes("--force"),o=_(t);try{try{let s=await o.listSims(),i=J(s,t.positional[0]||t.simId),a=r&&i.lockedBy&&i.lockedByKind!=="user-active"?i.lockedBy:null,l=await o.claim(i.id,{force:r});$(i.id);let d=Math.max(0,Math.round((l.lockExpiresAt-Date.now())/1e3)),c=l.bootedCount>0?` (booted ${l.bootedCount})`:"";console.log(` claimed: ${l.simId} [${d}s]${c}`),a&&console.log(` took over from: ${a}`)}catch(s){if(s instanceof Me){let i=Math.max(0,Math.round(s.lock.expiresInMs/1e3));console.error(` claim failed: locked by ${s.lock.by} for ${i}s more`),console.error(" use --force to take it, or `rnxsim open --new` for a fresh sim"),process.exit(1)}console.error(` claim failed: ${s instanceof Error?s.message:String(s)}`),process.exit(1)}}finally{o.close()}}async function gn(e,n,t,r){if(r.length===0)return{closed:[],remaining:[]};await Promise.all(r.map(s=>e.closeSim(s).catch(()=>{})));let o=new Set(r);for(let s=0;s<40;s++){let i=[];try{let a=P(n,{commandTimeoutMs:t});try{i=(await a.listSims()).filter(d=>o.has(d.id)&&d.readyState==="open").map(d=>d.id)}finally{a.close()}}catch{i=[]}if(i.length===0)return{closed:[...o],remaining:[]};if(s===39)return{closed:[...o].filter(a=>!i.includes(a)),remaining:i};await y(250)}return{closed:[...o],remaining:[]}}function hn(e,n){let t=e.filter(u=>u.readyState==="open"),r=t.map(u=>u.id),o=n.explicitKeepId?.trim()||"",s=n.savedKeepId?.trim()||"",i=s?t.some(u=>u.id===s):!1,a=s&&!i?s:null,l=null,d=null,c=null;if(n.closeOthers)if(o){let u=t.find(g=>g.id===o);u?l=u.id:d=o}else if(s&&i)l=s;else{let u=t.find(g=>g.isPrimary)??t[0]??null;u&&(l=u.id,s&&!i&&(c=u.id))}return{openIds:r,keepId:l,targets:d?[]:r.filter(u=>u!==l),staleSavedId:a,missingExplicitKeepId:d,fallbackKeepId:c}}async function tr(e,n={}){let t=U(e,{port:n.port,commandTimeoutMs:n.timeoutMs,stripBooleanFlags:["--all","--others"]}),r=_(t),o=t.simId?` --sim ${t.simId}`:"",s=e.includes("--all"),i=e.includes("--others");if(s||i){try{let a=await r.listSims(),l=D(),d=t.positional[0]||(t.simIdSource==="flag"?t.simId:void 0),c=hn(a,{closeOthers:i,explicitKeepId:d,savedKeepId:l});if(c.staleSavedId&&B(),c.fallbackKeepId&&($(c.fallbackKeepId),console.log(` saved sim ${c.staleSavedId} is gone \u2014 keeping primary ${c.fallbackKeepId}`)),c.missingExplicitKeepId&&(console.error(` close failed: keep sim ${c.missingExplicitKeepId} is not connected; not closing other sims`),process.exit(1)),c.targets.length===0){console.log(c.keepId?` nothing to close \u2014 only the kept sim ${c.keepId} is connected`:c.staleSavedId?` nothing to close \u2014 no sims connected (cleared stale current sim ${c.staleSavedId})`:" nothing to close \u2014 no sims connected");return}let u=await gn(r,t.wsPort,t.commandTimeoutMs,c.targets);await pe(a,c.targets);let g=D();g&&u.closed.includes(g)&&(c.keepId?$(c.keepId):B());let O=` closed ${u.closed.length} sim(s)${c.keepId?` (kept ${c.keepId})`:""}`;console.log(O),u.remaining.length>0&&(console.error(` close failed: still connected: ${u.remaining.join(", ")}`),process.exit(1))}catch(a){console.error(` close failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}finally{r.close()}return}try{try{let a=await r.listSims(),l=J(a,t.positional[0]||t.simId),d=a.find(u=>u.id!==l.id&&u.readyState==="open");await r.closeSim(l.id),await ln(t.wsPort,t.commandTimeoutMs,l.id)||(await pe(a,[l.id]),console.error(` close failed: ${l.id} is still connected`),process.exit(1)),await pe(a,[l.id]),D()===l.id&&(d?$(d.id):B()),console.log(` closed: ${l.id}`)}catch(a){console.error(` close failed: ${a instanceof Error?a.message:String(a)}`),await A(r,{errorsCommand:`rnxsim get errors 5${o}`,warningsCommand:`rnxsim get warnings 5${o}`,requestsCommand:`rnxsim get requests 5${o}`}),process.exit(1)}}finally{r.close()}}export{Ut as a,Tt as b,Dt as c,Gn as d,Gt as e,mt as f,Jt as g,q as h,tn as i,rn as j,Jn as k,Qn as l,an as m,cn as n,dn as o,pe as p,fn as q,Yn as r,Zn as s,Xn as t,er as u,gn as v,hn as w,tr as x};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{H as t,L as n,N as l,j as r}from"./chunk-66NF2KNG.js";function m(){let e=t(),i=r()?n():null;return i&&l(i)?{primary:`engine dev source (:${i.bridgePort})`,installedRuntime:e?`installed runtime v${e}`:null,isDevBridge:!0}:{primary:e?`runtime v${e}`:"runtime not installed",installedRuntime:null,isDevBridge:!1}}export{m as a};
@@ -1,6 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{b as C}from"./chunk-B7KMNHX7.js";import{f as h}from"./chunk-U4PN6JOT.js";import{G as B,O as b,g as S}from"./chunk-66NF2KNG.js";import a from"node:fs";import c from"node:path";var g=1,k=`automatic-cleanup-v${g}.json`,A=`automatic-cleanup-v${g}.lock`,P=360*60*1e3;function w(){let i=c.join(S(),k);try{return JSON.parse(a.readFileSync(i,"utf8")).generation===g}catch{return!1}}function N(i){if(i<1024)return`${i} B`;let e=["KiB","MiB","GiB","TiB"],n=i/1024,s=e[0];for(let r=1;r<e.length&&n>=1024;r++)n/=1024,s=e[r];return`${n.toFixed(n>=10?1:2)} ${s}`}function p(i){let e;try{e=a.lstatSync(i)}catch{return 0}let n=e.blocks>0?e.blocks*512:e.size;if(!e.isDirectory()||e.isSymbolicLink())return n;let s=n;try{for(let r of a.readdirSync(i))s+=p(c.join(i,r))}catch{}return s}function E(i){for(let e of["SingletonLock","SingletonSocket","lockfile"])try{if(a.lstatSync(c.join(i,e)))return!0}catch{}return!1}function v(i,e){let n;try{n=a.readdirSync(i,{withFileTypes:!0})}catch{return[]}let s=E(e),r=[];for(let t of n){if(!t.isDirectory()||t.isSymbolicLink())continue;let o=c.join(i,t.name);if(C(t.name)){r.push({path:o,bytes:p(o),kind:"browser-cache",state:s?"in-use":"safe",selected:!s,detail:s?"browser profile is open; close it before cleanup":"disposable browser HTTP, bytecode, or GPU cache"});continue}r.push(...v(o,e))}return r}function x(i){let e=c.join(i,"profiles","playwright"),n;try{n=a.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.flatMap(s=>{if(!s.isDirectory()||s.isSymbolicLink())return[];let r=c.join(e,s.name);return v(r,r)})}function L(i){let e=c.join(i,"electron","userData");return v(e,e)}function R(i,e){let n=c.join(i,"recordings"),s;try{s=a.readdirSync(n,{withFileTypes:!0})}catch{return[]}return s.map(r=>{let t=c.join(n,r.name);return{path:t,bytes:p(t),kind:"recording",state:"aggressive",selected:e,detail:"user-created recording or captured-frame output"}})}function U(i){let e=new Set(b()),n=[...e],s=h.planLocalRetention({retainVersions:2,protectVersions:n}),r=h.planLocalRetention({retainVersions:1,protectVersions:n}),t=new Set(s.removeVersions),o=new Set(r.removeVersions),l=new Set([...s.keepVersions,...s.removeVersions,...r.keepVersions,...r.removeVersions]),m=[];for(let u of[...l].sort()){let d=h.product.runtimeDir(u),y="retained",f="retained runtime";e.has(u)&&u!==s.activeVersion?(y="in-use",f="runtime is serving a connected simulator"):t.has(u)?(y="safe",f="inactive runtime outside the two-version rollback window"):o.has(u)?(y="aggressive",f="most recent rollback runtime"):u===s.activeVersion&&(f="active runtime; always protected"),m.push({path:d,bytes:p(d),kind:"runtime-version",state:y,selected:y==="safe"||y==="aggressive"&&i,detail:f})}for(let u of s.removeCacheFiles)m.push({path:u,bytes:p(u),kind:"runtime-archive",state:"safe",selected:!0,detail:"downloaded archive is unnecessary after successful extraction"});return{activeRuntime:s.activeVersion,entries:m}}function T(i={}){let e=i.aggressive===!0,n=S(),s=U(e),r=[...s.entries,...x(n),...L(n),...R(n,e)].sort((t,o)=>o.bytes-t.bytes||t.path.localeCompare(o.path));return{home:n,activeRuntime:s.activeRuntime,entries:r,reclaimableBytes:r.reduce((t,o)=>t+(o.selected?o.bytes:0),0),protectedBytes:r.reduce((t,o)=>t+(o.selected?0:o.bytes),0),totalBytes:p(n)}}function D(i,e){let n=c.relative(i,e);if(!n||n.startsWith("..")||c.isAbsolute(n))throw new Error(`refusing cleanup target outside the rnx data home: ${e}`)}function I(i={}){let e=T(i),n=i.aggressive===!0?1:2;h.pruneLocalRetention({retainVersions:n,protectVersions:b()});for(let t of e.entries)if(t.selected&&!(t.kind==="runtime-archive"||t.kind==="runtime-version")){if(t.kind==="browser-cache"){let l=c.relative(e.home,t.path).split(c.sep),m=l[0]==="profiles"&&l[1]==="playwright"&&l[2]?c.join(e.home,"profiles","playwright",l[2]):l[0]==="electron"&&l[1]==="userData"?c.join(e.home,"electron","userData"):null;if(m&&E(m)){t.state="in-use",t.selected=!1,t.detail="browser profile opened while cleanup was starting";continue}}D(e.home,t.path),a.rmSync(t.path,{recursive:!0,force:!0})}let s=e.entries.filter(t=>t.selected&&!a.existsSync(t.path)).map(t=>t.path),r=p(e.home);return{...e,removedPaths:s,reclaimedBytes:Math.max(0,e.totalBytes-r),remainingBytes:r}}function $(){B();let i=S(),e=c.join(i,k),n=c.join(i,A);if(w())return{status:"already-complete",reclaimedBytes:0,remainingBytes:0,deferredInUseBytes:0};let s=null;for(let r=0;r<2&&s===null;r++)try{let t=a.openSync(n,"wx");try{a.writeFileSync(t,`${JSON.stringify({pid:process.pid,startedAt:Date.now()})}
5
- `,"utf8"),s=t}catch(o){a.closeSync(t);try{a.unlinkSync(n)}catch{}throw o}}catch(t){if((t instanceof Error&&"code"in t?t.code:null)!=="EEXIST")throw t;let l=0,m=0,u=null;try{u=a.lstatSync(n);let d=JSON.parse(a.readFileSync(n,"utf8"));l=typeof d.pid=="number"?d.pid:0,m=typeof d.startedAt=="number"?d.startedAt:0}catch{}if(l>0&&m>0&&Date.now()-m<P)try{return process.kill(l,0),{status:"busy",reclaimedBytes:0,remainingBytes:0,deferredInUseBytes:0}}catch{}if(!u)continue;try{let d=a.lstatSync(n);if(d.dev!==u.dev||d.ino!==u.ino)return{status:"busy",reclaimedBytes:0,remainingBytes:0,deferredInUseBytes:0};a.unlinkSync(n)}catch{}}if(s===null)return{status:"busy",reclaimedBytes:0,remainingBytes:0,deferredInUseBytes:0};try{if(w())return{status:"already-complete",reclaimedBytes:0,remainingBytes:0,deferredInUseBytes:0};let r=I(),t=r.entries.reduce((l,m)=>l+(m.state==="in-use"?m.bytes:0),0);if(t>0)return{status:"deferred",reclaimedBytes:r.reclaimedBytes,remainingBytes:r.remainingBytes,deferredInUseBytes:t};let o=`${e}.${process.pid}.tmp`;return a.writeFileSync(o,`${JSON.stringify({generation:g,completedAt:Date.now(),reclaimedBytes:r.reclaimedBytes})}
6
- `,"utf8"),a.renameSync(o,e),{status:"complete",reclaimedBytes:r.reclaimedBytes,remainingBytes:r.remainingBytes,deferredInUseBytes:0}}finally{a.closeSync(s);try{a.unlinkSync(n)}catch{}}}export{w as a,N as b,T as c,I as d,$ as e};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- var p={"--help":{type:"boolean",short:"-h"},"--version":{type:"boolean",short:"-V"},"--verbose":{type:"boolean",short:"-v"},"--port":{type:"number",short:"-p"},"--device":{type:"string",short:"-d"},"--theme":{type:"string",short:"-t"},"--headless":{type:"boolean"},"--driver":{type:"string"},"--sim":{type:"string"},"--session":{type:"string"},"--tab":{type:"string"}},m=new Set(["list","describe","find","get","do","wait","network","logs","shell"]),d=new Set(["do","get","wait","shell","debug"]),b=new Set(["detox","maestro","record","film","storage","permissions","perf","screenshot","mode","inspect","debug","timeline","what-happened","shell","assert","device","open","list","use","claim","close","compat","report-issue","desktop","login","logout","auth","setup","serve","daemon","runtime","upgrade","update","version","skill","config","cleanup","app-fonts","agent-wrapper","agent",...m]);function u(c){let r=c.slice(2),e={command:null,commandArgs:[],globalFlags:{},help:!1,version:!1,verbose:!1},s=0;for(;s<r.length;){let o=r[s];if(o==="--"){e.commandArgs.push(...r.slice(s+1));break}let i=Object.entries(p).find(([a,t])=>a===o||t.short===o);if(i){let[a,t]=i,l=a.replace(/^--/,"");if(t.type==="boolean")e.globalFlags[l]=!0,s++;else{let n=r[s+1];if(n===void 0||n.startsWith("-")){console.error(` warning: ${o} requires a value`),s++;continue}if(t.type==="number"){let g=Number(n);if(Number.isNaN(g)){console.error(` warning: ${o} requires a number, got "${n}"`),s+=2;continue}e.globalFlags[l]=g}else e.globalFlags[l]=n;s+=2}continue}if(!e.command&&!o.startsWith("-")){let a=o.indexOf("-");if(a>0){let t=o.slice(0,a),l=o.slice(a+1);if(d.has(t)&&l.length>0){e.command=t;let n=r.slice(s+1);e.commandArgs=[l,...n[0]==="--"?n.slice(1):n];break}}if(b.has(o)){e.command=o;let t=r.slice(s+1);e.commandArgs=t[0]==="--"?t.slice(1):t;break}e.commandArgs=r.slice(s);break}e.commandArgs.push(o),s++}return e.help=!!e.globalFlags.help,e.version=!!e.globalFlags.version,e.verbose=!!e.globalFlags.verbose,e}export{m as a,u as b};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a}from"./chunk-EUAVBTKU.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";export{a as getCliVersion};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a,b,c,d,e,f}from"./chunk-YRV7HR3P.js";import"./chunk-N6A3SXMR.js";import"./chunk-TCWQJILS.js";import"./chunk-VZBLFMYC.js";import"./chunk-KR5BGMBZ.js";import"./chunk-HG7ORJMT.js";import"./chunk-TYE3WBSR.js";import"./chunk-5OX7ANRA.js";import"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import"./chunk-6UKJB2VC.js";import"./chunk-66NF2KNG.js";import"./chunk-EUAVBTKU.js";import"./chunk-ZMZTHU7V.js";import"./chunk-FTC4M26Q.js";import"./chunk-MENV7VLD.js";export{c as daemonInstall,b as getDaemonServiceStatus,a as runDaemon,e as teardownDaemonService,d as teardownLegacyMacDaemonArtifacts,f as teardownSootsimHome};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import"./chunk-37I5AIS7.js";import{f as a,g as b,h as c,i as d,j as e,k as f,l as g}from"./chunk-GZDHEONW.js";import"./chunk-G74YIEVS.js";import"./chunk-B7KMNHX7.js";import"./chunk-7VWOSTD5.js";import"./chunk-66NF2KNG.js";import"./chunk-MENV7VLD.js";export{c as ALL_DRIVERS,g as buildDriverListRows,a as electronDriver,d as getAllDrivers,e as getDriver,b as playwrightDriver,f as resolveDriver};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{c,d,e,f,g,h}from"./chunk-MNGQ42QE.js";import"./chunk-BRIZOR4K.js";import"./chunk-2SA2VTGP.js";import{b as a,c as b}from"./chunk-KZW5WBGU.js";import"./chunk-LDQ7HVCW.js";import"./chunk-Q3RGLERJ.js";import"./chunk-Y2FSZSO7.js";import"./chunk-NPVGMH2N.js";import"./chunk-BKNOLP3J.js";import"./chunk-HMDOLCKG.js";import"./chunk-SI3BUTQR.js";import"./chunk-274UD5FD.js";import"./chunk-XRGEEPJ5.js";import"./chunk-TGQNQ6XT.js";import"./chunk-GZDHEONW.js";import"./chunk-G74YIEVS.js";import"./chunk-T4FT6CM7.js";import"./chunk-YZRFF4YA.js";import"./chunk-4BXCZHAU.js";import"./chunk-FWYYCUAZ.js";import"./chunk-AY47WKS5.js";import"./chunk-3D57IBPC.js";import"./chunk-7INBNA3U.js";import"./chunk-PEPUGJVI.js";import"./chunk-N6A3SXMR.js";import"./chunk-TCWQJILS.js";import"./chunk-B7KMNHX7.js";import"./chunk-U4PN6JOT.js";import"./chunk-HG7ORJMT.js";import"./chunk-TYE3WBSR.js";import"./chunk-5OX7ANRA.js";import"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import"./chunk-6UKJB2VC.js";import"./chunk-66NF2KNG.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";export{e as discoverSootsimUrl,c as getLastFlowPreviewUploadResult,d as getLastFlowTraceSteps,g as hoistLeadingSimFlag,a as parseFlowFile,f as runFlowPlayback,h as runMaestroAuthoring,b as validateFlowFile};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a,b,c}from"./chunk-VZBLFMYC.js";import"./chunk-KR5BGMBZ.js";import"./chunk-HG7ORJMT.js";import"./chunk-TYE3WBSR.js";import"./chunk-5OX7ANRA.js";import"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import"./chunk-6UKJB2VC.js";import"./chunk-66NF2KNG.js";import"./chunk-EUAVBTKU.js";import"./chunk-ZMZTHU7V.js";import"./chunk-FTC4M26Q.js";import"./chunk-MENV7VLD.js";export{c as printCommandHelp,b as printGroupHelp,a as printHelp};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-66NF2KNG.js";import"./chunk-MENV7VLD.js";export{b as ACTIVE_RUNTIME_FILE,e as CONFIG_FILE,f as DAEMON_HEARTBEAT_STALE_MS,c as DAEMON_LOCKFILE,d as DEV_BRIDGE_LOCKFILE,a as SOOTSIM_HOME_ENV,J as activeRuntimeDir,m as activeRuntimeFile,u as cacheDir,R as claimDaemonLockfile,x as configFilePath,F as consumeRuntimeUpgradeNotice,s as daemonAppBundlePath,r as daemonAppDir,t as daemonAppLauncherPath,v as daemonLockfilePath,w as devBridgeLockfilePath,n as electronDir,o as electronUserDataDir,p as electronVersionDir,G as ensureSootsimHome,M as isDaemonLockfileFresh,N as isDevBridgeLockfileFresh,i as isDevWorkstation,h as isSootsimDevCheckout,q as profilesDir,H as readActiveRuntime,K as readDaemonLockfile,L as readDevBridgeLockfile,O as readLiveRuntimeVersions,C as readOrCreateAnonymousId,A as readPrivacyPreferences,y as readSharedConfig,S as removeDaemonLockfile,T as removeDevBridgeLockfile,l as runtimeDir,D as runtimeUpgradeNoticePath,k as runtimesDir,j as shouldSkipPersistentDaemon,g as sootsimHomeDir,I as writeActiveRuntime,P as writeDaemonLockfile,Q as writeDevBridgeLockfile,B as writePrivacyPreferences,E as writeRuntimeUpgradeNotice,z as writeSharedConfig};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{i as a,j as b}from"./chunk-KZW5WBGU.js";import"./chunk-LDQ7HVCW.js";import"./chunk-Q3RGLERJ.js";import"./chunk-Y2FSZSO7.js";import"./chunk-HMDOLCKG.js";import"./chunk-SI3BUTQR.js";import"./chunk-274UD5FD.js";import"./chunk-XRGEEPJ5.js";import"./chunk-TGQNQ6XT.js";import"./chunk-GZDHEONW.js";import"./chunk-G74YIEVS.js";import"./chunk-T4FT6CM7.js";import"./chunk-YZRFF4YA.js";import"./chunk-4BXCZHAU.js";import"./chunk-FWYYCUAZ.js";import"./chunk-AY47WKS5.js";import"./chunk-3D57IBPC.js";import"./chunk-7INBNA3U.js";import"./chunk-PEPUGJVI.js";import"./chunk-B7KMNHX7.js";import"./chunk-U4PN6JOT.js";import"./chunk-HG7ORJMT.js";import"./chunk-TYE3WBSR.js";import"./chunk-5OX7ANRA.js";import"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import"./chunk-6UKJB2VC.js";import"./chunk-66NF2KNG.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";export{a as printShellPerfReport,b as runInspect};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a}from"./chunk-WBT32R6N.js";import"./chunk-VUFRB347.js";import"./chunk-G74YIEVS.js";import"./chunk-MENV7VLD.js";export{a as runInstallDesktop};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{c as a}from"./chunk-L24Z3CRS.js";import"./chunk-AY47WKS5.js";import"./chunk-3D57IBPC.js";import"./chunk-7INBNA3U.js";import"./chunk-U4PN6JOT.js";import"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import"./chunk-66NF2KNG.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";export{a as runRuntime};
@@ -1,44 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{b as Se,c as J,d as ye,e as V,f as ve,h as be,i as P,j as we,k as Ae,l as ke,m as Te,q as Ce,t as k,u as Ie,v as Ee,w as Pe,x as Re}from"./chunk-TBMVBI26.js";import"./chunk-DM6KUAOZ.js";import{e as ge}from"./chunk-NPVGMH2N.js";import"./chunk-BKNOLP3J.js";import{a as ue,b as pe,d as me,e as L,f as he}from"./chunk-SI3BUTQR.js";import{d as fe}from"./chunk-T4FT6CM7.js";import{g as _}from"./chunk-YZRFF4YA.js";import"./chunk-FWYYCUAZ.js";import"./chunk-3D57IBPC.js";import"./chunk-7INBNA3U.js";import{a as F,b as G,c as oe,d as ae}from"./chunk-N6A3SXMR.js";import"./chunk-TCWQJILS.js";import{f as O}from"./chunk-U4PN6JOT.js";import{c as de,d as le}from"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import{E as Y,G as x,H as j,I as Z,J as Q,K as ee,M as te,P as ie,Q as re,R as ne,S as $,T as se,g as q,h as z,y as W,z as X}from"./chunk-66NF2KNG.js";import{a as ce}from"./chunk-EUAVBTKU.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";import{spawn as yt}from"child_process";import C from"fs";import{createServer as vt}from"http";import b from"path";import{WebSocket as g,WebSocketServer as bt}from"ws";import Oe from"node:fs";import B from"node:path";import{spawn as Ke}from"node:child_process";function Ge(o){return typeof o.text=="string"?o.text.trim():""}function qe(o){let e=o?.trim();return e||"tm"}async function xe(o){let e=o.sessionId.trim();if(!G(e))throw new Error(`invalid Team Machine session id: ${e||"<empty>"}`);let t=Ge(o.prompt);if(!t)throw new Error("prompt text is empty");let i=qe(o.command),s=o.timeoutMs??15e3;await new Promise((n,c)=>{let r=Ke(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),a="",d=setTimeout(()=>{try{r.kill("SIGTERM")}catch{}c(new Error(`tm send timed out after ${Math.round(s/1e3)}s`))},s);r.stderr?.setEncoding("utf8"),r.stderr?.on("data",l=>{a.length<4e3&&(a+=String(l))}),r.on("error",l=>{clearTimeout(d),c(l)}),r.on("exit",(l,u)=>{if(clearTimeout(d),l===0){n();return}let p=a.trim();c(new Error(p||`tm send exited with ${u?`signal ${u}`:`code ${l??"unknown"}`}`))})})}var M=1,ze=25;function Xe(){return[Number(process.env.VITE_PORT_WEB||process.env.PORT||3e3),Number(process.env.VITE_PORT_ZERO||7849),Number(process.env.VITE_PORT_R2||9500)].filter(o=>Number.isFinite(o)&&o>0)}var D=class{subscriptions=new Map;sessionsBySocket=new Map;allSockets=new Set;pendingPromptEchoes=new Map;pendingTurns=new Map;pendingSessionStates=new Map;pendingSessionPatches=new Map;sessionStatusPersistTimer=null;opts;constructor(e={}){this.opts=e}registerSocket(e){this.allSockets.add(e)}unregisterSocket(e){let t=this.sessionsBySocket.get(e);if(t){for(let i of t)this.decrementSubscription(i);this.sessionsBySocket.delete(e)}this.allSockets.delete(e)}async handleMessage(e,t){let i=t?.type;if(typeof i!="string"||!i.startsWith("agent:"))return!1;let s=t.id;try{let n=await this.dispatch(e,i,t);this.respond(e,s,n)}catch(n){n instanceof k?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await Te()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
5
- `)}}close(){this.sessionStatusPersistTimer&&(clearTimeout(this.sessionStatusPersistTimer),this.sessionStatusPersistTimer=null),this.flushSessionStatuses();for(let e of this.subscriptions.values())try{e.unsubscribe()}catch{}this.subscriptions.clear(),this.sessionsBySocket.clear(),this.allSockets.clear()}async dispatch(e,t,i){switch(t){case"agent:list-projects":return V();case"agent:upsert-project":return J(i.input??{});case"agent:delete-project":return be(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return we(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-claimed-prompt":return this.sendClaimedPrompt(i);case"agent:send-prompt":{let n=String(i.sessionId),c=P(n);if(!c)throw new k("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await Ee(n,r),this.notePromptAccepted(n,r,c.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await Pe(String(i.sessionId));let s=P(String(i.sessionId));return s&&this.broadcastSessionStatus(s),{ok:!0};case"agent:get-transcript":return this.getTranscript(String(i.sessionId));case"agent:get-paths":return this.getPaths();case"agent:subscribe-events":return this.subscribeSocket(e,String(i.sessionId));case"agent:unsubscribe-events":return this.unsubscribeSocket(e,String(i.sessionId));default:throw new k("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new k("NO_SIM","agent:send-claimed-prompt requires simId");let i=this.opts.resolveCliLease?.(t)??null;if(!i||i.kind!=="cli"||i.expiresAt<=Date.now())throw new k("NO_CLAIM",`sim ${t} has no active CLI claim`);let s=F(i.cliIdentityKey);if(!s)throw new k("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await xe({sessionId:s,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"team-machine",sessionId:s}}async doStartSession(e){if(!ye(e.projectId))throw new k("NO_PROJECT",`no project: ${e.projectId}`);let i=await Ie(e);return this.broadcastSessionStatus(i.session),i}async autoAttachForUrl(e){let t=e.bundleUrl??"",i=(()=>{try{return new URL(t).port||null}catch{return null}})();if(!i)return{project:null};let s=this.opts.getExcludePorts?.()??Xe(),c=(await _({excludePorts:s})).find(l=>String(l.port)===i);if(!c||!c.cwd)return{project:null};let r=V().find(l=>l.cwd===c.cwd)??null,a=Array.from(new Set([...r?.knownBundleUrls??[],c.bundleUrl,t]));return{project:J({cwd:c.cwd,name:c.projectName??B.basename(c.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[c.cwd],knownBundleUrls:a,framework:r?.framework??Ye(c.framework),bundleId:c.bundleId??r?.bundleId})}}getTranscript(e){let t=Ce(e);return Oe.existsSync(t)?Oe.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=Se();return{userDataDir:e,storeFile:B.join(e,"attached-projects.json"),sessionsDir:B.join(e,"sessions"),transcriptsDir:B.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let s=this.subscriptions.get(t);if(s)return s.refCount++,{ok:!0,refCount:s.refCount};let n=Re(t,c=>{let r=this.coalescePromptEcho(t,c);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),c.type==="turn-completed"){let a=P(t);if(a)try{ve(a.projectId,{usd:c.costUsd,ts:c.ts})}catch(d){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${d instanceof Error?d.message:String(d)}
6
- `)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let c=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,c);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:c>1,pendingTurns:c,queueDepth:Math.max(0,c-1)}}applySessionEvent(e,t){switch(t.type){case"prompt-received":case"turn-started":this.patchSession(e,{status:"working",needsAttention:!1});return;case"turn-completed":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"idle",needsAttention:!1,lastTurnFiles:t.filesTouched,currentlyEditing:void 0});return}case"approval-needed":this.patchSession(e,{status:"needs-attention",needsAttention:!0});return;case"error":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"needs-attention",needsAttention:i<=0,currentlyEditing:void 0});return}case"exited":this.clearPromptTracking(e),this.patchSession(e,{status:"ended",needsAttention:!1,wrapperPid:void 0,currentlyEditing:void 0});return;case"ready":case"turn-reasoning":case"turn-message":case"turn-plan":case"tool-call":case"file-edited":case"file-diff-delta":return}}patchSession(e,t){let i=this.pendingSessionStates.get(e)??P(e);if(!i)return;let s=Ae(i,t);this.pendingSessionStates.set(e,s),this.pendingSessionPatches.set(e,{...this.pendingSessionPatches.get(e),...t}),this.broadcastSessionStatus(s),!this.sessionStatusPersistTimer&&(this.sessionStatusPersistTimer=setTimeout(()=>{this.sessionStatusPersistTimer=null,this.flushSessionStatuses()},ze))}flushSessionStatuses(){if(this.pendingSessionPatches.size===0)return;let e=this.pendingSessionStates,t=this.pendingSessionPatches;this.pendingSessionStates=new Map,this.pendingSessionPatches=new Map;try{ke([...t].map(([i,s])=>({id:i,patch:s})))}catch(i){for(let[s,n]of e)this.pendingSessionStates.has(s)||this.pendingSessionStates.set(s,n);for(let[s,n]of t)this.pendingSessionPatches.set(s,{...n,...this.pendingSessionPatches.get(s)});process.stderr.write(`[sootsim-agent] session status persistence failed: ${i instanceof Error?i.message:String(i)}
7
- `)}}coalescePromptEcho(e,t){if(t.type!=="prompt-received")return t;let i=this.pendingPromptEchoes.get(e);if(!i||i.length===0)return t;for(;i.length>0&&Date.now()-i[0].sentAt>15e3;)i.shift();return i.length===0?(this.pendingPromptEchoes.delete(e),t):(i.shift(),i.length===0?this.pendingPromptEchoes.delete(e):this.pendingPromptEchoes.set(e,i),null)}consumeSettledTurn(e){let t=Math.max(0,(this.pendingTurns.get(e)??1)-1);return t>0?this.pendingTurns.set(e,t):this.pendingTurns.delete(e),t}clearPromptTracking(e){this.pendingPromptEchoes.delete(e),this.pendingTurns.delete(e)}fanOutEvent(e,t){let i=JSON.stringify({type:"agent:event",sessionId:e,event:t});for(let[s,n]of this.sessionsBySocket)if(n.has(e)&&s.readyState===M)try{s.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===M)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===M)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===M)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function Ye(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Le from"http";import Be from"https";import{finished as et,pipeline as tt}from"stream/promises";var K="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",Ze=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function Qe(o){let e=o.toLowerCase();for(let t of Ze)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function _e(o){let e=Qe(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":K},...e?.headers}}var it=new Set(["host","origin","referer","user-agent","accept-encoding","cookie","connection","keep-alive","transfer-encoding","upgrade","content-length","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]),rt={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,PUT,DELETE,PATCH,OPTIONS","access-control-allow-headers":"*","access-control-expose-headers":"*","access-control-max-age":"3600"},nt=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function Me(o){return o.protocol!=="https:"?{}:ue(o.hostname)?{rejectUnauthorized:!1}:{}}function R(o){for(let[e,t]of Object.entries(rt))o.setHeader(e,t)}function st(o,e){let t=[],i=e;i?.code&&t.push(i.code),i?.message&&t.push(i.message),i?.cause?.code&&t.push(i.cause.code),i?.cause?.message&&t.push(i.cause.message);let n=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function ot(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(it.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?_e(e):{"user-agent":K}),t}function at(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(nt.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function De(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function Ne(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function He(o,e){if(o.method==="OPTIONS"){R(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){R(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{R(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n;if(o.method!=="GET"&&o.method!=="HEAD"){let a=[];for await(let d of o)a.push(Buffer.isBuffer(d)?d:Buffer.from(d));a.length>0&&(n=Buffer.concat(a))}let c=o.method||"GET",r=async(a,d,l,u)=>{let p=a.protocol==="https:"?Be:Le,m=ot(o.headers,a);a.origin!==s.origin&&(delete m.authorization,delete m["proxy-authorization"]),d==="GET"||d==="HEAD"?(delete m["content-length"],delete m["content-type"]):l&&(m["content-length"]=String(l.byteLength));let y=await new Promise((w,A)=>{let S=p.request({hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:a.pathname+a.search,method:d,headers:m,...Me(a)},w),I=()=>S.destroy(new Error("fetch proxy client disconnected"));o.once("aborted",I),S.once("close",()=>o.off("aborted",I)),S.once("error",A),l===void 0?S.end():S.end(l)}),f=y.statusCode??502,h=y.headers.location;if(h&&(f===301||f===302||f===303||f===307||f===308)){if(u>=10)throw y.destroy(),new Error("too many redirects");let w=(f===301||f===302)&&d==="POST"||f===303&&d!=="GET"&&d!=="HEAD",A=new URL(h,a);y.resume(),await et(y),await r(A,w?"GET":d,w?void 0:l,u+1);return}for(let[w,A]of Object.entries(y.headers)){let S=w.toLowerCase();A===void 0||S==="set-cookie"||S==="connection"||S==="keep-alive"||S==="proxy-authenticate"||S==="proxy-authorization"||S==="te"||S==="trailer"||S==="transfer-encoding"||S==="upgrade"||S.startsWith("access-control-")||e.setHeader(w,A)}R(e);let v=y.headers["set-cookie"]??[];v.length>0&&e.setHeader("x-sootsim-set-cookie",(Array.isArray(v)?v:[v]).join(", ")),e.statusCode=f,await tt(y,e)};try{await r(s,c,n,0)}catch(a){if(e.headersSent){e.destroy(a instanceof Error?a:new Error(String(a)));return}R(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${st(s.href,a)}`)}}function Ue(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let d=new URL(t,"http://sootsim.local");i=d.searchParams.get("path")||"",s=d.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let c=n.protocol==="https:"?Be:Le,r=at(o.headers,n),a=c.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:r,...Me(n)},d=>{let l=Object.keys(d.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(d.statusCode??502,{...d.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":l}),d.pipe(e)});return a.on("error",d=>{e.statusCode=502,e.end(`app proxy error: ${d.message}`)}),o.pipe(a),!0}import{WebSocket as T,WebSocketServer as ct}from"ws";var dt="/__websocket-proxy",lt=new Set(["host","connection","upgrade","transfer-encoding","content-length","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version"]);function E(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
8
- Connection: close\r
9
- Content-Type: text/plain\r
10
- Content-Length: ${t.length}\r
11
- \r
12
- ${t}`)}catch{}o.destroy()}function ut(o){let e=o.headers.origin,t=o.headers.host;if(!e||!t)return!1;try{return new URL(e).host===t}catch{return!1}}function pt(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,c]of Object.entries(i))c!=null&&(lt.has(n.toLowerCase())||(s[n]=Array.isArray(c)?c.join(", "):String(c)));return s}function mt(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function ht(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function N(o,e,t){if(!(o.readyState===T.CLOSED||o.readyState===T.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function ft(o,e){let t=!1,i=(s,n,c,r)=>{t||(t=!0,N(n,c,r.toString()),s.readyState===T.OPEN&&N(s,c,r.toString()))};o.on("message",(s,n)=>{e.readyState===T.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===T.OPEN&&o.send(s,{binary:n})}),o.on("close",(s,n)=>i(o,e,s,n)),e.on("close",(s,n)=>i(e,o,s,n)),o.on("error",()=>N(e,1011,"proxy client error")),e.on("error",()=>N(o,1011,"upstream websocket error"))}function gt(o,e,t,i){let s={...t},n=Object.keys(s).filter(c=>c.toLowerCase()==="origin");if(i&&n.length===0)s.origin=mt(o);else if(!i)for(let c of n)delete s[c];return Object.keys(s).length===0?new T(o.href,e):new T(o.href,e,{headers:s})}function St(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===dt}catch{return!1}}function Fe(o,e,t,i=!0){if(!St(o.url))return!1;if(!ut(o))return E(e,403,"forbidden websocket proxy origin"),!0;let s,n;try{let d=new URL(o.url||"/","http://localhost"),l=d.searchParams.get("url");if(!l)return E(e,400,"missing websocket proxy url"),!0;if(s=new URL(l),s.protocol!=="ws:"&&s.protocol!=="wss:")return E(e,400,"invalid websocket proxy protocol"),!0;n=pt(d.searchParams.get("headers"))}catch{return E(e,400,"invalid websocket proxy request"),!0}let c=ht(o),r=gt(s,c,n,i),a=!1;return e.once("close",()=>{a||r.terminate()}),r.once("open",()=>{if(a)return;a=!0;let d=r.protocol;new ct({noServer:!0,clientTracking:!1,handleProtocols(u){return d||u.values().next().value||!1}}).handleUpgrade(o,e,t,u=>{ft(u,r)})}),r.once("error",()=>{a||(a=!0,E(e,502,"upstream websocket error"))}),r.once("close",()=>{a||(a=!0,E(e,502,"upstream websocket closed"))}),!0}var wt="require-corp",At=new Set(["tap","keyboard"]),kt=2e3,Tt=1e3;function Ct(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:At.has(o.type)}var We=5e3,It=3600*1e3,Et="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",Pt={".html":"text/html; charset=utf-8",".js":"application/javascript",".cjs":"application/javascript",".mjs":"application/javascript",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json",".txt":"text/plain; charset=utf-8"};function je(o,e,t){let i;try{let a=W();i=JSON.stringify(a)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",c=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(ce())};</script>`,r=o.toString("utf8");return r.includes("<head>")?r.replace("<head>",`<head>${c}`):r.includes("</head>")?r.replace("</head>",c+"</head>"):r.includes("</body>")?r.replace("</body>",c+"</body>"):c+r}function $e(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var H=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;contrastOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new D({getExcludePorts:e.agentScanExcludes,resolveCliLease:t=>{let i=this.sims.get(t),s=i?this.getActiveLease(i):null;return s?{kind:s.kind,cliIdentityKey:s.cliIdentityKey,expiresAt:s.expiresAt}:null}}),this.contrastOrigin=e.contrastOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??o.SIM_IDLE_REAP_TTL_MS,this.automationSimIdleReapTtlMs=e.automationSimIdleReapTtlMs??o.AUTOMATION_SIM_IDLE_REAP_TTL_MS,this.maxConcurrentAutomationSims=e.maxConcurrentAutomationSims??o.MAX_CONCURRENT_AUTOMATION_SIMS,this.automationSimActiveGraceMs=e.automationSimActiveGraceMs??o.AUTOMATION_SIM_ACTIVE_GRACE_MS}getAgentHost(){return this.agentHost}reapIdleSimsForTest(e=Date.now()){this.reapIdleSims(e)}start(e){this.startAsync(e)}async startAsync(e){if(this.httpServer||this.wss)return this.effectivePort;this.refreshActiveRuntime();for(let t=0;t<this.portFallbackCount;t++){let i=this.preferredPort+t;try{return await this.bindOnce(i,e?.silent===!0),this.effectivePort=i,this.port=i,this.startedAt=Date.now(),t>0&&!e?.silent&&process.stderr.write(`ws bridge bound to port ${i} (preferred ${this.preferredPort} was taken)
13
- `),this.afterBind(),i}catch(s){if(s?.code!=="EADDRINUSE")throw s;e?.silent||process.stderr.write(`ws bridge port ${i} already in use, trying ${i+1}
14
- `)}}throw new Error(`could not bind ws bridge after ${this.portFallbackCount} attempts starting at ${this.preferredPort}`)}bindOnce(e,t){return new Promise((i,s)=>{let n=vt((a,d)=>this.handleHttpRequest(a,d)),c=!1,r=a=>{if(!c){c=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,s(a)}};n.once("error",r),n.listen(e,"127.0.0.1",()=>{c||(c=!0,n.removeListener("error",r),n.on("error",a=>{process.stderr.write(`ws bridge http error: ${String(a)}
15
- `)}),this.httpServer=n,this.wss=new bt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(a,d,l)=>{Fe(a,d,l)||this.wss?.handleUpgrade(a,d,l,u=>{this.wss?.emit("connection",u,a)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,s=i?"sim":"cli",n=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),s==="sim")n={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(n.id,n),this.writeConnectedRuntimeSnapshot(),this.shouldPromoteSim(n)&&(this.primarySimId=n.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let c=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,c)}e.on("message",c=>{let r;try{r=JSON.parse(c.toString())}catch{return}if(!(!r||typeof r!="object")){if(typeof r.type=="string"&&r.type.startsWith("agent:")){this.agentHost.handleMessage(e,r);return}if(r.type==="runtime:list"){let a=O.listInstalled(),d=this.getActiveRuntime(),l={type:"runtime:list:ok",id:r.id,installed:a,active:d.version,activeRuntimeDir:d.runtimeDir};try{e.send(JSON.stringify(l))}catch{}return}if(r.type==="runtime:use"){let a=typeof r.version=="string"?r.version:"";if(!O.listInstalled().includes(a)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${a||"(missing)"} is not installed`}))}catch{}return}let l=this.setActiveRuntime(a);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:l.version,runtimeDir:l.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let a=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:a.version,activeRuntimeDir:a.runtimeDir}))}catch{}return}if(s==="sim"&&r.type==="bridge:hello"&&n&&!n.url){let a=n.id;this.sims.delete(a),this.primarySimId===a&&(this.primarySimId=this.getOpenSim()?.id??null),n=null,s="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.writeConnectedRuntimeSnapshot(),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let l=r,u=this.tryRestoreSimId(n,l.simId);n.url=l.url,n.title=l.title,n.userAgent=l.userAgent,this.writeConnectedRuntimeSnapshot(),typeof l.kind=="string"&&l.kind.trim()&&(n.kind=l.kind.trim()),l.meta&&typeof l.meta=="object"&&(n.meta=l.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let l=r;this.updateUserFocusLease(n,l);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){if(!r.patch||typeof r.patch!="object"||Array.isArray(r.patch))return;let l=Object.fromEntries(Object.entries(r.patch));try{this.writeAndBroadcastSharedConfig(l)}catch(u){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${u instanceof Error?u.message:String(u)}
16
- `);return}return}if(r.type==="bridge:open-path"){let l=typeof r.path=="string"?r.path:"",u=typeof r.line=="number"&&Number.isFinite(r.line)?r.line:void 0,p=typeof r.column=="number"&&Number.isFinite(r.column)?r.column:void 0;l&&this.openPathInEditor(l,u,p);return}if(r.type==="bridge:boot-clients"&&n){let l=[];for(let[p,m]of this.cliSimBySocket)m===n.id&&l.push(p);for(let p of l){this.cliSimBySocket.delete(p);try{p.close(1e3,"booted by sim")}catch{}}let u=!!n.cliLease;n.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`rnx booted ${l.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
17
- `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let a=this.pendingCommands.get(r.id);if(a){this.pendingCommands.delete(r.id),r.error?a.reject(new Error(r.error)):a.resolve(r.result);return}let d=this.cliBySentId.get(r.id);if(d&&(this.cliBySentId.delete(r.id),d.ws.readyState===g.OPEN)){let l=this.getOtherCliIdentityCount(d.ws,d.simId),u=l>0?{...r,id:d.originalId,_otherCliCount:l}:{...r,id:d.originalId};d.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[m,y]of this.cliBySentId)y.ws===e&&this.cliBySentId.delete(m);p&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let p=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:p,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:claim"){let p=await this.waitForSim(r.simId),m=this.tryAcquireLease(e,p,{force:r.force===!0});if(!m.granted){e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${p.id} is locked by another cli`,_locked:m.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,m.bootedCount>0?`cli force-claimed sim (booted ${m.bootedCount})`:"cli claimed sim"),e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:p.id,lockedBy:m.lease.cliIdentityKey,lockExpiresAt:m.lease.expiresAt,bootedCount:m.bootedCount}}));return}let a=await this.waitForSim(r.simId);if(Ct(r)){let p=this.tryAcquireLease(e,a);if(!p.granted){e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${a.id} is locked by another cli \u2014 use \`rnxsim claim ${a.id} --force\` or \`rnxsim open --new\``,_locked:p.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,a.id),this.recordSimAction(a.id,this.describeForwardedCommand(r));let d=this.nextCommandId++;this.cliBySentId.set(d,{simId:a.id,ws:e,originalId:r.id});let{simId:l,...u}=r;if(a.ws.send(JSON.stringify({...u,id:d})),u.type==="close"){this.cliBySentId.delete(d),e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:a.id}}));let p=a.ws,m=setTimeout(()=>{this.closeSimSocketFromHost(p)},kt);$e(m)}}catch(a){e.readyState===g.OPEN&&e.send(JSON.stringify({id:r.id,error:a instanceof Error?a.message:String(a)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[c,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(c));for(let[c,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===g.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(c));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let c=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,a]of this.cliBySentId)a.ws===e&&this.cliBySentId.delete(r);c&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
18
- `),this.cliIdleTimer=setInterval(()=>this.sweepIdleCliClients(),3e4),this.cliIdleTimer.unref(),this.wsHeartbeatTimer=setInterval(()=>this.sweepDeadWebSockets(),o.WS_HEARTBEAT_INTERVAL_MS),this.wsHeartbeatTimer.unref(),this.shouldWriteLockfile){try{if(x(),!ne(this.buildLockfileSnapshot()))throw new Error("another rnx daemon wrote the lockfile during startup \u2014 aborting")}catch(e){throw process.stderr.write(`ws bridge failed to claim daemon lockfile: ${String(e)}
19
- `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},We),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}if(this.shouldWriteDevLockfile){try{this.writeDevLockfileSnapshot()}catch(e){process.stderr.write(`ws bridge failed to write dev bridge lockfile: ${String(e)}
20
- `)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},We),this.devHeartbeatTimer.unref()}this.agentHost.seedOnBoot()}bootstrapping=!0;connectedRuntimeVersions(){let e=new Set;for(let t of this.sims.values())try{let i=new URL(t.url||t.origin||"http://localhost"),s=L(i.hostname);s&&e.add(s)}catch{}return[...e].sort()}buildLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,activeRuntimeDir:this.activeRuntimeDirPath,servedRuntimes:this.connectedRuntimeVersions(),startedAt:this.startedAt,heartbeatAt:Date.now(),bootstrapping:this.bootstrapping}}buildDevLockfileSnapshot(){let e=this.getShellPort?.()??null;return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,...e&&e>0?{shellPort:e}:{},cwd:process.cwd(),startedAt:this.startedAt,heartbeatAt:Date.now(),source:"vite-dev",servedRuntimes:this.connectedRuntimeVersions()}}writeLockfileSnapshot(){ie(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){re(this.buildDevLockfileSnapshot())}writeConnectedRuntimeSnapshot(){if(this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}if(this.shouldWriteDevLockfile&&this.httpServer)try{this.writeDevLockfileSnapshot()}catch{}}refreshActiveRuntime(){this.activeRuntimeVersion=j(),this.activeRuntimeDirPath=pe()??Q()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=_({excludePorts:e,buildIconProxyUrl:t=>`/__bundle-proxy?url=${encodeURIComponent(t)}`}).then(t=>(this.scanCache=t,this.scanCacheAt=Date.now(),t)).catch(t=>{let i=t instanceof Error?t.message:String(t);return console.error("[rnx] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<o.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[Et]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):It}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer||C.existsSync(b.join(q(),"runtime-update-disabled"))||process.env.SOOTSIM_HOME&&z()&&!j())return;this.runRuntimeUpdate("startup");let e=this.resolveRuntimeUpdateIntervalMs();this.runtimeUpdateTimer=setInterval(()=>{this.runRuntimeUpdate("periodic")},e),this.runtimeUpdateTimer.unref()}runRuntimeUpdate(e){return this.runtimeUpdateInFlight?this.runtimeUpdateInFlight:(this.runtimeUpdateInFlight=(async()=>{try{e==="startup"&&process.stderr.write(`rnx: checking for runtime updates\u2026
21
- `);let t=await O.updateToLatest({protectVersions:this.connectedRuntimeVersions()});if(!t.updated||!t.latestVersion){e==="startup"&&process.stderr.write(`rnx: runtime ${this.activeRuntimeVersion??"(none)"} is current
22
- `);return}let i=this.activeRuntimeVersion,s=this.setActiveRuntime(t.latestVersion);process.stderr.write(`rnx runtime updated to ${s.version} (${e})
23
- `);try{Y({from:i,to:s.version,at:Date.now()})}catch{}}catch(t){process.stderr.write(`rnx runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
24
- `)}finally{if(this.runtimeUpdateInFlight=null,e==="startup"&&this.bootstrapping){if(this.bootstrapping=!1,this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}process.stderr.write(`rnx: ready
25
- `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(Z(e),this.refreshActiveRuntime(),this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}let t=JSON.stringify({type:"runtime:changed",version:e,runtimeDir:this.activeRuntimeDirPath});for(let i of this.sims.values()){try{let s=new URL(i.url||i.origin||"http://localhost");if(L(s.hostname))continue}catch{}if(i.ws.readyState===g.OPEN)try{i.ws.send(t)}catch{}}return{version:e,runtimeDir:this.activeRuntimeDirPath}}getActiveRuntime(){return{version:this.activeRuntimeVersion,runtimeDir:this.activeRuntimeDirPath}}removeLockfile(){if(this.shouldWriteLockfile)try{$()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy",wt),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),De(e.url)){He(e,t);return}if(Ne(e.url)&&Ue(e,t))return;let i=(e.method||"GET").toUpperCase(),s;try{s=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`)}catch{t.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),t.end("invalid request URL or host");return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Headers","Content-Type"),t.setHeader("Cache-Control","no-store"),i==="OPTIONS"){t.writeHead(204,{Allow:"GET, HEAD, POST, OPTIONS"}),t.end();return}if(i==="GET"||i==="HEAD"){let u="{}";try{u=JSON.stringify(W())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(u);return}if(i==="POST"){(async()=>{try{let u=[],p=0;for await(let h of e){let v=Buffer.isBuffer(h)?h:Buffer.from(h);if(p+=v.byteLength,p>8*1024*1024){t.writeHead(413,{"Content-Type":"text/plain; charset=utf-8"}),t.end("shared config patch is too large");return}u.push(v)}let m=JSON.parse(Buffer.concat(u).toString("utf8"));if(!m||typeof m!="object"||Array.isArray(m))throw new Error("shared config patch must be an object");let y=Object.fromEntries(Object.entries(m)),f=this.writeAndBroadcastSharedConfig(y);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(f))}catch(u){t.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),t.end(`invalid shared config patch: ${u instanceof Error?u.message:String(u)}`)}})();return}t.writeHead(405,{Allow:"GET, HEAD, POST, OPTIONS"}),t.end("method not allowed");return}if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}if(s.pathname==="/__bundle-proxy"){let u=s.searchParams.get("url");if(!u){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let p;try{p=new URL(u)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let m=p.hostname;if(!(m==="localhost"||m==="127.0.0.1"||m==="::1"||m.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let f=await fetch(p.toString(),{redirect:"follow"}),h={},v=f.headers.get("content-type");if(v&&(h["Content-Type"]=v),h["Cache-Control"]="no-store",t.writeHead(f.status,h),!f.body){t.end();return}let w=f.body.getReader();for(;;){let{done:A,value:S}=await w.read();if(A)break;t.write(Buffer.from(S))}t.end()}catch(f){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${f instanceof Error?f.message:String(f)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,bridgeSource:this.shouldWriteDevLockfile?"vite-dev":this.shouldWriteLockfile?"daemon":"embedded",startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}let n=me(s.hostname),c=L(s.hostname);n||this.refreshActiveRuntime();let r=n?he(s.hostname):this.activeRuntimeDirPath;if(!r){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end(n?`rnx: runtime ${c??"(invalid version origin)"} is not installed. run \`rnxsim open\` from that app again.`:"rnx: no active runtime installed. run `rnxsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let u of a.split("/"))if(u===".."){t.writeHead(403),t.end("forbidden");return}let d=b.resolve(r,"."+a),l=r.endsWith(b.sep)?r:r+b.sep;if(!d.startsWith(l)&&d!==r){t.writeHead(403),t.end("forbidden");return}C.realpath(d,(u,p)=>{let m=u?d:p,y=m.endsWith(b.sep)?m:m+b.sep;if(!u){let f=(()=>{try{let h=C.realpathSync(r);return h.endsWith(b.sep)?h:h+b.sep}catch{return l}})();if(!y.startsWith(f)&&m+b.sep!==f){t.writeHead(403),t.end("forbidden");return}}C.stat(m,(f,h)=>{if(f||!h?.isFile()){let S=b.extname(a).toLowerCase();if(S&&S!==".html"){t.writeHead(404),t.end("not found");return}if(a.startsWith("/__")||a.startsWith("/api/")||a==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let I=b.join(r,"index.html");C.readFile(I,(Je,Ve)=>{if(Je){t.writeHead(404),t.end("not found");return}if(t.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),i==="HEAD"){t.end();return}t.end(je(Ve,this.effectivePort,this.contrastOrigin))});return}let v=b.extname(m).toLowerCase(),w=Pt[v]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":w,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(v===".html"){C.readFile(m,(S,I)=>{if(S){try{t.end()}catch{}return}t.end(je(I,this.effectivePort,this.contrastOrigin))});return}let A=C.createReadStream(m);A.pipe(t),A.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,s]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(e-n<o.CLI_IDLE_TIMEOUT_MS)continue;let c=!1;for(let r of this.cliBySentId.values())if(r.ws===i){c=!0;break}if(!c){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[r,a]of this.cliBySentId)a.ws===i&&this.cliBySentId.delete(r);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}isAutomationSim(e){return e.meta?.sootsimHostDriver==="playwright"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let c=Math.max(n.lastActiveAt,n.connectedAt),r=e-c,a=this.isAutomationSim(n);if(a&&this.automationSimOwnerAlive(n))continue;let d=a?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=d){this.closeSimSocketFromHost(n.ws);continue}a&&i.push({sim:n,idleMs:r})}let s=this.maxConcurrentAutomationSims;if(i.length>s){i.sort((n,c)=>c.idleMs-n.idleMs);for(let{sim:n,idleMs:c}of i.slice(0,i.length-s))c<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(n.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==g.OPEN)continue;if(this.wsIsAlive.get(e)===!1){try{e.terminate()}catch{}continue}this.wsIsAlive.set(e,!1);try{e.ping()}catch{try{e.terminate()}catch{}}}}closeSimSocketFromHost(e){if(e.readyState!==g.OPEN)return;try{e.close(de,le)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==g.CLOSED)try{e.terminate()}catch{}},Tt);$e(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let c=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:d=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(d)},reject:d=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(d)}}),this.broadcastSimClientStates();let{simId:r,...a}=e;t.ws.send(JSON.stringify({...a,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,c=(a,d)=>new Promise(l=>{try{let u=yt(a,d,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,l(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),l(!0))})}catch{l(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let a=r.split(" ").filter(Boolean);if(a.length&&await c(a[0],[...a.slice(1),"-g",n]))return}await c("cursor",["-g",n])||await c("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await fe(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.devHeartbeatTimer&&(clearInterval(this.devHeartbeatTimer),this.devHeartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{$()}catch{}if(this.shouldWriteDevLockfile)try{se()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=g.CLOSED}let i=this.getActiveLease(e);return{id:e.id,origin:e.origin,url:e.url,title:e.title,userAgent:e.userAgent,connectedAt:e.connectedAt,lastSeenAt:e.lastSeenAt,lastActiveAt:e.lastActiveAt||void 0,isPrimary:e.id===this.primarySimId,readyState:t===g.OPEN?"open":t===g.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),c=Date.now(),r=this.getActiveLease(t),a=r&&r.cliIdentityKey===s,d=0;if(r&&!a&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-c)},bootedCount:0};if(r&&!a&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}d++}}let l={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:c+o.CLI_LEASE_TTL_MS};return t.cliLease=l,{granted:!0,lease:l,bootedCount:d}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,c=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===c||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=c,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let i=this.sims.get(e);return i?.ws.readyState===g.OPEN?i:null}let t=this.getDefaultSimCandidates();return t.find(i=>i.id===this.primarySimId)??t[0]??null}getDefaultSimCandidates(){let e=Array.from(this.sims.values()).filter(i=>i.ws.readyState===g.OPEN),t=e.filter(i=>i.url);return t.length>0?t:e}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let c=0;c<i;c++){if(e){let r=this.getOpenSim(e);if(r)return r}else{let r=this.getDefaultSimCandidates();if(r.length>1)throw new Error(`multiple sims are connected: ${r.map(d=>d.id).join(", ")}; run \`rnxsim use <sim>\` or pass \`--sim <sim>\``);let a=r[0];if(a)return a}await new Promise(r=>setTimeout(r,s))}if(!e)throw new Error("no sim connected");let n=this.getDefaultSimCandidates().map(c=>c.id);throw new Error(`no sim connected with id ${e}`+(n.length>0?`; connected sims: ${n.join(", ")}`:""))}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===g.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===g.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}writeAndBroadcastSharedConfig(e){let t=X(e),i=JSON.stringify({type:"bridge:shared-config-changed",config:t});for(let s of this.sims.values())if(s.ws.readyState===g.OPEN)try{s.ws.send(i)}catch{}return t}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==g.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let c=Date.now();n.lastActiveAt=c,n.recentActions=[{label:s,at:c},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==g.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,c]of this.cliSimBySocket){if(c!==t||n.readyState!==g.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===g.OPEN)return!1;let n=this.getRestorableSimState(i),c=e.id;this.sims.delete(c),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===c&&(this.primarySimId=e.id);for(let[r,a]of this.cliSimBySocket)a===c&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id),this.writeConnectedRuntimeSnapshot()}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function Rt(){return!!((process.env.XPC_SERVICE_NAME||"").includes("dev.sootsim.daemon")||process.env.INVOCATION_ID)}async function yi(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
26
- rnxsim serve \u2014 run the rnx bridge in the foreground
27
-
28
- hosts the WS bridge that CLI commands talk to. once running, any rnx
29
- renderer (browser, electron, headless playwright) that connects to port 7668
30
- becomes drivable from 'rnxsim describe', 'rnxsim do tap', etc.
31
-
32
- usage:
33
- rnxsim serve [options]
34
-
35
- options:
36
- --port <n> bridge port (defaults to ${7668})
37
- --quiet suppress per-connection logging
38
-
39
- examples:
40
- rnxsim serve
41
- rnxsim serve --port 7668 --quiet
42
- `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q"),n=ee();n&&te(n)&&(console.error(` an rnx bridge is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'rnxsim daemon stop' first"),process.exit(1)),x();let c=await ge(),r=new H({port:i,writeLockfile:!0,contrastOrigin:c}),a=await r.startAsync({silent:s}),d=Date.now(),l=y=>{s||process.stdout.write(`${y}
43
- `)},u=new Set,p=setInterval(()=>{let y=r.listSims(),f=new Set(y.map(h=>h.id));for(let h of y)if(!u.has(h.id)){let v=h.title||h.url||h.origin||"(unknown)";l(` + ${h.id} ${v}`)}for(let h of u)f.has(h)||l(` - ${h}`);u.clear();for(let h of f)u.add(h)},500);oe({event:"daemon_heartbeat",properties:{bridge_port:a,under_daemon:Rt(),platform:process.platform,subsource:"daemon"}}),ae(),l(`rnx bridge listening on ws://localhost:${a} (runtime http on same port)`),a!==i&&l(` (preferred port ${i} was taken \u2014 fell back to ${a})`),l(" ready for browser, electron, or headless playwright sims to connect"),l(" (ctrl-c to stop)");let m=async y=>{clearInterval(p),l(`
44
- ${y} received \u2014 shutting down after ${Math.round((Date.now()-d)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{yi as runServe};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{a}from"./chunk-4BXCZHAU.js";import"./chunk-5OX7ANRA.js";import"./chunk-MENV7VLD.js";export{a as settingsStore};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{c as a,d as b}from"./chunk-N6A3SXMR.js";import"./chunk-TCWQJILS.js";import"./chunk-66NF2KNG.js";import"./chunk-MENV7VLD.js";export{b as flushCliTelemetry,a as trackCliEvent};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{e as a,f as b,g as c}from"./chunk-NPVGMH2N.js";import"./chunk-BKNOLP3J.js";import"./chunk-T4FT6CM7.js";import"./chunk-YZRFF4YA.js";import"./chunk-FWYYCUAZ.js";import"./chunk-3D57IBPC.js";import"./chunk-7INBNA3U.js";import"./chunk-N6A3SXMR.js";import"./chunk-TCWQJILS.js";import"./chunk-33FKQH54.js";import"./chunk-7VWOSTD5.js";import"./chunk-66NF2KNG.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";export{a as resolveDefaultUploadOrigin,b as resolvePublicPreviewOrigin,c as runUpload};
@@ -1,6 +0,0 @@
1
- /*! rnx v0.1.312 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{b as a}from"./chunk-AY47WKS5.js";import"./chunk-3D57IBPC.js";import{d as s,f as t}from"./chunk-U4PN6JOT.js";import{a as m}from"./chunk-KR5BGMBZ.js";import{l as r}from"./chunk-66NF2KNG.js";import{a as l}from"./chunk-EUAVBTKU.js";import"./chunk-ZMZTHU7V.js";import"./chunk-MENV7VLD.js";import g from"node:fs";import d from"node:path";async function R($){let{IS_BETA:c,BETA_LABEL:u}=await import("./beta-GT3NN67B.js"),f=c?` \xB7 ${u}`:"";console.log(`rnxsim v${l()}${f}`);let o=m(),n=t.resolveChannel();o.isDevBridge?(console.log(o.primary),o.installedRuntime&&console.log(`${o.installedRuntime} \xB7 ${n}`)):o.primary==="runtime not installed"?console.log("runtime not installed \u2014 run `rnxsim runtime install`"):console.log(`${o.primary} \xB7 ${n}`);let{config:i}=await a();if(i?.runtimeVersion){let p=g.existsSync(d.join(r(i.runtimeVersion),"index.html"));console.log(`project runtime v${i.runtimeVersion} \xB7 configured \xB7 ${p?"installed":"installs on open"}`)}let e=await t.checkUpToDate({channel:n});e.outdated&&e.latest&&console.log(`
5
- \u2191 default runtime v${e.latest} available; run \`rnxsim upgrade\``),console.log(`
6
- what's new: ${s}`)}export{R as runVersion};