rnxsim 0.1.376 → 0.1.377

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 (295) hide show
  1. package/README.md +28 -25
  2. package/cli/app-config.ts +9 -12
  3. package/cli/app-fonts.ts +3 -3
  4. package/cli/app-project.ts +8 -8
  5. package/cli/auth.ts +7 -9
  6. package/cli/bin.ts +16 -31
  7. package/cli/bridge-flow-runner.ts +3 -3
  8. package/cli/browser-backend.ts +44 -0
  9. package/cli/command-contract.ts +221 -0
  10. package/cli/command-registry.ts +291 -0
  11. package/cli/commands/agent-wrapper.ts +2 -2
  12. package/cli/commands/app-fonts.ts +2 -2
  13. package/cli/commands/assert.ts +3 -3
  14. package/cli/commands/auth.ts +1 -1
  15. package/cli/commands/box/cloud-box.ts +1 -1
  16. package/cli/commands/box/plane-share.ts +2 -2
  17. package/cli/commands/box.ts +4 -6
  18. package/cli/commands/compat.ts +1 -1
  19. package/cli/commands/config.ts +2 -2
  20. package/cli/commands/control.ts +29 -29
  21. package/cli/commands/cpu-profile.ts +7 -7
  22. package/cli/commands/daemon-mac-app.ts +7 -7
  23. package/cli/commands/daemon.ts +10 -10
  24. package/cli/commands/debug.ts +11 -11
  25. package/cli/commands/detox.ts +13 -13
  26. package/cli/commands/diagnose.ts +6 -6
  27. package/cli/commands/do-chain.ts +1 -2
  28. package/cli/commands/electron.ts +1 -3
  29. package/cli/commands/film.ts +3 -3
  30. package/cli/commands/flow.ts +43 -43
  31. package/cli/commands/inspect/count.ts +1 -1
  32. package/cli/commands/inspect/describe.ts +1 -1
  33. package/cli/commands/inspect/env.ts +2 -2
  34. package/cli/commands/inspect/get-layout.ts +1 -1
  35. package/cli/commands/inspect/keyboard.ts +1 -1
  36. package/cli/commands/inspect/list.ts +1 -1
  37. package/cli/commands/inspect/memory.ts +1 -1
  38. package/cli/commands/inspect/resolve-target.ts +1 -1
  39. package/cli/commands/inspect/screens.ts +1 -1
  40. package/cli/commands/inspect/tree.ts +1 -1
  41. package/cli/commands/inspect/url.ts +1 -1
  42. package/cli/commands/inspect/wait-event.ts +5 -5
  43. package/cli/commands/inspect.ts +34 -34
  44. package/cli/commands/install-desktop.ts +3 -3
  45. package/cli/commands/login.ts +6 -6
  46. package/cli/commands/maestro-generate.ts +5 -5
  47. package/cli/commands/maestro.ts +5 -5
  48. package/cli/commands/profile.ts +1 -1
  49. package/cli/commands/record.ts +9 -9
  50. package/cli/commands/runtime.ts +18 -18
  51. package/cli/commands/screenshot-command.ts +1 -1
  52. package/cli/commands/screenshot-layers.ts +5 -5
  53. package/cli/commands/screenshot-mode.ts +1 -1
  54. package/cli/commands/screenshot.ts +8 -8
  55. package/cli/commands/screenshots-capture.ts +5 -5
  56. package/cli/commands/serve.ts +3 -3
  57. package/cli/commands/setup.ts +20 -12
  58. package/cli/commands/skills.ts +5 -5
  59. package/cli/commands/slides.ts +1 -1
  60. package/cli/commands/telemetry.ts +1 -1
  61. package/cli/commands/three-mode.ts +1 -1
  62. package/cli/commands/timeline.ts +8 -8
  63. package/cli/commands/upgrade.ts +116 -131
  64. package/cli/commands/upload.ts +12 -12
  65. package/cli/commands/version.ts +7 -7
  66. package/cli/commands/what-happened.ts +9 -9
  67. package/cli/current-sim.ts +3 -3
  68. package/cli/desktop-companion.ts +1 -1
  69. package/cli/drivers/playwright.ts +9 -9
  70. package/cli/drivers/registry.ts +1 -1
  71. package/cli/drivers/types.ts +1 -1
  72. package/cli/flow-file.ts +2 -2
  73. package/cli/flow-session.ts +1 -1
  74. package/cli/help-core.ts +136 -0
  75. package/cli/help.ts +17 -53
  76. package/cli/hints.ts +5 -5
  77. package/cli/inspect-notice-state.ts +1 -1
  78. package/cli/maestro-js.ts +1 -1
  79. package/cli/outbound-endpoints.ts +23 -5
  80. package/cli/parse-args.ts +19 -66
  81. package/cli/recording-access.ts +1 -1
  82. package/cli/registry.ts +1 -0
  83. package/cli/run-registry.ts +1 -1
  84. package/cli/run-rnx-core.ts +148 -0
  85. package/cli/run-rnx.ts +6 -9
  86. package/cli/runtime-notes.ts +3 -3
  87. package/cli/standalone.ts +4 -0
  88. package/cli/ws-bridge.ts +8 -8
  89. package/detox/config-loader.ts +2 -2
  90. package/detox/index.ts +8 -8
  91. package/detox/jest-preset.cjs +1 -1
  92. package/detox/navigation.ts +2 -2
  93. package/dist-lib/agent-daemon-client.cjs +5 -5
  94. package/dist-lib/agent-events.cjs +1 -1
  95. package/dist-lib/agent-identity.cjs +2 -2
  96. package/dist-lib/agent-sessions.cjs +10 -10
  97. package/dist-lib/attached-projects.cjs +6 -6
  98. package/dist-lib/auth/shared-session.cjs +6 -6
  99. package/dist-lib/backend-origin.cjs +1 -1
  100. package/dist-lib/beta.cjs +1 -1
  101. package/dist-lib/beta.mjs +1 -1
  102. package/dist-lib/bridge-constants.cjs +1 -1
  103. package/dist-lib/bridge-contract-input.cjs +1 -1
  104. package/dist-lib/bridge-contract-input.mjs +1 -1
  105. package/dist-lib/bridge-contract.cjs +1 -1
  106. package/dist-lib/bridge-contract.mjs +1 -1
  107. package/dist-lib/cli-constants.cjs +1 -1
  108. package/dist-lib/config.cjs +25 -25
  109. package/dist-lib/detox/index.cjs +9 -9
  110. package/dist-lib/detox/jest-preset.cjs +1 -1
  111. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  112. package/dist-lib/home-paths.cjs +29 -29
  113. package/dist-lib/host/bridge-host.cjs +128 -49
  114. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  115. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  116. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  117. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  118. package/dist-lib/host/websocket-proxy.cjs +1 -1
  119. package/dist-lib/index.cjs +14 -14
  120. package/dist-lib/jump-to-source-babel.cjs +1 -1
  121. package/dist-lib/menu.cjs +1 -1
  122. package/dist-lib/menu.mjs +1 -1
  123. package/dist-lib/metro-production-bundle.cjs +1 -1
  124. package/dist-lib/metro-production-bundle.mjs +1 -1
  125. package/dist-lib/metro.cjs +8 -8
  126. package/dist-lib/profiles.cjs +12 -12
  127. package/dist-lib/public-brand.cjs +1 -1
  128. package/dist-lib/react-native-host-modules.cjs +1 -1
  129. package/dist-lib/react-native-host-modules.mjs +1 -1
  130. package/dist-lib/render-mode.cjs +1 -1
  131. package/dist-lib/scripts/dev-server-scanner.cjs +8 -8
  132. package/dist-lib/sdk.cjs +1 -1
  133. package/dist-lib/sdk.mjs +1 -1
  134. package/dist-lib/skills.cjs +262 -135
  135. package/dist-lib/vite.cjs +9 -9
  136. package/package.json +4 -11
  137. package/scripts/dev-server-scanner.ts +2 -2
  138. package/scripts/optional-demo-registry.ts +1 -1
  139. package/skills/contrast/SKILL.md +3 -3
  140. package/skills/rnx-debug/SKILL.md +1 -1
  141. package/skills/rnx-test/SKILL.md +2 -2
  142. package/src/agent-identity.ts +1 -1
  143. package/src/agent-sessions.ts +7 -5
  144. package/src/cli-version.ts +12 -4
  145. package/src/config.ts +26 -28
  146. package/src/disk-cleanup.ts +11 -11
  147. package/src/home-paths.ts +28 -28
  148. package/src/host/bridge-host.ts +16 -16
  149. package/src/metro-plugin.ts +2 -2
  150. package/src/profiles.ts +2 -2
  151. package/src/runtime-assets.ts +7 -7
  152. package/src/runtime-delivery.ts +13 -13
  153. package/src/screenshots/orchestrate.ts +1 -1
  154. package/src/screenshots/schema.ts +2 -2
  155. package/src/skills/builtin/a11y-review.ts +2 -2
  156. package/src/skills/builtin/compat-check.ts +2 -2
  157. package/src/skills/builtin/maestro-test.ts +2 -2
  158. package/src/skills/builtin/perf-profile.ts +2 -2
  159. package/src/skills/builtin/screenshot-all.ts +2 -2
  160. package/src/skills/builtin/visual-diff.ts +2 -2
  161. package/src/skills/registry.ts +8 -8
  162. package/src/skills/types.ts +1 -1
  163. package/src/vite-plugin-one.ts +3 -3
  164. package/src/vite-plugin.ts +15 -2
  165. package/dist-cli/bin.js +0 -15
  166. package/dist-cli/chunks/agent-H42FCKFF.js +0 -48
  167. package/dist-cli/chunks/agent-wrapper-BBZKTZS6.js +0 -17
  168. package/dist-cli/chunks/app-fonts-43VXIKF4.js +0 -4
  169. package/dist-cli/chunks/assert-IXOLVO5Z.js +0 -49
  170. package/dist-cli/chunks/auth-KFMFB6FU.js +0 -12
  171. package/dist-cli/chunks/beta-5AO3SJB7.js +0 -4
  172. package/dist-cli/chunks/box-ZHM66L6K.js +0 -1730
  173. package/dist-cli/chunks/camera-FNJVFCDQ.js +0 -33
  174. package/dist-cli/chunks/chunk-37MCSPTE.js +0 -71
  175. package/dist-cli/chunks/chunk-3PEMSUAQ.js +0 -30
  176. package/dist-cli/chunks/chunk-4TQ5HOK3.js +0 -7
  177. package/dist-cli/chunks/chunk-5YZYDEMI.js +0 -4
  178. package/dist-cli/chunks/chunk-6CV3R3XD.js +0 -15
  179. package/dist-cli/chunks/chunk-7LGK5XU6.js +0 -4
  180. package/dist-cli/chunks/chunk-7R2TK2NY.js +0 -4
  181. package/dist-cli/chunks/chunk-7VZZQQEE.js +0 -497
  182. package/dist-cli/chunks/chunk-AFOVILIL.js +0 -130
  183. package/dist-cli/chunks/chunk-BEU7CD7E.js +0 -9
  184. package/dist-cli/chunks/chunk-CE4JQJ6Y.js +0 -6
  185. package/dist-cli/chunks/chunk-CIE6CZXL.js +0 -142
  186. package/dist-cli/chunks/chunk-CSJ7L7ZL.js +0 -312
  187. package/dist-cli/chunks/chunk-CWCQP53A.js +0 -27
  188. package/dist-cli/chunks/chunk-DCS5FK5N.js +0 -7
  189. package/dist-cli/chunks/chunk-DEV3E3MV.js +0 -4
  190. package/dist-cli/chunks/chunk-DGJMIVZM.js +0 -5
  191. package/dist-cli/chunks/chunk-DGX3MN65.js +0 -5
  192. package/dist-cli/chunks/chunk-DNPQMTW5.js +0 -4
  193. package/dist-cli/chunks/chunk-DOVBJBVD.js +0 -5
  194. package/dist-cli/chunks/chunk-DPBJ3S3J.js +0 -3
  195. package/dist-cli/chunks/chunk-FVZBGPCU.js +0 -4
  196. package/dist-cli/chunks/chunk-GDKMOIUT.js +0 -4
  197. package/dist-cli/chunks/chunk-GIF2NJCS.js +0 -32
  198. package/dist-cli/chunks/chunk-GZE57ORL.js +0 -4
  199. package/dist-cli/chunks/chunk-H3U56DKI.js +0 -24
  200. package/dist-cli/chunks/chunk-HZLOYAPH.js +0 -4
  201. package/dist-cli/chunks/chunk-J2IKAEU2.js +0 -4
  202. package/dist-cli/chunks/chunk-JXAXYK7W.js +0 -11
  203. package/dist-cli/chunks/chunk-KJE2O2GK.js +0 -4
  204. package/dist-cli/chunks/chunk-KMNVDZZI.js +0 -423
  205. package/dist-cli/chunks/chunk-LC3QRIRB.js +0 -10
  206. package/dist-cli/chunks/chunk-LGFTAQYC.js +0 -4
  207. package/dist-cli/chunks/chunk-LQMUA5IY.js +0 -4
  208. package/dist-cli/chunks/chunk-MFIQTWC5.js +0 -4
  209. package/dist-cli/chunks/chunk-MGALNF2F.js +0 -7
  210. package/dist-cli/chunks/chunk-MLBZZHOY.js +0 -4
  211. package/dist-cli/chunks/chunk-NNRF7GIB.js +0 -107
  212. package/dist-cli/chunks/chunk-NORLYTTO.js +0 -7
  213. package/dist-cli/chunks/chunk-P6KVGV3H.js +0 -14
  214. package/dist-cli/chunks/chunk-PAJTUK33.js +0 -4
  215. package/dist-cli/chunks/chunk-QELIC5XP.js +0 -4
  216. package/dist-cli/chunks/chunk-QRDF33WD.js +0 -11
  217. package/dist-cli/chunks/chunk-R76BA7C7.js +0 -535
  218. package/dist-cli/chunks/chunk-RVEB4CZ2.js +0 -4
  219. package/dist-cli/chunks/chunk-SK4M7NXT.js +0 -5
  220. package/dist-cli/chunks/chunk-SKMG5DD7.js +0 -5
  221. package/dist-cli/chunks/chunk-TEESPOYR.js +0 -4
  222. package/dist-cli/chunks/chunk-TH2UFGVP.js +0 -4
  223. package/dist-cli/chunks/chunk-TLP3T3VO.js +0 -4
  224. package/dist-cli/chunks/chunk-TZUABDIJ.js +0 -38
  225. package/dist-cli/chunks/chunk-UB2W6OQM.js +0 -99
  226. package/dist-cli/chunks/chunk-UYVXALPB.js +0 -506
  227. package/dist-cli/chunks/chunk-VQDYFFIG.js +0 -5
  228. package/dist-cli/chunks/chunk-VWCNJPCJ.js +0 -5
  229. package/dist-cli/chunks/chunk-VZIK4WIS.js +0 -74
  230. package/dist-cli/chunks/chunk-W3FNXAQP.js +0 -4
  231. package/dist-cli/chunks/chunk-XCDNVNP3.js +0 -4
  232. package/dist-cli/chunks/chunk-XSVILA4Z.js +0 -4
  233. package/dist-cli/chunks/chunk-XUTJ7ZWD.js +0 -4
  234. package/dist-cli/chunks/chunk-YTXY3MHW.js +0 -4
  235. package/dist-cli/chunks/chunk-ZF7PVX44.js +0 -28
  236. package/dist-cli/chunks/chunk-ZSSG7OR7.js +0 -4
  237. package/dist-cli/chunks/cleanup-MLOK2OZA.js +0 -25
  238. package/dist-cli/chunks/cli-version-OBNR366V.js +0 -4
  239. package/dist-cli/chunks/compat-SHMFSKU7.js +0 -23
  240. package/dist-cli/chunks/config-TPEAEUJ2.js +0 -13
  241. package/dist-cli/chunks/connect-3LEXWTE5.js +0 -4
  242. package/dist-cli/chunks/control-Z3FWA6BO.js +0 -4
  243. package/dist-cli/chunks/daemon-RSVYSC65.js +0 -4
  244. package/dist-cli/chunks/debug-GUVAK2KR.js +0 -200
  245. package/dist-cli/chunks/desktop-OOP2PTKP.js +0 -31
  246. package/dist-cli/chunks/detox-C2ILVBEC.js +0 -52
  247. package/dist-cli/chunks/device-NXIQQJWR.js +0 -18
  248. package/dist-cli/chunks/diagnose-2JBGYE5L.js +0 -43
  249. package/dist-cli/chunks/disk-cleanup-VURWJYQV.js +0 -4
  250. package/dist-cli/chunks/do-chain-DJ4UQC7A.js +0 -5
  251. package/dist-cli/chunks/drivers-JMA2OIKU.js +0 -4
  252. package/dist-cli/chunks/env-KTNPKEZR.js +0 -4
  253. package/dist-cli/chunks/film-DCPS7EID.js +0 -74
  254. package/dist-cli/chunks/flow-4DZ7B2OA.js +0 -4
  255. package/dist-cli/chunks/help-34CJMQY2.js +0 -4
  256. package/dist-cli/chunks/hidden-runtime-alias-HHT2C7WE.js +0 -4
  257. package/dist-cli/chunks/home-paths-KTPGCPMS.js +0 -4
  258. package/dist-cli/chunks/inspect-JF5WYJRD.js +0 -4
  259. package/dist-cli/chunks/install-desktop-ZIC4CDXI.js +0 -4
  260. package/dist-cli/chunks/login-TTJAOI2Q.js +0 -26
  261. package/dist-cli/chunks/logout-ERAQ6SKW.js +0 -4
  262. package/dist-cli/chunks/maestro-W46QCF77.js +0 -108
  263. package/dist-cli/chunks/maestro-generate-VBLM3MTU.js +0 -36
  264. package/dist-cli/chunks/mode-ZEDZK7R7.js +0 -26
  265. package/dist-cli/chunks/optional-demo-registry-ZUTPSVYQ.js +0 -4
  266. package/dist-cli/chunks/perf-YVT2WXT4.js +0 -48
  267. package/dist-cli/chunks/permissions-L7VVDHFP.js +0 -13
  268. package/dist-cli/chunks/platform-7TJOU2FB.js +0 -6
  269. package/dist-cli/chunks/privacy-57UOTB5J.js +0 -4
  270. package/dist-cli/chunks/record-VXG37P7U.js +0 -72
  271. package/dist-cli/chunks/report-issue-WNNOBZHC.js +0 -29
  272. package/dist-cli/chunks/reset-H5NBFE5U.js +0 -4
  273. package/dist-cli/chunks/resolve-target-57TK5WLE.js +0 -4
  274. package/dist-cli/chunks/runtime-QU2NIF2K.js +0 -4
  275. package/dist-cli/chunks/screenshot-command-AN56TTG7.js +0 -159
  276. package/dist-cli/chunks/screenshot-layers-3W5R7DB2.js +0 -20
  277. package/dist-cli/chunks/screenshots-capture-6AWJY7XZ.js +0 -42
  278. package/dist-cli/chunks/serve-GLYO5Q7J.js +0 -56
  279. package/dist-cli/chunks/setup-UA2HLD7S.js +0 -4
  280. package/dist-cli/chunks/sim-client-5C2RDQQO.js +0 -4
  281. package/dist-cli/chunks/skills-EYXWBRNQ.js +0 -50
  282. package/dist-cli/chunks/state-REJ7W6K3.js +0 -14
  283. package/dist-cli/chunks/storage-CFMDHI3V.js +0 -37
  284. package/dist-cli/chunks/store-XMCUA45G.js +0 -4
  285. package/dist-cli/chunks/telemetry-FBL3NAKB.js +0 -4
  286. package/dist-cli/chunks/timeline-HMCHN5FO.js +0 -24
  287. package/dist-cli/chunks/upgrade-2QSPAA3P.js +0 -7
  288. package/dist-cli/chunks/upload-DUQBKZYV.js +0 -4
  289. package/dist-cli/chunks/version-IOA6QFGB.js +0 -6
  290. package/dist-cli/chunks/web-NCGUYVCJ.js +0 -4
  291. package/dist-cli/chunks/welcome-QYGSQCWQ.js +0 -5
  292. package/dist-cli/chunks/what-happened-YTOUK4LO.js +0 -25
  293. package/dist-cli/chunks/ws-bridge-OF4OZARG.js +0 -4
  294. package/scripts/postinstall.cjs +0 -3
  295. package/scripts/preuninstall.cjs +0 -118
