sootsim 0.1.66 → 0.1.67

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 (147) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-IW7CCSSI.js → agent-Z45KTLTP.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-5DJBERZP.js → agent-wrapper-EEKVEJOC.js} +2 -2
  4. package/dist-cli/chunks/{assert-RHILK3WR.js → assert-MDYZKXZ6.js} +2 -2
  5. package/dist-cli/chunks/auto-bootstrap-YZ6C6VYO.js +2 -0
  6. package/dist-cli/chunks/beta-WXH75XUE.js +2 -0
  7. package/dist-cli/chunks/chunk-2HKCZLY7.js +372 -0
  8. package/dist-cli/chunks/{chunk-UMXVWFST.js → chunk-2I535GZU.js} +1 -1
  9. package/dist-cli/chunks/{chunk-TJEP4DBA.js → chunk-3KVVIZ6M.js} +2 -2
  10. package/dist-cli/chunks/chunk-42NMKOVE.js +3 -0
  11. package/dist-cli/chunks/{chunk-WAOLC7WV.js → chunk-4H6LBA4A.js} +1 -1
  12. package/dist-cli/chunks/{chunk-LVFWALS4.js → chunk-4QSGVTBE.js} +2 -2
  13. package/dist-cli/chunks/{chunk-T4YLDM5C.js → chunk-52RZ6TSZ.js} +3 -3
  14. package/dist-cli/chunks/{chunk-AYBGSHQK.js → chunk-5WRBVYML.js} +2 -2
  15. package/dist-cli/chunks/{chunk-BD76YSRN.js → chunk-67566AJS.js} +2 -2
  16. package/dist-cli/chunks/chunk-6O64VUC6.js +2 -0
  17. package/dist-cli/chunks/chunk-7PQHQOCI.js +186 -0
  18. package/dist-cli/chunks/{chunk-V4SZERWD.js → chunk-AQ7YR4MO.js} +14 -14
  19. package/dist-cli/chunks/{chunk-6AP6LXVV.js → chunk-ATRGAFJD.js} +1 -1
  20. package/dist-cli/chunks/{chunk-LRBMW2WC.js → chunk-BCVVANS5.js} +2 -2
  21. package/dist-cli/chunks/chunk-CUNQTNH4.js +35 -0
  22. package/dist-cli/chunks/{chunk-DEQ7RED3.js → chunk-DOWYG3HG.js} +2 -2
  23. package/dist-cli/chunks/{chunk-XZ5SQJM2.js → chunk-EJTXYZEF.js} +128 -36
  24. package/dist-cli/chunks/{chunk-4NT6VRUU.js → chunk-F23Y4HMT.js} +1 -1
  25. package/dist-cli/chunks/{chunk-M2Q4FXRE.js → chunk-F4RC4AOY.js} +1 -1
  26. package/dist-cli/chunks/chunk-GFVC6EEB.js +1 -0
  27. package/dist-cli/chunks/{chunk-BEQD2DSK.js → chunk-HW5YHSIE.js} +1 -1
  28. package/dist-cli/chunks/{chunk-VRV2X4X2.js → chunk-IB4BRND4.js} +1 -1
  29. package/dist-cli/chunks/{chunk-22CO2ZE3.js → chunk-IBWN764Q.js} +2 -2
  30. package/dist-cli/chunks/chunk-JE4JBSNJ.js +119 -0
  31. package/dist-cli/chunks/{chunk-HWCZYW6M.js → chunk-K4PKR2EO.js} +2 -2
  32. package/dist-cli/chunks/chunk-KBJ2WHII.js +73 -0
  33. package/dist-cli/chunks/chunk-KR36VJSN.js +1 -0
  34. package/dist-cli/chunks/{chunk-EEMGSSWY.js → chunk-LQ5BA5JU.js} +2 -2
  35. package/dist-cli/chunks/chunk-MIAAZSSE.js +12 -0
  36. package/dist-cli/chunks/{chunk-BTHB3PMG.js → chunk-N4JRDJMN.js} +3 -3
  37. package/dist-cli/chunks/{chunk-FXF2FHPI.js → chunk-NYR3Z44O.js} +2 -2
  38. package/dist-cli/chunks/{chunk-EIQLQDKX.js → chunk-O624O5MO.js} +2 -2
  39. package/dist-cli/chunks/{chunk-4LYNJPUM.js → chunk-SH6HMUCY.js} +2 -2
  40. package/dist-cli/chunks/chunk-SVFSMAZN.js +2 -0
  41. package/dist-cli/chunks/chunk-TEMZK6Q2.js +1 -0
  42. package/dist-cli/chunks/{chunk-D4VEI6MI.js → chunk-TLTS533S.js} +1 -1
  43. package/dist-cli/chunks/chunk-U47AHSGE.js +23 -0
  44. package/dist-cli/chunks/{chunk-LCKLQSZX.js → chunk-XCRUPKWB.js} +2 -2
  45. package/dist-cli/chunks/{chunk-NCSGLZRV.js → chunk-YGQV3CUV.js} +2 -2
  46. package/dist-cli/chunks/{chunk-UNSLXX7V.js → chunk-ZJJKYJMH.js} +2 -2
  47. package/dist-cli/chunks/{chunk-GDCMTHEU.js → chunk-ZO7SGE65.js} +1 -1
  48. package/dist-cli/chunks/{chunk-HIN5TAAL.js → chunk-ZP2HMCKS.js} +1 -1
  49. package/dist-cli/chunks/cli-version-5LGQQE5P.js +2 -0
  50. package/dist-cli/chunks/{compat-I7JXYUJN.js → compat-5MMZ4R3Q.js} +3 -3
  51. package/dist-cli/chunks/{config-3HR5RKVH.js → config-YWN44WJQ.js} +2 -2
  52. package/dist-cli/chunks/control-LUCFDAZI.js +2 -0
  53. package/dist-cli/chunks/{cpu-profile-ZVHMTVAU.js → cpu-profile-VFGUVXU5.js} +2 -2
  54. package/dist-cli/chunks/{daemon-VYRTYH55.js → daemon-ONX5ZBXF.js} +2 -2
  55. package/dist-cli/chunks/{debug-CQ6Y7GJ2.js → debug-CPOG32OT.js} +5 -5
  56. package/dist-cli/chunks/demo-app-registry-LWT6JLU6.js +2 -0
  57. package/dist-cli/chunks/{detox-7ZKTGLDR.js → detox-J6NGSZR5.js} +2 -2
  58. package/dist-cli/chunks/{device-4M6Z7E2N.js → device-QYOQXI2P.js} +2 -2
  59. package/dist-cli/chunks/{diagnose-SMQLYGNX.js → diagnose-MMW4LJLA.js} +2 -2
  60. package/dist-cli/chunks/drivers-NRWUJJCD.js +2 -0
  61. package/dist-cli/chunks/{electron-6N2MIN5W.js → electron-IK3HIZY4.js} +3 -3
  62. package/dist-cli/chunks/flow-2MB7HINM.js +2 -0
  63. package/dist-cli/chunks/{hints-RJCZS2E3.js → hints-KZOD56U5.js} +2 -2
  64. package/dist-cli/chunks/{home-paths-DCUNA3CD.js → home-paths-R2YZZTUM.js} +2 -2
  65. package/dist-cli/chunks/inspect-ZARO3HQ4.js +970 -0
  66. package/dist-cli/chunks/install-O67RTYCX.js +2 -0
  67. package/dist-cli/chunks/{install-desktop-C7424OSW.js → install-desktop-4GH5I7SC.js} +3 -3
  68. package/dist-cli/chunks/{keys-TXUQOAZ3.js → keys-AXEFZUUI.js} +2 -2
  69. package/dist-cli/chunks/{launch-MVA44QTC.js → launch-QLE56ON7.js} +3 -3
  70. package/dist-cli/chunks/{login-NHO2WTHC.js → login-J45NQQM6.js} +4 -4
  71. package/dist-cli/chunks/{logout-SRRWADCE.js → logout-ZE5OUBB7.js} +2 -2
  72. package/dist-cli/chunks/{maestro-UHNXEZAN.js → maestro-FS6CAKDD.js} +2 -2
  73. package/dist-cli/chunks/{preview-ETIUP7KC.js → preview-TSU5IXVR.js} +2 -2
  74. package/dist-cli/chunks/{profile-MY5JFVIF.js → profile-ZBJ4TYWA.js} +2 -2
  75. package/dist-cli/chunks/{react-KCMC4GL3.js → react-TGZLTTYN.js} +2 -2
  76. package/dist-cli/chunks/record-JSBFUNOD.js +54 -0
  77. package/dist-cli/chunks/runtime-DGDQ7NVY.js +2 -0
  78. package/dist-cli/chunks/{runtime-delivery-LQZIWQU6.js → runtime-delivery-36UMAXOV.js} +2 -2
  79. package/dist-cli/chunks/screenshot-3CHMALUJ.js +33 -0
  80. package/dist-cli/chunks/{screenshot-mode-USPWASI3.js → screenshot-mode-C547UT5H.js} +2 -2
  81. package/dist-cli/chunks/{screenshots-EPEDNA6H.js → screenshots-XCNGSNYG.js} +2 -2
  82. package/dist-cli/chunks/{server-222QT33M.js → server-W37X3IW7.js} +6 -6
  83. package/dist-cli/chunks/setup-repo-DETS5ZJT.js +2 -0
  84. package/dist-cli/chunks/{skills-6XRREE2M.js → skills-OXZLDNDW.js} +2 -2
  85. package/dist-cli/chunks/{start-YCAZBZEX.js → start-N6ZQYUBP.js} +4 -4
  86. package/dist-cli/chunks/store-QOXJKJUZ.js +2 -0
  87. package/dist-cli/chunks/telemetry-74LX7WG4.js +2 -0
  88. package/dist-cli/chunks/{test-6TNRHSWC.js → test-DWZ7PRSW.js} +3 -3
  89. package/dist-cli/chunks/{three-mode-MDOLHGXW.js → three-mode-P2R7KA62.js} +2 -2
  90. package/dist-cli/chunks/{timeline-72MWE44G.js → timeline-VPES3YCN.js} +3 -3
  91. package/dist-cli/chunks/{upgrade-IHZ4DFAE.js → upgrade-NYQLA4UJ.js} +2 -2
  92. package/dist-cli/chunks/upload-YOMMYESV.js +2 -0
  93. package/dist-cli/chunks/{web-JLJSJUS2.js → web-OTALJKK5.js} +2 -2
  94. package/dist-cli/chunks/what-happened-GZ73H6KF.js +22 -0
  95. package/dist-cli/chunks/{whoami-2EYGCRDQ.js → whoami-UDLQK7IY.js} +2 -2
  96. package/dist-lib/agent-daemon-client.cjs +1 -1
  97. package/dist-lib/agent-events.cjs +1 -1
  98. package/dist-lib/agent-sessions.cjs +1 -1
  99. package/dist-lib/attached-projects.cjs +1 -1
  100. package/dist-lib/auth/shared-session.cjs +1 -1
  101. package/dist-lib/backend-origin.cjs +1 -1
  102. package/dist-lib/bridge-constants.cjs +1 -1
  103. package/dist-lib/cli-constants.cjs +1 -1
  104. package/dist-lib/config.cjs +1 -1
  105. package/dist-lib/dev-bundle-resolution.cjs +9 -2
  106. package/dist-lib/home-paths.cjs +1 -1
  107. package/dist-lib/host/bridge-host.cjs +23 -7
  108. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  109. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  110. package/dist-lib/index.cjs +1 -1
  111. package/dist-lib/metro.cjs +1 -1
  112. package/dist-lib/profiles.cjs +1 -1
  113. package/dist-lib/render-mode.cjs +1 -1
  114. package/dist-lib/vite-base.cjs +23 -7
  115. package/dist-lib/vite.cjs +1 -1
  116. package/package.json +1 -1
  117. package/dist-cli/chunks/auto-bootstrap-PS2UDBP7.js +0 -2
  118. package/dist-cli/chunks/beta-XLYWSKEA.js +0 -2
  119. package/dist-cli/chunks/chunk-5MVFADNH.js +0 -3
  120. package/dist-cli/chunks/chunk-7NYW73Q6.js +0 -2
  121. package/dist-cli/chunks/chunk-EMMX6RF7.js +0 -73
  122. package/dist-cli/chunks/chunk-FIIBCY5I.js +0 -3
  123. package/dist-cli/chunks/chunk-G4VWDOWB.js +0 -17
  124. package/dist-cli/chunks/chunk-GMKGJHVG.js +0 -1
  125. package/dist-cli/chunks/chunk-M3ZEZHOB.js +0 -34
  126. package/dist-cli/chunks/chunk-MWTMLNGM.js +0 -348
  127. package/dist-cli/chunks/chunk-NQKBIKUZ.js +0 -1
  128. package/dist-cli/chunks/chunk-QMRXLBPN.js +0 -11
  129. package/dist-cli/chunks/chunk-X4HQLK4V.js +0 -119
  130. package/dist-cli/chunks/chunk-XOTJSR4T.js +0 -2
  131. package/dist-cli/chunks/chunk-YSQV4D7P.js +0 -1
  132. package/dist-cli/chunks/chunk-Z6HSVZIO.js +0 -100
  133. package/dist-cli/chunks/cli-version-ESQ2S6N5.js +0 -2
  134. package/dist-cli/chunks/control-TDZXFNVT.js +0 -2
  135. package/dist-cli/chunks/demo-app-registry-JAYU7BBM.js +0 -2
  136. package/dist-cli/chunks/drivers-SIY6JBEM.js +0 -2
  137. package/dist-cli/chunks/flow-BZEWL7UQ.js +0 -2
  138. package/dist-cli/chunks/inspect-T5NC7HHB.js +0 -1025
  139. package/dist-cli/chunks/install-YTJI5RS7.js +0 -2
  140. package/dist-cli/chunks/record-DHDSXC2Y.js +0 -51
  141. package/dist-cli/chunks/runtime-AJP6V5LM.js +0 -2
  142. package/dist-cli/chunks/screenshot-4KPEEI6I.js +0 -28
  143. package/dist-cli/chunks/setup-repo-D56L3CEB.js +0 -2
  144. package/dist-cli/chunks/store-Z32KZ34K.js +0 -2
  145. package/dist-cli/chunks/telemetry-RFTX2BZK.js +0 -2
  146. package/dist-cli/chunks/upload-G5C7LJWG.js +0 -2
  147. package/dist-cli/chunks/what-happened-BUXSJ3QS.js +0 -15
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as o}from"./chunk-3KVVIZ6M.js";import"./chunk-ATRGAFJD.js";import"./chunk-N4JRDJMN.js";import"./chunk-DOWYG3HG.js";import"./chunk-O624O5MO.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";async function t(n){console.error(" note: `sootsim install` is now `sootsim setup-repo`. forwarding\u2026\n"),await o(n)}export{t as runInstall};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as b}from"./chunk-6AP6LXVV.js";import{a as x}from"./chunk-GDCMTHEU.js";import"./chunk-D4VEI6MI.js";import{spawn as k,spawnSync as u}from"child_process";import{chmodSync as S,createWriteStream as E,existsSync as w,mkdirSync as y,renameSync as T,rmSync as g,statSync as P}from"fs";import{tmpdir as D}from"os";import{dirname as M,join as f,resolve as v}from"path";var h="https://sootbean.com/api/electron-release";function A(){let r=process.arch;if(process.platform==="darwin"){let o=r==="arm64"?"mac-arm64":"mac-x64",n=`sootsim-latest-${o}.dmg`;return{platform:o,filename:n,url:`${h}/${n}`,install:_}}if(process.platform==="linux"){let o="sootsim-latest-linux-x64.AppImage";return{platform:"linux-x64",filename:o,url:`${h}/${o}`,install:L}}if(process.platform==="win32"){let o="sootsim-latest-win-x64.exe";return{platform:"win-x64",filename:o,url:`${h}/${o}`,install:C}}return null}async function O({url:r,dest:o,onProgress:n}){let s=await fetch(r,{redirect:"follow"});if(!s.ok)throw new Error(`download failed: ${s.status} ${s.statusText} (${r})`);let t=s.headers.get("content-length"),a=t?Number(t):null;if(!s.body)throw new Error("download failed: empty response body");y(M(o),{recursive:!0});let i=E(o),d=s.body.getReader(),c=0;try{for(;;){let{done:l,value:p}=await d.read();if(l)break;i.write(Buffer.from(p)),c+=p.byteLength,n?.(c,a)}}finally{await new Promise((l,p)=>{i.end(e=>e?p(e):l())})}}function I(r,o){let n=(r/1048576).toFixed(1);if(!o)return` ${n} MB`;let s=Math.min(100,Math.round(r/o*100)),t=(o/(1024*1024)).toFixed(1),a=24,i=Math.round(s/100*a);return` ${"\u2588".repeat(i)+"\u2591".repeat(a-i)} ${s}% ${n} / ${t} MB`}async function _(r){let o=u("hdiutil",["attach","-nobrowse","-readonly",r],{encoding:"utf8"});if(o.status!==0)throw new Error(`hdiutil attach failed: ${o.stderr||o.stdout}`.trim());let n=o.stdout.trim().split(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as b}from"./chunk-ATRGAFJD.js";import{a as x}from"./chunk-ZO7SGE65.js";import"./chunk-TLTS533S.js";import{spawn as k,spawnSync as u}from"child_process";import{chmodSync as S,createWriteStream as E,existsSync as w,mkdirSync as y,renameSync as T,rmSync as g,statSync as P}from"fs";import{tmpdir as D}from"os";import{dirname as M,join as f,resolve as v}from"path";var h="https://sootbean.com/api/electron-release";function A(){let r=process.arch;if(process.platform==="darwin"){let o=r==="arm64"?"mac-arm64":"mac-x64",n=`sootsim-latest-${o}.dmg`;return{platform:o,filename:n,url:`${h}/${n}`,install:_}}if(process.platform==="linux"){let o="sootsim-latest-linux-x64.AppImage";return{platform:"linux-x64",filename:o,url:`${h}/${o}`,install:L}}if(process.platform==="win32"){let o="sootsim-latest-win-x64.exe";return{platform:"win-x64",filename:o,url:`${h}/${o}`,install:C}}return null}async function O({url:r,dest:o,onProgress:n}){let s=await fetch(r,{redirect:"follow"});if(!s.ok)throw new Error(`download failed: ${s.status} ${s.statusText} (${r})`);let t=s.headers.get("content-length"),a=t?Number(t):null;if(!s.body)throw new Error("download failed: empty response body");y(M(o),{recursive:!0});let i=E(o),d=s.body.getReader(),c=0;try{for(;;){let{done:l,value:p}=await d.read();if(l)break;i.write(Buffer.from(p)),c+=p.byteLength,n?.(c,a)}}finally{await new Promise((l,p)=>{i.end(e=>e?p(e):l())})}}function I(r,o){let n=(r/1048576).toFixed(1);if(!o)return` ${n} MB`;let s=Math.min(100,Math.round(r/o*100)),t=(o/(1024*1024)).toFixed(1),a=24,i=Math.round(s/100*a);return` ${"\u2588".repeat(i)+"\u2591".repeat(a-i)} ${s}% ${n} / ${t} MB`}async function _(r){let o=u("hdiutil",["attach","-nobrowse","-readonly",r],{encoding:"utf8"});if(o.status!==0)throw new Error(`hdiutil attach failed: ${o.stderr||o.stdout}`.trim());let n=o.stdout.trim().split(`
3
3
  `),t=n[n.length-1].split(" ").pop()?.trim();if(!t||!w(t))throw new Error(`could not determine dmg mount point (output: ${o.stdout})`);let a=f(t,"sootsim.app");if(!w(a))throw u("hdiutil",["detach","-force",t]),new Error(`sootsim.app not found inside ${t}`);let i="/Applications",d=v(process.env.HOME||"","Applications"),c=i;try{let m=f(i,`.sootsim-write-probe-${process.pid}`);u("touch",[m]),w(m)?g(m,{force:!0}):c=d}catch{c=d}c===d&&y(c,{recursive:!0});let l=f(c,"sootsim.app");w(l)&&g(l,{recursive:!0,force:!0});let p=u("cp",["-R",a,l]),e=u("hdiutil",["detach","-force",t]);if(p.status!==0)throw new Error(`copy to ${l} failed: ${p.stderr?.toString()||""}`.trim());return e.status!==0&&console.warn(` warning: failed to unmount ${t} (${e.stderr?.toString().trim()||"unknown error"})`),u("xattr",["-dr","com.apple.quarantine",l]),l}async function L(r){let o=v(process.env.HOME||"","Applications");y(o,{recursive:!0});let n=f(o,"sootsim.AppImage");return w(n)&&g(n,{force:!0}),T(r,n),S(n,493),n}async function C(r){return await new Promise((o,n)=>{let s=k("cmd",["/c","start",'""',"/wait",r],{stdio:"inherit"});s.once("error",n),s.once("exit",t=>{t===0?o():n(new Error(`installer exited with code ${t}`))})}),r}async function Y(r){(r.includes("--help")||r.includes("-h"))&&(console.log(`
4
4
  sootsim install-desktop \u2014 download and install the optional desktop GUI
5
5
 
@@ -20,4 +20,4 @@ examples:
20
20
  `),process.exit(0));let o=r.includes("--yes")||r.includes("-y")||process.env.SOOTSIM_NO_PROMPT==="1"||process.env.CI==="1"||!process.stdin.isTTY,n=r.includes("--force"),s=x();if(s&&!n){console.log(` sootsim desktop already installed at: ${s.path}`),console.log(" pass --force to reinstall.");return}let t=A();if(t||(console.error(` no desktop build available for ${process.platform}/${process.arch}.`),console.error(" supported: darwin-arm64, darwin-x64, linux-x64, win32-x64"),process.exit(1)),console.log(` platform: ${t.platform}`),console.log(` download: ${t.url}`),console.log(),!o){if(!await b("download and install now?",!0)){console.log(" cancelled.");return}console.log()}let a=f(D(),`sootsim-install-${Date.now()}`),i=f(a,t.filename),d=0;process.stdout.write(` downloading ${t.filename}...
21
21
  `);try{await O({url:t.url,dest:i,onProgress:(e,m)=>{let $=Date.now();$-d<100&&e<(m??1/0)||(d=$,process.stdout.isTTY&&process.stdout.write(`\r\x1B[2K${I(e,m)}`))}})}catch(e){g(a,{recursive:!0,force:!0}),console.error(`
22
22
  download failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}process.stdout.isTTY&&process.stdout.write(`
23
- `);let c=P(i).size;console.log(` downloaded ${(c/(1024*1024)).toFixed(1)} MB`),console.log(),console.log(" installing...");let{trackCliEvent:l,flushCliTelemetry:p}=await import("./telemetry-RFTX2BZK.js");try{let e=await t.install(i);l({event:"cli_install_desktop_succeeded",properties:{platform:t.platform,size_bytes:c}}),console.log(` installed: ${e}`)}catch(e){l({event:"cli_install_desktop_failed",properties:{platform:t.platform,error:e instanceof Error?e.message:String(e)}}),await p(),console.error(` install failed: ${e instanceof Error?e.message:String(e)}`),console.error(` keeping download at ${i} for manual install.`),process.exit(1)}finally{g(a,{recursive:!0,force:!0})}console.log(),console.log(" next steps:"),console.log(" sootsim electron launch the desktop app"),console.log(" sootsim open <target> open a demo or bundle in it")}export{Y as runInstallDesktop};
23
+ `);let c=P(i).size;console.log(` downloaded ${(c/(1024*1024)).toFixed(1)} MB`),console.log(),console.log(" installing...");let{trackCliEvent:l,flushCliTelemetry:p}=await import("./telemetry-74LX7WG4.js");try{let e=await t.install(i);l({event:"cli_install_desktop_succeeded",properties:{platform:t.platform,size_bytes:c}}),console.log(` installed: ${e}`)}catch(e){l({event:"cli_install_desktop_failed",properties:{platform:t.platform,error:e instanceof Error?e.message:String(e)}}),await p(),console.error(` install failed: ${e instanceof Error?e.message:String(e)}`),console.error(` keeping download at ${i} for manual install.`),process.exit(1)}finally{g(a,{recursive:!0,force:!0})}console.log(),console.log(" next steps:"),console.log(" sootsim electron launch the desktop app"),console.log(" sootsim open <target> open a demo or bundle in it")}export{Y as runInstallDesktop};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as l,b as d,c as k,d as y,e as g}from"./chunk-EEMGSSWY.js";import{d as c}from"./chunk-EIQLQDKX.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";async function a(){let s=await c();return s?.token||(process.stderr.write(" sootsim keys ... needs you to be signed in.\n run `sootsim login` first.\n"),process.exit(1)),{origin:s.origin,token:s.token}}function f(s){if(!s)return"never";try{return new Date(s).toLocaleString()}catch{return s}}async function h(s){let i=s[0];if(!i||i==="--help"||i==="-h"){u();return}if(i==="list"){let{origin:o,token:e}=await a(),n=await fetch(`${o.replace(/\/$/,"")}/api/sootsim/billing/keys`,{headers:{authorization:`Bearer ${e}`}});n.ok||(console.error(` keys list failed (${n.status})`),process.exit(1));let{keys:r}=await n.json();if(r.length===0){console.log(" no keys. create one with `sootsim keys create <label>`.");return}for(let t of r)console.log(` ${t.keyPrefix}\u2026 ${t.label.padEnd(24)} scopes=${t.scopes.join(",")} last=${f(t.lastUsedAt)} id=${t.id}`);return}if(i==="create"){let o=s[1]?.trim();o||(console.error(" usage: sootsim keys create <label>"),process.exit(1));let{origin:e,token:n}=await a(),r=await fetch(`${e.replace(/\/$/,"")}/api/sootsim/billing/keys`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({label:o})});r.ok||(console.error(` keys create failed (${r.status}): ${await r.text()}`),process.exit(1));let t=await r.json();console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as l,b as d,c as k,d as y,e as g}from"./chunk-LQ5BA5JU.js";import{d as c}from"./chunk-O624O5MO.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";async function a(){let s=await c();return s?.token||(process.stderr.write(" sootsim keys ... needs you to be signed in.\n run `sootsim login` first.\n"),process.exit(1)),{origin:s.origin,token:s.token}}function f(s){if(!s)return"never";try{return new Date(s).toLocaleString()}catch{return s}}async function h(s){let i=s[0];if(!i||i==="--help"||i==="-h"){u();return}if(i==="list"){let{origin:o,token:e}=await a(),n=await fetch(`${o.replace(/\/$/,"")}/api/sootsim/billing/keys`,{headers:{authorization:`Bearer ${e}`}});n.ok||(console.error(` keys list failed (${n.status})`),process.exit(1));let{keys:r}=await n.json();if(r.length===0){console.log(" no keys. create one with `sootsim keys create <label>`.");return}for(let t of r)console.log(` ${t.keyPrefix}\u2026 ${t.label.padEnd(24)} scopes=${t.scopes.join(",")} last=${f(t.lastUsedAt)} id=${t.id}`);return}if(i==="create"){let o=s[1]?.trim();o||(console.error(" usage: sootsim keys create <label>"),process.exit(1));let{origin:e,token:n}=await a(),r=await fetch(`${e.replace(/\/$/,"")}/api/sootsim/billing/keys`,{method:"POST",headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},body:JSON.stringify({label:o})});r.ok||(console.error(` keys create failed (${r.status}): ${await r.text()}`),process.exit(1));let t=await r.json();console.log(`
3
3
  created: ${t.record.label} (${t.record.keyPrefix}\u2026)`),console.log(` scopes: ${t.record.scopes.join(",")}`),console.log(`
4
4
  secret: ${t.secret}
5
5
  `),console.log(` copy this now \u2014 we can't show it again.
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import"./chunk-GMKGJHVG.js";import{b as m}from"./chunk-Z6HSVZIO.js";import{a as u}from"./chunk-GDCMTHEU.js";import"./chunk-NQKBIKUZ.js";import"./chunk-AYBGSHQK.js";import"./chunk-HIN5TAAL.js";import{D as c,E as r,F as l,y as s,z as a}from"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";import{spawn as p}from"child_process";import{existsSync as h}from"fs";async function I(n){if(n.includes("--help")||n.includes("-h")){console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import"./chunk-TEMZK6Q2.js";import{b as m}from"./chunk-7PQHQOCI.js";import{a as u}from"./chunk-ZO7SGE65.js";import"./chunk-GFVC6EEB.js";import"./chunk-5WRBVYML.js";import"./chunk-ZP2HMCKS.js";import{D as c,E as r,F as l,y as s,z as a}from"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import{spawn as p}from"child_process";import{existsSync as h}from"fs";async function I(n){if(n.includes("--help")||n.includes("-h")){console.log(`
3
3
  sootsim launch \u2014 one-shot: install runtime if needed, start daemon, open app
4
4
 
5
5
  usage:
@@ -13,4 +13,4 @@ options:
13
13
  examples:
14
14
  sootsim launch
15
15
  sootsim launch --version 1.2.3
16
- `);return}let e=n.includes("--no-runtime-install"),i=n.indexOf("--channel"),t=i>=0&&n[i+1]?n[i+1]:"stable",o=n.indexOf("--version"),f=o>=0&&n[o+1]?n[o+1]:void 0;s(),await v({skipAutoInstall:e,channel:t,explicitVersion:f}),await d(),await x()}async function v(n){let e=a(),i=c();if(e&&i)return;n.skipAutoInstall&&(console.error(" no sootsim runtime installed. run `sootsim runtime install` first, or drop --no-runtime-install."),process.exit(1)),console.log("sootsim: first run \u2014 installing runtime");let{runRuntime:t}=await import("./runtime-AJP6V5LM.js"),o=[];n.explicitVersion&&o.push(n.explicitVersion),n.channel!=="stable"&&o.push("--channel",n.channel),await t(["install",...o],{channel:n.channel})}async function d(){let n=r();if(l(n))return;console.log("sootsim: starting daemon");let e=w();p(e,["server","--quiet"],{detached:!0,stdio:"ignore",env:process.env}).unref();let t=Date.now()+8e3;for(;Date.now()<t;){let o=r();if(l(o))return;await g(150)}console.error(" daemon didn't become ready within 8s \u2014 check ~/.sootsim/ or run `sootsim server` in a terminal to see errors"),process.exit(1)}async function x(){u()||(console.error(" no sootsim desktop companion installed. run `sootsim install-desktop` to download electron + the shell."),process.exit(1));let e=await m.launch({});e.launched||(console.error(` ${e.message}`),process.exit(1)),console.log(` ${e.message}`)}function w(){let n=process.argv[1];return n&&h(n)?n:"sootsim"}function g(n){return new Promise(e=>setTimeout(e,n))}async function R(){s(),await d()}export{R as ensureDaemonRunning,I as runLaunch};
16
+ `);return}let e=n.includes("--no-runtime-install"),i=n.indexOf("--channel"),t=i>=0&&n[i+1]?n[i+1]:"stable",o=n.indexOf("--version"),f=o>=0&&n[o+1]?n[o+1]:void 0;s(),await v({skipAutoInstall:e,channel:t,explicitVersion:f}),await d(),await x()}async function v(n){let e=a(),i=c();if(e&&i)return;n.skipAutoInstall&&(console.error(" no sootsim runtime installed. run `sootsim runtime install` first, or drop --no-runtime-install."),process.exit(1)),console.log("sootsim: first run \u2014 installing runtime");let{runRuntime:t}=await import("./runtime-DGDQ7NVY.js"),o=[];n.explicitVersion&&o.push(n.explicitVersion),n.channel!=="stable"&&o.push("--channel",n.channel),await t(["install",...o],{channel:n.channel})}async function d(){let n=r();if(l(n))return;console.log("sootsim: starting daemon");let e=w();p(e,["server","--quiet"],{detached:!0,stdio:"ignore",env:process.env}).unref();let t=Date.now()+8e3;for(;Date.now()<t;){let o=r();if(l(o))return;await g(150)}console.error(" daemon didn't become ready within 8s \u2014 check ~/.sootsim/ or run `sootsim server` in a terminal to see errors"),process.exit(1)}async function x(){u()||(console.error(" no sootsim desktop companion installed. run `sootsim install-desktop` to download electron + the shell."),process.exit(1));let e=await m.launch({});e.launched||(console.error(` ${e.message}`),process.exit(1)),console.log(` ${e.message}`)}function w(){let n=process.argv[1];return n&&h(n)?n:"sootsim"}function g(n){return new Promise(e=>setTimeout(e,n))}async function R(){s(),await d()}export{R as ensureDaemonRunning,I as runLaunch};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as f,d as m}from"./chunk-EIQLQDKX.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";import{exec as S}from"node:child_process";import{randomBytes as $}from"node:crypto";import _ from"node:http";var I=process.env.SOOTSIM_AUTH_ORIGIN||"https://sootbean.com",h="http://localhost:3000";async function x(t){if(t)return t;if(process.env.SOOTSIM_AUTH_ORIGIN)return process.env.SOOTSIM_AUTH_ORIGIN;if(process.env.SOOTSIM_UPLOAD_ORIGIN)return process.env.SOOTSIM_UPLOAD_ORIGIN;try{if((await fetch(`${h}/api/auth/me`)).ok)return h}catch{}return I}function R(){console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as f,d as m}from"./chunk-O624O5MO.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import{exec as S}from"node:child_process";import{randomBytes as $}from"node:crypto";import _ from"node:http";var I=process.env.SOOTSIM_AUTH_ORIGIN||"https://sootbean.com",h="http://localhost:3000";async function x(t){if(t)return t;if(process.env.SOOTSIM_AUTH_ORIGIN)return process.env.SOOTSIM_AUTH_ORIGIN;if(process.env.SOOTSIM_UPLOAD_ORIGIN)return process.env.SOOTSIM_UPLOAD_ORIGIN;try{if((await fetch(`${h}/api/auth/me`)).ok)return h}catch{}return I}function R(){console.log(`
3
3
  sootsim login \u2014 sign in so desktop uploads can attach to your account
