sootsim 0.1.145 → 0.1.147

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 (154) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-YX5V2KV7.js → agent-COSQ2VSX.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-3X53DI4P.js → agent-wrapper-J6LA36AT.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-5I6J7HMM.js → app-fonts-H4CXDIF6.js} +2 -2
  5. package/dist-cli/chunks/{assert-BDSCYJ3N.js → assert-THSUXYWU.js} +2 -2
  6. package/dist-cli/chunks/auto-bootstrap-SPALBOGS.js +2 -0
  7. package/dist-cli/chunks/beta-U3V7RSRI.js +2 -0
  8. package/dist-cli/chunks/{camera-HXVXO2XW.js → camera-4NINTJSC.js} +2 -2
  9. package/dist-cli/chunks/{chunk-36RF3WRB.js → chunk-4CLJIXM3.js} +1 -1
  10. package/dist-cli/chunks/{chunk-26P6DJRO.js → chunk-54R6LIOF.js} +2 -2
  11. package/dist-cli/chunks/{chunk-2GAVMQGW.js → chunk-5CTOWZY4.js} +2 -2
  12. package/dist-cli/chunks/{chunk-KSNQFEBZ.js → chunk-5MX2B2EO.js} +2 -2
  13. package/dist-cli/chunks/{chunk-QZAJOB4N.js → chunk-5PKIU2SG.js} +1 -1
  14. package/dist-cli/chunks/{chunk-CUPKQONE.js → chunk-B46RT5KY.js} +1 -1
  15. package/dist-cli/chunks/{chunk-DNM2AOHD.js → chunk-BDLFGAKU.js} +1 -1
  16. package/dist-cli/chunks/{chunk-HVRSV4QO.js → chunk-BOU5OTEA.js} +1 -1
  17. package/dist-cli/chunks/{chunk-NX6V5VAV.js → chunk-DO2Z5CNM.js} +3 -3
  18. package/dist-cli/chunks/{chunk-4QJCDB6B.js → chunk-DXL23RFP.js} +2 -2
  19. package/dist-cli/chunks/chunk-EJIK4ANI.js +2 -0
  20. package/dist-cli/chunks/chunk-EWAA5DKR.js +1 -0
  21. package/dist-cli/chunks/{chunk-TRA4IJCY.js → chunk-FOLNNKZG.js} +2 -2
  22. package/dist-cli/chunks/{chunk-YWUBSH2K.js → chunk-FY4TSSMQ.js} +1 -1
  23. package/dist-cli/chunks/{chunk-F6UIBH3K.js → chunk-HENMFGLU.js} +1 -1
  24. package/dist-cli/chunks/{chunk-YENFSYAG.js → chunk-HN2Q2ZWT.js} +1 -1
  25. package/dist-cli/chunks/{chunk-7GBAY2BX.js → chunk-HYVQAUD4.js} +2 -2
  26. package/dist-cli/chunks/{chunk-QS37KABB.js → chunk-KAAYKAUG.js} +2 -2
  27. package/dist-cli/chunks/chunk-KTCY7WJ2.js +2 -0
  28. package/dist-cli/chunks/{chunk-I5FEWPWO.js → chunk-L7SG7TDU.js} +1 -1
  29. package/dist-cli/chunks/{chunk-F6YOWJAA.js → chunk-LWC2FLTG.js} +2 -2
  30. package/dist-cli/chunks/{chunk-ANTCWWXN.js → chunk-MCQIOGWG.js} +1 -1
  31. package/dist-cli/chunks/{chunk-MNMNX4O7.js → chunk-OL7HTJVC.js} +1 -1
  32. package/dist-cli/chunks/{chunk-RV3WN4FQ.js → chunk-PWGYVHEW.js} +2 -2
  33. package/dist-cli/chunks/{chunk-6MAW2X3J.js → chunk-PZL2H5SD.js} +1 -1
  34. package/dist-cli/chunks/{chunk-C6XQHJFR.js → chunk-QCPYYZGR.js} +2 -2
  35. package/dist-cli/chunks/{chunk-R76YX6KD.js → chunk-QEC2WZAU.js} +2 -2
  36. package/dist-cli/chunks/{chunk-7ODTKW6U.js → chunk-QGQRB6D2.js} +2 -2
  37. package/dist-cli/chunks/chunk-QGWWRXSG.js +1 -0
  38. package/dist-cli/chunks/{chunk-NRBPTQVR.js → chunk-SAV6NL5J.js} +3 -3
  39. package/dist-cli/chunks/{chunk-RGJAUL7P.js → chunk-SIGAKBUY.js} +2 -2
  40. package/dist-cli/chunks/{chunk-T35Q6ZGG.js → chunk-SK3UIUQL.js} +1 -1
  41. package/dist-cli/chunks/{chunk-3AALQI5D.js → chunk-SQBPTIVB.js} +2 -2
  42. package/dist-cli/chunks/{chunk-AXNDFONG.js → chunk-T7ERR3Y2.js} +1 -1
  43. package/dist-cli/chunks/{chunk-3Q7M3ATN.js → chunk-TM6NU7CC.js} +2 -2
  44. package/dist-cli/chunks/{chunk-5MF7XOPR.js → chunk-TNCYQFCC.js} +1 -1
  45. package/dist-cli/chunks/{chunk-5HCF2FQK.js → chunk-UODOGO3P.js} +2 -2
  46. package/dist-cli/chunks/{chunk-2R6ALEI7.js → chunk-UPDZS7GX.js} +3 -3
  47. package/dist-cli/chunks/{chunk-KDNOWAFU.js → chunk-UQGDJNV2.js} +2 -2
  48. package/dist-cli/chunks/{chunk-7FL2TKGB.js → chunk-V5TDYT4H.js} +2 -2
  49. package/dist-cli/chunks/{chunk-Q3UIMXJY.js → chunk-VC7MRZW7.js} +2 -2
  50. package/dist-cli/chunks/{chunk-RHHCV6M4.js → chunk-VZ7VB7HX.js} +2 -2
  51. package/dist-cli/chunks/{chunk-A27TUQQZ.js → chunk-ZO7E7WE5.js} +1 -1
  52. package/dist-cli/chunks/chunk-ZPDQ3S7P.js +1 -0
  53. package/dist-cli/chunks/{chunk-AUMBVWWD.js → chunk-ZU5S3Z7A.js} +2 -2
  54. package/dist-cli/chunks/cli-version-TJZ4JXUC.js +2 -0
  55. package/dist-cli/chunks/{compat-OH3WCY73.js → compat-E5CN4JWN.js} +3 -3
  56. package/dist-cli/chunks/{config-75MZT5JS.js → config-H75A6KBX.js} +2 -2
  57. package/dist-cli/chunks/{control-KSGYRJQK.js → control-CYDNB7NS.js} +2 -2
  58. package/dist-cli/chunks/{cpu-profile-2EHAVP5P.js → cpu-profile-QUFYSFW2.js} +2 -2
  59. package/dist-cli/chunks/{daemon-KRESTNSO.js → daemon-7GPY5B63.js} +2 -2
  60. package/dist-cli/chunks/{debug-XJ2XIBGI.js → debug-5WWA5QA3.js} +3 -3
  61. package/dist-cli/chunks/{detox-D3P2BFHN.js → detox-O55BWRH7.js} +2 -2
  62. package/dist-cli/chunks/{device-TMFWZCML.js → device-AQRY7VKI.js} +2 -2
  63. package/dist-cli/chunks/{diagnose-67SOCM6I.js → diagnose-FDKSEQJ5.js} +2 -2
  64. package/dist-cli/chunks/drivers-QDHVKRYQ.js +2 -0
  65. package/dist-cli/chunks/{electron-FLPDCIDO.js → electron-ZQBTU3QE.js} +3 -3
  66. package/dist-cli/chunks/flow-H6MLEX2L.js +2 -0
  67. package/dist-cli/chunks/help-THQ2V5SE.js +2 -0
  68. package/dist-cli/chunks/{hints-ODFXO5MG.js → hints-7UYBREXC.js} +2 -2
  69. package/dist-cli/chunks/{home-paths-NIEX6VIW.js → home-paths-2FGC73RX.js} +2 -2
  70. package/dist-cli/chunks/{inspect-C5R2IXQP.js → inspect-DIBHPUVR.js} +3 -3
  71. package/dist-cli/chunks/install-R63X4FZO.js +2 -0
  72. package/dist-cli/chunks/{install-desktop-TGI4DCY3.js → install-desktop-JGMQYTE4.js} +3 -3
  73. package/dist-cli/chunks/{keys-2QJCGBZU.js → keys-76ZYEU3L.js} +2 -2
  74. package/dist-cli/chunks/{launch-A2NXENLP.js → launch-73NGQKXM.js} +3 -3
  75. package/dist-cli/chunks/{login-TQLNNRFL.js → login-6EFONAEU.js} +4 -4
  76. package/dist-cli/chunks/{logout-N6R66AFU.js → logout-C3W5XSSV.js} +2 -2
  77. package/dist-cli/chunks/{maestro-DMNUWMEX.js → maestro-HVAORFSN.js} +2 -2
  78. package/dist-cli/chunks/optional-demo-registry-AJQV4MPG.js +2 -0
  79. package/dist-cli/chunks/{preview-O45WIZT7.js → preview-EC3BTC6H.js} +2 -2
  80. package/dist-cli/chunks/{profile-HSL4JQ2B.js → profile-UAZ2OUJ4.js} +2 -2
  81. package/dist-cli/chunks/{react-STTXJK2P.js → react-XQCVY4U2.js} +2 -2
  82. package/dist-cli/chunks/{record-6X7TU345.js → record-IGGTUUYU.js} +2 -2
  83. package/dist-cli/chunks/runtime-ATNAKUCZ.js +2 -0
  84. package/dist-cli/chunks/{runtime-delivery-D76JBTRS.js → runtime-delivery-NXMBF4CK.js} +2 -2
  85. package/dist-cli/chunks/{screenshot-WLKERV6O.js → screenshot-JTZJZCCX.js} +2 -2
  86. package/dist-cli/chunks/{screenshot-mode-QGT6WGQ6.js → screenshot-mode-WZ6ZO5CD.js} +2 -2
  87. package/dist-cli/chunks/screenshots-P5VB65PJ.js +74 -0
  88. package/dist-cli/chunks/{server-NNJNTLTV.js → server-2BYQFJUM.js} +12 -12
  89. package/dist-cli/chunks/setup-repo-7BUMPQZM.js +2 -0
  90. package/dist-cli/chunks/{skills-FTYSXEVA.js → skills-A2I5K4UQ.js} +2 -2
  91. package/dist-cli/chunks/{slides-FTSJM4AC.js → slides-O25XV2IB.js} +2 -2
  92. package/dist-cli/chunks/{start-Q37DNJPY.js → start-HY4ZGAE2.js} +4 -4
  93. package/dist-cli/chunks/store-VXGE7SLD.js +2 -0
  94. package/dist-cli/chunks/telemetry-HGRYUILN.js +2 -0
  95. package/dist-cli/chunks/{test-7WGTTJFK.js → test-IVVOPKT5.js} +3 -3
  96. package/dist-cli/chunks/{three-mode-T6V3MWE7.js → three-mode-TYAB3FVD.js} +2 -2
  97. package/dist-cli/chunks/{timeline-T36NNMIW.js → timeline-R6M6EJQA.js} +2 -2
  98. package/dist-cli/chunks/{upgrade-D5LA6F7T.js → upgrade-CZQ6GK7Y.js} +2 -2
  99. package/dist-cli/chunks/upload-NR4J3LM2.js +2 -0
  100. package/dist-cli/chunks/{version-NEMFK44K.js → version-XVAS3GOH.js} +2 -2
  101. package/dist-cli/chunks/{web-EBBS27LE.js → web-35EQF7J6.js} +2 -2
  102. package/dist-cli/chunks/{what-happened-LWSM2L7E.js → what-happened-MYXKT7EW.js} +2 -2
  103. package/dist-cli/chunks/{whoami-AXLQJ7NW.js → whoami-J7EHW2UD.js} +2 -2
  104. package/dist-lib/agent-daemon-client.cjs +1 -1
  105. package/dist-lib/agent-events.cjs +1 -1
  106. package/dist-lib/agent-sessions.cjs +1 -1
  107. package/dist-lib/attached-projects.cjs +1 -1
  108. package/dist-lib/auth/shared-session.cjs +1 -1
  109. package/dist-lib/backend-origin.cjs +1 -1
  110. package/dist-lib/beta.cjs +1 -1
  111. package/dist-lib/beta.mjs +1 -1
  112. package/dist-lib/bridge-constants.cjs +1 -1
  113. package/dist-lib/cli-constants.cjs +1 -1
  114. package/dist-lib/config.cjs +1 -1
  115. package/dist-lib/detox/index.cjs +1 -1
  116. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  117. package/dist-lib/home-paths.cjs +1 -1
  118. package/dist-lib/host/bridge-host.cjs +47 -3
  119. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  120. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  121. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  122. package/dist-lib/host/websocket-proxy.cjs +1 -1
  123. package/dist-lib/index.cjs +1 -1
  124. package/dist-lib/metro.cjs +1 -1
  125. package/dist-lib/profiles.cjs +1 -1
  126. package/dist-lib/render-mode.cjs +1 -1
  127. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  128. package/dist-lib/sdk.cjs +1 -1
  129. package/dist-lib/sdk.mjs +1 -1
  130. package/dist-lib/skills.cjs +47 -3
  131. package/dist-lib/vite.cjs +1 -1
  132. package/package.json +1 -1
  133. package/src/host/bridge-host.ts +70 -4
  134. package/src/screenshots/orchestrate.ts +7 -0
  135. package/src/screenshots/org-deck.ts +91 -0
  136. package/dist-cli/chunks/auto-bootstrap-JVI75WWN.js +0 -2
  137. package/dist-cli/chunks/beta-IXSKJTBA.js +0 -2
  138. package/dist-cli/chunks/chunk-HONMR5LW.js +0 -1
  139. package/dist-cli/chunks/chunk-OW2ZBOB3.js +0 -2
  140. package/dist-cli/chunks/chunk-QNJYE5OY.js +0 -2
  141. package/dist-cli/chunks/chunk-SMMTE4QY.js +0 -1
  142. package/dist-cli/chunks/chunk-WJA4MM4L.js +0 -1
  143. package/dist-cli/chunks/cli-version-C56OR6JV.js +0 -2
  144. package/dist-cli/chunks/drivers-OYNUTXKG.js +0 -2
  145. package/dist-cli/chunks/flow-Q2Z4UAPG.js +0 -2
  146. package/dist-cli/chunks/help-EVEPPKOR.js +0 -2
  147. package/dist-cli/chunks/install-H4QD5NHJ.js +0 -2
  148. package/dist-cli/chunks/optional-demo-registry-Q2WTD5VQ.js +0 -2
  149. package/dist-cli/chunks/runtime-K3KCLSIW.js +0 -2
  150. package/dist-cli/chunks/screenshots-H4CT4M6U.js +0 -70
  151. package/dist-cli/chunks/setup-repo-I4NU3XER.js +0 -2
  152. package/dist-cli/chunks/store-YJZETFWA.js +0 -2
  153. package/dist-cli/chunks/telemetry-73CWUPJ6.js +0 -2
  154. package/dist-cli/chunks/upload-DR6AU55F.js +0 -2
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as g,d as m}from"./chunk-R76YX6KD.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";import{exec as O}from"node:child_process";import{randomBytes as S}from"node:crypto";import _ from"node:http";var I=process.env.SOOTSIM_AUTH_ORIGIN||"https://sootbean.com",h="http://localhost:3000";async function x(r){if(r)return r;if(process.env.SOOTSIM_AUTH_ORIGIN)return process.env.SOOTSIM_AUTH_ORIGIN;if(process.env.SOOTSIM_UPLOAD_ORIGIN)return process.env.SOOTSIM_UPLOAD_ORIGIN;try{if((await fetch(`${h}/api/auth/me`)).ok)return h}catch{}return I}function L(){console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as g,d as m}from"./chunk-QEC2WZAU.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import{exec as O}from"node:child_process";import{randomBytes as S}from"node:crypto";import _ from"node:http";var I=process.env.SOOTSIM_AUTH_ORIGIN||"https://sootbean.com",h="http://localhost:3000";async function x(r){if(r)return r;if(process.env.SOOTSIM_AUTH_ORIGIN)return process.env.SOOTSIM_AUTH_ORIGIN;if(process.env.SOOTSIM_UPLOAD_ORIGIN)return process.env.SOOTSIM_UPLOAD_ORIGIN;try{if((await fetch(`${h}/api/auth/me`)).ok)return h}catch{}return I}function L(){console.log(`
3
3
  sootsim login \u2014 sign in so desktop uploads can attach to your account