@@ -1,56 +0,0 @@
1
- /*! rnx v0.1.376 | (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 Te,c as q,d as Ce,e as X,f as Ee,h as Ie,i as _,j as xe,k as Re,l as Pe,m as Oe,q as _e,t as T,u as Le,v as Me,w as Be,x as De}from"./chunk-NORLYTTO.js";import"./chunk-XCDNVNP3.js";import{a as we,b as Ae,d as ke}from"./chunk-LGFTAQYC.js";import{e as be}from"./chunk-UB2W6OQM.js";import"./chunk-JXAXYK7W.js";import"./chunk-SKMG5DD7.js";import{a as ge,c as Se,d as D,e as ye}from"./chunk-KJE2O2GK.js";import{d as ve}from"./chunk-XUTJ7ZWD.js";import{b as z,d as E,m as B}from"./chunk-P6KVGV3H.js";import"./chunk-TLP3T3VO.js";import"./chunk-GZE57ORL.js";import{c as me,d as fe}from"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import{c as O}from"./chunk-TH2UFGVP.js";import{f as M}from"./chunk-CE4JQJ6Y.js";import{A as V,B as re,J as ne,L,M as K,N as se,O as oe,P as ae,R as ce,U as de,V as le,W as ue,X as G,Y as pe,g as ee,h as te,r as ie}from"./chunk-QRDF33WD.js";import{a as he}from"./chunk-XSVILA4Z.js";import"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";import{spawn as Ut}from"child_process";import w from"fs";import{createServer as jt}from"http";import v from"path";import{WebSocket as g,WebSocketServer as Ft}from"ws";import je from"node:fs";import H from"node:path";import{spawn as dt}from"node:child_process";var He=/^[A-Za-z0-9._:-]{1,160}$/;function Y(o){if(!o?.startsWith("TM_SESSION:"))return null;let e=o.slice(11).trim();return He.test(e)?e:null}function Ne(o){return He.test(o)}function lt(o){return typeof o.text=="string"?o.text.trim():""}function ut(o){let e=o?.trim();return e||"tm"}async function Ue(o){let e=o.sessionId.trim();if(!Ne(e))throw new Error(`invalid Team Machine session id: ${e||"<empty>"}`);let t=lt(o.prompt);if(!t)throw new Error("prompt text is empty");let i=ut(o.command),r=o.timeoutMs??15e3;await new Promise((n,c)=>{let s=dt(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),a="",l=setTimeout(()=>{try{s.kill("SIGTERM")}catch{}c(new Error(`tm send timed out after ${Math.round(r/1e3)}s`))},r);s.stderr?.setEncoding("utf8"),s.stderr?.on("data",d=>{a.length<4e3&&(a+=String(d))}),s.on("error",d=>{clearTimeout(l),c(d)}),s.on("exit",(d,u)=>{if(clearTimeout(l),d===0){n();return}let p=a.trim();c(new Error(p||`tm send exited with ${u?`signal ${u}`:`code ${d??"unknown"}`}`))})})}var N=1,pt=25;function ht(){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 U=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 r=t.id;try{let n=await this.dispatch(e,i,t);this.respond(e,r,n)}catch(n){n instanceof T?this.respondError(e,r,n.message,n.code):this.respondError(e,r,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await Oe()}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 X();case"agent:upsert-project":return q(i.input??{});case"agent:delete-project":return Ie(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return xe(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=_(n);if(!c)throw new T("NO_SESSION",`no session: ${n}`);let s=this.normalizePromptEnvelope(i);return await Me(n,s),this.notePromptAccepted(n,s,c.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await Be(String(i.sessionId));let r=_(String(i.sessionId));return r&&this.broadcastSessionStatus(r),{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 T("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new T("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 T("NO_CLAIM",`sim ${t} has no active CLI claim`);let r=Y(i.cliIdentityKey);if(!r)throw new T("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await Ue({sessionId:r,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"team-machine",sessionId:r}}async doStartSession(e){if(!Ce(e.projectId))throw new T("NO_PROJECT",`no project: ${e.projectId}`);let i=await Le(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 r=this.opts.getExcludePorts?.()??ht(),c=(await B({excludePorts:r})).find(d=>String(d.port)===i);if(!c||!c.cwd)return{project:null};let s=X().find(d=>d.cwd===c.cwd)??null,a=Array.from(new Set([...s?.knownBundleUrls??[],c.bundleUrl,t]));return{project:q({cwd:c.cwd,name:c.projectName??H.basename(c.cwd),preferredProvider:e.provider??s?.preferredProvider,sourceRoots:s?.sourceRoots??[c.cwd],knownBundleUrls:a,framework:s?.framework??mt(c.framework),bundleId:c.bundleId??s?.bundleId})}}getTranscript(e){let t=_e(e);return je.existsSync(t)?je.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=Te();return{userDataDir:e,storeFile:H.join(e,"attached-projects.json"),sessionsDir:H.join(e,"sessions"),transcriptsDir:H.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 r=this.subscriptions.get(t);if(r)return r.refCount++,{ok:!0,refCount:r.refCount};let n=De(t,c=>{let s=this.coalescePromptEcho(t,c);if(s&&(this.applySessionEvent(t,s),this.fanOutEvent(t,s)),c.type==="turn-completed"){let a=_(t);if(a)try{Ee(a.projectId,{usd:c.costUsd,ts:c.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
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 r=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:r}),this.pendingPromptEchoes.set(e,n);let c=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,c);let s=t.displayText??t.text;return this.patchSession(e,{lastPrompt:s,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:s,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:r}),{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)??_(e);if(!i)return;let r=Re(i,t);this.pendingSessionStates.set(e,r),this.pendingSessionPatches.set(e,{...this.pendingSessionPatches.get(e),...t}),this.broadcastSessionStatus(r),!this.sessionStatusPersistTimer&&(this.sessionStatusPersistTimer=setTimeout(()=>{this.sessionStatusPersistTimer=null,this.flushSessionStatuses()},pt))}flushSessionStatuses(){if(this.pendingSessionPatches.size===0)return;let e=this.pendingSessionStates,t=this.pendingSessionPatches;this.pendingSessionStates=new Map,this.pendingSessionPatches=new Map;try{Pe([...t].map(([i,r])=>({id:i,patch:r})))}catch(i){for(let[r,n]of e)this.pendingSessionStates.has(r)||this.pendingSessionStates.set(r,n);for(let[r,n]of t)this.pendingSessionPatches.set(r,{...n,...this.pendingSessionPatches.get(r)});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[r,n]of this.sessionsBySocket)if(n.has(e)&&r.readyState===N)try{r.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===N)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===N)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,r){if(e.readyState===N)try{e.send(JSON.stringify({id:t,error:i,...r?{code:r}:{}}))}catch{}}};function mt(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import We from"http";import $e from"https";import{finished as St,pipeline as yt}from"stream/promises";var Z="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",ft=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function gt(o){let e=o.toLowerCase();for(let t of ft)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function Fe(o){let e=gt(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":Z},...e?.headers}}var vt=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"]),bt={"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"},wt=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function Je(o){return o.protocol!=="https:"?{}:E(o.hostname)?{rejectUnauthorized:!1}:{}}function C(o){for(let[e,t]of Object.entries(bt))o.setHeader(e,t)}function At(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 kt(o,e){let t={};for(let[i,r]of Object.entries(o))r&&(vt.has(i.toLowerCase())||(t[i]=Array.isArray(r)?r.join(", "):r));return Object.assign(t,e?Fe(e):{"user-agent":Z}),t}function Tt(o,e){let t={};for(let[i,r]of Object.entries(o))r&&(wt.has(i.toLowerCase())||(t[i]=r));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function Ve(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function Ke(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Q(o,e){if(o.method==="OPTIONS"){C(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){C(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let r;try{r=new URL(i)}catch{C(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 l of o)a.push(Buffer.isBuffer(l)?l:Buffer.from(l));a.length>0&&(n=Buffer.concat(a))}let c=o.method||"GET",s=async(a,l,d,u)=>{let p=a.protocol==="https:"?$e:We,h=kt(o.headers,a);a.origin!==r.origin&&(delete h.authorization,delete h["proxy-authorization"]),l==="GET"||l==="HEAD"?(delete h["content-length"],delete h["content-type"]):d&&(h["content-length"]=String(d.byteLength));let m=await new Promise((A,k)=>{let y=p.request({hostname:z(a.hostname),port:a.port||(a.protocol==="https:"?443:80),path:a.pathname+a.search,method:l,headers:h,...Je(a)},A),R=()=>y.destroy(new Error("fetch proxy client disconnected"));o.once("aborted",R),y.once("close",()=>o.off("aborted",R)),y.once("error",k),d===void 0?y.end():y.end(d)}),S=m.statusCode??502,f=m.headers.location;if(f&&(S===301||S===302||S===303||S===307||S===308)){if(u>=10)throw m.destroy(),new Error("too many redirects");let A=(S===301||S===302)&&l==="POST"||S===303&&l!=="GET"&&l!=="HEAD",k=new URL(f,a);m.resume(),await St(m),await s(k,A?"GET":l,A?void 0:d,u+1);return}for(let[A,k]of Object.entries(m.headers)){let y=A.toLowerCase();k===void 0||y==="set-cookie"||y==="connection"||y==="keep-alive"||y==="proxy-authenticate"||y==="proxy-authorization"||y==="te"||y==="trailer"||y==="transfer-encoding"||y==="upgrade"||y.startsWith("access-control-")||e.setHeader(A,k)}C(e);let b=m.headers["set-cookie"]??[];b.length>0&&e.setHeader("x-sootsim-set-cookie",(Array.isArray(b)?b:[b]).join(", ")),e.statusCode=S,await yt(m,e)};try{await s(r,c,n,0)}catch(a){if(e.headersSent){e.destroy(a instanceof Error?a:new Error(String(a)));return}C(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${At(r.href,a)}`)}}async function Ge(o,e){let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){C(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("bundle-proxy: missing url query param");return}let r;try{r=new URL(i)}catch{C(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("bundle-proxy: invalid url");return}if(!E(r.hostname)){C(e),e.writeHead(403,{"Content-Type":"text/plain"}),e.end("bundle-proxy: only loopback targets allowed");return}await Q(o,e)}function ze(o,e){let t=o.url||"",i="",r="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",r=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!r)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,r)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let c=n.protocol==="https:"?$e:We,s=Tt(o.headers,n),a=c.request({hostname:z(n.hostname),port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:s,...Je(n)},l=>{let d=Object.keys(l.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return a.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),o.pipe(a),!0}import qe from"node:fs";import Ct from"node:path";var Xe=1,j=class extends Error{},F=class{registered=new Map;open=new Map;byRoot=new Map;nextPlaneId=1;async handleMessage(e,t){if(typeof t!="object"||t===null)return!1;let i={...t},r=i.type;if(typeof r!="string"||!r.startsWith("plane:"))return!1;let n=i.id;try{this.respond(e,n,await this.dispatch(e,r,i))}catch(c){let s=c instanceof j?"plane-not-registered":void 0;this.respondError(e,n,c instanceof Error?c.message:String(c),s)}return!0}unregisterSocket(e){for(let[t,i]of[...this.registered]){if(!i.delete(e)||i.size>0)continue;this.registered.delete(t);let r=this.byRoot.get(t);r&&(this.open.delete(r),this.byRoot.delete(t))}for(let[t,i]of[...this.open])i.sockets.delete(e),i.sockets.size===0&&!this.registered.has(i.root)&&(this.open.delete(t),this.byRoot.delete(i.root))}registeredRoots(){return[...this.registered.keys()]}async dispatch(e,t,i){switch(t){case"plane:register":{let r=this.realRoot(String(i.root??"")),n=this.registered.get(r)??new Set;return n.add(e),this.registered.set(r,n),{root:r,holders:n.size}}case"plane:status":{let r=this.realRoot(String(i.root??"")),n=this.registered.get(r);return{root:r,holders:n?.size??0,registered:!!n}}case"plane:open":{let r=this.realRoot(String(i.root??""));if(!this.registered.has(r))throw new j(`no box has registered ${r}; start one with \`rnx box\` there`);let n=this.byRoot.get(r),c=n?this.open.get(n):void 0;if(n&&c)return c.sockets.add(e),{planeId:n,version:c.version};let s=new ke(r);await s.refresh();let a=`plane-${this.nextPlaneId++}`,l={root:r,plane:s,version:we(s.index()),sockets:new Set([e])};return this.open.set(a,l),this.byRoot.set(r,a),{planeId:a,version:l.version}}case"plane:close":{let r=this.open.get(String(i.planeId??""));return r&&r.sockets.delete(e),{ok:!0}}default:{let r=this.entry(i),n=await Ae(r.plane,t,i);if(!n)throw new Error(`unknown plane command: ${t}`);return n.version&&(r.version=n.version),n.result}}}entry(e){let t=this.open.get(String(e.planeId??""));if(!t)throw new Error(`unknown planeId: ${String(e.planeId)}`);return t}realRoot(e){if(!e)throw new Error("root is required");let t=Ct.resolve(e),i;try{i=qe.realpathSync(t)}catch{throw new Error(`no such directory: ${t}`)}if(!qe.statSync(i).isDirectory())throw new Error(`not a directory: ${i}`);return i}respond(e,t,i){if(e.readyState===Xe)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,r){if(e.readyState===Xe)try{e.send(JSON.stringify({id:t,error:i,...r?{code:r}:{}}))}catch{}}};import Ye from"node:fs/promises";import I from"node:path";import{build as Et}from"esbuild";var Ze="/__sootsim-replacement-module";function It(o){switch(I.extname(o).toLowerCase()){case".js":return"js";case".jsx":return"jsx";case".ts":return"ts";case".tsx":return"tsx";default:return null}}function xt(o,e,t){let i=o.headers.origin,r;if(i)try{E(new URL(i).hostname)&&(r=i)}catch{}e.writeHead(200,{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-cache",...r?{"Access-Control-Allow-Origin":r,Vary:"Origin"}:{}}),e.end(o.method==="HEAD"?void 0:t)}function Qe(o){if(!o)return!1;try{return new URL(o,"http://rnx.local").pathname===Ze}catch{return!1}}async function et(o,e,t={}){let i=o.url||"",r;try{r=new URL(i,"http://rnx.local")}catch{return!1}if(t.requireLoopbackOrigin){let d=o.headers.origin,u=o.socket.remoteAddress?.replace(/^::ffff:/,""),p=!!(u&&E(u));if(p&&d)try{p=E(new URL(d).hostname)}catch{p=!1}if(!p)return e.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement modules are available only to loopback origins"),!0}if(r.pathname!==Ze)return!1;if(t.requestToken&&r.searchParams.get("token")!==t.requestToken)return e.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement module request token is invalid"),!0;let n=r.searchParams.get("path");if(!n)return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("missing path param"),!0;if(!It(n))return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement files must be .js, .jsx, .ts, or .tsx"),!0;if(!I.isAbsolute(n))return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file path must be absolute"),!0;let s=new Set(r.searchParams.getAll("runtimePackage")),a;if(t.projectRoot){let d=I.resolve(t.projectRoot);a=await Ye.realpath(t.projectRoot);let u=I.relative(d,n);if(u.startsWith("..")||I.isAbsolute(u))return e.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file must be inside the project root"),!0}let l;try{l=await Ye.realpath(n)}catch(d){let u=d instanceof Error?d.message:String(d);return e.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),e.end(`replacement file not found: ${u}`),!0}if(a){let d=I.relative(a,l);if(d.startsWith("..")||I.isAbsolute(d))return e.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file must be inside the project root"),!0}try{let d=await Et({entryPoints:[l],bundle:!0,write:!1,format:"esm",platform:"browser",target:"es2022",jsx:"transform",jsxFactory:"React.createElement",jsxFragment:"React.Fragment",tsconfigRaw:{compilerOptions:{jsx:"react"}},sourcemap:"inline",logLevel:"silent",plugins:[{name:"sootsim-replacement-runtime",setup(u){u.onResolve({filter:/^(react|react-native|react\/jsx-runtime|react\/jsx-dev-runtime)$/},p=>({path:p.path,namespace:"sootsim-replacement-runtime"})),u.onResolve({filter:/.*/},p=>s.has(p.path)?{path:p.path,namespace:"sootsim-replacement-runtime"}:void 0),u.onLoad({filter:/.*/,namespace:"sootsim-replacement-runtime"},p=>p.path==="react-native"?{contents:`const bridge = globalThis.__sootsim_components__
8
- if (!bridge) throw new Error('[rnx] replacement React Native bridge is not ready')
9
- module.exports = bridge`,loader:"js"}:p.path==="react"?{contents:`const bridge = globalThis.__sootsim_react_bridge
10
- if (!bridge) throw new Error('[rnx] replacement React bridge is not ready')
11
- module.exports = bridge`,loader:"js"}:p.path!=="react/jsx-runtime"&&p.path!=="react/jsx-dev-runtime"?{contents:`const packages = globalThis.__sootsim_config_package_modules
12
- const bridge = packages?.[${JSON.stringify(p.path)}]
13
- if (!bridge) throw new Error(${JSON.stringify(`[rnx] replacement package bridge ${p.path} is not ready`)})
14
- module.exports = bridge`,loader:"js"}:{contents:`const React = globalThis.__sootsim_react_bridge
15
- if (!React) throw new Error('[rnx] replacement React bridge is not ready')
16
- exports.Fragment = React.Fragment
17
- exports.jsx = (type, props, key) => React.createElement(type, key === undefined ? props : { ...props, key })
18
- exports.jsxs = exports.jsx
19
- exports.jsxDEV = exports.jsx`,loader:"js"})}}]});xt(o,e,d.outputFiles[0]?.text??"")}catch(d){let u=d instanceof Error?d.message:String(d);e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end(`replacement bundle failed: ${u}`)}return!0}import{WebSocket as x,WebSocketServer as Rt}from"ws";var Pt="/__websocket-proxy",Ot=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 P(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
20
- Connection: close\r
21
- Content-Type: text/plain\r
22
- Content-Length: ${t.length}\r
23
- \r
24
- ${t}`)}catch{}o.destroy()}function _t(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 Lt(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 r={};for(let[n,c]of Object.entries(i))c!=null&&(Ot.has(n.toLowerCase())||(r[n]=Array.isArray(c)?c.join(", "):String(c)));return r}function Mt(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function Bt(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function W(o,e,t){if(!(o.readyState===x.CLOSED||o.readyState===x.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function Dt(o,e){let t=!1,i=(r,n,c,s)=>{t||(t=!0,W(n,c,s.toString()),r.readyState===x.OPEN&&W(r,c,s.toString()))};o.on("message",(r,n)=>{e.readyState===x.OPEN&&e.send(r,{binary:n})}),e.on("message",(r,n)=>{o.readyState===x.OPEN&&o.send(r,{binary:n})}),o.on("close",(r,n)=>i(o,e,r,n)),e.on("close",(r,n)=>i(e,o,r,n)),o.on("error",()=>W(e,1011,"proxy client error")),e.on("error",()=>W(o,1011,"upstream websocket error"))}function Ht(o,e,t,i){let r={...t},n=Object.keys(r).filter(c=>c.toLowerCase()==="origin");if(i&&n.length===0)r.origin=Mt(o);else if(!i)for(let c of n)delete r[c];return Object.keys(r).length===0?new x(o.href,e):new x(o.href,e,{headers:r})}function Nt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===Pt}catch{return!1}}function tt(o,e,t,i=!0){if(!Nt(o.url))return!1;if(!_t(o))return P(e,403,"forbidden websocket proxy origin"),!0;let r,n;try{let l=new URL(o.url||"/","http://localhost"),d=l.searchParams.get("url");if(!d)return P(e,400,"missing websocket proxy url"),!0;if(r=new URL(d),r.protocol!=="ws:"&&r.protocol!=="wss:")return P(e,400,"invalid websocket proxy protocol"),!0;n=Lt(l.searchParams.get("headers"))}catch{return P(e,400,"invalid websocket proxy request"),!0}let c=Bt(o),s=Ht(r,c,n,i),a=!1;return e.once("close",()=>{a||s.terminate()}),s.once("open",()=>{if(a)return;a=!0;let l=s.protocol;new Rt({noServer:!0,clientTracking:!1,handleProtocols(u){return l||u.values().next().value||!1}}).handleUpgrade(o,e,t,u=>{Dt(u,s)})}),s.once("error",()=>{a||(a=!0,P(e,502,"upstream websocket error"))}),s.once("close",()=>{a||(a=!0,P(e,502,"upstream websocket closed"))}),!0}var Wt="require-corp",$t=new Set(["tap","keyboard","longPress","perform","reset","camera"]),Jt=2e3,Vt=1e3;function Kt(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:$t.has(o.type)}var it=5e3,Gt=3600*1e3,zt="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",rt={".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",".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".mov":"video/quicktime"},nt="/__camera-fixtures/",qt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function st(o,e,t){let i;try{let a=V();i=JSON.stringify(a)}catch{i="{}"}let r=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",c=`<script>window.__sootsimSharedConfig=${i};`+r+n+`window.__sootsimCliVersion=${JSON.stringify(he())};</script>`,s=o.toString("utf8");return s.includes("<head>")?s.replace("<head>",`<head>${c}`):s.includes("</head>")?s.replace("</head>",c+"</head>"):s.includes("</body>")?s.replace("</body>",c+"</body>"):c+s}function ot(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var $=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;planeHost=new F;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 U({getExcludePorts:e.agentScanExcludes,resolveCliLease:t=>{let i=this.sims.get(t),r=i?this.getActiveLease(i):null;return r?{kind:r.kind,cliIdentityKey:r.cliIdentityKey,expiresAt:r.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)
25
- `),this.afterBind(),i}catch(r){if(r?.code!=="EADDRINUSE")throw r;e?.silent||process.stderr.write(`ws bridge port ${i} already in use, trying ${i+1}
26
- `)}}throw new Error(`could not bind ws bridge after ${this.portFallbackCount} attempts starting at ${this.preferredPort}`)}bindOnce(e,t){return new Promise((i,r)=>{let n=jt((a,l)=>this.handleHttpRequest(a,l)),c=!1,s=a=>{if(!c){c=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,r(a)}};n.once("error",s),n.listen(e,"127.0.0.1",()=>{c||(c=!0,n.removeListener("error",s),n.on("error",a=>{process.stderr.write(`ws bridge http error: ${String(a)}
27
- `)}),this.httpServer=n,this.wss=new Ft({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(a,l,d)=>{tt(a,l,d)||this.wss?.handleUpgrade(a,l,d,u=>{this.wss?.emit("connection",u,a)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,r=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),r==="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 s;try{s=JSON.parse(c.toString())}catch{return}if(!(!s||typeof s!="object")){if(typeof s.type=="string"&&s.type.startsWith("agent:")){this.agentHost.handleMessage(e,s);return}if(typeof s.type=="string"&&s.type.startsWith("plane:")){this.planeHost.handleMessage(e,s);return}if(s.type==="runtime:list"){let a=M.listInstalled(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:s.id,installed:a,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(s.type==="runtime:use"){let a=typeof s.version=="string"?s.version:"";if(!M.listInstalled().includes(a)){try{e.send(JSON.stringify({type:"runtime:use:error",id:s.id,error:`runtime ${a||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(a);try{e.send(JSON.stringify({type:"runtime:use:ok",id:s.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(s.type==="runtime:get"){let a=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:s.id,active:a.version,activeRuntimeDir:a.runtimeDir}))}catch{}return}if(r==="sim"&&s.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,r="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.writeConnectedRuntimeSnapshot(),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(r==="sim"){if(n&&(n.lastSeenAt=Date.now()),s.type==="bridge:register"&&n){let d=s,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,this.writeConnectedRuntimeSnapshot(),typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(s.type==="bridge:user-focus-state"&&n){let d=s;this.updateUserFocusLease(n,d);return}if(s.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(s.type==="bridge:write-shared-config"){if(!s.patch||typeof s.patch!="object"||Array.isArray(s.patch))return;let d=Object.fromEntries(Object.entries(s.patch));try{this.writeAndBroadcastSharedConfig(d)}catch(u){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${u instanceof Error?u.message:String(u)}
28
- `);return}return}if(s.type==="bridge:open-path"){let d=typeof s.path=="string"?s.path:"",u=typeof s.line=="number"&&Number.isFinite(s.line)?s.line:void 0,p=typeof s.column=="number"&&Number.isFinite(s.column)?s.column:void 0;d&&this.openPathInEditor(d,u,p);return}if(s.type==="bridge:boot-clients"&&n){let d=[];for(let[p,h]of this.cliSimBySocket)h===n.id&&d.push(p);for(let p of d){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 ${d.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
29
- `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let a=this.pendingCommands.get(s.id);if(a){this.pendingCommands.delete(s.id),s.error?a.reject(new Error(s.error)):a.resolve(s.result);return}let l=this.cliBySentId.get(s.id);if(l&&(this.cliBySentId.delete(s.id),l.ws.readyState===g.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...s,id:l.originalId,_otherCliCount:d}:{...s,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(s.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[h,m]of this.cliBySentId)m.ws===e&&this.cliBySentId.delete(h);p&&this.broadcastSimClientStates();return}if(s.type==="bridge:hello"){let p=typeof s.cliIdentityKey=="string"&&s.cliIdentityKey.trim()?s.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof s.cliLabel=="string"&&s.cliLabel.trim()&&this.cliLabelBySocket.set(e,s.cliLabel.trim()),e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,result:{cliIdentityKey:p,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(s.type==="bridge:list-sims"){e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,result:this.listSims()}));return}if(s.type==="bridge:claim"){let p=await this.waitForSim(s.simId),h=this.tryAcquireLease(e,p,{force:s.force===!0});if(!h.granted){e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,error:`sim ${p.id} is locked by another cli`,_locked:h.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,h.bootedCount>0?`cli force-claimed sim (booted ${h.bootedCount})`:"cli claimed sim"),e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,result:{simId:p.id,lockedBy:h.lease.cliIdentityKey,lockExpiresAt:h.lease.expiresAt,bootedCount:h.bootedCount}}));return}let a=await this.waitForSim(s.simId);if(Kt(s)){let p=this.tryAcquireLease(e,a);if(!p.granted){e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,error:`sim ${a.id} is locked by another cli \u2014 use \`rnx claim ${a.id} --force\` or \`rnx open --new\``,_locked:p.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,a.id),this.recordSimAction(a.id,this.describeForwardedCommand(s));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:a.id,ws:e,originalId:s.id});let{simId:d,...u}=s;if(a.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,result:{requested:!0,simId:a.id}}));let p=a.ws,h=setTimeout(()=>{this.closeSimSocketFromHost(p)},Jt);ot(h)}}catch(a){e.readyState===g.OPEN&&e.send(JSON.stringify({id:s.id,error:a instanceof Error?a.message:String(a)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),this.planeHost.unregisterSocket(e),r==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[c,s]of this.pendingCommands)s.simId===n.id&&(s.reject(new Error("sim disconnected")),this.pendingCommands.delete(c));for(let[c,s]of this.cliBySentId)s.simId===n.id&&(s.ws.readyState===g.OPEN&&s.ws.send(JSON.stringify({id:s.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(c));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(r==="cli"){let c=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[s,a]of this.cliBySentId)a.ws===e&&this.cliBySentId.delete(s);c&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
30
- `),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(L(),!ue(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)}
31
- `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},it),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)}
32
- `)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},it),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"),r=D(i.hostname);r&&e.add(r)}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(){de(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){le(this.buildDevLockfileSnapshot())}writeConnectedRuntimeSnapshot(){if(this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}if(this.shouldWriteDevLockfile&&this.httpServer)try{this.writeDevLockfileSnapshot()}catch{}}refreshActiveRuntime(){this.activeRuntimeVersion=K(),this.activeRuntimeDirPath=ge()??oe()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=B({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}handleCameraFixture(e,t,i){let r=(t.method||"GET").toUpperCase(),n={"Access-Control-Allow-Origin":"*","Cache-Control":"no-store"};if(r==="OPTIONS"){i.writeHead(204,{...n,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range"}),i.end();return}if(r!=="GET"&&r!=="HEAD"){i.writeHead(405,n),i.end();return}if(!qt.test(e)){i.writeHead(400,{...n,"Content-Type":"text/plain; charset=utf-8"}),i.end("bad fixture name");return}let c=ie(),s=v.join(c,e),a;try{a=w.lstatSync(s)}catch{i.writeHead(404,{...n,"Content-Type":"text/plain; charset=utf-8"}),i.end("not found");return}if(!a.isFile()){i.writeHead(403,{...n,"Content-Type":"text/plain; charset=utf-8"}),i.end("forbidden");return}let l=rt[v.extname(s).toLowerCase()]||"application/octet-stream",d=a.size,u=/^bytes=(\d*)-(\d*)$/.exec(t.headers.range||"");if(u){let[,p,h]=u,m=p?Number(p):0,S=h?Math.min(Number(h),d-1):d-1;if(!Number.isFinite(m)||m>S||m>=d){i.writeHead(416,{...n,"Content-Range":`bytes */${d}`}),i.end();return}if(i.writeHead(206,{...n,"Content-Type":l,"Content-Range":`bytes ${m}-${S}/${d}`,"Accept-Ranges":"bytes","Content-Length":String(S-m+1)}),r==="HEAD"){i.end();return}w.createReadStream(s,{start:m,end:S}).pipe(i);return}if(i.writeHead(200,{...n,"Content-Type":l,"Accept-Ranges":"bytes","Content-Length":String(d)}),r==="HEAD"){i.end();return}w.createReadStream(s).pipe(i)}handleServerScan(e){let t=r=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(r))},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(r=>t(r))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[zt]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):Gt}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer||w.existsSync(v.join(ee(),"runtime-update-disabled"))||process.env.SOOTSIM_HOME&&te()&&!K())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
33
- `);let t=await M.updateToLatest({protectVersions:this.connectedRuntimeVersions()});if(!t.updated||!t.latestVersion){e==="startup"&&process.stderr.write(`rnx: runtime ${this.activeRuntimeVersion??"(none)"} is current
34
- `);return}let i=this.activeRuntimeVersion,r=this.setActiveRuntime(t.latestVersion);process.stderr.write(`rnx runtime updated to ${r.version} (${e})
35
- `);try{ne({from:i,to:r.version,at:Date.now()})}catch{}}catch(t){process.stderr.write(`rnx runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
36
- `)}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
37
- `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(se(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 r=new URL(i.url||i.origin||"http://localhost");if(D(r.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{G({pid:process.pid,startedAt:this.startedAt})}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"),Ve(e.url)){Q(e,t);return}if(Ke(e.url)&&ze(e,t))return;if(Qe(e.url)){et(e,t);return}let i=(e.method||"GET").toUpperCase(),r;try{r=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(r.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(V())}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 f of e){let b=Buffer.isBuffer(f)?f:Buffer.from(f);if(p+=b.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(b)}let h=JSON.parse(Buffer.concat(u).toString("utf8"));if(!h||typeof h!="object"||Array.isArray(h))throw new Error("shared config patch must be an object");let m=Object.fromEntries(Object.entries(h)),S=this.writeAndBroadcastSharedConfig(m);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(S))}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(r.pathname.startsWith(nt)){this.handleCameraFixture(r.pathname.slice(nt.length),e,t);return}if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}if(r.pathname==="/__bundle-proxy"){Ge(e,t);return}if(r.pathname==="/__server-scan"){this.handleServerScan(t);return}if(r.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=Se(r.hostname),c=D(r.hostname);n||this.refreshActiveRuntime();let s=n?ye(r.hostname):this.activeRuntimeDirPath;if(!s){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end(n?`rnx: runtime ${c??"(invalid version origin)"} is not installed. run \`rnx open\` from that app again.`:"rnx: no active runtime installed. run `rnx runtime install` to fetch one.");return}let a=r.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 l=v.resolve(s,"."+a),d=s.endsWith(v.sep)?s:s+v.sep;if(!l.startsWith(d)&&l!==s){t.writeHead(403),t.end("forbidden");return}w.realpath(l,(u,p)=>{let h=u?l:p,m=h.endsWith(v.sep)?h:h+v.sep;if(!u){let S=(()=>{try{let f=w.realpathSync(s);return f.endsWith(v.sep)?f:f+v.sep}catch{return d}})();if(!m.startsWith(S)&&h+v.sep!==S){t.writeHead(403),t.end("forbidden");return}}w.stat(h,(S,f)=>{if(S||!f?.isFile()){let y=v.extname(a).toLowerCase();if(y&&y!==".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 R=v.join(s,"index.html");w.readFile(R,(at,ct)=>{if(at){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(st(ct,this.effectivePort,this.contrastOrigin))});return}let b=v.extname(h).toLowerCase(),A=rt[b]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":A,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(b===".html"){w.readFile(h,(y,R)=>{if(y){try{t.end()}catch{}return}t.end(st(R,this.effectivePort,this.contrastOrigin))});return}let k=w.createReadStream(h);k.pipe(t),k.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,r]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(e-n<o.CLI_IDLE_TIMEOUT_MS)continue;let c=!1;for(let s of this.cliBySentId.values())if(s.ws===i){c=!0;break}if(!c){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[s,a]of this.cliBySentId)a.ws===i&&this.cliBySentId.delete(s);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),s=e-c,a=this.isAutomationSim(n);if(a&&this.automationSimOwnerAlive(n))continue;let l=a?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(s>=l){this.closeSimSocketFromHost(n.ws);continue}a&&i.push({sim:n,idleMs:s})}let r=this.maxConcurrentAutomationSims;if(i.length>r){i.sort((n,c)=>c.idleMs-n.idleMs);for(let{sim:n,idleMs:c}of i.slice(0,i.length-r))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(me,fe)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==g.CLOSED)try{e.terminate()}catch{}},Vt);ot(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((r,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:l=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),r(l)},reject:l=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:s,...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 r=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${r}`,c=(a,l)=>new Promise(d=>{try{let u=Ut(a,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),s=process.env.REACT_EDITOR||process.env.EDITOR;if(s){let a=s.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 ve(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{G({pid:process.pid,startedAt:this.startedAt})}catch{}if(this.shouldWriteDevLockfile)try{pe({bridgePort:this.effectivePort,pid:process.pid,startedAt:this.startedAt})}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,r]of this.pendingCommands)r.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 r=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),c=Date.now(),s=this.getActiveLease(t),a=s&&s.cliIdentityKey===r,l=0;if(s&&!a&&!i.force)return{granted:!1,lease:s,lock:{by:s.cliLabel||s.cliIdentityKey,expiresInMs:Math.max(0,s.expiresAt-c)},bootedCount:0};if(s&&!a&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let h=this.cliIdentityKeyBySocket.get(u);if(h&&h!==r){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:r,cliLabel:n,expiresAt:c+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,r=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===r&&e.visibilityState===n&&e.documentFocused===c||(e.userFocused=i,e.userVisible=r,e.visibilityState=n,e.documentFocused=c,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let r=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,r):r;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,r=t.intervalMs??200;for(let c=0;c<i;c++){if(e){let s=this.getOpenSim(e);if(s)return s}else{let s=this.getDefaultSimCandidates();if(s.length>1)throw new Error(`multiple sims are connected: ${s.map(l=>l.id).join(", ")}; run \`rnx use <sim>\` or pass \`--sim <sim>\``);let a=s[0];if(a)return a}await new Promise(s=>setTimeout(s,r))}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 r=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!r||!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=re(e),i=JSON.stringify({type:"bridge:shared-config-changed",config:t});for(let r of this.sims.values())if(r.ws.readyState===g.OPEN)try{r.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 r=t?.trim();if(!r)return;let n=this.sims.get(e);if(!n)return;let c=Date.now();n.lastActiveAt=c,n.recentActions=[{label:r,at:c},...n.recentActions.filter(s=>s.label!==r)].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"query":return"queried semantic tree";case"resolve":return"resolved semantic selector";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,r]of this.cliSimBySocket){if(r!==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),r=new Set;for(let[n,c]of this.cliSimBySocket){if(c!==t||n.readyState!==g.OPEN)continue;let s=this.cliIdentityKeyBySocket.get(n);s&&s===i||r.add(s??`ws-unknown-${r.size}`)}return r.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 r=this.sims.get(i);if(r&&r!==e&&r.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(s=>({...s})),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[s,a]of this.cliSimBySocket)a===c&&this.cliSimBySocket.set(s,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[r,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(r)}}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{}}};async function Yi(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
38
- rnx serve \u2014 run the rnx bridge in the foreground
39
-
40
- hosts the WS bridge that CLI commands talk to. once running, any rnx
41
- renderer (browser, electron, headless playwright) that connects to port 7668
42
- becomes drivable from 'rnx describe', 'rnx do tap', etc.
43
-
44
- usage:
45
- rnx serve [options]
46
-
47
- options:
48
- --port <n> bridge port (defaults to ${7668})
49
- --quiet suppress per-connection logging
50
-
51
- examples:
52
- rnx serve
53
- rnx serve --port 7668 --quiet
54
- `),O(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]}`),O(1));let r=o.includes("--quiet")||o.includes("-q"),n=ae();n&&ce(n)&&(console.error(` an rnx bridge is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'rnx daemon stop' first"),O(1)),L();let c=await be(),s=new $({port:i,writeLockfile:!0,contrastOrigin:c}),a=await s.startAsync({silent:r}),l=Date.now(),d=m=>{r||process.stdout.write(`${m}
55
- `)},u=new Set,p=setInterval(()=>{let m=s.listSims(),S=new Set(m.map(f=>f.id));for(let f of m)if(!u.has(f.id)){let b=f.title||f.url||f.origin||"(unknown)";d(` + ${f.id} ${b}`)}for(let f of u)S.has(f)||d(` - ${f}`);u.clear();for(let f of S)u.add(f)},500);d(`rnx bridge listening on ws://localhost:${a} (runtime http on same port)`),a!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${a})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let h=async m=>{clearInterval(p),d(`
56
- ${m} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await s.close()}catch{}O(0)};process.on("SIGINT",()=>h("SIGINT")),process.on("SIGTERM",()=>h("SIGTERM")),process.on("SIGHUP",()=>h("SIGHUP")),process.on("exit",()=>{try{s.removeLockfile()}catch{}}),await new Promise(()=>{})}export{Yi as runServe};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (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-GIF2NJCS.js";import"./chunk-RVEB4CZ2.js";import"./chunk-H3U56DKI.js";import"./chunk-4TQ5HOK3.js";import"./chunk-KJE2O2GK.js";import"./chunk-GDKMOIUT.js";import"./chunk-UYVXALPB.js";import"./chunk-VWCNJPCJ.js";import"./chunk-XUTJ7ZWD.js";import"./chunk-P6KVGV3H.js";import"./chunk-DCS5FK5N.js";import"./chunk-TZUABDIJ.js";import"./chunk-QELIC5XP.js";import"./chunk-CSJ7L7ZL.js";import"./chunk-DNPQMTW5.js";import"./chunk-TLP3T3VO.js";import"./chunk-FVZBGPCU.js";import"./chunk-GZE57ORL.js";import"./chunk-VZIK4WIS.js";import"./chunk-LC3QRIRB.js";import"./chunk-MLBZZHOY.js";import"./chunk-VQDYFFIG.js";import"./chunk-TEESPOYR.js";import"./chunk-DOVBJBVD.js";import"./chunk-DGJMIVZM.js";import"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-TH2UFGVP.js";import"./chunk-AFOVILIL.js";import"./chunk-7R2TK2NY.js";import"./chunk-CE4JQJ6Y.js";import"./chunk-J2IKAEU2.js";import"./chunk-7LGK5XU6.js";import"./chunk-BEU7CD7E.js";import"./chunk-W3FNXAQP.js";import"./chunk-QRDF33WD.js";import"./chunk-XSVILA4Z.js";import"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";export{a as runSetup};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (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}from"./chunk-MFIQTWC5.js";import"./chunk-KMNVDZZI.js";import"./chunk-YTXY3MHW.js";import"./chunk-QELIC5XP.js";import"./chunk-CSJ7L7ZL.js";import"./chunk-ZSSG7OR7.js";export{i as SimClient,a as SimClientError,b as SimConnectError,e as SimKeyboardError,f as SimPerformError,c as SimReadyTimeoutError,g as SimResetError,d as SimTapError,h as buildSimOpenUrl};
@@ -1,50 +0,0 @@
1
- /*! rnx v0.1.376 | (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}from"./chunk-TH2UFGVP.js";import{a as S}from"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";import*as s from"fs";import*as b from"os";import*as a from"path";import{fileURLToPath as y}from"url";function j(){try{let t=y(import.meta.resolve(`${S.packageName}/package.json`));return a.join(a.dirname(t),"skills")}catch{let t=a.dirname(y(import.meta.url));return a.resolve(t,"../../skills")}}var g=j(),v=new Set(["all","codex","claude"]);function x(){console.log(`rnx skill
5
-
6
- install and inspect bundled rnx agent skills.
7
-
8
- usage:
9
- rnx skill install [all|codex|claude] [skill-name...]
10
- rnx skill install --target <dir> [skill-name...]
11
- rnx skill show [skill-name]
12
-
13
- commands:
14
- install install skills; no target means all supported local agents
15
- show list bundled skills, or print one skill markdown
16
-
17
- targets:
18
- all Codex and Claude Code (default)
19
- codex $CODEX_HOME/skills, or ~/.codex/skills
20
- claude $CLAUDE_CONFIG_DIR/skills, or ~/.claude/skills
21
- `)}function I(){console.log(`rnx skill install
22
-
23
- install bundled rnx skills in the agent skill layout: <skill>/SKILL.md.
24
- each skill directory is symlinked back to its source, so edits stay live
25
- without a re-install. an existing install from an older CLI is upgraded in
26
- place; an unrelated skill directory is left alone unless --force is passed.
27
-
28
- usage:
29
- rnx skill install [all|codex|claude] [skill-name...]
30
- rnx skill install --target <dir> [skill-name...]
31
-
32
- options:
33
- --force, -f replace a conflicting existing skill with the symlink
34
-
35
- examples:
36
- rnx skill install
37
- rnx skill install codex
38
- rnx skill install codex rnx-debug
39
- rnx skill install --force rnx-debug
40
- `)}function m(t,n){let e=process.env[t]||a.join(b.homedir(),n);return a.join(e,"skills")}function p(){return[{label:"codex",dir:m("CODEX_HOME",".codex")},{label:"claude",dir:m("CLAUDE_CONFIG_DIR",".claude")}]}function C(t){if(t==="all")return p();if(t==="codex")return[{label:"codex",dir:m("CODEX_HOME",".codex")}];if(t==="claude")return[{label:"claude",dir:m("CLAUDE_CONFIG_DIR",".claude")}];console.error(` unknown skill install target: ${t}`),console.error(" expected all, codex, or claude"),c(1)}function E(t){let n=t.match(/^---\n([\s\S]*?)\n---/);if(!n)return null;let e=n[1],l=L(e,"name");return l?{name:l,description:L(e,"description")||""}:null}function L(t,n){let e=t.split(`
41
- `),l=`${n}:`;for(let i=0;i<e.length;i++){let r=e[i];if(!r.startsWith(l))continue;let o=r.slice(l.length).trim();if(o===">-"||o===">"||o==="|-"||o==="|"){let f=[];for(let d=i+1;d<e.length;d++){let u=e[d];if(/^[A-Za-z0-9_-]+:\s*/.test(u))break;if(u.trim()===""){f.push("");continue}if(!/^\s+/.test(u))break;f.push(u.trim())}return f.join(o.startsWith("|")?`
42
- `:" ").trim()}return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.slice(1,-1):o}return null}function h(){if(!s.existsSync(g))return[];let t=[];for(let n of s.readdirSync(g)){let e=a.join(g,n,"SKILL.md");if(!s.existsSync(e))continue;let l=E(s.readFileSync(e,"utf8"));l&&t.push({name:n,description:l.description})}return t.sort((n,e)=>n.name.localeCompare(e.name))}function $(t,n){if(n.length===0)return t;let e=t.filter(l=>n.some(i=>{let r=i.replace(/^sootsim-/,"").replace(/^rnx-/,"");return l.name.includes(i)||l.name.replace(/^rnx-/,"").includes(r)}));return e.length===0&&(console.error(` no skills matched: ${n.join(", ")}`),console.error(" available: "+t.map(l=>l.name).join(", ")),c(1)),e}function k(t){try{return s.lstatSync(t)}catch{return null}}function T(t,n){let e=k(t);if(!e||!e.isSymbolicLink())return!1;try{return s.realpathSync(t)===s.realpathSync(n)}catch{return!1}}function _(t,n,e){if(t.isSymbolicLink()||!t.isDirectory())return!1;let l;try{l=s.readdirSync(n)}catch{return!1}if(l.length!==1||l[0]!=="SKILL.md")return!1;let i=a.join(n,"SKILL.md"),r=k(i);if(!r)return!1;if(r.isSymbolicLink())try{return s.readlinkSync(i).includes(`${a.sep}skills${a.sep}`)}catch{return!1}if(!r.isFile())return!1;try{return s.readFileSync(i).equals(s.readFileSync(a.join(e,"SKILL.md")))}catch{return!1}}function w(t,n,e){let l=a.join(g,t.name),i=a.join(n,t.name);s.mkdirSync(n,{recursive:!0});let r=k(i);return r?T(i,l)?"up-to-date":e||_(r,i,l)?(s.rmSync(i,{recursive:!0,force:!0}),s.symlinkSync(l,i),"replaced"):"conflict":(s.symlinkSync(l,i),"linked")}function H(){let t=h();if(t.length!==0)for(let n of p()){let e=a.resolve(n.dir);if(s.existsSync(a.dirname(e))){try{s.mkdirSync(e,{recursive:!0})}catch{continue}try{D(e)}catch{}for(let l of t)try{w(l,e,!1)}catch{}}}}var F=["sootsim-setup","sootsim-debug","sootsim-perf","sootsim-test","sootsim-visual"];function D(t){for(let n of F){let e=a.join(t,n),l=k(e);l&&(l.isSymbolicLink()||_(l,e,a.join(g,n)))&&s.rmSync(e,{recursive:!0,force:!0})}}function O(t){if(t.length===0){console.log(" no skills found");return}console.log(`
43
- available skills:
44
- `);for(let n of t)console.log(` ${n.name}`),console.log(` ${n.description}
45
- `);console.log(" usage: rnx skill install [all|codex|claude] [skill-name...]"),console.log(` usage: rnx skill show [skill-name]
46
- `)}function A(t){let n=null,e=!1,l=[];for(let i=0;i<t.length;i++){let r=t[i];if((r==="--help"||r==="-h")&&(I(),c(0)),r==="--force"||r==="-f"){e=!0;continue}if(r==="--target"){let o=t[i+1];(!o||o.startsWith("-"))&&(console.error(" --target requires a directory"),c(1)),n&&(console.error(" pass only one install target"),c(1)),n=[{label:"target",dir:o}],i++;continue}if(r.startsWith("-")&&(console.error(` unknown option: ${r}`),I(),c(1)),!n&&v.has(r)){n=C(r);continue}l.push(r)}return{targets:n??p(),filters:l,force:e}}async function R(t){let n=h();n.length===0&&(console.error(" no skills found in rnx package"),c(1));let e=A(t),l=$(n,e.filters),i=e.targets.map(o=>({...o,dir:a.resolve(o.dir)}));for(let o of i)s.mkdirSync(o.dir,{recursive:!0}),s.statSync(o.dir).isDirectory()||(console.error(` target is not a directory: ${o.dir}`),c(1)),D(o.dir);console.log(`
47
- installing ${l.length} skill(s) to ${i.length} target(s)
48
- `);let r=0;for(let o of i){console.log(` target ${o.label}: ${o.dir}`);for(let f of l){let d=a.join(o.dir,f.name),u=w(f,o.dir,e.force);u==="linked"?console.log(` linked ${f.name} -> ${d}`):u==="replaced"?console.log(` relinked ${f.name} -> ${d}`):u==="up-to-date"?console.log(` up to date ${f.name}`):(r++,console.log(` conflict ${f.name}: ${d} exists and is not this skill \u2014 pass --force to replace`))}console.log("")}r>0&&(console.error(` ${r} conflict(s); rerun with --force only if replacing them is intended.
49
- `),c(1)),console.log(` done. restart the agent session to load newly installed skills.
50
- `)}function W(t){let n=h(),e=t.find(r=>!r.startsWith("-"));if(!e){O(n);return}let[l]=$(n,[e]),i=s.readFileSync(a.join(g,l.name,"SKILL.md"),"utf8");console.log(i)}async function M(t){let[n,...e]=t;if(!n||n==="--help"||n==="-h"){x();return}if(n==="install"){await R(e);return}if(n==="show"||n==="list"){W(e);return}console.error(` unknown skill command: ${n}`),x(),c(1)}export{H as refreshInstalledSkills,M as runSkill};
@@ -1,14 +0,0 @@
1
- /*! rnx v0.1.376 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{m as g}from"./chunk-TZUABDIJ.js";import{f as a,g as u}from"./chunk-CSJ7L7ZL.js";import{t as c,v as l}from"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-QRDF33WD.js";import"./chunk-ZSSG7OR7.js";function d(t){return!!t&&typeof t=="object"&&typeof Reflect.get(t,"capturedAt")=="number"&&(Reflect.get(t,"tree")===void 0||a(Reflect.get(t,"tree")))}function f(){console.log(`
5
- rnx state - capture the current app state in one call
6
-
7
- usage:
8
- rnx state [--json] [--sim <id>]
9
-
10
- options:
11
- --json print the complete structured result, including the screenshot
12
- --sim <id> target a specific sim
13
- --port <p> WS bridge port
14
- `)}async function S(t,p={}){if(t.includes("--help")||t.includes("-h"))return f(),0;let o=c(t,{port:p.port,stripBooleanFlags:["--json"]});if(o.positional.length>0)return console.error(` unexpected state argument: ${o.positional[0]}`),1;let n=l(o);try{let e=await n.send({type:"state"});if(!d(e))throw new Error("state bridge returned an invalid result");if(t.includes("--json"))return console.log(JSON.stringify(e)),0;let r=e.route;if(console.log(` route: ${r?.screen??r?.url??"(unknown)"}`),r?.stack?.length&&console.log(` stack: ${r.stack.join(" > ")}`),console.log(` keyboard: ${e.keyboard?.visible?"visible":"hidden"}`),console.log(""),console.log(e.tree?u(e.tree):""),console.log(""),e.recentErrors?.length){console.log(` recent errors (${e.recentErrors.length}):`);for(let i of e.recentErrors)console.log(` [${i.level}] ${i.text}`)}else console.log(" recent errors: none");let s=typeof e.screenshot=="string"?e.screenshot.length:0;return console.log(s>0?` screenshot: captured (${s} characters; use --json to read it)`:" screenshot: unavailable"),0}catch(e){return console.error(` state failed: ${e instanceof Error?e.message:e}`),await g(n),1}finally{n.close()}}export{S as runState};
@@ -1,37 +0,0 @@
1
- /*! rnx v0.1.376 | (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 f}from"./chunk-6CV3R3XD.js";import{b as t,c as l,d as s,e as c,f as a}from"./chunk-VWCNJPCJ.js";import"./chunk-TZUABDIJ.js";import"./chunk-CSJ7L7ZL.js";import"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-QRDF33WD.js";import"./chunk-ZSSG7OR7.js";function p(){console.log(`
5
- rnx storage profile \u2014 manage isolated storage profiles
6
-
7
- usage:
8
- rnx storage profile list
9
- rnx storage profile create <id>
10
- rnx storage profile clear <id>
11
- rnx storage profile delete <id>
12
-
13
- profiles isolate cookies, localStorage, IndexedDB, cache, permissions, and
14
- service workers in Electron and Playwright launches. Plain browser-tab launches
15
- cannot honor profiles and will fail clearly if a profile is requested.
16
-
17
- examples:
18
- rnx storage profile list
19
- rnx storage profile create qa
20
- rnx open 8081 --profile qa
21
- rnx open 8081 --profile qa --driver playwright
22
- rnx storage profile clear qa
23
- rnx storage profile delete qa
24
- `)}async function d(r,n){if(r.includes("--help")||r.includes("-h"))return p(),0;let o=r[0]??"list";try{switch(o){case"list":{let e=t();for(let i of e)console.log(` ${i.id}`);return 0}case"create":{let e=r[1];if(!e)return console.error(" profile create expects <id>"),1;let i=s(e);return console.log(` created profile: ${i.id}`),0}case"ensure":{let e=r[1];if(!e)return console.error(" profile ensure expects <id>"),1;let i=l(e);return console.log(` profile: ${i.id}`),0}case"clear":{let e=r[1];return e?(l(e),a(e),console.log(` cleared profile: ${e}`),0):(console.error(" profile clear expects <id>"),1)}case"delete":{let e=r[1];if(!e)return console.error(" profile delete expects <id>"),1;let i=c(e);return console.log(` deleted profile: ${i.id}`),0}default:return console.error(` unknown profile command: ${o}`),p(),1}}catch(e){return console.error(` profile failed: ${e instanceof Error?e.message:String(e)}`),1}}var m=new Set(["--sim","--port","-p"]),g=new Set(["profile","clear"]);function x(r){for(let n=0;n<r.length;n++){let o=r[n];if(o.startsWith("-")){m.has(o)&&n++;continue}return g.has(o)?{name:o,index:n}:null}return null}function u(){console.log(`
25
- rnx storage \u2014 manage sim and app storage
26
-
27
- usage:
28
- rnx storage profile <subcommand>
29
- rnx storage clear [--full] [--sim <id>] [--json]
30
-
31
- subcommands:
32
- profile list
33
- profile create <id>
34
- profile clear <id>
35
- profile delete <id>
36
- clear clear the current guest app data and relaunch it
37
- `)}async function w(r,n){if(r.includes("--help")||r.includes("-h"))return u(),0;let o=x(r);return o?.name==="profile"?d([...r.slice(0,o.index),...r.slice(o.index+1)],n):o?.name==="clear"?f([...r.slice(0,o.index),...r.slice(o.index+1)],n):(console.error(` unknown storage command: ${o?.name??"(missing)"}`),u(),1)}export{w as runStorage};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (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-DNPQMTW5.js";import"./chunk-DGJMIVZM.js";import"./chunk-ZSSG7OR7.js";export{a as settingsStore};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (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}from"./chunk-J2IKAEU2.js";import"./chunk-7LGK5XU6.js";import"./chunk-BEU7CD7E.js";import"./chunk-W3FNXAQP.js";import"./chunk-QRDF33WD.js";import"./chunk-ZSSG7OR7.js";export{a as buildCliDiagnosticEvent,d as flushCliTelemetry,b as trackCliDiagnostic,c as trackCliError};
@@ -1,24 +0,0 @@
1
- /*! rnx v0.1.376 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{t as d,v as u,y as i}from"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import{c as o}from"./chunk-TH2UFGVP.js";import"./chunk-QRDF33WD.js";import"./chunk-ZSSG7OR7.js";import{writeFileSync as b}from"fs";function p(){console.log(`
5
- rnx timeline \u2014 control the semantic event timeline
6
-
7
- usage:
8
- rnx timeline <subcommand> [args]
9
-
10
- subcommands:
11
- status show enabled kinds and ring sizes
12
- start [kinds] enable kinds (csv); 'all' for every opt-in
13
- stop [kinds] disable kinds (csv); 'all' for every kind
14
- clear drop all events + cursors
15
- dump <file> write current merged ring to JSON
16
-
17
- note: cheap kinds (console, fetch, app-launch, keyboard, screen, alert,
18
- toast, notification, route, shell, actionsheet, picker) record at all times.
19
- start/stop enables opt-in kinds (react-commit, scroll, gesture, text-input,
20
- layout, reanimated, animation).
21
-
22
- read the timeline with: rnx what-happened
23
- `)}async function k(s,g){let l=d(s,{port:g.port,stripBooleanFlags:["--json","--help","-h"]}),r=l.positional[0];(!r||s.includes("--help")||s.includes("-h"))&&(p(),o(0));let a=s.includes("--json"),t=u(l),c=l.positional.slice(1),n=c[0]?c[0].split(",").map(e=>e.trim()).filter(Boolean):[];try{switch(r){case"status":{let e=await i(t,"SootSim.bridges.timeline.status");console.log(JSON.stringify(e,null,a?0:2));break}case"start":{n.length===0&&n.push("all"),await i(t,"SootSim.bridges.timeline.enable",...n);let e=await i(t,"SootSim.bridges.timeline.status");console.log(JSON.stringify(e,null,a?0:2));break}case"stop":{n.length===0&&n.push("all"),await i(t,"SootSim.bridges.timeline.disable",...n);let e=await i(t,"SootSim.bridges.timeline.status");console.log(JSON.stringify(e,null,a?0:2));break}case"clear":{await i(t,"SootSim.bridges.timeline.clear"),console.log(" cleared");break}case"dump":{let e=c[0];e||(console.error(" usage: rnx timeline dump <file>"),o(1));let m=await i(t,"SootSim.bridges.timeline.recent",{limit:1e6});b(e,JSON.stringify(m.events,null,2)+`
24
- `),console.log(` wrote ${m.events.length} event(s) to ${e}`);break}default:console.error(` unknown subcommand: ${r}`),p(),o(1)}}finally{t.close()}}export{k as runTimeline};
@@ -1,7 +0,0 @@
1
- /*! rnx v0.1.376 | (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 h,b as v,c as $}from"./chunk-3PEMSUAQ.js";import{b as p}from"./chunk-FVZBGPCU.js";import"./chunk-GZE57ORL.js";import"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-TH2UFGVP.js";import{b as g}from"./chunk-CE4JQJ6Y.js";import{M as a,g as m,h as u,l as d}from"./chunk-QRDF33WD.js";import{a as f}from"./chunk-XSVILA4Z.js";import"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";import{spawn as y}from"node:child_process";import x from"node:fs";import R from"node:os";import s from"node:path";var b="https://registry.npmjs.org/rnxsim/latest";async function W(t){let n=t.indexOf("--channel"),e=n>=0&&t[n+1]?t[n+1]:void 0;console.log(`rnx upgrade
5
- `),console.log("runtime:");let o=a(),{config:l}=await p(),r=l?.runtimeVersion,c=r?x.existsSync(s.join(d(r),"index.html")):!1;r&&console.log(` project config: v${r}`);let i=(r&&c?null:await $(["install",...r?[r,"--set-active=false"]:[],...e?["--channel",e]:[]],{}))?.version??r??a();i&&console.log(r?c?` result: v${i} already installed for this project`:` result: not installed \u2192 v${i} for this project`:o&&o!==i?` result: v${o} \u2192 v${i}`:o?` result: v${i} already current`:` result: not installed \u2192 v${i}`);let k=i?await h(i):null;console.log(`
6
- cli:`),await j(),i&&console.log(`
7
- ${v(i,k)}`)}function w(){if(u())return{kind:"dev"};let t=process.argv[1]??"";try{t=x.realpathSync(t)}catch{}let n=s.sep;if(t.includes(`${n}_npx${n}`)||t.includes(`${n}.bunx${n}`))return{kind:"npx"};if(t.includes(`${n}.bun${n}`))return{kind:"global",command:"bun",args:["add","-g","rnxsim@latest"]};if(t.includes(`${n}pnpm${n}`))return{kind:"global",command:"pnpm",args:["add","-g","rnxsim@latest"]};let e=s.join(m(),"cli");if(t.startsWith(`${e}${n}`))return{kind:"global",command:"npm",args:["i","-g","--prefix",e,"rnxsim@latest"]};let o=s.resolve(process.env.SOOTSIM_CLI_PREFIX||s.join(R.homedir(),".local"));return t.startsWith(`${o}${n}`)?{kind:"global",command:"npm",args:["i","-g","--prefix",o,"rnxsim@latest"]}:{kind:"global",command:"npm",args:["i","-g","rnxsim@latest"]}}async function j(){let t=f(),n=await C();if(!n){console.log(` v${t} \u2014 couldn't reach the npm registry, skipped`);return}if(g(n,t)<=0){console.log(` v${t} (latest)`);return}let e=w();if(console.log(` v${t} \u2192 v${n}`),e.kind==="dev"){console.log(" running from the Contrast dev checkout \u2014 pull instead of upgrading");return}if(e.kind==="npx"){console.log(" running from the npx cache \u2014 get the latest with:"),console.log(" npx rnxsim@latest");return}let o=`${e.command} ${e.args.join(" ")}`;console.log(` updating global install (${o})\u2026`),await S(e.command,e.args)?console.log(` updated to v${n}`):(console.log(" update failed \u2014 run it yourself:"),console.log(` ${o}`))}function S(t,n){return new Promise(e=>{let o=y(t,n,{stdio:"inherit"});o.on("error",()=>e(!1)),o.on("exit",l=>e(l===0))})}async function C(){try{let t=await fetch(b,{headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"&&n.version?n.version:null}catch{return null}}export{W as runUpgrade};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (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-UB2W6OQM.js";import"./chunk-JXAXYK7W.js";import"./chunk-SKMG5DD7.js";import"./chunk-XUTJ7ZWD.js";import"./chunk-P6KVGV3H.js";import"./chunk-TLP3T3VO.js";import"./chunk-GZE57ORL.js";import"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-TH2UFGVP.js";import"./chunk-QRDF33WD.js";import"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";export{a as resolveDefaultUploadOrigin,b as resolvePublicPreviewOrigin,c as runUpload};
@@ -1,6 +0,0 @@
1
- /*! rnx v0.1.376 | (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-FVZBGPCU.js";import"./chunk-GZE57ORL.js";import{a as m}from"./chunk-MLBZZHOY.js";import"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import{d as s,f as t}from"./chunk-CE4JQJ6Y.js";import{l as r}from"./chunk-QRDF33WD.js";import{a as l}from"./chunk-XSVILA4Z.js";import"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";import g from"node:fs";import d from"node:path";async function R($){let{IS_BETA:c,BETA_LABEL:u}=await import("./beta-5AO3SJB7.js"),f=c?` \xB7 ${u}`:"";console.log(`rnx 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 `rnx runtime install`"):console.log(`${o.primary} \xB7 ${n}`);let{config:e}=await a();if(e?.runtimeVersion){let p=g.existsSync(d.join(r(e.runtimeVersion),"index.html"));console.log(`project runtime v${e.runtimeVersion} \xB7 configured \xB7 ${p?"installed":"installs on open"}`)}let i=await t.checkUpToDate({channel:n});i.outdated&&i.latest&&console.log(`
5
- \u2191 default runtime v${i.latest} available; run \`rnx upgrade\``),console.log(`
6
- what's new: ${s}`)}export{R as runVersion};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (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}from"./chunk-PAJTUK33.js";import"./chunk-ZSSG7OR7.js";export{b as COMPAT_CATEGORIES,j as COMPAT_RESULT_CAVEAT,c as POLYFILL_REGISTRY,a as UNSUPPORTABLE,f as countScanResults,i as formatDetailedScanLines,h as formatPackageStatus,g as formatScanCounts,d as scanDeps,e as scanDepsWithData};
@@ -1,5 +0,0 @@
1
- /*! rnx v0.1.376 | (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 t}from"./chunk-GIF2NJCS.js";import"./chunk-RVEB4CZ2.js";import"./chunk-H3U56DKI.js";import{r as e}from"./chunk-4TQ5HOK3.js";import"./chunk-KJE2O2GK.js";import"./chunk-GDKMOIUT.js";import"./chunk-UYVXALPB.js";import"./chunk-VWCNJPCJ.js";import"./chunk-XUTJ7ZWD.js";import"./chunk-P6KVGV3H.js";import"./chunk-DCS5FK5N.js";import"./chunk-TZUABDIJ.js";import"./chunk-QELIC5XP.js";import"./chunk-CSJ7L7ZL.js";import"./chunk-DNPQMTW5.js";import"./chunk-TLP3T3VO.js";import"./chunk-FVZBGPCU.js";import"./chunk-GZE57ORL.js";import"./chunk-VZIK4WIS.js";import"./chunk-LC3QRIRB.js";import"./chunk-MLBZZHOY.js";import"./chunk-VQDYFFIG.js";import"./chunk-TEESPOYR.js";import"./chunk-DOVBJBVD.js";import"./chunk-DGJMIVZM.js";import"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-TH2UFGVP.js";import"./chunk-AFOVILIL.js";import"./chunk-7R2TK2NY.js";import"./chunk-CE4JQJ6Y.js";import"./chunk-J2IKAEU2.js";import{a as r}from"./chunk-7LGK5XU6.js";import{f as o}from"./chunk-BEU7CD7E.js";import"./chunk-W3FNXAQP.js";import{C as n}from"./chunk-QRDF33WD.js";import"./chunk-XSVILA4Z.js";import"./chunk-5YZYDEMI.js";import"./chunk-ZSSG7OR7.js";async function u(){return!n()&&r()?(await t([],{launchConnectRN:!0}),0):(o("Run any React Native app in a local simulator."),console.log(`
5
- Opening ConnectRN`),await e(["ConnectRN","--no-describe","--quiet"]),0)}export{u as runWelcome};
@@ -1,25 +0,0 @@
1
- /*! rnx v0.1.376 | (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 T,B as A,D as y,O as _,P as b,Q as S}from"./chunk-CSJ7L7ZL.js";import{e as x,t as N,v as F}from"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import{c as k}from"./chunk-TH2UFGVP.js";import"./chunk-QRDF33WD.js";import"./chunk-ZSSG7OR7.js";function B(n){let t=[];for(let e=0;e<n.length;e++)if(n[e]==="--since"&&e+1<n.length){t.push(e,e+1);let s=n[e+1].trim(),l=/^(\d+(?:\.\d+)?)(ms|s|m)?$/.exec(s);if(l){let c=Number(l[1]),u=l[2]??"ms",v=u==="s"?c*1e3:u==="m"?c*6e4:c;return{since:Date.now()-v,consumed:t}}let i=Number(s);if(Number.isFinite(i)&&i>1e12)return{since:i,consumed:t}}return{consumed:t}}function D(n){let t=[];for(let e=0;e<n.length;e++)if(n[e]==="--kinds"&&e+1<n.length)return t.push(e,e+1),{kinds:n[e+1].split(",").map(s=>s.trim()).filter(Boolean),consumed:t};return{consumed:t}}function K(n){let t=[];for(let e=0;e<n.length;e++)if(n[e]==="--limit"&&e+1<n.length){t.push(e,e+1);let s=Number(n[e+1]);if(Number.isFinite(s)&&s>0)return{limit:s,consumed:t}}return{consumed:t}}function E(n){let t=[],e={label:"initial state",events:[],startedAt:n[0]?.t??null};t.push(e);for(let s of n)if(e.events.push(s),s.kind==="screen"||s.kind==="route"){let l=s.data,i=l?.phase;if(!i||i==="enter"||i==="appear"||i==="active"){let c=l?.name||l?.activeName||l?.path||l?.pathname||s.kind;t.length===1&&e.events.length===1?e.label=`${s.kind}: ${c}`:(e={label:`${s.kind}: ${c}`,events:[],startedAt:s.t},t.push(e))}}return t}async function Q(n,t){let e=N(n,{port:t.port,stripBooleanFlags:["--summary","--all","--json","--no-advance","--help","-h","--flow","--noisy"],stripValueFlags:["--since","--kinds","--limit"]});(n.includes("--help")||n.includes("-h"))&&(console.log(`
5
- rnx what-happened \u2014 show recent events from the semantic timeline
6
-
7
- usage:
8
- rnx what-happened # since last CLI call
9
- rnx what-happened --summary # one-line counts
10
- rnx what-happened --all # full ring (ignore cursor)
11
- rnx what-happened --since 5s # absolute window
12
- rnx what-happened --kinds toast,fetch
13
- rnx what-happened --noisy # include react-commit/layout/scroll
14
- rnx what-happened --limit 50
15
- rnx what-happened --json
16
- rnx what-happened --no-advance # don't advance cursor after read
17
-
18
- note: react-commit, layout, and scroll are opt-in/noisy events. enable them
19
- with "rnx timeline start <kind>", then pass --noisy or include them in
20
- --kinds to see them.
21
- `),k(0));let s=n.includes("--summary"),l=n.includes("--flow"),i=n.includes("--all"),c=n.includes("--json"),u=n.includes("--no-advance"),v=n.includes("--noisy"),{since:a}=B(n),{kinds:d}=D(n),{limit:C}=K(n),g=x(),$={limit:C??200,...d&&d.length?{kinds:d}:{},...a!==void 0?{since:a}:i?{}:{sinceCursor:g}},h=F(e);try{if(s){let r=await T(h,$);if(c)console.log(JSON.stringify(r));else{let m=i?"all time":a!==void 0?`last ${((Date.now()-a)/1e3).toFixed(1)}s`:"since last call";console.log(` ${m}: ${_(r)}`)}!u&&!i&&r.lastAt&&await y(h,g,r.lastAt);return}let o=await A(h,$),I=Array.isArray(d)&&d.some(r=>b.has(r)),M=!v&&!I,f=0;if(M){let r=o.events.filter(m=>b.has(m.kind)?(f+=1,!1):!0);o.events=r}if(c)console.log(JSON.stringify(l?E(o.events):o,null,2));else{if(o.events.length===0)f>0?console.log(` no non-noise events (${f} react-commit/layout/scroll hidden)`):console.log(i?" no events recorded":a!==void 0?" no events in window":" no new events since last call");else if(l){let r=o.events[0]?.t??null,m=E(o.events),w=i?`\u2500\u2500\u2500 ${o.events.length} event(s) total \u2014 flow view \u2500\u2500\u2500`:a!==void 0?`\u2500\u2500\u2500 ${o.events.length} event(s) in last ${((Date.now()-a)/1e3).toFixed(1)}s \u2014 flow view \u2500\u2500\u2500`:`\u2500\u2500\u2500 ${o.events.length} event(s) since last call \u2014 flow view \u2500\u2500\u2500`;console.log(` ${w}`);for(let p of m){console.log(`
22
- \u2500\u2500 ${p.label} (${p.events.length} event${p.events.length===1?"":"s"}) \u2500\u2500`);for(let O of p.events)console.log(S(O,r))}}else{let r=o.events[0]?.t??null,m=i?`\u2500\u2500\u2500 ${o.events.length} event(s) total \u2500\u2500\u2500`:a!==void 0?`\u2500\u2500\u2500 ${o.events.length} event(s) in last ${((Date.now()-a)/1e3).toFixed(1)}s \u2500\u2500\u2500`:`\u2500\u2500\u2500 ${o.events.length} event(s) since last call \u2500\u2500\u2500`;console.log(` ${m}`);for(let w of o.events)console.log(S(w,r))}f>0&&o.events.length>0&&process.stderr.write(`
23
- ${f} high-frequency event(s) hidden (react-commit/layout/scroll)
24
- rerun with --noisy or --kinds react-commit,layout,scroll to include them
25
- `)}!u&&!i&&o.watermark>0&&await y(h,g,o.watermark)}finally{h.close()}}export{Q as runWhatHappened};
@@ -1,4 +0,0 @@
1
- /*! rnx v0.1.376 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import { createRequire as __sootsimCreateRequire } from 'node:module'
3
- var require = __sootsimCreateRequire(import.meta.url)
4
- import{k as a,l as b,m as c,n as d,o as e,p as f,q as g,r as h,s as i,t as j,u as k,v as l,w as m,x as n,y as o,z as p}from"./chunk-CWCQP53A.js";import"./chunk-DGX3MN65.js";import"./chunk-QRDF33WD.js";import"./chunk-ZSSG7OR7.js";export{i as BridgeSimLockedError,a as RNX_PLACEMENT_ENV,f as bridgePortForShellBaseUrl,c as bridgeWsUrl,o as callInBridge,p as callInBridgeWrite,m as checkSimHealth,k as createBridge,l as createBridgeFromParsed,n as evalInBridge,j as parseBridgeCliArgs,h as printBridgeWorldNotice,d as resolveBridgeWorld,g as resolveDefaultBridgePort,b as resolvePlacement,e as worldForBridgePort};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- // npm installs package code only. `sootsim setup` owns runtime and machine
3
- // changes so installs never download a runtime or register a service implicitly.
@@ -1,118 +0,0 @@
1
- #!/usr/bin/env node
2
- // preuninstall — runs before `npm rm -g sootsim` actually removes the bin.
3
- //
4
- // without this hook the user is left with a 79MB ghost: a launchd/systemd
5
- // service still ENABLED + actively running (with ExecStart pointing at the
6
- // now-missing binary), ~/.sootsim/ (cache + runtimes + electron + profiles +
7
- // daemon.json), and the user's first instinct (`sootsim daemon uninstall`)
8
- // is gone with the package. so we tear it all down here, while the bin still
9
- // exists.
10
- //
11
- // reliability: npm preuninstall hooks are best-effort — they don't fire when
12
- // the package wasn't installed by npm (yarn/bun/pnpm have their own lifecycle
13
- // rules), and they don't run as part of `npm cache verify` cleanup or manual
14
- // dir removal. that's why `sootsim daemon uninstall` is also documented as
15
- // the manual teardown path.
16
- //
17
- // strategy: spawn the bundled bin to run `daemon uninstall` (single source of
18
- // truth — the same logic the user invokes manually). if that fails for any
19
- // reason — node version mismatch, the bin already removed by a previous
20
- // half-completed run, missing $HOME — do a best-effort raw fs cleanup so the
21
- // machine isn't left in a broken state.
22
-
23
- const { spawnSync } = require('child_process')
24
- const fs = require('fs')
25
- const os = require('os')
26
- const path = require('path')
27
-
28
- if (process.env.SOOTSIM_SKIP_PREUNINSTALL === '1') {
29
- process.exit(0)
30
- }
31
-
32
- // dev / workspace installs (running inside the Contrast monorepo, not in a
33
- // node_modules tree) — don't tear anything down. the developer is rebuilding
34
- // the workspace, not actually uninstalling.
35
- const pkgDir = path.resolve(__dirname, '..')
36
- if (!pkgDir.includes(`${path.sep}node_modules${path.sep}`)) {
37
- process.exit(0)
38
- }
39
-
40
- // skipped under sudo for the same reason as postinstall: $HOME would be /root,
41
- // but the user who needs cleanup is the one who installed sootsim. they can
42
- // run `sootsim daemon uninstall` themselves before `sudo npm rm -g sootsim`
43
- // to clean their own home.
44
- const isRoot = typeof process.getuid === 'function' && process.getuid() === 0
45
- if (isRoot && process.env.SUDO_USER) {
46
- console.log(
47
- 'rnx: preuninstall skipped under sudo — run `rnx daemon uninstall` ' +
48
- 'as your user first to remove ~/.sootsim and the bridge daemon',
49
- )
50
- process.exit(0)
51
- }
52
-
53
- const bin = path.join(pkgDir, 'dist-cli', 'bin.js')
54
- let unifiedOk = false
55
- if (fs.existsSync(bin)) {
56
- const res = spawnSync(process.execPath, [bin, 'daemon', 'uninstall'], {
57
- stdio: 'inherit',
58
- timeout: 30_000,
59
- })
60
- unifiedOk = res.status === 0
61
- }
62
-
63
- if (!unifiedOk) {
64
- // raw fallback. mirrors teardownDaemonService + teardownSootsimHome from
65
- // cli/commands/daemon.ts. idempotent: each entry is checked before remove.
66
- console.log('rnx: bin path failed — running raw cleanup fallback')
67
- rawCleanup()
68
- }
69
-
70
- process.exit(0)
71
-
72
- function rawCleanup() {
73
- const home = sootsimHomeDir()
74
- if (process.platform === 'darwin') {
75
- safeSpawn('launchctl', ['bootout', `gui/${getuid()}/dev.sootsim.daemon`])
76
- safeSpawn('launchctl', ['bootout', `gui/${getuid()}/dev.sootsim.server`])
77
- safeRemove(path.join(os.homedir(), 'Library/LaunchAgents/dev.sootsim.daemon.plist'))
78
- safeRemove(path.join(os.homedir(), 'Library/LaunchAgents/dev.sootsim.server.plist'))
79
- safeRemove(path.join(os.homedir(), 'Library/Logs/sootsim'), {
80
- recursive: true,
81
- })
82
- } else if (process.platform === 'linux') {
83
- safeSpawn('systemctl', ['--user', 'disable', '--now', 'sootsim-daemon'])
84
- safeSpawn('systemctl', ['--user', 'daemon-reload'])
85
- safeSpawn('systemctl', ['--user', 'reset-failed', 'sootsim-daemon'])
86
- safeRemove(path.join(os.homedir(), '.config/systemd/user/sootsim-daemon.service'))
87
- safeRemove(path.join(os.homedir(), '.local/state/sootsim'), { recursive: true })
88
- }
89
- // ~/.sootsim is the same on every platform; honor $SOOTSIM_HOME.
90
- safeRemove(home, { recursive: true })
91
- }
92
-
93
- function sootsimHomeDir() {
94
- const env = process.env.SOOTSIM_HOME
95
- if (env && env.length > 0) return path.resolve(env)
96
- return path.join(os.homedir(), '.sootsim')
97
- }
98
-
99
- function safeRemove(p, opts) {
100
- try {
101
- if (fs.existsSync(p)) {
102
- fs.rmSync(p, { force: true, ...(opts || {}) })
103
- console.log(` removed ${p}`)
104
- }
105
- } catch (err) {
106
- console.log(` could not remove ${p}: ${err && err.message}`)
107
- }
108
- }
109
-
110
- function safeSpawn(cmd, args) {
111
- try {
112
- spawnSync(cmd, args, { stdio: 'ignore' })
113
- } catch {}
114
- }
115
-
116
- function getuid() {
117
- return typeof process.getuid === 'function' ? process.getuid() : 0
118
- }