4
4
 
5
5
  usage:
@@ -21,6 +21,6 @@ options:
21
21
  <p style="color:#ccc">${t}</p>
22
22
  </div>
23
23
  </body>
24
- </html>`}async function P(t){try{let o=await fetch(`${t.replace(/\/$/,"")}/api/dev-login`,{method:"POST"});if(o.status===403)return{ok:!1,error:"dev-login disabled (not in dev mode)"};if(!o.ok){let c=await o.text().catch(()=>"");return{ok:!1,error:`dev-login ${o.status}: ${c}`}}let e=await o.json();return e.token?{ok:!0,token:e.token,userId:e.user?.id,email:e.email}:{ok:!1,error:"dev-login response missing token"}}catch(o){return{ok:!1,error:o instanceof Error?o.message:"dev-login fetch failed"}}}function A(t){try{let o=new URL(t).hostname;return o==="localhost"||o==="127.0.0.1"||o.endsWith(".local")}catch{return!1}}async function G(t){(t.includes("--help")||t.includes("-h"))&&(R(),process.exit(0));let o=[...t],e=await x(T(o,"--origin"));if(A(e)){console.log(` detected local origin (${e}) \u2014 signing in as dev user`);let r=await P(e);if(r.ok){f({token:r.token,user:r.userId?{id:r.userId,email:r.email}:null,origin:e,source:"cli"});let s=await m(e),l=s?.user?.email||r.email||s?.user?.id||r.userId,{trackCliEvent:n,flushCliTelemetry:a}=await import("./telemetry-RFTX2BZK.js");n({event:"cli_login_succeeded",identity:{userId:r.userId??s?.user?.id??null},properties:{origin:e,mode:"dev"}}),await a(),console.log(` signed in${l?` as ${l}`:""} (dev)`);return}console.log(` dev-login not available (${r.error}); falling back to browser`)}let c=$(16).toString("hex"),i=await new Promise(r=>{let s=_.createServer((l,n)=>{try{let a=new URL(l.url||"/","http://127.0.0.1"),w=a.searchParams.get("state"),k=a.searchParams.get("token"),b=a.searchParams.get("email")||void 0,O=a.searchParams.get("userId")||void 0,g=a.searchParams.get("error");if(n.setHeader("content-type","text/html; charset=utf-8"),g){n.end(u(`sign-in failed: ${g}`)),r({ok:!1,error:g}),s.close();return}if(w!==c){n.end(u("state mismatch. close this tab and retry `sootsim login`.")),r({ok:!1,error:"state mismatch"}),s.close();return}if(!k){n.end(u("missing token. close this tab and retry `sootsim login`.")),r({ok:!1,error:"missing token"}),s.close();return}n.end(u("sign-in complete. you can return to the terminal.")),r({ok:!0,token:k,email:b,userId:O}),s.close()}catch(a){n.statusCode=500,n.end(u("sign-in callback failed. retry `sootsim login`.")),r({ok:!1,error:a instanceof Error?a.message:"callback failed"}),s.close()}});s.listen(0,"127.0.0.1",()=>{let l=s.address();if(!l||typeof l=="string"){r({ok:!1,error:"failed to bind callback server"}),s.close();return}let n=new URL(`${e.replace(/\/$/,"")}/auth/sootsim-cli`);n.searchParams.set("state",c),n.searchParams.set("port",String(l.port)),n.searchParams.set("sootbean",e),console.log(" opening browser for sootsim login..."),console.log(` waiting for callback on 127.0.0.1:${l.port}`),console.log(` if nothing opens, visit:
24
+ </html>`}async function P(t){try{let o=await fetch(`${t.replace(/\/$/,"")}/api/dev-login`,{method:"POST"});if(o.status===403)return{ok:!1,error:"dev-login disabled (not in dev mode)"};if(!o.ok){let c=await o.text().catch(()=>"");return{ok:!1,error:`dev-login ${o.status}: ${c}`}}let e=await o.json();return e.token?{ok:!0,token:e.token,userId:e.user?.id,email:e.email}:{ok:!1,error:"dev-login response missing token"}}catch(o){return{ok:!1,error:o instanceof Error?o.message:"dev-login fetch failed"}}}function A(t){try{let o=new URL(t).hostname;return o==="localhost"||o==="127.0.0.1"||o.endsWith(".local")}catch{return!1}}async function G(t){(t.includes("--help")||t.includes("-h"))&&(R(),process.exit(0));let o=[...t],e=await x(T(o,"--origin"));if(A(e)){console.log(` detected local origin (${e}) \u2014 signing in as dev user`);let r=await P(e);if(r.ok){f({token:r.token,user:r.userId?{id:r.userId,email:r.email}:null,origin:e,source:"cli"});let s=await m(e),l=s?.user?.email||r.email||s?.user?.id||r.userId,{trackCliEvent:n,flushCliTelemetry:a}=await import("./telemetry-74LX7WG4.js");n({event:"cli_login_succeeded",identity:{userId:r.userId??s?.user?.id??null},properties:{origin:e,mode:"dev"}}),await a(),console.log(` signed in${l?` as ${l}`:""} (dev)`);return}console.log(` dev-login not available (${r.error}); falling back to browser`)}let c=$(16).toString("hex"),i=await new Promise(r=>{let s=_.createServer((l,n)=>{try{let a=new URL(l.url||"/","http://127.0.0.1"),w=a.searchParams.get("state"),k=a.searchParams.get("token"),b=a.searchParams.get("email")||void 0,O=a.searchParams.get("userId")||void 0,g=a.searchParams.get("error");if(n.setHeader("content-type","text/html; charset=utf-8"),g){n.end(u(`sign-in failed: ${g}`)),r({ok:!1,error:g}),s.close();return}if(w!==c){n.end(u("state mismatch. close this tab and retry `sootsim login`.")),r({ok:!1,error:"state mismatch"}),s.close();return}if(!k){n.end(u("missing token. close this tab and retry `sootsim login`.")),r({ok:!1,error:"missing token"}),s.close();return}n.end(u("sign-in complete. you can return to the terminal.")),r({ok:!0,token:k,email:b,userId:O}),s.close()}catch(a){n.statusCode=500,n.end(u("sign-in callback failed. retry `sootsim login`.")),r({ok:!1,error:a instanceof Error?a.message:"callback failed"}),s.close()}});s.listen(0,"127.0.0.1",()=>{let l=s.address();if(!l||typeof l=="string"){r({ok:!1,error:"failed to bind callback server"}),s.close();return}let n=new URL(`${e.replace(/\/$/,"")}/auth/sootsim-cli`);n.searchParams.set("state",c),n.searchParams.set("port",String(l.port)),n.searchParams.set("sootbean",e),console.log(" opening browser for sootsim login..."),console.log(` waiting for callback on 127.0.0.1:${l.port}`),console.log(` if nothing opens, visit:
25
25
  ${n.toString()}
26
- `),L(n.toString())})});if(!i.ok){let{trackCliEvent:r,flushCliTelemetry:s}=await import("./telemetry-RFTX2BZK.js");r({event:"cli_login_failed",properties:{origin:e,error:i.error}}),await s(),console.error(` login failed: ${i.error}`),process.exit(1)}f({token:i.token,user:i.userId?{id:i.userId,email:i.email}:null,origin:e,source:"cli"});let d=await m(e),p=d?.user?.email||i.email||d?.user?.id||i.userId,{trackCliEvent:y,flushCliTelemetry:v}=await import("./telemetry-RFTX2BZK.js");y({event:"cli_login_succeeded",identity:{userId:i.userId??d?.user?.id??null},properties:{origin:e}}),await v(),console.log(` signed in${p?` as ${p}`:""}`)}export{G as runLogin};
26
+ `),L(n.toString())})});if(!i.ok){let{trackCliEvent:r,flushCliTelemetry:s}=await import("./telemetry-74LX7WG4.js");r({event:"cli_login_failed",properties:{origin:e,error:i.error}}),await s(),console.error(` login failed: ${i.error}`),process.exit(1)}f({token:i.token,user:i.userId?{id:i.userId,email:i.email}:null,origin:e,source:"cli"});let d=await m(e),p=d?.user?.email||i.email||d?.user?.id||i.userId,{trackCliEvent:y,flushCliTelemetry:v}=await import("./telemetry-74LX7WG4.js");y({event:"cli_login_succeeded",identity:{userId:i.userId??d?.user?.id??null},properties:{origin:e}}),await v(),console.log(` signed in${p?` as ${p}`:""}`)}export{G as runLogin};
@@ -1,2 +1,2 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as r,b as i}from"./chunk-DEQ7RED3.js";import{a as t,c as o}from"./chunk-EIQLQDKX.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";async function s(){let e=t();if(!e?.token){console.log(" not signed in");return}try{await fetch(`${e.origin.replace(/\/$/,"")}/api/auth/sign-out`,{method:"POST",headers:{authorization:`Bearer ${e.token}`}})}catch{}o(),r({event:"cli_logout",identity:{userId:e.user?.id??null},properties:{origin:e.origin}}),await i(),console.log(" signed out")}export{s as runLogout};
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as r,b as i}from"./chunk-DOWYG3HG.js";import{a as t,c as o}from"./chunk-O624O5MO.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";async function s(){let e=t();if(!e?.token){console.log(" not signed in");return}try{await fetch(`${e.origin.replace(/\/$/,"")}/api/auth/sign-out`,{method:"POST",headers:{authorization:`Bearer ${e.token}`}})}catch{}o(),r({event:"cli_logout",identity:{userId:e.user?.id??null},properties:{origin:e.origin}}),await i(),console.log(" signed out")}export{s as runLogout};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as h,c as w}from"./chunk-MWTMLNGM.js";import"./chunk-LVFWALS4.js";import"./chunk-YSQV4D7P.js";import"./chunk-4LYNJPUM.js";import"./chunk-EMMX6RF7.js";import"./chunk-EEMGSSWY.js";import"./chunk-XZ5SQJM2.js";import"./chunk-QMRXLBPN.js";import"./chunk-HWCZYW6M.js";import"./chunk-M3ZEZHOB.js";import"./chunk-V4SZERWD.js";import"./chunk-LCKLQSZX.js";import"./chunk-Z6HSVZIO.js";import"./chunk-GDCMTHEU.js";import"./chunk-NQKBIKUZ.js";import"./chunk-AYBGSHQK.js";import"./chunk-HIN5TAAL.js";import"./chunk-UNSLXX7V.js";import"./chunk-XOTJSR4T.js";import"./chunk-DEQ7RED3.js";import"./chunk-EIQLQDKX.js";import"./chunk-LRBMW2WC.js";import"./chunk-FXF2FHPI.js";import"./chunk-G4VWDOWB.js";import"./chunk-VRV2X4X2.js";import"./chunk-7NYW73Q6.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";import*as i from"fs";import*as l from"path";var v=[".maestro","maestro"];function x(){console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as h,c as w}from"./chunk-2HKCZLY7.js";import"./chunk-4QSGVTBE.js";import"./chunk-KR36VJSN.js";import"./chunk-SH6HMUCY.js";import"./chunk-KBJ2WHII.js";import"./chunk-LQ5BA5JU.js";import"./chunk-EJTXYZEF.js";import"./chunk-MIAAZSSE.js";import"./chunk-K4PKR2EO.js";import"./chunk-CUNQTNH4.js";import"./chunk-AQ7YR4MO.js";import"./chunk-XCRUPKWB.js";import"./chunk-7PQHQOCI.js";import"./chunk-ZO7SGE65.js";import"./chunk-GFVC6EEB.js";import"./chunk-5WRBVYML.js";import"./chunk-ZP2HMCKS.js";import"./chunk-ZJJKYJMH.js";import"./chunk-SVFSMAZN.js";import"./chunk-DOWYG3HG.js";import"./chunk-O624O5MO.js";import"./chunk-BCVVANS5.js";import"./chunk-NYR3Z44O.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import*as i from"fs";import*as l from"path";var v=[".maestro","maestro"];function x(){console.log(`
3
3
  sootsim maestro \u2014 run maestro YAML flows against sootsim (drop-in)
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import"./chunk-D4VEI6MI.js";import{resolve as c,dirname as m}from"path";import{fileURLToPath as a}from"url";var t=m(a(import.meta.resolve("sootsim-engine/package.json")));async function g(o,r){(o.includes("--help")||o.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import"./chunk-TLTS533S.js";import{resolve as c,dirname as m}from"path";import{fileURLToPath as a}from"url";var t=m(a(import.meta.resolve("sootsim-engine/package.json")));async function g(o,r){(o.includes("--help")||o.includes("-h"))&&(console.log(`
3
3
  sootsim preview \u2014 production-like preview
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as s,c as i,d as t,e as n,f as c}from"./chunk-AYBGSHQK.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";function f(){console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as s,c as i,d as t,e as n,f as c}from"./chunk-5WRBVYML.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";function f(){console.log(`
3
3
  sootsim profile \u2014 manage isolated storage profiles
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{c as w,e as b,h as m,i as f}from"./chunk-G4VWDOWB.js";import"./chunk-VRV2X4X2.js";import"./chunk-7NYW73Q6.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";function h(){console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{c as w,e as b,h as m,i as f}from"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";function h(){console.log(`
3
3
  sootsim react \u2014 inspect React component render cost in the tenant worker
4
4
 
5
5
  usage:
@@ -0,0 +1,54 @@
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as N}from"./chunk-SH6HMUCY.js";import"./chunk-KBJ2WHII.js";import{d as Y}from"./chunk-LQ5BA5JU.js";import"./chunk-GFVC6EEB.js";import{d as K}from"./chunk-ZP2HMCKS.js";import"./chunk-DOWYG3HG.js";import"./chunk-O624O5MO.js";import{c as h,e as b,f as Q}from"./chunk-U47AHSGE.js";import{b as X}from"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import{existsSync as fe,mkdirSync as O,readdirSync as pe,readFileSync as ge,rmSync as z,writeFileSync as E}from"fs";import{homedir as we,tmpdir as he}from"os";import{dirname as W,extname as ee,join as A,resolve as be}from"path";var Z=24e4,ve=3e4;async function P(e,r,o,i){let t=Math.max(2e4,i+ve);try{return await e.send({type:"evaluate",code:r},{timeoutMs:t})}catch(n){let s=n instanceof Error?n.message:String(n);/^command timed out after \d+s$/.test(s)&&(console.error(` ${o} stalled \u2014 the render host did not finish within ${Math.round(t/1e3)}s; it is likely contended or wedged.
3
+ the capture lock auto-releases, so simply retry the recording.
4
+ if it persists, recover the sim with \`sootsim close --sim <id>\`.`),process.exit(1)),/render host not available|already streaming|already recording/i.test(s)&&(console.error(` ${o} failed: ${s}
5
+ a prior recording was abandoned and its capture is still
6
+ releasing. the lock self-heals in ~${Math.round((i+2e4)/1e3)}s \u2014 retry then, or recover now with
7
+ \`sootsim close --sim <id>\` and reopen the sim.`),process.exit(1)),console.error(` ${o} failed: ${s}`),process.exit(1)}}var ye=new Set(["--sim","--port","-p","--mode","--duration","--fps","--format","--output","-o","--frames","--max-width","--origin"]),$e=new Set(["start","stop","cancel","status","prelude-start"]);function Se(e){for(let r=0;r<e.length;r++){let o=e[r];if(o.startsWith("-")){ye.has(o)&&r++;continue}return $e.has(o)?{name:o,index:r}:null}return null}async function ze(e,r){let o=Se(e);if(o){let a=[...e.slice(0,o.index),...e.slice(o.index+1)];if(o.name==="start"){await Be(a,r);return}if(o.name==="prelude-start"){await Me(a,r);return}if(o.name==="stop"){await Ee(a,r);return}if(o.name==="cancel"){await Ue(a,r);return}await Ie(a,r);return}let i=h(e,{port:r.port,stripBooleanFlags:["--no-shell","--shell-only","--open"],stripValueFlags:["--mode","--duration","--fps","--format","--output","--frames","--max-width","--origin"]}),t=te(u(e,"--mode")),n=e.includes("--shell-only")?"shell":e.includes("--no-shell")?"tenant":void 0,s=u(e,"--format");s&&!["webm","mp4","gif","png"].includes(s)&&(console.error(` invalid --format "${s}" \u2014 expected webm | mp4 | gif | png`),process.exit(1));let c=u(e,"--output"),d=Number(u(e,"--duration")??"10");(!Number.isFinite(d)||d<=0)&&(console.error(` invalid --duration "${u(e,"--duration")}" \u2014 expected a positive number of seconds`),process.exit(1));let l=1800;d>l&&(console.error(` invalid --duration "${u(e,"--duration")}" \u2014 exceeds the ${l}s (30m) maximum`),process.exit(1));let f=Number(u(e,"--fps")??"30"),v=u(e,"--frames");if(v!==void 0){let a=Number(v);(!Number.isInteger(a)||a<=0)&&(console.error(` invalid --frames "${v}" \u2014 expected a positive integer count`),process.exit(1))}let j=e.includes("--open"),H=u(e,"--max-width")?Number(u(e,"--max-width")):void 0,p=Math.max(100,Math.round(d*1e3)),q=u(e,"--origin");if(t==="live"||t==="combined"){c&&console.log(` note: --output is ignored for --mode ${t} \u2014 the recording uploads to /preview/<id>`),n&&t==="live"&&console.log(` note: --${n==="shell"?"shell-only":"no-shell"} is ignored for --mode live \u2014 live recordings capture events only, no video`),await N("record",{originOverride:q,allowGitHubAuth:!0});let a=b({...i,commandTimeoutMs:6e4});try{await G(a),await ie(a,t),t==="combined"&&await B(a),await se(a,q);let R=await ae(a,t,t==="combined"?n:void 0);R.ok||(console.error(` start failed: recording store refused to start (${t})`+(R.error?`: ${R.error}`:"")),process.exit(1)),console.log(` recording ${t} for ${d}s`),await new Promise(x=>setTimeout(x,p)),await de(a);let _=await ce(a);le(_,j,t)}finally{a.close()}return}let F=v?Number(v):null,$=_e(s,c,F);j&&console.log(" note: --open is ignored for local-file capture \u2014 it applies to --mode live/combined");let w=b({...i,commandTimeoutMs:6e4});try{if(await oe(w),await B(w),$==="png"){let S=F??10,g=U(c,`sootsim-frames-${I()}`);c&&ee(c)&&console.log(` note: --frames writes multiple pngs, so --output "${c}" is a directory \u2014 frame-NNN.png files land inside it`),O(g,{recursive:!0});for(let m of pe(g))/^frame-\d+\.png$/.test(m)&&z(A(g,m),{force:!0});console.log(` sampling ${S} frames over ${d}s \u2192 ${g}`);let y=await w.send({type:"evaluate",code:`window.__sootsimRecorder.startFrameCapture({ count: ${S}, durationMs: ${p}${n?`, layers: ${JSON.stringify(n)}`:""} })`});(!y.ok||!y.requestId)&&(console.error(` frame capture start failed: ${y.error??"unknown error"}`),process.exit(1)),await new Promise(m=>setTimeout(m,p));let ue=Date.now()+Math.max(5e3,p),T=null;for(;;){let m=await w.send({type:"evaluate",code:`window.__sootsimRecorder.getFrameCaptureResult(${y.requestId})`});if(m||(console.error(" frame capture result missing"),process.exit(1)),m.done){m.ok||(console.error(` frame capture failed: ${m.error??"unknown error"}`),process.exit(1)),T=m.frames??[];break}Date.now()>=ue&&(console.error(" frame capture timed out"),process.exit(1)),await new Promise(C=>setTimeout(C,100))}T.forEach((m,C)=>{let me=`${g}/frame-${String(C+1).padStart(3,"0")}.png`;E(me,Buffer.from(m.data,"base64"))}),console.log(` saved ${T.length} frames`);return}if($==="gif"){let S=F??Math.max(10,Math.round(d*f/3)),g=U(c,`sootsim-${I()}.gif`);O(W(g),{recursive:!0}),console.log(` encoding gif: ${S} frames over ${d}s \u2192 ${g}`);let y=await P(w,`window.__sootsimRecorder.captureGif({ frames: ${S}, durationMs: ${p}${H?`, maxWidth: ${H}`:""}${n?`, layers: ${JSON.stringify(n)}`:""} })`,"gif encode",p);y||(console.error(" gif capture returned no frames"),process.exit(1)),E(g,Buffer.from(y.data,"base64")),console.log(` saved: ${g} (${D(y.size)})`);return}let a=U(c,`sootsim-${I()}.${$}`);O(W(a),{recursive:!0});let R={format:$,fps:f,durationMs:p};n&&(R.layers=n);let _=await P(w,`window.__sootsimRecorder.start(${JSON.stringify(R)})`,`${$} start`,p);_.ok||(console.error(` start failed: ${_.error??"unknown error"}`),/render host not available|already streaming|already recording/i.test(_.error??"")&&console.error(" a prior recording was abandoned and its capture is still\n releasing. retry in ~20s, or recover now with\n `sootsim close --sim <id>` then reopen the sim."),process.exit(1)),console.log(` recording ${$} for ${d}s \u2192 ${a}`),await new Promise(S=>setTimeout(S,p));let x=await P(w,"window.__sootsimRecorder.stop()",`${$} encode/flush`,p);x.ok||(console.error(` stop failed: ${x.error??"unknown error"}`),process.exit(1)),x.size||(console.error(" recorder returned an empty blob \u2014 nothing written"),process.exit(1)),await re(w,a),console.log(` saved: ${a} (${D(x.size)})`)}finally{w.close()}}var Re=6e3;async function J(e,r){try{return await e.send({type:"evaluate",code:r},{timeoutMs:Re})}catch(o){let i=o instanceof Error?o.message:String(o);throw/^command timed out after \d+s$/.test(i)&&(console.error(" sim did not respond \u2014 it is connected to the bridge but has not\n loaded an app (or its page is unresponsive). run `sootsim list`\n and target a sim with a loaded app via --sim <id>."),process.exit(1)),o}}async function oe(e){await J(e,'typeof window.__sootsimRecorder !== "undefined"')||(console.error(" window.__sootsimRecorder missing \u2014 is sootsim engine running in this sim?"),process.exit(1))}async function B(e){let{hidden:r}=await Q(e);r&&(console.error(` refusing to record: the sootsim tab is hidden, so frame capture
8
+ would be throttled to ~1fps and produce a frozen-looking file.
9
+ bring the chrome window to the foreground (un-minimize / switch to
10
+ its tab) or run the recording in headless playwright, then retry.`),process.exit(1))}async function re(e,r){let o=[],i=0;for(;;){let t=await e.send({type:"evaluate",code:`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`});if(!t)throw new Error("no blob available on recorder");if(o.push(Buffer.from(t.data,"base64")),i=t.offset,t.done)break}E(r,Buffer.concat(o))}function u(e,r){let o=e.indexOf(r);if(!(o<0||o===e.length-1))return e[o+1]}function xe(e){if(!e)return;let r=ee(e).toLowerCase().replace(/^\./,"");if(r==="webm"||r==="mp4"||r==="gif")return r;if(r==="png")return"png"}function _e(e,r,o){return e||(o!=null?"png":xe(r)??"webm")}function I(){return new Date().toISOString().replace(/[:T]/g,"-").replace(/\..+/,"")}function ke(){let e=A(we(),".sootsim","recordings");return O(e,{recursive:!0}),e}function U(e,r){return e?be(process.cwd(),e):A(ke(),r)}function D(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(2)}MB`}function te(e){if(!e)return"video";if(e==="video"||e==="live"||e==="combined")return e;console.error(` invalid --mode "${e}" \u2014 expected video | live | combined`),process.exit(1)}function L(){return A(he(),`sootsim-recording-${X()}.json`)}function M(){let e=L();if(!fe(e))return null;try{return{mode:"video",...JSON.parse(ge(e,"utf8"))}}catch{return z(e,{force:!0}),null}}function Oe(e){E(L(),JSON.stringify(e,null,2))}function k(){z(L(),{force:!0})}function V(e,r){e&&r.simId&&e!==r.simId&&console.log(` note: the tracked recording session is on sim ${r.simId}, not the
11
+ requested sim ${e}. record state is global (not per-sim);
12
+ this command acts on that session regardless of --sim.`)}async function Be(e,r){let o=M();o&&(console.error(` recording already in progress (started ${o.startedAt}, sim ${o.simId??"?"}). run \`sootsim record stop\` first, or \`sootsim record cancel\` to discard.`),process.exit(1));let i=h(e,{port:r.port,stripBooleanFlags:["--no-shell","--shell-only"],stripValueFlags:["--mode","--fps","--format","--max-width","--origin"]}),t=te(u(e,"--mode")),n=e.includes("--shell-only")?"shell":e.includes("--no-shell")?"tenant":void 0,s=u(e,"--format"),c=s==="mp4"?"mp4":"webm";s&&c!==s&&(console.error(` record start only supports webm or mp4 (got: ${s}). for gif/png use atomic mode: sootsim record --format ${s} --duration <s>`),process.exit(1));let d=Number(u(e,"--fps")??"30"),l=b({...i,commandTimeoutMs:15e3});try{if(t==="live"||t==="combined"){n&&t==="live"&&console.log(` note: --${n==="shell"?"shell-only":"no-shell"} is ignored for --mode live \u2014 live recordings capture events only, no video`),await N("record",{originOverride:u(e,"--origin"),allowGitHubAuth:!0}),await G(l),await ie(l,t),t==="combined"&&await B(l),await se(l,u(e,"--origin"));let f=await ae(l,t,t==="combined"?n:void 0);f.ok||(console.error(` start failed: recording store refused to start (${t})`+(f.error?`: ${f.error}`:"")),process.exit(1))}else{await oe(l),await B(l);let f={format:c,fps:d};n&&(f.layers=n);let v=await l.send({type:"evaluate",code:`window.__sootsimRecorder.start(${JSON.stringify(f)})`});v.ok||(console.error(` start failed: ${v.error??"unknown error"}`),process.exit(1))}Oe({simId:i.simId??null,mode:t,format:c,fps:d,layers:n,startedAt:new Date().toISOString()}),console.log(t==="video"?` recording ${c} @ ${d}fps${n?` (${n})`:""} \u2014 run \`sootsim record stop --output <path>\` when done`:` recording ${t} \u2014 run \`sootsim record stop\` when done (add --open to launch the preview URL)`)}finally{l.close()}}async function Me(e,r){let o=M();o&&(console.error(` recording already in progress (started ${o.startedAt}, sim ${o.simId??"?"}). run \`sootsim record stop\` first, or \`sootsim record cancel\` to discard.`),process.exit(1));let i=h(e,{port:r.port,stripBooleanFlags:[],stripValueFlags:["--origin"]}),t=b({...i,commandTimeoutMs:15e3});try{if(await G(t),await B(t),!await t.send({type:"evaluate",code:`(() => {
13
+ const start = window.SootSim?.bridges?.startRecordingPrelude
14
+ if (typeof start !== 'function') return false
15
+ return Promise.resolve(start()).then((value) => value === true)
16
+ })()`})){let s=await t.send({type:"evaluate",code:`(() => {
17
+ const getError = window.SootSim?.bridges?.getRecordingStartError
18
+ return typeof getError === 'function' ? getError() : null
19
+ })()`}).catch(()=>null);console.error(` prelude start failed: recording store refused to start${typeof s=="string"&&s?` (${s})`:""}`),process.exit(1)}console.log(" recording preview prelude \u2014 run `sootsim record start --mode combined` when the visible proof segment is ready")}finally{t.close()}}async function ne(e){try{let r=await e.send({type:"evaluate",code:`(() => {
20
+ const store = window.SootSim?.bridges?.getRecordingState?.();
21
+ const headless = window.__sootsimRecorder?.state?.();
22
+ return { store: store ? store.state : undefined, headless };
23
+ })()`});return r?r.store==="recording"||r.headless==="recording"?"recording":r.store==="processing"?"processing":r.store==="idle"||r.headless==="idle"?"idle":null:null}catch{return null}}async function Ie(e,r){let o=M();if(o){V(h(e,{port:r.port}).simId,o),o.mode==="video"?console.log(` recording ${o.mode} (${o.format} @ ${o.fps}fps) on sim ${o.simId??"?"} since ${o.startedAt}`):console.log(` recording ${o.mode} on sim ${o.simId??"?"} since ${o.startedAt}`);return}let i=h(e,{port:r.port}),t=b({...i,commandTimeoutMs:8e3});try{let n=await ne(t);console.log(n==="recording"||n==="processing"?` a recording is in progress (engine state: ${n}), but not via
24
+ \`record start\` \u2014 it was started by an atomic \`record --duration\`
25
+ run or the in-browser record button, which own their own lifecycle.
26
+ if that controlling run is still alive it will finish on its own
27
+ (atomic \`--mode video/gif/png\` writes a local file from that
28
+ process; live/combined upload to /preview/<id>). if the run was
29
+ killed, the recording is abandoned and will NOT finish \u2014 reclaim
30
+ it now with \`sootsim record cancel\`, or it auto-reclaims when the
31
+ abandoned capture's deadline lapses.`:" no recording in progress")}finally{t.close()}}async function Ue(e,r){let o=M();if(!o){let s=h(e,{port:r.port}),c=b({...s,commandTimeoutMs:8e3});try{let d=await ne(c);if(d==="recording"||d==="processing"){let l=await c.send({type:"evaluate",code:`(async () => {
32
+ const r = window.__sootsimRecorder;
33
+ if (r && typeof r.forceRelease === 'function') return await r.forceRelease();
34
+ return false;
35
+ })()`}).catch(()=>!1);console.log(l?" reclaimed an abandoned recording (started by an atomic\n `record --duration` run or the record button whose owner is\n gone). the recorder is idle again \u2014 live/combined can start.":" a recording is in progress and still owned by a live atomic\n `record --duration` run or the in-browser record button \u2014 it\n will finish on its own and nothing was reclaimed.")}else console.log(" no recording in progress")}finally{c.close()}return}let i=h(e,{port:r.port});V(i.simId,o);let t=o.simId??i.simId??void 0,n=b({...i,simId:t,commandTimeoutMs:15e3});try{o.mode==="live"||o.mode==="combined"?await n.send({type:"evaluate",code:"void window.SootSim?.bridges?.cancelRecording?.()"}):await n.send({type:"evaluate",code:"window.__sootsimRecorder.stop()"})}catch{}finally{k(),n.close()}console.log(" recording cancelled")}async function Ee(e,r){let o=M();o||(console.error(" no recording in progress. start one with `sootsim record start`."),process.exit(1));let i=h(e,{port:r.port,stripBooleanFlags:["--open"],stripValueFlags:["--output"]});V(i.simId,o);let t=o.simId??i.simId??void 0,n=e.includes("--open"),s=b({...i,simId:t,commandTimeoutMs:6e4});try{if(o.mode==="live"||o.mode==="combined"){await de(s);let f=await ce(s);k(),le(f,n,o.mode);return}let c=u(e,"--output"),d=U(c,`sootsim-${I()}.${o.format}`);O(W(d),{recursive:!0});let l=await s.send({type:"evaluate",code:"window.__sootsimRecorder.stop()"});l.ok||(console.error(` stop failed: ${l.error??"unknown error"}`),k(),process.exit(1)),l.size||(console.error(" recorder returned an empty blob \u2014 nothing written"),k(),process.exit(1)),await re(s,d),k(),console.log(` saved: ${d} (${D(l.size)})`)}finally{s.close()}}async function G(e){await J(e,'typeof window.SootSim?.bridges?.startRecording === "function" && typeof window.SootSim?.bridges?.stopRecording === "function"')||(console.error(" SootSim.bridges.startRecording missing \u2014 is sootsim engine running in this sim?"),process.exit(1))}async function ie(e,r){await J(e,`(() => {
36
+ const fn = window.__sootsimCaptureBundle
37
+ if (typeof fn !== 'function') return false
38
+ const snap = fn()
39
+ return !!(snap && snap.bundleUrl)
40
+ })()`)||(console.error(` --mode ${r} needs a guest app bundle to upload to /preview/<id>,
41
+ but this sim has no bundle loaded (a built-in shell screen like
42
+ photos/settings/home has none). open a metro/guest app first, or
43
+ use \`--mode video\` for a local screen recording with no upload.`),process.exit(1))}async function se(e,r){let o=Y();if(!o)return;let i=o.kind==="api-key"?o.secret:o.token,t=o.kind==="github"?{repoId:o.repoId,installationId:o.installationId}:null,n=r?r.replace(/\/$/,""):null;await e.send({type:"evaluate",code:`(() => {
44
+ const set = window.SootSim && window.SootSim.bridges && window.SootSim.bridges.setSession
45
+ if (typeof set !== 'function') return false
46
+ set({ token: ${JSON.stringify(i)}, user: null })
47
+ window.__sootsimPreviewUploadIdentity = ${JSON.stringify(t)}
48
+ window.__sootsimPreviewUseInjectedBearer = true
49
+ ${n?`window.__sootsimUploadOrigin = ${JSON.stringify(n)}`:"delete window.__sootsimUploadOrigin"}
50
+ return true
51
+ })()`})||(console.error(" SootSim.bridges.setSession missing \u2014 this sim is running an engine\n build without CLI-injected preview auth. reload the sim or open a\n fresh one (`sootsim open --new`); if it persists, update sootsim."),process.exit(1))}async function ae(e,r,o){let i=o?JSON.stringify(o):"undefined";return await e.send({type:"evaluate",code:`window.SootSim.bridges.startRecording(${JSON.stringify(r)}, ${i}, { skipEntitlement: true })`})===!0?{ok:!0,error:null}:{ok:!1,error:await e.send({type:"evaluate",code:"(window.SootSim?.bridges?.getRecordingStartError?.() ?? null)"}).catch(()=>null)??null}}async function de(e){await e.send({type:"evaluate",code:"void window.SootSim.bridges.stopRecording()"})}async function ce(e){let r=Date.now()+Z;for(;Date.now()<r;){let o=await e.send({type:"evaluate",code:"(() => { const s = window.SootSim?.bridges?.getRecordingState?.(); return s ? { state: s.state, lastUpload: s.lastUpload, uploadError: s.uploadError } : null })()"});if(o&&o.state==="idle"){if(o.uploadError)return{uploadError:o.uploadError};if(o.lastUpload?.previewUrl)return{previewUrl:o.lastUpload.previewUrl,eventCount:o.lastUpload.eventCount}}await new Promise(i=>setTimeout(i,300))}return{uploadError:`upload did not settle within ${Z/1e3}s`}}function le(e,r,o){e.uploadError&&(console.error(` upload failed: ${e.uploadError}`),process.exit(1)),e.previewUrl||(console.error(" upload returned no preview URL"),process.exit(1)),console.log(` preview: ${e.previewUrl}`),console.log(` note: this URL is content-addressed \u2014 re-recording the same bundle
52
+ replaces this capture at the same /preview/<id>.`),(o==="live"||o==="combined")&&typeof e.eventCount=="number"&&console.log(` captured ${e.eventCount} event${e.eventCount===1?"":"s"}`),(o==="live"||o==="combined")&&e.eventCount===0&&console.log(o==="combined"?` note: this combined recording captured no events \u2014 the Live tab has
53
+ nothing to replay, and the Video tab may stall with no events to drive it.`:` note: this live recording captured no events \u2014 the preview has nothing
54
+ to replay and will boot a fresh interactive session instead.`),r&&K(e.previewUrl)}export{xe as extToFormat,_e as resolveFormat,ze as runRecord,u as valueOf};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a}from"./chunk-52RZ6TSZ.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-YGQV3CUV.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";export{a as runRuntime};
@@ -1,2 +1,2 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-NCSGLZRV.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";export{a as DEFAULT_RUNTIME_CDN_ORIGIN,b as RUNTIME_CDN_ORIGIN_ENV,c as RUNTIME_CHANNEL_ENV,l as checkRuntimeUpToDate,h as fetchRuntimeManifest,j as installRuntime,d as resolveRuntimeCdnOrigin,e as resolveRuntimeChannel,i as resolveRuntimeVersion,f as runtimeManifestUrl,g as runtimeTarballUrl,k as updateRuntimeToLatest};
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a,b,c,d,e,f,g,h,i,j,k,l}from"./chunk-YGQV3CUV.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";export{a as DEFAULT_RUNTIME_CDN_ORIGIN,b as RUNTIME_CDN_ORIGIN_ENV,c as RUNTIME_CHANNEL_ENV,l as checkRuntimeUpToDate,h as fetchRuntimeManifest,j as installRuntime,d as resolveRuntimeCdnOrigin,e as resolveRuntimeChannel,i as resolveRuntimeVersion,f as runtimeManifestUrl,g as runtimeTarballUrl,k as updateRuntimeToLatest};
@@ -0,0 +1,33 @@
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as R}from"./chunk-4QSGVTBE.js";import"./chunk-KR36VJSN.js";import{a as b}from"./chunk-4H6LBA4A.js";import"./chunk-ZJJKYJMH.js";import"./chunk-BCVVANS5.js";import{f as g}from"./chunk-NYR3Z44O.js";import{c as w,d as y,e as x,f as v,h as S}from"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import{mkdirSync as $,writeFileSync as _}from"fs";import{dirname as A,resolve as B}from"path";async function z(e,o){(e.includes("--help")||e.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 exclude the simulated iOS chrome (status bar, keyboard,
15
+ toasts) \u2014 captures the tenant surfaces only
16
+ --shell-only capture only the shell chrome, no tenant content
17
+ --area x,y,w,h crop to a logical sootsim rect
18
+ --id <testID> crop to a node's bounding box
19
+ --text <text> crop to a node found by text content
20
+ --gallery crawl and capture multiple screens as HTML gallery
21
+ --themes capture light and dark variants
22
+
23
+ examples:
24
+ sootsim screenshot
25
+ sootsim screenshot --with-frame --output framed.png
26
+ sootsim screenshot --area 0,200,393,400 --output hero.png
27
+ sootsim screenshot --id loginButton --output button.png
28
+ `),process.exit(0));let t=U(e);if(t.length>0){for(let{flag:l,suggestion:h}of t)console.error(h?` unknown flag: ${l} (did you mean ${h}?)`:` unknown flag: ${l}`);console.error(" run `sootsim screenshot --help` for the list of supported flags"),process.exit(1)}let r=e.includes("--gallery"),i=e.includes("--themes"),n=N(e),u=D(e);if(r||i)return n&&(console.error(" --with-frame is not supported with --gallery / --themes"),process.exit(1)),E(e,o);n&&e.some(l=>l==="--area"||l==="--id"||l==="--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 s=w(e,{port:o.port,stripBooleanFlags:["--with-frame","--no-frame","--no-shell","--shell-only"],stripValueFlags:["--output","--area","--id","--text"]}),a=T(e),c=await P(e);if(await O(s.wsPort)){try{await M(s,a,c,n,u)}catch(l){console.error(` screenshot failed: ${l instanceof Error?l.message:String(l)}`),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)),c&&(console.error(" --area / --id / --text require a running sootsim bridge"),console.error(" start one with `sootsim server`, `sootsim electron`, or your project dev server"),process.exit(1)),await E(e,o)}async function O(e){let o=y(e,{commandTimeoutMs:1e3});try{return await o.listSims(),!0}catch{return!1}finally{o.close()}}async function P(e){let o=e.find((i,n)=>e[n-1]==="--area");if(o){let i=o.split(",").map(c=>Number(c.trim()));if(i.length!==4||i.some(c=>!Number.isFinite(c)))throw new Error(`--area expects x,y,w,h (got "${o}")`);let[n,u,s,a]=i;return{x:n,y:u,w:s,h:a}}let t=e.find((i,n)=>e[n-1]==="--id"),r=e.find((i,n)=>e[n-1]==="--text");return t||r?{__matcher:{id:t,text:r}}:null}async function M(e,o,t,r,i){let n=x({...e,commandTimeoutMs:1e4});try{(await v(n)).hidden&&process.stderr.write(` \u26A0 screenshot will capture the LAST PAINTED canvas \u2014 likely stale.
29
+ navigation/\`shell\` commands sent before this screenshot may not
30
+ have repainted yet. focus the tab manually or \`sootsim --sim <id>\`
31
+ to target a visible sim before capturing.
32
+
33
+ `);let s=t,a=t?.__matcher;if(a){let d=await n.send({type:"evaluate",code:b(a)});if(!d)throw new Error(a.id?`no node with id "${a.id}"`:`no node matching text "${a.text}"`);s=d}let c=s?{x:s.x,y:s.y,w:s.w,h:s.h}:void 0,p={type:"screenshot"};i&&(p.layers=i),c&&(p.crop=c);let h=(await n.send(p)).replace(/^data:image\/png;base64,/,"");c&&console.log(` area: x=${c.x} y=${c.y} w=${c.w} h=${c.h}`),i&&console.log(` layers: ${i}`);let m=B(process.cwd(),o||"/tmp/sootsim-inspect.png");$(A(m),{recursive:!0});let f=Buffer.from(h,"base64");if(r){let d=await L(n);if(!d)throw new Error("could not read current device model from the target sim");let k=await R(f,d);_(m,k),console.log(` frame: ${d}`)}else _(m,f);console.log(` saved: ${m}`)}finally{n.close()}}async function L(e){let o=await S(e,"SootSim.bridges.settings.get")??{deviceModel:null},t=typeof o.deviceModel=="string"?o.deviceModel:null;return!t||!(t in g)?null:t}function N(e){let o=!1;for(let t of e)t==="--with-frame"&&(o=!0),t==="--no-frame"&&(o=!1);return o}function D(e){if(e.includes("--shell-only"))return"shell";if(e.includes("--no-shell"))return"tenant"}var C=new Set(["--help","-h","--verbose","-v","--with-frame","--no-frame","--no-shell","--shell-only","--gallery","--themes"]),F=new Set(["--output","--area","--id","--text","--url","--port","--timeout","--sim"]),G={"--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 U(e){let o=[];for(let t=0;t<e.length;t++){let r=e[t];if(r.startsWith("-")){if(F.has(r)){t++;continue}C.has(r)||o.push({flag:r,suggestion:G[r]})}}return o}function T(e){let o=e.find((t,r)=>e[r-1]==="--output");if(o)return o;for(let t=0;t<e.length;t++){let r=e[t];if(r.startsWith("-")){F.has(r)&&t++;continue}return r}}async function E(e,o){let t=T(e)||"sootsim-screenshot.png",r=e.includes("--gallery"),i=e.find((s,a)=>e[a-1]==="--url")||`http://localhost:${o.port||5173}`,{chromium:n}=await import("playwright"),u=await n.launch({channel:"chrome",headless:!0});try{if(r)console.log(" capturing gallery..."),console.log(" (gallery mode not yet implemented)");else{let s=await u.newPage({viewport:{width:500,height:900}});await s.goto(i,{waitUntil:"networkidle"}),await s.waitForTimeout(2e3);let a=B(process.cwd(),t);$(A(a),{recursive:!0}),await s.screenshot({path:a}),console.log(` saved: ${a}`),await s.close()}}catch(s){console.error(` screenshot failed: ${s.message}`),process.exitCode=1}finally{await u.close()}}export{z as runScreenshot};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as o}from"./chunk-22CO2ZE3.js";import"./chunk-G4VWDOWB.js";import"./chunk-VRV2X4X2.js";import"./chunk-7NYW73Q6.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";async function n(e,s){(e.includes("--help")||e.includes("-h"))&&(console.log(`
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as o}from"./chunk-IBWN764Q.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";async function n(e,s){(e.includes("--help")||e.includes("-h"))&&(console.log(`
3
3
  sootsim screenshot-mode \u2014 toggle the screenshot-mode chrome overlay
4
4
 
5
5
  usage:
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as Y}from"./chunk-MWTMLNGM.js";import{b as j}from"./chunk-LVFWALS4.js";import"./chunk-YSQV4D7P.js";import"./chunk-4LYNJPUM.js";import"./chunk-EMMX6RF7.js";import"./chunk-EEMGSSWY.js";import{b as O}from"./chunk-XZ5SQJM2.js";import"./chunk-QMRXLBPN.js";import"./chunk-HWCZYW6M.js";import"./chunk-M3ZEZHOB.js";import"./chunk-V4SZERWD.js";import"./chunk-LCKLQSZX.js";import"./chunk-Z6HSVZIO.js";import"./chunk-GDCMTHEU.js";import"./chunk-NQKBIKUZ.js";import"./chunk-AYBGSHQK.js";import"./chunk-HIN5TAAL.js";import"./chunk-UNSLXX7V.js";import"./chunk-XOTJSR4T.js";import"./chunk-DEQ7RED3.js";import"./chunk-EIQLQDKX.js";import"./chunk-LRBMW2WC.js";import{a as w,b as D,c as k,d as z,e as x,f as T}from"./chunk-FXF2FHPI.js";import"./chunk-G4VWDOWB.js";import"./chunk-VRV2X4X2.js";import"./chunk-7NYW73Q6.js";import"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";import{mkdirSync as B,readFileSync as pe,writeFileSync as G}from"fs";import{tmpdir as je}from"os";import C from"path";import{mkdirSync as I,readFileSync as Q,writeFileSync as H}from"fs";import F from"path";function _(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 v(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function ee(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 M(e,t){let o=ee(e),i=Math.max(0,Math.min(1,t)),n=o.match(/^#([0-9a-f]{6})$/i);if(n){let s=n[1],r=Number.parseInt(s.slice(0,2),16),a=Number.parseInt(s.slice(2,4),16),u=Number.parseInt(s.slice(4,6),16);return`rgba(${r}, ${a}, ${u}, ${i})`}return o.startsWith("rgb(")?o.replace(/^rgb\((.+)\)$/i,`rgba($1, ${i})`):o}function te(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 re(e){let t=e.glow;return t?`radial-gradient(circle at 50% 24%, ${M(t,.46)} 0%, ${M(t,.2)} 24%, rgba(0,0,0,0) 62%)`:"none"}function A(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)";default:return"none"}}function L(...e){let t=e.map(o=>o.trim()).filter(o=>o.length>0&&o!=="none");return t.length>0?t.join(" "):"none"}function E(e){let t=M(e.color,e.opacity),o=M(e.color,e.opacity*.52);return`drop-shadow(0 34px ${e.spread}px ${o}) drop-shadow(0 0 ${e.blur}px ${t})`}function R(e,t){return!t.glow||e.color&&e.color!==w.color?e:{...e,color:t.glow}}function oe(e,t){if(e==="editorial-left"){let n=Math.round(t.height*.056),s=Math.round(t.height*.022);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.12)}px`,`left:${Math.round(t.width*.085)}px`,`width:${Math.round(t.width*.42)}px`,"text-align:left","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.92;`,subStyle:`font-size:${s}px;line-height:1.36;max-width:${Math.round(t.width*.36)}px;`,eyebrowStyle:"align-items:flex-start;",deviceStyle:(r,a,u)=>{let p=Math.round(t.width*.68*(a.scale??r.scale)),l=Math.round(t.height*(.03+r.offsetY+(a.offsetY??0))),c=a.pose||r.pose||"tilted-right",m=R(r.shadow,u);return["position:absolute",`top:${Math.round(t.height*.18)+l}px`,`left:${Math.round(t.width*.56)}px`,`width:${p}px`,"transform-origin:center center",`transform:${A(c)}`,`filter:${E(m)}`,"z-index:2"].join(";")}}}if(e==="minimal-bottom"){let n=Math.round(t.height*.041),s=Math.round(t.height*.019);return{copyStyle:["position:absolute",`left:${Math.round(t.width*.12)}px`,`right:${Math.round(t.width*.12)}px`,`bottom:${Math.round(t.height*.085)}px`,"text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.96;`,subStyle:`font-size:${s}px;line-height:1.34;max-width:${Math.round(t.width*.56)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(r,a,u)=>{let p=Math.round(t.width*.84*(a.scale??r.scale)),l=Math.round(t.height*(r.offsetY+(a.offsetY??0))),c=a.pose||r.pose,m=R(r.shadow,u);return["position:absolute",`top:${Math.round(t.height*.075)+l}px`,"left:50%",`width:${p}px`,"transform-origin:center center",`transform:${L("translateX(-50%)",A(c))}`,`filter:${E(m)}`,"z-index:2"].join(";")}}}let o=Math.round(t.height*.04),i=Math.round(t.height*.019);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.084)}px`,"left:50%",`width:${Math.round(t.width*.88)}px`,"transform:translateX(-50%)","text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${o}px;line-height:0.92;`,subStyle:`font-size:${i}px;line-height:1.34;max-width:${Math.round(t.width*.6)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(n,s,r)=>{let a=t.name==="ipad-13"?.54:.64,u=Math.round(t.width*a*(s.scale??n.scale)),p=Math.round(t.height*(n.offsetY+(s.offsetY??0))),l=s.pose||n.pose,c=R(n.shadow,r);return["position:absolute",`top:${Math.round(t.height*(t.name==="ipad-13"?.25:.28))+p}px`,"left:50%",`width:${u}px`,"transform-origin:center top",`transform:${L("translateX(-50%)",A(l))}`,`filter:${E(c)}`,"z-index:2"].join(";")}}}function ne({canvas:e,compose:t,slide:o,imageDataUrl:i}){let n=o.background??t.background,s=oe(t.text.preset,e),r=t.text.preset!=="none"&&!!(o.eyebrow||o.headline||o.subheadline),a=s.deviceStyle(t.frame,o,n),u=o.headline?`<div style="font-weight:780;white-space:pre-line;text-wrap:balance;${s.titleStyle}">${v(o.headline)}</div>`:"",p=o.subheadline?`<div style="margin-top:${Math.round(e.height*.018)}px;color:${t.text.subColor};white-space:pre-line;text-wrap:balance;${s.subStyle}">${v(o.subheadline)}</div>`:"",l=o.eyebrow?`<div style="display:flex;${s.eyebrowStyle}margin-bottom:${Math.round(e.height*.016)}px;"><div style="font-size:${Math.round(e.height*.014)}px;font-weight:700;letter-spacing:0.18em;text-transform:uppercase;color:${t.text.eyebrowColor};">${v(o.eyebrow)}</div></div>`:"";return`<!doctype html>
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as Y}from"./chunk-2HKCZLY7.js";import{b as j}from"./chunk-4QSGVTBE.js";import"./chunk-KR36VJSN.js";import"./chunk-SH6HMUCY.js";import"./chunk-KBJ2WHII.js";import"./chunk-LQ5BA5JU.js";import{b as O}from"./chunk-EJTXYZEF.js";import"./chunk-MIAAZSSE.js";import"./chunk-K4PKR2EO.js";import"./chunk-CUNQTNH4.js";import"./chunk-AQ7YR4MO.js";import"./chunk-XCRUPKWB.js";import"./chunk-7PQHQOCI.js";import"./chunk-ZO7SGE65.js";import"./chunk-GFVC6EEB.js";import"./chunk-5WRBVYML.js";import"./chunk-ZP2HMCKS.js";import"./chunk-ZJJKYJMH.js";import"./chunk-SVFSMAZN.js";import"./chunk-DOWYG3HG.js";import"./chunk-O624O5MO.js";import"./chunk-BCVVANS5.js";import{a as w,b as D,c as k,d as z,e as x,f as T}from"./chunk-NYR3Z44O.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import{mkdirSync as B,readFileSync as pe,writeFileSync as G}from"fs";import{tmpdir as je}from"os";import C from"path";import{mkdirSync as I,readFileSync as Q,writeFileSync as H}from"fs";import F from"path";function _(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 v(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function ee(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 M(e,t){let o=ee(e),i=Math.max(0,Math.min(1,t)),n=o.match(/^#([0-9a-f]{6})$/i);if(n){let s=n[1],r=Number.parseInt(s.slice(0,2),16),a=Number.parseInt(s.slice(2,4),16),u=Number.parseInt(s.slice(4,6),16);return`rgba(${r}, ${a}, ${u}, ${i})`}return o.startsWith("rgb(")?o.replace(/^rgb\((.+)\)$/i,`rgba($1, ${i})`):o}function te(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 re(e){let t=e.glow;return t?`radial-gradient(circle at 50% 24%, ${M(t,.46)} 0%, ${M(t,.2)} 24%, rgba(0,0,0,0) 62%)`:"none"}function A(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)";default:return"none"}}function L(...e){let t=e.map(o=>o.trim()).filter(o=>o.length>0&&o!=="none");return t.length>0?t.join(" "):"none"}function E(e){let t=M(e.color,e.opacity),o=M(e.color,e.opacity*.52);return`drop-shadow(0 34px ${e.spread}px ${o}) drop-shadow(0 0 ${e.blur}px ${t})`}function R(e,t){return!t.glow||e.color&&e.color!==w.color?e:{...e,color:t.glow}}function oe(e,t){if(e==="editorial-left"){let n=Math.round(t.height*.056),s=Math.round(t.height*.022);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.12)}px`,`left:${Math.round(t.width*.085)}px`,`width:${Math.round(t.width*.42)}px`,"text-align:left","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.92;`,subStyle:`font-size:${s}px;line-height:1.36;max-width:${Math.round(t.width*.36)}px;`,eyebrowStyle:"align-items:flex-start;",deviceStyle:(r,a,u)=>{let p=Math.round(t.width*.68*(a.scale??r.scale)),l=Math.round(t.height*(.03+r.offsetY+(a.offsetY??0))),c=a.pose||r.pose||"tilted-right",m=R(r.shadow,u);return["position:absolute",`top:${Math.round(t.height*.18)+l}px`,`left:${Math.round(t.width*.56)}px`,`width:${p}px`,"transform-origin:center center",`transform:${A(c)}`,`filter:${E(m)}`,"z-index:2"].join(";")}}}if(e==="minimal-bottom"){let n=Math.round(t.height*.041),s=Math.round(t.height*.019);return{copyStyle:["position:absolute",`left:${Math.round(t.width*.12)}px`,`right:${Math.round(t.width*.12)}px`,`bottom:${Math.round(t.height*.085)}px`,"text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.96;`,subStyle:`font-size:${s}px;line-height:1.34;max-width:${Math.round(t.width*.56)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(r,a,u)=>{let p=Math.round(t.width*.84*(a.scale??r.scale)),l=Math.round(t.height*(r.offsetY+(a.offsetY??0))),c=a.pose||r.pose,m=R(r.shadow,u);return["position:absolute",`top:${Math.round(t.height*.075)+l}px`,"left:50%",`width:${p}px`,"transform-origin:center center",`transform:${L("translateX(-50%)",A(c))}`,`filter:${E(m)}`,"z-index:2"].join(";")}}}let o=Math.round(t.height*.04),i=Math.round(t.height*.019);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.084)}px`,"left:50%",`width:${Math.round(t.width*.88)}px`,"transform:translateX(-50%)","text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${o}px;line-height:0.92;`,subStyle:`font-size:${i}px;line-height:1.34;max-width:${Math.round(t.width*.6)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(n,s,r)=>{let a=t.name==="ipad-13"?.54:.64,u=Math.round(t.width*a*(s.scale??n.scale)),p=Math.round(t.height*(n.offsetY+(s.offsetY??0))),l=s.pose||n.pose,c=R(n.shadow,r);return["position:absolute",`top:${Math.round(t.height*(t.name==="ipad-13"?.25:.28))+p}px`,"left:50%",`width:${u}px`,"transform-origin:center top",`transform:${L("translateX(-50%)",A(l))}`,`filter:${E(c)}`,"z-index:2"].join(";")}}}function ne({canvas:e,compose:t,slide:o,imageDataUrl:i}){let n=o.background??t.background,s=oe(t.text.preset,e),r=t.text.preset!=="none"&&!!(o.eyebrow||o.headline||o.subheadline),a=s.deviceStyle(t.frame,o,n),u=o.headline?`<div style="font-weight:780;white-space:pre-line;text-wrap:balance;${s.titleStyle}">${v(o.headline)}</div>`:"",p=o.subheadline?`<div style="margin-top:${Math.round(e.height*.018)}px;color:${t.text.subColor};white-space:pre-line;text-wrap:balance;${s.subStyle}">${v(o.subheadline)}</div>`:"",l=o.eyebrow?`<div style="display:flex;${s.eyebrowStyle}margin-bottom:${Math.round(e.height*.016)}px;"><div style="font-size:${Math.round(e.height*.014)}px;font-weight:700;letter-spacing:0.18em;text-transform:uppercase;color:${t.text.eyebrowColor};">${v(o.eyebrow)}</div></div>`:"";return`<!doctype html>
3
3
  <html>
4
4
  <head>
5
5
  <meta charset="utf-8" />
@@ -1,19 +1,19 @@
1
- /*! sootsim v0.1.66 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as ee,c as D,d as te,e as H,f as ie,h as re,i as A,j as ne,k as se,l as oe,p as ae,s as k,t as ce,u as de,v as le,w as ue}from"./chunk-BD76YSRN.js";import"./chunk-M2Q4FXRE.js";import{a as Q}from"./chunk-EMMX6RF7.js";import"./chunk-EEMGSSWY.js";import{e as E}from"./chunk-HWCZYW6M.js";import"./chunk-LCKLQSZX.js";import"./chunk-NQKBIKUZ.js";import{d as Y}from"./chunk-HIN5TAAL.js";import{a as F}from"./chunk-4NT6VRUU.js";import{a as z,b as X}from"./chunk-DEQ7RED3.js";import"./chunk-EIQLQDKX.js";import"./chunk-G4VWDOWB.js";import"./chunk-VRV2X4X2.js";import{a as U}from"./chunk-7NYW73Q6.js";import{k as Z}from"./chunk-NCSGLZRV.js";import{A as $,B,D as J,E as K,F as G,G as V,H as q,I as N,u as L,v as W,y as T,z as j}from"./chunk-BEQD2DSK.js";import"./chunk-D4VEI6MI.js";import{spawn as Le}from"child_process";import w from"fs";import{createServer as Be}from"http";import S from"path";import{WebSocket as h,WebSocketServer as Ne}from"ws";import pe from"node:fs";import I from"node:path";var P=1;function Ae(){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(a=>Number.isFinite(a)&&a>0)}var R=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 k?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await oe()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as ee,c as D,d as te,e as H,f as ie,h as re,i as A,j as ne,k as se,l as oe,p as ae,s as k,t as ce,u as de,v as le,w as ue}from"./chunk-67566AJS.js";import"./chunk-F4RC4AOY.js";import{a as Q}from"./chunk-KBJ2WHII.js";import"./chunk-LQ5BA5JU.js";import{e as E}from"./chunk-K4PKR2EO.js";import"./chunk-XCRUPKWB.js";import"./chunk-GFVC6EEB.js";import{d as Y}from"./chunk-ZP2HMCKS.js";import{a as F}from"./chunk-F23Y4HMT.js";import{a as z,b as X}from"./chunk-DOWYG3HG.js";import"./chunk-O624O5MO.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import{a as U}from"./chunk-6O64VUC6.js";import{k as Z}from"./chunk-YGQV3CUV.js";import{A as $,B,D as J,E as K,F as V,G,H as q,I as N,u as L,v as W,y as T,z as j}from"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";import{spawn as Le}from"child_process";import w from"fs";import{createServer as Be}from"http";import S from"path";import{WebSocket as h,WebSocketServer as Ne}from"ws";import pe from"node:fs";import I from"node:path";var P=1;function Ae(){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(a=>Number.isFinite(a)&&a>0)}var R=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 k?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await oe()}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 H();case"agent:upsert-project":return D(i.input??{});case"agent:delete-project":return re(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return ne(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-prompt":{let n=String(i.sessionId),o=A(n);if(!o)throw new k("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await de(n,r),this.notePromptAccepted(n,r,o.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await le(String(i.sessionId));let s=A(String(i.sessionId));return s&&this.broadcastSessionStatus(s),{ok:!0};case"agent:get-transcript":return this.getTranscript(String(i.sessionId));case"agent:get-paths":return this.getPaths();case"agent:subscribe-events":return this.subscribeSocket(e,String(i.sessionId));case"agent:unsubscribe-events":return this.unsubscribeSocket(e,String(i.sessionId));default:throw new k("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async doStartSession(e){if(!te(e.projectId))throw new k("NO_PROJECT",`no project: ${e.projectId}`);let i=await ce(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?.()??Ae(),o=(await E({excludePorts:s})).find(d=>String(d.port)===i);if(!o||!o.cwd)return{project:null};let r=H().find(d=>d.cwd===o.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],o.bundleUrl,t]));return{project:D({cwd:o.cwd,name:o.projectName??I.basename(o.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[o.cwd],knownBundleUrls:c,framework:r?.framework??ke(o.framework),bundleId:o.bundleId??r?.bundleId})}}getTranscript(e){let t=ae(e);return pe.existsSync(t)?pe.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=ee();return{userDataDir:e,storeFile:I.join(e,"attached-projects.json"),sessionsDir:I.join(e,"sessions"),transcriptsDir:I.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=ue(t,o=>{let r=this.coalescePromptEcho(t,o);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),o.type==="turn-completed"){let c=A(t);if(c)try{ie(c.projectId,{usd:o.costUsd,ts:o.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
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 o=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,o);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:o>1,pendingTurns:o,queueDepth:Math.max(0,o-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){se(e,t);let i=A(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===P)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===P)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===P)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===P)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function ke(a){return a==="expo"?"expo":a==="one"||a==="vxrn"?"one":"unknown"}import Ee from"http";import Ie from"https";var M="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",Ce=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"}}];function Te(a){let e=a.toLowerCase();for(let t of Ce)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t.headers;return{}}function me(a){return{"accept-encoding":"identity","user-agent":M,...Te(a.hostname)}}var Pe=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"]),Re={"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"};function C(a){for(let[e,t]of Object.entries(Re))a.setHeader(e,t)}function Oe(a,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 a.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function _e(a,e){let t={};for(let[i,s]of Object.entries(a))s&&(Pe.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?me(e):{"user-agent":M}),t}function he(a){return a?.startsWith("/__fetch-proxy?")||a?.startsWith("/__proxy?")||!1}function fe(a){return a?!!(a.startsWith("/__app-api?")||a.startsWith("/__app-api/")):!1}async function ge(a,e){if(a.method==="OPTIONS"){C(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((a.url||"").split("?")[1]||"").get("url");if(!i){C(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{C(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n=_e(a.headers,s),o;if(a.method!=="GET"&&a.method!=="HEAD"){let d=[];for await(let u of a)d.push(Buffer.isBuffer(u)?u:Buffer.from(u));d.length>0&&(o=Buffer.concat(d))}let r;try{r=await fetch(s.href,{method:a.method,headers:n,body:o,redirect:"follow"})}catch(d){C(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${Oe(s.href,d)}`);return}r.headers.forEach((d,u)=>{let p=u.toLowerCase();p==="content-encoding"||p==="transfer-encoding"||p==="content-length"||p==="set-cookie"||p.startsWith("access-control-")||e.setHeader(u,d)}),C(e);let c=r.headers.getSetCookie?.()??[];c.length>0&&e.setHeader("x-sootsim-set-cookie",c.join(", ")),e.statusCode=r.status;let l=Buffer.from(await r.arrayBuffer());e.end(l)}function Se(a,e){let t=a.url||"",i="",s="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",s=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(a.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":a.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":a.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 o=n.protocol==="https:"?Ie:Ee,r={...a.headers};delete r.host,r.host=n.host;let c=o.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:a.method,headers:r},l=>{let d=Object.keys(l.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":a.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return c.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),a.pipe(c),!0}var De=new Set(["tap","keyboard"]),He=2e3,Me=1e3;function Ue(a){return!a||typeof a.type!="string"?!1:a.acquireLock===!0?!0:a.readOnly===!0?!1:De.has(a.type)}var Fe=5e3,We=3600*1e3,je="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",$e={".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 ye(a,e,t){let i;try{let c=L();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimSootbeanOrigin=${JSON.stringify(t)};`:"",o=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(F())};</script>`,r=a.toString("utf8");return r.includes("</head>")?r.replace("</head>",o+"</head>"):r.includes("</body>")?r.replace("</body>",o+"</body>"):o+r}function ve(a){typeof a=="object"&&a!==null&&"unref"in a&&a.unref()}var O=class a{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;shouldWriteLockfile;sootbeanOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new R({getExcludePorts:e.agentScanExcludes}),this.sootbeanOrigin=e.sootbeanOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??a.SIM_IDLE_REAP_TTL_MS}getAgentHost(){return this.agentHost}reapIdleSimsForTest(e=Date.now()){this.reapIdleSims(e)}start(e){this.startAsync(e)}async startAsync(e){if(this.httpServer||this.wss)return this.effectivePort;this.refreshActiveRuntime();for(let t=0;t<this.portFallbackCount;t++){let i=this.preferredPort+t;try{return await this.bindOnce(i,e?.silent===!0),this.effectivePort=i,this.port=i,this.startedAt=Date.now(),t>0&&!e?.silent&&process.stderr.write(`ws bridge bound to port ${i} (preferred ${this.preferredPort} was taken)
5
5
  `),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}
6
6
  `)}}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=Be((c,l)=>this.handleHttpRequest(c,l)),o=!1,r=c=>{if(!o){o=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,s(c)}};n.once("error",r),n.listen(e,"127.0.0.1",()=>{o||(o=!0,n.removeListener("error",r),n.on("error",c=>{process.stderr.write(`ws bridge http error: ${String(c)}
7
- `)}),this.httpServer=n,this.wss=new Ne({server:n}),this.wireWebSocketServer(),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 o=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,o)}e.on("message",o=>{let r;try{r=JSON.parse(o.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=B(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:r.id,installed:c,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(r.type==="runtime:use"){let c=typeof r.version=="string"?r.version:"";if(!B().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d.focused===!0);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=W(d)}catch(m){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${m instanceof Error?m.message:String(m)}
7
+ `)}),this.httpServer=n,this.wss=new Ne({server:n}),this.wireWebSocketServer(),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 o=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,o)}e.on("message",o=>{let r;try{r=JSON.parse(o.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=B(),l=this.getActiveRuntime(),d={type:"runtime:list:ok",id:r.id,installed:c,active:l.version,activeRuntimeDir:l.runtimeDir};try{e.send(JSON.stringify(d))}catch{}return}if(r.type==="runtime:use"){let c=typeof r.version=="string"?r.version:"";if(!B().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=W(d)}catch(m){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${m instanceof Error?m.message:String(m)}
8
8
  `);return}let p=JSON.stringify({type:"bridge:shared-config-changed",config:u});for(let m of this.sims.values())if(m.ws.readyState===h.OPEN)try{m.ws.send(p)}catch{}return}if(r.type==="bridge:open-path"){let d=typeof r.path=="string"?r.path:"",u=typeof r.line=="number"&&Number.isFinite(r.line)?r.line:void 0,p=typeof r.column=="number"&&Number.isFinite(r.column)?r.column:void 0;d&&this.openPathInEditor(d,u,p);return}if(r.type==="bridge:boot-clients"&&n){let d=[];for(let[p,m]of this.cliSimBySocket)m===n.id&&d.push(p);for(let p of d){this.cliSimBySocket.delete(p);try{p.close(1e3,"booted by sim")}catch{}}let u=!!n.cliLease;n.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+a.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`sootsim booted ${d.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
9
9
  `),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let c=this.pendingCommands.get(r.id);if(c){this.pendingCommands.delete(r.id),r.error?c.reject(new Error(r.error)):c.resolve(r.result);return}let l=this.cliBySentId.get(r.id);if(l&&(this.cliBySentId.delete(r.id),l.ws.readyState===h.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...r,id:l.originalId,i:d}:{...r,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[m,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(m);p&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let p=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:p,leaseTtlMs:a.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:open"){if(typeof r.url!="string"||!r.url)throw new Error("bridge:open requires a url");await this.openUrl(r.url,{newWindow:r.newWindow===!0}),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{ok:!0,url:r.url}}));return}if(r.type==="bridge:claim"){let p=await this.waitForSim(r.simId),m=this.tryAcquireLease(e,p,{force:r.force===!0});if(!m.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${p.id} is locked by another cli`,o:m.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,m.bootedCount>0?`cli force-claimed sim (booted ${m.bootedCount})`:"cli claimed sim"),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:p.id,lockedBy:m.lease.cliIdentityKey,lockExpiresAt:m.lease.expiresAt,bootedCount:m.bootedCount}}));return}let c=await this.waitForSim(r.simId);if(Ue(r)){let p=this.tryAcquireLease(e,c);if(!p.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${c.id} is locked by another cli \u2014 use \`sootsim claim ${c.id} --force\` or \`sootsim open --new\``,o:p.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,c.id),this.recordSimAction(c.id,this.describeForwardedCommand(r));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:c.id,ws:e,originalId:r.id});let{simId:d,...u}=r;if(c.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:c.id}}));let p=c.ws,m=setTimeout(()=>{this.closeSimSocketFromHost(p)},He);ve(m)}}catch(c){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:c instanceof Error?c.message:String(c)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[o,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(o));for(let[o,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===h.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(o));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let o=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,c]of this.cliBySentId)c.ws===e&&this.cliBySentId.delete(r);o&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
10
10
  `),this.cliIdleTimer=setInterval(()=>this.sweepIdleCliClients(),3e4),this.cliIdleTimer.unref(),this.wsHeartbeatTimer=setInterval(()=>this.sweepDeadWebSockets(),a.WS_HEARTBEAT_INTERVAL_MS),this.wsHeartbeatTimer.unref(),this.shouldWriteLockfile){try{if(T(),!q(this.buildLockfileSnapshot()))throw new Error("another sootsim daemon wrote the lockfile during startup \u2014 aborting")}catch(e){throw process.stderr.write(`ws bridge failed to claim daemon lockfile: ${String(e)}
11
- `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},Fe),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}this.agentHost.seedOnBoot()}bootstrapping=!0;buildLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,activeRuntimeDir:this.activeRuntimeDirPath,startedAt:this.startedAt,heartbeatAt:Date.now(),bootstrapping:this.bootstrapping}}writeLockfileSnapshot(){V(this.buildLockfileSnapshot())}refreshActiveRuntime(){this.activeRuntimeVersion=j(),this.activeRuntimeDirPath=J()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=E({excludePorts:e,buildIconProxyUrl:t=>`/__bundle-proxy?url=${encodeURIComponent(t)}`}).then(t=>(this.scanCache=t,this.scanCacheAt=Date.now(),t)).catch(t=>{let i=t instanceof Error?t.message:String(t);return console.error("[sootsim] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<a.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[je]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):We}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer)return;this.runRuntimeUpdate("startup");let e=this.resolveRuntimeUpdateIntervalMs();this.runtimeUpdateTimer=setInterval(()=>{this.runRuntimeUpdate("periodic")},e),this.runtimeUpdateTimer.unref()}runRuntimeUpdate(e){return this.runtimeUpdateInFlight?this.runtimeUpdateInFlight:(this.runtimeUpdateInFlight=(async()=>{try{e==="startup"&&process.stderr.write(`sootsim: checking for runtime updates\u2026
11
+ `),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},Fe),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}this.agentHost.seedOnBoot()}bootstrapping=!0;buildLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,activeRuntimeDir:this.activeRuntimeDirPath,startedAt:this.startedAt,heartbeatAt:Date.now(),bootstrapping:this.bootstrapping}}writeLockfileSnapshot(){G(this.buildLockfileSnapshot())}refreshActiveRuntime(){this.activeRuntimeVersion=j(),this.activeRuntimeDirPath=J()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=E({excludePorts:e,buildIconProxyUrl:t=>`/__bundle-proxy?url=${encodeURIComponent(t)}`}).then(t=>(this.scanCache=t,this.scanCacheAt=Date.now(),t)).catch(t=>{let i=t instanceof Error?t.message:String(t);return console.error("[sootsim] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<a.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[je]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):We}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer)return;this.runRuntimeUpdate("startup");let e=this.resolveRuntimeUpdateIntervalMs();this.runtimeUpdateTimer=setInterval(()=>{this.runRuntimeUpdate("periodic")},e),this.runtimeUpdateTimer.unref()}runRuntimeUpdate(e){return this.runtimeUpdateInFlight?this.runtimeUpdateInFlight:(this.runtimeUpdateInFlight=(async()=>{try{e==="startup"&&process.stderr.write(`sootsim: checking for runtime updates\u2026
12
12
  `);let t=await Z();if(!t.updated||!t.latestVersion){e==="startup"&&process.stderr.write(`sootsim: runtime ${this.activeRuntimeVersion??"(none)"} is current
13
13
  `);return}let i=this.setActiveRuntime(t.latestVersion);process.stderr.write(`sootsim runtime updated to ${i.version} (${e})
14
14
  `)}catch(t){process.stderr.write(`sootsim runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
15
15
  `)}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
16
- `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if($(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{N()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy","credentialless"),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),he(e.url)){ge(e,t);return}if(fe(e.url)&&Se(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let m=await fetch(d.toString(),{redirect:"follow"}),f={},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:v,value:b}=await g.read();if(v)break;t.write(Buffer.from(b))}t.end()}catch(m){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${m instanceof Error?m.message:String(m)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(L())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let o=s.pathname;if(o==="/runtime"||o==="/runtime/"?o="/":o.startsWith("/runtime/")&&(o=o.slice(8)),(o===""||o==="/")&&(o="/index.html"),o.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&o.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of o.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=S.resolve(n,"."+o),c=n.endsWith(S.sep)?n:n+S.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}w.realpath(r,(l,d)=>{let u=l?r:d,p=u.endsWith(S.sep)?u:u+S.sep;if(!l){let m=(()=>{try{let f=w.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}}w.stat(u,(m,f)=>{if(m||!f?.isFile()){let b=S.extname(o).toLowerCase();if(b&&b!==".html"){t.writeHead(404),t.end("not found");return}if(o.startsWith("/__")||o.startsWith("/api/")||o==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let x=S.join(n,"index.html");w.readFile(x,(be,we)=>{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(ye(we,this.effectivePort,this.sootbeanOrigin))});return}let y=S.extname(u).toLowerCase(),g=$e[y]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(y===".html"){w.readFile(u,(b,x)=>{if(b){try{t.end()}catch{}return}t.end(ye(x,this.effectivePort,this.sootbeanOrigin))});return}let v=w.createReadStream(u);v.pipe(t),v.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<a.CLI_IDLE_TIMEOUT_MS)){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[o,r]of this.cliBySentId)r.ws===i&&this.cliBySentId.delete(o);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values());for(let i of this.sims.values()){if(i.id===this.primarySimId||t.has(i.id)||this.getActiveLease(i))continue;let s=Math.max(i.lastActiveAt,i.connectedAt);e-s<this.simIdleReapTtlMs||this.closeSimSocketFromHost(i.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==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(4001,U)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},Me);ve(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 o=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(o),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(o),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,o=(c,l)=>new Promise(d=>{try{let u=Le(c,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await o(c[0],[...c.slice(1),"-g",n]))return}await o("cursor",["-g",n])||await o("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await Y(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{N()}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,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),o=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-o)},bootedCount:0};if(r&&!c&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:o+a.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t;e.userFocused!==i&&(e.userFocused=i,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+a.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 o=this.getOpenSim(e);if(o)return o;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};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 o=Date.now();n.lastActiveAt=o,n.recentActions=[{label:s,at:o},...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,o]of this.cliSimBySocket){if(o!==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),o=e.id;this.sims.delete(o),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===o&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===o&&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()+a.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 Je(){let a=process.env.XPC_SERVICE_NAME||"";return!!(a.includes("dev.sootsim.daemon")||a.includes("dev.sootsim.server")||process.env.INVOCATION_ID)}async function wt(a,e={}){(a.includes("--help")||a.includes("-h"))&&(console.log(`
16
+ `)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if($(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{N()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy","credentialless"),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),he(e.url)){ge(e,t);return}if(fe(e.url)&&Se(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let m=await fetch(d.toString(),{redirect:"follow"}),f={},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:v,value:b}=await g.read();if(v)break;t.write(Buffer.from(b))}t.end()}catch(m){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${m instanceof Error?m.message:String(m)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(L())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let o=s.pathname;if(o==="/runtime"||o==="/runtime/"?o="/":o.startsWith("/runtime/")?o=o.slice(8):o==="/sootsim"||o==="/sootsim/"?o="/":o.startsWith("/sootsim/")&&(o=o.slice(8)),(o===""||o==="/")&&(o="/index.html"),o.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&o.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of o.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=S.resolve(n,"."+o),c=n.endsWith(S.sep)?n:n+S.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}w.realpath(r,(l,d)=>{let u=l?r:d,p=u.endsWith(S.sep)?u:u+S.sep;if(!l){let m=(()=>{try{let f=w.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}}w.stat(u,(m,f)=>{if(m||!f?.isFile()){let b=S.extname(o).toLowerCase();if(b&&b!==".html"){t.writeHead(404),t.end("not found");return}if(o.startsWith("/__")||o.startsWith("/api/")||o==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let x=S.join(n,"index.html");w.readFile(x,(be,we)=>{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(ye(we,this.effectivePort,this.sootbeanOrigin))});return}let y=S.extname(u).toLowerCase(),g=$e[y]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(y===".html"){w.readFile(u,(b,x)=>{if(b){try{t.end()}catch{}return}t.end(ye(x,this.effectivePort,this.sootbeanOrigin))});return}let v=w.createReadStream(u);v.pipe(t),v.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<a.CLI_IDLE_TIMEOUT_MS)){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[o,r]of this.cliBySentId)r.ws===i&&this.cliBySentId.delete(o);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values());for(let i of this.sims.values()){if(i.id===this.primarySimId||t.has(i.id)||this.getActiveLease(i))continue;let s=Math.max(i.lastActiveAt,i.connectedAt);e-s<this.simIdleReapTtlMs||this.closeSimSocketFromHost(i.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==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(4001,U)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},Me);ve(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 o=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(o),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(o),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,o=(c,l)=>new Promise(d=>{try{let u=Le(c,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await o(c[0],[...c.slice(1),"-g",n]))return}await o("cursor",["-g",n])||await o("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await Y(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{N()}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),o=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-o)},bootedCount:0};if(r&&!c&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:o+a.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,o=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===o||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=o,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+a.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 o=this.getOpenSim(e);if(o)return o;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 o=Date.now();n.lastActiveAt=o,n.recentActions=[{label:s,at:o},...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,o]of this.cliSimBySocket){if(o!==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),o=e.id;this.sims.delete(o),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===o&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===o&&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()+a.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 Je(){let a=process.env.XPC_SERVICE_NAME||"";return!!(a.includes("dev.sootsim.daemon")||a.includes("dev.sootsim.server")||process.env.INVOCATION_ID)}async function wt(a,e={}){(a.includes("--help")||a.includes("-h"))&&(console.log(`
17
17
  sootsim server \u2014 run the sootsim bridge daemon in the foreground
18
18
 
19
19
  hosts the WS bridge that CLI commands talk to. once running, any sootsim
@@ -30,6 +30,6 @@ options:
30
30
  examples:
31
31
  sootsim server
32
32
  sootsim server --port 7668 --quiet
33
- `),process.exit(0));let t=a.indexOf("--port"),i=t>=0&&a[t+1]?Number(a[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${a[t+1]}`),process.exit(1));let s=a.includes("--quiet")||a.includes("-q"),n=K();n&&G(n)&&(console.error(` a sootsim daemon is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),T();let o=await Q(),r=new O({port:i,writeLockfile:!0,sootbeanOrigin:o}),c=await r.startAsync({silent:s}),l=Date.now(),d=f=>{s||process.stdout.write(`${f}
33
+ `),process.exit(0));let t=a.indexOf("--port"),i=t>=0&&a[t+1]?Number(a[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${a[t+1]}`),process.exit(1));let s=a.includes("--quiet")||a.includes("-q"),n=K();n&&V(n)&&(console.error(` a sootsim daemon is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),T();let o=await Q(),r=new O({port:i,writeLockfile:!0,sootbeanOrigin:o}),c=await r.startAsync({silent:s}),l=Date.now(),d=f=>{s||process.stdout.write(`${f}
34
34
  `)},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 v=g.title||g.url||g.origin||"(unknown)";d(` + ${g.id} ${v}`)}for(let g of u)y.has(g)||d(` - ${g}`);u.clear();for(let g of y)u.add(g)},500);z({event:"daemon_heartbeat",properties:{bridge_port:c,under_daemon:Je(),platform:process.platform,subsource:"daemon"}}),X(),d(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${c})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let m=async f=>{clearInterval(p),d(`
35
35
  ${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{wt as runServer};
@@ -0,0 +1,2 @@
1
+ /*! sootsim v0.1.67 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a}from"./chunk-3KVVIZ6M.js";import"./chunk-ATRGAFJD.js";import"./chunk-N4JRDJMN.js";import"./chunk-DOWYG3HG.js";import"./chunk-O624O5MO.js";import"./chunk-U47AHSGE.js";import"./chunk-IB4BRND4.js";import"./chunk-6O64VUC6.js";import"./chunk-HW5YHSIE.js";import"./chunk-TLTS533S.js";export{a as runSetupRepo};