sootsim 0.1.227 → 0.1.228

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 (175) hide show
  1. package/README.md +14 -14
  2. package/detox/element-types.ts +3 -3
  3. package/detox/expectations.ts +29 -24
  4. package/detox/gestures.ts +16 -16
  5. package/detox/index.ts +34 -32
  6. package/dist-cli/bin.js +4 -4
  7. package/dist-cli/chunks/{agent-HBVXCRJT.js → agent-6P5T2QHC.js} +2 -2
  8. package/dist-cli/chunks/{agent-wrapper-X376DPV2.js → agent-wrapper-SMEMJZXI.js} +2 -2
  9. package/dist-cli/chunks/{app-fonts-LIQTD5RP.js → app-fonts-6OQTLX3U.js} +2 -2
  10. package/dist-cli/chunks/{assert-X6PPLN72.js → assert-ZAYFOW6R.js} +2 -2
  11. package/dist-cli/chunks/{auth-INRWIM2C.js → auth-Y53UANSH.js} +2 -2
  12. package/dist-cli/chunks/beta-ZQCASJ7C.js +2 -0
  13. package/dist-cli/chunks/{camera-LGFHYCJ5.js → camera-AJQWSOO4.js} +2 -2
  14. package/dist-cli/chunks/{chunk-2BQOZATN.js → chunk-2I62CFYI.js} +3 -3
  15. package/dist-cli/chunks/{chunk-E3DLUOFK.js → chunk-34MFG4IM.js} +7 -7
  16. package/dist-cli/chunks/{chunk-J7IFVTWX.js → chunk-4A6HM2K3.js} +1 -1
  17. package/dist-cli/chunks/chunk-4QOY4T27.js +3 -0
  18. package/dist-cli/chunks/{chunk-HRYKZ5YY.js → chunk-6Q2B7QHC.js} +5 -5
  19. package/dist-cli/chunks/{chunk-F5HOYUD2.js → chunk-6U3GMNTP.js} +1 -1
  20. package/dist-cli/chunks/{chunk-RNWJQ4UR.js → chunk-72AQH53U.js} +1 -1
  21. package/dist-cli/chunks/{chunk-NIN75M5H.js → chunk-7HMRWJHH.js} +1 -1
  22. package/dist-cli/chunks/{chunk-YB2LM6VB.js → chunk-7TJVPCQA.js} +6 -6
  23. package/dist-cli/chunks/{chunk-LM544J6V.js → chunk-A5SO4OGE.js} +1 -1
  24. package/dist-cli/chunks/{chunk-D42IRY2Y.js → chunk-AJ3CDBW6.js} +2 -2
  25. package/dist-cli/chunks/chunk-ALE5MU5Z.js +2 -0
  26. package/dist-cli/chunks/{chunk-NHE3YHDU.js → chunk-AVS7RL73.js} +2 -2
  27. package/dist-cli/chunks/chunk-AWF575Y5.js +1 -0
  28. package/dist-cli/chunks/chunk-BHNOPI7I.js +2 -0
  29. package/dist-cli/chunks/{chunk-LCJSTEIR.js → chunk-D2QUTBZP.js} +2 -2
  30. package/dist-cli/chunks/{chunk-ESK7B2BQ.js → chunk-DEVNCWS4.js} +6 -6
  31. package/dist-cli/chunks/{chunk-GUCFICA4.js → chunk-E5FOMYR6.js} +1 -1
  32. package/dist-cli/chunks/{chunk-2XXPF6LP.js → chunk-EFMPSG7T.js} +2 -2
  33. package/dist-cli/chunks/{chunk-4J7BIXEB.js → chunk-EKWOBYJO.js} +2 -2
  34. package/dist-cli/chunks/{chunk-E75EBS77.js → chunk-EPQ5EZBJ.js} +2 -2
  35. package/dist-cli/chunks/{chunk-Q4FB222M.js → chunk-FDSFA7WL.js} +3 -3
  36. package/dist-cli/chunks/{chunk-UGWURWHN.js → chunk-FSKQZHM2.js} +2 -2
  37. package/dist-cli/chunks/{chunk-QWRYD2QV.js → chunk-G42TLJVQ.js} +18 -18
  38. package/dist-cli/chunks/{chunk-HXHB5A6R.js → chunk-JA52F67H.js} +2 -2
  39. package/dist-cli/chunks/chunk-JKZY5CPQ.js +2 -0
  40. package/dist-cli/chunks/{chunk-MG6JE3AM.js → chunk-JV43GSZB.js} +2 -2
  41. package/dist-cli/chunks/{chunk-7L5IKIHC.js → chunk-JWZMAJC7.js} +1 -1
  42. package/dist-cli/chunks/{chunk-F53C5HAB.js → chunk-KIL5F7KD.js} +1 -1
  43. package/dist-cli/chunks/chunk-KY2KLPYL.js +1 -0
  44. package/dist-cli/chunks/{chunk-DB3GMVOH.js → chunk-LBXHG4AU.js} +2 -2
  45. package/dist-cli/chunks/{chunk-SBIAPF6E.js → chunk-MCMMRIJV.js} +1 -1
  46. package/dist-cli/chunks/{chunk-A4BOYB55.js → chunk-MWZOCZ7J.js} +2 -2
  47. package/dist-cli/chunks/{chunk-HXSV263V.js → chunk-NCXHUU7N.js} +1 -1
  48. package/dist-cli/chunks/{chunk-HTVB3FW2.js → chunk-NME4QWJ3.js} +2 -2
  49. package/dist-cli/chunks/{chunk-J2JAOIMN.js → chunk-OETQYAI2.js} +2 -2
  50. package/dist-cli/chunks/chunk-PJBYZZWR.js +2 -0
  51. package/dist-cli/chunks/{chunk-NU755HCE.js → chunk-PNPH4JLS.js} +1 -1
  52. package/dist-cli/chunks/chunk-RT3OS624.js +118 -0
  53. package/dist-cli/chunks/{chunk-7LDHOQ7B.js → chunk-SACWV3LZ.js} +20 -20
  54. package/dist-cli/chunks/chunk-SPJSTRXX.js +24 -0
  55. package/dist-cli/chunks/{chunk-3L5EXWCP.js → chunk-UYLESZU3.js} +1 -1
  56. package/dist-cli/chunks/{chunk-XESYTWFM.js → chunk-WWZL7HNB.js} +29 -29
  57. package/dist-cli/chunks/{chunk-T6MEERRI.js → chunk-ZBJ5JMXM.js} +2 -2
  58. package/dist-cli/chunks/chunk-ZWJEJR73.js +4 -0
  59. package/dist-cli/chunks/cli-version-V4GJYM74.js +2 -0
  60. package/dist-cli/chunks/{compat-MH673TEJ.js → compat-W7E4744D.js} +3 -3
  61. package/dist-cli/chunks/{config-SSCDV5ZJ.js → config-N7G65EY2.js} +2 -2
  62. package/dist-cli/chunks/{control-54R2XDLV.js → control-7VDFEVWU.js} +2 -2
  63. package/dist-cli/chunks/daemon-UI3PQ47F.js +2 -0
  64. package/dist-cli/chunks/{debug-PFP646II.js → debug-ZKUCSCOU.js} +3 -3
  65. package/dist-cli/chunks/{desktop-BPYYJ3EM.js → desktop-L3OXTT45.js} +3 -3
  66. package/dist-cli/chunks/{detox-BIUVHXYH.js → detox-QG4IBZAG.js} +2 -2
  67. package/dist-cli/chunks/{device-BNSPNIP6.js → device-QC6MDI7W.js} +2 -2
  68. package/dist-cli/chunks/{diagnose-BPTDSGOB.js → diagnose-HTUDENJK.js} +2 -2
  69. package/dist-cli/chunks/drivers-L2BXXDI7.js +2 -0
  70. package/dist-cli/chunks/{film-ILA6VSOG.js → film-CT7FHNLE.js} +3 -3
  71. package/dist-cli/chunks/flow-XUBXWJHL.js +2 -0
  72. package/dist-cli/chunks/help-7CIGANJN.js +2 -0
  73. package/dist-cli/chunks/{hidden-runtime-alias-TD7IVAPF.js → hidden-runtime-alias-YTUEPZ3U.js} +2 -2
  74. package/dist-cli/chunks/{home-paths-H36JDTNO.js → home-paths-7K6HDXOP.js} +2 -2
  75. package/dist-cli/chunks/inspect-ZY3QI7VJ.js +2 -0
  76. package/dist-cli/chunks/install-desktop-CVPRYFFV.js +2 -0
  77. package/dist-cli/chunks/{login-5WGZX2ZD.js → login-XHOOXAOW.js} +4 -4
  78. package/dist-cli/chunks/{logout-V53WTVIZ.js → logout-7BISNC5F.js} +2 -2
  79. package/dist-cli/chunks/{maestro-HGKYRD54.js → maestro-YD3G7LSG.js} +3 -3
  80. package/dist-cli/chunks/{maestro-generate-6DNZSKDP.js → maestro-generate-WNOWZC5K.js} +3 -3
  81. package/dist-cli/chunks/{mode-YFMKORE5.js → mode-Y6JJMXU5.js} +2 -2
  82. package/dist-cli/chunks/optional-demo-registry-YUXURWKX.js +2 -0
  83. package/dist-cli/chunks/{perf-EOIGFDWM.js → perf-AY3ZKTDS.js} +2 -2
  84. package/dist-cli/chunks/{record-2F54QS6Y.js → record-ZC4W6QN6.js} +10 -10
  85. package/dist-cli/chunks/runtime-MVYAP3UX.js +2 -0
  86. package/dist-cli/chunks/screenshot-command-NRKTGTSJ.js +151 -0
  87. package/dist-cli/chunks/{screenshots-capture-DIICN24R.js → screenshots-capture-LZR3AHWN.js} +3 -3
  88. package/dist-cli/chunks/{serve-66NC6PPZ.js → serve-4X2WI5XF.js} +5 -5
  89. package/dist-cli/chunks/{setup-ZYN4BTBR.js → setup-KODPGJBJ.js} +3 -3
  90. package/dist-cli/chunks/{skills-MDBIER7U.js → skills-DEAUDOAN.js} +2 -2
  91. package/dist-cli/chunks/{storage-AQ3SEO4Y.js → storage-P7FQRH5T.js} +2 -2
  92. package/dist-cli/chunks/store-PTRXOHHV.js +2 -0
  93. package/dist-cli/chunks/telemetry-JHKOHSI2.js +2 -0
  94. package/dist-cli/chunks/{timeline-VEGHQZ36.js → timeline-7ISYXLR3.js} +2 -2
  95. package/dist-cli/chunks/{upgrade-RNDCRPLJ.js → upgrade-NZBJS5L2.js} +3 -3
  96. package/dist-cli/chunks/upload-J34H5SXV.js +2 -0
  97. package/dist-cli/chunks/{version-XUMPKQUM.js → version-J6BLGLTO.js} +2 -2
  98. package/dist-cli/chunks/{web-ESQGHVPD.js → web-Y6UVYM3Z.js} +2 -2
  99. package/dist-cli/chunks/{what-happened-6NJENKUF.js → what-happened-YKXXY6W2.js} +2 -2
  100. package/dist-lib/agent-daemon-client.cjs +1 -1
  101. package/dist-lib/agent-events.cjs +1 -1
  102. package/dist-lib/agent-identity.cjs +1 -1
  103. package/dist-lib/agent-sessions.cjs +1 -1
  104. package/dist-lib/attached-projects.cjs +1 -1
  105. package/dist-lib/auth/shared-session.cjs +2 -2
  106. package/dist-lib/backend-origin.cjs +18 -18
  107. package/dist-lib/beta.cjs +1 -1
  108. package/dist-lib/beta.mjs +1 -1
  109. package/dist-lib/bridge-constants.cjs +4 -4
  110. package/dist-lib/cli-constants.cjs +1 -1
  111. package/dist-lib/config.cjs +1 -1
  112. package/dist-lib/detox/index.cjs +321 -79
  113. package/dist-lib/dev-bundle-resolution.cjs +2 -2
  114. package/dist-lib/home-paths.cjs +1 -1
  115. package/dist-lib/host/bridge-host.cjs +18 -13
  116. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  117. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  118. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  119. package/dist-lib/host/websocket-proxy.cjs +1 -1
  120. package/dist-lib/index.cjs +1 -1
  121. package/dist-lib/jump-to-source-babel.cjs +1 -1
  122. package/dist-lib/menu.cjs +1 -1
  123. package/dist-lib/menu.mjs +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 +7 -7
  128. package/dist-lib/sdk.cjs +12 -4
  129. package/dist-lib/sdk.mjs +12 -4
  130. package/dist-lib/skills.cjs +425 -169
  131. package/dist-lib/vite.cjs +1 -1
  132. package/package.json +4 -4
  133. package/scripts/dev-server-scanner.ts +5 -5
  134. package/scripts/postinstall.cjs +1 -1
  135. package/scripts/preuninstall.cjs +1 -1
  136. package/skills/{soot → contrast}/SKILL.md +4 -4
  137. package/skills/sootsim-perf/SKILL.md +3 -1
  138. package/src/auth/shared-session.ts +1 -1
  139. package/src/backend-origin.ts +11 -11
  140. package/src/bridge-constants.ts +3 -3
  141. package/src/home-paths.ts +1 -1
  142. package/src/host/agent-host.ts +2 -2
  143. package/src/host/bridge-host.ts +21 -21
  144. package/src/native-dev-bundle-url.ts +3 -3
  145. package/src/runtime-assets.ts +3 -3
  146. package/src/runtime-delivery.ts +10 -4
  147. package/src/screenshots/compose.ts +4 -1
  148. package/src/screenshots/frame-compose.ts +4 -1
  149. package/src/screenshots/orchestrate.ts +7 -2
  150. package/src/vite-plugin-one.ts +3 -3
  151. package/src/vite-plugin.ts +3 -3
  152. package/dist-cli/chunks/beta-WLLSIVLW.js +0 -2
  153. package/dist-cli/chunks/chunk-35EAEAN4.js +0 -24
  154. package/dist-cli/chunks/chunk-44Z2X5R4.js +0 -2
  155. package/dist-cli/chunks/chunk-4BLOZ3AF.js +0 -2
  156. package/dist-cli/chunks/chunk-7K5K5NKB.js +0 -2
  157. package/dist-cli/chunks/chunk-7RWDQCIT.js +0 -1
  158. package/dist-cli/chunks/chunk-BVD2JFOX.js +0 -1
  159. package/dist-cli/chunks/chunk-HBEEYWK5.js +0 -2
  160. package/dist-cli/chunks/chunk-JNUGPBWC.js +0 -118
  161. package/dist-cli/chunks/chunk-KBSJA7HK.js +0 -3
  162. package/dist-cli/chunks/chunk-Z2E2DDIQ.js +0 -4
  163. package/dist-cli/chunks/cli-version-NNBCIQKL.js +0 -2
  164. package/dist-cli/chunks/daemon-GL5GQTWB.js +0 -2
  165. package/dist-cli/chunks/drivers-KBKJVF2Y.js +0 -2
  166. package/dist-cli/chunks/flow-L247VVBM.js +0 -2
  167. package/dist-cli/chunks/help-QIZEANNK.js +0 -2
  168. package/dist-cli/chunks/inspect-6OAVS27G.js +0 -2
  169. package/dist-cli/chunks/install-desktop-LKYAUUQY.js +0 -2
  170. package/dist-cli/chunks/optional-demo-registry-YGNESGBH.js +0 -2
  171. package/dist-cli/chunks/runtime-FYVV4DCQ.js +0 -2
  172. package/dist-cli/chunks/screenshot-command-R535TYXY.js +0 -151
  173. package/dist-cli/chunks/store-6ZGLOTZI.js +0 -2
  174. package/dist-cli/chunks/telemetry-V76UPVDV.js +0 -2
  175. package/dist-cli/chunks/upload-KRBS3Y7Q.js +0 -2
@@ -0,0 +1,151 @@
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as re,b as ne,f as se}from"./chunk-SACWV3LZ.js";import"./chunk-OETQYAI2.js";import{a as k}from"./chunk-4QOY4T27.js";import{b as Q}from"./chunk-WWZL7HNB.js";import{a as ee}from"./chunk-AJ3CDBW6.js";import"./chunk-34MFG4IM.js";import{a as te,b as oe}from"./chunk-ALE5MU5Z.js";import"./chunk-DEVNCWS4.js";import"./chunk-EKWOBYJO.js";import"./chunk-KY2KLPYL.js";import"./chunk-6Q2B7QHC.js";import"./chunk-NCXHUU7N.js";import"./chunk-FSKQZHM2.js";import"./chunk-PJBYZZWR.js";import"./chunk-UYLESZU3.js";import"./chunk-A5SO4OGE.js";import"./chunk-LBXHG4AU.js";import{r as K}from"./chunk-G42TLJVQ.js";import{g as A,h as X,i as R,j as J,k as Z,l as M,m as $}from"./chunk-SPJSTRXX.js";import"./chunk-KIL5F7KD.js";import"./chunk-BHNOPI7I.js";import"./chunk-2I62CFYI.js";import"./chunk-EFMPSG7T.js";import"./chunk-JV43GSZB.js";import"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import"./chunk-RT3OS624.js";import"./chunk-PNPH4JLS.js";import"./chunk-NME4QWJ3.js";import{a as x,b as j,c as I,d as L,e as U,f as F,g as E}from"./chunk-7HMRWJHH.js";import"./chunk-6U3GMNTP.js";import{mkdirSync as ce,writeFileSync as ie}from"fs";import{dirname as le,resolve as ue}from"path";async function de(e,t){let o=Le(e);(o.includes("--help")||o.includes("-h"))&&(console.log(`
3
+ sootsim screenshot \u2014 capture the canvas as a PNG
4
+
5
+ usage:
6
+ sootsim screenshot [output] [options]
7
+ sootsim screenshot [options] --output <path>
8
+
9
+ options:
10
+ --output <path> output file path (default: /tmp/sootsim-inspect.png)
11
+ first positional arg works too: \`screenshot /tmp/x.png\`
12
+ --with-frame wrap the captured screen in a tight device frame
13
+ --no-frame capture the raw screen bitmap (default)
14
+ --no-shell tenant-only capture (no status bar, keyboard, toasts,
15
+ notification center, or other shell overlays). use for
16
+ clean app screenshots when a shell surface is in the way.
17
+ --shell-only capture only the shell chrome, no tenant content
18
+ --area x,y,w,h crop to a logical sootsim rect
19
+ --id <testID> crop to a node's bounding box
20
+ --text <text> crop to a node found by text content
21
+ --gallery crawl and capture multiple screens as HTML gallery
22
+ --themes capture light and dark variants
23
+
24
+ examples:
25
+ sootsim screenshot
26
+ sootsim screenshot --no-shell --output app.png
27
+ sootsim screenshot --with-frame --output framed.png
28
+ sootsim screenshot --area 0,200,393,400 --output hero.png
29
+ sootsim screenshot --id loginButton --output button.png
30
+ `),process.exit(0));let i=Ue(o);if(i.length>0){for(let{flag:p,suggestion:g}of i)console.error(g?` unknown flag: ${p} (did you mean ${g}?)`:` unknown flag: ${p}`);console.error(" run `sootsim screenshot --help` for the list of supported flags"),process.exit(1)}let r=o.includes("--gallery"),s=o.includes("--themes"),n=ze(o),a=_e(o);if(r||s)return n&&(console.error(" --with-frame is not supported with --gallery / --themes"),process.exit(1)),ae(o,t);n&&o.some(p=>p==="--area"||p==="--id"||p==="--text")&&(console.error(" --with-frame only supports full-screen capture for now"),console.error(" remove --area / --id / --text, or capture raw and compose later"),process.exit(1));let c=A(o,{port:t.port,stripBooleanFlags:["--with-frame","--no-frame","--no-shell","--shell-only"],stripValueFlags:["--output","--area","--id","--text"]}),l=me(o),u=await Be(o);if(await Re(c.wsPort)){try{await Oe(c,l,u,n,a)}catch(p){console.error(` screenshot failed: ${p instanceof Error?p.message:String(p)}`),process.exit(1)}return}n&&(console.error(" --with-frame requires a running sootsim bridge"),console.error(" open the app in a live sim first, then rerun the command"),process.exit(1)),u&&(console.error(" --area / --id / --text require a running sootsim bridge"),console.error(" start one with `sootsim serve`, `sootsim desktop`, or your project dev server"),process.exit(1)),await ae(o,t)}async function Re(e){let t=X(e,{commandTimeoutMs:1e3});try{return await t.listSims(),!0}catch{return!1}finally{t.close()}}async function Be(e){let t=e.find((r,s)=>e[s-1]==="--area");if(t){let r=t.split(",").map(l=>Number(l.trim()));if(r.length!==4||r.some(l=>!Number.isFinite(l)))throw new Error(`--area expects x,y,w,h (got "${t}")`);let[s,n,a,c]=r;return{x:s,y:n,w:a,h:c}}let o=e.find((r,s)=>e[s-1]==="--id"),i=e.find((r,s)=>e[s-1]==="--text");return o||i?{__matcher:{id:o,text:i}}:null}async function Oe(e,t,o,i,r){let s=R({...e,commandTimeoutMs:45e3});try{(await J(s)).hidden&&process.stderr.write(` \u26A0 screenshot will capture the LAST PAINTED canvas \u2014 likely stale.
31
+ navigation/\`shell\` commands sent before this screenshot may not
32
+ have repainted yet. focus the tab manually or \`sootsim --sim <id>\`
33
+ to target a visible sim before capturing.
34
+
35
+ `);let a=Number(process.env.CONTRAST_SCREENSHOT_READY_MAX_MS)||9e4,c=await K(s,a);if(!c.ready)throw new Error(`app not ready to capture after ${Math.round(c.elapsedMs/1e3)}s`+(c.loadingText?` (still showing "${c.loadingText}")`:"")+"; refusing to capture the boot/loading card. retry once the app paints.");let l=o,u=o?.__matcher;if(u){let v=await s.send({type:"evaluate",code:Q(u)});if(!v)throw new Error(u.id?`no node with id "${u.id}"`:`no node matching text "${u.text}"`);l=v}let d=l?{x:l.x,y:l.y,w:l.w,h:l.h}:void 0,p={type:"screenshot"};r&&(p.layers=r),d&&(p.crop=d);let g=await s.send(p);if(typeof g!="string"||g.length<="data:image/png;base64,".length)throw new Error("screenshot capture returned no image data \u2014 the sim is connected but not painting; check `sootsim get errors`");let m=g.replace(/^data:image\/png;base64,/,"");d&&console.log(` area: x=${d.x} y=${d.y} w=${d.w} h=${d.h}`),r&&console.log(` layers: ${r}`);let w=ue(process.cwd(),t||"/tmp/sootsim-inspect.png");ce(le(w),{recursive:!0});let S=Buffer.from(m,"base64");if(i){let v=await Te(s);if(!v)throw new Error("could not read current device model from the target sim");let Ae=await re(S,v);ie(w,Ae),console.log(` frame: ${v}`)}else ie(w,S);console.log(` saved: ${w}`)}finally{s.close()}}async function Te(e){let t=await M(e,"SootSim.bridges.settings.get")??{deviceModel:null},o=typeof t.deviceModel=="string"?t.deviceModel:null;return!o||!(o in E)?null:o}function ze(e){let t=!1;for(let o of e)o==="--with-frame"&&(t=!0),o==="--no-frame"&&(t=!1);return t}function _e(e){if(e.includes("--shell-only"))return"shell";if(e.includes("--no-shell"))return"tenant"}var je=new Set(["--help","-h","--verbose","-v","--with-frame","--no-frame","--no-shell","--shell-only","--gallery","--themes"]),pe=new Set(["--output","--area","--id","--text","--url","--port","--timeout","--sim"]),Ie={"--rect":"--area","--crop":"--area","--region":"--area","--bounds":"--area","--box":"--area","--xywh":"--area","--out":"--output","-o":"--output","--file":"--output","--path":"--output","--testid":"--id","--test-id":"--id","--test_id":"--id"};function Le(e){let t=[],o={"-o":"--output","--out":"--output","--file":"--output","--path":"--output","--testid":"--id","--test-id":"--id","--test_id":"--id","--rect":"--area","--crop":"--area","--region":"--area","--bounds":"--area","--box":"--area","--xywh":"--area"};for(let i of e){let r=o[i];t.push(r??i)}return t}function Ue(e){let t=[];for(let o=0;o<e.length;o++){let i=e[o];if(i.startsWith("-")){if(pe.has(i)){o++;continue}je.has(i)||t.push({flag:i,suggestion:Ie[i]})}}return t}function me(e){let t=e.find((o,i)=>e[i-1]==="--output");if(t)return t;for(let o=0;o<e.length;o++){let i=e[o];if(i.startsWith("-")){pe.has(i)&&o++;continue}return i}}async function ae(e,t){let o=me(e)||"sootsim-screenshot.png",i=e.includes("--gallery"),r=e.find((a,c)=>e[c-1]==="--url")||`http://localhost:${t.port||5173}`,{chromium:s}=await import("playwright"),n=await k(a=>s.launch(a),{headless:!0});try{if(i)console.log(" capturing gallery..."),console.log(" (gallery mode not yet implemented)");else{let a=await n.newPage({viewport:{width:500,height:900}});await a.goto(r,{waitUntil:"networkidle"}),await a.waitForTimeout(2e3);let c=ue(process.cwd(),o);ce(le(c),{recursive:!0}),await a.screenshot({path:c}),console.log(` saved: ${c}`),await a.close()}}catch(a){console.error(` screenshot failed: ${a.message}`),process.exitCode=1}finally{await n.close()}}import{mkdirSync as V,readFileSync as et,writeFileSync as ve}from"fs";import{tmpdir as to}from"os";import T from"path";import{mkdirSync as fe,readFileSync as He,writeFileSync as ge}from"fs";import H from"path";function he(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 Y(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function Ye(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 B(e,t){let o=Ye(e),i=Math.max(0,Math.min(1,t)),r=o.match(/^#([0-9a-f]{6})$/i);if(r){let s=r[1],n=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(${n}, ${a}, ${c}, ${i})`}return o.startsWith("rgb(")?o.replace(/^rgb\((.+)\)$/i,`rgba($1, ${i})`):o}function Ge(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 We(e){let t=e.glow;return t?`radial-gradient(circle at 50% 24%, ${B(t,.46)} 0%, ${B(t,.2)} 24%, rgba(0,0,0,0) 62%)`:"none"}function G(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 we(...e){let t=e.map(o=>o.trim()).filter(o=>o.length>0&&o!=="none");return t.length>0?t.join(" "):"none"}function W(e){let t=B(e.color,e.opacity),o=B(e.color,e.opacity*.52);return`drop-shadow(0 34px ${e.spread}px ${o}) drop-shadow(0 0 ${e.blur}px ${t})`}function q(e,t){return!t.glow||e.color&&e.color!==x.color?e:{...e,color:t.glow}}function qe(e,t){if(e==="editorial-left"){let r=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:${r}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:(n,a,c)=>{let l=Math.round(t.width*.68*(a.scale??n.scale)),u=Math.round(t.height*(.03+n.offsetY+(a.offsetY??0))),d=a.pose||n.pose||"tilted-right",p=q(n.shadow,c);return["position:absolute",`top:${Math.round(t.height*.18)+u}px`,`left:${Math.round(t.width*.56)}px`,`width:${l}px`,"transform-origin:center center",`transform:${G(d)}`,`filter:${W(p)}`,"z-index:2"].join(";")}}}if(e==="minimal-bottom"){let r=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:${r}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:(n,a,c)=>{let l=Math.round(t.width*.84*(a.scale??n.scale)),u=Math.round(t.height*(n.offsetY+(a.offsetY??0))),d=a.pose||n.pose,p=q(n.shadow,c);return["position:absolute",`top:${Math.round(t.height*.075)+u}px`,"left:50%",`width:${l}px`,"transform-origin:center center",`transform:${we("translateX(-50%)",G(d))}`,`filter:${W(p)}`,"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:(r,s,n)=>{let a=Math.round(t.width*.64*(s.scale??r.scale)),c=Math.round(t.height*(r.offsetY+(s.offsetY??0))),l=s.pose||r.pose,u=q(r.shadow,n);return["position:absolute",`top:${Math.round(t.height*.28)+c}px`,"left:50%",`width:${a}px`,"transform-origin:center top",`transform:${we("translateX(-50%)",G(l))}`,`filter:${W(u)}`,"z-index:2"].join(";")}}}function Ve({canvas:e,compose:t,slide:o,imageDataUrl:i}){let r=o.background??t.background,s=qe(t.text.preset,e),n=t.text.preset!=="none"&&!!(o.eyebrow||o.headline||o.subheadline),a=s.deviceStyle(t.frame,o,r),c=o.headline?`<div style="font-weight:780;white-space:pre-line;text-wrap:balance;${s.titleStyle}">${Y(o.headline)}</div>`:"",l=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}">${Y(o.subheadline)}</div>`:"",u=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};">${Y(o.eyebrow)}</div></div>`:"";return`<!doctype html>
36
+ <html>
37
+ <head>
38
+ <meta charset="utf-8" />
39
+ <style>
40
+ html, body {
41
+ margin: 0;
42
+ width: ${e.width}px;
43
+ height: ${e.height}px;
44
+ overflow: hidden;
45
+ background: transparent;
46
+ }
47
+ body {
48
+ font-family: "SF Pro Display", "Helvetica Neue", system-ui, sans-serif;
49
+ }
50
+ #canvas {
51
+ position: relative;
52
+ width: ${e.width}px;
53
+ height: ${e.height}px;
54
+ overflow: hidden;
55
+ background: ${Ge(r)};
56
+ color: ${t.text.color};
57
+ isolation: isolate;
58
+ }
59
+ #glow {
60
+ position: absolute;
61
+ inset: 0;
62
+ background: ${We(r)};
63
+ pointer-events: none;
64
+ }
65
+ #copy {
66
+ ${s.copyStyle};
67
+ }
68
+ #device {
69
+ ${a};
70
+ }
71
+ #device img {
72
+ display: block;
73
+ width: 100%;
74
+ height: auto;
75
+ }
76
+ </style>
77
+ </head>
78
+ <body>
79
+ <div id="canvas">
80
+ <div id="glow"></div>
81
+ ${n?`<div id="copy">${u}${c}${l}</div>`:""}
82
+ <div id="device"><img src="${i}" alt="" /></div>
83
+ </div>
84
+ </body>
85
+ </html>`}async function ye(e,t,o){let i=[],r=o??await(async()=>{let{chromium:n}=await import("playwright");return k(a=>n.launch(a),{headless:!0})})();try{let n=await r.newContext({viewport:{width:1280,height:720}});try{for(let a of t){let l=`data:image/png;base64,${He(a.imagePath).toString("base64")}`;for(let u of e.canvases){let d=await n.newPage();try{await d.setViewportSize({width:u.width,height:u.height}),await d.setContent(Ve({canvas:u,compose:e,slide:a.slide,imageDataUrl:l}),{waitUntil:"load"}),await d.waitForTimeout(20);let p=H.join(e.outDir,u.name,e.locale);fe(p,{recursive:!0});let g=H.join(p,`${a.slide.assetKey}.png`),f=await d.screenshot({type:"png",clip:{x:0,y:0,width:u.width,height:u.height}});ge(g,f),i.push({slideId:a.slide.id,canvas:u.name,locale:e.locale,outputPath:g,sourcePath:a.imagePath})}finally{await d.close()}}}}finally{await n.close()}}finally{!o&&typeof r.close=="function"&&await r.close()}fe(e.outDir,{recursive:!0});let s=H.join(e.outDir,"manifest.json");return ge(s,JSON.stringify({generatedAt:new Date().toISOString(),locale:e.locale,outputs:i},null,2)),{manifestPath:s,outputs:i.map(n=>n.outputPath),entries:i}}function D(e){return typeof e=="string"&&e.length>0?e:void 0}async function Se(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 n=s.config.frames;return Array.isArray(n)?n.map(a=>{let c=a??{};return{title:D(c.title),subtitle:D(c.subtitle),bgTop:D(c.bgTop),bgBottom:D(c.bgBottom),titleColor:D(c.titleColor)}}):null}function be(e,t){e.compose.slides.forEach((o,i)=>{let r=t[i];if(r&&(r.title!=null&&(o.headline=r.title),r.subtitle!=null&&(o.subheadline=r.subtitle),r.bgTop&&r.bgBottom)){let s={type:"gradient",direction:180,stops:[{offset:0,color:I(r.bgTop)},{offset:1,color:I(r.bgBottom)}]};o.background=s}})}import{readFileSync as Ke}from"fs";import P from"path";function h(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function O(e,t){if(!h(e))throw new Error(`${t} must be an object`);return e}function y(e,t=""){return typeof e=="string"?e:t}function b(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function xe(e,t){return typeof e=="boolean"?e:t}function C(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function Pe(e,t){return typeof e!="string"||e.trim().length===0?t:Object.prototype.hasOwnProperty.call(E,e)?e:null}function $e(e,t){if(typeof e=="string"){let r=F(e);if(!r)throw new Error(`unknown background preset: ${e}`);return r}if(!h(e))return U(t);let o=e.type==="solid"||e.type==="gradient"?e.type:t.type;if(o==="solid")return{type:o,color:y(e.color,t.color??"#000000"),glow:b(e.glow)??t.glow};let i=Array.isArray(e.stops)?e.stops.map(r=>{if(!h(r))return null;let s=C(r.offset,Number.NaN),n=b(r.color);return!Number.isFinite(s)||!n?null:{offset:s,color:n}}).filter(r=>!!r):t.stops?.map(r=>({...r}))??[];return{type:o,direction:C(e.direction,t.direction??180),glow:b(e.glow)??t.glow,stops:i.length>0?i:t.stops?.map(r=>({...r}))??[]}}function Xe(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 r=L(i);if(!r)throw new Error(`unknown canvas preset: ${i}`);return r});if(o.length===0)throw new Error("compose.canvases must include at least one preset");return o}function Je(e){switch(e){case"editorial-left":case"minimal-bottom":case"none":case"bold-top":return e;default:return"bold-top"}}function Ze(e){switch(e){case"plan":case"flow":case"auto":return e;default:return"auto"}}function ke(e){switch(e){case"straight":case"tilted-left":case"tilted-right":case"cut-bottom":case"cut-top":return e;default:return}}function N(e,t){return P.isAbsolute(t)?t:P.resolve(e,t)}function Qe(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 r=O(o,`compose.slides[${i}]`),s=b(r.screenshot);if(!s)throw new Error(`compose.slides[${i}].screenshot is required`);let n=b(r.id),a=he(n||s);return{id:n||a,assetKey:a,screenshot:s,headline:y(r.headline),subheadline:y(r.subheadline),eyebrow:y(r.eyebrow),pose:ke(r.pose),scale:typeof r.scale=="number"&&Number.isFinite(r.scale)?r.scale:void 0,offsetY:typeof r.offsetY=="number"&&Number.isFinite(r.offsetY)?r.offsetY:void 0,background:r.theme||r.background?$e(r.theme??r.background,t):void 0}})}function Ce(e){let t=P.resolve(e),o=P.dirname(t),i=ee.parse(Ke(t,"utf8")),r=O(i,"screenshots plan"),s=O(r.capture??{},"capture"),n=O(r.compose??{},"compose"),a=typeof r.app=="number"?String(r.app):b(r.app),c=Pe(r.device,null),l=N(o,y(s.out,P.join(".sootsim","screenshots","capture"))),u=b(s.from),d=b(s.flow);if(!u&&!d)throw new Error("capture.flow or capture.from is required");let p=s.mode==="raw"||s.mode==="framed"||s.mode==="raw+framed"?s.mode:"raw+framed",g=Ze(s.pathMode),f=$e(n.background??"cyan",F("cyan")),m={show:xe(n.frame&&h(n.frame)?n.frame.show:void 0,!0),style:Pe(n.frame&&h(n.frame)?n.frame.style:null,null)||c||j,pose:ke(n.frame&&h(n.frame)?n.frame.pose:void 0)||"straight",scale:C(n.frame&&h(n.frame)?n.frame.scale:void 0,1),offsetY:C(n.frame&&h(n.frame)?n.frame.offsetY:void 0,0),shadow:{color:y(n.frame&&h(n.frame)&&h(n.frame.shadow)?n.frame.shadow.color:void 0,x.color),blur:C(n.frame&&h(n.frame)&&h(n.frame.shadow)?n.frame.shadow.blur:void 0,x.blur),spread:C(n.frame&&h(n.frame)&&h(n.frame.shadow)?n.frame.shadow.spread:void 0,x.spread),opacity:C(n.frame&&h(n.frame)&&h(n.frame.shadow)?n.frame.shadow.opacity:void 0,x.opacity)}};return{planPath:t,planDir:o,appTarget:a,deviceModel:c,capture:{flowPath:d?N(o,d):null,fromDir:u?N(o,u):null,outDir:l,rawDir:u?N(o,u):P.join(l,"raw"),framedDir:P.join(l,"framed"),mode:p,pathMode:g,simId:b(s.sim),openInNewSim:xe(s.new,!1)},compose:{outDir:N(o,y(n.out,P.join(".sootsim","screenshots","exports"))),locale:y(n.locale,"en"),canvases:Xe(n.canvases),frame:m,background:f,text:{preset:Je(n.text&&h(n.text)?n.text.preset:void 0),color:y(n.text&&h(n.text)?n.text.color:void 0,"#ffffff"),subColor:y(n.text&&h(n.text)?n.text.subColor:void 0,"rgba(232,240,247,0.86)"),eyebrowColor:y(n.text&&h(n.text)?n.text.eyebrowColor:void 0,"rgba(229,242,255,0.72)")},slides:Qe(n.slides,f)}}}function tt(e){return e.capture.pathMode==="plan"||e.capture.pathMode==="flow"?e.capture.pathMode:e.capture.fromDir?"flow":"plan"}function ot(e,t){if(!e.capture.flowPath)throw new Error("capture flow path is required to build flow args");let o=[e.capture.flowPath],i=tt(e);o.push("--screenshots",e.capture.rawDir),i==="flow"&&o.push("--screenshot-paths","flow");let r=t.appTarget??e.appTarget,s=t.deviceModel??e.deviceModel,n=t.simId??e.capture.simId;return r&&o.push("--url",r),s&&o.push("--device",s),n&&o.push("--sim",n),e.capture.openInNewSim&&o.push("--new"),o}function z(e,t){return T.isAbsolute(t)?t:T.join(e.capture.rawDir,t)}function rt(e){return T.join(e.capture.outDir,"manifest.json")}async function nt(e,t){if(!e.capture.flowPath)return;V(e.capture.rawDir,{recursive:!0});let o=ot(e,t),i=await se(o);if(i!==0)throw new Error(`flow capture failed with exit code ${i}`)}async function st(e,t){let o=new Map;V(e.capture.framedDir,{recursive:!0});let i=t??await(async()=>{let{chromium:r}=await import("playwright");return k(s=>r.launch(s),{headless:!0})})();try{let r=await ne(i);try{for(let s of e.compose.slides){let n=z(e,s.screenshot),a=et(n),c=await r.compose(a,e.compose.frame.style),l=T.join(e.capture.framedDir,`${s.assetKey}.png`);ve(l,c),o.set(s.id,l)}}finally{await r.close()}}finally{!t&&typeof i.close=="function"&&await i.close()}return o}function it(e,t,o){let i=[],r=[];V(e.capture.outDir,{recursive:!0});let s=rt(e),n=e.compose.slides.map(a=>{let c=z(e,a.screenshot),l=t.get(a.id)??null;return i.push(c),l&&r.push(l),{id:a.id,screenshot:a.screenshot,rawPath:c,framedPath:l}});return ve(s,JSON.stringify({generatedAt:new Date().toISOString(),deviceModel:o,mode:e.capture.mode,rawDir:e.capture.rawDir,framedDir:e.capture.framedDir,slides:n},null,2)),{manifestPath:s,rawDir:e.capture.rawDir,framedDir:e.capture.framedDir,rawFiles:i,framedFiles:r}}function at(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 Me(e,t={}){let o=Ce(e);t.orgDeckFrames&&t.orgDeckFrames.length>0&&be(o,t.orgDeckFrames);let i=t.deviceModel??o.deviceModel;t.composeOnly||await nt(o,t);let r=o.capture.mode!=="raw"||!t.captureOnly&&o.compose.frame.show===!0,n=r||!t.captureOnly?await(async()=>{let{chromium:a}=await import("playwright");return k(c=>a.launch(c),{headless:!0})})():null;try{let a=r?await st(o,n??void 0):new Map,c=it(o,a,i);if(t.captureOnly)return{plan:o,capture:c,compose:null};let l=at(o,a),u=await ye(o.compose,l,n??void 0);return{plan:o,capture:c,compose:u}}finally{n&&typeof n.close=="function"&&await n.close()}}async function De(e,t={}){if(e.includes("--help")||e.includes("-h"))return console.log(`
86
+ sootsim screenshot appstore \u2014 capture and compose app-store screenshot sets
87
+
88
+ usage:
89
+ sootsim screenshot appstore --plan <plan.yaml> [options]
90
+
91
+ options:
92
+ --plan <path> screenshot plan yaml
93
+ --sim <id> reuse a live sim for capture
94
+ --app <target> override plan app target (port, url, or shell url)
95
+ --device <model> override plan capture device for this run
96
+ --org <slug> overlay copy/colors from a team's org screenshot deck
97
+ --repo <name> repo for --org (both required to pull the org deck)
98
+ --api-origin <url> contrast origin to fetch the deck from (default: the
99
+ signed-in session origin, else https://contrast.dev)
100
+ --capture-only stop after raw/framed intermediates
101
+ --compose-only skip flow capture, reuse existing raw screenshots
102
+
103
+ examples:
104
+ sootsim screenshot appstore --plan app-store.yaml
105
+ sootsim screenshot appstore --plan app-store.yaml --sim a9
106
+ sootsim screenshot appstore --plan app-store.yaml --org acme --repo mobile
107
+ `),0;let o=m=>e.find((w,S)=>e[S-1]===m),i=new Set(["--plan","--sim","--app","--device","--org","--repo","--api-origin"]),r=e.filter((m,w)=>{if(m.startsWith("-"))return!1;let S=e[w-1];return!S||!i.has(S)}),s=o("--plan")||r[0];if(!s)return console.error(" error: screenshots plan path is required (`--plan <path>`)."),1;let n=o("--sim")?.trim()||null,a=o("--app")?.trim()||null,c=o("--device")?.trim()||null,l=o("--org")?.trim()||null,u=o("--repo")?.trim()||null,d=o("--api-origin")?.trim()||null,p=e.includes("--capture-only"),g=e.includes("--compose-only"),f=null;if(l||u){if(!l||!u)return console.error(" error: --org and --repo must be passed together."),1;let m=te();if(!m)return console.error(" error: --org/--repo needs auth \u2014 run `sootsim login` or set SOOTSIM_API_KEY."),1;let w=d||(m.kind==="session"?m.origin:"https://contrast.dev");try{f=await Se({org:l,repo:u,origin:w,authHeader:oe(m)})}catch(S){return console.error(` ${S.message}`),1}!f||f.length===0?console.log(` note: no org deck for ${l}/${u} \u2014 composing with the plan's copy/colors.`):console.log(` org deck: ${f.length} slide(s) from ${l}/${u}`)}try{let m=await Me(s,{simId:n,appTarget:a,deviceModel:c,captureOnly:p,composeOnly:g,orgDeckFrames:f});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}}import{mkdirSync as ct,writeFileSync as lt}from"node:fs";import{dirname as ut,isAbsolute as dt,join as Ne,resolve as pt}from"node:path";var mt=`
108
+ sootsim screenshot slides \u2014 compose App Store screenshots in the live sim
109
+
110
+ usage:
111
+ sootsim screenshot slides list slides (alias: slides list)
112
+ sootsim screenshot slides set <n> [fields] patch a slide's copy/colors
113
+ sootsim screenshot slides add append a blank slide (focuses it)
114
+ sootsim screenshot slides remove <n> delete a slide
115
+ sootsim screenshot slides focus <n> open a slide (device flips into it)
116
+ sootsim screenshot slides overview back to the gallery
117
+ sootsim screenshot slides capture [<n>] capture the live frame into a slide
118
+ sootsim screenshot slides export [<n>] [--out <dir>]
119
+ write composed App-Store PNG(s)
120
+
121
+ set fields:
122
+ --title <text> headline
123
+ --subtitle <text> subheadline
124
+ --bg-top <color> gradient top (white gray slate black cyan blue
125
+ --bg-bottom <color> gradient bottom teal green lime gold orange coral
126
+ --title-color <color> copy color override, or "auto" red berry magenta
127
+ --title-size <s> sm | md | lg | none gray-light
128
+ --underlay <s> black | white | none gray-dark \u2026)
129
+ --shadow <s> light | medium | strong | none
130
+
131
+ notes:
132
+ slides are addressed by 1-based index. screenshot mode is auto-enabled.
133
+ capture shoots whatever the sim currently shows \u2014 navigate the app first
134
+ (sootsim do tap-id \u2026), then capture.
135
+
136
+ examples:
137
+ sootsim screenshot slides set 1 --title "The ultimate MMA community." --bg-top cyan --bg-bottom black
138
+ sootsim screenshot slides capture 1
139
+ sootsim screenshot slides export --out ./exports
140
+ `,ht={"--title":"title","--subtitle":"subtitle","--bg-top":"bgTop","--bg-bottom":"bgBottom","--title-color":"titleColor","--title-size":"titleSize","--underlay":"titleUnderlay","--shadow":"titleShadow","--out":"out"};function ft(e){let t=[],o={},i=!1;for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="--json"){i=!0;continue}let n=s.indexOf("="),a=n>0?s.slice(0,n):s,c=ht[a];if(c){n>0?o[c]=s.slice(n+1):(o[c]=e[r+1]??"",r+=1);continue}t.push(s)}return{rest:t,values:o,json:i}}function gt(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:e}async function wt(e){if(!await Z(e,`(async () => {
141
+ if (window.SootSim?.bridges?.settings?.get?.()?.screenshotMode) return true
142
+ window.dispatchEvent(new CustomEvent('sootsim:shell-command', {
143
+ detail: { type: 'fire-action', id: 'toggle-screenshot-mode' },
144
+ }))
145
+ const deadline = Date.now() + 2000
146
+ while (Date.now() < deadline) {
147
+ if (window.SootSim?.bridges?.settings?.get?.()?.screenshotMode) return true
148
+ await new Promise((r) => setTimeout(r, 40))
149
+ }
150
+ return false
151
+ })()`,{acquireLock:!0}))throw new Error("could not enable screenshot mode \u2014 is this a browser sim with the screenshot plugin? (electron has no screenshot mode)")}function yt(e){console.log(` ${e.projectName} \u2014 canvas ${e.canvas} (${e.exportSize.width}\xD7${e.exportSize.height}), device ${e.deviceModel}`);for(let t of e.slides){let o=[t.focused?"focused":t.active?"active":null,t.captured?`captured${t.captureMode==="3d"?" 3d":""}`:"no capture"].filter(Boolean).join(", "),i=t.title?`"${t.title}"`:"(no title)",r=[`bg ${t.bgTop}\u2192${t.bgBottom}`,t.titleColor?`color ${t.titleColor}`:null,t.titleSize?`size ${t.titleSize}`:null,t.titleUnderlay?`underlay ${t.titleUnderlay}`:null,t.titleShadow?`shadow ${t.titleShadow}`:null].filter(Boolean).join(", ");console.log(` ${t.index}. ${i} \u2014 ${r} [${o}]`),t.subtitle&&console.log(` ${t.subtitle}`)}}function St(e){let t=e.match(/^data:[^;]+;base64,(.+)$/);if(!t)throw new Error("export returned an unexpected payload");return Buffer.from(t[1],"base64")}async function Fe(e,t){if(e.includes("--help")||e.includes("-h")){console.log(mt);return}let{rest:o,values:i,json:r}=ft(e),s=A(o,{port:t.port,commandTimeoutMs:45e3}),n=s.positional[0]??"list",a=gt(s.positional[1]),c=R(s),l=u=>{r?console.log(JSON.stringify(u,null,2)):yt(u)};try{switch(await wt(c),n){case"list":{l(await M(c,"SootSim.bridges.screenshotControl.getState"));break}case"set":{if(a==null)throw new Error("usage: sootsim screenshot slides set <n> --title \u2026 (see --help)");let u={};for(let d of["title","subtitle","bgTop","bgBottom","titleColor","titleSize","titleUnderlay","titleShadow"])i[d]!=null&&(u[d]=i[d]);if(Object.keys(u).length===0)throw new Error("nothing to set \u2014 pass at least one field (see --help)");l(await $(c,"SootSim.bridges.screenshotControl.setSlide",a,u));break}case"add":{l(await $(c,"SootSim.bridges.screenshotControl.addSlide"));break}case"remove":{if(a==null)throw new Error("usage: sootsim screenshot slides remove <n>");l(await $(c,"SootSim.bridges.screenshotControl.removeSlide",a));break}case"focus":{if(a==null)throw new Error("usage: sootsim screenshot slides focus <n>");l(await $(c,"SootSim.bridges.screenshotControl.focusSlide",a));break}case"overview":{l(await $(c,"SootSim.bridges.screenshotControl.overview"));break}case"capture":{let u=await $(c,"SootSim.bridges.screenshotControl.capture",...a!=null?[a]:[]);l(u);break}case"export":{let u=i.out?dt(i.out)?i.out:pt(process.cwd(),i.out):Ne(process.cwd(),"screenshots"),d=await M(c,"SootSim.bridges.screenshotControl.getState"),p=a!=null?d.slides.filter(f=>f.index===a||f.id===a):d.slides.filter(f=>f.captured);if(p.length===0)throw new Error(a!=null?`no slide ${a}`:"no captured slides to export \u2014 capture first");let g=[];for(let f of p){let m=await M(c,"SootSim.bridges.screenshotControl.exportSlide",f.index),w=Ne(u,m.name);ct(ut(w),{recursive:!0}),lt(w,St(m.dataUrl)),g.push(w),console.log(` saved: ${w} (${m.width}\xD7${m.height})`)}r&&console.log(JSON.stringify({written:g},null,2));break}default:throw new Error(`unknown subcommand "${n}" \u2014 see sootsim screenshot slides --help`)}}finally{c.close()}}var bt=new Set(["--sim","--port","-p","--output","-o","--out","--plan","--app","--device","--org","--repo","--api-origin","--branch","--platform","--slides","--shell-origin","--timeout"]),xt=new Set(["capture","slides","appstore"]);function Ee(e){for(let t=0;t<e.length;t++){let o=e[t];if(o.startsWith("-")){bt.has(o)&&t++;continue}return xt.has(o)?{name:o,index:t}:null}return null}function _(e,t){return[...e.slice(0,t),...e.slice(t+1)]}function Pt(e){let t=[];for(let o=0;o<e.length;o++){if(e[o]==="--sim"){o++;continue}t.push(e[o])}return t}async function Po(e,t){let o=Ee(e);if(!o||o.name==="capture"){await de(o?_(e,o.index):e,t);return}if(o.name==="slides"){await Fe(_(e,o.index),t);return}let i=_(e,o.index),r=Ee(i);if(r?.name==="capture")try{let{runScreenshotsCapture:s}=await import("./screenshots-capture-LZR3AHWN.js");return await s(Pt(_(i,r.index)))}catch(s){if(s instanceof Error&&"code"in s&&s.code==="ERR_MODULE_NOT_FOUND")return console.error("screenshot appstore capture is repo-only tooling \u2014 it needs the sootsim workspace (playwright is not shipped with the published CLI)."),1;throw s}return De(i,t)}export{Po as runScreenshotCommand};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as M}from"./chunk-KBSJA7HK.js";import{a as x}from"./chunk-4BLOZ3AF.js";import"./chunk-2BQOZATN.js";import"./chunk-NU755HCE.js";import"./chunk-F5HOYUD2.js";import{execSync as T}from"node:child_process";import{mkdirSync as D,mkdtempSync as O,rmSync as E,writeFileSync as j}from"node:fs";import{tmpdir as G}from"node:os";import{dirname as q,isAbsolute as B,join as U,resolve as L}from"node:path";import{chromium as W}from"playwright-core";var z=`
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as M}from"./chunk-4QOY4T27.js";import{a as x}from"./chunk-ALE5MU5Z.js";import"./chunk-2I62CFYI.js";import"./chunk-PNPH4JLS.js";import"./chunk-6U3GMNTP.js";import{execSync as T}from"node:child_process";import{mkdirSync as D,mkdtempSync as O,rmSync as E,writeFileSync as j}from"node:fs";import{tmpdir as G}from"node:os";import{dirname as q,isAbsolute as B,join as U,resolve as L}from"node:path";import{chromium as W}from"playwright-core";var z=`
3
3
  sootsim screenshot appstore capture \u2014 headlessly capture + upload App Store slides
4
4
 
5
5
  usage:
@@ -32,7 +32,7 @@ examples:
32
32
  sootsim screenshot appstore capture needs a logged-in session.
33
33
  run \`sootsim login\` first (the captured slides upload to that account).
34
34
 
35
- `),process.exit(1)}function V(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function Y(t){let e=new URL(t);if(V(e.hostname)){let s=(Number(e.port)||3e3)-3e3;if(s>=0&&s<=1e3)return e.port=String(5173+s),e.origin}return e.hostname==="sootbean.com"||e.hostname.endsWith(".sootbean.com")?"https://sootsim.com":t}function K(){try{return Number(T("sysctl -n vm.loadavg").toString().trim().split(/\s+/)[1])||0}catch{return 0}}async function Q(t,e,n,s){let i=await fetch(`${t}/api/sootsim/screenshot-decks?org=${encodeURIComponent(n)}&repo=${encodeURIComponent(s)}`,{headers:{authorization:`Bearer ${e}`}});if(!i.ok)return[];let a=await i.json().catch(()=>null),d=[];for(let g of a?.decks??[])Array.isArray(g.config?.frames)&&d.push(...g.config.frames);return d}async function X(t,e,n,s){let i=await fetch(`${t}/api/sootsim/screenshot-capture?ref=${encodeURIComponent(s)}&org=${encodeURIComponent(n)}`,{headers:{authorization:`Bearer ${e}`}});return i.ok?`data:image/png;base64,${Buffer.from(await i.arrayBuffer()).toString("base64")}`:null}async function Z(t,e){let n=Date.now()+e;for(;Date.now()<n;){for(let s of t.frames())if(await s.evaluate(()=>!!globalThis.SootSim?.bridges?.screenshotControl).catch(()=>!1))return s;await t.waitForTimeout(250)}throw new Error("screenshot bridge never appeared \u2014 the build shell did not boot screenshot mode (check --branch/--platform has a ready build, and you are logged in)")}async function I(t){return t.evaluate(async()=>{let n=globalThis.SootSim?.bridges?.screenshotControl;if(!n)throw new Error("screenshotControl missing");return n.getState()})}async function _(t){await t.evaluate(async()=>{let e=globalThis.SootSim?.bridges?.settings,n=Date.now()+3e3;for(;Date.now()<n;){if(e?.get?.()?.screenshotMode)return;await new Promise(s=>setTimeout(s,50))}e&&!e.get().screenshotMode&&(e.set("screenshotMode",!0),e.get().showFrame||e.set("showFrame",!0))})}async function ee(t,e,n,s){await t.evaluate(async([i,a,d])=>{let g=globalThis.SootSim,h=g?.bridges?.screenshotControl;if(!h)throw new Error("screenshotControl missing");let w=b=>new Promise(u=>setTimeout(u,b));if(a){h.focusSlide(i);let b=Date.now()+3e4,u=g?.bridges?.threeMode;for(;Date.now()<b&&(u=g?.bridges?.threeMode,!(u?.setScreenImage&&u?.captureStage&&u?.getState?.()?.ready));)await w(150);await w(1e3);let c=a;u?.configure?.({colorway:c.colorway,background:c.background,...c.customGradient?{customGradient:c.customGradient}:{},setting:c.setting,focus:c.focus,environment:c.environmentActive?{pins:c.environmentPins??{},effects:c.environmentEffects??{}}:!1,pose:{phonePosition:c.phonePosition,phoneRotation:c.phoneRotation,cameraPosition:c.cameraPosition,target:c.target}}),await w(900),d&&u?.setScreenImage&&(u.setScreenImage(d),await w(1200))}await h.capture(i)},[e,n,s])}async function ue(t){if(t.includes("--help")||t.includes("-h"))return console.log(z),0;let e=H(t);if(!e.org||!e.repo)return process.stderr.write(` --org and --repo are required (see --help)
35
+ `),process.exit(1)}function V(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="::1"||/^127(?:\.\d{1,3}){3}$/.test(e)}function Y(t){let e=new URL(t);if(V(e.hostname)){let s=(Number(e.port)||3e3)-3e3;if(s>=0&&s<=1e3)return e.port=String(5173+s),e.origin}return e.hostname==="contrast.dev"||e.hostname.endsWith(".contrast.dev")?"https://sootsim.com":t}function K(){try{return Number(T("sysctl -n vm.loadavg").toString().trim().split(/\s+/)[1])||0}catch{return 0}}async function Q(t,e,n,s){let i=await fetch(`${t}/api/sootsim/screenshot-decks?org=${encodeURIComponent(n)}&repo=${encodeURIComponent(s)}`,{headers:{authorization:`Bearer ${e}`}});if(!i.ok)return[];let a=await i.json().catch(()=>null),d=[];for(let g of a?.decks??[])Array.isArray(g.config?.frames)&&d.push(...g.config.frames);return d}async function X(t,e,n,s){let i=await fetch(`${t}/api/sootsim/screenshot-capture?ref=${encodeURIComponent(s)}&org=${encodeURIComponent(n)}`,{headers:{authorization:`Bearer ${e}`}});return i.ok?`data:image/png;base64,${Buffer.from(await i.arrayBuffer()).toString("base64")}`:null}async function Z(t,e){let n=Date.now()+e;for(;Date.now()<n;){for(let s of t.frames())if(await s.evaluate(()=>!!globalThis.SootSim?.bridges?.screenshotControl).catch(()=>!1))return s;await t.waitForTimeout(250)}throw new Error("screenshot bridge never appeared \u2014 the build shell did not boot screenshot mode (check --branch/--platform has a ready build, and you are logged in)")}async function I(t){return t.evaluate(async()=>{let n=globalThis.SootSim?.bridges?.screenshotControl;if(!n)throw new Error("screenshotControl missing");return n.getState()})}async function _(t){await t.evaluate(async()=>{let e=globalThis.SootSim?.bridges?.settings,n=Date.now()+3e3;for(;Date.now()<n;){if(e?.get?.()?.screenshotMode)return;await new Promise(s=>setTimeout(s,50))}e&&!e.get().screenshotMode&&(e.set("screenshotMode",!0),e.get().showFrame||e.set("showFrame",!0))})}async function ee(t,e,n,s){await t.evaluate(async([i,a,d])=>{let g=globalThis.SootSim,h=g?.bridges?.screenshotControl;if(!h)throw new Error("screenshotControl missing");let w=b=>new Promise(u=>setTimeout(u,b));if(a){h.focusSlide(i);let b=Date.now()+3e4,u=g?.bridges?.threeMode;for(;Date.now()<b&&(u=g?.bridges?.threeMode,!(u?.setScreenImage&&u?.captureStage&&u?.getState?.()?.ready));)await w(150);await w(1e3);let c=a;u?.configure?.({colorway:c.colorway,background:c.background,...c.customGradient?{customGradient:c.customGradient}:{},setting:c.setting,focus:c.focus,environment:c.environmentActive?{pins:c.environmentPins??{},effects:c.environmentEffects??{}}:!1,pose:{phonePosition:c.phonePosition,phoneRotation:c.phoneRotation,cameraPosition:c.cameraPosition,target:c.target}}),await w(900),d&&u?.setScreenImage&&(u.setScreenImage(d),await w(1200))}await h.capture(i)},[e,n,s])}async function ue(t){if(t.includes("--help")||t.includes("-h"))return console.log(z),0;let e=H(t);if(!e.org||!e.repo)return process.stderr.write(` --org and --repo are required (see --help)
36
36
  `),1;let{token:n,origin:s}=J(),i=(e.apiOrigin??s).replace(/\/$/,""),a=(e.shellOrigin??Y(i)).replace(/\/$/,""),d=await Q(i,n,e.org,e.repo);if(!e.dryRun&&!e.force&&d.length>0)return process.stderr.write(` refusing to overwrite the existing ${e.org}/${e.repo} deck (${d.length} slide(s)). re-run with --force to replace it, or --dry-run to preview.
37
37
  `),1;let g=K(),h=Number(T("sysctl -n hw.ncpu").toString().trim())||8;if(g>h)return process.stderr.write(` load average ${g.toFixed(1)} exceeds ${h} cores \u2014 tear down other work first.
38
38
  `),1;let w=`${a}/build/${encodeURIComponent(e.org)}/${encodeURIComponent(e.repo)}/${encodeURIComponent(e.branch)}?platform=${encodeURIComponent(e.platform)}&ssMode=1`,b=O(U(G(),"sootsim-capture-")),{browser:u,reapNow:c}=await M(r=>W.launchPersistentContext(b,r),{headless:!0,viewport:{width:393,height:852},deviceScaleFactor:3,args:["--enable-unsafe-webgpu","--enable-features=Vulkan,WebGPU","--hide-scrollbars"]});await u.addInitScript(r=>{try{localStorage.setItem("sootsim.session.token",r)}catch{}},n);let y=[],p=u.pages()[0]??await u.newPage();e.dryRun?await p.route(/\/api\/sootsim\/screenshot-(decks|capture)/,r=>r.request().method()==="PUT"?r.abort():r.continue()):p.on("response",r=>{let m=r.url();r.request().method()==="PUT"&&(m.includes("/api/sootsim/screenshot-decks")?y.push({kind:"deck",status:r.status()}):m.includes("/api/sootsim/screenshot-capture")&&y.push({kind:"capture",status:r.status()}))});let R=[];p.on("pageerror",r=>R.push(r.message));let N=p.waitForResponse(r=>r.url().includes("/api/sootsim/screenshot-decks")&&r.request().method()==="GET",{timeout:e.timeoutMs}).catch(()=>null);try{await p.goto(w,{waitUntil:"domcontentloaded",timeout:e.timeoutMs});let r=await Z(p,e.timeoutMs);await _(r),await N,await p.waitForTimeout(800);let m=await I(r);if(m.slides.length===0)return process.stderr.write(` the deck has no slides to capture \u2014 add slides in the composer first.
@@ -1,12 +1,12 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as le,c as H,d as de,e as F,f as ue,h as pe,i as C,j as me,k as he,l as fe,p as ge,s as v,t as Se,u as ye,v as ve,w as be}from"./chunk-A4BOYB55.js";import"./chunk-RNWJQ4UR.js";import{a as ce}from"./chunk-E3DLUOFK.js";import"./chunk-4BLOZ3AF.js";import{h as ae}from"./chunk-Z2E2DDIQ.js";import{f as P,g as se}from"./chunk-4J7BIXEB.js";import"./chunk-UGWURWHN.js";import"./chunk-7K5K5NKB.js";import{d as oe}from"./chunk-3L5EXWCP.js";import"./chunk-LM544J6V.js";import"./chunk-35EAEAN4.js";import{a as ee,b as te}from"./chunk-44Z2X5R4.js";import"./chunk-2BQOZATN.js";import{a as re,b as ne}from"./chunk-J7IFVTWX.js";import"./chunk-E75EBS77.js";import{E as J,G as E,H as K,I as V,J as D,L as G,M as q,O as z,Q as X,R as Y,S as Z,T as U,U as Q,y as M,z as j}from"./chunk-NU755HCE.js";import{a as ie}from"./chunk-7L5IKIHC.js";import"./chunk-F5HOYUD2.js";import{spawn as ut}from"child_process";import I from"fs";import{createServer as pt}from"http";import S from"path";import{WebSocket as h,WebSocketServer as mt}from"ws";import Ie from"node:fs";import R from"node:path";import{spawn as Me}from"node:child_process";import De from"node:fs";import Ue from"node:os";import He from"node:path";var we=/^[A-Za-z0-9._:-]{1,160}$/;function W(o){if(!o?.startsWith("AGENTBUS_SESSION:"))return null;let e=o.slice(17).trim();return we.test(e)?e:null}function Ae(o){return we.test(o)}function Fe(o){return typeof o.text=="string"?o.text.trim():""}function We(o){let e=o?.trim();if(e)return e;let t=process.env.AGENTBUS_COMMAND?.trim();if(t)return t;let i=He.join(Ue.homedir(),".local","bin","agentbus");return De.existsSync(i)?i:"agentbus"}async function ke(o){let e=o.sessionId.trim();if(!Ae(e))throw new Error(`invalid agentbus session id: ${e||"<empty>"}`);let t=Fe(o.prompt);if(!t)throw new Error("prompt text is empty");let i=We(o.command),s=o.timeoutMs??15e3;await new Promise((n,a)=>{let r=Me(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),c="",d=setTimeout(()=>{try{r.kill("SIGTERM")}catch{}a(new Error(`agentbus send timed out after ${Math.round(s/1e3)}s`))},s);r.stderr?.setEncoding("utf8"),r.stderr?.on("data",l=>{c.length<4e3&&(c+=String(l))}),r.on("error",l=>{clearTimeout(d),a(l)}),r.on("exit",(l,u)=>{if(clearTimeout(d),l===0){n();return}let p=c.trim();a(new Error(p||`agentbus send exited with ${u?`signal ${u}`:`code ${l??"unknown"}`}`))})})}var _=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 v?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 fe()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as le,c as H,d as de,e as F,f as ue,h as pe,i as C,j as me,k as he,l as fe,p as ge,s as v,t as Se,u as ye,v as ve,w as be}from"./chunk-MWZOCZ7J.js";import"./chunk-72AQH53U.js";import{a as ce}from"./chunk-34MFG4IM.js";import"./chunk-ALE5MU5Z.js";import{h as ae}from"./chunk-ZWJEJR73.js";import{f as P,g as se}from"./chunk-EKWOBYJO.js";import"./chunk-FSKQZHM2.js";import"./chunk-PJBYZZWR.js";import{d as oe}from"./chunk-UYLESZU3.js";import"./chunk-A5SO4OGE.js";import"./chunk-SPJSTRXX.js";import{a as ee,b as te}from"./chunk-BHNOPI7I.js";import"./chunk-2I62CFYI.js";import{a as re,b as ne}from"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import{E as J,G as E,H as K,I as V,J as D,L as G,M as q,O as z,Q as X,R as Y,S as Z,T as U,U as Q,y as M,z as j}from"./chunk-PNPH4JLS.js";import{a as ie}from"./chunk-JWZMAJC7.js";import"./chunk-6U3GMNTP.js";import{spawn as ut}from"child_process";import I from"fs";import{createServer as pt}from"http";import S from"path";import{WebSocket as h,WebSocketServer as mt}from"ws";import Ie from"node:fs";import R from"node:path";import{spawn as Me}from"node:child_process";import De from"node:fs";import Ue from"node:os";import He from"node:path";var we=/^[A-Za-z0-9._:-]{1,160}$/;function W(o){if(!o?.startsWith("AGENTBUS_SESSION:"))return null;let e=o.slice(17).trim();return we.test(e)?e:null}function Ae(o){return we.test(o)}function Fe(o){return typeof o.text=="string"?o.text.trim():""}function We(o){let e=o?.trim();if(e)return e;let t=process.env.AGENTBUS_COMMAND?.trim();if(t)return t;let i=He.join(Ue.homedir(),".local","bin","agentbus");return De.existsSync(i)?i:"agentbus"}async function ke(o){let e=o.sessionId.trim();if(!Ae(e))throw new Error(`invalid agentbus session id: ${e||"<empty>"}`);let t=Fe(o.prompt);if(!t)throw new Error("prompt text is empty");let i=We(o.command),s=o.timeoutMs??15e3;await new Promise((n,a)=>{let r=Me(i,["send",e,t],{stdio:["ignore","ignore","pipe"],env:process.env}),c="",d=setTimeout(()=>{try{r.kill("SIGTERM")}catch{}a(new Error(`agentbus send timed out after ${Math.round(s/1e3)}s`))},s);r.stderr?.setEncoding("utf8"),r.stderr?.on("data",l=>{c.length<4e3&&(c+=String(l))}),r.on("error",l=>{clearTimeout(d),a(l)}),r.on("exit",(l,u)=>{if(clearTimeout(d),l===0){n();return}let p=c.trim();a(new Error(p||`agentbus send exited with ${u?`signal ${u}`:`code ${l??"unknown"}`}`))})})}var _=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 v?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 fe()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
3
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 pe(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return me(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-claimed-prompt":return this.sendClaimedPrompt(i);case"agent:send-prompt":{let n=String(i.sessionId),a=C(n);if(!a)throw new v("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await ye(n,r),this.notePromptAccepted(n,r,a.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await ve(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 v("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async sendClaimedPrompt(e){let t=typeof e.simId=="string"?e.simId.trim():"";if(!t)throw new v("NO_SIM","agent:send-claimed-prompt requires simId");let i=this.opts.resolveCliLease?.(t)??null;if(!i||i.kind!=="cli"||i.expiresAt<=Date.now())throw new v("NO_CLAIM",`sim ${t} has no active CLI claim`);let s=W(i.cliIdentityKey);if(!s)throw new v("UNSUPPORTED_CLAIM",`sim ${t} is claimed by a CLI identity that is not promptable`);return await ke({sessionId:s,prompt:this.normalizePromptEnvelope(e)}),{ok:!0,routed:"agentbus",sessionId:s}}async doStartSession(e){if(!de(e.projectId))throw new v("NO_PROJECT",`no project: ${e.projectId}`);let i=await Se(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 P({excludePorts:s})).find(l=>String(l.port)===i);if(!a||!a.cwd)return{project:null};let r=F().find(l=>l.cwd===a.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],a.bundleUrl,t]));return{project:H({cwd:a.cwd,name:a.projectName??R.basename(a.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[a.cwd],knownBundleUrls:c,framework:r?.framework??je(a.framework),bundleId:a.bundleId??r?.bundleId})}}getTranscript(e){let t=ge(e);return Ie.existsSync(t)?Ie.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=le();return{userDataDir:e,storeFile:R.join(e,"attached-projects.json"),sessionsDir:R.join(e,"sessions"),transcriptsDir:R.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=be(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{ue(c.projectId,{usd:a.costUsd,ts:a.ts})}catch(d){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${d instanceof Error?d.message:String(d)}
4
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){he(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===_)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===_)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===_)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===_)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function je(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Ve from"http";import Ge from"https";var $="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",Je=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function Ke(o){let e=o.toLowerCase();for(let t of Je)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function Ce(o){let e=Ke(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":$},...e?.headers}}var qe=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"]),ze={"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"},Xe=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function T(o){for(let[e,t]of Object.entries(ze))o.setHeader(e,t)}function Ye(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 Ze(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 Qe(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(qe.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?Ce(e):{"user-agent":$}),t}function et(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Xe.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function Te(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function Ee(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Pe(o,e){if(o.method==="OPTIONS"){T(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){T(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{T(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n=Qe(o.headers,s),a;if(o.method!=="GET"&&o.method!=="HEAD"){let l=[];for await(let u of o)l.push(Buffer.isBuffer(u)?u:Buffer.from(u));if(l.length>0){let u=Buffer.concat(l);a=Ze(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(l){T(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${Ye(s.href,l)}`);return}r.headers.forEach((l,u)=>{let p=u.toLowerCase();p==="content-encoding"||p==="transfer-encoding"||p==="content-length"||p==="set-cookie"||p.startsWith("access-control-")||e.setHeader(u,l)}),T(e);let c=r.headers.getSetCookie?.()??[];c.length>0&&e.setHeader("x-sootsim-set-cookie",c.join(", ")),e.statusCode=r.status;let d=Buffer.from(await r.arrayBuffer());e.end(d)}function Re(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let d=new URL(t,"http://sootsim.local");i=d.searchParams.get("path")||"",s=d.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let a=n.protocol==="https:"?Ge:Ve,r=et(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},d=>{let l=Object.keys(d.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(d.statusCode??502,{...d.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":l}),d.pipe(e)});return c.on("error",d=>{e.statusCode=502,e.end(`app proxy error: ${d.message}`)}),o.pipe(c),!0}import{WebSocket as k,WebSocketServer as tt}from"ws";var it="/__websocket-proxy",rt=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 A(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 nt(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 st(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&&(rt.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function ot(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function at(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function O(o,e,t){if(!(o.readyState===k.CLOSED||o.readyState===k.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function ct(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,O(n,a,r.toString()),s.readyState===k.OPEN&&O(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===k.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===k.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",()=>O(e,1011,"proxy client error")),e.on("error",()=>O(o,1011,"upstream websocket error"))}function lt(o,e,t){let i={...t};return Object.keys(i).some(s=>s.toLowerCase()==="origin")||(i.origin=ot(o)),new k(o.href,e,{headers:i})}function dt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===it}catch{return!1}}function _e(o,e,t){if(!dt(o.url))return!1;if(!nt(o))return A(e,403,"forbidden websocket proxy origin"),!0;let i,s;try{let c=new URL(o.url||"/","http://localhost"),d=c.searchParams.get("url");if(!d)return A(e,400,"missing websocket proxy url"),!0;if(i=new URL(d),i.protocol!=="ws:"&&i.protocol!=="wss:")return A(e,400,"invalid websocket proxy protocol"),!0;s=st(c.searchParams.get("headers"))}catch{return A(e,400,"invalid websocket proxy request"),!0}let n=at(o),a=lt(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 tt({noServer:!0,clientTracking:!1,handleProtocols(l){return c||l.values().next().value||!1}}).handleUpgrade(o,e,t,l=>{ct(l,a)})}),a.once("error",()=>{r||(r=!0,A(e,502,"upstream websocket error"))}),a.once("close",()=>{r||(r=!0,A(e,502,"upstream websocket closed"))}),!0}var ht="require-corp",ft=new Set(["tap","keyboard"]),gt=2e3,St=1e3;function yt(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:ft.has(o.type)}var xe=5e3,vt=3600*1e3,bt="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",wt={".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 Oe(o,e,t){let i;try{let c=M();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(ie())};</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 Le(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var L=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;sootbeanOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new x({getExcludePorts:e.agentScanExcludes,resolveCliLease:t=>{let i=this.sims.get(t),s=i?this.getActiveLease(i):null;return s?{kind:s.kind,cliIdentityKey:s.cliIdentityKey,expiresAt:s.expiresAt}:null}}),this.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)
9
+ ${t}`)}catch{}o.destroy()}function nt(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 st(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&&(rt.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function ot(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function at(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function O(o,e,t){if(!(o.readyState===k.CLOSED||o.readyState===k.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function ct(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,O(n,a,r.toString()),s.readyState===k.OPEN&&O(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===k.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===k.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",()=>O(e,1011,"proxy client error")),e.on("error",()=>O(o,1011,"upstream websocket error"))}function lt(o,e,t){let i={...t};return Object.keys(i).some(s=>s.toLowerCase()==="origin")||(i.origin=ot(o)),new k(o.href,e,{headers:i})}function dt(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===it}catch{return!1}}function _e(o,e,t){if(!dt(o.url))return!1;if(!nt(o))return A(e,403,"forbidden websocket proxy origin"),!0;let i,s;try{let c=new URL(o.url||"/","http://localhost"),d=c.searchParams.get("url");if(!d)return A(e,400,"missing websocket proxy url"),!0;if(i=new URL(d),i.protocol!=="ws:"&&i.protocol!=="wss:")return A(e,400,"invalid websocket proxy protocol"),!0;s=st(c.searchParams.get("headers"))}catch{return A(e,400,"invalid websocket proxy request"),!0}let n=at(o),a=lt(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 tt({noServer:!0,clientTracking:!1,handleProtocols(l){return c||l.values().next().value||!1}}).handleUpgrade(o,e,t,l=>{ct(l,a)})}),a.once("error",()=>{r||(r=!0,A(e,502,"upstream websocket error"))}),a.once("close",()=>{r||(r=!0,A(e,502,"upstream websocket closed"))}),!0}var ht="require-corp",ft=new Set(["tap","keyboard"]),gt=2e3,St=1e3;function yt(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:ft.has(o.type)}var xe=5e3,vt=3600*1e3,bt="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",wt={".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 Oe(o,e,t){let i;try{let c=M();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimContrastOrigin=${JSON.stringify(t)};`:"",a=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(ie())};</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 Le(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var L=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;getShellPort;contrastOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.getShellPort=e.getShellPort??null,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new x({getExcludePorts:e.agentScanExcludes,resolveCliLease:t=>{let i=this.sims.get(t),s=i?this.getActiveLease(i):null;return s?{kind:s.kind,cliIdentityKey:s.cliIdentityKey,expiresAt:s.expiresAt}:null}}),this.contrastOrigin=e.contrastOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??o.SIM_IDLE_REAP_TTL_MS,this.automationSimIdleReapTtlMs=e.automationSimIdleReapTtlMs??o.AUTOMATION_SIM_IDLE_REAP_TTL_MS,this.maxConcurrentAutomationSims=e.maxConcurrentAutomationSims??o.MAX_CONCURRENT_AUTOMATION_SIMS,this.automationSimActiveGraceMs=e.automationSimActiveGraceMs??o.AUTOMATION_SIM_ACTIVE_GRACE_MS}getAgentHost(){return this.agentHost}reapIdleSimsForTest(e=Date.now()){this.reapIdleSims(e)}start(e){this.startAsync(e)}async startAsync(e){if(this.httpServer||this.wss)return this.effectivePort;this.refreshActiveRuntime();for(let t=0;t<this.portFallbackCount;t++){let i=this.preferredPort+t;try{return await this.bindOnce(i,e?.silent===!0),this.effectivePort=i,this.port=i,this.startedAt=Date.now(),t>0&&!e?.silent&&process.stderr.write(`ws bridge bound to port ${i} (preferred ${this.preferredPort} was taken)
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=pt((c,d)=>this.handleHttpRequest(c,d)),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
12
  `)}),this.httpServer=n,this.wss=new mt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,d,l)=>{_e(c,d,l)||this.wss?.handleUpgrade(c,d,l,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(),d=this.getActiveRuntime(),l={type:"runtime:list:ok",id:r.id,installed:c,active:d.version,activeRuntimeDir:d.runtimeDir};try{e.send(JSON.stringify(l))}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 l=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:l.version,runtimeDir:l.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let 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"&&r.type==="bridge:hello"&&n&&!n.url){let c=n.id;this.sims.delete(c),this.primarySimId===c&&(this.primarySimId=this.getOpenSim()?.id??null),n=null,s="cli",this.cliIdentityKeyBySocket.set(e,`ws-${this.nextCliFallbackId++}`),this.broadcastSimAssignments(),this.broadcastSimClientStates()}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let l=r,u=this.tryRestoreSimId(n,l.simId);n.url=l.url,n.title=l.title,n.userAgent=l.userAgent,typeof l.kind=="string"&&l.kind.trim()&&(n.kind=l.kind.trim()),l.meta&&typeof l.meta=="object"&&(n.meta=l.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let l=r;this.updateUserFocusLease(n,l);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let l=r.patch&&typeof r.patch=="object"?r.patch:null;if(!l)return;let u;try{u=j(l)}catch(m){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${m instanceof Error?m.message:String(m)}
@@ -19,7 +19,7 @@ ${t}`)}catch{}o.destroy()}function nt(o){let e=o.headers.origin,t=o.headers.host
19
19
  `);return}let i=this.activeRuntimeVersion,s=this.setActiveRuntime(t.latestVersion);process.stderr.write(`sootsim runtime updated to ${s.version} (${e})
20
20
  `);try{J({from:i,to:s.version,at:Date.now()})}catch{}}catch(t){process.stderr.write(`sootsim runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
21
21
  `)}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
22
- `)}}})(),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",ht),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),Te(e.url)){Pe(e,t);return}if(Ee(e.url)&&Re(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 d=s.searchParams.get("url");if(!d){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let l;try{l=new URL(d)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=l.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(l.toString(),{redirect:"follow"}),f={},y=m.headers.get("content-type");if(y&&(f["Content-Type"]=y),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:w}=await g.read();if(b)break;t.write(Buffer.from(w))}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,bridgeSource:this.shouldWriteDevLockfile?"vite-dev":this.shouldWriteLockfile?"daemon":"embedded",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 d="{}";try{d=JSON.stringify(M())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(d);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 d of a.split("/"))if(d===".."){t.writeHead(403),t.end("forbidden");return}let r=S.resolve(n,"."+a),c=n.endsWith(S.sep)?n:n+S.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}I.realpath(r,(d,l)=>{let u=d?r:l,p=u.endsWith(S.sep)?u:u+S.sep;if(!d){let m=(()=>{try{let f=I.realpathSync(n);return f.endsWith(S.sep)?f:f+S.sep}catch{return c}})();if(!p.startsWith(m)&&u+S.sep!==m){t.writeHead(403),t.end("forbidden");return}}I.stat(u,(m,f)=>{if(m||!f?.isFile()){let w=S.extname(a).toLowerCase();if(w&&w!==".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=S.join(n,"index.html");I.readFile(N,(Be,Ne)=>{if(Be){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(Oe(Ne,this.effectivePort,this.sootbeanOrigin))});return}let y=S.extname(u).toLowerCase(),g=wt[y]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(y===".html"){I.readFile(u,(w,N)=>{if(w){try{t.end()}catch{}return}t.end(Oe(N,this.effectivePort,this.sootbeanOrigin))});return}let b=I.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"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n);if(c&&this.automationSimOwnerAlive(n))continue;let d=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=d){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(re,ne)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},St);Le(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:d=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(d)},reject:d=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(d)}}),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,d)=>new Promise(l=>{try{let u=ut(c,d,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,l(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),l(!0))})}catch{l(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let 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 oe(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.devHeartbeatTimer&&(clearInterval(this.devHeartbeatTimer),this.devHeartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{U()}catch{}if(this.shouldWriteDevLockfile)try{Q()}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,d=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{}d++}}let l={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=l,{granted:!0,lease:l,bootedCount:d}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,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 At(){return!!((process.env.XPC_SERVICE_NAME||"").includes("dev.sootsim.daemon")||process.env.INVOCATION_ID)}async function mi(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
22
+ `)}}})(),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",ht),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),Te(e.url)){Pe(e,t);return}if(Ee(e.url)&&Re(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 d=s.searchParams.get("url");if(!d){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let l;try{l=new URL(d)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=l.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(l.toString(),{redirect:"follow"}),f={},y=m.headers.get("content-type");if(y&&(f["Content-Type"]=y),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:w}=await g.read();if(b)break;t.write(Buffer.from(w))}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,bridgeSource:this.shouldWriteDevLockfile?"vite-dev":this.shouldWriteLockfile?"daemon":"embedded",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 d="{}";try{d=JSON.stringify(M())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(d);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 d of a.split("/"))if(d===".."){t.writeHead(403),t.end("forbidden");return}let r=S.resolve(n,"."+a),c=n.endsWith(S.sep)?n:n+S.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}I.realpath(r,(d,l)=>{let u=d?r:l,p=u.endsWith(S.sep)?u:u+S.sep;if(!d){let m=(()=>{try{let f=I.realpathSync(n);return f.endsWith(S.sep)?f:f+S.sep}catch{return c}})();if(!p.startsWith(m)&&u+S.sep!==m){t.writeHead(403),t.end("forbidden");return}}I.stat(u,(m,f)=>{if(m||!f?.isFile()){let w=S.extname(a).toLowerCase();if(w&&w!==".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=S.join(n,"index.html");I.readFile(N,(Be,Ne)=>{if(Be){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(Oe(Ne,this.effectivePort,this.contrastOrigin))});return}let y=S.extname(u).toLowerCase(),g=wt[y]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(y===".html"){I.readFile(u,(w,N)=>{if(w){try{t.end()}catch{}return}t.end(Oe(N,this.effectivePort,this.contrastOrigin))});return}let b=I.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"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n);if(c&&this.automationSimOwnerAlive(n))continue;let d=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=d){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(re,ne)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},St);Le(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:d=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(d)},reject:d=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(d)}}),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,d)=>new Promise(l=>{try{let u=ut(c,d,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,l(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),l(!0))})}catch{l(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let 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 oe(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.devHeartbeatTimer&&(clearInterval(this.devHeartbeatTimer),this.devHeartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{U()}catch{}if(this.shouldWriteDevLockfile)try{Q()}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,d=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{}d++}}let l={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=l,{granted:!0,lease:l,bootedCount:d}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,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 At(){return!!((process.env.XPC_SERVICE_NAME||"").includes("dev.sootsim.daemon")||process.env.INVOCATION_ID)}async function mi(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
23
23
  sootsim serve \u2014 run the sootsim bridge in the foreground