4
4
 
5
5
  usage:
@@ -21,6 +21,6 @@ options:
21
21
  <p style="color:#ccc">${r}</p>
22
22
  </div>
23
23
  </body>
24
- </html>`}async function P(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/api/dev-login`,{method:"POST"});if(e.status===403)return{ok:!1,error:"dev-login disabled (not in dev mode)"};if(!e.ok){let c=await e.text().catch(()=>"");return{ok:!1,error:`dev-login ${e.status}: ${c}`}}let t=await e.json();return t.token?{ok:!0,token:t.token,userId:t.user?.id,email:t.email}:{ok:!1,error:"dev-login response missing token"}}catch(e){return{ok:!1,error:e instanceof Error?e.message:"dev-login fetch failed"}}}function A(r){try{let e=new URL(r).hostname.replace(/^\[|\]$/g,"").toLowerCase();return!!(e==="localhost"||/^127(?:\.\d{1,3}){3}$/.test(e)||e==="::1"||e==="0.0.0.0"||e.endsWith(".local")||e.endsWith(".localhost")||e==="host.containers.internal"||e==="host.docker.internal"||e==="host.orb.internal"||e==="host.lima.internal"||e==="fd07:b51a:cc66:f0::fe"||e==="192.168.5.2"||/^192\.168\.(?:64|139)\.1$/.test(e))}catch{return!1}}async function G(r){(r.includes("--help")||r.includes("-h"))&&(L(),process.exit(0));let e=[...r],t=await x(R(e,"--origin"));if(A(t)){console.log(` detected local origin (${t}) \u2014 signing in as dev user`);let o=await P(t);if(o.ok){g({token:o.token,user:o.userId?{id:o.userId,email:o.email}:null,origin:t,source:"cli"});let s=await m(t),l=s?.user?.email||o.email||s?.user?.id||o.userId,{trackCliEvent:n,flushCliTelemetry:a}=await import("./telemetry-73CWUPJ6.js");n({event:"cli_login_succeeded",identity:{userId:o.userId??s?.user?.id??null},properties:{origin:t,mode:"dev"}}),await a(),console.log(` signed in${l?` as ${l}`:""} (dev)`);return}console.log(` dev-login not available (${o.error}); falling back to browser`)}let c=S(16).toString("hex"),i=await new Promise(o=>{let s=_.createServer((l,n)=>{try{let a=new URL(l.url||"/","http://127.0.0.1"),w=a.searchParams.get("state"),k=a.searchParams.get("token"),b=a.searchParams.get("email")||void 0,$=a.searchParams.get("userId")||void 0,f=a.searchParams.get("error");if(n.setHeader("content-type","text/html; charset=utf-8"),f){n.end(u(`sign-in failed: ${f}`)),o({ok:!1,error:f}),s.close();return}if(w!==c){n.end(u("state mismatch. close this tab and retry `sootsim login`.")),o({ok:!1,error:"state mismatch"}),s.close();return}if(!k){n.end(u("missing token. close this tab and retry `sootsim login`.")),o({ok:!1,error:"missing token"}),s.close();return}n.end(u("sign-in complete. you can return to the terminal.")),o({ok:!0,token:k,email:b,userId:$}),s.close()}catch(a){n.statusCode=500,n.end(u("sign-in callback failed. retry `sootsim login`.")),o({ok:!1,error:a instanceof Error?a.message:"callback failed"}),s.close()}});s.listen(0,"127.0.0.1",()=>{let l=s.address();if(!l||typeof l=="string"){o({ok:!1,error:"failed to bind callback server"}),s.close();return}let n=new URL(`${t.replace(/\/$/,"")}/auth/sootsim-cli`);n.searchParams.set("state",c),n.searchParams.set("port",String(l.port)),n.searchParams.set("sootbean",t),console.log(" opening browser for sootsim login..."),console.log(` waiting for callback on 127.0.0.1:${l.port}`),console.log(` if nothing opens, visit:
24
+ </html>`}async function P(r){try{let e=await fetch(`${r.replace(/\/$/,"")}/api/dev-login`,{method:"POST"});if(e.status===403)return{ok:!1,error:"dev-login disabled (not in dev mode)"};if(!e.ok){let c=await e.text().catch(()=>"");return{ok:!1,error:`dev-login ${e.status}: ${c}`}}let t=await e.json();return t.token?{ok:!0,token:t.token,userId:t.user?.id,email:t.email}:{ok:!1,error:"dev-login response missing token"}}catch(e){return{ok:!1,error:e instanceof Error?e.message:"dev-login fetch failed"}}}function A(r){try{let e=new URL(r).hostname.replace(/^\[|\]$/g,"").toLowerCase();return!!(e==="localhost"||/^127(?:\.\d{1,3}){3}$/.test(e)||e==="::1"||e==="0.0.0.0"||e.endsWith(".local")||e.endsWith(".localhost")||e==="host.containers.internal"||e==="host.docker.internal"||e==="host.orb.internal"||e==="host.lima.internal"||e==="fd07:b51a:cc66:f0::fe"||e==="192.168.5.2"||/^192\.168\.(?:64|139)\.1$/.test(e))}catch{return!1}}async function G(r){(r.includes("--help")||r.includes("-h"))&&(L(),process.exit(0));let e=[...r],t=await x(R(e,"--origin"));if(A(t)){console.log(` detected local origin (${t}) \u2014 signing in as dev user`);let o=await P(t);if(o.ok){g({token:o.token,user:o.userId?{id:o.userId,email:o.email}:null,origin:t,source:"cli"});let s=await m(t),l=s?.user?.email||o.email||s?.user?.id||o.userId,{trackCliEvent:n,flushCliTelemetry:a}=await import("./telemetry-HGRYUILN.js");n({event:"cli_login_succeeded",identity:{userId:o.userId??s?.user?.id??null},properties:{origin:t,mode:"dev"}}),await a(),console.log(` signed in${l?` as ${l}`:""} (dev)`);return}console.log(` dev-login not available (${o.error}); falling back to browser`)}let c=S(16).toString("hex"),i=await new Promise(o=>{let s=_.createServer((l,n)=>{try{let a=new URL(l.url||"/","http://127.0.0.1"),w=a.searchParams.get("state"),k=a.searchParams.get("token"),b=a.searchParams.get("email")||void 0,$=a.searchParams.get("userId")||void 0,f=a.searchParams.get("error");if(n.setHeader("content-type","text/html; charset=utf-8"),f){n.end(u(`sign-in failed: ${f}`)),o({ok:!1,error:f}),s.close();return}if(w!==c){n.end(u("state mismatch. close this tab and retry `sootsim login`.")),o({ok:!1,error:"state mismatch"}),s.close();return}if(!k){n.end(u("missing token. close this tab and retry `sootsim login`.")),o({ok:!1,error:"missing token"}),s.close();return}n.end(u("sign-in complete. you can return to the terminal.")),o({ok:!0,token:k,email:b,userId:$}),s.close()}catch(a){n.statusCode=500,n.end(u("sign-in callback failed. retry `sootsim login`.")),o({ok:!1,error:a instanceof Error?a.message:"callback failed"}),s.close()}});s.listen(0,"127.0.0.1",()=>{let l=s.address();if(!l||typeof l=="string"){o({ok:!1,error:"failed to bind callback server"}),s.close();return}let n=new URL(`${t.replace(/\/$/,"")}/auth/sootsim-cli`);n.searchParams.set("state",c),n.searchParams.set("port",String(l.port)),n.searchParams.set("sootbean",t),console.log(" opening browser for sootsim login..."),console.log(` waiting for callback on 127.0.0.1:${l.port}`),console.log(` if nothing opens, visit:
25
25
  ${n.toString()}
26
- `),T(n.toString())})});if(!i.ok){let{trackCliEvent:o,flushCliTelemetry:s}=await import("./telemetry-73CWUPJ6.js");o({event:"cli_login_failed",properties:{origin:t,error:i.error}}),await s(),console.error(` login failed: ${i.error}`),process.exit(1)}g({token:i.token,user:i.userId?{id:i.userId,email:i.email}:null,origin:t,source:"cli"});let d=await m(t),p=d?.user?.email||i.email||d?.user?.id||i.userId,{trackCliEvent:y,flushCliTelemetry:v}=await import("./telemetry-73CWUPJ6.js");y({event:"cli_login_succeeded",identity:{userId:i.userId??d?.user?.id??null},properties:{origin:t}}),await v(),console.log(` signed in${p?` as ${p}`:""}`)}export{G as runLogin};
26
+ `),T(n.toString())})});if(!i.ok){let{trackCliEvent:o,flushCliTelemetry:s}=await import("./telemetry-HGRYUILN.js");o({event:"cli_login_failed",properties:{origin:t,error:i.error}}),await s(),console.error(` login failed: ${i.error}`),process.exit(1)}g({token:i.token,user:i.userId?{id:i.userId,email:i.email}:null,origin:t,source:"cli"});let d=await m(t),p=d?.user?.email||i.email||d?.user?.id||i.userId,{trackCliEvent:y,flushCliTelemetry:v}=await import("./telemetry-HGRYUILN.js");y({event:"cli_login_succeeded",identity:{userId:i.userId??d?.user?.id??null},properties:{origin:t}}),await v(),console.log(` signed in${p?` as ${p}`:""}`)}export{G as runLogin};
@@ -1,2 +1,2 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as r,b as i}from"./chunk-RV3WN4FQ.js";import{a as t,c as o}from"./chunk-R76YX6KD.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";async function s(){let e=t();if(!e?.token){console.log(" not signed in");return}try{await fetch(`${e.origin.replace(/\/$/,"")}/api/auth/sign-out`,{method:"POST",headers:{authorization:`Bearer ${e.token}`}})}catch{}o(),r({event:"cli_logout",identity:{userId:e.user?.id??null},properties:{origin:e.origin}}),await i(),console.log(" signed out")}export{s as runLogout};
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as r,b as i}from"./chunk-PWGYVHEW.js";import{a as t,c as o}from"./chunk-QEC2WZAU.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";async function s(){let e=t();if(!e?.token){console.log(" not signed in");return}try{await fetch(`${e.origin.replace(/\/$/,"")}/api/auth/sign-out`,{method:"POST",headers:{authorization:`Bearer ${e.token}`}})}catch{}o(),r({event:"cli_logout",identity:{userId:e.user?.id??null},properties:{origin:e.origin}}),await i(),console.log(" signed out")}export{s as runLogout};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as y,c as v}from"./chunk-2R6ALEI7.js";import"./chunk-2GAVMQGW.js";import"./chunk-WJA4MM4L.js";import"./chunk-F6YOWJAA.js";import"./chunk-RHHCV6M4.js";import"./chunk-3Q7M3ATN.js";import{b as h,c as w}from"./chunk-3AALQI5D.js";import"./chunk-C6XQHJFR.js";import"./chunk-QS37KABB.js";import"./chunk-5HCF2FQK.js";import"./chunk-AXNDFONG.js";import"./chunk-YENFSYAG.js";import"./chunk-Q3UIMXJY.js";import"./chunk-QZAJOB4N.js";import"./chunk-7GBAY2BX.js";import"./chunk-6MAW2X3J.js";import"./chunk-4QJCDB6B.js";import"./chunk-SMMTE4QY.js";import"./chunk-MNMNX4O7.js";import"./chunk-T35Q6ZGG.js";import"./chunk-RV3WN4FQ.js";import"./chunk-R76YX6KD.js";import"./chunk-RGJAUL7P.js";import"./chunk-OW2ZBOB3.js";import"./chunk-36RF3WRB.js";import"./chunk-QNJYE5OY.js";import"./chunk-TRA4IJCY.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";import*as n from"fs";import*as a from"path";var S=[".maestro","maestro"];function k(){console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as y,c as v}from"./chunk-UPDZS7GX.js";import"./chunk-5CTOWZY4.js";import"./chunk-QGWWRXSG.js";import"./chunk-LWC2FLTG.js";import"./chunk-VZ7VB7HX.js";import"./chunk-TM6NU7CC.js";import{b as h,c as w}from"./chunk-SQBPTIVB.js";import"./chunk-QCPYYZGR.js";import"./chunk-KAAYKAUG.js";import"./chunk-UODOGO3P.js";import"./chunk-T7ERR3Y2.js";import"./chunk-HN2Q2ZWT.js";import"./chunk-VC7MRZW7.js";import"./chunk-5PKIU2SG.js";import"./chunk-HYVQAUD4.js";import"./chunk-PZL2H5SD.js";import"./chunk-DXL23RFP.js";import"./chunk-ZPDQ3S7P.js";import"./chunk-OL7HTJVC.js";import"./chunk-SK3UIUQL.js";import"./chunk-PWGYVHEW.js";import"./chunk-QEC2WZAU.js";import"./chunk-SIGAKBUY.js";import"./chunk-KTCY7WJ2.js";import"./chunk-4CLJIXM3.js";import"./chunk-EJIK4ANI.js";import"./chunk-FOLNNKZG.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import*as n from"fs";import*as a from"path";var S=[".maestro","maestro"];function k(){console.log(`
3
3
  sootsim maestro \u2014 run maestro YAML flows against sootsim (drop-in)
4
4
 
5
5
  usage:
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b}from"./chunk-5PKIU2SG.js";import"./chunk-ZO7E7WE5.js";export{a as loadOptionalDemoApps,b as optionalDemoAppsSync};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import"./chunk-A27TUQQZ.js";import{resolve as c,dirname as m}from"path";import{fileURLToPath as a}from"url";var t=m(a(import.meta.resolve("sootsim-engine/package.json")));async function g(o,r){(o.includes("--help")||o.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import"./chunk-ZO7E7WE5.js";import{resolve as c,dirname as m}from"path";import{fileURLToPath as a}from"url";var t=m(a(import.meta.resolve("sootsim-engine/package.json")));async function g(o,r){(o.includes("--help")||o.includes("-h"))&&(console.log(`
3
3
  sootsim preview \u2014 production-like preview
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as s,c as i,d as t,e as n,f as c}from"./chunk-4QJCDB6B.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";function f(){console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as s,c as i,d as t,e as n,f as c}from"./chunk-DXL23RFP.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";function f(){console.log(`
3
3
  sootsim profile \u2014 manage isolated storage profiles
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{c as w,e as b,h as m,i as f}from"./chunk-Q3UIMXJY.js";import"./chunk-T35Q6ZGG.js";import"./chunk-36RF3WRB.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";function h(){console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{c as w,e as b,h as m,i as f}from"./chunk-VC7MRZW7.js";import"./chunk-SK3UIUQL.js";import"./chunk-4CLJIXM3.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";function h(){console.log(`
3
3
  sootsim react \u2014 inspect React component render cost in the tenant worker
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as P}from"./chunk-F6YOWJAA.js";import"./chunk-RHHCV6M4.js";import{d as Z,f as ee}from"./chunk-3Q7M3ATN.js";import"./chunk-YENFSYAG.js";import{c as b,e as v,f as Y}from"./chunk-Q3UIMXJY.js";import"./chunk-SMMTE4QY.js";import{d as X}from"./chunk-MNMNX4O7.js";import{b as Q}from"./chunk-T35Q6ZGG.js";import"./chunk-RV3WN4FQ.js";import"./chunk-R76YX6KD.js";import"./chunk-36RF3WRB.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";import{existsSync as we,mkdirSync as B,readdirSync as he,readFileSync as be,rmSync as J,writeFileSync as I}from"fs";import{homedir as ve,tmpdir as ye}from"os";import{dirname as D,extname as oe,join as N,resolve as Se}from"path";var z=24e4,Re=3e4;async function W(e,r,o,i){let t=Math.max(2e4,i+Re);try{return await e.send({type:"evaluate",code:r},{timeoutMs:t})}catch(n){let s=n instanceof Error?n.message:String(n);/^command timed out after \d+s$/.test(s)&&(console.error(` ${o} stalled \u2014 the render host did not finish within ${Math.round(t/1e3)}s; it is likely contended or wedged.
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as P}from"./chunk-LWC2FLTG.js";import"./chunk-VZ7VB7HX.js";import{d as Z,f as ee}from"./chunk-TM6NU7CC.js";import"./chunk-HN2Q2ZWT.js";import{c as b,e as v,f as Y}from"./chunk-VC7MRZW7.js";import"./chunk-ZPDQ3S7P.js";import{d as X}from"./chunk-OL7HTJVC.js";import{b as Q}from"./chunk-SK3UIUQL.js";import"./chunk-PWGYVHEW.js";import"./chunk-QEC2WZAU.js";import"./chunk-4CLJIXM3.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import{existsSync as we,mkdirSync as B,readdirSync as he,readFileSync as be,rmSync as J,writeFileSync as I}from"fs";import{homedir as ve,tmpdir as ye}from"os";import{dirname as D,extname as oe,join as N,resolve as Se}from"path";var z=24e4,Re=3e4;async function W(e,r,o,i){let t=Math.max(2e4,i+Re);try{return await e.send({type:"evaluate",code:r},{timeoutMs:t})}catch(n){let s=n instanceof Error?n.message:String(n);/^command timed out after \d+s$/.test(s)&&(console.error(` ${o} stalled \u2014 the render host did not finish within ${Math.round(t/1e3)}s; it is likely contended or wedged.
3
3
  the capture lock auto-releases, so simply retry the recording.
4
4
  if it persists, recover the sim with \`sootsim close --sim <id>\`.`),process.exit(1)),/render host not available|already streaming|already recording/i.test(s)&&(console.error(` ${o} failed: ${s}
5
5
  a prior recording was abandoned and its capture is still
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b}from"./chunk-SAV6NL5J.js";import"./chunk-VC7MRZW7.js";import"./chunk-SK3UIUQL.js";import"./chunk-4CLJIXM3.js";import"./chunk-QGQRB6D2.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";export{b as formatReleaseEntry,a as runRuntime};
@@ -1,2 +1,2 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-7ODTKW6U.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";export{a as DEFAULT_RUNTIME_CDN_ORIGIN,b as RUNTIME_CDN_ORIGIN_ENV,c as RUNTIME_CHANNEL_ENV,n as checkRuntimeUpToDate,h as fetchRuntimeManifest,j as fetchRuntimeReleases,l as installRuntime,d as resolveRuntimeCdnOrigin,e as resolveRuntimeChannel,k as resolveRuntimeVersion,f as runtimeManifestUrl,i as runtimeReleasesUrl,g as runtimeTarballUrl,m as updateRuntimeToLatest};
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n}from"./chunk-QGQRB6D2.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";export{a as DEFAULT_RUNTIME_CDN_ORIGIN,b as RUNTIME_CDN_ORIGIN_ENV,c as RUNTIME_CHANNEL_ENV,n as checkRuntimeUpToDate,h as fetchRuntimeManifest,j as fetchRuntimeReleases,l as installRuntime,d as resolveRuntimeCdnOrigin,e as resolveRuntimeChannel,k as resolveRuntimeVersion,f as runtimeManifestUrl,i as runtimeReleasesUrl,g as runtimeTarballUrl,m as updateRuntimeToLatest};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as S}from"./chunk-2GAVMQGW.js";import"./chunk-WJA4MM4L.js";import{a as b}from"./chunk-I5FEWPWO.js";import{c as g,d as w,e as y,f as v,h as x}from"./chunk-Q3UIMXJY.js";import"./chunk-T35Q6ZGG.js";import"./chunk-RGJAUL7P.js";import"./chunk-36RF3WRB.js";import"./chunk-QNJYE5OY.js";import{f as m}from"./chunk-TRA4IJCY.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";import{mkdirSync as A,writeFileSync as R}from"fs";import{dirname as E,resolve as F}from"path";async function J(t,o){let e=U(t);(e.includes("--help")||e.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as S}from"./chunk-5CTOWZY4.js";import"./chunk-QGWWRXSG.js";import{a as b}from"./chunk-L7SG7TDU.js";import{c as g,d as w,e as y,f as v,h as x}from"./chunk-VC7MRZW7.js";import"./chunk-SK3UIUQL.js";import"./chunk-SIGAKBUY.js";import"./chunk-4CLJIXM3.js";import"./chunk-EJIK4ANI.js";import{g as m}from"./chunk-FOLNNKZG.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import{mkdirSync as A,writeFileSync as R}from"fs";import{dirname as E,resolve as F}from"path";async function J(t,o){let e=U(t);(e.includes("--help")||e.includes("-h"))&&(console.log(`
3
3
  sootsim screenshot \u2014 capture the canvas as a PNG
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as o}from"./chunk-26P6DJRO.js";import"./chunk-Q3UIMXJY.js";import"./chunk-T35Q6ZGG.js";import"./chunk-36RF3WRB.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";async function n(e,s){(e.includes("--help")||e.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as o}from"./chunk-54R6LIOF.js";import"./chunk-VC7MRZW7.js";import"./chunk-SK3UIUQL.js";import"./chunk-4CLJIXM3.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";async function n(e,s){(e.includes("--help")||e.includes("-h"))&&(console.log(`
3
3
  sootsim screenshot-mode \u2014 toggle the screenshot-mode chrome overlay
4
4
 
5
5
  usage:
@@ -0,0 +1,74 @@
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as q}from"./chunk-UPDZS7GX.js";import{b as L}from"./chunk-5CTOWZY4.js";import"./chunk-QGWWRXSG.js";import"./chunk-LWC2FLTG.js";import"./chunk-VZ7VB7HX.js";import{d as U,e as K}from"./chunk-TM6NU7CC.js";import{b as H}from"./chunk-SQBPTIVB.js";import"./chunk-QCPYYZGR.js";import"./chunk-KAAYKAUG.js";import"./chunk-UODOGO3P.js";import"./chunk-T7ERR3Y2.js";import"./chunk-HN2Q2ZWT.js";import"./chunk-VC7MRZW7.js";import"./chunk-5PKIU2SG.js";import"./chunk-HYVQAUD4.js";import"./chunk-PZL2H5SD.js";import"./chunk-DXL23RFP.js";import"./chunk-ZPDQ3S7P.js";import"./chunk-OL7HTJVC.js";import"./chunk-SK3UIUQL.js";import"./chunk-PWGYVHEW.js";import"./chunk-QEC2WZAU.js";import"./chunk-SIGAKBUY.js";import"./chunk-KTCY7WJ2.js";import"./chunk-4CLJIXM3.js";import"./chunk-EJIK4ANI.js";import{a as y,b as A,c as E,d as O,e as v,f as C,g as _}from"./chunk-FOLNNKZG.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import{mkdirSync as I,readFileSync as ye,writeFileSync as se}from"fs";import{tmpdir as We}from"os";import F from"path";import{mkdirSync as W,readFileSync as ae,writeFileSync as X}from"fs";import B from"path";function V(e){return e.replace(/\\/g,"/").replace(/\.png$/i,"").trim().split("/").filter(Boolean).join("--").replace(/[^A-Za-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"slide"}function T(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function ce(e){let t=e.trim();return/^#[0-9a-f]{3}$/i.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t}function D(e,t){let o=ce(e),i=Math.max(0,Math.min(1,t)),n=o.match(/^#([0-9a-f]{6})$/i);if(n){let s=n[1],r=Number.parseInt(s.slice(0,2),16),a=Number.parseInt(s.slice(2,4),16),c=Number.parseInt(s.slice(4,6),16);return`rgba(${r}, ${a}, ${c}, ${i})`}return o.startsWith("rgb(")?o.replace(/^rgb\((.+)\)$/i,`rgba($1, ${i})`):o}function le(e){if(e.type==="solid")return e.color||"#000000";let t=e.direction??180,o=e.stops?.map(i=>`${i.color} ${i.offset}%`).join(", ")||"#000000 0%, #111111 100%";return`linear-gradient(${t}deg, ${o})`}function pe(e){let t=e.glow;return t?`radial-gradient(circle at 50% 24%, ${D(t,.46)} 0%, ${D(t,.2)} 24%, rgba(0,0,0,0) 62%)`:"none"}function R(e){switch(e){case"tilted-left":return"perspective(2400px) rotateY(10deg) rotateZ(-2deg)";case"tilted-right":return"perspective(2400px) rotateY(-10deg) rotateZ(2deg)";case"cut-bottom":return"translateY(10%) scale(1.08)";case"cut-top":return"translateY(-16%) scale(1.08)";case"straight":default:return"none"}}function G(...e){let t=e.map(o=>o.trim()).filter(o=>o.length>0&&o!=="none");return t.length>0?t.join(" "):"none"}function j(e){let t=D(e.color,e.opacity),o=D(e.color,e.opacity*.52);return`drop-shadow(0 34px ${e.spread}px ${o}) drop-shadow(0 0 ${e.blur}px ${t})`}function Y(e,t){return!t.glow||e.color&&e.color!==y.color?e:{...e,color:t.glow}}function ue(e,t){if(e==="editorial-left"){let n=Math.round(t.height*.056),s=Math.round(t.height*.022);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.12)}px`,`left:${Math.round(t.width*.085)}px`,`width:${Math.round(t.width*.42)}px`,"text-align:left","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.92;`,subStyle:`font-size:${s}px;line-height:1.36;max-width:${Math.round(t.width*.36)}px;`,eyebrowStyle:"align-items:flex-start;",deviceStyle:(r,a,c)=>{let p=Math.round(t.width*.68*(a.scale??r.scale)),l=Math.round(t.height*(.03+r.offsetY+(a.offsetY??0))),d=a.pose||r.pose||"tilted-right",h=Y(r.shadow,c);return["position:absolute",`top:${Math.round(t.height*.18)+l}px`,`left:${Math.round(t.width*.56)}px`,`width:${p}px`,"transform-origin:center center",`transform:${R(d)}`,`filter:${j(h)}`,"z-index:2"].join(";")}}}if(e==="minimal-bottom"){let n=Math.round(t.height*.041),s=Math.round(t.height*.019);return{copyStyle:["position:absolute",`left:${Math.round(t.width*.12)}px`,`right:${Math.round(t.width*.12)}px`,`bottom:${Math.round(t.height*.085)}px`,"text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.96;`,subStyle:`font-size:${s}px;line-height:1.34;max-width:${Math.round(t.width*.56)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(r,a,c)=>{let p=Math.round(t.width*.84*(a.scale??r.scale)),l=Math.round(t.height*(r.offsetY+(a.offsetY??0))),d=a.pose||r.pose,h=Y(r.shadow,c);return["position:absolute",`top:${Math.round(t.height*.075)+l}px`,"left:50%",`width:${p}px`,"transform-origin:center center",`transform:${G("translateX(-50%)",R(d))}`,`filter:${j(h)}`,"z-index:2"].join(";")}}}let o=Math.round(t.height*.04),i=Math.round(t.height*.019);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.084)}px`,"left:50%",`width:${Math.round(t.width*.88)}px`,"transform:translateX(-50%)","text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${o}px;line-height:0.92;`,subStyle:`font-size:${i}px;line-height:1.34;max-width:${Math.round(t.width*.6)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(n,s,r)=>{let a=t.name==="ipad-13"?.54:.64,c=Math.round(t.width*a*(s.scale??n.scale)),p=Math.round(t.height*(n.offsetY+(s.offsetY??0))),l=s.pose||n.pose,d=Y(n.shadow,r);return["position:absolute",`top:${Math.round(t.height*(t.name==="ipad-13"?.25:.28))+p}px`,"left:50%",`width:${c}px`,"transform-origin:center top",`transform:${G("translateX(-50%)",R(l))}`,`filter:${j(d)}`,"z-index:2"].join(";")}}}function de({canvas:e,compose:t,slide:o,imageDataUrl:i}){let n=o.background??t.background,s=ue(t.text.preset,e),r=t.text.preset!=="none"&&!!(o.eyebrow||o.headline||o.subheadline),a=s.deviceStyle(t.frame,o,n),c=o.headline?`<div style="font-weight:780;white-space:pre-line;text-wrap:balance;${s.titleStyle}">${T(o.headline)}</div>`:"",p=o.subheadline?`<div style="margin-top:${Math.round(e.height*.018)}px;color:${t.text.subColor};white-space:pre-line;text-wrap:balance;${s.subStyle}">${T(o.subheadline)}</div>`:"",l=o.eyebrow?`<div style="display:flex;${s.eyebrowStyle}margin-bottom:${Math.round(e.height*.016)}px;"><div style="font-size:${Math.round(e.height*.014)}px;font-weight:700;letter-spacing:0.18em;text-transform:uppercase;color:${t.text.eyebrowColor};">${T(o.eyebrow)}</div></div>`:"";return`<!doctype html>
3
+ <html>
4
+ <head>
5
+ <meta charset="utf-8" />
6
+ <style>
7
+ html, body {
8
+ margin: 0;
9
+ width: ${e.width}px;
10
+ height: ${e.height}px;
11
+ overflow: hidden;
12
+ background: transparent;
13
+ }
14
+ body {
15
+ font-family: "SF Pro Display", "Helvetica Neue", system-ui, sans-serif;
16
+ }
17
+ #canvas {
18
+ position: relative;
19
+ width: ${e.width}px;
20
+ height: ${e.height}px;
21
+ overflow: hidden;
22
+ background: ${le(n)};
23
+ color: ${t.text.color};
24
+ isolation: isolate;
25
+ }
26
+ #glow {
27
+ position: absolute;
28
+ inset: 0;
29
+ background: ${pe(n)};
30
+ pointer-events: none;
31
+ }
32
+ #copy {
33
+ ${s.copyStyle};
34
+ }
35
+ #device {
36
+ ${a};
37
+ }
38
+ #device img {
39
+ display: block;
40
+ width: 100%;
41
+ height: auto;
42
+ }
43
+ </style>
44
+ </head>
45
+ <body>
46
+ <div id="canvas">
47
+ <div id="glow"></div>
48
+ ${r?`<div id="copy">${l}${c}${p}</div>`:""}
49
+ <div id="device"><img src="${i}" alt="" /></div>
50
+ </div>
51
+ </body>
52
+ </html>`}async function Z(e,t,o){let i=[],n=o??await(async()=>{let{chromium:r}=await import("playwright");return r.launch({headless:!0})})();try{let r=await n.newContext({viewport:{width:1280,height:720}});try{for(let a of t){let p=`data:image/png;base64,${ae(a.imagePath).toString("base64")}`;for(let l of e.canvases){let d=await r.newPage();try{await d.setViewportSize({width:l.width,height:l.height}),await d.setContent(de({canvas:l,compose:e,slide:a.slide,imageDataUrl:p}),{waitUntil:"load"}),await d.waitForTimeout(20);let h=B.join(e.outDir,l.name,e.locale);W(h,{recursive:!0});let P=B.join(h,`${a.slide.assetKey}.png`),g=await d.screenshot({type:"png",clip:{x:0,y:0,width:l.width,height:l.height}});X(P,g),i.push({slideId:a.slide.id,canvas:l.name,locale:e.locale,outputPath:P,sourcePath:a.imagePath})}finally{await d.close()}}}}finally{await r.close()}}finally{!o&&typeof n.close=="function"&&await n.close()}W(e.outDir,{recursive:!0});let s=B.join(e.outDir,"manifest.json");return X(s,JSON.stringify({generatedAt:new Date().toISOString(),locale:e.locale,outputs:i},null,2)),{manifestPath:s,outputs:i.map(r=>r.outputPath),entries:i}}function $(e){return typeof e=="string"&&e.length>0?e:void 0}async function J(e){let o=`${e.origin.replace(/\/$/,"")}/api/sootsim/screenshot-decks?org=${encodeURIComponent(e.org)}&repo=${encodeURIComponent(e.repo)}`,i=await fetch(o,{headers:{Authorization:e.authHeader}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`org deck fetch failed (${i.status} ${i.statusText}) for ${e.org}/${e.repo}${a?` \u2014 ${a.slice(0,200)}`:""}`)}let s=(await i.json()).decks?.[0];if(!s||!s.config||typeof s.config!="object")return null;let r=s.config.frames;return Array.isArray(r)?r.map(a=>{let c=a??{};return{title:$(c.title),subtitle:$(c.subtitle),bgTop:$(c.bgTop),bgBottom:$(c.bgBottom),titleColor:$(c.titleColor)}}):null}function Q(e,t){e.compose.slides.forEach((o,i)=>{let n=t[i];if(n&&(n.title!=null&&(o.headline=n.title),n.subtitle!=null&&(o.subheadline=n.subtitle),n.bgTop&&n.bgBottom)){let s={type:"gradient",direction:180,stops:[{offset:0,color:E(n.bgTop)},{offset:1,color:E(n.bgBottom)}]};o.background=s}})}import{readFileSync as me}from"fs";import S from"path";function u(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function N(e,t){if(!u(e))throw new Error(`${t} must be an object`);return e}function f(e,t=""){return typeof e=="string"?e:t}function w(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function ee(e,t){return typeof e=="boolean"?e:t}function b(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function te(e,t){return typeof e!="string"||e.trim().length===0?t:Object.prototype.hasOwnProperty.call(_,e)?e:null}function re(e,t){if(typeof e=="string"){let n=C(e);if(!n)throw new Error(`unknown background preset: ${e}`);return n}if(!u(e))return v(t);let o=e.type==="solid"||e.type==="gradient"?e.type:t.type;if(o==="solid")return{type:o,color:f(e.color,t.color??"#000000"),glow:w(e.glow)??t.glow};let i=Array.isArray(e.stops)?e.stops.map(n=>{if(!u(n))return null;let s=b(n.offset,Number.NaN),r=w(n.color);return!Number.isFinite(s)||!r?null:{offset:s,color:r}}).filter(n=>!!n):t.stops?.map(n=>({...n}))??[];return{type:o,direction:b(e.direction,t.direction??180),glow:w(e.glow)??t.glow,stops:i.length>0?i:t.stops?.map(n=>({...n}))??[]}}function fe(e){let o=(Array.isArray(e)?e:["iphone-6-9"]).map(i=>{if(typeof i!="string")throw new Error("compose.canvases entries must be strings");let n=O(i);if(!n)throw new Error(`unknown canvas preset: ${i}`);return n});if(o.length===0)throw new Error("compose.canvases must include at least one preset");return o}function he(e){switch(e){case"editorial-left":case"minimal-bottom":case"none":case"bold-top":return e;default:return"bold-top"}}function ge(e){switch(e){case"plan":case"flow":case"auto":return e;default:return"auto"}}function oe(e){switch(e){case"straight":case"tilted-left":case"tilted-right":case"cut-bottom":case"cut-top":return e;default:return}}function k(e,t){return S.isAbsolute(t)?t:S.resolve(e,t)}function we(e,t){if(!Array.isArray(e)||e.length===0)throw new Error("compose.slides must be a non-empty array");return e.map((o,i)=>{let n=N(o,`compose.slides[${i}]`),s=w(n.screenshot);if(!s)throw new Error(`compose.slides[${i}].screenshot is required`);let r=w(n.id),a=V(r||s);return{id:r||a,assetKey:a,screenshot:s,headline:f(n.headline),subheadline:f(n.subheadline),eyebrow:f(n.eyebrow),pose:oe(n.pose),scale:typeof n.scale=="number"&&Number.isFinite(n.scale)?n.scale:void 0,offsetY:typeof n.offsetY=="number"&&Number.isFinite(n.offsetY)?n.offsetY:void 0,background:n.theme||n.background?re(n.theme??n.background,t):void 0}})}function ne(e){let t=S.resolve(e),o=S.dirname(t),i=H.parse(me(t,"utf8")),n=N(i,"screenshots plan"),s=N(n.capture??{},"capture"),r=N(n.compose??{},"compose"),a=typeof n.app=="number"?String(n.app):w(n.app),c=te(n.device,null),p=k(o,f(s.out,S.join(".sootsim","screenshots","capture"))),l=w(s.from),d=w(s.flow);if(!l&&!d)throw new Error("capture.flow or capture.from is required");let h=s.mode==="raw"||s.mode==="framed"||s.mode==="raw+framed"?s.mode:"raw+framed",P=ge(s.pathMode),g=re(r.background??"cyan",C("cyan")),m={show:ee(r.frame&&u(r.frame)?r.frame.show:void 0,!0),style:te(r.frame&&u(r.frame)?r.frame.style:null,null)||c||A,pose:oe(r.frame&&u(r.frame)?r.frame.pose:void 0)||"straight",scale:b(r.frame&&u(r.frame)?r.frame.scale:void 0,1),offsetY:b(r.frame&&u(r.frame)?r.frame.offsetY:void 0,0),shadow:{color:f(r.frame&&u(r.frame)&&u(r.frame.shadow)?r.frame.shadow.color:void 0,y.color),blur:b(r.frame&&u(r.frame)&&u(r.frame.shadow)?r.frame.shadow.blur:void 0,y.blur),spread:b(r.frame&&u(r.frame)&&u(r.frame.shadow)?r.frame.shadow.spread:void 0,y.spread),opacity:b(r.frame&&u(r.frame)&&u(r.frame.shadow)?r.frame.shadow.opacity:void 0,y.opacity)}};return{planPath:t,planDir:o,appTarget:a,deviceModel:c,capture:{flowPath:d?k(o,d):null,fromDir:l?k(o,l):null,outDir:p,rawDir:l?k(o,l):S.join(p,"raw"),framedDir:S.join(p,"framed"),mode:h,pathMode:P,simId:w(s.sim),openInNewSim:ee(s.new,!1)},compose:{outDir:k(o,f(r.out,S.join(".sootsim","screenshots","exports"))),locale:f(r.locale,"en"),canvases:fe(r.canvases),frame:m,background:g,text:{preset:he(r.text&&u(r.text)?r.text.preset:void 0),color:f(r.text&&u(r.text)?r.text.color:void 0,"#ffffff"),subColor:f(r.text&&u(r.text)?r.text.subColor:void 0,"rgba(232,240,247,0.86)"),eyebrowColor:f(r.text&&u(r.text)?r.text.eyebrowColor:void 0,"rgba(229,242,255,0.72)")},slides:we(r.slides,g)}}}function Se(e){return e.capture.pathMode==="plan"||e.capture.pathMode==="flow"?e.capture.pathMode:e.capture.fromDir?"flow":"plan"}function be(e,t){if(!e.capture.flowPath)throw new Error("capture flow path is required to build flow args");let o=[e.capture.flowPath],i=Se(e);o.push("--screenshots",e.capture.rawDir),i==="flow"&&o.push("--screenshot-paths","flow");let n=t.appTarget??e.appTarget,s=t.deviceModel??e.deviceModel,r=t.simId??e.capture.simId;return n&&o.push("--url",n),s&&o.push("--device",s),r&&o.push("--sim",r),e.capture.openInNewSim&&o.push("--new"),o}function z(e,t){return F.isAbsolute(t)?t:F.join(e.capture.rawDir,t)}function Pe(e){return F.join(e.capture.outDir,"manifest.json")}async function xe(e,t){if(!e.capture.flowPath)return;I(e.capture.rawDir,{recursive:!0});let o=be(e,t),i=await q(o);if(i!==0)throw new Error(`flow capture failed with exit code ${i}`)}async function $e(e,t){let o=new Map;I(e.capture.framedDir,{recursive:!0});let i=t??await(async()=>{let{chromium:n}=await import("playwright");return n.launch({headless:!0})})();try{let n=await L(i);try{for(let s of e.compose.slides){let r=z(e,s.screenshot),a=ye(r),c=await n.compose(a,e.compose.frame.style),p=F.join(e.capture.framedDir,`${s.assetKey}.png`);se(p,c),o.set(s.id,p)}}finally{await n.close()}}finally{!t&&typeof i.close=="function"&&await i.close()}return o}function ke(e,t,o){let i=[],n=[];I(e.capture.outDir,{recursive:!0});let s=Pe(e),r=e.compose.slides.map(a=>{let c=z(e,a.screenshot),p=t.get(a.id)??null;return i.push(c),p&&n.push(p),{id:a.id,screenshot:a.screenshot,rawPath:c,framedPath:p}});return se(s,JSON.stringify({generatedAt:new Date().toISOString(),deviceModel:o,mode:e.capture.mode,rawDir:e.capture.rawDir,framedDir:e.capture.framedDir,slides:r},null,2)),{manifestPath:s,rawDir:e.capture.rawDir,framedDir:e.capture.framedDir,rawFiles:i,framedFiles:n}}function Me(e,t){return e.compose.slides.map(o=>({slide:o,imagePath:e.compose.frame.show===!0?t.get(o.id)??z(e,o.screenshot):z(e,o.screenshot)}))}async function ie(e,t={}){let o=ne(e);t.orgDeckFrames&&t.orgDeckFrames.length>0&&Q(o,t.orgDeckFrames);let i=t.deviceModel??o.deviceModel;t.composeOnly||await xe(o,t);let n=o.capture.mode!=="raw"||!t.captureOnly&&o.compose.frame.show===!0,r=n||!t.captureOnly?await(async()=>{let{chromium:a}=await import("playwright");return a.launch({headless:!0})})():null;try{let a=n?await $e(o,r??void 0):new Map,c=ke(o,a,i);if(t.captureOnly)return{plan:o,capture:c,compose:null};let p=Me(o,a),l=await Z(o.compose,p,r??void 0);return{plan:o,capture:c,compose:l}}finally{r&&typeof r.close=="function"&&await r.close()}}async function st(e,t={}){if(e.includes("--help")||e.includes("-h"))return console.log(`
53
+ sootsim screenshots \u2014 capture and compose app-store screenshot sets
54
+
55
+ usage:
56
+ sootsim screenshots --plan <plan.yaml> [options]
57
+
58
+ options:
59
+ --plan <path> screenshot plan yaml
60
+ --sim <id> reuse a live sim for capture
61
+ --app <target> override plan app target (port, url, or shell url)
62
+ --device <model> override plan capture device for this run
63
+ --org <slug> overlay copy/colors from a team's org screenshot deck
64
+ --repo <name> repo for --org (both required to pull the org deck)
65
+ --api-origin <url> sootbean origin to fetch the deck from (default: the
66
+ signed-in session origin, else https://sootbean.com)
67
+ --capture-only stop after raw/framed intermediates
68
+ --compose-only skip flow capture, reuse existing raw screenshots
69
+
70
+ examples:
71
+ sootsim screenshots --plan app-store.yaml
72
+ sootsim screenshots --plan app-store.yaml --sim a9
73
+ sootsim screenshots --plan app-store.yaml --org acme --repo mobile
74
+ `),0;let o=m=>e.find((M,x)=>e[x-1]===m),i=new Set(["--plan","--sim","--app","--device","--org","--repo","--api-origin"]),n=e.filter((m,M)=>{if(m.startsWith("-"))return!1;let x=e[M-1];return!x||!i.has(x)}),s=o("--plan")||n[0];if(!s)return console.error(" error: screenshots plan path is required (`--plan <path>`)."),1;let r=o("--sim")?.trim()||null,a=o("--app")?.trim()||null,c=o("--device")?.trim()||null,p=o("--org")?.trim()||null,l=o("--repo")?.trim()||null,d=o("--api-origin")?.trim()||null,h=e.includes("--capture-only"),P=e.includes("--compose-only"),g=null;if(p||l){if(!p||!l)return console.error(" error: --org and --repo must be passed together."),1;let m=U();if(!m)return console.error(" error: --org/--repo needs auth \u2014 run `sootsim login` or set SOOTSIM_API_KEY."),1;let M=d||(m.kind==="session"?m.origin:"https://sootbean.com");try{g=await J({org:p,repo:l,origin:M,authHeader:K(m)})}catch(x){return console.error(` ${x.message}`),1}!g||g.length===0?console.log(` note: no org deck for ${p}/${l} \u2014 composing with the plan's copy/colors.`):console.log(` org deck: ${g.length} slide(s) from ${p}/${l}`)}try{let m=await ie(s,{simId:r,appTarget:a,deviceModel:c,captureOnly:h,composeOnly:P,orgDeckFrames:g});return console.log(` capture manifest: ${m.capture.manifestPath}`),m.compose?(console.log(` compose manifest: ${m.compose.manifestPath}`),console.log(` exports: ${m.compose.outputs.length}`)):console.log(" compose skipped"),0}catch(m){return console.error(` screenshots failed: ${m.message}`),1}}export{st as runScreenshots};
@@ -1,24 +1,24 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as oe,c as M,d as ae,e as F,f as ce,h as de,i as C,j as le,k as ue,l as pe,p as he,s as T,t as me,u as fe,v as ge,w as Se}from"./chunk-7FL2TKGB.js";import"./chunk-5MF7XOPR.js";import{a as se}from"./chunk-RHHCV6M4.js";import"./chunk-3Q7M3ATN.js";import{e as R}from"./chunk-QS37KABB.js";import"./chunk-YENFSYAG.js";import"./chunk-Q3UIMXJY.js";import"./chunk-QZAJOB4N.js";import"./chunk-SMMTE4QY.js";import{d as re}from"./chunk-MNMNX4O7.js";import"./chunk-T35Q6ZGG.js";import{a as Z,b as Q}from"./chunk-RV3WN4FQ.js";import"./chunk-R76YX6KD.js";import{a as te,b as ie}from"./chunk-36RF3WRB.js";import{a as ee}from"./chunk-YWUBSH2K.js";import{m as ne}from"./chunk-7ODTKW6U.js";import{A as P,B as K,C as V,D as U,F as G,G as q,H as z,I as X,J as Y,K as H,h as j,i as $,w as D,x as J}from"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";import{spawn as Qe}from"child_process";import k from"fs";import{createServer as et}from"http";import y from"path";import{WebSocket as m,WebSocketServer as tt}from"ws";import ye from"node:fs";import x from"node:path";var O=1;function xe(){return[Number(process.env.VITE_PORT_WEB||process.env.PORT||3e3),Number(process.env.VITE_PORT_ZERO||7849),Number(process.env.VITE_PORT_POSTGRES||7432),Number(process.env.VITE_PORT_R2||9500)].filter(o=>Number.isFinite(o)&&o>0)}var _=class{subscriptions=new Map;sessionsBySocket=new Map;allSockets=new Set;pendingPromptEchoes=new Map;pendingTurns=new Map;opts;constructor(e={}){this.opts=e}registerSocket(e){this.allSockets.add(e)}unregisterSocket(e){let t=this.sessionsBySocket.get(e);if(t){for(let i of t)this.decrementSubscription(i);this.sessionsBySocket.delete(e)}this.allSockets.delete(e)}async handleMessage(e,t){let i=t?.type;if(typeof i!="string"||!i.startsWith("agent:"))return!1;let s=t.id;try{let n=await this.dispatch(e,i,t);this.respond(e,s,n)}catch(n){n instanceof T?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await pe()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
3
- `)}}close(){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 F();case"agent:upsert-project":return M(i.input??{});case"agent:delete-project":return de(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return le(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-prompt":{let n=String(i.sessionId),a=C(n);if(!a)throw new T("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await fe(n,r),this.notePromptAccepted(n,r,a.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await ge(String(i.sessionId));let s=C(String(i.sessionId));return s&&this.broadcastSessionStatus(s),{ok:!0};case"agent:get-transcript":return this.getTranscript(String(i.sessionId));case"agent:get-paths":return this.getPaths();case"agent:subscribe-events":return this.subscribeSocket(e,String(i.sessionId));case"agent:unsubscribe-events":return this.unsubscribeSocket(e,String(i.sessionId));default:throw new T("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async doStartSession(e){if(!ae(e.projectId))throw new T("NO_PROJECT",`no project: ${e.projectId}`);let i=await me(e);return this.broadcastSessionStatus(i.session),i}async autoAttachForUrl(e){let t=e.bundleUrl??"",i=(()=>{try{return new URL(t).port||null}catch{return null}})();if(!i)return{project:null};let s=this.opts.getExcludePorts?.()??xe(),a=(await R({excludePorts:s})).find(d=>String(d.port)===i);if(!a||!a.cwd)return{project:null};let r=F().find(d=>d.cwd===a.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],a.bundleUrl,t]));return{project:M({cwd:a.cwd,name:a.projectName??x.basename(a.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[a.cwd],knownBundleUrls:c,framework:r?.framework??Oe(a.framework),bundleId:a.bundleId??r?.bundleId})}}getTranscript(e){let t=he(e);return ye.existsSync(t)?ye.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=oe();return{userDataDir:e,storeFile:x.join(e,"attached-projects.json"),sessionsDir:x.join(e,"sessions"),transcriptsDir:x.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let s=this.subscriptions.get(t);if(s)return s.refCount++,{ok:!0,refCount:s.refCount};let n=Se(t,a=>{let r=this.coalescePromptEcho(t,a);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),a.type==="turn-completed"){let c=C(t);if(c)try{ce(c.projectId,{usd:a.costUsd,ts:a.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
4
- `)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let a=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,a);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:a>1,pendingTurns:a,queueDepth:Math.max(0,a-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){ue(e,t);let i=C(e);i&&this.broadcastSessionStatus(i)}coalescePromptEcho(e,t){if(t.type!=="prompt-received")return t;let i=this.pendingPromptEchoes.get(e);if(!i||i.length===0)return t;for(;i.length>0&&Date.now()-i[0].sentAt>15e3;)i.shift();return i.length===0?(this.pendingPromptEchoes.delete(e),t):(i.shift(),i.length===0?this.pendingPromptEchoes.delete(e):this.pendingPromptEchoes.set(e,i),null)}consumeSettledTurn(e){let t=Math.max(0,(this.pendingTurns.get(e)??1)-1);return t>0?this.pendingTurns.set(e,t):this.pendingTurns.delete(e),t}clearPromptTracking(e){this.pendingPromptEchoes.delete(e),this.pendingTurns.delete(e)}fanOutEvent(e,t){let i=JSON.stringify({type:"agent:event",sessionId:e,event:t});for(let[s,n]of this.sessionsBySocket)if(n.has(e)&&s.readyState===O)try{s.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===O)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===O)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===O)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function Oe(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Be from"http";import Ne from"https";var W="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",_e=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function Le(o){let e=o.toLowerCase();for(let t of _e)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function be(o){let e=Le(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":W},...e?.headers}}var De=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"]),Ue={"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"},He=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function E(o){for(let[e,t]of Object.entries(Ue))o.setHeader(e,t)}function Me(o,e){let t=[],i=e;i?.code&&t.push(i.code),i?.message&&t.push(i.message),i?.cause?.code&&t.push(i.cause.code),i?.cause?.message&&t.push(i.cause.message);let n=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function Fe(o){let t=(Array.isArray(o)?o[0]:o)?.split(";",1)[0]?.trim().toLowerCase();return t?t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t==="application/x-www-form-urlencoded"||t==="application/xml"||t.endsWith("+xml")||t==="application/javascript"||t==="application/graphql":!1}function We(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(De.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?be(e):{"user-agent":W}),t}function je(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(He.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function ve(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function we(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Ae(o,e){if(o.method==="OPTIONS"){E(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){E(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{E(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n=We(o.headers,s),a;if(o.method!=="GET"&&o.method!=="HEAD"){let d=[];for await(let u of o)d.push(Buffer.isBuffer(u)?u:Buffer.from(u));if(d.length>0){let u=Buffer.concat(d);a=Fe(o.headers["content-type"])?u.toString("utf8"):u}}let r;try{r=await fetch(s.href,{method:o.method,headers:n,body:a,redirect:"follow"})}catch(d){E(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${Me(s.href,d)}`);return}r.headers.forEach((d,u)=>{let p=u.toLowerCase();p==="content-encoding"||p==="transfer-encoding"||p==="content-length"||p==="set-cookie"||p.startsWith("access-control-")||e.setHeader(u,d)}),E(e);let c=r.headers.getSetCookie?.()??[];c.length>0&&e.setHeader("x-sootsim-set-cookie",c.join(", ")),e.statusCode=r.status;let l=Buffer.from(await r.arrayBuffer());e.end(l)}function ke(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",s=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let a=n.protocol==="https:"?Ne:Be,r=je(o.headers,n),c=a.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:r},l=>{let d=Object.keys(l.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return c.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),o.pipe(c),!0}import{WebSocket as A,WebSocketServer as $e}from"ws";var Je="/__websocket-proxy",Ke=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 w(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as oe,c as H,d as ae,e as F,f as ce,h as de,i as C,j as le,k as ue,l as pe,p as me,s as T,t as he,u as fe,v as ge,w as Se}from"./chunk-V5TDYT4H.js";import"./chunk-TNCYQFCC.js";import{a as se}from"./chunk-VZ7VB7HX.js";import"./chunk-TM6NU7CC.js";import{e as R}from"./chunk-KAAYKAUG.js";import"./chunk-HN2Q2ZWT.js";import"./chunk-VC7MRZW7.js";import"./chunk-5PKIU2SG.js";import"./chunk-ZPDQ3S7P.js";import{d as re}from"./chunk-OL7HTJVC.js";import"./chunk-SK3UIUQL.js";import{a as Z,b as Q}from"./chunk-PWGYVHEW.js";import"./chunk-QEC2WZAU.js";import{a as te,b as ie}from"./chunk-4CLJIXM3.js";import{a as ee}from"./chunk-FY4TSSMQ.js";import{m as ne}from"./chunk-QGQRB6D2.js";import{A as P,B as K,C as V,D,F as G,G as q,H as z,I as X,J as Y,K as U,h as j,i as $,w as N,x as J}from"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import{spawn as Qe}from"child_process";import k from"fs";import{createServer as et}from"http";import y from"path";import{WebSocket as h,WebSocketServer as tt}from"ws";import ye from"node:fs";import _ from"node:path";var O=1;function _e(){return[Number(process.env.VITE_PORT_WEB||process.env.PORT||3e3),Number(process.env.VITE_PORT_ZERO||7849),Number(process.env.VITE_PORT_POSTGRES||7432),Number(process.env.VITE_PORT_R2||9500)].filter(o=>Number.isFinite(o)&&o>0)}var x=class{subscriptions=new Map;sessionsBySocket=new Map;allSockets=new Set;pendingPromptEchoes=new Map;pendingTurns=new Map;opts;constructor(e={}){this.opts=e}registerSocket(e){this.allSockets.add(e)}unregisterSocket(e){let t=this.sessionsBySocket.get(e);if(t){for(let i of t)this.decrementSubscription(i);this.sessionsBySocket.delete(e)}this.allSockets.delete(e)}async handleMessage(e,t){let i=t?.type;if(typeof i!="string"||!i.startsWith("agent:"))return!1;let s=t.id;try{let n=await this.dispatch(e,i,t);this.respond(e,s,n)}catch(n){n instanceof T?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await pe()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
3
+ `)}}close(){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 F();case"agent:upsert-project":return H(i.input??{});case"agent:delete-project":return de(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return le(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-prompt":{let n=String(i.sessionId),a=C(n);if(!a)throw new T("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await fe(n,r),this.notePromptAccepted(n,r,a.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await ge(String(i.sessionId));let s=C(String(i.sessionId));return s&&this.broadcastSessionStatus(s),{ok:!0};case"agent:get-transcript":return this.getTranscript(String(i.sessionId));case"agent:get-paths":return this.getPaths();case"agent:subscribe-events":return this.subscribeSocket(e,String(i.sessionId));case"agent:unsubscribe-events":return this.unsubscribeSocket(e,String(i.sessionId));default:throw new T("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async doStartSession(e){if(!ae(e.projectId))throw new T("NO_PROJECT",`no project: ${e.projectId}`);let i=await he(e);return this.broadcastSessionStatus(i.session),i}async autoAttachForUrl(e){let t=e.bundleUrl??"",i=(()=>{try{return new URL(t).port||null}catch{return null}})();if(!i)return{project:null};let s=this.opts.getExcludePorts?.()??_e(),a=(await R({excludePorts:s})).find(d=>String(d.port)===i);if(!a||!a.cwd)return{project:null};let r=F().find(d=>d.cwd===a.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],a.bundleUrl,t]));return{project:H({cwd:a.cwd,name:a.projectName??_.basename(a.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[a.cwd],knownBundleUrls:c,framework:r?.framework??Oe(a.framework),bundleId:a.bundleId??r?.bundleId})}}getTranscript(e){let t=me(e);return ye.existsSync(t)?ye.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=oe();return{userDataDir:e,storeFile:_.join(e,"attached-projects.json"),sessionsDir:_.join(e,"sessions"),transcriptsDir:_.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let s=this.subscriptions.get(t);if(s)return s.refCount++,{ok:!0,refCount:s.refCount};let n=Se(t,a=>{let r=this.coalescePromptEcho(t,a);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),a.type==="turn-completed"){let c=C(t);if(c)try{ce(c.projectId,{usd:a.costUsd,ts:a.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
4
+ `)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let a=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,a);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:a>1,pendingTurns:a,queueDepth:Math.max(0,a-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){ue(e,t);let i=C(e);i&&this.broadcastSessionStatus(i)}coalescePromptEcho(e,t){if(t.type!=="prompt-received")return t;let i=this.pendingPromptEchoes.get(e);if(!i||i.length===0)return t;for(;i.length>0&&Date.now()-i[0].sentAt>15e3;)i.shift();return i.length===0?(this.pendingPromptEchoes.delete(e),t):(i.shift(),i.length===0?this.pendingPromptEchoes.delete(e):this.pendingPromptEchoes.set(e,i),null)}consumeSettledTurn(e){let t=Math.max(0,(this.pendingTurns.get(e)??1)-1);return t>0?this.pendingTurns.set(e,t):this.pendingTurns.delete(e),t}clearPromptTracking(e){this.pendingPromptEchoes.delete(e),this.pendingTurns.delete(e)}fanOutEvent(e,t){let i=JSON.stringify({type:"agent:event",sessionId:e,event:t});for(let[s,n]of this.sessionsBySocket)if(n.has(e)&&s.readyState===O)try{s.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===O)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===O)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===O)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function Oe(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Be from"http";import Me from"https";var W="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",xe=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function Le(o){let e=o.toLowerCase();for(let t of xe)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function be(o){let e=Le(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":W},...e?.headers}}var Ne=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"]),De={"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"},Ue=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function I(o){for(let[e,t]of Object.entries(De))o.setHeader(e,t)}function He(o,e){let t=[],i=e;i?.code&&t.push(i.code),i?.message&&t.push(i.message),i?.cause?.code&&t.push(i.cause.code),i?.cause?.message&&t.push(i.cause.message);let n=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function Fe(o){let t=(Array.isArray(o)?o[0]:o)?.split(";",1)[0]?.trim().toLowerCase();return t?t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t==="application/x-www-form-urlencoded"||t==="application/xml"||t.endsWith("+xml")||t==="application/javascript"||t==="application/graphql":!1}function We(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Ne.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?be(e):{"user-agent":W}),t}function je(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Ue.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function ve(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function we(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Ae(o,e){if(o.method==="OPTIONS"){I(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){I(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{I(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n=We(o.headers,s),a;if(o.method!=="GET"&&o.method!=="HEAD"){let d=[];for await(let u of o)d.push(Buffer.isBuffer(u)?u:Buffer.from(u));if(d.length>0){let u=Buffer.concat(d);a=Fe(o.headers["content-type"])?u.toString("utf8"):u}}let r;try{r=await fetch(s.href,{method:o.method,headers:n,body:a,redirect:"follow"})}catch(d){I(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${He(s.href,d)}`);return}r.headers.forEach((d,u)=>{let p=u.toLowerCase();p==="content-encoding"||p==="transfer-encoding"||p==="content-length"||p==="set-cookie"||p.startsWith("access-control-")||e.setHeader(u,d)}),I(e);let c=r.headers.getSetCookie?.()??[];c.length>0&&e.setHeader("x-sootsim-set-cookie",c.join(", ")),e.statusCode=r.status;let l=Buffer.from(await r.arrayBuffer());e.end(l)}function ke(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",s=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let a=n.protocol==="https:"?Me:Be,r=je(o.headers,n),c=a.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:r},l=>{let d=Object.keys(l.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return c.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),o.pipe(c),!0}import{WebSocket as A,WebSocketServer as $e}from"ws";var Je="/__websocket-proxy",Ke=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 w(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
5
5
  Connection: close\r
6
6
  Content-Type: text/plain\r
7
7
  Content-Length: ${t.length}\r
8
8
  \r
9
- ${t}`)}catch{}o.destroy()}function Ve(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 Ge(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,a]of Object.entries(i))a!=null&&(Ke.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function qe(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function ze(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function L(o,e,t){if(!(o.readyState===A.CLOSED||o.readyState===A.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function Xe(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,L(n,a,r.toString()),s.readyState===A.OPEN&&L(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===A.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===A.OPEN&&o.send(s,{binary:n})}),o.on("close",(s,n)=>i(o,e,s,n)),e.on("close",(s,n)=>i(e,o,s,n)),o.on("error",()=>L(e,1011,"proxy client error")),e.on("error",()=>L(o,1011,"upstream websocket error"))}function Ye(o,e,t){let i={...t};return Object.keys(i).some(s=>s.toLowerCase()==="origin")||(i.origin=qe(o)),new A(o.href,e,{headers:i})}function Ze(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===Je}catch{return!1}}function Ce(o,e,t){if(!Ze(o.url))return!1;if(!Ve(o))return w(e,403,"forbidden websocket proxy origin"),!0;let i,s;try{let c=new URL(o.url||"/","http://localhost"),l=c.searchParams.get("url");if(!l)return w(e,400,"missing websocket proxy url"),!0;if(i=new URL(l),i.protocol!=="ws:"&&i.protocol!=="wss:")return w(e,400,"invalid websocket proxy protocol"),!0;s=Ge(c.searchParams.get("headers"))}catch{return w(e,400,"invalid websocket proxy request"),!0}let n=ze(o),a=Ye(i,n,s),r=!1;return e.once("close",()=>{r||a.terminate()}),a.once("open",()=>{if(r)return;r=!0;let c=a.protocol;new $e({noServer:!0,clientTracking:!1,handleProtocols(d){return c||d.values().next().value||!1}}).handleUpgrade(o,e,t,d=>{Xe(d,a)})}),a.once("error",()=>{r||(r=!0,w(e,502,"upstream websocket error"))}),a.once("close",()=>{r||(r=!0,w(e,502,"upstream websocket closed"))}),!0}var it=new Set(["tap","keyboard"]),rt=2e3,nt=1e3;function st(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:it.has(o.type)}var ot=5e3,at=3600*1e3,ct="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",dt={".html":"text/html; charset=utf-8",".js":"application/javascript",".cjs":"application/javascript",".mjs":"application/javascript",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json",".txt":"text/plain; charset=utf-8"};function Te(o,e,t){let i;try{let c=D();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimSootbeanOrigin=${JSON.stringify(t)};`:"",a=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(ee())};</script>`,r=o.toString("utf8");return r.includes("<head>")?r.replace("<head>",`<head>${a}`):r.includes("</head>")?r.replace("</head>",a+"</head>"):r.includes("</body>")?r.replace("</body>",a+"</body>"):a+r}function Ee(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var B=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;preferredPort;portFallbackCount;simIdleReapTtlMs;shouldWriteLockfile;sootbeanOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=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.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new _({getExcludePorts:e.agentScanExcludes}),this.sootbeanOrigin=e.sootbeanOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??o.SIM_IDLE_REAP_TTL_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)
9
+ ${t}`)}catch{}o.destroy()}function Ve(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 Ge(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,a]of Object.entries(i))a!=null&&(Ke.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function qe(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function ze(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function L(o,e,t){if(!(o.readyState===A.CLOSED||o.readyState===A.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function Xe(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,L(n,a,r.toString()),s.readyState===A.OPEN&&L(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===A.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===A.OPEN&&o.send(s,{binary:n})}),o.on("close",(s,n)=>i(o,e,s,n)),e.on("close",(s,n)=>i(e,o,s,n)),o.on("error",()=>L(e,1011,"proxy client error")),e.on("error",()=>L(o,1011,"upstream websocket error"))}function Ye(o,e,t){let i={...t};return Object.keys(i).some(s=>s.toLowerCase()==="origin")||(i.origin=qe(o)),new A(o.href,e,{headers:i})}function Ze(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===Je}catch{return!1}}function Ce(o,e,t){if(!Ze(o.url))return!1;if(!Ve(o))return w(e,403,"forbidden websocket proxy origin"),!0;let i,s;try{let c=new URL(o.url||"/","http://localhost"),l=c.searchParams.get("url");if(!l)return w(e,400,"missing websocket proxy url"),!0;if(i=new URL(l),i.protocol!=="ws:"&&i.protocol!=="wss:")return w(e,400,"invalid websocket proxy protocol"),!0;s=Ge(c.searchParams.get("headers"))}catch{return w(e,400,"invalid websocket proxy request"),!0}let n=ze(o),a=Ye(i,n,s),r=!1;return e.once("close",()=>{r||a.terminate()}),a.once("open",()=>{if(r)return;r=!0;let c=a.protocol;new $e({noServer:!0,clientTracking:!1,handleProtocols(d){return c||d.values().next().value||!1}}).handleUpgrade(o,e,t,d=>{Xe(d,a)})}),a.once("error",()=>{r||(r=!0,w(e,502,"upstream websocket error"))}),a.once("close",()=>{r||(r=!0,w(e,502,"upstream websocket closed"))}),!0}var it=new Set(["tap","keyboard"]),rt=2e3,nt=1e3;function st(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:it.has(o.type)}var ot=5e3,at=3600*1e3,ct="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",dt={".html":"text/html; charset=utf-8",".js":"application/javascript",".cjs":"application/javascript",".mjs":"application/javascript",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".ttf":"font/ttf",".otf":"font/otf",".woff":"font/woff",".woff2":"font/woff2",".map":"application/json",".txt":"text/plain; charset=utf-8"};function Te(o,e,t){let i;try{let c=N();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimSootbeanOrigin=${JSON.stringify(t)};`:"",a=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(ee())};</script>`,r=o.toString("utf8");return r.includes("<head>")?r.replace("<head>",`<head>${a}`):r.includes("</head>")?r.replace("</head>",a+"</head>"):r.includes("</body>")?r.replace("</body>",a+"</body>"):a+r}function Ie(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var B=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;sootbeanOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=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.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new x({getExcludePorts:e.agentScanExcludes}),this.sootbeanOrigin=e.sootbeanOrigin?.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)
10
10
  `),this.afterBind(),i}catch(s){if(s?.code!=="EADDRINUSE")throw s;e?.silent||process.stderr.write(`ws bridge port ${i} already in use, trying ${i+1}
11
11
  `)}}throw new Error(`could not bind ws bridge after ${this.portFallbackCount} attempts starting at ${this.preferredPort}`)}bindOnce(e,t){return new Promise((i,s)=>{let n=et((c,l)=>this.handleHttpRequest(c,l)),a=!1,r=c=>{if(!a){a=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,s(c)}};n.once("error",r),n.listen(e,"127.0.0.1",()=>{a||(a=!0,n.removeListener("error",r),n.on("error",c=>{process.stderr.write(`ws bridge http error: ${String(c)}
12
- `)}),this.httpServer=n,this.wss=new tt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,l,d)=>{Ce(c,l,d)||this.wss?.handleUpgrade(c,l,d,u=>{this.wss?.emit("connection",u,c)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,s=i?"sim":"cli",n=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),s==="sim")n={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(n.id,n),this.shouldPromoteSim(n)&&(this.primarySimId=n.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let a=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,a)}e.on("message",a=>{let r;try{r=JSON.parse(a.toString())}catch{return}if(!(!r||typeof r!="object")){if(typeof r.type=="string"&&r.type.startsWith("agent:")){this.agentHost.handleMessage(e,r);return}if(r.type==="runtime:list"){let c=U(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:r.id,installed:c,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(r.type==="runtime:use"){let c=typeof r.version=="string"?r.version:"";if(!U().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=J(d)}catch(h){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${h instanceof Error?h.message:String(h)}
13
- `);return}let p=JSON.stringify({type:"bridge:shared-config-changed",config:u});for(let h of this.sims.values())if(h.ws.readyState===m.OPEN)try{h.ws.send(p)}catch{}return}if(r.type==="bridge:open-path"){let d=typeof r.path=="string"?r.path:"",u=typeof r.line=="number"&&Number.isFinite(r.line)?r.line:void 0,p=typeof r.column=="number"&&Number.isFinite(r.column)?r.column:void 0;d&&this.openPathInEditor(d,u,p);return}if(r.type==="bridge:boot-clients"&&n){let d=[];for(let[p,h]of this.cliSimBySocket)h===n.id&&d.push(p);for(let p of d){this.cliSimBySocket.delete(p);try{p.close(1e3,"booted by sim")}catch{}}let u=!!n.cliLease;n.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`sootsim booted ${d.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
14
- `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let c=this.pendingCommands.get(r.id);if(c){this.pendingCommands.delete(r.id),r.error?c.reject(new Error(r.error)):c.resolve(r.result);return}let l=this.cliBySentId.get(r.id);if(l&&(this.cliBySentId.delete(r.id),l.ws.readyState===m.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...r,id:l.originalId,_otherCliCount:d}:{...r,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[h,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(h);p&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let p=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:p,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:open"){if(typeof r.url!="string"||!r.url)throw new Error("bridge:open requires a url");await this.openUrl(r.url,{newWindow:r.newWindow===!0}),e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,result:{ok:!0,url:r.url}}));return}if(r.type==="bridge:claim"){let p=await this.waitForSim(r.simId),h=this.tryAcquireLease(e,p,{force:r.force===!0});if(!h.granted){e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${p.id} is locked by another cli`,_locked:h.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,h.bootedCount>0?`cli force-claimed sim (booted ${h.bootedCount})`:"cli claimed sim"),e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:p.id,lockedBy:h.lease.cliIdentityKey,lockExpiresAt:h.lease.expiresAt,bootedCount:h.bootedCount}}));return}let c=await this.waitForSim(r.simId);if(st(r)){let p=this.tryAcquireLease(e,c);if(!p.granted){e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${c.id} is locked by another cli \u2014 use \`sootsim claim ${c.id} --force\` or \`sootsim open --new\``,_locked:p.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,c.id),this.recordSimAction(c.id,this.describeForwardedCommand(r));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:c.id,ws:e,originalId:r.id});let{simId:d,...u}=r;if(c.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:c.id}}));let p=c.ws,h=setTimeout(()=>{this.closeSimSocketFromHost(p)},rt);Ee(h)}}catch(c){e.readyState===m.OPEN&&e.send(JSON.stringify({id:r.id,error:c instanceof Error?c.message:String(c)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[a,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(a));for(let[a,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===m.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(a));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let a=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,c]of this.cliBySentId)c.ws===e&&this.cliBySentId.delete(r);a&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
12
+ `)}),this.httpServer=n,this.wss=new tt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,l,d)=>{Ce(c,l,d)||this.wss?.handleUpgrade(c,l,d,u=>{this.wss?.emit("connection",u,c)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,s=i?"sim":"cli",n=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),s==="sim")n={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(n.id,n),this.shouldPromoteSim(n)&&(this.primarySimId=n.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let a=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,a)}e.on("message",a=>{let r;try{r=JSON.parse(a.toString())}catch{return}if(!(!r||typeof r!="object")){if(typeof r.type=="string"&&r.type.startsWith("agent:")){this.agentHost.handleMessage(e,r);return}if(r.type==="runtime:list"){let c=D(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:r.id,installed:c,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(r.type==="runtime:use"){let c=typeof r.version=="string"?r.version:"";if(!D().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=J(d)}catch(m){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${m instanceof Error?m.message:String(m)}
13
+ `);return}let p=JSON.stringify({type:"bridge:shared-config-changed",config:u});for(let m of this.sims.values())if(m.ws.readyState===h.OPEN)try{m.ws.send(p)}catch{}return}if(r.type==="bridge:open-path"){let d=typeof r.path=="string"?r.path:"",u=typeof r.line=="number"&&Number.isFinite(r.line)?r.line:void 0,p=typeof r.column=="number"&&Number.isFinite(r.column)?r.column:void 0;d&&this.openPathInEditor(d,u,p);return}if(r.type==="bridge:boot-clients"&&n){let d=[];for(let[p,m]of this.cliSimBySocket)m===n.id&&d.push(p);for(let p of d){this.cliSimBySocket.delete(p);try{p.close(1e3,"booted by sim")}catch{}}let u=!!n.cliLease;n.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`sootsim booted ${d.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
14
+ `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let c=this.pendingCommands.get(r.id);if(c){this.pendingCommands.delete(r.id),r.error?c.reject(new Error(r.error)):c.resolve(r.result);return}let l=this.cliBySentId.get(r.id);if(l&&(this.cliBySentId.delete(r.id),l.ws.readyState===h.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...r,id:l.originalId,_otherCliCount:d}:{...r,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[m,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(m);p&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let p=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:p,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:open"){if(typeof r.url!="string"||!r.url)throw new Error("bridge:open requires a url");await this.openUrl(r.url,{newWindow:r.newWindow===!0}),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{ok:!0,url:r.url}}));return}if(r.type==="bridge:claim"){let p=await this.waitForSim(r.simId),m=this.tryAcquireLease(e,p,{force:r.force===!0});if(!m.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${p.id} is locked by another cli`,_locked:m.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,m.bootedCount>0?`cli force-claimed sim (booted ${m.bootedCount})`:"cli claimed sim"),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:p.id,lockedBy:m.lease.cliIdentityKey,lockExpiresAt:m.lease.expiresAt,bootedCount:m.bootedCount}}));return}let c=await this.waitForSim(r.simId);if(st(r)){let p=this.tryAcquireLease(e,c);if(!p.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${c.id} is locked by another cli \u2014 use \`sootsim claim ${c.id} --force\` or \`sootsim open --new\``,_locked:p.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,c.id),this.recordSimAction(c.id,this.describeForwardedCommand(r));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:c.id,ws:e,originalId:r.id});let{simId:d,...u}=r;if(c.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:c.id}}));let p=c.ws,m=setTimeout(()=>{this.closeSimSocketFromHost(p)},rt);Ie(m)}}catch(c){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:c instanceof Error?c.message:String(c)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[a,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(a));for(let[a,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===h.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(a));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let a=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,c]of this.cliBySentId)c.ws===e&&this.cliBySentId.delete(r);a&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
15
15
  `),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(P(),!Y(this.buildLockfileSnapshot()))throw new Error("another sootsim daemon wrote the lockfile during startup \u2014 aborting")}catch(e){throw process.stderr.write(`ws bridge failed to claim daemon lockfile: ${String(e)}
16
16
  `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},ot),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}this.agentHost.seedOnBoot()}bootstrapping=!0;buildLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,activeRuntimeDir:this.activeRuntimeDirPath,startedAt:this.startedAt,heartbeatAt:Date.now(),bootstrapping:this.bootstrapping}}writeLockfileSnapshot(){X(this.buildLockfileSnapshot())}refreshActiveRuntime(){this.activeRuntimeVersion=K(),this.activeRuntimeDirPath=G()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=R({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("[sootsim] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<o.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[ct]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):at}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer)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(`sootsim: checking for runtime updates\u2026
17
17
  `);let t=await ne();if(!t.updated||!t.latestVersion){e==="startup"&&process.stderr.write(`sootsim: runtime ${this.activeRuntimeVersion??"(none)"} is current
18
18
  `);return}let i=this.setActiveRuntime(t.latestVersion);process.stderr.write(`sootsim runtime updated to ${i.version} (${e})
19
19
  `)}catch(t){process.stderr.write(`sootsim runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
20
20
  `)}finally{if(this.runtimeUpdateInFlight=null,e==="startup"&&this.bootstrapping){if(this.bootstrapping=!1,this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}process.stderr.write(`sootsim: ready
21
- `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(V(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())if(i.ws.readyState===m.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{H()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy","credentialless"),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),ve(e.url)){Ae(e,t);return}if(we(e.url)&&ke(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let h=await fetch(d.toString(),{redirect:"follow"}),f={},S=h.headers.get("content-type");if(S&&(f["Content-Type"]=S),f["Cache-Control"]="no-store",t.writeHead(h.status,f),!h.body){t.end();return}let g=h.body.getReader();for(;;){let{done:b,value:v}=await g.read();if(b)break;t.write(Buffer.from(v))}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(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(D())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of a.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=y.resolve(n,"."+a),c=n.endsWith(y.sep)?n:n+y.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}k.realpath(r,(l,d)=>{let u=l?r:d,p=u.endsWith(y.sep)?u:u+y.sep;if(!l){let h=(()=>{try{let f=k.realpathSync(n);return f.endsWith(y.sep)?f:f+y.sep}catch{return c}})();if(!p.startsWith(h)&&u+y.sep!==h){t.writeHead(403),t.end("forbidden");return}}k.stat(u,(h,f)=>{if(h||!f?.isFile()){let v=y.extname(a).toLowerCase();if(v&&v!==".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 N=y.join(n,"index.html");k.readFile(N,(Pe,Re)=>{if(Pe){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(Te(Re,this.effectivePort,this.sootbeanOrigin))});return}let S=y.extname(u).toLowerCase(),g=dt[S]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(S===".html"){k.readFile(u,(v,N)=>{if(v){try{t.end()}catch{}return}t.end(Te(N,this.effectivePort,this.sootbeanOrigin))});return}let b=k.createReadStream(u);b.pipe(t),b.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,s]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(!(e-n<o.CLI_IDLE_TIMEOUT_MS)){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[a,r]of this.cliBySentId)r.ws===i&&this.cliBySentId.delete(a);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values());for(let i of this.sims.values()){if(i.id===this.primarySimId||t.has(i.id)||this.getActiveLease(i))continue;let s=Math.max(i.lastActiveAt,i.connectedAt);e-s<this.simIdleReapTtlMs||this.closeSimSocketFromHost(i.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==m.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!==m.OPEN)return;try{e.close(te,ie)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==m.CLOSED)try{e.terminate()}catch{}},nt);Ee(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let a=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,a=(c,l)=>new Promise(d=>{try{let u=Qe(c,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await a(c[0],[...c.slice(1),"-g",n]))return}await a("cursor",["-g",n])||await a("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await re(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{H()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=m.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===m.OPEN?"open":t===m.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),a=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-a)},bootedCount:0};if(r&&!c&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let h=this.cliIdentityKeyBySocket.get(u);if(h&&h!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,a=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===a||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=a,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let s=this.sims.get(e);return s?.ws.readyState===m.OPEN?s:null}let t=this.primarySimId!=null?this.sims.get(this.primarySimId):null;if(t?.ws.readyState===m.OPEN&&t.url)return t;let i=null;for(let s of this.sims.values())if(s.ws.readyState===m.OPEN){if(s.url)return s;i??=s}return t?.ws.readyState===m.OPEN?t:i}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let n=0;n<i;n++){let a=this.getOpenSim(e);if(a)return a;await new Promise(r=>setTimeout(r,s))}throw new Error(e?`no sim connected with id ${e}`:"no sim connected")}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===m.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===m.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==m.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let a=Date.now();n.lastActiveAt=a,n.recentActions=[{label:s,at:a},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==m.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,a]of this.cliSimBySocket){if(a!==t||n.readyState!==m.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===m.OPEN)return!1;let n=this.getRestorableSimState(i),a=e.id;this.sims.delete(a),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===a&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===a&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id)}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function Ie(){let o=process.env.XPC_SERVICE_NAME||"";return!!(o.includes("dev.sootsim.daemon")||o.includes("dev.sootsim.server")||process.env.INVOCATION_ID)}async function $t(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
21
+ `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(V(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())if(i.ws.readyState===h.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{U()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy","credentialless"),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),ve(e.url)){Ae(e,t);return}if(we(e.url)&&ke(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let m=await fetch(d.toString(),{redirect:"follow"}),f={},S=m.headers.get("content-type");if(S&&(f["Content-Type"]=S),f["Cache-Control"]="no-store",t.writeHead(m.status,f),!m.body){t.end();return}let g=m.body.getReader();for(;;){let{done:b,value:v}=await g.read();if(b)break;t.write(Buffer.from(v))}t.end()}catch(m){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${m instanceof Error?m.message:String(m)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(N())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of a.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=y.resolve(n,"."+a),c=n.endsWith(y.sep)?n:n+y.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}k.realpath(r,(l,d)=>{let u=l?r:d,p=u.endsWith(y.sep)?u:u+y.sep;if(!l){let m=(()=>{try{let f=k.realpathSync(n);return f.endsWith(y.sep)?f:f+y.sep}catch{return c}})();if(!p.startsWith(m)&&u+y.sep!==m){t.writeHead(403),t.end("forbidden");return}}k.stat(u,(m,f)=>{if(m||!f?.isFile()){let v=y.extname(a).toLowerCase();if(v&&v!==".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 M=y.join(n,"index.html");k.readFile(M,(Pe,Re)=>{if(Pe){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(Te(Re,this.effectivePort,this.sootbeanOrigin))});return}let S=y.extname(u).toLowerCase(),g=dt[S]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(S===".html"){k.readFile(u,(v,M)=>{if(v){try{t.end()}catch{}return}t.end(Te(M,this.effectivePort,this.sootbeanOrigin))});return}let b=k.createReadStream(u);b.pipe(t),b.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,s]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(!(e-n<o.CLI_IDLE_TIMEOUT_MS)){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[a,r]of this.cliBySentId)r.ws===i&&this.cliBySentId.delete(a);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"}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n),l=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=l){this.closeSimSocketFromHost(n.ws);continue}c&&i.push({sim:n,idleMs:r})}let s=this.maxConcurrentAutomationSims;if(i.length>s){i.sort((n,a)=>a.idleMs-n.idleMs);for(let{sim:n,idleMs:a}of i.slice(0,i.length-s))a<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(n.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==h.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!==h.OPEN)return;try{e.close(te,ie)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},nt);Ie(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let a=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,a=(c,l)=>new Promise(d=>{try{let u=Qe(c,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await a(c[0],[...c.slice(1),"-g",n]))return}await a("cursor",["-g",n])||await a("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await re(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{U()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=h.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===h.OPEN?"open":t===h.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),a=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-a)},bootedCount:0};if(r&&!c&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,a=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===a||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=a,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let s=this.sims.get(e);return s?.ws.readyState===h.OPEN?s:null}let t=this.primarySimId!=null?this.sims.get(this.primarySimId):null;if(t?.ws.readyState===h.OPEN&&t.url)return t;let i=null;for(let s of this.sims.values())if(s.ws.readyState===h.OPEN){if(s.url)return s;i??=s}return t?.ws.readyState===h.OPEN?t:i}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let n=0;n<i;n++){let a=this.getOpenSim(e);if(a)return a;await new Promise(r=>setTimeout(r,s))}throw new Error(e?`no sim connected with id ${e}`:"no sim connected")}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===h.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===h.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==h.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let a=Date.now();n.lastActiveAt=a,n.recentActions=[{label:s,at:a},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==h.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,a]of this.cliSimBySocket){if(a!==t||n.readyState!==h.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===h.OPEN)return!1;let n=this.getRestorableSimState(i),a=e.id;this.sims.delete(a),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===a&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===a&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id)}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function Ee(){let o=process.env.XPC_SERVICE_NAME||"";return!!(o.includes("dev.sootsim.daemon")||o.includes("dev.sootsim.server")||process.env.INVOCATION_ID)}async function $t(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
22
22
  sootsim server \u2014 run the sootsim bridge daemon in the foreground
23
23
 
24
24
  hosts the WS bridge that CLI commands talk to. once running, any sootsim
@@ -35,6 +35,6 @@ options:
35
35
  examples:
36
36
  sootsim server
37
37
  sootsim server --port 7668 --quiet
38
- `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q");if($()){let f=j()?"this is a dev workstation (IS_TAMAGUI_DEV=1)":"this is a dev checkout";if(console.error(` refusing to run a standalone sootsim daemon \u2014 ${f}.`),console.error(` the live \`bun dev\` stack already hosts the bridge on :${7668}; a`),console.error(" standalone server would shadow it on a fallback port and serve the stale"),console.error(" published runtime. set SOOTSIM_FORCE_DAEMON_INSTALL=1 to run it anyway."),Ie()){console.error(" uninstalling the persistent agent so it stops respawning here...");try{let{runDaemon:S}=await import("./daemon-KRESTNSO.js");await S(["uninstall"],{port:i})}catch(S){console.error(` (uninstall failed: ${S instanceof Error?S.message:String(S)})`),console.error(" run `sootsim daemon uninstall` manually to stop it.")}}process.exit(0)}let n=q();n&&z(n)&&(console.error(` a sootsim daemon is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),P();let a=await se(),r=new B({port:i,writeLockfile:!0,sootbeanOrigin:a}),c=await r.startAsync({silent:s}),l=Date.now(),d=f=>{s||process.stdout.write(`${f}
39
- `)},u=new Set,p=setInterval(()=>{let f=r.listSims(),S=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)";d(` + ${g.id} ${b}`)}for(let g of u)S.has(g)||d(` - ${g}`);u.clear();for(let g of S)u.add(g)},500);Z({event:"daemon_heartbeat",properties:{bridge_port:c,under_daemon:Ie(),platform:process.platform,subsource:"daemon"}}),Q(),d(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${c})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let h=async f=>{clearInterval(p),d(`
40
- ${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>h("SIGINT")),process.on("SIGTERM",()=>h("SIGTERM")),process.on("SIGHUP",()=>h("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{$t as runServer};
38
+ `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q");if($()){let f=j()?"this is a dev workstation (IS_TAMAGUI_DEV=1)":"this is a dev checkout";if(console.error(` refusing to run a standalone sootsim daemon \u2014 ${f}.`),console.error(` the live \`bun dev\` stack already hosts the bridge on :${7668}; a`),console.error(" standalone server would shadow it on a fallback port and serve the stale"),console.error(" published runtime. set SOOTSIM_FORCE_DAEMON_INSTALL=1 to run it anyway."),Ee()){console.error(" uninstalling the persistent agent so it stops respawning here...");try{let{runDaemon:S}=await import("./daemon-7GPY5B63.js");await S(["uninstall"],{port:i})}catch(S){console.error(` (uninstall failed: ${S instanceof Error?S.message:String(S)})`),console.error(" run `sootsim daemon uninstall` manually to stop it.")}}process.exit(0)}let n=q();n&&z(n)&&(console.error(` a sootsim daemon is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),P();let a=await se(),r=new B({port:i,writeLockfile:!0,sootbeanOrigin:a}),c=await r.startAsync({silent:s}),l=Date.now(),d=f=>{s||process.stdout.write(`${f}
39
+ `)},u=new Set,p=setInterval(()=>{let f=r.listSims(),S=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)";d(` + ${g.id} ${b}`)}for(let g of u)S.has(g)||d(` - ${g}`);u.clear();for(let g of S)u.add(g)},500);Z({event:"daemon_heartbeat",properties:{bridge_port:c,under_daemon:Ee(),platform:process.platform,subsource:"daemon"}}),Q(),d(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${c})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let m=async f=>{clearInterval(p),d(`
40
+ ${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{$t as runServer};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a}from"./chunk-ZU5S3Z7A.js";import"./chunk-BDLFGAKU.js";import"./chunk-DO2Z5CNM.js";import"./chunk-VC7MRZW7.js";import"./chunk-SK3UIUQL.js";import"./chunk-PWGYVHEW.js";import"./chunk-QEC2WZAU.js";import"./chunk-4CLJIXM3.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";export{a as runSetupRepo};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import"./chunk-A27TUQQZ.js";import*as l from"fs";import*as i from"path";import{fileURLToPath as f}from"url";function g(){try{let s=f(import.meta.resolve("sootsim/package.json"));return i.join(i.dirname(s),"skills")}catch{let s=i.dirname(f(import.meta.url));return i.resolve(s,"../../skills")}}var m=g();function d(s){let n=s.match(/^---\n([\s\S]*?)\n---/);if(!n)return null;let e=n[1],o=e.match(/^name:\s*(.+)$/m),r=e.match(/^description:\s*(.+)$/m);return o?{name:o[1].trim(),description:r?.[1]?.trim()||""}:null}function p(){if(!l.existsSync(m))return[];let s=l.readdirSync(m).filter(e=>e.endsWith(".md")),n=[];for(let e of s){let o=l.readFileSync(i.join(m,e),"utf8"),r=d(o);r&&n.push({...r,filename:e})}return n}function u(s,n){let e=i.join(m,s.filename),o=i.join(n,s.filename);l.copyFileSync(e,o),console.log(` copied ${s.name} \u2192 ${o}`)}async function h(s){if(s.includes("--list")||s.includes("-l")||s.length===0){let t=p();if(t.length===0){console.log(" no skills found");return}console.log(`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import"./chunk-ZO7E7WE5.js";import*as l from"fs";import*as i from"path";import{fileURLToPath as f}from"url";function g(){try{let s=f(import.meta.resolve("sootsim/package.json"));return i.join(i.dirname(s),"skills")}catch{let s=i.dirname(f(import.meta.url));return i.resolve(s,"../../skills")}}var m=g();function d(s){let n=s.match(/^---\n([\s\S]*?)\n---/);if(!n)return null;let e=n[1],o=e.match(/^name:\s*(.+)$/m),r=e.match(/^description:\s*(.+)$/m);return o?{name:o[1].trim(),description:r?.[1]?.trim()||""}:null}function p(){if(!l.existsSync(m))return[];let s=l.readdirSync(m).filter(e=>e.endsWith(".md")),n=[];for(let e of s){let o=l.readFileSync(i.join(m,e),"utf8"),r=d(o);r&&n.push({...r,filename:e})}return n}function u(s,n){let e=i.join(m,s.filename),o=i.join(n,s.filename);l.copyFileSync(e,o),console.log(` copied ${s.name} \u2192 ${o}`)}async function h(s){if(s.includes("--list")||s.includes("-l")||s.length===0){let t=p();if(t.length===0){console.log(" no skills found");return}console.log(`
3
3
  available skills:
4
4
  `);for(let c of t)console.log(` ${c.name}`),console.log(` ${c.description}
5
5
  `);console.log(" usage: sootsim skills <target-dir> [skill-name...]"),console.log(" example: sootsim skills ./my-project"),console.log(` example: sootsim skills ./my-project debug perf
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.145 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{c as S,e as y,g as v,h as b,i as u}from"./chunk-Q3UIMXJY.js";import"./chunk-T35Q6ZGG.js";import"./chunk-36RF3WRB.js";import"./chunk-ANTCWWXN.js";import"./chunk-A27TUQQZ.js";import{mkdirSync as $,writeFileSync as x}from"node:fs";import{dirname as k,isAbsolute as B,join as C,resolve as E}from"node:path";var z=`
1
+ /*! sootsim v0.1.147 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{c as S,e as y,g as v,h as b,i as u}from"./chunk-VC7MRZW7.js";import"./chunk-SK3UIUQL.js";import"./chunk-4CLJIXM3.js";import"./chunk-MCQIOGWG.js";import"./chunk-ZO7E7WE5.js";import{mkdirSync as $,writeFileSync as x}from"node:fs";import{dirname as k,isAbsolute as B,join as C,resolve as E}from"node:path";var z=`
3
3
  sootsim slides \u2014 compose App Store screenshots in the live sim
4
4
 
5
5
  usage: