rnxsim 0.1.347 → 0.1.348

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 (167) hide show
  1. package/dist-cli/bin.js +5 -5
  2. package/dist-cli/chunks/{agent-VVY2A5YV.js → agent-VOCGVTX2.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-YBMTZ3KU.js → agent-wrapper-FJ65K7VP.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-EF7FM3VP.js → app-fonts-DUJRSKPV.js} +2 -2
  5. package/dist-cli/chunks/{assert-J7N6WGMS.js → assert-TWQWK2AW.js} +2 -2
  6. package/dist-cli/chunks/{auth-YGX3WVEL.js → auth-AQ3PDHBU.js} +2 -2
  7. package/dist-cli/chunks/{beta-JXYFAOHO.js → beta-E5MXYTSU.js} +2 -2
  8. package/dist-cli/chunks/{camera-WIVF3UQ3.js → camera-644CQ6CM.js} +2 -2
  9. package/dist-cli/chunks/{chunk-BA45ZZKU.js → chunk-2C23SW2O.js} +2 -2
  10. package/dist-cli/chunks/{chunk-2W4ME6YI.js → chunk-2W2WZV6U.js} +2 -2
  11. package/dist-cli/chunks/{chunk-SMLCC5EP.js → chunk-32GBZENF.js} +1 -1
  12. package/dist-cli/chunks/{chunk-6CGQWXXT.js → chunk-3H3VFCQA.js} +2 -2
  13. package/dist-cli/chunks/{chunk-XGUCAKZM.js → chunk-4WBCIUI5.js} +1 -1
  14. package/dist-cli/chunks/{chunk-2PAG4FBP.js → chunk-52F4KQTG.js} +2 -2
  15. package/dist-cli/chunks/{chunk-4KOWLH77.js → chunk-5AYTVU6P.js} +2 -2
  16. package/dist-cli/chunks/{chunk-4RI6KXVH.js → chunk-5C2YOOQB.js} +1 -1
  17. package/dist-cli/chunks/{chunk-DC4MQAR3.js → chunk-5UDXV7UU.js} +1 -1
  18. package/dist-cli/chunks/{chunk-4KK5IRA6.js → chunk-6QUIXWY4.js} +2 -2
  19. package/dist-cli/chunks/{chunk-LWE2HRS4.js → chunk-7KGKGYKZ.js} +2 -2
  20. package/dist-cli/chunks/{chunk-EEZEVA2C.js → chunk-7VUV64H6.js} +2 -2
  21. package/dist-cli/chunks/{chunk-2UZ6QQ6S.js → chunk-BC6P65EO.js} +2 -2
  22. package/dist-cli/chunks/{chunk-IS2LT6MN.js → chunk-BIEQJ66T.js} +2 -2
  23. package/dist-cli/chunks/{chunk-FQ3OHHCY.js → chunk-BNMD7ZGN.js} +2 -2
  24. package/dist-cli/chunks/{chunk-O7WPHIYQ.js → chunk-CHLYDXIP.js} +1 -1
  25. package/dist-cli/chunks/{chunk-7C6XE6AT.js → chunk-EJ5WTR3A.js} +2 -2
  26. package/dist-cli/chunks/{chunk-3HBHHU5F.js → chunk-EMNRIRDA.js} +3 -3
  27. package/dist-cli/chunks/{chunk-WIYBEKBM.js → chunk-EOXI7D6H.js} +2 -2
  28. package/dist-cli/chunks/{chunk-HWAGFGV7.js → chunk-EZSBYWMS.js} +3 -3
  29. package/dist-cli/chunks/{chunk-VENH5KLL.js → chunk-F5E3GJAF.js} +1 -1
  30. package/dist-cli/chunks/{chunk-DTNRKFSE.js → chunk-HNYPDSJ6.js} +2 -2
  31. package/dist-cli/chunks/{chunk-NJ2JVAGV.js → chunk-I5KU5FGG.js} +2 -2
  32. package/dist-cli/chunks/{chunk-BAXXUHKV.js → chunk-ILF4REF4.js} +2 -2
  33. package/dist-cli/chunks/{chunk-WNZOJDBL.js → chunk-JLWC7UJR.js} +1 -1
  34. package/dist-cli/chunks/{chunk-ANANQDHB.js → chunk-JPYL2LYZ.js} +1 -1
  35. package/dist-cli/chunks/{chunk-3SPBSEVL.js → chunk-JTGES3IH.js} +1 -1
  36. package/dist-cli/chunks/{chunk-SNBSRIKO.js → chunk-JXA2VQXZ.js} +2 -2
  37. package/dist-cli/chunks/{chunk-SYQZTZTR.js → chunk-KF6QGGYJ.js} +1 -1
  38. package/dist-cli/chunks/{chunk-ABBCVE5V.js → chunk-MCKYUOMA.js} +2 -2
  39. package/dist-cli/chunks/{chunk-JQTBZERT.js → chunk-MYOLOVHV.js} +2 -2
  40. package/dist-cli/chunks/{chunk-KYTBJ2QV.js → chunk-NSAUGFN3.js} +1 -1
  41. package/dist-cli/chunks/{chunk-LRRQI4TP.js → chunk-O7ZWWZA6.js} +2 -2
  42. package/dist-cli/chunks/{chunk-JG2TIZ7E.js → chunk-OKF5M2Z5.js} +2 -2
  43. package/dist-cli/chunks/{chunk-JP4FCK5J.js → chunk-PCVP5LMW.js} +2 -2
  44. package/dist-cli/chunks/{chunk-24Q4J4U6.js → chunk-PPURCICX.js} +1 -1
  45. package/dist-cli/chunks/{chunk-TAYE2YII.js → chunk-QXH2M3VL.js} +1 -1
  46. package/dist-cli/chunks/{chunk-IQWQ6KI7.js → chunk-RGOUICK3.js} +2 -2
  47. package/dist-cli/chunks/{chunk-ZY44NCRQ.js → chunk-S7YC23BL.js} +1 -1
  48. package/dist-cli/chunks/{chunk-QJYUHYQS.js → chunk-SZRLMZHI.js} +1 -1
  49. package/dist-cli/chunks/{chunk-7D56NCJ3.js → chunk-TAG7EJME.js} +2 -2
  50. package/dist-cli/chunks/{chunk-23WNLQUB.js → chunk-UONC7KUI.js} +2 -2
  51. package/dist-cli/chunks/{chunk-ZPCQFQEN.js → chunk-UWE33SLE.js} +1 -1
  52. package/dist-cli/chunks/{chunk-UM7IG4DE.js → chunk-V5EMBTTF.js} +2 -2
  53. package/dist-cli/chunks/{chunk-PCU2CQCI.js → chunk-VARLW54M.js} +3 -3
  54. package/dist-cli/chunks/{chunk-HY7XOD5E.js → chunk-VEXSD6UX.js} +1 -1
  55. package/dist-cli/chunks/{chunk-QK2U5IW3.js → chunk-VP6GLOZV.js} +2 -2
  56. package/dist-cli/chunks/{chunk-XB7DLZNQ.js → chunk-WC3A7REV.js} +1 -1
  57. package/dist-cli/chunks/{chunk-U6CJ3EHB.js → chunk-XFPFJPC3.js} +1 -1
  58. package/dist-cli/chunks/{chunk-Z6K6TD7X.js → chunk-XKXFMGVL.js} +1 -1
  59. package/dist-cli/chunks/{chunk-JKRVWCTC.js → chunk-XNDTB3MY.js} +1 -1
  60. package/dist-cli/chunks/{chunk-OG3KGU4V.js → chunk-XSZTWXKO.js} +2 -2
  61. package/dist-cli/chunks/{chunk-W4MASUQ7.js → chunk-ZJM65MGO.js} +2 -2
  62. package/dist-cli/chunks/{chunk-2E5KDIGN.js → chunk-ZP6XJFIZ.js} +2 -2
  63. package/dist-cli/chunks/{chunk-EIIZZ2XK.js → chunk-ZYN24EAC.js} +2 -2
  64. package/dist-cli/chunks/{cleanup-ZIDQQLEN.js → cleanup-TUEKM74E.js} +2 -2
  65. package/dist-cli/chunks/cli-version-G245R6SZ.js +4 -0
  66. package/dist-cli/chunks/{compat-5PFPTBBK.js → compat-IUPOKLTA.js} +2 -2
  67. package/dist-cli/chunks/{config-CG73FOTM.js → config-ASM5XAOP.js} +2 -2
  68. package/dist-cli/chunks/{control-7IYIDOOI.js → control-7MNUENCP.js} +2 -2
  69. package/dist-cli/chunks/daemon-Z4QQZ3MU.js +4 -0
  70. package/dist-cli/chunks/{debug-6AQQXXE3.js → debug-DHVKEWB4.js} +3 -3
  71. package/dist-cli/chunks/{desktop-HJE5B4XO.js → desktop-GLLBZHMW.js} +3 -3
  72. package/dist-cli/chunks/{detox-KUZ7EYOP.js → detox-WODZ2EWW.js} +2 -2
  73. package/dist-cli/chunks/{device-O6WI4PQT.js → device-X7CS5MQG.js} +2 -2
  74. package/dist-cli/chunks/{diagnose-FTCJGH2Q.js → diagnose-TYZCBRU3.js} +2 -2
  75. package/dist-cli/chunks/{disk-cleanup-YAXG52EZ.js → disk-cleanup-FPURW754.js} +2 -2
  76. package/dist-cli/chunks/drivers-3JKGMIIZ.js +4 -0
  77. package/dist-cli/chunks/{film-KTLKRCJR.js → film-37ZSWJKU.js} +3 -3
  78. package/dist-cli/chunks/flow-GQFLFIGW.js +4 -0
  79. package/dist-cli/chunks/help-YTY42PPH.js +4 -0
  80. package/dist-cli/chunks/{hidden-runtime-alias-W375XBOM.js → hidden-runtime-alias-6EFZUXQJ.js} +2 -2
  81. package/dist-cli/chunks/{home-paths-CIGRWLDB.js → home-paths-WD6TZ6QL.js} +2 -2
  82. package/dist-cli/chunks/inspect-HELBBLXA.js +4 -0
  83. package/dist-cli/chunks/install-desktop-2RRZVJNK.js +4 -0
  84. package/dist-cli/chunks/{login-AJWLXLPQ.js → login-2GWUX4NP.js} +2 -2
  85. package/dist-cli/chunks/{logout-CEJLZIOI.js → logout-BE7WGD5D.js} +2 -2
  86. package/dist-cli/chunks/{maestro-YF4M6M6L.js → maestro-O74P2DZG.js} +3 -3
  87. package/dist-cli/chunks/{maestro-generate-FJWDLMEB.js → maestro-generate-6JURLX3R.js} +3 -3
  88. package/dist-cli/chunks/{mode-6BJ523BY.js → mode-XYUVX7AU.js} +2 -2
  89. package/dist-cli/chunks/{optional-demo-registry-5CKCN2TP.js → optional-demo-registry-IC4UQVTB.js} +2 -2
  90. package/dist-cli/chunks/{perf-WE6QTFJU.js → perf-F5ZZQCBM.js} +2 -2
  91. package/dist-cli/chunks/{permissions-OZZZZFPB.js → permissions-7XDTQYJU.js} +2 -2
  92. package/dist-cli/chunks/privacy-XV5ZHV3E.js +4 -0
  93. package/dist-cli/chunks/{record-QHQS2524.js → record-EEKNNKJT.js} +3 -3
  94. package/dist-cli/chunks/{report-issue-SEMVVJUH.js → report-issue-56Z3NWRI.js} +2 -2
  95. package/dist-cli/chunks/reset-B6U3JO4X.js +4 -0
  96. package/dist-cli/chunks/runtime-PXGXWBEU.js +4 -0
  97. package/dist-cli/chunks/{screenshot-command-WW33MAB3.js → screenshot-command-MQ3WIBXC.js} +3 -3
  98. package/dist-cli/chunks/{screenshot-layers-2GJTEQ4T.js → screenshot-layers-6JAJQ3H2.js} +2 -2
  99. package/dist-cli/chunks/{screenshots-capture-J5HKONCC.js → screenshots-capture-NPW3E2QE.js} +2 -2
  100. package/dist-cli/chunks/{serve-FEBNDKUD.js → serve-KRV5HEU6.js} +15 -15
  101. package/dist-cli/chunks/{setup-NGZWS373.js → setup-IY4W4XPM.js} +2 -2
  102. package/dist-cli/chunks/{skills-CFCZFEME.js → skills-FLCPBNIS.js} +2 -2
  103. package/dist-cli/chunks/{state-XWRKK7FW.js → state-E73SW66N.js} +2 -2
  104. package/dist-cli/chunks/{storage-C5GNK4XB.js → storage-SE6JKPRT.js} +2 -2
  105. package/dist-cli/chunks/store-S2P72CGA.js +4 -0
  106. package/dist-cli/chunks/telemetry-SJ6SACTK.js +4 -0
  107. package/dist-cli/chunks/{timeline-7RA7ZILQ.js → timeline-SRNLNLRI.js} +2 -2
  108. package/dist-cli/chunks/{upgrade-ZW6IJ5LX.js → upgrade-6EBXQN2P.js} +2 -2
  109. package/dist-cli/chunks/upload-FV534V6T.js +4 -0
  110. package/dist-cli/chunks/{version-N3E4OIMM.js → version-F3LHN6MY.js} +2 -2
  111. package/dist-cli/chunks/{web-UC2SFEBA.js → web-AIQHG4YK.js} +2 -2
  112. package/dist-cli/chunks/{welcome-DAZPCMES.js → welcome-746DEM6E.js} +3 -3
  113. package/dist-cli/chunks/{what-happened-VUNKID5W.js → what-happened-QEZB6FLC.js} +2 -2
  114. package/dist-lib/agent-daemon-client.cjs +1 -1
  115. package/dist-lib/agent-events.cjs +1 -1
  116. package/dist-lib/agent-identity.cjs +1 -1
  117. package/dist-lib/agent-sessions.cjs +1 -1
  118. package/dist-lib/attached-projects.cjs +1 -1
  119. package/dist-lib/auth/shared-session.cjs +1 -1
  120. package/dist-lib/backend-origin.cjs +1 -1
  121. package/dist-lib/beta.cjs +1 -1
  122. package/dist-lib/beta.mjs +1 -1
  123. package/dist-lib/bridge-constants.cjs +1 -1
  124. package/dist-lib/bridge-contract.cjs +1 -1
  125. package/dist-lib/cli-constants.cjs +1 -1
  126. package/dist-lib/config.cjs +1 -1
  127. package/dist-lib/detox/index.cjs +1 -1
  128. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  129. package/dist-lib/home-paths.cjs +1 -1
  130. package/dist-lib/host/bridge-host.cjs +2 -4
  131. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  132. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  133. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  134. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  135. package/dist-lib/host/websocket-proxy.cjs +1 -1
  136. package/dist-lib/index.cjs +1 -1
  137. package/dist-lib/jump-to-source-babel.cjs +1 -1
  138. package/dist-lib/menu.cjs +1 -1
  139. package/dist-lib/menu.mjs +1 -1
  140. package/dist-lib/metro-production-bundle.cjs +1 -1
  141. package/dist-lib/metro-production-bundle.mjs +1 -1
  142. package/dist-lib/metro.cjs +1 -1
  143. package/dist-lib/profiles.cjs +1 -1
  144. package/dist-lib/public-brand.cjs +1 -1
  145. package/dist-lib/react-native-host-modules.cjs +1 -1
  146. package/dist-lib/react-native-host-modules.mjs +1 -1
  147. package/dist-lib/render-mode.cjs +1 -1
  148. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  149. package/dist-lib/sdk.cjs +1 -1
  150. package/dist-lib/sdk.mjs +1 -1
  151. package/dist-lib/skills.cjs +3 -4
  152. package/dist-lib/vite.cjs +1 -1
  153. package/package.json +1 -1
  154. package/src/host/bridge-host.ts +2 -7
  155. package/dist-cli/chunks/cli-version-BEJJXF35.js +0 -4
  156. package/dist-cli/chunks/daemon-G6VR7LJI.js +0 -4
  157. package/dist-cli/chunks/drivers-6QOL2SON.js +0 -4
  158. package/dist-cli/chunks/flow-6VQN4VNW.js +0 -4
  159. package/dist-cli/chunks/help-22OURA2E.js +0 -4
  160. package/dist-cli/chunks/inspect-36A2IEJL.js +0 -4
  161. package/dist-cli/chunks/install-desktop-KOW3XXUF.js +0 -4
  162. package/dist-cli/chunks/privacy-3BERNBUM.js +0 -4
  163. package/dist-cli/chunks/reset-A5AA5ML6.js +0 -4
  164. package/dist-cli/chunks/runtime-R26QWA2M.js +0 -4
  165. package/dist-cli/chunks/store-L3A4CLND.js +0 -4
  166. package/dist-cli/chunks/telemetry-O67J22QU.js +0 -4
  167. package/dist-cli/chunks/upload-UKUN6HCD.js +0 -4
@@ -1,10 +1,10 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{b as ye,c as K,d as be,e as G,f as ve,h as we,i as _,j as Ae,k as Te,l as Ce,m as xe,q as Ee,t as C,u as ke,v as Ie,w as Re,x as Pe}from"./chunk-W4MASUQ7.js";import"./chunk-Z6K6TD7X.js";import{e as Se}from"./chunk-IS2LT6MN.js";import"./chunk-2UZ6QQ6S.js";import"./chunk-23WNLQUB.js";import{a as me,c as he,d as D,e as fe}from"./chunk-4KOWLH77.js";import{d as ge}from"./chunk-LRRQI4TP.js";import{c as I,k as N}from"./chunk-2E5KDIGN.js";import"./chunk-SYQZTZTR.js";import"./chunk-3SPBSEVL.js";import{c as ue,d as pe}from"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import{f as M}from"./chunk-FQ3OHHCY.js";import{A as $,B as ee,G as te,I as L,J as V,K as ie,L as re,M as ne,O as se,R as oe,S as ae,T as ce,U as J,V as de,g as X,h as Z,r as Q}from"./chunk-WNZOJDBL.js";import{a as le}from"./chunk-IQWQ6KI7.js";import"./chunk-XGUCAKZM.js";import"./chunk-DC4MQAR3.js";import{spawn as _t}from"child_process";import T from"fs";import{createServer as Ot}from"http";import v from"path";import{WebSocket as S,WebSocketServer as Lt}from"ws";import Me from"node:fs";import B from"node:path";import{spawn as tt}from"node:child_process";var _e=/^[A-Za-z0-9._:-]{1,160}$/;function z(o){if(!o?.startsWith("TM_SESSION:"))return null;let e=o.slice(11).trim();return _e.test(e)?e:null}function Oe(o){return _e.test(o)}function it(o){return typeof o.text=="string"?o.text.trim():""}function rt(o){let e=o?.trim();return e||"tm"}async function Le(o){let e=o.sessionId.trim();if(!Oe(e))throw new Error(`invalid Team Machine session id: ${e||"<empty>"}`);let t=it(o.prompt);if(!t)throw new Error("prompt text is empty");let i=rt(o.command),r=o.timeoutMs??15e3;await new Promise((s,c)=>{let n=tt(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),a="",d=setTimeout(()=>{try{n.kill("SIGTERM")}catch{}c(new Error(`tm send timed out after ${Math.round(r/1e3)}s`))},r);n.stderr?.setEncoding("utf8"),n.stderr?.on("data",l=>{a.length<4e3&&(a+=String(l))}),n.on("error",l=>{clearTimeout(d),c(l)}),n.on("exit",(l,u)=>{if(clearTimeout(d),l===0){s();return}let p=a.trim();c(new Error(p||`tm send exited with ${u?`signal ${u}`:`code ${l??"unknown"}`}`))})})}var H=1,nt=25;function st(){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 s=await this.dispatch(e,i,t);this.respond(e,r,s)}catch(s){s instanceof C?this.respondError(e,r,s.message,s.code):this.respondError(e,r,s instanceof Error?s.message:String(s))}return!0}async seedOnBoot(){try{await xe()}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 G();case"agent:upsert-project":return K(i.input??{});case"agent:delete-project":return we(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return Ae(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 s=String(i.sessionId),c=_(s);if(!c)throw new C("NO_SESSION",`no session: ${s}`);let n=this.normalizePromptEnvelope(i);return await Ie(s,n),this.notePromptAccepted(s,n,c.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await Re(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 C("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new C("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 C("NO_CLAIM",`sim ${t} has no active CLI claim`);let r=z(i.cliIdentityKey);if(!r)throw new C("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await Le({sessionId:r,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"team-machine",sessionId:r}}async doStartSession(e){if(!be(e.projectId))throw new C("NO_PROJECT",`no project: ${e.projectId}`);let i=await ke(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?.()??st(),c=(await N({excludePorts:r})).find(l=>String(l.port)===i);if(!c||!c.cwd)return{project:null};let n=G().find(l=>l.cwd===c.cwd)??null,a=Array.from(new Set([...n?.knownBundleUrls??[],c.bundleUrl,t]));return{project:K({cwd:c.cwd,name:c.projectName??B.basename(c.cwd),preferredProvider:e.provider??n?.preferredProvider,sourceRoots:n?.sourceRoots??[c.cwd],knownBundleUrls:a,framework:n?.framework??ot(c.framework),bundleId:c.bundleId??n?.bundleId})}}getTranscript(e){let t=Ee(e);return Me.existsSync(t)?Me.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=ye();return{userDataDir:e,storeFile:B.join(e,"attached-projects.json"),sessionsDir:B.join(e,"sessions"),transcriptsDir:B.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let r=this.subscriptions.get(t);if(r)return r.refCount++,{ok:!0,refCount:r.refCount};let s=Pe(t,c=>{let n=this.coalescePromptEcho(t,c);if(n&&(this.applySessionEvent(t,n),this.fanOutEvent(t,n)),c.type==="turn-completed"){let a=_(t);if(a)try{ve(a.projectId,{usd:c.costUsd,ts:c.ts})}catch(d){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${d instanceof Error?d.message:String(d)}
4
+ import{b as ye,c as K,d as be,e as G,f as ve,h as we,i as _,j as Ae,k as Te,l as Ce,m as xe,q as Ee,t as x,u as ke,v as Ie,w as Re,x as Pe}from"./chunk-ZJM65MGO.js";import"./chunk-XKXFMGVL.js";import{e as Se}from"./chunk-BIEQJ66T.js";import"./chunk-BC6P65EO.js";import"./chunk-UONC7KUI.js";import{a as me,c as he,d as D,e as fe}from"./chunk-5AYTVU6P.js";import{d as ge}from"./chunk-O7ZWWZA6.js";import{c as C,k as N}from"./chunk-ZP6XJFIZ.js";import"./chunk-KF6QGGYJ.js";import"./chunk-JTGES3IH.js";import{c as ue,d as pe}from"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import{f as M}from"./chunk-BNMD7ZGN.js";import{A as $,B as ee,G as te,I as L,J as V,K as ie,L as re,M as ne,O as se,R as oe,S as ae,T as ce,U as J,V as de,g as X,h as Z,r as Q}from"./chunk-JLWC7UJR.js";import{a as le}from"./chunk-RGOUICK3.js";import"./chunk-4WBCIUI5.js";import"./chunk-5UDXV7UU.js";import{spawn as _t}from"child_process";import A from"fs";import{createServer as Ot}from"http";import v from"path";import{WebSocket as S,WebSocketServer as Lt}from"ws";import Me from"node:fs";import B from"node:path";import{spawn as tt}from"node:child_process";var _e=/^[A-Za-z0-9._:-]{1,160}$/;function z(o){if(!o?.startsWith("TM_SESSION:"))return null;let e=o.slice(11).trim();return _e.test(e)?e:null}function Oe(o){return _e.test(o)}function it(o){return typeof o.text=="string"?o.text.trim():""}function rt(o){let e=o?.trim();return e||"tm"}async function Le(o){let e=o.sessionId.trim();if(!Oe(e))throw new Error(`invalid Team Machine session id: ${e||"<empty>"}`);let t=it(o.prompt);if(!t)throw new Error("prompt text is empty");let i=rt(o.command),r=o.timeoutMs??15e3;await new Promise((s,c)=>{let n=tt(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),a="",d=setTimeout(()=>{try{n.kill("SIGTERM")}catch{}c(new Error(`tm send timed out after ${Math.round(r/1e3)}s`))},r);n.stderr?.setEncoding("utf8"),n.stderr?.on("data",l=>{a.length<4e3&&(a+=String(l))}),n.on("error",l=>{clearTimeout(d),c(l)}),n.on("exit",(l,u)=>{if(clearTimeout(d),l===0){s();return}let m=a.trim();c(new Error(m||`tm send exited with ${u?`signal ${u}`:`code ${l??"unknown"}`}`))})})}var H=1,nt=25;function st(){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 s=await this.dispatch(e,i,t);this.respond(e,r,s)}catch(s){s instanceof x?this.respondError(e,r,s.message,s.code):this.respondError(e,r,s instanceof Error?s.message:String(s))}return!0}async seedOnBoot(){try{await xe()}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 G();case"agent:upsert-project":return K(i.input??{});case"agent:delete-project":return we(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return Ae(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 s=String(i.sessionId),c=_(s);if(!c)throw new x("NO_SESSION",`no session: ${s}`);let n=this.normalizePromptEnvelope(i);return await Ie(s,n),this.notePromptAccepted(s,n,c.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await Re(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 x("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new x("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 x("NO_CLAIM",`sim ${t} has no active CLI claim`);let r=z(i.cliIdentityKey);if(!r)throw new x("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await Le({sessionId:r,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"team-machine",sessionId:r}}async doStartSession(e){if(!be(e.projectId))throw new x("NO_PROJECT",`no project: ${e.projectId}`);let i=await ke(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?.()??st(),c=(await N({excludePorts:r})).find(l=>String(l.port)===i);if(!c||!c.cwd)return{project:null};let n=G().find(l=>l.cwd===c.cwd)??null,a=Array.from(new Set([...n?.knownBundleUrls??[],c.bundleUrl,t]));return{project:K({cwd:c.cwd,name:c.projectName??B.basename(c.cwd),preferredProvider:e.provider??n?.preferredProvider,sourceRoots:n?.sourceRoots??[c.cwd],knownBundleUrls:a,framework:n?.framework??ot(c.framework),bundleId:c.bundleId??n?.bundleId})}}getTranscript(e){let t=Ee(e);return Me.existsSync(t)?Me.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=ye();return{userDataDir:e,storeFile:B.join(e,"attached-projects.json"),sessionsDir:B.join(e,"sessions"),transcriptsDir:B.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let r=this.subscriptions.get(t);if(r)return r.refCount++,{ok:!0,refCount:r.refCount};let s=Pe(t,c=>{let n=this.coalescePromptEcho(t,c);if(n&&(this.applySessionEvent(t,n),this.fanOutEvent(t,n)),c.type==="turn-completed"){let a=_(t);if(a)try{ve(a.projectId,{usd:c.costUsd,ts:c.ts})}catch(d){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${d instanceof Error?d.message:String(d)}
6
6
  `)}}});return this.subscriptions.set(t,{unsubscribe:s,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(),s=this.pendingPromptEchoes.get(e)??[];s.push({sentAt:r}),this.pendingPromptEchoes.set(e,s);let c=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,c);let n=t.displayText??t.text;return this.patchSession(e,{lastPrompt:n,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:n,...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=Te(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()},nt))}flushSessionStatuses(){if(this.pendingSessionPatches.size===0)return;let e=this.pendingSessionStates,t=this.pendingSessionPatches;this.pendingSessionStates=new Map,this.pendingSessionPatches=new Map;try{Ce([...t].map(([i,r])=>({id:i,patch:r})))}catch(i){for(let[r,s]of e)this.pendingSessionStates.has(r)||this.pendingSessionStates.set(r,s);for(let[r,s]of t)this.pendingSessionPatches.set(r,{...s,...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,s]of this.sessionsBySocket)if(s.has(e)&&r.readyState===H)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===H)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===H)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,r){if(e.readyState===H)try{e.send(JSON.stringify({id:t,error:i,...r?{code:r}:{}}))}catch{}}};function ot(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import De from"http";import Be from"https";import{finished as dt,pipeline as lt}from"stream/promises";var q="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",at=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function ct(o){let e=o.toLowerCase();for(let t of at)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function Ne(o){let e=ct(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":q},...e?.headers}}var ut=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"]),pt={"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"},mt=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function He(o){return o.protocol!=="https:"?{}:I(o.hostname)?{rejectUnauthorized:!1}:{}}function O(o){for(let[e,t]of Object.entries(pt))o.setHeader(e,t)}function ht(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 s=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${s} | upstream url still contains placeholder env values`:s}function ft(o,e){let t={};for(let[i,r]of Object.entries(o))r&&(ut.has(i.toLowerCase())||(t[i]=Array.isArray(r)?r.join(", "):r));return Object.assign(t,e?Ne(e):{"user-agent":q}),t}function gt(o,e){let t={};for(let[i,r]of Object.entries(o))r&&(mt.has(i.toLowerCase())||(t[i]=r));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function Ue(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function Fe(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function je(o,e){if(o.method==="OPTIONS"){O(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){O(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let r;try{r=new URL(i)}catch{O(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let s;if(o.method!=="GET"&&o.method!=="HEAD"){let a=[];for await(let d of o)a.push(Buffer.isBuffer(d)?d:Buffer.from(d));a.length>0&&(s=Buffer.concat(a))}let c=o.method||"GET",n=async(a,d,l,u)=>{let p=a.protocol==="https:"?Be:De,m=ft(o.headers,a);a.origin!==r.origin&&(delete m.authorization,delete m["proxy-authorization"]),d==="GET"||d==="HEAD"?(delete m["content-length"],delete m["content-type"]):l&&(m["content-length"]=String(l.byteLength));let f=await new Promise((w,A)=>{let y=p.request({hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:a.pathname+a.search,method:d,headers:m,...He(a)},w),k=()=>y.destroy(new Error("fetch proxy client disconnected"));o.once("aborted",k),y.once("close",()=>o.off("aborted",k)),y.once("error",A),l===void 0?y.end():y.end(l)}),h=f.statusCode??502,g=f.headers.location;if(g&&(h===301||h===302||h===303||h===307||h===308)){if(u>=10)throw f.destroy(),new Error("too many redirects");let w=(h===301||h===302)&&d==="POST"||h===303&&d!=="GET"&&d!=="HEAD",A=new URL(g,a);f.resume(),await dt(f),await n(A,w?"GET":d,w?void 0:l,u+1);return}for(let[w,A]of Object.entries(f.headers)){let y=w.toLowerCase();A===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(w,A)}O(e);let b=f.headers["set-cookie"]??[];b.length>0&&e.setHeader("x-sootsim-set-cookie",(Array.isArray(b)?b:[b]).join(", ")),e.statusCode=h,await lt(f,e)};try{await n(r,c,s,0)}catch(a){if(e.headersSent){e.destroy(a instanceof Error?a:new Error(String(a)));return}O(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${ht(r.href,a)}`)}}function We(o,e){let t=o.url||"",i="",r="";if(t.startsWith("/__app-api?")){let d=new URL(t,"http://sootsim.local");i=d.searchParams.get("path")||"",r=d.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 s;try{s=new URL(i,r)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let c=s.protocol==="https:"?Be:De,n=gt(o.headers,s),a=c.request({hostname:s.hostname,port:s.port||(s.protocol==="https:"?443:80),path:s.pathname+s.search,method:o.method,headers:n,...He(s)},d=>{let l=Object.keys(d.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(d.statusCode??502,{...d.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":l}),d.pipe(e)});return a.on("error",d=>{e.statusCode=502,e.end(`app proxy error: ${d.message}`)}),o.pipe(a),!0}import $e from"node:fs/promises";import x from"node:path";import{build as St}from"esbuild";var Ve="/__sootsim-replacement-module",R="/__sootsim-replacement-runtime";function yt(o){switch(x.extname(o).toLowerCase()){case".js":return"js";case".jsx":return"jsx";case".ts":return"ts";case".tsx":return"tsx";default:return null}}function bt(o){return o?`export * from ${JSON.stringify(o)};
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,s]of this.sessionsBySocket)if(s.has(e)&&r.readyState===H)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===H)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===H)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,r){if(e.readyState===H)try{e.send(JSON.stringify({id:t,error:i,...r?{code:r}:{}}))}catch{}}};function ot(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import De from"http";import Be from"https";import{finished as dt,pipeline as lt}from"stream/promises";var q="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",at=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function ct(o){let e=o.toLowerCase();for(let t of at)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function Ne(o){let e=ct(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":q},...e?.headers}}var ut=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"]),pt={"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"},mt=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function He(o){return o.protocol!=="https:"?{}:C(o.hostname)?{rejectUnauthorized:!1}:{}}function O(o){for(let[e,t]of Object.entries(pt))o.setHeader(e,t)}function ht(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 s=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${s} | upstream url still contains placeholder env values`:s}function ft(o,e){let t={};for(let[i,r]of Object.entries(o))r&&(ut.has(i.toLowerCase())||(t[i]=Array.isArray(r)?r.join(", "):r));return Object.assign(t,e?Ne(e):{"user-agent":q}),t}function gt(o,e){let t={};for(let[i,r]of Object.entries(o))r&&(mt.has(i.toLowerCase())||(t[i]=r));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function Ue(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function Fe(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function je(o,e){if(o.method==="OPTIONS"){O(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){O(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let r;try{r=new URL(i)}catch{O(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let s;if(o.method!=="GET"&&o.method!=="HEAD"){let a=[];for await(let d of o)a.push(Buffer.isBuffer(d)?d:Buffer.from(d));a.length>0&&(s=Buffer.concat(a))}let c=o.method||"GET",n=async(a,d,l,u)=>{let m=a.protocol==="https:"?Be:De,p=ft(o.headers,a);a.origin!==r.origin&&(delete p.authorization,delete p["proxy-authorization"]),d==="GET"||d==="HEAD"?(delete p["content-length"],delete p["content-type"]):l&&(p["content-length"]=String(l.byteLength));let h=await new Promise((w,T)=>{let y=m.request({hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:a.pathname+a.search,method:d,headers:p,...He(a)},w),I=()=>y.destroy(new Error("fetch proxy client disconnected"));o.once("aborted",I),y.once("close",()=>o.off("aborted",I)),y.once("error",T),l===void 0?y.end():y.end(l)}),f=h.statusCode??502,g=h.headers.location;if(g&&(f===301||f===302||f===303||f===307||f===308)){if(u>=10)throw h.destroy(),new Error("too many redirects");let w=(f===301||f===302)&&d==="POST"||f===303&&d!=="GET"&&d!=="HEAD",T=new URL(g,a);h.resume(),await dt(h),await n(T,w?"GET":d,w?void 0:l,u+1);return}for(let[w,T]of Object.entries(h.headers)){let y=w.toLowerCase();T===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(w,T)}O(e);let b=h.headers["set-cookie"]??[];b.length>0&&e.setHeader("x-sootsim-set-cookie",(Array.isArray(b)?b:[b]).join(", ")),e.statusCode=f,await lt(h,e)};try{await n(r,c,s,0)}catch(a){if(e.headersSent){e.destroy(a instanceof Error?a:new Error(String(a)));return}O(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${ht(r.href,a)}`)}}function We(o,e){let t=o.url||"",i="",r="";if(t.startsWith("/__app-api?")){let d=new URL(t,"http://sootsim.local");i=d.searchParams.get("path")||"",r=d.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 s;try{s=new URL(i,r)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let c=s.protocol==="https:"?Be:De,n=gt(o.headers,s),a=c.request({hostname:s.hostname,port:s.port||(s.protocol==="https:"?443:80),path:s.pathname+s.search,method:o.method,headers:n,...He(s)},d=>{let l=Object.keys(d.headers).filter(u=>{let m=u.toLowerCase();return!m.startsWith("access-control-")&&m!=="set-cookie"}).join(", ");e.writeHead(d.statusCode??502,{...d.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":l}),d.pipe(e)});return a.on("error",d=>{e.statusCode=502,e.end(`app proxy error: ${d.message}`)}),o.pipe(a),!0}import $e from"node:fs/promises";import E from"node:path";import{build as St}from"esbuild";var Ve="/__sootsim-replacement-module",R="/__sootsim-replacement-runtime";function yt(o){switch(E.extname(o).toLowerCase()){case".js":return"js";case".jsx":return"jsx";case".ts":return"ts";case".tsx":return"tsx";default:return null}}function bt(o){return o?`export * from ${JSON.stringify(o)};
8
8
  import React from ${JSON.stringify(o)};
9
9
  export default React;
10
10
  `:`const bridge = globalThis.__sootsim_react_bridge
@@ -77,26 +77,26 @@ export const Platform = rn.Platform
77
77
  export const Keyboard = rn.Keyboard
78
78
  export const Dimensions = rn.Dimensions
79
79
  export const Appearance = rn.Appearance
80
- `}function Y(o,e,t){let i=o.headers.origin,r;if(i)try{I(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 Je(o){if(!o)return!1;try{let e=new URL(o,"http://rnx.local").pathname;return e===Ve||e.startsWith(`${R}/`)}catch{return!1}}async function Ke(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,l=o.socket.remoteAddress?.replace(/^::ffff:/,""),u=!!(l&&I(l));if(u&&d)try{u=I(new URL(d).hostname)}catch{u=!1}if(!u)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===`${R}/react`)return Y(o,e,bt(t.reactBridgeUrl)),!0;if(r.pathname===`${R}/react-native`)return Y(o,e,vt()),!0;if(r.pathname!==Ve)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 s=r.searchParams.get("path");if(!s)return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("missing path param"),!0;if(!yt(s))return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement files must be .js, .jsx, .ts, or .tsx"),!0;if(!x.isAbsolute(s))return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file path must be absolute"),!0;let n;if(t.projectRoot){let d=x.resolve(t.projectRoot);n=await $e.realpath(t.projectRoot);let l=x.relative(d,s);if(l.startsWith("..")||x.isAbsolute(l))return e.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file must be inside the project root"),!0}let a;try{a=await $e.realpath(s)}catch(d){let l=d instanceof Error?d.message:String(d);return e.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),e.end(`replacement file not found: ${l}`),!0}if(n){let d=x.relative(n,a);if(d.startsWith("..")||x.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 l=(await St({entryPoints:[a],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",external:["react","react-native"]})).outputFiles[0]?.text??"",u=/\bimport\s+(?:\*\s+as\s+React|React(?:\s*,|\s+from)|\{[^}]*\bdefault\s+as\s+React\b)/.test(l),m=((/\bReact\.(?:createElement|Fragment)\b/.test(l)&&!u?`import * as React from '${R}/react';
81
- `:"")+l).replace(/from\s*["']react-native["']/g,`from '${R}/react-native'`).replace(/from\s*["']react["']/g,`from '${R}/react'`);Y(o,e,m)}catch(d){let l=d instanceof Error?d.message:String(d);e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end(`replacement bundle failed: ${l}`)}return!0}import{WebSocket as E,WebSocketServer as wt}from"ws";var At="/__websocket-proxy",Tt=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
80
+ `}function Y(o,e,t){let i=o.headers.origin,r;if(i)try{C(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 Je(o){if(!o)return!1;try{let e=new URL(o,"http://rnx.local").pathname;return e===Ve||e.startsWith(`${R}/`)}catch{return!1}}async function Ke(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,l=o.socket.remoteAddress?.replace(/^::ffff:/,""),u=!!(l&&C(l));if(u&&d)try{u=C(new URL(d).hostname)}catch{u=!1}if(!u)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===`${R}/react`)return Y(o,e,bt(t.reactBridgeUrl)),!0;if(r.pathname===`${R}/react-native`)return Y(o,e,vt()),!0;if(r.pathname!==Ve)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 s=r.searchParams.get("path");if(!s)return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("missing path param"),!0;if(!yt(s))return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement files must be .js, .jsx, .ts, or .tsx"),!0;if(!E.isAbsolute(s))return e.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file path must be absolute"),!0;let n;if(t.projectRoot){let d=E.resolve(t.projectRoot);n=await $e.realpath(t.projectRoot);let l=E.relative(d,s);if(l.startsWith("..")||E.isAbsolute(l))return e.writeHead(403,{"Content-Type":"text/plain; charset=utf-8"}),e.end("replacement file must be inside the project root"),!0}let a;try{a=await $e.realpath(s)}catch(d){let l=d instanceof Error?d.message:String(d);return e.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),e.end(`replacement file not found: ${l}`),!0}if(n){let d=E.relative(n,a);if(d.startsWith("..")||E.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 l=(await St({entryPoints:[a],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",external:["react","react-native"]})).outputFiles[0]?.text??"",u=/\bimport\s+(?:\*\s+as\s+React|React(?:\s*,|\s+from)|\{[^}]*\bdefault\s+as\s+React\b)/.test(l),p=((/\bReact\.(?:createElement|Fragment)\b/.test(l)&&!u?`import * as React from '${R}/react';
81
+ `:"")+l).replace(/from\s*["']react-native["']/g,`from '${R}/react-native'`).replace(/from\s*["']react["']/g,`from '${R}/react'`);Y(o,e,p)}catch(d){let l=d instanceof Error?d.message:String(d);e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end(`replacement bundle failed: ${l}`)}return!0}import{WebSocket as k,WebSocketServer as wt}from"ws";var At="/__websocket-proxy",Tt=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
82
82
  Connection: close\r
83
83
  Content-Type: text/plain\r
84
84
  Content-Length: ${t.length}\r
85
85
  \r
86
- ${t}`)}catch{}o.destroy()}function Ct(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 xt(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[s,c]of Object.entries(i))c!=null&&(Tt.has(s.toLowerCase())||(r[s]=Array.isArray(c)?c.join(", "):String(c)));return r}function Et(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function kt(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function F(o,e,t){if(!(o.readyState===E.CLOSED||o.readyState===E.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function It(o,e){let t=!1,i=(r,s,c,n)=>{t||(t=!0,F(s,c,n.toString()),r.readyState===E.OPEN&&F(r,c,n.toString()))};o.on("message",(r,s)=>{e.readyState===E.OPEN&&e.send(r,{binary:s})}),e.on("message",(r,s)=>{o.readyState===E.OPEN&&o.send(r,{binary:s})}),o.on("close",(r,s)=>i(o,e,r,s)),e.on("close",(r,s)=>i(e,o,r,s)),o.on("error",()=>F(e,1011,"proxy client error")),e.on("error",()=>F(o,1011,"upstream websocket error"))}function Rt(o,e,t,i){let r={...t},s=Object.keys(r).filter(c=>c.toLowerCase()==="origin");if(i&&s.length===0)r.origin=Et(o);else if(!i)for(let c of s)delete r[c];return Object.keys(r).length===0?new E(o.href,e):new E(o.href,e,{headers:r})}function Pt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===At}catch{return!1}}function Ge(o,e,t,i=!0){if(!Pt(o.url))return!1;if(!Ct(o))return P(e,403,"forbidden websocket proxy origin"),!0;let r,s;try{let d=new URL(o.url||"/","http://localhost"),l=d.searchParams.get("url");if(!l)return P(e,400,"missing websocket proxy url"),!0;if(r=new URL(l),r.protocol!=="ws:"&&r.protocol!=="wss:")return P(e,400,"invalid websocket proxy protocol"),!0;s=xt(d.searchParams.get("headers"))}catch{return P(e,400,"invalid websocket proxy request"),!0}let c=kt(o),n=Rt(r,c,s,i),a=!1;return e.once("close",()=>{a||n.terminate()}),n.once("open",()=>{if(a)return;a=!0;let d=n.protocol;new wt({noServer:!0,clientTracking:!1,handleProtocols(u){return d||u.values().next().value||!1}}).handleUpgrade(o,e,t,u=>{It(u,n)})}),n.once("error",()=>{a||(a=!0,P(e,502,"upstream websocket error"))}),n.once("close",()=>{a||(a=!0,P(e,502,"upstream websocket closed"))}),!0}var Mt="require-corp",Nt=new Set(["tap","keyboard","longPress","perform","reset","camera"]),Dt=2e3,Bt=1e3;function Ht(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:Nt.has(o.type)}var ze=5e3,Ut=3600*1e3,Ft="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",qe={".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"},Ye="/__camera-fixtures/",jt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Xe(o,e,t){let i;try{let a=$();i=JSON.stringify(a)}catch{i="{}"}let r=e>0?`window.__sootsimBridgePort=${e};`:"",s=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",c=`<script>window.__sootsimSharedConfig=${i};`+r+s+`window.__sootsimCliVersion=${JSON.stringify(le())};</script>`,n=o.toString("utf8");return n.includes("<head>")?n.replace("<head>",`<head>${c}`):n.includes("</head>")?n.replace("</head>",c+"</head>"):n.includes("</body>")?n.replace("</body>",c+"</body>"):c+n}function Ze(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var j=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;contrastOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new 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)
86
+ ${t}`)}catch{}o.destroy()}function Ct(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 xt(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[s,c]of Object.entries(i))c!=null&&(Tt.has(s.toLowerCase())||(r[s]=Array.isArray(c)?c.join(", "):String(c)));return r}function Et(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function kt(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function F(o,e,t){if(!(o.readyState===k.CLOSED||o.readyState===k.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function It(o,e){let t=!1,i=(r,s,c,n)=>{t||(t=!0,F(s,c,n.toString()),r.readyState===k.OPEN&&F(r,c,n.toString()))};o.on("message",(r,s)=>{e.readyState===k.OPEN&&e.send(r,{binary:s})}),e.on("message",(r,s)=>{o.readyState===k.OPEN&&o.send(r,{binary:s})}),o.on("close",(r,s)=>i(o,e,r,s)),e.on("close",(r,s)=>i(e,o,r,s)),o.on("error",()=>F(e,1011,"proxy client error")),e.on("error",()=>F(o,1011,"upstream websocket error"))}function Rt(o,e,t,i){let r={...t},s=Object.keys(r).filter(c=>c.toLowerCase()==="origin");if(i&&s.length===0)r.origin=Et(o);else if(!i)for(let c of s)delete r[c];return Object.keys(r).length===0?new k(o.href,e):new k(o.href,e,{headers:r})}function Pt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===At}catch{return!1}}function Ge(o,e,t,i=!0){if(!Pt(o.url))return!1;if(!Ct(o))return P(e,403,"forbidden websocket proxy origin"),!0;let r,s;try{let d=new URL(o.url||"/","http://localhost"),l=d.searchParams.get("url");if(!l)return P(e,400,"missing websocket proxy url"),!0;if(r=new URL(l),r.protocol!=="ws:"&&r.protocol!=="wss:")return P(e,400,"invalid websocket proxy protocol"),!0;s=xt(d.searchParams.get("headers"))}catch{return P(e,400,"invalid websocket proxy request"),!0}let c=kt(o),n=Rt(r,c,s,i),a=!1;return e.once("close",()=>{a||n.terminate()}),n.once("open",()=>{if(a)return;a=!0;let d=n.protocol;new wt({noServer:!0,clientTracking:!1,handleProtocols(u){return d||u.values().next().value||!1}}).handleUpgrade(o,e,t,u=>{It(u,n)})}),n.once("error",()=>{a||(a=!0,P(e,502,"upstream websocket error"))}),n.once("close",()=>{a||(a=!0,P(e,502,"upstream websocket closed"))}),!0}var Mt="require-corp",Nt=new Set(["tap","keyboard","longPress","perform","reset","camera"]),Dt=2e3,Bt=1e3;function Ht(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:Nt.has(o.type)}var ze=5e3,Ut=3600*1e3,Ft="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",qe={".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"},Ye="/__camera-fixtures/",jt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function Xe(o,e,t){let i;try{let a=$();i=JSON.stringify(a)}catch{i="{}"}let r=e>0?`window.__sootsimBridgePort=${e};`:"",s=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",c=`<script>window.__sootsimSharedConfig=${i};`+r+s+`window.__sootsimCliVersion=${JSON.stringify(le())};</script>`,n=o.toString("utf8");return n.includes("<head>")?n.replace("<head>",`<head>${c}`):n.includes("</head>")?n.replace("</head>",c+"</head>"):n.includes("</body>")?n.replace("</body>",c+"</body>"):c+n}function Ze(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var j=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;contrastOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new 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)
87
87
  `),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}
88
88
  `)}}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 s=Ot((a,d)=>this.handleHttpRequest(a,d)),c=!1,n=a=>{if(!c){c=!0;try{s.close()}catch{}this.httpServer=null,this.wss=null,r(a)}};s.once("error",n),s.listen(e,"127.0.0.1",()=>{c||(c=!0,s.removeListener("error",n),s.on("error",a=>{process.stderr.write(`ws bridge http error: ${String(a)}
89
- `)}),this.httpServer=s,this.wss=new Lt({noServer:!0}),this.wireWebSocketServer(),s.on("upgrade",(a,d,l)=>{Ge(a,d,l)||this.wss?.handleUpgrade(a,d,l,u=>{this.wss?.emit("connection",u,a)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,r=i?"sim":"cli",s=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),r==="sim")s={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(s.id,s),this.writeConnectedRuntimeSnapshot(),this.shouldPromoteSim(s)&&(this.primarySimId=s.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let c=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,c)}e.on("message",c=>{let n;try{n=JSON.parse(c.toString())}catch{return}if(!(!n||typeof n!="object")){if(typeof n.type=="string"&&n.type.startsWith("agent:")){this.agentHost.handleMessage(e,n);return}if(n.type==="runtime:list"){let a=M.listInstalled(),d=this.getActiveRuntime(),l={type:"runtime:list:ok",id:n.id,installed:a,active:d.version,activeRuntimeDir:d.runtimeDir};try{e.send(JSON.stringify(l))}catch{}return}if(n.type==="runtime:use"){let a=typeof n.version=="string"?n.version:"";if(!M.listInstalled().includes(a)){try{e.send(JSON.stringify({type:"runtime:use:error",id:n.id,error:`runtime ${a||"(missing)"} is not installed`}))}catch{}return}let l=this.setActiveRuntime(a);try{e.send(JSON.stringify({type:"runtime:use:ok",id:n.id,version:l.version,runtimeDir:l.runtimeDir}))}catch{}return}if(n.type==="runtime:get"){let a=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:n.id,active:a.version,activeRuntimeDir:a.runtimeDir}))}catch{}return}if(r==="sim"&&n.type==="bridge:hello"&&s&&!s.url){let a=s.id;this.sims.delete(a),this.primarySimId===a&&(this.primarySimId=this.getOpenSim()?.id??null),s=null,r="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.writeConnectedRuntimeSnapshot(),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(r==="sim"){if(s&&(s.lastSeenAt=Date.now()),n.type==="bridge:register"&&s){let l=n,u=this.tryRestoreSimId(s,l.simId);s.url=l.url,s.title=l.title,s.userAgent=l.userAgent,this.writeConnectedRuntimeSnapshot(),typeof l.kind=="string"&&l.kind.trim()&&(s.kind=l.kind.trim()),l.meta&&typeof l.meta=="object"&&(s.meta=l.meta);let p=this.primarySimId!==s.id&&this.shouldPromoteSim(s);p&&(this.primarySimId=s.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(n.type==="bridge:user-focus-state"&&s){let l=n;this.updateUserFocusLease(s,l);return}if(n.type==="bridge:user-interact"&&s){this.updateUserActivity(s);return}if(n.type==="bridge:write-shared-config"){if(!n.patch||typeof n.patch!="object"||Array.isArray(n.patch))return;let l=Object.fromEntries(Object.entries(n.patch));try{this.writeAndBroadcastSharedConfig(l)}catch(u){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${u instanceof Error?u.message:String(u)}
90
- `);return}return}if(n.type==="bridge:open-path"){let l=typeof n.path=="string"?n.path:"",u=typeof n.line=="number"&&Number.isFinite(n.line)?n.line:void 0,p=typeof n.column=="number"&&Number.isFinite(n.column)?n.column:void 0;l&&this.openPathInEditor(l,u,p);return}if(n.type==="bridge:boot-clients"&&s){let l=[];for(let[p,m]of this.cliSimBySocket)m===s.id&&l.push(p);for(let p of l){this.cliSimBySocket.delete(p);try{p.close(1e3,"booted by sim")}catch{}}let u=!!s.cliLease;s.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`rnx booted ${l.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${s.id}]
91
- `),this.recordSimAction(s.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let a=this.pendingCommands.get(n.id);if(a){this.pendingCommands.delete(n.id),n.error?a.reject(new Error(n.error)):a.resolve(n.result);return}let d=this.cliBySentId.get(n.id);if(d&&(this.cliBySentId.delete(n.id),d.ws.readyState===S.OPEN)){let l=this.getOtherCliIdentityCount(d.ws,d.simId),u=l>0?{...n,id:d.originalId,_otherCliCount:l}:{...n,id:d.originalId};d.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(n.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[m,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(m);p&&this.broadcastSimClientStates();return}if(n.type==="bridge:hello"){let p=typeof n.cliIdentityKey=="string"&&n.cliIdentityKey.trim()?n.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof n.cliLabel=="string"&&n.cliLabel.trim()&&this.cliLabelBySocket.set(e,n.cliLabel.trim()),e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:{cliIdentityKey:p,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(n.type==="bridge:list-sims"){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:this.listSims()}));return}if(n.type==="bridge:claim"){let p=await this.waitForSim(n.simId),m=this.tryAcquireLease(e,p,{force:n.force===!0});if(!m.granted){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,error:`sim ${p.id} is locked by another cli`,_locked:m.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,m.bootedCount>0?`cli force-claimed sim (booted ${m.bootedCount})`:"cli claimed sim"),e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:{simId:p.id,lockedBy:m.lease.cliIdentityKey,lockExpiresAt:m.lease.expiresAt,bootedCount:m.bootedCount}}));return}let a=await this.waitForSim(n.simId);if(Ht(n)){let p=this.tryAcquireLease(e,a);if(!p.granted){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.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(n));let d=this.nextCommandId++;this.cliBySentId.set(d,{simId:a.id,ws:e,originalId:n.id});let{simId:l,...u}=n;if(a.ws.send(JSON.stringify({...u,id:d})),u.type==="close"){this.cliBySentId.delete(d),e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:{requested:!0,simId:a.id}}));let p=a.ws,m=setTimeout(()=>{this.closeSimSocketFromHost(p)},Dt);Ze(m)}}catch(a){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,error:a instanceof Error?a.message:String(a)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),r==="sim"&&s){this.rememberDisconnectedSim(s),this.primarySimId===s.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[c,n]of this.pendingCommands)n.simId===s.id&&(n.reject(new Error("sim disconnected")),this.pendingCommands.delete(c));for(let[c,n]of this.cliBySentId)n.simId===s.id&&(n.ws.readyState===S.OPEN&&n.ws.send(JSON.stringify({id:n.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[n,a]of this.cliBySentId)a.ws===e&&this.cliBySentId.delete(n);c&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
89
+ `)}),this.httpServer=s,this.wss=new Lt({noServer:!0}),this.wireWebSocketServer(),s.on("upgrade",(a,d,l)=>{Ge(a,d,l)||this.wss?.handleUpgrade(a,d,l,u=>{this.wss?.emit("connection",u,a)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,r=i?"sim":"cli",s=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),r==="sim")s={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(s.id,s),this.writeConnectedRuntimeSnapshot(),this.shouldPromoteSim(s)&&(this.primarySimId=s.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let c=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,c)}e.on("message",c=>{let n;try{n=JSON.parse(c.toString())}catch{return}if(!(!n||typeof n!="object")){if(typeof n.type=="string"&&n.type.startsWith("agent:")){this.agentHost.handleMessage(e,n);return}if(n.type==="runtime:list"){let a=M.listInstalled(),d=this.getActiveRuntime(),l={type:"runtime:list:ok",id:n.id,installed:a,active:d.version,activeRuntimeDir:d.runtimeDir};try{e.send(JSON.stringify(l))}catch{}return}if(n.type==="runtime:use"){let a=typeof n.version=="string"?n.version:"";if(!M.listInstalled().includes(a)){try{e.send(JSON.stringify({type:"runtime:use:error",id:n.id,error:`runtime ${a||"(missing)"} is not installed`}))}catch{}return}let l=this.setActiveRuntime(a);try{e.send(JSON.stringify({type:"runtime:use:ok",id:n.id,version:l.version,runtimeDir:l.runtimeDir}))}catch{}return}if(n.type==="runtime:get"){let a=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:n.id,active:a.version,activeRuntimeDir:a.runtimeDir}))}catch{}return}if(r==="sim"&&n.type==="bridge:hello"&&s&&!s.url){let a=s.id;this.sims.delete(a),this.primarySimId===a&&(this.primarySimId=this.getOpenSim()?.id??null),s=null,r="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.writeConnectedRuntimeSnapshot(),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(r==="sim"){if(s&&(s.lastSeenAt=Date.now()),n.type==="bridge:register"&&s){let l=n,u=this.tryRestoreSimId(s,l.simId);s.url=l.url,s.title=l.title,s.userAgent=l.userAgent,this.writeConnectedRuntimeSnapshot(),typeof l.kind=="string"&&l.kind.trim()&&(s.kind=l.kind.trim()),l.meta&&typeof l.meta=="object"&&(s.meta=l.meta);let m=this.primarySimId!==s.id&&this.shouldPromoteSim(s);m&&(this.primarySimId=s.id),(u||m)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(n.type==="bridge:user-focus-state"&&s){let l=n;this.updateUserFocusLease(s,l);return}if(n.type==="bridge:user-interact"&&s){this.updateUserActivity(s);return}if(n.type==="bridge:write-shared-config"){if(!n.patch||typeof n.patch!="object"||Array.isArray(n.patch))return;let l=Object.fromEntries(Object.entries(n.patch));try{this.writeAndBroadcastSharedConfig(l)}catch(u){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${u instanceof Error?u.message:String(u)}
90
+ `);return}return}if(n.type==="bridge:open-path"){let l=typeof n.path=="string"?n.path:"",u=typeof n.line=="number"&&Number.isFinite(n.line)?n.line:void 0,m=typeof n.column=="number"&&Number.isFinite(n.column)?n.column:void 0;l&&this.openPathInEditor(l,u,m);return}if(n.type==="bridge:boot-clients"&&s){let l=[];for(let[m,p]of this.cliSimBySocket)p===s.id&&l.push(m);for(let m of l){this.cliSimBySocket.delete(m);try{m.close(1e3,"booted by sim")}catch{}}let u=!!s.cliLease;s.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`rnx booted ${l.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${s.id}]
91
+ `),this.recordSimAction(s.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let a=this.pendingCommands.get(n.id);if(a){this.pendingCommands.delete(n.id),n.error?a.reject(new Error(n.error)):a.resolve(n.result);return}let d=this.cliBySentId.get(n.id);if(d&&(this.cliBySentId.delete(n.id),d.ws.readyState===S.OPEN)){let l=this.getOtherCliIdentityCount(d.ws,d.simId),u=l>0?{...n,id:d.originalId,_otherCliCount:l}:{...n,id:d.originalId};d.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(n.type==="bridge:bye"){let m=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[p,h]of this.cliBySentId)h.ws===e&&this.cliBySentId.delete(p);m&&this.broadcastSimClientStates();return}if(n.type==="bridge:hello"){let m=typeof n.cliIdentityKey=="string"&&n.cliIdentityKey.trim()?n.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,m),typeof n.cliLabel=="string"&&n.cliLabel.trim()&&this.cliLabelBySocket.set(e,n.cliLabel.trim()),e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:{cliIdentityKey:m,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(n.type==="bridge:list-sims"){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:this.listSims()}));return}if(n.type==="bridge:claim"){let m=await this.waitForSim(n.simId),p=this.tryAcquireLease(e,m,{force:n.force===!0});if(!p.granted){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,error:`sim ${m.id} is locked by another cli`,_locked:p.lock}));return}this.setCliSimTarget(e,m.id),this.recordSimAction(m.id,p.bootedCount>0?`cli force-claimed sim (booted ${p.bootedCount})`:"cli claimed sim"),e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:{simId:m.id,lockedBy:p.lease.cliIdentityKey,lockExpiresAt:p.lease.expiresAt,bootedCount:p.bootedCount}}));return}let a=await this.waitForSim(n.simId);if(Ht(n)){let m=this.tryAcquireLease(e,a);if(!m.granted){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,error:`sim ${a.id} is locked by another cli \u2014 use \`rnx claim ${a.id} --force\` or \`rnx open --new\``,_locked:m.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,a.id),this.recordSimAction(a.id,this.describeForwardedCommand(n));let d=this.nextCommandId++;this.cliBySentId.set(d,{simId:a.id,ws:e,originalId:n.id});let{simId:l,...u}=n;if(a.ws.send(JSON.stringify({...u,id:d})),u.type==="close"){this.cliBySentId.delete(d),e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,result:{requested:!0,simId:a.id}}));let m=a.ws,p=setTimeout(()=>{this.closeSimSocketFromHost(m)},Dt);Ze(p)}}catch(a){e.readyState===S.OPEN&&e.send(JSON.stringify({id:n.id,error:a instanceof Error?a.message:String(a)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),r==="sim"&&s){this.rememberDisconnectedSim(s),this.primarySimId===s.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[c,n]of this.pendingCommands)n.simId===s.id&&(n.reject(new Error("sim disconnected")),this.pendingCommands.delete(c));for(let[c,n]of this.cliBySentId)n.simId===s.id&&(n.ws.readyState===S.OPEN&&n.ws.send(JSON.stringify({id:n.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[n,a]of this.cliBySentId)a.ws===e&&this.cliBySentId.delete(n);c&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
92
92
  `),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(),!ce(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)}
93
93
  `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},ze),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)}
94
- `)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},ze),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(){oe(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){ae(this.buildDevLockfileSnapshot())}writeConnectedRuntimeSnapshot(){if(this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}if(this.shouldWriteDevLockfile&&this.httpServer)try{this.writeDevLockfileSnapshot()}catch{}}refreshActiveRuntime(){this.activeRuntimeVersion=V(),this.activeRuntimeDirPath=me()??re()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=N({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(),s={"Access-Control-Allow-Origin":"*","Cache-Control":"no-store"};if(r==="OPTIONS"){i.writeHead(204,{...s,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range"}),i.end();return}if(r!=="GET"&&r!=="HEAD"){i.writeHead(405,s),i.end();return}if(!jt.test(e)){i.writeHead(400,{...s,"Content-Type":"text/plain; charset=utf-8"}),i.end("bad fixture name");return}let c=Q(),n=v.join(c,e),a;try{a=T.lstatSync(n)}catch{i.writeHead(404,{...s,"Content-Type":"text/plain; charset=utf-8"}),i.end("not found");return}if(!a.isFile()){i.writeHead(403,{...s,"Content-Type":"text/plain; charset=utf-8"}),i.end("forbidden");return}let d=qe[v.extname(n).toLowerCase()]||"application/octet-stream",l=a.size,u=/^bytes=(\d*)-(\d*)$/.exec(t.headers.range||"");if(u){let[,p,m]=u,f=p?Number(p):0,h=m?Math.min(Number(m),l-1):l-1;if(!Number.isFinite(f)||f>h||f>=l){i.writeHead(416,{...s,"Content-Range":`bytes */${l}`}),i.end();return}if(i.writeHead(206,{...s,"Content-Type":d,"Content-Range":`bytes ${f}-${h}/${l}`,"Accept-Ranges":"bytes","Content-Length":String(h-f+1)}),r==="HEAD"){i.end();return}T.createReadStream(n,{start:f,end:h}).pipe(i);return}if(i.writeHead(200,{...s,"Content-Type":d,"Accept-Ranges":"bytes","Content-Length":String(l)}),r==="HEAD"){i.end();return}T.createReadStream(n).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[Ft]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):Ut}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer||T.existsSync(v.join(X(),"runtime-update-disabled"))||process.env.SOOTSIM_HOME&&Z()&&!V())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
94
+ `)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},ze),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(){oe(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){ae(this.buildDevLockfileSnapshot())}writeConnectedRuntimeSnapshot(){if(this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}if(this.shouldWriteDevLockfile&&this.httpServer)try{this.writeDevLockfileSnapshot()}catch{}}refreshActiveRuntime(){this.activeRuntimeVersion=V(),this.activeRuntimeDirPath=me()??re()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=N({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(),s={"Access-Control-Allow-Origin":"*","Cache-Control":"no-store"};if(r==="OPTIONS"){i.writeHead(204,{...s,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range"}),i.end();return}if(r!=="GET"&&r!=="HEAD"){i.writeHead(405,s),i.end();return}if(!jt.test(e)){i.writeHead(400,{...s,"Content-Type":"text/plain; charset=utf-8"}),i.end("bad fixture name");return}let c=Q(),n=v.join(c,e),a;try{a=A.lstatSync(n)}catch{i.writeHead(404,{...s,"Content-Type":"text/plain; charset=utf-8"}),i.end("not found");return}if(!a.isFile()){i.writeHead(403,{...s,"Content-Type":"text/plain; charset=utf-8"}),i.end("forbidden");return}let d=qe[v.extname(n).toLowerCase()]||"application/octet-stream",l=a.size,u=/^bytes=(\d*)-(\d*)$/.exec(t.headers.range||"");if(u){let[,m,p]=u,h=m?Number(m):0,f=p?Math.min(Number(p),l-1):l-1;if(!Number.isFinite(h)||h>f||h>=l){i.writeHead(416,{...s,"Content-Range":`bytes */${l}`}),i.end();return}if(i.writeHead(206,{...s,"Content-Type":d,"Content-Range":`bytes ${h}-${f}/${l}`,"Accept-Ranges":"bytes","Content-Length":String(f-h+1)}),r==="HEAD"){i.end();return}A.createReadStream(n,{start:h,end:f}).pipe(i);return}if(i.writeHead(200,{...s,"Content-Type":d,"Accept-Ranges":"bytes","Content-Length":String(l)}),r==="HEAD"){i.end();return}A.createReadStream(n).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[Ft]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):Ut}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer||A.existsSync(v.join(X(),"runtime-update-disabled"))||process.env.SOOTSIM_HOME&&Z()&&!V())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
95
95
  `);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
96
96
  `);return}let i=this.activeRuntimeVersion,r=this.setActiveRuntime(t.latestVersion);process.stderr.write(`rnx runtime updated to ${r.version} (${e})
97
97
  `);try{te({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)}
98
98
  `)}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
99
- `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(ie(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===S.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{J({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",Mt),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),Ue(e.url)){je(e,t);return}if(Fe(e.url)&&We(e,t))return;if(Je(e.url)){Ke(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($())}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 g of e){let b=Buffer.isBuffer(g)?g:Buffer.from(g);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 m=JSON.parse(Buffer.concat(u).toString("utf8"));if(!m||typeof m!="object"||Array.isArray(m))throw new Error("shared config patch must be an object");let f=Object.fromEntries(Object.entries(m)),h=this.writeAndBroadcastSharedConfig(f);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(h))}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(Ye)){this.handleCameraFixture(r.pathname.slice(Ye.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"){let u=r.searchParams.get("url");if(!u){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let p;try{p=new URL(u)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let m=p.hostname;if(!(m==="localhost"||m==="127.0.0.1"||m==="::1"||m.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let h=await fetch(p.toString(),{redirect:"follow"}),g={},b=h.headers.get("content-type");if(b&&(g["Content-Type"]=b),g["Cache-Control"]="no-store",t.writeHead(h.status,g),!h.body){t.end();return}let w=h.body.getReader();for(;;){let{done:A,value:y}=await w.read();if(A)break;t.write(Buffer.from(y))}t.end()}catch(h){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${h instanceof Error?h.message:String(h)}`)}})();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 s=he(r.hostname),c=D(r.hostname);s||this.refreshActiveRuntime();let n=s?fe(r.hostname):this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end(s?`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 d=v.resolve(n,"."+a),l=n.endsWith(v.sep)?n:n+v.sep;if(!d.startsWith(l)&&d!==n){t.writeHead(403),t.end("forbidden");return}T.realpath(d,(u,p)=>{let m=u?d:p,f=m.endsWith(v.sep)?m:m+v.sep;if(!u){let h=(()=>{try{let g=T.realpathSync(n);return g.endsWith(v.sep)?g:g+v.sep}catch{return l}})();if(!f.startsWith(h)&&m+v.sep!==h){t.writeHead(403),t.end("forbidden");return}}T.stat(m,(h,g)=>{if(h||!g?.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 k=v.join(n,"index.html");T.readFile(k,(Qe,et)=>{if(Qe){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(Xe(et,this.effectivePort,this.contrastOrigin))});return}let b=v.extname(m).toLowerCase(),w=qe[b]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":w,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(b===".html"){T.readFile(m,(y,k)=>{if(y){try{t.end()}catch{}return}t.end(Xe(k,this.effectivePort,this.contrastOrigin))});return}let A=T.createReadStream(m);A.pipe(t),A.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,r]of this.cliSimBySocket){let s=this.cliLastCommandAt.get(i)??0;if(e-s<o.CLI_IDLE_TIMEOUT_MS)continue;let c=!1;for(let n of this.cliBySentId.values())if(n.ws===i){c=!0;break}if(!c){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[n,a]of this.cliBySentId)a.ws===i&&this.cliBySentId.delete(n);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 s of this.sims.values()){if(s.id===this.primarySimId||t.has(s.id)||this.getActiveLease(s))continue;let c=Math.max(s.lastActiveAt,s.connectedAt),n=e-c,a=this.isAutomationSim(s);if(a&&this.automationSimOwnerAlive(s))continue;let d=a?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(n>=d){this.closeSimSocketFromHost(s.ws);continue}a&&i.push({sim:s,idleMs:n})}let r=this.maxConcurrentAutomationSims;if(i.length>r){i.sort((s,c)=>c.idleMs-s.idleMs);for(let{sim:s,idleMs:c}of i.slice(0,i.length-r))c<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(s.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==S.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!==S.OPEN)return;try{e.close(ue,pe)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==S.CLOSED)try{e.terminate()}catch{}},Bt);Ze(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,s)=>{let c=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:d=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),r(d)},reject:d=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(d)}}),this.broadcastSimClientStates();let{simId:n,...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}`:""}`:"",s=`${e}${r}`,c=(a,d)=>new Promise(l=>{try{let u=_t(a,d,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,l(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),l(!0))})}catch{l(!1)}}),n=process.env.REACT_EDITOR||process.env.EDITOR;if(n){let a=n.split(" ").filter(Boolean);if(a.length&&await c(a[0],[...a.slice(1),"-g",s]))return}await c("cursor",["-g",s])||await c("code",["-g",s])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await ge(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{J({pid:process.pid,startedAt:this.startedAt})}catch{}if(this.shouldWriteDevLockfile)try{de({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=S.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===S.OPEN?"open":t===S.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})(),s=this.cliLabelBySocket.get(e),c=Date.now(),n=this.getActiveLease(t),a=n&&n.cliIdentityKey===r,d=0;if(n&&!a&&!i.force)return{granted:!1,lease:n,lock:{by:n.cliLabel||n.cliIdentityKey,expiresInMs:Math.max(0,n.expiresAt-c)},bootedCount:0};if(n&&!a&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==r){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}d++}}let l={kind:"cli",cliIdentityKey:r,cliLabel:s,expiresAt:c+o.CLI_LEASE_TTL_MS};return t.cliLease=l,{granted:!0,lease:l,bootedCount:d}}updateUserFocusLease(e,t){let i=t.focused===!0,r=typeof t.visible=="boolean"?t.visible:void 0,s=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===s&&e.documentFocused===c||(e.userFocused=i,e.userVisible=r,e.visibilityState=s,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,s=t&&t.kind==="user-active"?Math.max(t.expiresAt,r):r;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:s},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===S.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===S.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 n=this.getOpenSim(e);if(n)return n}else{let n=this.getDefaultSimCandidates();if(n.length>1)throw new Error(`multiple sims are connected: ${n.map(d=>d.id).join(", ")}; run \`rnx use <sim>\` or pass \`--sim <sim>\``);let a=n[0];if(a)return a}await new Promise(n=>setTimeout(n,r))}if(!e)throw new Error("no sim connected");let s=this.getDefaultSimCandidates().map(c=>c.id);throw new Error(`no sim connected with id ${e}`+(s.length>0?`; connected sims: ${s.join(", ")}`:""))}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===S.OPEN;if(!t||!i||!t.url)return!0;let r=e.origin?.includes(":5173"),s=t.origin?.includes(":5173");return!!r||!s}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===S.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}writeAndBroadcastSharedConfig(e){let t=ee(e),i=JSON.stringify({type:"bridge:shared-config-changed",config:t});for(let r of this.sims.values())if(r.ws.readyState===S.OPEN)try{r.ws.send(i)}catch{}return t}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==S.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 s=this.sims.get(e);if(!s)return;let c=Date.now();s.lastActiveAt=c,s.recentActions=[{label:r,at:c},...s.recentActions.filter(n=>n.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"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!==S.OPEN)continue;let s=this.cliIdentityKeyBySocket.get(i);t.add(s??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),r=new Set;for(let[s,c]of this.cliSimBySocket){if(c!==t||s.readyState!==S.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(s);n&&n===i||r.add(n??`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===S.OPEN)return!1;let s=this.getRestorableSimState(i),c=e.id;this.sims.delete(c),e.id=i,s&&(e.recentActions=s.recentActions.map(n=>({...n})),e.lastActiveAt=s.lastActiveAt,e.cliLease=s.cliLease?{...s.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===c&&(this.primarySimId=e.id);for(let[n,a]of this.cliSimBySocket)a===c&&this.cliSimBySocket.set(n,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,s]of this.cliSimBySocket)s===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 Di(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
99
+ `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(ie(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===S.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{J({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",Mt),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),Ue(e.url)){je(e,t);return}if(Fe(e.url)&&We(e,t))return;if(Je(e.url)){Ke(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($())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(u);return}if(i==="POST"){(async()=>{try{let u=[],m=0;for await(let g of e){let b=Buffer.isBuffer(g)?g:Buffer.from(g);if(m+=b.byteLength,m>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 p=JSON.parse(Buffer.concat(u).toString("utf8"));if(!p||typeof p!="object"||Array.isArray(p))throw new Error("shared config patch must be an object");let h=Object.fromEntries(Object.entries(p)),f=this.writeAndBroadcastSharedConfig(h);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(f))}catch(u){t.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}),t.end(`invalid shared config patch: ${u instanceof Error?u.message:String(u)}`)}})();return}t.writeHead(405,{Allow:"GET, HEAD, POST, OPTIONS"}),t.end("method not allowed");return}if(r.pathname.startsWith(Ye)){this.handleCameraFixture(r.pathname.slice(Ye.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"){let u=r.searchParams.get("url");if(!u){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let m;try{m=new URL(u)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}if(!C(m.hostname)){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let p=await fetch(m.toString(),{redirect:"follow"}),h={},f=p.headers.get("content-type");if(f&&(h["Content-Type"]=f),h["Cache-Control"]="no-store",t.writeHead(p.status,h),!p.body){t.end();return}let g=p.body.getReader();for(;;){let{done:b,value:w}=await g.read();if(b)break;t.write(Buffer.from(w))}t.end()}catch(p){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${p instanceof Error?p.message:String(p)}`)}})();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 s=he(r.hostname),c=D(r.hostname);s||this.refreshActiveRuntime();let n=s?fe(r.hostname):this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end(s?`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 d=v.resolve(n,"."+a),l=n.endsWith(v.sep)?n:n+v.sep;if(!d.startsWith(l)&&d!==n){t.writeHead(403),t.end("forbidden");return}A.realpath(d,(u,m)=>{let p=u?d:m,h=p.endsWith(v.sep)?p:p+v.sep;if(!u){let f=(()=>{try{let g=A.realpathSync(n);return g.endsWith(v.sep)?g:g+v.sep}catch{return l}})();if(!h.startsWith(f)&&p+v.sep!==f){t.writeHead(403),t.end("forbidden");return}}A.stat(p,(f,g)=>{if(f||!g?.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 I=v.join(n,"index.html");A.readFile(I,(Qe,et)=>{if(Qe){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(Xe(et,this.effectivePort,this.contrastOrigin))});return}let b=v.extname(p).toLowerCase(),w=qe[b]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":w,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(b===".html"){A.readFile(p,(y,I)=>{if(y){try{t.end()}catch{}return}t.end(Xe(I,this.effectivePort,this.contrastOrigin))});return}let T=A.createReadStream(p);T.pipe(t),T.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,r]of this.cliSimBySocket){let s=this.cliLastCommandAt.get(i)??0;if(e-s<o.CLI_IDLE_TIMEOUT_MS)continue;let c=!1;for(let n of this.cliBySentId.values())if(n.ws===i){c=!0;break}if(!c){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[n,a]of this.cliBySentId)a.ws===i&&this.cliBySentId.delete(n);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 s of this.sims.values()){if(s.id===this.primarySimId||t.has(s.id)||this.getActiveLease(s))continue;let c=Math.max(s.lastActiveAt,s.connectedAt),n=e-c,a=this.isAutomationSim(s);if(a&&this.automationSimOwnerAlive(s))continue;let d=a?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(n>=d){this.closeSimSocketFromHost(s.ws);continue}a&&i.push({sim:s,idleMs:n})}let r=this.maxConcurrentAutomationSims;if(i.length>r){i.sort((s,c)=>c.idleMs-s.idleMs);for(let{sim:s,idleMs:c}of i.slice(0,i.length-r))c<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(s.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==S.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!==S.OPEN)return;try{e.close(ue,pe)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==S.CLOSED)try{e.terminate()}catch{}},Bt);Ze(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,s)=>{let c=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:d=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),r(d)},reject:d=>{clearTimeout(c),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(d)}}),this.broadcastSimClientStates();let{simId:n,...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}`:""}`:"",s=`${e}${r}`,c=(a,d)=>new Promise(l=>{try{let u=_t(a,d,{detached:!0,stdio:"ignore"}),m=!1;u.on("error",()=>{m||(m=!0,l(!1))}),u.on("spawn",()=>{m||(m=!0,u.unref(),l(!0))})}catch{l(!1)}}),n=process.env.REACT_EDITOR||process.env.EDITOR;if(n){let a=n.split(" ").filter(Boolean);if(a.length&&await c(a[0],[...a.slice(1),"-g",s]))return}await c("cursor",["-g",s])||await c("code",["-g",s])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await ge(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{J({pid:process.pid,startedAt:this.startedAt})}catch{}if(this.shouldWriteDevLockfile)try{de({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=S.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===S.OPEN?"open":t===S.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})(),s=this.cliLabelBySocket.get(e),c=Date.now(),n=this.getActiveLease(t),a=n&&n.cliIdentityKey===r,d=0;if(n&&!a&&!i.force)return{granted:!1,lease:n,lock:{by:n.cliLabel||n.cliIdentityKey,expiresInMs:Math.max(0,n.expiresAt-c)},bootedCount:0};if(n&&!a&&i.force)for(let[u,m]of this.cliSimBySocket){if(m!==t.id)continue;let p=this.cliIdentityKeyBySocket.get(u);if(p&&p!==r){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}d++}}let l={kind:"cli",cliIdentityKey:r,cliLabel:s,expiresAt:c+o.CLI_LEASE_TTL_MS};return t.cliLease=l,{granted:!0,lease:l,bootedCount:d}}updateUserFocusLease(e,t){let i=t.focused===!0,r=typeof t.visible=="boolean"?t.visible:void 0,s=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===s&&e.documentFocused===c||(e.userFocused=i,e.userVisible=r,e.visibilityState=s,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,s=t&&t.kind==="user-active"?Math.max(t.expiresAt,r):r;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:s},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===S.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===S.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 n=this.getOpenSim(e);if(n)return n}else{let n=this.getDefaultSimCandidates();if(n.length>1)throw new Error(`multiple sims are connected: ${n.map(d=>d.id).join(", ")}; run \`rnx use <sim>\` or pass \`--sim <sim>\``);let a=n[0];if(a)return a}await new Promise(n=>setTimeout(n,r))}if(!e)throw new Error("no sim connected");let s=this.getDefaultSimCandidates().map(c=>c.id);throw new Error(`no sim connected with id ${e}`+(s.length>0?`; connected sims: ${s.join(", ")}`:""))}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===S.OPEN;if(!t||!i||!t.url)return!0;let r=e.origin?.includes(":5173"),s=t.origin?.includes(":5173");return!!r||!s}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===S.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}writeAndBroadcastSharedConfig(e){let t=ee(e),i=JSON.stringify({type:"bridge:shared-config-changed",config:t});for(let r of this.sims.values())if(r.ws.readyState===S.OPEN)try{r.ws.send(i)}catch{}return t}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==S.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 s=this.sims.get(e);if(!s)return;let c=Date.now();s.lastActiveAt=c,s.recentActions=[{label:r,at:c},...s.recentActions.filter(n=>n.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"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!==S.OPEN)continue;let s=this.cliIdentityKeyBySocket.get(i);t.add(s??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),r=new Set;for(let[s,c]of this.cliSimBySocket){if(c!==t||s.readyState!==S.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(s);n&&n===i||r.add(n??`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===S.OPEN)return!1;let s=this.getRestorableSimState(i),c=e.id;this.sims.delete(c),e.id=i,s&&(e.recentActions=s.recentActions.map(n=>({...n})),e.lastActiveAt=s.lastActiveAt,e.cliLease=s.cliLease?{...s.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===c&&(this.primarySimId=e.id);for(let[n,a]of this.cliSimBySocket)a===c&&this.cliSimBySocket.set(n,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,s]of this.cliSimBySocket)s===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 Bi(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
100
100
  rnx serve \u2014 run the rnx bridge in the foreground
101
101
 
102
102
  hosts the WS bridge that CLI commands talk to. once running, any rnx
@@ -113,6 +113,6 @@ options:
113
113
  examples:
114
114
  rnx serve
115
115
  rnx serve --port 7668 --quiet
116
- `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let r=o.includes("--quiet")||o.includes("-q"),s=ne();s&&se(s)&&(console.error(` an rnx bridge is already running (pid ${s.pid}, port ${s.bridgePort})`),console.error(" stop it with 'rnx daemon stop' first"),process.exit(1)),L();let c=await Se(),n=new j({port:i,writeLockfile:!0,contrastOrigin:c}),a=await n.startAsync({silent:r}),d=Date.now(),l=f=>{r||process.stdout.write(`${f}
117
- `)},u=new Set,p=setInterval(()=>{let f=n.listSims(),h=new Set(f.map(g=>g.id));for(let g of f)if(!u.has(g.id)){let b=g.title||g.url||g.origin||"(unknown)";l(` + ${g.id} ${b}`)}for(let g of u)h.has(g)||l(` - ${g}`);u.clear();for(let g of h)u.add(g)},500);l(`rnx bridge listening on ws://localhost:${a} (runtime http on same port)`),a!==i&&l(` (preferred port ${i} was taken \u2014 fell back to ${a})`),l(" ready for browser, electron, or headless playwright sims to connect"),l(" (ctrl-c to stop)");let m=async f=>{clearInterval(p),l(`
118
- ${f} received \u2014 shutting down after ${Math.round((Date.now()-d)/1e3)}s`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{n.removeLockfile()}catch{}}),await new Promise(()=>{})}export{Di as runServe};
116
+ `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let r=o.includes("--quiet")||o.includes("-q"),s=ne();s&&se(s)&&(console.error(` an rnx bridge is already running (pid ${s.pid}, port ${s.bridgePort})`),console.error(" stop it with 'rnx daemon stop' first"),process.exit(1)),L();let c=await Se(),n=new j({port:i,writeLockfile:!0,contrastOrigin:c}),a=await n.startAsync({silent:r}),d=Date.now(),l=h=>{r||process.stdout.write(`${h}
117
+ `)},u=new Set,m=setInterval(()=>{let h=n.listSims(),f=new Set(h.map(g=>g.id));for(let g of h)if(!u.has(g.id)){let b=g.title||g.url||g.origin||"(unknown)";l(` + ${g.id} ${b}`)}for(let g of u)f.has(g)||l(` - ${g}`);u.clear();for(let g of f)u.add(g)},500);l(`rnx bridge listening on ws://localhost:${a} (runtime http on same port)`),a!==i&&l(` (preferred port ${i} was taken \u2014 fell back to ${a})`),l(" ready for browser, electron, or headless playwright sims to connect"),l(" (ctrl-c to stop)");let p=async h=>{clearInterval(m),l(`
118
+ ${h} received \u2014 shutting down after ${Math.round((Date.now()-d)/1e3)}s`);try{await n.close()}catch{}process.exit(0)};process.on("SIGINT",()=>p("SIGINT")),process.on("SIGTERM",()=>p("SIGTERM")),process.on("SIGHUP",()=>p("SIGHUP")),process.on("exit",()=>{try{n.removeLockfile()}catch{}}),await new Promise(()=>{})}export{Bi as runServe};
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{b as N,c as I}from"./chunk-BA45ZZKU.js";import{d as D,g as A,i as E,j as M}from"./chunk-KYTBJ2QV.js";import"./chunk-7D56NCJ3.js";import"./chunk-EIIZZ2XK.js";import"./chunk-WIYBEKBM.js";import"./chunk-NJ2JVAGV.js";import"./chunk-BAXXUHKV.js";import"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import"./chunk-VENH5KLL.js";import{f}from"./chunk-FQ3OHHCY.js";import{c as O}from"./chunk-2PAG4FBP.js";import"./chunk-6CGQWXXT.js";import{a as d}from"./chunk-SMLCC5EP.js";import{a as $}from"./chunk-ZPCQFQEN.js";import{C as w,D as k,J as P,l as x}from"./chunk-WNZOJDBL.js";import{a as j}from"./chunk-IQWQ6KI7.js";import{a as s}from"./chunk-XGUCAKZM.js";import"./chunk-HY7XOD5E.js";import"./chunk-DC4MQAR3.js";import ee from"node:fs";import q from"node:os";import F from"node:path";import{spawn as z}from"node:child_process";import u from"node:fs";import a from"node:path";function C(e){let n=a.resolve(e);for(;;){if(u.existsSync(a.join(n,"package.json")))return n;let r=a.dirname(n);if(r===n)return null;n=r}}function m(e){let n=a.resolve(e);for(;;){if(u.existsSync(a.join(n,"bun.lock"))||u.existsSync(a.join(n,"bun.lockb")))return"bun";if(u.existsSync(a.join(n,"pnpm-lock.yaml")))return"pnpm";if(u.existsSync(a.join(n,"package-lock.json")))return"npm";let r=a.dirname(n);if(r===n)return"npm";n=r}}function V(e){let n=a.resolve(e.appDir),r=G(a.join(n,"package.json")),o=`${s.commandName} open`,t=r.scripts?.[s.commandName];if(t&&t!==o)throw new Error(`package.json already defines scripts.${s.commandName} as ${JSON.stringify(t)}; resolve that conflict before setup`);let i=m(n),c=[];return r.devDependencies?.[s.packageName]!==e.cliVersion&&c.push(H(i,e.cliVersion)),t!==o&&c.push(Q(i)),{appDir:n,packageManager:i,operations:c}}async function J(e,n){for(let r of e.operations)n.dryRun||await K(r,e.appDir,n.json)}function y(e){return e.operations.map(n=>`${n.command} ${n.args.map(Z).join(" ")}`)}function G(e){let n;try{n=JSON.parse(u.readFileSync(e,"utf8"))}catch(t){let i=t instanceof Error?t.message:String(t);throw new Error(`could not read ${e}: ${i}`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must contain a JSON object`);let r=T(Reflect.get(n,"scripts")),o=T(Reflect.get(n,"devDependencies"));return{...r?{scripts:r}:{},...o?{devDependencies:o}:{}}}function T(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function H(e,n){let r=`${s.packageName}@${n}`;switch(e){case"bun":return{command:"bun",args:["add","--dev","--exact",r],description:`install ${r} as an exact dev dependency`};case"pnpm":return{command:"pnpm",args:["add","--save-dev","--save-exact",r],description:`install ${r} as an exact dev dependency`};case"npm":return{command:"npm",args:["install","--save-dev","--save-exact",r],description:`install ${r} as an exact dev dependency`}}}function Z(e){return/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:JSON.stringify(e)}function K(e,n,r){return new Promise((o,t)=>{let i=z(e.command,e.args,{cwd:n,stdio:r?["ignore",2,"inherit"]:"inherit"});i.once("error",t),i.once("exit",c=>{c===0?o():t(new Error(`${e.command} exited with code ${c??"unknown"}`))})})}function Q(e){return{command:e,args:e==="bun"?["pm","pkg","set",`scripts.${s.commandName}=${s.commandName} open`]:["pkg","set",`scripts.${s.commandName}=${s.commandName} open`],description:`add the \`${s.commandName}\` package script`}}async function Te(e){if(e.includes("--help")||e.includes("-h")){me();return}let n=ne(e);try{let r=C(n.appDir),o=N(),t=w(),i=await te(n,o),c=await oe(n,r),g=await ie(n,t),B=!1,U=await f.fetchManifest(),l=f.resolveVersion(U,{channel:"stable"}).version,S=j();if(S==="0.0.0")throw new Error("could not resolve the installed rnx CLI version");let p=null;c&&r&&(p=V({appDir:r,cliVersion:S})),ce(n),pe(n,o,i,l),ue(n,r,p),le(n,g);let v=!1;if(!n.dryRun){let b=P();v=(await f.install({version:l,channel:"stable",setActive:!0,protectVersions:b?[b]:[]})).installed}p&&await J(p,{dryRun:n.dryRun,json:n.json});let h=o.installed;i&&!o.installed&&!n.dryRun&&(await I({port:7668,force:!1}),h=!0),n.dryRun||k({productAnalytics:g,crashReports:B});let W=r?se(r):null;de(n,W);let R={runtimeVersion:l,serviceInstalled:h,repositoryPrepared:p!==null},Y=ae(l);return n.json?console.log(JSON.stringify({...R,runtimeInstalled:n.dryRun?!1:v,dryRun:n.dryRun,cache:Y,repositoryOperations:p?y(p):[]},null,2)):fe(p),R}catch(r){throw O(r),r}}function ne(e){let n=e.indexOf("--app"),r=n>=0?e[n+1]:void 0;if(n>=0&&(!r||r.startsWith("-")))throw new Error("--app requires a directory");let o=_(e,"--service","--no-service"),t=_(e,"--repo","--no-repo");return{appDir:F.resolve(r??process.cwd()),ci:e.includes("--ci")||$(),dryRun:e.includes("--dry-run"),json:e.includes("--json"),yes:e.includes("--yes")||e.includes("-y"),service:o,repository:t,productAnalytics:re(e,"--analytics")}}function _(e,n,r){if(e.includes(n)&&e.includes(r))throw new Error(`${n} and ${r} cannot be used together`);if(e.includes(n))return!0;if(e.includes(r))return!1}function re(e,n){let r=e.find(i=>i.startsWith(`${n}=`)),o=e.indexOf(n),t=r?.slice(n.length+1)??(o>=0?e[o+1]:void 0);if(t!==void 0){if(t==="on"||t==="yes"||t==="true")return!0;if(t==="off"||t==="no"||t==="false")return!1;throw new Error(`${n} must be on or off`)}}async function te(e,n){if(e.ci){if(e.service===!0)throw new Error("--ci cannot install a machine service");return!1}return n.supported?n.installed&&e.service===void 0?!0:e.service!==void 0?e.service:e.yes?!0:(L(e,"--service or --no-service"),d("Install the background service and shared managed runtime?",!0)):!1}async function oe(e,n){if(!n){if(e.repository===!0)throw new Error("--repo requires a package.json");return!1}return e.repository!==void 0?e.repository:e.yes?!0:(L(e,"--repo or --no-repo"),d(`Prepare ${n} for reproducible rnx runs?`,!0))}async function ie(e,n){return e.productAnalytics!==void 0?e.productAnalytics:n.configured?n.productAnalytics:e.yes||e.ci||!process.stdin.isTTY?!1:d("Share anonymous package incompatibilities and error classes to improve rnx?",!1)}function L(e,n){if(!(process.stdin.isTTY&&!e.ci))throw new Error(`non-interactive setup requires ${n}, or --yes to accept defaults`)}function se(e){let n=JSON.parse(ee.readFileSync(F.join(e,"package.json"),"utf8"));if(!n||typeof n!="object")throw new Error("package.json must contain an object");return D(n)}function ae(e){let n=q.platform(),r=q.arch();return{path:x(e),key:`sootsim-runtime-${n}-${r}-${e}`,inputs:{platform:n,arch:r,runtimeVersion:e}}}function ce(e){e.json||console.log(`
4
+ import{b as N,c as I}from"./chunk-2C23SW2O.js";import{d as D,g as A,i as E,j as M}from"./chunk-NSAUGFN3.js";import"./chunk-TAG7EJME.js";import"./chunk-ZYN24EAC.js";import"./chunk-EOXI7D6H.js";import"./chunk-I5KU5FGG.js";import"./chunk-ILF4REF4.js";import"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import"./chunk-F5E3GJAF.js";import{f}from"./chunk-BNMD7ZGN.js";import{c as O}from"./chunk-52F4KQTG.js";import"./chunk-3H3VFCQA.js";import{a as d}from"./chunk-32GBZENF.js";import{a as $}from"./chunk-UWE33SLE.js";import{C as w,D as k,J as P,l as x}from"./chunk-JLWC7UJR.js";import{a as j}from"./chunk-RGOUICK3.js";import{a as s}from"./chunk-4WBCIUI5.js";import"./chunk-VEXSD6UX.js";import"./chunk-5UDXV7UU.js";import ee from"node:fs";import q from"node:os";import F from"node:path";import{spawn as z}from"node:child_process";import u from"node:fs";import a from"node:path";function C(e){let n=a.resolve(e);for(;;){if(u.existsSync(a.join(n,"package.json")))return n;let r=a.dirname(n);if(r===n)return null;n=r}}function m(e){let n=a.resolve(e);for(;;){if(u.existsSync(a.join(n,"bun.lock"))||u.existsSync(a.join(n,"bun.lockb")))return"bun";if(u.existsSync(a.join(n,"pnpm-lock.yaml")))return"pnpm";if(u.existsSync(a.join(n,"package-lock.json")))return"npm";let r=a.dirname(n);if(r===n)return"npm";n=r}}function V(e){let n=a.resolve(e.appDir),r=G(a.join(n,"package.json")),o=`${s.commandName} open`,t=r.scripts?.[s.commandName];if(t&&t!==o)throw new Error(`package.json already defines scripts.${s.commandName} as ${JSON.stringify(t)}; resolve that conflict before setup`);let i=m(n),c=[];return r.devDependencies?.[s.packageName]!==e.cliVersion&&c.push(H(i,e.cliVersion)),t!==o&&c.push(Q(i)),{appDir:n,packageManager:i,operations:c}}async function J(e,n){for(let r of e.operations)n.dryRun||await K(r,e.appDir,n.json)}function y(e){return e.operations.map(n=>`${n.command} ${n.args.map(Z).join(" ")}`)}function G(e){let n;try{n=JSON.parse(u.readFileSync(e,"utf8"))}catch(t){let i=t instanceof Error?t.message:String(t);throw new Error(`could not read ${e}: ${i}`)}if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`${e} must contain a JSON object`);let r=T(Reflect.get(n,"scripts")),o=T(Reflect.get(n,"devDependencies"));return{...r?{scripts:r}:{},...o?{devDependencies:o}:{}}}function T(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=Object.entries(e).filter(r=>typeof r[1]=="string");return Object.fromEntries(n)}function H(e,n){let r=`${s.packageName}@${n}`;switch(e){case"bun":return{command:"bun",args:["add","--dev","--exact",r],description:`install ${r} as an exact dev dependency`};case"pnpm":return{command:"pnpm",args:["add","--save-dev","--save-exact",r],description:`install ${r} as an exact dev dependency`};case"npm":return{command:"npm",args:["install","--save-dev","--save-exact",r],description:`install ${r} as an exact dev dependency`}}}function Z(e){return/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:JSON.stringify(e)}function K(e,n,r){return new Promise((o,t)=>{let i=z(e.command,e.args,{cwd:n,stdio:r?["ignore",2,"inherit"]:"inherit"});i.once("error",t),i.once("exit",c=>{c===0?o():t(new Error(`${e.command} exited with code ${c??"unknown"}`))})})}function Q(e){return{command:e,args:e==="bun"?["pm","pkg","set",`scripts.${s.commandName}=${s.commandName} open`]:["pkg","set",`scripts.${s.commandName}=${s.commandName} open`],description:`add the \`${s.commandName}\` package script`}}async function Te(e){if(e.includes("--help")||e.includes("-h")){me();return}let n=ne(e);try{let r=C(n.appDir),o=N(),t=w(),i=await te(n,o),c=await oe(n,r),g=await ie(n,t),B=!1,U=await f.fetchManifest(),l=f.resolveVersion(U,{channel:"stable"}).version,S=j();if(S==="0.0.0")throw new Error("could not resolve the installed rnx CLI version");let p=null;c&&r&&(p=V({appDir:r,cliVersion:S})),ce(n),pe(n,o,i,l),ue(n,r,p),le(n,g);let v=!1;if(!n.dryRun){let b=P();v=(await f.install({version:l,channel:"stable",setActive:!0,protectVersions:b?[b]:[]})).installed}p&&await J(p,{dryRun:n.dryRun,json:n.json});let h=o.installed;i&&!o.installed&&!n.dryRun&&(await I({port:7668,force:!1}),h=!0),n.dryRun||k({productAnalytics:g,crashReports:B});let W=r?se(r):null;de(n,W);let R={runtimeVersion:l,serviceInstalled:h,repositoryPrepared:p!==null},Y=ae(l);return n.json?console.log(JSON.stringify({...R,runtimeInstalled:n.dryRun?!1:v,dryRun:n.dryRun,cache:Y,repositoryOperations:p?y(p):[]},null,2)):fe(p),R}catch(r){throw O(r),r}}function ne(e){let n=e.indexOf("--app"),r=n>=0?e[n+1]:void 0;if(n>=0&&(!r||r.startsWith("-")))throw new Error("--app requires a directory");let o=_(e,"--service","--no-service"),t=_(e,"--repo","--no-repo");return{appDir:F.resolve(r??process.cwd()),ci:e.includes("--ci")||$(),dryRun:e.includes("--dry-run"),json:e.includes("--json"),yes:e.includes("--yes")||e.includes("-y"),service:o,repository:t,productAnalytics:re(e,"--analytics")}}function _(e,n,r){if(e.includes(n)&&e.includes(r))throw new Error(`${n} and ${r} cannot be used together`);if(e.includes(n))return!0;if(e.includes(r))return!1}function re(e,n){let r=e.find(i=>i.startsWith(`${n}=`)),o=e.indexOf(n),t=r?.slice(n.length+1)??(o>=0?e[o+1]:void 0);if(t!==void 0){if(t==="on"||t==="yes"||t==="true")return!0;if(t==="off"||t==="no"||t==="false")return!1;throw new Error(`${n} must be on or off`)}}async function te(e,n){if(e.ci){if(e.service===!0)throw new Error("--ci cannot install a machine service");return!1}return n.supported?n.installed&&e.service===void 0?!0:e.service!==void 0?e.service:e.yes?!0:(L(e,"--service or --no-service"),d("Install the background service and shared managed runtime?",!0)):!1}async function oe(e,n){if(!n){if(e.repository===!0)throw new Error("--repo requires a package.json");return!1}return e.repository!==void 0?e.repository:e.yes?!0:(L(e,"--repo or --no-repo"),d(`Prepare ${n} for reproducible rnx runs?`,!0))}async function ie(e,n){return e.productAnalytics!==void 0?e.productAnalytics:n.configured?n.productAnalytics:e.yes||e.ci||!process.stdin.isTTY?!1:d("Share anonymous package incompatibilities and error classes to improve rnx?",!1)}function L(e,n){if(!(process.stdin.isTTY&&!e.ci))throw new Error(`non-interactive setup requires ${n}, or --yes to accept defaults`)}function se(e){let n=JSON.parse(ee.readFileSync(F.join(e,"package.json"),"utf8"));if(!n||typeof n!="object")throw new Error("package.json must contain an object");return D(n)}function ae(e){let n=q.platform(),r=q.arch();return{path:x(e),key:`sootsim-runtime-${n}-${r}-${e}`,inputs:{platform:n,arch:r,runtimeVersion:e}}}function ce(e){e.json||console.log(`
5
5
  rnx setup`)}function pe(e,n,r,o){e.json||(console.log(`
6
6
  1. machine`),console.log(` stable runtime: ${o}`),console.log(` background service: ${n.supported?r?"install":"skip":"unsupported on this platform"}`))}function ue(e,n,r){if(!e.json){if(console.log(`
7
7
  2. repository`),!n){console.log(" no package.json found; repository preparation skipped");return}if(!r){console.log(` skipped for ${n}`);return}console.log(` package manager: ${m(n)}`);for(let o of y(r))console.log(` ${e.dryRun?"would run":"run"}: ${o}`)}}function le(e,n){e.json||(console.log(`
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as h}from"./chunk-XGUCAKZM.js";import"./chunk-DC4MQAR3.js";import*as l from"fs";import*as L from"os";import*as a from"path";import{fileURLToPath as x}from"url";function D(){try{let e=x(import.meta.resolve(`${h.packageName}/package.json`));return a.join(a.dirname(e),"skills")}catch{let e=a.dirname(x(import.meta.url));return a.resolve(e,"../../skills")}}var d=D(),j=new Set(["all","codex","claude"]);function S(){console.log(`rnx skill
4
+ import{a as h}from"./chunk-4WBCIUI5.js";import"./chunk-5UDXV7UU.js";import*as l from"fs";import*as L from"os";import*as a from"path";import{fileURLToPath as x}from"url";function D(){try{let e=x(import.meta.resolve(`${h.packageName}/package.json`));return a.join(a.dirname(e),"skills")}catch{let e=a.dirname(x(import.meta.url));return a.resolve(e,"../../skills")}}var d=D(),j=new Set(["all","codex","claude"]);function S(){console.log(`rnx skill
5
5
 
6
6
  install and inspect bundled rnx agent skills.
7
7
 
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{m as a}from"./chunk-7C6XE6AT.js";import"./chunk-O7WPHIYQ.js";import{q as c,s as l}from"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import"./chunk-WNZOJDBL.js";import"./chunk-DC4MQAR3.js";function g(t){return!!t&&typeof t=="object"&&typeof Reflect.get(t,"capturedAt")=="number"}function p(){console.log(`
4
+ import{m as a}from"./chunk-EJ5WTR3A.js";import"./chunk-CHLYDXIP.js";import{q as c,s as l}from"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import"./chunk-JLWC7UJR.js";import"./chunk-5UDXV7UU.js";function g(t){return!!t&&typeof t=="object"&&typeof Reflect.get(t,"capturedAt")=="number"}function p(){console.log(`
5
5
  rnx state - capture the current app state in one call
6
6
 
7
7
  usage:
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as f}from"./chunk-QK2U5IW3.js";import"./chunk-7C6XE6AT.js";import"./chunk-O7WPHIYQ.js";import"./chunk-DTNRKFSE.js";import{b as t,c as l,d as s,e as c,f as a}from"./chunk-SNBSRIKO.js";import"./chunk-24Q4J4U6.js";import"./chunk-WNZOJDBL.js";import"./chunk-DC4MQAR3.js";function p(){console.log(`
4
+ import{a as f}from"./chunk-VP6GLOZV.js";import"./chunk-EJ5WTR3A.js";import"./chunk-CHLYDXIP.js";import"./chunk-HNYPDSJ6.js";import{b as t,c as l,d as s,e as c,f as a}from"./chunk-JXA2VQXZ.js";import"./chunk-PPURCICX.js";import"./chunk-JLWC7UJR.js";import"./chunk-5UDXV7UU.js";function p(){console.log(`
5
5
  rnx storage profile \u2014 manage isolated storage profiles
6
6
 
7
7
  usage:
@@ -0,0 +1,4 @@
1
+ /*! rnx v0.1.348 | (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-2W2WZV6U.js";import"./chunk-ILF4REF4.js";import"./chunk-5UDXV7UU.js";export{a as settingsStore};
@@ -0,0 +1,4 @@
1
+ /*! rnx v0.1.348 | (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-52F4KQTG.js";import"./chunk-3H3VFCQA.js";import"./chunk-32GBZENF.js";import"./chunk-UWE33SLE.js";import"./chunk-JLWC7UJR.js";import"./chunk-5UDXV7UU.js";export{a as buildCliDiagnosticEvent,d as flushCliTelemetry,b as trackCliDiagnostic,c as trackCliError};
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{q as m,s as d,v as i}from"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import"./chunk-WNZOJDBL.js";import"./chunk-DC4MQAR3.js";import{writeFileSync as g}from"fs";function u(){console.log(`
4
+ import{q as m,s as d,v as i}from"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import"./chunk-JLWC7UJR.js";import"./chunk-5UDXV7UU.js";import{writeFileSync as g}from"fs";function u(){console.log(`
5
5
  rnx timeline \u2014 control the semantic event timeline
6
6
 
7
7
  usage:
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as h,b as v,c as $}from"./chunk-PCU2CQCI.js";import{b as p}from"./chunk-JQTBZERT.js";import"./chunk-3SPBSEVL.js";import"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import{b as g}from"./chunk-FQ3OHHCY.js";import{J as a,g as m,h as u,l as d}from"./chunk-WNZOJDBL.js";import{a as f}from"./chunk-IQWQ6KI7.js";import"./chunk-XGUCAKZM.js";import"./chunk-DC4MQAR3.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
4
+ import{a as h,b as v,c as $}from"./chunk-VARLW54M.js";import{b as p}from"./chunk-MYOLOVHV.js";import"./chunk-JTGES3IH.js";import"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import{b as g}from"./chunk-BNMD7ZGN.js";import{J as a,g as m,h as u,l as d}from"./chunk-JLWC7UJR.js";import{a as f}from"./chunk-RGOUICK3.js";import"./chunk-4WBCIUI5.js";import"./chunk-5UDXV7UU.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
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
6
  cli:`),await j(),i&&console.log(`
7
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};
@@ -0,0 +1,4 @@
1
+ /*! rnx v0.1.348 | (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-BIEQJ66T.js";import"./chunk-BC6P65EO.js";import"./chunk-UONC7KUI.js";import"./chunk-O7ZWWZA6.js";import"./chunk-ZP6XJFIZ.js";import"./chunk-KF6QGGYJ.js";import"./chunk-JTGES3IH.js";import"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import"./chunk-JLWC7UJR.js";import"./chunk-4WBCIUI5.js";import"./chunk-5UDXV7UU.js";export{a as resolveDefaultUploadOrigin,b as resolvePublicPreviewOrigin,c as runUpload};
@@ -1,6 +1,6 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{a as m}from"./chunk-EIIZZ2XK.js";import{b as a}from"./chunk-JQTBZERT.js";import"./chunk-3SPBSEVL.js";import"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import{d as s,f as t}from"./chunk-FQ3OHHCY.js";import{l as r}from"./chunk-WNZOJDBL.js";import{a as l}from"./chunk-IQWQ6KI7.js";import"./chunk-XGUCAKZM.js";import"./chunk-DC4MQAR3.js";import g from"node:fs";import d from"node:path";async function R($){let{IS_BETA:c,BETA_LABEL:u}=await import("./beta-JXYFAOHO.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(`
4
+ import{a as m}from"./chunk-ZYN24EAC.js";import{b as a}from"./chunk-MYOLOVHV.js";import"./chunk-JTGES3IH.js";import"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import{d as s,f as t}from"./chunk-BNMD7ZGN.js";import{l as r}from"./chunk-JLWC7UJR.js";import{a as l}from"./chunk-RGOUICK3.js";import"./chunk-4WBCIUI5.js";import"./chunk-5UDXV7UU.js";import g from"node:fs";import d from"node:path";async function R($){let{IS_BETA:c,BETA_LABEL:u}=await import("./beta-E5MXYTSU.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
5
  \u2191 default runtime v${i.latest} available; run \`rnx upgrade\``),console.log(`
6
6
  what's new: ${s}`)}export{R as runVersion};
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-KYTBJ2QV.js";import"./chunk-DC4MQAR3.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};
4
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-NSAUGFN3.js";import"./chunk-5UDXV7UU.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 +1,5 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{r as f}from"./chunk-JP4FCK5J.js";import"./chunk-4KOWLH77.js";import"./chunk-QJYUHYQS.js";import"./chunk-LRRQI4TP.js";import{k as u}from"./chunk-2E5KDIGN.js";import"./chunk-NJ2JVAGV.js";import"./chunk-2W4ME6YI.js";import"./chunk-BAXXUHKV.js";import"./chunk-SYQZTZTR.js";import"./chunk-JQTBZERT.js";import"./chunk-3SPBSEVL.js";import"./chunk-7C6XE6AT.js";import"./chunk-O7WPHIYQ.js";import{r as m}from"./chunk-DTNRKFSE.js";import"./chunk-JG2TIZ7E.js";import"./chunk-U6CJ3EHB.js";import"./chunk-SNBSRIKO.js";import"./chunk-24Q4J4U6.js";import"./chunk-FQ3OHHCY.js";import"./chunk-JKRVWCTC.js";import{a as d}from"./chunk-6CGQWXXT.js";import{b as p}from"./chunk-SMLCC5EP.js";import"./chunk-ZPCQFQEN.js";import{C as l}from"./chunk-WNZOJDBL.js";import"./chunk-XGUCAKZM.js";import"./chunk-DC4MQAR3.js";function a(e){return`${e.projectName?.trim()||e.framework} on :${e.port}`}async function R(){let e=l();console.log(`
5
- welcome to rnx`),console.log(` diagnostics: ${e.configured&&e.productAnalytics?"bounded opt-in on":"off until you opt in"}`),console.log(" looking for a running React Native app\u2026");let o=[...await u({excludePorts:[7668]})].sort((r,n)=>r.port-n.port);if(o.length===0)return console.error(" no running React Native development server found."),console.error(" start your app normally, then run `npx rnxsim` again."),1;if(o.length>1&&!d()){console.error(" multiple React Native development servers found.");for(let r of o)console.error(` ${a(r)}: rnx open ${r.port}`);return console.error(" choose one explicitly; automated runs do not guess."),1}let g=o.length===1?0:await p("which running app should rnx open?",o.map(a)),t=o[g];if(!t)throw new Error("rnx app selection returned an invalid choice");console.log(` found ${a(t)} \xB7 opening simulator\u2026`);let i=await f([t.bundleUrl]);if(i!==void 0){let{runInspect:r}=await import("./inspect-36A2IEJL.js");await r(["wait","ready","--max-ms","120000"],{port:i});let n=m(i,{commandTimeoutMs:45e3});try{let s=await n.send({type:"screenshot"}),c="data:image/png;base64,";if(typeof s!="string"||!s.startsWith(c)||s.length<=c.length)throw new Error("the simulator connected but did not produce a visible app frame")}finally{n.close()}}return 0}export{R as runWelcome};
4
+ import{r as f}from"./chunk-PCVP5LMW.js";import"./chunk-5AYTVU6P.js";import"./chunk-SZRLMZHI.js";import"./chunk-O7ZWWZA6.js";import{k as u}from"./chunk-ZP6XJFIZ.js";import"./chunk-I5KU5FGG.js";import"./chunk-2W2WZV6U.js";import"./chunk-ILF4REF4.js";import"./chunk-KF6QGGYJ.js";import"./chunk-MYOLOVHV.js";import"./chunk-JTGES3IH.js";import"./chunk-EJ5WTR3A.js";import"./chunk-CHLYDXIP.js";import{r as m}from"./chunk-HNYPDSJ6.js";import"./chunk-OKF5M2Z5.js";import"./chunk-XFPFJPC3.js";import"./chunk-JXA2VQXZ.js";import"./chunk-PPURCICX.js";import"./chunk-BNMD7ZGN.js";import"./chunk-XNDTB3MY.js";import{a as d}from"./chunk-3H3VFCQA.js";import{b as p}from"./chunk-32GBZENF.js";import"./chunk-UWE33SLE.js";import{C as l}from"./chunk-JLWC7UJR.js";import"./chunk-4WBCIUI5.js";import"./chunk-5UDXV7UU.js";function a(e){return`${e.projectName?.trim()||e.framework} on :${e.port}`}async function R(){let e=l();console.log(`
5
+ welcome to rnx`),console.log(` diagnostics: ${e.configured&&e.productAnalytics?"bounded opt-in on":"off until you opt in"}`),console.log(" looking for a running React Native app\u2026");let o=[...await u({excludePorts:[7668]})].sort((r,n)=>r.port-n.port);if(o.length===0)return console.error(" no running React Native development server found."),console.error(" start your app normally, then run `npx rnxsim` again."),1;if(o.length>1&&!d()){console.error(" multiple React Native development servers found.");for(let r of o)console.error(` ${a(r)}: rnx open ${r.port}`);return console.error(" choose one explicitly; automated runs do not guess."),1}let g=o.length===1?0:await p("which running app should rnx open?",o.map(a)),t=o[g];if(!t)throw new Error("rnx app selection returned an invalid choice");console.log(` found ${a(t)} \xB7 opening simulator\u2026`);let i=await f([t.bundleUrl]);if(i!==void 0){let{runInspect:r}=await import("./inspect-HELBBLXA.js");await r(["wait","ready","--max-ms","120000"],{port:i});let n=m(i,{commandTimeoutMs:45e3});try{let s=await n.send({type:"screenshot"}),c="data:image/png;base64,";if(typeof s!="string"||!s.startsWith(c)||s.length<=c.length)throw new Error("the simulator connected but did not produce a visible app frame")}finally{n.close()}}return 0}export{R as runWelcome};
@@ -1,7 +1,7 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import { createRequire as __sootsimCreateRequire } from 'node:module'
3
3
  var require = __sootsimCreateRequire(import.meta.url)
4
- import{D as F,E as T,G as y,R as A,S as b,T as S}from"./chunk-O7WPHIYQ.js";import{e as k,q as x,s as N}from"./chunk-DTNRKFSE.js";import"./chunk-24Q4J4U6.js";import"./chunk-WNZOJDBL.js";import"./chunk-DC4MQAR3.js";function O(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 B(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 D(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 _(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 J(n,t){let e=x(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(`
4
+ import{D as F,E as T,G as y,R as A,S as b,T as S}from"./chunk-CHLYDXIP.js";import{e as k,q as x,s as N}from"./chunk-HNYPDSJ6.js";import"./chunk-PPURCICX.js";import"./chunk-JLWC7UJR.js";import"./chunk-5UDXV7UU.js";function O(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 B(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 D(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 _(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 J(n,t){let e=x(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
5
  rnx what-happened \u2014 show recent events from the semantic timeline
6
6
 
7
7
  usage:
@@ -1,4 +1,4 @@
1
- /*! rnx v0.1.347 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! rnx v0.1.348 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  let __sootsim_import_meta_url = ''; try { __sootsim_import_meta_url = require('url').pathToFileURL(__filename).href; } catch {}
3
3
  "use strict";
4
4
  var __create = Object.create;