24
24
 
25
25
  hosts the WS bridge that CLI commands talk to. once running, any sootsim
@@ -36,6 +36,6 @@ options:
36
36
  examples:
37
37
  sootsim serve
38
38
  sootsim serve --port 7668 --quiet
39
- `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q"),n=q();n&&z(n)&&(console.error(` a sootsim bridge is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),E();let a=await ce(),r=new L({port:i,writeLockfile:!0,sootbeanOrigin:a}),c=await r.startAsync({silent:s}),d=Date.now(),l=f=>{s||process.stdout.write(`${f}
39
+ `),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q"),n=q();n&&z(n)&&(console.error(` a sootsim bridge is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),E();let a=await ce(),r=new L({port:i,writeLockfile:!0,contrastOrigin:a}),c=await r.startAsync({silent:s}),d=Date.now(),l=f=>{s||process.stdout.write(`${f}
40
40
  `)},u=new Set,p=setInterval(()=>{let f=r.listSims(),y=new Set(f.map(g=>g.id));for(let g of f)if(!u.has(g.id)){let b=g.title||g.url||g.origin||"(unknown)";l(` + ${g.id} ${b}`)}for(let g of u)y.has(g)||l(` - ${g}`);u.clear();for(let g of y)u.add(g)},500);ee({event:"daemon_heartbeat",properties:{bridge_port:c,under_daemon:At(),platform:process.platform,subsource:"daemon"}}),te(),l(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&l(` (preferred port ${i} was taken \u2014 fell back to ${c})`),l(" ready for browser, electron, or headless playwright sims to connect"),l(" (ctrl-c to stop)");let m=async f=>{clearInterval(p),l(`
41
41
  ${f} received \u2014 shutting down after ${Math.round((Date.now()-d)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{mi as runServe};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as g,b as k}from"./chunk-GUCFICA4.js";import{b as S,c as x}from"./chunk-T6MEERRI.js";import{a as w}from"./chunk-44Z2X5R4.js";import"./chunk-2BQOZATN.js";import"./chunk-HXHB5A6R.js";import"./chunk-LCJSTEIR.js";import"./chunk-2XXPF6LP.js";import"./chunk-MG6JE3AM.js";import"./chunk-J7IFVTWX.js";import"./chunk-E75EBS77.js";import"./chunk-JNUGPBWC.js";import{H as v,M as f,O as m,l as b}from"./chunk-NU755HCE.js";import"./chunk-7L5IKIHC.js";import"./chunk-SBIAPF6E.js";import"./chunk-NIN75M5H.js";import"./chunk-F5HOYUD2.js";import{existsSync as r,mkdirSync as j,readFileSync as d,readdirSync as I,writeFileSync as D}from"fs";import{basename as p,dirname as y,join as i,relative as c,resolve as h}from"path";var T=["bun","pnpm","npm"];async function pe(n){(n.includes("--help")||n.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as g,b as k}from"./chunk-E5FOMYR6.js";import{b as S,c as x}from"./chunk-ZBJ5JMXM.js";import{a as w}from"./chunk-BHNOPI7I.js";import"./chunk-2I62CFYI.js";import"./chunk-JA52F67H.js";import"./chunk-D2QUTBZP.js";import"./chunk-EFMPSG7T.js";import"./chunk-JV43GSZB.js";import"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import"./chunk-RT3OS624.js";import{H as v,M as f,O as m,l as b}from"./chunk-PNPH4JLS.js";import"./chunk-JWZMAJC7.js";import"./chunk-MCMMRIJV.js";import"./chunk-7HMRWJHH.js";import"./chunk-6U3GMNTP.js";import{existsSync as r,mkdirSync as j,readFileSync as d,readdirSync as I,writeFileSync as D}from"fs";import{basename as p,dirname as y,join as i,relative as c,resolve as h}from"path";var T=["bun","pnpm","npm"];async function pe(n){(n.includes("--help")||n.includes("-h"))&&(console.log(`
3
3
  sootsim setup \u2014 set up this machine for SootSim
4
4
 
5
5
  usage:
@@ -94,4 +94,4 @@ module.exports = {
94
94
  4. inspect and drive it:
95
95
  sootsim describe
96
96
  sootsim do tap-text "Sign in"
97
- `)}function N(n,e){switch(n){case"bun":return`bunx ${e}`;case"pnpm":return`pnpm exec ${e}`;case"npm":return`npx ${e}`}}function ne(n,e){switch(n){case"bun":return`bun run ${e}`;case"pnpm":return`pnpm run ${e}`;case"npm":return`npm run ${e}`}}function oe(n){switch(n){case"bun":return"bun add -g sootsim";case"pnpm":return"pnpm add -g sootsim";case"npm":return"npm i -g sootsim"}}async function te(n,e){if(!e||n.dryRun)return;if(console.log(" last step:"),!process.stdin.isTTY){console.log(" run `sootsim open` after your Metro/Expo/One server is up");return}if(!await g("I'll run `sootsim open` for you now?",!0)){console.log(" later: sootsim open");return}let{runOpenCommand:o}=await import("./control-54R2XDLV.js");await o([],{port:7668})}async function R(n,e,o){return o.yes?!0:process.stdin.isTTY?g(n,e):(console.log(` ${n} ${e?"[Y/n]":"[y/N]"} n (non-interactive; pass --yes to accept)`),!1)}export{J as detectConfigScaffoldExt,M as detectNodeVersionPins,W as detectPreferredPackageManager,E as readMachineSetupStatus,pe as runSetup,de as shouldRunSetupForBareCommand};
97
+ `)}function N(n,e){switch(n){case"bun":return`bunx ${e}`;case"pnpm":return`pnpm exec ${e}`;case"npm":return`npx ${e}`}}function ne(n,e){switch(n){case"bun":return`bun run ${e}`;case"pnpm":return`pnpm run ${e}`;case"npm":return`npm run ${e}`}}function oe(n){switch(n){case"bun":return"bun add -g sootsim";case"pnpm":return"pnpm add -g sootsim";case"npm":return"npm i -g sootsim"}}async function te(n,e){if(!e||n.dryRun)return;if(console.log(" last step:"),!process.stdin.isTTY){console.log(" run `sootsim open` after your Metro/Expo/One server is up");return}if(!await g("I'll run `sootsim open` for you now?",!0)){console.log(" later: sootsim open");return}let{runOpenCommand:o}=await import("./control-7VDFEVWU.js");await o([],{port:7668})}async function R(n,e,o){return o.yes?!0:process.stdin.isTTY?g(n,e):(console.log(` ${n} ${e?"[Y/n]":"[y/N]"} n (non-interactive; pass --yes to accept)`),!1)}export{J as detectConfigScaffoldExt,M as detectNodeVersionPins,W as detectPreferredPackageManager,E as readMachineSetupStatus,pe as runSetup,de as shouldRunSetupForBareCommand};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import"./chunk-F5HOYUD2.js";import*as i from"fs";import*as I from"os";import*as a from"path";import{fileURLToPath as h}from"url";function $(){try{let t=h(import.meta.resolve("sootsim/package.json"));return a.join(a.dirname(t),"skills")}catch{let t=a.dirname(h(import.meta.url));return a.resolve(t,"../../skills")}}var d=$(),w=new Set(["all","codex","claude"]);function S(){console.log(`sootsim skill
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import"./chunk-6U3GMNTP.js";import*as i from"fs";import*as I from"os";import*as a from"path";import{fileURLToPath as h}from"url";function $(){try{let t=h(import.meta.resolve("sootsim/package.json"));return a.join(a.dirname(t),"skills")}catch{let t=a.dirname(h(import.meta.url));return a.resolve(t,"../../skills")}}var d=$(),w=new Set(["all","codex","claude"]);function S(){console.log(`sootsim skill
3
3
 
4
4
  install and inspect bundled SootSim agent skills.
5
5
 
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{k as f}from"./chunk-XESYTWFM.js";import"./chunk-D42IRY2Y.js";import"./chunk-ESK7B2BQ.js";import"./chunk-4J7BIXEB.js";import"./chunk-BVD2JFOX.js";import{a as t,b as n,c as l,d as c,e as a}from"./chunk-HRYKZ5YY.js";import"./chunk-HXSV263V.js";import"./chunk-UGWURWHN.js";import"./chunk-7K5K5NKB.js";import"./chunk-3L5EXWCP.js";import"./chunk-LM544J6V.js";import"./chunk-DB3GMVOH.js";import"./chunk-QWRYD2QV.js";import"./chunk-35EAEAN4.js";import"./chunk-F53C5HAB.js";import"./chunk-2XXPF6LP.js";import"./chunk-MG6JE3AM.js";import"./chunk-J7IFVTWX.js";import"./chunk-E75EBS77.js";import"./chunk-JNUGPBWC.js";import"./chunk-NU755HCE.js";import"./chunk-HTVB3FW2.js";import"./chunk-NIN75M5H.js";import"./chunk-F5HOYUD2.js";function p(){console.log(`
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{k as f}from"./chunk-WWZL7HNB.js";import"./chunk-AJ3CDBW6.js";import"./chunk-DEVNCWS4.js";import"./chunk-EKWOBYJO.js";import"./chunk-KY2KLPYL.js";import{a as t,b as n,c as l,d as c,e as a}from"./chunk-6Q2B7QHC.js";import"./chunk-NCXHUU7N.js";import"./chunk-FSKQZHM2.js";import"./chunk-PJBYZZWR.js";import"./chunk-UYLESZU3.js";import"./chunk-A5SO4OGE.js";import"./chunk-LBXHG4AU.js";import"./chunk-G42TLJVQ.js";import"./chunk-SPJSTRXX.js";import"./chunk-KIL5F7KD.js";import"./chunk-EFMPSG7T.js";import"./chunk-JV43GSZB.js";import"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import"./chunk-RT3OS624.js";import"./chunk-PNPH4JLS.js";import"./chunk-NME4QWJ3.js";import"./chunk-7HMRWJHH.js";import"./chunk-6U3GMNTP.js";function p(){console.log(`
3
3
  sootsim storage profile \u2014 manage isolated storage profiles
4
4
 
5
5
  usage:
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a}from"./chunk-NME4QWJ3.js";import"./chunk-7HMRWJHH.js";import"./chunk-6U3GMNTP.js";export{a as settingsStore};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b}from"./chunk-BHNOPI7I.js";import"./chunk-2I62CFYI.js";import"./chunk-PNPH4JLS.js";import"./chunk-6U3GMNTP.js";export{b as flushCliTelemetry,a as trackCliEvent};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{g as m,i as d,l as s}from"./chunk-35EAEAN4.js";import"./chunk-J7IFVTWX.js";import"./chunk-E75EBS77.js";import"./chunk-NU755HCE.js";import"./chunk-F5HOYUD2.js";import{writeFileSync as g}from"fs";function u(){console.log(`
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{g as m,i as d,l as s}from"./chunk-SPJSTRXX.js";import"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import"./chunk-PNPH4JLS.js";import"./chunk-6U3GMNTP.js";import{writeFileSync as g}from"fs";function u(){console.log(`
3
3
  sootsim timeline \u2014 control the semantic event timeline
4
4
 
5
5
  usage:
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as d}from"./chunk-Q4FB222M.js";import{e as m}from"./chunk-Z2E2DDIQ.js";import"./chunk-35EAEAN4.js";import"./chunk-J7IFVTWX.js";import"./chunk-E75EBS77.js";import{K as a,g as r,h as l}from"./chunk-NU755HCE.js";import{a as c}from"./chunk-7L5IKIHC.js";import"./chunk-F5HOYUD2.js";import{spawn as g}from"node:child_process";import u from"node:fs";import p from"node:os";import e from"node:path";var f="https://registry.npmjs.org/sootsim/latest";async function j(o){let n=o.indexOf("--channel"),t=n>=0&&o[n+1]?o[n+1]:void 0;console.log(`sootsim upgrade
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as d}from"./chunk-FDSFA7WL.js";import{e as m}from"./chunk-ZWJEJR73.js";import"./chunk-SPJSTRXX.js";import"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import{K as a,g as r,h as l}from"./chunk-PNPH4JLS.js";import{a as c}from"./chunk-JWZMAJC7.js";import"./chunk-6U3GMNTP.js";import{spawn as g}from"node:child_process";import u from"node:fs";import p from"node:os";import e from"node:path";var f="https://registry.npmjs.org/sootsim/latest";async function j(o){let n=o.indexOf("--channel"),t=n>=0&&o[n+1]?o[n+1]:void 0;console.log(`sootsim upgrade
3
3
  `),console.log("runtime:");let i=m();i&&(console.log(` pinned to ${i} \u2014 installing the pin, not channel latest`),console.log(" (run `sootsim runtime unpin` to follow latest again)")),await d(["install",...t?["--channel",t]:[]],{}),console.log(`
4
- cli:`),await $()}function h(){if(l())return{kind:"dev"};let o=process.argv[1]??"";try{o=u.realpathSync(o)}catch{}let n=e.sep;if(o.includes(`${n}_npx${n}`)||o.includes(`${n}.bunx${n}`))return{kind:"npx"};if(o.includes(`${n}.bun${n}`))return{kind:"global",command:"bun",args:["add","-g","sootsim@latest"]};if(o.includes(`${n}pnpm${n}`))return{kind:"global",command:"pnpm",args:["add","-g","sootsim@latest"]};let t=e.join(r(),"cli");if(o.startsWith(`${t}${n}`))return{kind:"global",command:"npm",args:["i","-g","--prefix",t,"sootsim@latest"]};let i=e.resolve(process.env.SOOTSIM_CLI_PREFIX||e.join(p.homedir(),".local"));return o.startsWith(`${i}${n}`)?{kind:"global",command:"npm",args:["i","-g","--prefix",i,"sootsim@latest"]}:{kind:"global",command:"npm",args:["i","-g","sootsim@latest"]}}async function $(){let o=c(),n=await k();if(!n){console.log(` v${o} \u2014 couldn't reach the npm registry, skipped`);return}if(a(n,o)<=0){console.log(` v${o} (latest)`);return}let t=h();if(console.log(` v${o} \u2192 v${n}`),t.kind==="dev"){console.log(" running from the soot dev checkout \u2014 pull instead of upgrading");return}if(t.kind==="npx"){console.log(" running from the npx cache \u2014 get the latest with:"),console.log(" npx sootsim@latest");return}let i=`${t.command} ${t.args.join(" ")}`;console.log(` updating global install (${i})\u2026`),await v(t.command,t.args)?console.log(` updated to v${n}`):(console.log(" update failed \u2014 run it yourself:"),console.log(` ${i}`))}function v(o,n){return new Promise(t=>{let i=g(o,n,{stdio:"inherit"});i.on("error",()=>t(!1)),i.on("exit",s=>t(s===0))})}async function k(){try{let o=await fetch(f,{headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let n=await o.json();return typeof n.version=="string"&&n.version?n.version:null}catch{return null}}export{j as runUpgrade};
4
+ cli:`),await $()}function h(){if(l())return{kind:"dev"};let o=process.argv[1]??"";try{o=u.realpathSync(o)}catch{}let n=e.sep;if(o.includes(`${n}_npx${n}`)||o.includes(`${n}.bunx${n}`))return{kind:"npx"};if(o.includes(`${n}.bun${n}`))return{kind:"global",command:"bun",args:["add","-g","sootsim@latest"]};if(o.includes(`${n}pnpm${n}`))return{kind:"global",command:"pnpm",args:["add","-g","sootsim@latest"]};let t=e.join(r(),"cli");if(o.startsWith(`${t}${n}`))return{kind:"global",command:"npm",args:["i","-g","--prefix",t,"sootsim@latest"]};let i=e.resolve(process.env.SOOTSIM_CLI_PREFIX||e.join(p.homedir(),".local"));return o.startsWith(`${i}${n}`)?{kind:"global",command:"npm",args:["i","-g","--prefix",i,"sootsim@latest"]}:{kind:"global",command:"npm",args:["i","-g","sootsim@latest"]}}async function $(){let o=c(),n=await k();if(!n){console.log(` v${o} \u2014 couldn't reach the npm registry, skipped`);return}if(a(n,o)<=0){console.log(` v${o} (latest)`);return}let t=h();if(console.log(` v${o} \u2192 v${n}`),t.kind==="dev"){console.log(" running from the Contrast dev checkout \u2014 pull instead of upgrading");return}if(t.kind==="npx"){console.log(" running from the npx cache \u2014 get the latest with:"),console.log(" npx sootsim@latest");return}let i=`${t.command} ${t.args.join(" ")}`;console.log(` updating global install (${i})\u2026`),await v(t.command,t.args)?console.log(` updated to v${n}`):(console.log(" update failed \u2014 run it yourself:"),console.log(` ${i}`))}function v(o,n){return new Promise(t=>{let i=g(o,n,{stdio:"inherit"});i.on("error",()=>t(!1)),i.on("exit",s=>t(s===0))})}async function k(){try{let o=await fetch(f,{headers:{accept:"application/json"},signal:AbortSignal.timeout(8e3)});if(!o.ok)return null;let n=await o.json();return typeof n.version=="string"&&n.version?n.version:null}catch{return null}}export{j as runUpgrade};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b,c}from"./chunk-34MFG4IM.js";import"./chunk-ALE5MU5Z.js";import"./chunk-FSKQZHM2.js";import"./chunk-PJBYZZWR.js";import"./chunk-UYLESZU3.js";import"./chunk-SPJSTRXX.js";import"./chunk-BHNOPI7I.js";import"./chunk-2I62CFYI.js";import"./chunk-4A6HM2K3.js";import"./chunk-EPQ5EZBJ.js";import"./chunk-PNPH4JLS.js";import"./chunk-6U3GMNTP.js";export{a as resolveDefaultUploadOrigin,b as resolvePublicPreviewOrigin,c as runUpload};
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.227 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as s,d as l,i as r}from"./chunk-Z2E2DDIQ.js";import{a as i}from"./chunk-LCJSTEIR.js";import"./chunk-NU755HCE.js";import{a as t}from"./chunk-7L5IKIHC.js";import"./chunk-F5HOYUD2.js";async function f(c){let{IS_BETA:m,BETA_LABEL:a}=await import("./beta-WLLSIVLW.js"),u=m?` \xB7 ${a}`:"";console.log(`sootsim v${t()}${u}`);let o=i(),e=l();o.isDevBridge?(console.log(o.primary),o.installedRuntime&&console.log(`${o.installedRuntime} \xB7 ${e}`)):o.primary==="runtime not installed"?console.log("runtime not installed \u2014 run `sootsim runtime install`"):console.log(`${o.primary} \xB7 ${e}`);let n=await r({channel:e});n.pinned&&console.log(` runtime pinned to v${n.pinned} (\`sootsim runtime unpin\` to follow latest)`),n.outdated&&n.latest&&console.log(`
1
+ /*! sootsim v0.1.228 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as s,d as l,i as r}from"./chunk-ZWJEJR73.js";import{a as i}from"./chunk-D2QUTBZP.js";import"./chunk-PNPH4JLS.js";import{a as t}from"./chunk-JWZMAJC7.js";import"./chunk-6U3GMNTP.js";async function f(c){let{IS_BETA:m,BETA_LABEL:a}=await import("./beta-ZQCASJ7C.js"),u=m?` \xB7 ${a}`:"";console.log(`sootsim v${t()}${u}`);let o=i(),e=l();o.isDevBridge?(console.log(o.primary),o.installedRuntime&&console.log(`${o.installedRuntime} \xB7 ${e}`)):o.primary==="runtime not installed"?console.log("runtime not installed \u2014 run `sootsim runtime install`"):console.log(`${o.primary} \xB7 ${e}`);let n=await r({channel:e});n.pinned&&console.log(` runtime pinned to v${n.pinned} (\`sootsim runtime unpin\` to follow latest)`),n.outdated&&n.latest&&console.log(`
3
3
  \u2191 runtime v${n.latest} available \u2014 run \`sootsim upgrade\``),console.log(`
4
4
  what's new: ${s}`)}export{f as runVersion};