sootsim 0.1.169 → 0.1.171
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.
- package/README.md +66 -63
- package/detox/index.ts +3 -3
- package/dist-cli/bin.js +3 -3
- package/dist-cli/chunks/agent-J4NTKR6V.js +46 -0
- package/dist-cli/chunks/{agent-wrapper-Y5FQA3RL.js → agent-wrapper-V2TD3UZR.js} +2 -2
- package/dist-cli/chunks/{app-fonts-FYVA4XV6.js → app-fonts-ROVXMKLG.js} +2 -2
- package/dist-cli/chunks/{assert-U64QBDM2.js → assert-CXQAEBLS.js} +2 -2
- package/dist-cli/chunks/beta-BLY4YCCD.js +2 -0
- package/dist-cli/chunks/{camera-3GXBVIAM.js → camera-XPZFAU3B.js} +2 -2
- package/dist-cli/chunks/chunk-2UEHUM6Q.js +13 -0
- package/dist-cli/chunks/chunk-3OFDUWRM.js +2 -0
- package/dist-cli/chunks/chunk-547XSOJL.js +62 -0
- package/dist-cli/chunks/{chunk-3L4NRJ6C.js → chunk-AHOHHXWK.js} +1 -1
- package/dist-cli/chunks/{chunk-JDGLBW64.js → chunk-AOPGVSJW.js} +1 -1
- package/dist-cli/chunks/chunk-B77QXVTZ.js +118 -0
- package/dist-cli/chunks/chunk-CJTJX3H7.js +23 -0
- package/dist-cli/chunks/{chunk-2TYEWVS4.js → chunk-CVLJ4RMA.js} +1 -1
- package/dist-cli/chunks/chunk-DGVQPBNL.js +1 -0
- package/dist-cli/chunks/{chunk-MVOHANJG.js → chunk-DR3E2NVD.js} +4 -4
- package/dist-cli/chunks/{chunk-FIDPRJYH.js → chunk-E7P6ILZK.js} +2 -2
- package/dist-cli/chunks/{chunk-CR6DOLUD.js → chunk-EXN7SSF3.js} +1 -1
- package/dist-cli/chunks/{chunk-IODOTOOP.js → chunk-FJ2WDOTA.js} +2 -2
- package/dist-cli/chunks/{chunk-LZEL2RU3.js → chunk-HBR56XPR.js} +1 -1
- package/dist-cli/chunks/chunk-HQ3WABUY.js +1 -0
- package/dist-cli/chunks/{chunk-5Q7IHJ7K.js → chunk-I5OLONCL.js} +2 -2
- package/dist-cli/chunks/{chunk-XEH4QGWB.js → chunk-I5XY2BFR.js} +2 -2
- package/dist-cli/chunks/{chunk-GC4THE6K.js → chunk-ICA7K635.js} +2 -2
- package/dist-cli/chunks/{chunk-WZG3YVJR.js → chunk-J7DI5B4Y.js} +1 -1
- package/dist-cli/chunks/{chunk-YADWU7OZ.js → chunk-JQSGI66Q.js} +2 -2
- package/dist-cli/chunks/chunk-JQW2OOL5.js +2 -0
- package/dist-cli/chunks/{chunk-B7BMSU7H.js → chunk-KT55MHRH.js} +1 -1
- package/dist-cli/chunks/{chunk-PV6MBKKE.js → chunk-LSZRVSXO.js} +2 -2
- package/dist-cli/chunks/{chunk-IACEJQIO.js → chunk-MBVNBHRK.js} +2 -2
- package/dist-cli/chunks/{chunk-VMYMPL6H.js → chunk-N64WUTJB.js} +5 -5
- package/dist-cli/chunks/{chunk-KUUFY6FC.js → chunk-O54LARIO.js} +1 -1
- package/dist-cli/chunks/{chunk-Y6IDAARY.js → chunk-OIIPFIZL.js} +1 -1
- package/dist-cli/chunks/chunk-OSS2T3WP.js +2 -0
- package/dist-cli/chunks/{chunk-KZIXAYN5.js → chunk-OTN33CWO.js} +4 -4
- package/dist-cli/chunks/{chunk-4F3BBP7B.js → chunk-OYQVSV4I.js} +2 -2
- package/dist-cli/chunks/{chunk-G2ZFDIPK.js → chunk-QBCJDPG3.js} +4 -4
- package/dist-cli/chunks/chunk-QIMO6SQX.js +2 -0
- package/dist-cli/chunks/{chunk-SNX3M4XD.js → chunk-RISDCDO2.js} +3 -3
- package/dist-cli/chunks/chunk-RJZRI3P3.js +2 -0
- package/dist-cli/chunks/{chunk-OGLWXPVG.js → chunk-RNWTVHIS.js} +3 -3
- package/dist-cli/chunks/chunk-RULKWLIO.js +6 -0
- package/dist-cli/chunks/{chunk-IBEMMV5E.js → chunk-RXBB4S3Q.js} +8 -8
- package/dist-cli/chunks/{chunk-SIB6I72P.js → chunk-U7NWELJ3.js} +2 -2
- package/dist-cli/chunks/{chunk-HC72ILJK.js → chunk-WPEXAZSS.js} +2 -2
- package/dist-cli/chunks/{chunk-DQZEN256.js → chunk-WXPG6OS6.js} +1 -1
- package/dist-cli/chunks/{chunk-DNA6VS6M.js → chunk-X4VXITOI.js} +1 -1
- package/dist-cli/chunks/{chunk-BIWJE7CB.js → chunk-XD66TGXU.js} +1 -1
- package/dist-cli/chunks/{chunk-X2HNVXNM.js → chunk-XFSQORQ5.js} +2 -2
- package/dist-cli/chunks/{chunk-5C6BR24W.js → chunk-YBPF6OGE.js} +6 -6
- package/dist-cli/chunks/{chunk-GLRFKYDV.js → chunk-YPHT4BSL.js} +2 -2
- package/dist-cli/chunks/cli-version-EQIZQ5NI.js +2 -0
- package/dist-cli/chunks/{compat-ORRWNXVT.js → compat-32AVWHB7.js} +3 -3
- package/dist-cli/chunks/control-LF34QRMZ.js +2 -0
- package/dist-cli/chunks/{cpu-profile-6PRSBZ2F.js → cpu-profile-EEAXEDDO.js} +2 -2
- package/dist-cli/chunks/daemon-MUQQZ64R.js +2 -0
- package/dist-cli/chunks/{debug-Q3J2X4WW.js → debug-MW62345L.js} +5 -5
- package/dist-cli/chunks/{detox-DN57GMMJ.js → detox-UAPUROWZ.js} +2 -2
- package/dist-cli/chunks/{device-IL5TPYGU.js → device-IWWFCELP.js} +2 -2
- package/dist-cli/chunks/{diagnose-BW6QWP4F.js → diagnose-DL22YIRH.js} +2 -2
- package/dist-cli/chunks/drivers-3LBGADWJ.js +2 -0
- package/dist-cli/chunks/{electron-DGMSXQWG.js → electron-KDVB42AG.js} +3 -3
- package/dist-cli/chunks/flow-OE7GVTNZ.js +2 -0
- package/dist-cli/chunks/help-G7XRDP3G.js +2 -0
- package/dist-cli/chunks/{hints-TK3EHB4U.js → hints-GNVLVDPN.js} +2 -2
- package/dist-cli/chunks/home-paths-4JHJTIX5.js +2 -0
- package/dist-cli/chunks/{inspect-NFWFGU4B.js → inspect-RT36PPFH.js} +24 -24
- package/dist-cli/chunks/{install-desktop-GB3JKSNX.js → install-desktop-MXUBQ6NJ.js} +3 -3
- package/dist-cli/chunks/{keys-RAAHRIFH.js → keys-PS5IUZ2M.js} +2 -2
- package/dist-cli/chunks/{login-KQ37GHDE.js → login-PLPGPVOR.js} +4 -4
- package/dist-cli/chunks/{logout-63SH2Y25.js → logout-3NCVFTBB.js} +2 -2
- package/dist-cli/chunks/{maestro-24BT3MML.js → maestro-OTPRMCZ3.js} +2 -2
- package/dist-cli/chunks/optional-demo-registry-RMRKVBDN.js +2 -0
- package/dist-cli/chunks/{preview-KQAOVN6R.js → preview-JM3GALNL.js} +2 -2
- package/dist-cli/chunks/{profile-AN2B4NJT.js → profile-T2BO5XLW.js} +2 -2
- package/dist-cli/chunks/{react-ATGV35B4.js → react-U3FQRLFA.js} +2 -2
- package/dist-cli/chunks/{record-36662T3R.js → record-C6FA3WXN.js} +4 -4
- package/dist-cli/chunks/runtime-IGGC2EEX.js +2 -0
- package/dist-cli/chunks/{screenshot-K4N5MPAT.js → screenshot-XPDBDFIK.js} +4 -4
- package/dist-cli/chunks/{screenshot-mode-4QOJDLSH.js → screenshot-mode-4FED7FGF.js} +2 -2
- package/dist-cli/chunks/{screenshots-TB35YMSR.js → screenshots-GVEUZFXL.js} +2 -2
- package/dist-cli/chunks/{screenshots-capture-W6X33BZ4.js → screenshots-capture-TPGPJZ3J.js} +2 -2
- package/dist-cli/chunks/{server-L2PKDJZ2.js → serve-5G4JU44V.js} +18 -17
- package/dist-cli/chunks/setup-BGRJTFGF.js +77 -0
- package/dist-cli/chunks/skills-AGVA7E6K.js +40 -0
- package/dist-cli/chunks/{slides-TORKO36P.js → slides-Z7LW64IW.js} +2 -2
- package/dist-cli/chunks/store-KKALNEVX.js +2 -0
- package/dist-cli/chunks/telemetry-WHOFSYSH.js +2 -0
- package/dist-cli/chunks/{test-5VCENVW3.js → test-PFT2C45X.js} +3 -3
- package/dist-cli/chunks/{three-mode-ZVS2DSX6.js → three-mode-HOCUD4BU.js} +2 -2
- package/dist-cli/chunks/{timeline-TNC5OWLF.js → timeline-STMBOMTT.js} +2 -2
- package/dist-cli/chunks/{upgrade-E7IO6A7Z.js → upgrade-UXMJ73RU.js} +2 -2
- package/dist-cli/chunks/upload-NJTGOKHA.js +2 -0
- package/dist-cli/chunks/version-FNSM3CIG.js +4 -0
- package/dist-cli/chunks/web-TMIGK6QS.js +2 -0
- package/dist-cli/chunks/{what-happened-RMHZ7DGX.js → what-happened-R5KC4F7B.js} +3 -3
- package/dist-cli/chunks/{whoami-D53ANHR5.js → whoami-DWRGFQKR.js} +2 -2
- package/dist-lib/agent-daemon-client.cjs +4 -5
- package/dist-lib/agent-events.cjs +1 -1
- package/dist-lib/agent-sessions.cjs +1 -1
- package/dist-lib/attached-projects.cjs +1 -1
- package/dist-lib/auth/shared-session.cjs +1 -1
- package/dist-lib/backend-origin.cjs +1 -1
- package/dist-lib/beta.cjs +3 -6
- package/dist-lib/beta.mjs +3 -5
- package/dist-lib/bridge-constants.cjs +1 -1
- package/dist-lib/cli-constants.cjs +1 -1
- package/dist-lib/config.cjs +1 -1
- package/dist-lib/detox/index.cjs +4 -4
- package/dist-lib/dev-bundle-resolution.cjs +2 -9
- package/dist-lib/home-paths.cjs +59 -1
- package/dist-lib/host/bridge-host.cjs +67 -5
- package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
- package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
- package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
- package/dist-lib/host/websocket-proxy.cjs +1 -1
- package/dist-lib/index.cjs +2 -2
- package/dist-lib/menu.cjs +1 -1
- package/dist-lib/menu.mjs +1 -1
- package/dist-lib/metro.cjs +2 -2
- package/dist-lib/profiles.cjs +1 -1
- package/dist-lib/render-mode.cjs +1 -1
- package/dist-lib/scripts/dev-server-scanner.cjs +5 -4
- package/dist-lib/sdk.cjs +1 -1
- package/dist-lib/sdk.mjs +1 -1
- package/dist-lib/skills.cjs +127 -11
- package/dist-lib/vite.cjs +2 -2
- package/package.json +2 -1
- package/scripts/dev-server-scanner.ts +3 -4
- package/scripts/postinstall.cjs +2 -2
- package/scripts/preuninstall.cjs +5 -7
- package/skills/soot.md +178 -0
- package/skills/sootsim-debug.md +384 -0
- package/skills/sootsim-setup.md +96 -0
- package/skills/sootsim-test.md +292 -0
- package/skills/sootsim-visual.md +122 -0
- package/src/agent-daemon-client.ts +4 -14
- package/src/beta.ts +3 -5
- package/src/dev-bundle-resolution.ts +1 -14
- package/src/home-paths.ts +77 -2
- package/src/host/agent-host.ts +1 -1
- package/src/host/bridge-host.ts +65 -6
- package/src/metro-plugin.ts +1 -1
- package/src/runtime-assets.ts +1 -1
- package/src/vite-plugin.ts +1 -0
- package/dist-cli/chunks/agent-V3GVCRPL.js +0 -46
- package/dist-cli/chunks/auto-bootstrap-YXDP3WKH.js +0 -2
- package/dist-cli/chunks/beta-FGSMZWLP.js +0 -2
- package/dist-cli/chunks/chunk-2IFWVIKM.js +0 -2
- package/dist-cli/chunks/chunk-3T36XLP3.js +0 -119
- package/dist-cli/chunks/chunk-5KY7TQ42.js +0 -5
- package/dist-cli/chunks/chunk-BQOMDL4K.js +0 -1
- package/dist-cli/chunks/chunk-FHMPJZKM.js +0 -7
- package/dist-cli/chunks/chunk-GQAWFQNN.js +0 -23
- package/dist-cli/chunks/chunk-HJTKKF7M.js +0 -13
- package/dist-cli/chunks/chunk-K4JAWKOY.js +0 -1
- package/dist-cli/chunks/chunk-M2TMFGZH.js +0 -2
- package/dist-cli/chunks/chunk-NXGQS7IR.js +0 -2
- package/dist-cli/chunks/chunk-R2INPDGW.js +0 -1
- package/dist-cli/chunks/chunk-SLL5SZN4.js +0 -2
- package/dist-cli/chunks/chunk-XM66K64H.js +0 -79
- package/dist-cli/chunks/cli-version-3L6FFDIX.js +0 -2
- package/dist-cli/chunks/config-5IB6ONJ2.js +0 -45
- package/dist-cli/chunks/control-BM4V27OB.js +0 -2
- package/dist-cli/chunks/daemon-62MZT4G4.js +0 -67
- package/dist-cli/chunks/drivers-V6QDFZQD.js +0 -2
- package/dist-cli/chunks/flow-VBM6TU32.js +0 -2
- package/dist-cli/chunks/help-XWKNL743.js +0 -2
- package/dist-cli/chunks/home-paths-G23H3RO6.js +0 -2
- package/dist-cli/chunks/install-5YL7FITA.js +0 -2
- package/dist-cli/chunks/launch-DYFE4CAD.js +0 -16
- package/dist-cli/chunks/optional-demo-registry-JJXPB3UD.js +0 -2
- package/dist-cli/chunks/runtime-NRMC3U3D.js +0 -2
- package/dist-cli/chunks/runtime-delivery-RO6CTYPQ.js +0 -2
- package/dist-cli/chunks/setup-repo-AK6QOUE7.js +0 -2
- package/dist-cli/chunks/skills-KDSOWUOE.js +0 -10
- package/dist-cli/chunks/start-GH2AOUX6.js +0 -23
- package/dist-cli/chunks/store-JHW65VGQ.js +0 -2
- package/dist-cli/chunks/telemetry-SZLRXJXW.js +0 -2
- package/dist-cli/chunks/upload-KKEWETA5.js +0 -2
- package/dist-cli/chunks/version-37OD33SE.js +0 -4
- package/dist-cli/chunks/web-4JVMIBTB.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as R}from"./chunk-EXN7SSF3.js";import{a as E}from"./chunk-XFSQORQ5.js";import"./chunk-DGVQPBNL.js";import{r as y}from"./chunk-X4VXITOI.js";import{c as x,d as v,e as S,f as b,h as _}from"./chunk-CJTJX3H7.js";import"./chunk-MBVNBHRK.js";import"./chunk-WXPG6OS6.js";import"./chunk-O54LARIO.js";import"./chunk-RULKWLIO.js";import"./chunk-I5OLONCL.js";import{g as w}from"./chunk-CVLJ4RMA.js";import"./chunk-AOPGVSJW.js";import{mkdirSync as $,writeFileSync as A}from"fs";import{dirname as M,resolve as F}from"path";async function Q(t,o){let e=q(t);(e.includes("--help")||e.includes("-h"))&&(console.log(`
|
|
3
3
|
sootsim screenshot \u2014 capture the canvas as a PNG
|
|
4
4
|
|
|
5
5
|
usage:
|
|
@@ -27,9 +27,9 @@ examples:
|
|
|
27
27
|
sootsim screenshot --with-frame --output framed.png
|
|
28
28
|
sootsim screenshot --area 0,200,393,400 --output hero.png
|
|
29
29
|
sootsim screenshot --id loginButton --output button.png
|
|
30
|
-
`),process.exit(0));let r=V(e);if(r.length>0){for(let{flag:a,suggestion:m}of r)console.error(m?` unknown flag: ${a} (did you mean ${m}?)`:` unknown flag: ${a}`);console.error(" run `sootsim screenshot --help` for the list of supported flags"),process.exit(1)}let s=e.includes("--gallery"),n=e.includes("--themes"),u=G(e),c=U(e);if(s||n)return u&&(console.error(" --with-frame is not supported with --gallery / --themes"),process.exit(1)),T(e,o);u&&e.some(a=>a==="--area"||a==="--id"||a==="--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 i=
|
|
30
|
+
`),process.exit(0));let r=V(e);if(r.length>0){for(let{flag:a,suggestion:m}of r)console.error(m?` unknown flag: ${a} (did you mean ${m}?)`:` unknown flag: ${a}`);console.error(" run `sootsim screenshot --help` for the list of supported flags"),process.exit(1)}let s=e.includes("--gallery"),n=e.includes("--themes"),u=G(e),c=U(e);if(s||n)return u&&(console.error(" --with-frame is not supported with --gallery / --themes"),process.exit(1)),T(e,o);u&&e.some(a=>a==="--area"||a==="--id"||a==="--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 i=x(e,{port:o.port,stripBooleanFlags:["--with-frame","--no-frame","--no-shell","--shell-only"],stripValueFlags:["--output","--area","--id","--text"]}),l=O(e),p=await D(e);if(await N(i.wsPort)){try{await L(i,l,p,u,c)}catch(a){console.error(` screenshot failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}return}u&&(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)),p&&(console.error(" --area / --id / --text require a running sootsim bridge"),console.error(" start one with `sootsim serve`, `sootsim electron`, or your project dev server"),process.exit(1)),await T(e,o)}async function N(t){let o=v(t,{commandTimeoutMs:1e3});try{return await o.listSims(),!0}catch{return!1}finally{o.close()}}async function D(t){let o=t.find((s,n)=>t[n-1]==="--area");if(o){let s=o.split(",").map(l=>Number(l.trim()));if(s.length!==4||s.some(l=>!Number.isFinite(l)))throw new Error(`--area expects x,y,w,h (got "${o}")`);let[n,u,c,i]=s;return{x:n,y:u,w:c,h:i}}let e=t.find((s,n)=>t[n-1]==="--id"),r=t.find((s,n)=>t[n-1]==="--text");return e||r?{__matcher:{id:e,text:r}}:null}async function L(t,o,e,r,s){let n=S({...t,commandTimeoutMs:45e3});try{(await b(n)).hidden&&process.stderr.write(` \u26A0 screenshot will capture the LAST PAINTED canvas \u2014 likely stale.
|
|
31
31
|
navigation/\`shell\` commands sent before this screenshot may not
|
|
32
32
|
have repainted yet. focus the tab manually or \`sootsim --sim <id>\`
|
|
33
33
|
to target a visible sim before capturing.
|
|
34
34
|
|
|
35
|
-
`);let c=Number(process.env.SOOT_SCREENSHOT_READY_MAX_MS)||9e4,i=await
|
|
35
|
+
`);let c=Number(process.env.SOOT_SCREENSHOT_READY_MAX_MS)||9e4,i=await y(n,c);if(!i.ready)throw new Error(`app not ready to capture after ${Math.round(i.elapsedMs/1e3)}s`+(i.loadingText?` (still showing "${i.loadingText}")`:"")+"; refusing to capture the boot/loading card. retry once the app paints.");let l=e,p=e?.__matcher;if(p){let h=await n.send({type:"evaluate",code:R(p)});if(!h)throw new Error(p.id?`no node with id "${p.id}"`:`no node matching text "${p.text}"`);l=h}let d=l?{x:l.x,y:l.y,w:l.w,h:l.h}:void 0,a={type:"screenshot"};s&&(a.layers=s),d&&(a.crop=d);let k=(await n.send(a)).replace(/^data:image\/png;base64,/,"");d&&console.log(` area: x=${d.x} y=${d.y} w=${d.w} h=${d.h}`),s&&console.log(` layers: ${s}`);let f=F(process.cwd(),o||"/tmp/sootsim-inspect.png");$(M(f),{recursive:!0});let g=Buffer.from(k,"base64");if(r){let h=await C(n);if(!h)throw new Error("could not read current device model from the target sim");let P=await E(g,h);A(f,P),console.log(` frame: ${h}`)}else A(f,g);console.log(` saved: ${f}`)}finally{n.close()}}async function C(t){let o=await _(t,"SootSim.bridges.settings.get")??{deviceModel:null},e=typeof o.deviceModel=="string"?o.deviceModel:null;return!e||!(e in w)?null:e}function G(t){let o=!1;for(let e of t)e==="--with-frame"&&(o=!0),e==="--no-frame"&&(o=!1);return o}function U(t){if(t.includes("--shell-only"))return"shell";if(t.includes("--no-shell"))return"tenant"}var H=new Set(["--help","-h","--verbose","-v","--with-frame","--no-frame","--no-shell","--shell-only","--gallery","--themes"]),B=new Set(["--output","--area","--id","--text","--url","--port","--timeout","--sim"]),I={"--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 q(t){let o=[],e={"-o":"--output","--out":"--output","--file":"--output","--path":"--output","--testid":"--id","--test-id":"--id","--test_id":"--id","--rect":"--area","--crop":"--area","--region":"--area","--bounds":"--area","--box":"--area","--xywh":"--area"};for(let r of t){let s=e[r];o.push(s??r)}return o}function V(t){let o=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.startsWith("-")){if(B.has(r)){e++;continue}H.has(r)||o.push({flag:r,suggestion:I[r]})}}return o}function O(t){let o=t.find((e,r)=>t[r-1]==="--output");if(o)return o;for(let e=0;e<t.length;e++){let r=t[e];if(r.startsWith("-")){B.has(r)&&e++;continue}return r}}async function T(t,o){let e=O(t)||"sootsim-screenshot.png",r=t.includes("--gallery"),s=t.find((c,i)=>t[i-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 c=await u.newPage({viewport:{width:500,height:900}});await c.goto(s,{waitUntil:"networkidle"}),await c.waitForTimeout(2e3);let i=F(process.cwd(),e);$(M(i),{recursive:!0}),await c.screenshot({path:i}),console.log(` saved: ${i}`),await c.close()}}catch(c){console.error(` screenshot failed: ${c.message}`),process.exitCode=1}finally{await u.close()}}export{Q as runScreenshot};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as o}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as o}from"./chunk-OYQVSV4I.js";import"./chunk-CJTJX3H7.js";import"./chunk-WXPG6OS6.js";import"./chunk-O54LARIO.js";import"./chunk-RULKWLIO.js";import"./chunk-AOPGVSJW.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.
|
|
2
|
-
import{b as q}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{b as q}from"./chunk-YBPF6OGE.js";import{b as L}from"./chunk-XFSQORQ5.js";import"./chunk-DGVQPBNL.js";import"./chunk-JQSGI66Q.js";import{b as H}from"./chunk-E7P6ILZK.js";import"./chunk-2UEHUM6Q.js";import"./chunk-QBCJDPG3.js";import"./chunk-OTN33CWO.js";import"./chunk-X4VXITOI.js";import"./chunk-OIIPFIZL.js";import"./chunk-DR3E2NVD.js";import"./chunk-J7DI5B4Y.js";import"./chunk-I5XY2BFR.js";import"./chunk-N64WUTJB.js";import{d as U,e as K}from"./chunk-U7NWELJ3.js";import"./chunk-JQW2OOL5.js";import"./chunk-KT55MHRH.js";import"./chunk-CJTJX3H7.js";import"./chunk-ICA7K635.js";import"./chunk-FJ2WDOTA.js";import"./chunk-LSZRVSXO.js";import"./chunk-MBVNBHRK.js";import"./chunk-3OFDUWRM.js";import"./chunk-WXPG6OS6.js";import"./chunk-O54LARIO.js";import"./chunk-RULKWLIO.js";import"./chunk-I5OLONCL.js";import{a as y,b as A,c as E,d as O,e as v,f as C,g as _}from"./chunk-CVLJ4RMA.js";import"./chunk-AOPGVSJW.js";import{mkdirSync as I,readFileSync as ye,writeFileSync as se}from"fs";import{tmpdir as We}from"os";import F from"path";import{mkdirSync as W,readFileSync as ae,writeFileSync as X}from"fs";import B from"path";function V(e){return e.replace(/\\/g,"/").replace(/\.png$/i,"").trim().split("/").filter(Boolean).join("--").replace(/[^A-Za-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"slide"}function T(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function ce(e){let t=e.trim();return/^#[0-9a-f]{3}$/i.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:t}function D(e,t){let o=ce(e),i=Math.max(0,Math.min(1,t)),n=o.match(/^#([0-9a-f]{6})$/i);if(n){let s=n[1],r=Number.parseInt(s.slice(0,2),16),a=Number.parseInt(s.slice(2,4),16),c=Number.parseInt(s.slice(4,6),16);return`rgba(${r}, ${a}, ${c}, ${i})`}return o.startsWith("rgb(")?o.replace(/^rgb\((.+)\)$/i,`rgba($1, ${i})`):o}function le(e){if(e.type==="solid")return e.color||"#000000";let t=e.direction??180,o=e.stops?.map(i=>`${i.color} ${i.offset}%`).join(", ")||"#000000 0%, #111111 100%";return`linear-gradient(${t}deg, ${o})`}function pe(e){let t=e.glow;return t?`radial-gradient(circle at 50% 24%, ${D(t,.46)} 0%, ${D(t,.2)} 24%, rgba(0,0,0,0) 62%)`:"none"}function R(e){switch(e){case"tilted-left":return"perspective(2400px) rotateY(10deg) rotateZ(-2deg)";case"tilted-right":return"perspective(2400px) rotateY(-10deg) rotateZ(2deg)";case"cut-bottom":return"translateY(10%) scale(1.08)";case"cut-top":return"translateY(-16%) scale(1.08)";case"straight":default:return"none"}}function G(...e){let t=e.map(o=>o.trim()).filter(o=>o.length>0&&o!=="none");return t.length>0?t.join(" "):"none"}function j(e){let t=D(e.color,e.opacity),o=D(e.color,e.opacity*.52);return`drop-shadow(0 34px ${e.spread}px ${o}) drop-shadow(0 0 ${e.blur}px ${t})`}function Y(e,t){return!t.glow||e.color&&e.color!==y.color?e:{...e,color:t.glow}}function ue(e,t){if(e==="editorial-left"){let n=Math.round(t.height*.056),s=Math.round(t.height*.022);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.12)}px`,`left:${Math.round(t.width*.085)}px`,`width:${Math.round(t.width*.42)}px`,"text-align:left","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.92;`,subStyle:`font-size:${s}px;line-height:1.36;max-width:${Math.round(t.width*.36)}px;`,eyebrowStyle:"align-items:flex-start;",deviceStyle:(r,a,c)=>{let p=Math.round(t.width*.68*(a.scale??r.scale)),l=Math.round(t.height*(.03+r.offsetY+(a.offsetY??0))),d=a.pose||r.pose||"tilted-right",h=Y(r.shadow,c);return["position:absolute",`top:${Math.round(t.height*.18)+l}px`,`left:${Math.round(t.width*.56)}px`,`width:${p}px`,"transform-origin:center center",`transform:${R(d)}`,`filter:${j(h)}`,"z-index:2"].join(";")}}}if(e==="minimal-bottom"){let n=Math.round(t.height*.041),s=Math.round(t.height*.019);return{copyStyle:["position:absolute",`left:${Math.round(t.width*.12)}px`,`right:${Math.round(t.width*.12)}px`,`bottom:${Math.round(t.height*.085)}px`,"text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${n}px;line-height:0.96;`,subStyle:`font-size:${s}px;line-height:1.34;max-width:${Math.round(t.width*.56)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(r,a,c)=>{let p=Math.round(t.width*.84*(a.scale??r.scale)),l=Math.round(t.height*(r.offsetY+(a.offsetY??0))),d=a.pose||r.pose,h=Y(r.shadow,c);return["position:absolute",`top:${Math.round(t.height*.075)+l}px`,"left:50%",`width:${p}px`,"transform-origin:center center",`transform:${G("translateX(-50%)",R(d))}`,`filter:${j(h)}`,"z-index:2"].join(";")}}}let o=Math.round(t.height*.04),i=Math.round(t.height*.019);return{copyStyle:["position:absolute",`top:${Math.round(t.height*.084)}px`,"left:50%",`width:${Math.round(t.width*.88)}px`,"transform:translateX(-50%)","text-align:center","z-index:3"].join(";"),titleStyle:`font-size:${o}px;line-height:0.92;`,subStyle:`font-size:${i}px;line-height:1.34;max-width:${Math.round(t.width*.6)}px;margin:0 auto;`,eyebrowStyle:"align-items:center;",deviceStyle:(n,s,r)=>{let a=t.name==="ipad-13"?.54:.64,c=Math.round(t.width*a*(s.scale??n.scale)),p=Math.round(t.height*(n.offsetY+(s.offsetY??0))),l=s.pose||n.pose,d=Y(n.shadow,r);return["position:absolute",`top:${Math.round(t.height*(t.name==="ipad-13"?.25:.28))+p}px`,"left:50%",`width:${c}px`,"transform-origin:center top",`transform:${G("translateX(-50%)",R(l))}`,`filter:${j(d)}`,"z-index:2"].join(";")}}}function de({canvas:e,compose:t,slide:o,imageDataUrl:i}){let n=o.background??t.background,s=ue(t.text.preset,e),r=t.text.preset!=="none"&&!!(o.eyebrow||o.headline||o.subheadline),a=s.deviceStyle(t.frame,o,n),c=o.headline?`<div style="font-weight:780;white-space:pre-line;text-wrap:balance;${s.titleStyle}">${T(o.headline)}</div>`:"",p=o.subheadline?`<div style="margin-top:${Math.round(e.height*.018)}px;color:${t.text.subColor};white-space:pre-line;text-wrap:balance;${s.subStyle}">${T(o.subheadline)}</div>`:"",l=o.eyebrow?`<div style="display:flex;${s.eyebrowStyle}margin-bottom:${Math.round(e.height*.016)}px;"><div style="font-size:${Math.round(e.height*.014)}px;font-weight:700;letter-spacing:0.18em;text-transform:uppercase;color:${t.text.eyebrowColor};">${T(o.eyebrow)}</div></div>`:"";return`<!doctype html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8" />
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{d as I}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{d as I}from"./chunk-U7NWELJ3.js";import"./chunk-LSZRVSXO.js";import"./chunk-RULKWLIO.js";import"./chunk-AOPGVSJW.js";import{execSync as E}from"node:child_process";import{mkdirSync as L,mkdtempSync as W,rmSync as q,writeFileSync as z}from"node:fs";import{tmpdir as H}from"node:os";import{dirname as J,isAbsolute as K,join as A,resolve as V}from"node:path";import{chromium as Y}from"playwright-core";import{execSync as j}from"node:child_process";function N(o){let e=o;if(e&&typeof e.process=="function")try{let t=e.process();if(t&&typeof t.pid=="number"&&t.pid>0)return t.pid}catch{}if(e&&typeof e.browser=="function")try{let t=e.browser();if(t)return N(t)}catch{}return null}function x(o){let e=[];try{e=j(`pgrep -P ${o} || true`).toString().split(`
|
|
3
3
|
`).filter(Boolean)}catch{}for(let t of e)x(Number(t));try{process.kill(o,"SIGKILL")}catch{}}var C=new Set,M=!1;function B(){if(M)return;M=!0;let o=()=>{for(let e of C)x(e)};process.on("SIGTERM",()=>{o(),process.exit(0)}),process.on("SIGINT",()=>{o(),process.exit(0)}),process.on("exit",o)}async function U(o){let e=await o(),t=N(e),n=new Set;t!=null&&(n.add(t),C.add(t),B());let i=e;return typeof i.on=="function"&&i.on("disconnected",()=>{for(let c of n)C.delete(c)}),{browser:e,reapNow:()=>{for(let c of n)x(c),C.delete(c);n.clear()}}}var Q=`
|
|
4
4
|
sootsim screenshots capture \u2014 headlessly capture + upload App Store slides
|
|
5
5
|
|
|
@@ -1,40 +1,41 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{b as oe,c as H,d as ae,e as F,f as ce,h as de,i as
|
|
3
|
-
`)}}close(){for(let e of this.subscriptions.values())try{e.unsubscribe()}catch{}this.subscriptions.clear(),this.sessionsBySocket.clear(),this.allSockets.clear()}async dispatch(e,t,i){switch(t){case"agent:list-projects":return F();case"agent:upsert-project":return H(i.input??{});case"agent:delete-project":return de(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return le(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-prompt":{let n=String(i.sessionId),a=
|
|
4
|
-
`)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let a=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,a);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:a>1,pendingTurns:a,queueDepth:Math.max(0,a-1)}}applySessionEvent(e,t){switch(t.type){case"prompt-received":case"turn-started":this.patchSession(e,{status:"working",needsAttention:!1});return;case"turn-completed":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"idle",needsAttention:!1,lastTurnFiles:t.filesTouched,currentlyEditing:void 0});return}case"approval-needed":this.patchSession(e,{status:"needs-attention",needsAttention:!0});return;case"error":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"needs-attention",needsAttention:i<=0,currentlyEditing:void 0});return}case"exited":this.clearPromptTracking(e),this.patchSession(e,{status:"ended",needsAttention:!1,wrapperPid:void 0,currentlyEditing:void 0});return;case"ready":case"turn-reasoning":case"turn-message":case"turn-plan":case"tool-call":case"file-edited":case"file-diff-delta":return}}patchSession(e,t){ue(e,t);let i=
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{b as oe,c as H,d as ae,e as F,f as ce,h as de,i as T,j as le,k as ue,l as pe,p as me,s as C,t as he,u as fe,v as ge,w as Se}from"./chunk-WPEXAZSS.js";import"./chunk-HBR56XPR.js";import{g as ne}from"./chunk-RNWTVHIS.js";import{f as P}from"./chunk-QBCJDPG3.js";import"./chunk-OIIPFIZL.js";import{a as se}from"./chunk-N64WUTJB.js";import"./chunk-U7NWELJ3.js";import"./chunk-JQW2OOL5.js";import"./chunk-KT55MHRH.js";import"./chunk-CJTJX3H7.js";import{d as re}from"./chunk-ICA7K635.js";import{a as Z,b as Q}from"./chunk-FJ2WDOTA.js";import"./chunk-LSZRVSXO.js";import{a as te,b as ie}from"./chunk-WXPG6OS6.js";import"./chunk-O54LARIO.js";import{C as E,D as $,E as J,F as M,H as K,I as V,K as G,M as q,N as z,O as X,P as U,Q as Y,y as N,z as j}from"./chunk-RULKWLIO.js";import{a as ee}from"./chunk-AHOHHXWK.js";import"./chunk-AOPGVSJW.js";import{spawn as Qe}from"child_process";import k from"fs";import{createServer as et}from"http";import S from"path";import{WebSocket as h,WebSocketServer as tt}from"ws";import ye from"node:fs";import R from"node:path";var _=1;function _e(){return[Number(process.env.VITE_PORT_WEB||process.env.PORT||3e3),Number(process.env.VITE_PORT_ZERO||7849),Number(process.env.VITE_PORT_POSTGRES||7432),Number(process.env.VITE_PORT_R2||9500)].filter(o=>Number.isFinite(o)&&o>0)}var O=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 C?this.respondError(e,s,n.message,n.code):this.respondError(e,s,n instanceof Error?n.message:String(n))}return!0}async seedOnBoot(){try{await pe()}catch(e){process.stderr.write(`[sootsim-agent] seedFromDemoAppRegistry failed: ${e instanceof Error?e.message:String(e)}
|
|
3
|
+
`)}}close(){for(let e of this.subscriptions.values())try{e.unsubscribe()}catch{}this.subscriptions.clear(),this.sessionsBySocket.clear(),this.allSockets.clear()}async dispatch(e,t,i){switch(t){case"agent:list-projects":return F();case"agent:upsert-project":return H(i.input??{});case"agent:delete-project":return de(String(i.projectId)),{ok:!0};case"agent:auto-attach-for-url":return this.autoAttachForUrl(i.input??{});case"agent:list-sessions":return le(i.projectId?String(i.projectId):void 0);case"agent:start-session":return this.doStartSession(i.input??{});case"agent:send-prompt":{let n=String(i.sessionId),a=T(n);if(!a)throw new C("NO_SESSION",`no session: ${n}`);let r=this.normalizePromptEnvelope(i);return await fe(n,r),this.notePromptAccepted(n,r,a.status==="working")}case"agent:end-session":this.dropSessionFanout(String(i.sessionId)),await ge(String(i.sessionId));let s=T(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 C("UNKNOWN_AGENT_MSG",`unknown agent message: ${t}`)}}async doStartSession(e){if(!ae(e.projectId))throw new C("NO_PROJECT",`no project: ${e.projectId}`);let i=await he(e);return this.broadcastSessionStatus(i.session),i}async autoAttachForUrl(e){let t=e.bundleUrl??"",i=(()=>{try{return new URL(t).port||null}catch{return null}})();if(!i)return{project:null};let s=this.opts.getExcludePorts?.()??_e(),a=(await P({excludePorts:s})).find(d=>String(d.port)===i);if(!a||!a.cwd)return{project:null};let r=F().find(d=>d.cwd===a.cwd)??null,c=Array.from(new Set([...r?.knownBundleUrls??[],a.bundleUrl,t]));return{project:H({cwd:a.cwd,name:a.projectName??R.basename(a.cwd),preferredProvider:e.provider??r?.preferredProvider,sourceRoots:r?.sourceRoots??[a.cwd],knownBundleUrls:c,framework:r?.framework??Oe(a.framework),bundleId:a.bundleId??r?.bundleId})}}getTranscript(e){let t=me(e);return ye.existsSync(t)?ye.readFileSync(t,"utf8"):{error:"transcript not found",code:"NO_TRANSCRIPT"}}getPaths(){let e=oe();return{userDataDir:e,storeFile:R.join(e,"attached-projects.json"),sessionsDir:R.join(e,"sessions"),transcriptsDir:R.join(e,"transcripts")}}subscribeSocket(e,t){let i=this.sessionsBySocket.get(e);if(i||(i=new Set,this.sessionsBySocket.set(e,i)),i.has(t))return{ok:!0,refCount:this.subscriptions.get(t)?.refCount??1};i.add(t);let s=this.subscriptions.get(t);if(s)return s.refCount++,{ok:!0,refCount:s.refCount};let n=Se(t,a=>{let r=this.coalescePromptEcho(t,a);if(r&&(this.applySessionEvent(t,r),this.fanOutEvent(t,r)),a.type==="turn-completed"){let c=T(t);if(c)try{ce(c.projectId,{usd:a.costUsd,ts:a.ts})}catch(l){process.stderr.write(`[sootsim-agent] recordTurnTelemetry failed: ${l instanceof Error?l.message:String(l)}
|
|
4
|
+
`)}}});return this.subscriptions.set(t,{unsubscribe:n,refCount:1}),{ok:!0,refCount:1}}unsubscribeSocket(e,t){let i=this.sessionsBySocket.get(e);return!i||!i.has(t)?{ok:!0,refCount:0}:(i.delete(t),this.decrementSubscription(t))}decrementSubscription(e){let t=this.subscriptions.get(e);if(!t)return{ok:!0,refCount:0};if(t.refCount--,t.refCount<=0){try{t.unsubscribe()}catch{}return this.subscriptions.delete(e),{ok:!0,refCount:0}}return{ok:!0,refCount:t.refCount}}dropSessionFanout(e){let t=this.subscriptions.get(e);if(t){try{t.unsubscribe()}catch{}this.subscriptions.delete(e)}for(let i of this.sessionsBySocket.values())i.delete(e);this.clearPromptTracking(e)}normalizePromptEnvelope(e){if(e?.prompt&&typeof e.prompt=="object"){let t=e.prompt;return{text:String(t.text??""),...typeof t.displayText=="string"?{displayText:t.displayText}:{},...typeof t.inspectSummary=="string"?{inspectSummary:t.inspectSummary}:{},...typeof t.inspectTrace=="string"?{inspectTrace:t.inspectTrace}:{}}}return{text:String(e?.text??""),...typeof e?.displayText=="string"?{displayText:e.displayText}:{},...typeof e?.inspectSummary=="string"?{inspectSummary:e.inspectSummary}:{},...typeof e?.inspectTrace=="string"?{inspectTrace:e.inspectTrace}:{}}}notePromptAccepted(e,t,i){let s=Date.now(),n=this.pendingPromptEchoes.get(e)??[];n.push({sentAt:s}),this.pendingPromptEchoes.set(e,n);let a=Math.max(this.pendingTurns.get(e)??0,i?1:0)+1;this.pendingTurns.set(e,a);let r=t.displayText??t.text;return this.patchSession(e,{lastPrompt:r,status:"working",needsAttention:!1}),this.fanOutEvent(e,{type:"prompt-received",text:r,...t.inspectSummary?{inspectSummary:t.inspectSummary}:{},...t.inspectTrace?{inspectTrace:t.inspectTrace}:{},ts:s}),{ok:!0,queued:a>1,pendingTurns:a,queueDepth:Math.max(0,a-1)}}applySessionEvent(e,t){switch(t.type){case"prompt-received":case"turn-started":this.patchSession(e,{status:"working",needsAttention:!1});return;case"turn-completed":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"idle",needsAttention:!1,lastTurnFiles:t.filesTouched,currentlyEditing:void 0});return}case"approval-needed":this.patchSession(e,{status:"needs-attention",needsAttention:!0});return;case"error":{let i=this.consumeSettledTurn(e);this.patchSession(e,{status:i>0?"working":"needs-attention",needsAttention:i<=0,currentlyEditing:void 0});return}case"exited":this.clearPromptTracking(e),this.patchSession(e,{status:"ended",needsAttention:!1,wrapperPid:void 0,currentlyEditing:void 0});return;case"ready":case"turn-reasoning":case"turn-message":case"turn-plan":case"tool-call":case"file-edited":case"file-diff-delta":return}}patchSession(e,t){ue(e,t);let i=T(e);i&&this.broadcastSessionStatus(i)}coalescePromptEcho(e,t){if(t.type!=="prompt-received")return t;let i=this.pendingPromptEchoes.get(e);if(!i||i.length===0)return t;for(;i.length>0&&Date.now()-i[0].sentAt>15e3;)i.shift();return i.length===0?(this.pendingPromptEchoes.delete(e),t):(i.shift(),i.length===0?this.pendingPromptEchoes.delete(e):this.pendingPromptEchoes.set(e,i),null)}consumeSettledTurn(e){let t=Math.max(0,(this.pendingTurns.get(e)??1)-1);return t>0?this.pendingTurns.set(e,t):this.pendingTurns.delete(e),t}clearPromptTracking(e){this.pendingPromptEchoes.delete(e),this.pendingTurns.delete(e)}fanOutEvent(e,t){let i=JSON.stringify({type:"agent:event",sessionId:e,event:t});for(let[s,n]of this.sessionsBySocket)if(n.has(e)&&s.readyState===_)try{s.send(i)}catch{}}broadcastSessionStatus(e){let t=JSON.stringify({type:"agent:session-status",session:e});for(let i of this.allSockets)if(i.readyState===_)try{i.send(t)}catch{}}respond(e,t,i){if(e.readyState===_)try{e.send(JSON.stringify({id:t,result:i}))}catch{}}respondError(e,t,i,s){if(e.readyState===_)try{e.send(JSON.stringify({id:t,error:i,...s?{code:s}:{}}))}catch{}}};function Oe(o){return o==="expo"?"expo":o==="one"||o==="vxrn"?"one":"unknown"}import Be from"http";import De from"https";var W="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",xe=[{hostSuffix:"uniswap.org",headers:{origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/"},suppressBrowserUserAgent:!0}];function Le(o){let e=o.toLowerCase();for(let t of xe)if(e===t.hostSuffix||e.endsWith(`.${t.hostSuffix}`))return t}function ve(o){let e=Le(o.hostname);return{"accept-encoding":"identity",...e?.suppressBrowserUserAgent?{}:{"user-agent":W},...e?.headers}}var Ne=new Set(["host","origin","referer","user-agent","accept-encoding","cookie","connection","keep-alive","transfer-encoding","upgrade","content-length","sec-fetch-site","sec-fetch-mode","sec-fetch-dest","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform"]),Me={"access-control-allow-origin":"*","access-control-allow-methods":"GET,POST,PUT,DELETE,PATCH,OPTIONS","access-control-allow-headers":"*","access-control-expose-headers":"*","access-control-max-age":"3600"},Ue=new Set(["host","origin","referer","sec-fetch-site","sec-fetch-mode","sec-fetch-dest"]);function I(o){for(let[e,t]of Object.entries(Me))o.setHeader(e,t)}function He(o,e){let t=[],i=e;i?.code&&t.push(i.code),i?.message&&t.push(i.message),i?.cause?.code&&t.push(i.cause.code),i?.cause?.message&&t.push(i.cause.message);let n=[...new Set(t.filter(Boolean))].join(" | ")||String(e);return o.includes("stored-in-.env.local")?`${n} | upstream url still contains placeholder env values`:n}function Fe(o){let t=(Array.isArray(o)?o[0]:o)?.split(";",1)[0]?.trim().toLowerCase();return t?t.startsWith("text/")||t==="application/json"||t.endsWith("+json")||t==="application/x-www-form-urlencoded"||t==="application/xml"||t.endsWith("+xml")||t==="application/javascript"||t==="application/graphql":!1}function We(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Ne.has(i.toLowerCase())||(t[i]=Array.isArray(s)?s.join(", "):s));return Object.assign(t,e?ve(e):{"user-agent":W}),t}function je(o,e){let t={};for(let[i,s]of Object.entries(o))s&&(Ue.has(i.toLowerCase())||(t[i]=s));return t.host=e.host,t.origin=e.origin,t.referer=`${e.origin}/`,t}function be(o){return o?.startsWith("/__fetch-proxy?")||o?.startsWith("/__proxy?")||!1}function we(o){return o?!!(o.startsWith("/__app-api?")||o.startsWith("/__app-api/")):!1}async function Ae(o,e){if(o.method==="OPTIONS"){I(e),e.writeHead(204),e.end();return}let i=new URLSearchParams((o.url||"").split("?")[1]||"").get("url");if(!i){I(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("missing url param");return}let s;try{s=new URL(i)}catch{I(e),e.writeHead(400,{"Content-Type":"text/plain"}),e.end("invalid url param");return}let n=We(o.headers,s),a;if(o.method!=="GET"&&o.method!=="HEAD"){let d=[];for await(let u of o)d.push(Buffer.isBuffer(u)?u:Buffer.from(u));if(d.length>0){let u=Buffer.concat(d);a=Fe(o.headers["content-type"])?u.toString("utf8"):u}}let r;try{r=await fetch(s.href,{method:o.method,headers:n,body:a,redirect:"follow"})}catch(d){I(e),e.writeHead(502,{"Content-Type":"text/plain"}),e.end(`fetch proxy error: ${He(s.href,d)}`);return}r.headers.forEach((d,u)=>{let p=u.toLowerCase();p==="content-encoding"||p==="transfer-encoding"||p==="content-length"||p==="set-cookie"||p.startsWith("access-control-")||e.setHeader(u,d)}),I(e);let c=r.headers.getSetCookie?.()??[];c.length>0&&e.setHeader("x-sootsim-set-cookie",c.join(", ")),e.statusCode=r.status;let l=Buffer.from(await r.arrayBuffer());e.end(l)}function ke(o,e){let t=o.url||"",i="",s="";if(t.startsWith("/__app-api?")){let l=new URL(t,"http://sootsim.local");i=l.searchParams.get("path")||"",s=l.searchParams.get("origin")?.trim()||""}else if(t.startsWith("/__app-api/"))i=t.slice(10);else return!1;if(!s)return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: missing origin query param"),!0;if(o.method==="OPTIONS")return e.writeHead(204,{"Access-Control-Allow-Origin":o.headers.origin||"*","Access-Control-Allow-Methods":"GET,POST,PUT,PATCH,DELETE,OPTIONS","Access-Control-Allow-Headers":o.headers["access-control-request-headers"]||"*","Access-Control-Allow-Credentials":"true","Access-Control-Max-Age":"86400"}),e.end(),!0;let n;try{n=new URL(i,s)}catch{return e.writeHead(400,{"Content-Type":"text/plain"}),e.end("app-api: invalid origin or path"),!0}let a=n.protocol==="https:"?De:Be,r=je(o.headers,n),c=a.request({hostname:n.hostname,port:n.port||(n.protocol==="https:"?443:80),path:n.pathname+n.search,method:o.method,headers:r},l=>{let d=Object.keys(l.headers).filter(u=>{let p=u.toLowerCase();return!p.startsWith("access-control-")&&p!=="set-cookie"}).join(", ");e.writeHead(l.statusCode??502,{...l.headers,"access-control-allow-origin":o.headers.origin||"*","access-control-allow-credentials":"true","access-control-expose-headers":d}),l.pipe(e)});return c.on("error",l=>{e.statusCode=502,e.end(`app proxy error: ${l.message}`)}),o.pipe(c),!0}import{WebSocket as A,WebSocketServer as $e}from"ws";var Je="/__websocket-proxy",Ke=new Set(["host","connection","upgrade","transfer-encoding","content-length","sec-websocket-accept","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version"]);function w(o,e,t){try{o.write(`HTTP/1.1 ${e} ${t}\r
|
|
5
5
|
Connection: close\r
|
|
6
6
|
Content-Type: text/plain\r
|
|
7
7
|
Content-Length: ${t.length}\r
|
|
8
8
|
\r
|
|
9
|
-
${t}`)}catch{}o.destroy()}function Ve(o){let e=o.headers.origin,t=o.headers.host;if(!e||!t)return!1;try{return new URL(e).host===t}catch{return!1}}function Ge(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,a]of Object.entries(i))a!=null&&(Ke.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function qe(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function ze(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function
|
|
9
|
+
${t}`)}catch{}o.destroy()}function Ve(o){let e=o.headers.origin,t=o.headers.host;if(!e||!t)return!1;try{return new URL(e).host===t}catch{return!1}}function Ge(o){if(!o)return{};let e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=JSON.parse(Buffer.from(t,"base64").toString("utf8"));if(!i||typeof i!="object"||Array.isArray(i))return{};let s={};for(let[n,a]of Object.entries(i))a!=null&&(Ke.has(n.toLowerCase())||(s[n]=Array.isArray(a)?a.join(", "):String(a)));return s}function qe(o){let e=new URL(o.href);return e.protocol=o.protocol==="wss:"?"https:":"http:",e.origin}function ze(o){let e=o.headers["sec-websocket-protocol"];return(Array.isArray(e)?e.join(","):e||"").split(",").map(i=>i.trim()).filter(Boolean)}function x(o,e,t){if(!(o.readyState===A.CLOSED||o.readyState===A.CLOSING))try{o.close(e,t)}catch{o.terminate()}}function Xe(o,e){let t=!1,i=(s,n,a,r)=>{t||(t=!0,x(n,a,r.toString()),s.readyState===A.OPEN&&x(s,a,r.toString()))};o.on("message",(s,n)=>{e.readyState===A.OPEN&&e.send(s,{binary:n})}),e.on("message",(s,n)=>{o.readyState===A.OPEN&&o.send(s,{binary:n})}),o.on("close",(s,n)=>i(o,e,s,n)),e.on("close",(s,n)=>i(e,o,s,n)),o.on("error",()=>x(e,1011,"proxy client error")),e.on("error",()=>x(o,1011,"upstream websocket error"))}function Ye(o,e,t){let i={...t};return Object.keys(i).some(s=>s.toLowerCase()==="origin")||(i.origin=qe(o)),new A(o.href,e,{headers:i})}function Ze(o){if(!o)return!1;try{return new URL(o,"http://localhost").pathname===Je}catch{return!1}}function Te(o,e,t){if(!Ze(o.url))return!1;if(!Ve(o))return w(e,403,"forbidden websocket proxy origin"),!0;let i,s;try{let c=new URL(o.url||"/","http://localhost"),l=c.searchParams.get("url");if(!l)return w(e,400,"missing websocket proxy url"),!0;if(i=new URL(l),i.protocol!=="ws:"&&i.protocol!=="wss:")return w(e,400,"invalid websocket proxy protocol"),!0;s=Ge(c.searchParams.get("headers"))}catch{return w(e,400,"invalid websocket proxy request"),!0}let n=ze(o),a=Ye(i,n,s),r=!1;return e.once("close",()=>{r||a.terminate()}),a.once("open",()=>{if(r)return;r=!0;let c=a.protocol;new $e({noServer:!0,clientTracking:!1,handleProtocols(d){return c||d.values().next().value||!1}}).handleUpgrade(o,e,t,d=>{Xe(d,a)})}),a.once("error",()=>{r||(r=!0,w(e,502,"upstream websocket error"))}),a.once("close",()=>{r||(r=!0,w(e,502,"upstream websocket closed"))}),!0}var it=new Set(["tap","keyboard"]),rt=2e3,nt=1e3;function st(o){return!o||typeof o.type!="string"?!1:o.acquireLock===!0?!0:o.readOnly===!0?!1:it.has(o.type)}var Ce=5e3,ot=3600*1e3,at="SOOTSIM_RUNTIME_UPDATE_INTERVAL_MS",ct={".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 Ie(o,e,t){let i;try{let c=N();i=JSON.stringify(c)}catch{i="{}"}let s=e>0?`window.__sootsimBridgePort=${e};`:"",n=t?`window.__sootsimSootbeanOrigin=${JSON.stringify(t)};`:"",a=`<script>window.__sootsimSharedConfig=${i};`+s+n+`window.__sootsimCliVersion=${JSON.stringify(ee())};</script>`,r=o.toString("utf8");return r.includes("<head>")?r.replace("<head>",`<head>${a}`):r.includes("</head>")?r.replace("</head>",a+"</head>"):r.includes("</body>")?r.replace("</body>",a+"</body>"):a+r}function Ee(o){typeof o=="object"&&o!==null&&"unref"in o&&o.unref()}var L=class o{port;openUrlHandler;httpServer=null;wss=null;nextCommandId=1;nextSimNumber=161;sims=new Map;primarySimId=null;pendingCommands=new Map;cliBySentId=new Map;cliSimBySocket=new Map;cliLastCommandAt=new Map;cliIdentityKeyBySocket=new Map;cliLabelBySocket=new Map;restorableSims=new Map;nextCliFallbackId=1;cliIdleTimer=null;agentHost;static CLI_IDLE_TIMEOUT_MS=6e4;static CLI_LEASE_TTL_MS=6e5;static USER_ACTIVE_LEASE_TTL_MS=8e3;static USER_BOOT_LEASE_TTL_MS=6e4;static SIM_RECONNECT_TTL_MS=3e4;static SIM_IDLE_REAP_TTL_MS=30*6e4;static AUTOMATION_SIM_IDLE_REAP_TTL_MS=10*6e4;static MAX_CONCURRENT_AUTOMATION_SIMS=6;static AUTOMATION_SIM_ACTIVE_GRACE_MS=6e4;preferredPort;portFallbackCount;simIdleReapTtlMs;automationSimIdleReapTtlMs;maxConcurrentAutomationSims;automationSimActiveGraceMs;shouldWriteLockfile;shouldWriteDevLockfile;sootbeanOrigin=null;effectivePort=0;startedAt=0;heartbeatTimer=null;devHeartbeatTimer=null;wsHeartbeatTimer=null;wsIsAlive=new WeakMap;static WS_HEARTBEAT_INTERVAL_MS=3e4;runtimeUpdateTimer=null;runtimeUpdateInFlight=null;activeRuntimeVersion=null;activeRuntimeDirPath=null;scanCache=null;scanCacheAt=0;inflightScan=null;static SCAN_FRESH_MS=2e3;constructor(e={}){this.preferredPort=e.port||7668,this.port=this.preferredPort,this.shouldWriteLockfile=e.writeLockfile===!0,this.shouldWriteDevLockfile=e.writeDevLockfile===!0,this.portFallbackCount=Math.max(1,e.portFallbackCount??10),this.openUrlHandler=e.openUrl,this.agentHost=new O({getExcludePorts:e.agentScanExcludes}),this.sootbeanOrigin=e.sootbeanOrigin?.replace(/\/$/,"")||null,this.simIdleReapTtlMs=e.simIdleReapTtlMs??o.SIM_IDLE_REAP_TTL_MS,this.automationSimIdleReapTtlMs=e.automationSimIdleReapTtlMs??o.AUTOMATION_SIM_IDLE_REAP_TTL_MS,this.maxConcurrentAutomationSims=e.maxConcurrentAutomationSims??o.MAX_CONCURRENT_AUTOMATION_SIMS,this.automationSimActiveGraceMs=e.automationSimActiveGraceMs??o.AUTOMATION_SIM_ACTIVE_GRACE_MS}getAgentHost(){return this.agentHost}reapIdleSimsForTest(e=Date.now()){this.reapIdleSims(e)}start(e){this.startAsync(e)}async startAsync(e){if(this.httpServer||this.wss)return this.effectivePort;this.refreshActiveRuntime();for(let t=0;t<this.portFallbackCount;t++){let i=this.preferredPort+t;try{return await this.bindOnce(i,e?.silent===!0),this.effectivePort=i,this.port=i,this.startedAt=Date.now(),t>0&&!e?.silent&&process.stderr.write(`ws bridge bound to port ${i} (preferred ${this.preferredPort} was taken)
|
|
10
10
|
`),this.afterBind(),i}catch(s){if(s?.code!=="EADDRINUSE")throw s;e?.silent||process.stderr.write(`ws bridge port ${i} already in use, trying ${i+1}
|
|
11
11
|
`)}}throw new Error(`could not bind ws bridge after ${this.portFallbackCount} attempts starting at ${this.preferredPort}`)}bindOnce(e,t){return new Promise((i,s)=>{let n=et((c,l)=>this.handleHttpRequest(c,l)),a=!1,r=c=>{if(!a){a=!0;try{n.close()}catch{}this.httpServer=null,this.wss=null,s(c)}};n.once("error",r),n.listen(e,"127.0.0.1",()=>{a||(a=!0,n.removeListener("error",r),n.on("error",c=>{process.stderr.write(`ws bridge http error: ${String(c)}
|
|
12
|
-
`)}),this.httpServer=n,this.wss=new tt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,l,d)=>{
|
|
12
|
+
`)}),this.httpServer=n,this.wss=new tt({noServer:!0}),this.wireWebSocketServer(),n.on("upgrade",(c,l,d)=>{Te(c,l,d)||this.wss?.handleUpgrade(c,l,d,u=>{this.wss?.emit("connection",u,c)})}),i())})})}wireWebSocketServer(){this.wss&&this.wss.on("connection",(e,t)=>{let i=t.headers.origin,s=i?"sim":"cli",n=null;if(e.on("error",()=>{}),this.wsIsAlive.set(e,!0),e.on("pong",()=>{this.wsIsAlive.set(e,!0)}),this.agentHost.registerSocket(e),s==="sim")n={id:this.allocateSimId(),ws:e,origin:i,connectedAt:Date.now(),lastSeenAt:Date.now(),lastActiveAt:0,recentActions:[]},this.sims.set(n.id,n),this.shouldPromoteSim(n)&&(this.primarySimId=n.id),this.broadcastSimAssignments(),this.broadcastSimClientStates();else{let a=`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,a)}e.on("message",a=>{let r;try{r=JSON.parse(a.toString())}catch{return}if(!(!r||typeof r!="object")){if(typeof r.type=="string"&&r.type.startsWith("agent:")){this.agentHost.handleMessage(e,r);return}if(r.type==="runtime:list"){let c=M(),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(!M().includes(c)){try{e.send(JSON.stringify({type:"runtime:use:error",id:r.id,error:`runtime ${c||"(missing)"} is not installed`}))}catch{}return}let d=this.setActiveRuntime(c);try{e.send(JSON.stringify({type:"runtime:use:ok",id:r.id,version:d.version,runtimeDir:d.runtimeDir}))}catch{}return}if(r.type==="runtime:get"){let c=this.getActiveRuntime();try{e.send(JSON.stringify({type:"runtime:get:ok",id:r.id,active:c.version,activeRuntimeDir:c.runtimeDir}))}catch{}return}if(s==="sim"){if(n&&(n.lastSeenAt=Date.now()),r.type==="bridge:register"&&n){let d=r,u=this.tryRestoreSimId(n,d.simId);n.url=d.url,n.title=d.title,n.userAgent=d.userAgent,typeof d.kind=="string"&&d.kind.trim()&&(n.kind=d.kind.trim()),d.meta&&typeof d.meta=="object"&&(n.meta=d.meta);let p=this.primarySimId!==n.id&&this.shouldPromoteSim(n);p&&(this.primarySimId=n.id),(u||p)&&(this.broadcastSimAssignments(),this.broadcastSimClientStates());return}if(r.type==="bridge:user-focus-state"&&n){let d=r;this.updateUserFocusLease(n,d);return}if(r.type==="bridge:user-interact"&&n){this.updateUserActivity(n);return}if(r.type==="bridge:write-shared-config"){let d=r.patch&&typeof r.patch=="object"?r.patch:null;if(!d)return;let u;try{u=j(d)}catch(m){process.stderr.write(`sootsim: bridge:write-shared-config failed: ${m instanceof Error?m.message:String(m)}
|
|
13
13
|
`);return}let p=JSON.stringify({type:"bridge:shared-config-changed",config:u});for(let m of this.sims.values())if(m.ws.readyState===h.OPEN)try{m.ws.send(p)}catch{}return}if(r.type==="bridge:open-path"){let d=typeof r.path=="string"?r.path:"",u=typeof r.line=="number"&&Number.isFinite(r.line)?r.line:void 0,p=typeof r.column=="number"&&Number.isFinite(r.column)?r.column:void 0;d&&this.openPathInEditor(d,u,p);return}if(r.type==="bridge:boot-clients"&&n){let d=[];for(let[p,m]of this.cliSimBySocket)m===n.id&&d.push(p);for(let p of d){this.cliSimBySocket.delete(p);try{p.close(1e3,"booted by sim")}catch{}}let u=!!n.cliLease;n.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:Date.now()+o.USER_BOOT_LEASE_TTL_MS},process.stderr.write(`sootsim booted ${d.length} cli client(s)${u?" (overrode prior lease)":""}; held sim for user [${n.id}]
|
|
14
14
|
`),this.recordSimAction(n.id,"sim booted cli clients"),this.broadcastSimClientStates();return}let c=this.pendingCommands.get(r.id);if(c){this.pendingCommands.delete(r.id),r.error?c.reject(new Error(r.error)):c.resolve(r.result);return}let l=this.cliBySentId.get(r.id);if(l&&(this.cliBySentId.delete(r.id),l.ws.readyState===h.OPEN)){let d=this.getOtherCliIdentityCount(l.ws,l.simId),u=d>0?{...r,id:l.originalId,_otherCliCount:d}:{...r,id:l.originalId};l.ws.send(JSON.stringify(u))}return}(async()=>{this.cliLastCommandAt.set(e,Date.now());try{if(r.type==="bridge:bye"){let p=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[m,f]of this.cliBySentId)f.ws===e&&this.cliBySentId.delete(m);p&&this.broadcastSimClientStates();return}if(r.type==="bridge:hello"){let p=typeof r.cliIdentityKey=="string"&&r.cliIdentityKey.trim()?r.cliIdentityKey.trim():this.cliIdentityKeyBySocket.get(e)||`ws-${this.nextCliFallbackId++}`;this.cliIdentityKeyBySocket.set(e,p),typeof r.cliLabel=="string"&&r.cliLabel.trim()&&this.cliLabelBySocket.set(e,r.cliLabel.trim()),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{cliIdentityKey:p,leaseTtlMs:o.CLI_LEASE_TTL_MS,leasing:!0}}));return}if(r.type==="bridge:list-sims"){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:this.listSims()}));return}if(r.type==="bridge:open"){if(typeof r.url!="string"||!r.url)throw new Error("bridge:open requires a url");await this.openUrl(r.url,{newWindow:r.newWindow===!0}),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{ok:!0,url:r.url}}));return}if(r.type==="bridge:claim"){let p=await this.waitForSim(r.simId),m=this.tryAcquireLease(e,p,{force:r.force===!0});if(!m.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${p.id} is locked by another cli`,_locked:m.lock}));return}this.setCliSimTarget(e,p.id),this.recordSimAction(p.id,m.bootedCount>0?`cli force-claimed sim (booted ${m.bootedCount})`:"cli claimed sim"),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{simId:p.id,lockedBy:m.lease.cliIdentityKey,lockExpiresAt:m.lease.expiresAt,bootedCount:m.bootedCount}}));return}let c=await this.waitForSim(r.simId);if(st(r)){let p=this.tryAcquireLease(e,c);if(!p.granted){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:`sim ${c.id} is locked by another cli \u2014 use \`sootsim claim ${c.id} --force\` or \`sootsim open --new\``,_locked:p.lock}));return}}else this.ensureCliIdentityKey(e);this.setCliSimTarget(e,c.id),this.recordSimAction(c.id,this.describeForwardedCommand(r));let l=this.nextCommandId++;this.cliBySentId.set(l,{simId:c.id,ws:e,originalId:r.id});let{simId:d,...u}=r;if(c.ws.send(JSON.stringify({...u,id:l})),u.type==="close"){this.cliBySentId.delete(l),e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,result:{requested:!0,simId:c.id}}));let p=c.ws,m=setTimeout(()=>{this.closeSimSocketFromHost(p)},rt);Ee(m)}}catch(c){e.readyState===h.OPEN&&e.send(JSON.stringify({id:r.id,error:c instanceof Error?c.message:String(c)}))}})()}}),e.on("close",()=>{if(this.agentHost.unregisterSocket(e),s==="sim"&&n){this.rememberDisconnectedSim(n),this.primarySimId===n.id&&(this.primarySimId=this.getOpenSim()?.id??null);for(let[a,r]of this.pendingCommands)r.simId===n.id&&(r.reject(new Error("sim disconnected")),this.pendingCommands.delete(a));for(let[a,r]of this.cliBySentId)r.simId===n.id&&(r.ws.readyState===h.OPEN&&r.ws.send(JSON.stringify({id:r.originalId,error:"sim disconnected before responding"})),this.cliBySentId.delete(a));this.broadcastSimAssignments(),this.broadcastSimClientStates()}else if(s==="cli"){let a=this.cliSimBySocket.delete(e);this.cliLastCommandAt.delete(e),this.cliIdentityKeyBySocket.delete(e),this.cliLabelBySocket.delete(e);for(let[r,c]of this.cliBySentId)c.ws===e&&this.cliBySentId.delete(r);a&&this.broadcastSimClientStates()}})})}afterBind(){if(process.stderr.write(`ws bridge listening on port ${this.port}
|
|
15
|
-
`),this.cliIdleTimer=setInterval(()=>this.sweepIdleCliClients(),3e4),this.cliIdleTimer.unref(),this.wsHeartbeatTimer=setInterval(()=>this.sweepDeadWebSockets(),o.WS_HEARTBEAT_INTERVAL_MS),this.wsHeartbeatTimer.unref(),this.shouldWriteLockfile){try{if(
|
|
16
|
-
`),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},
|
|
15
|
+
`),this.cliIdleTimer=setInterval(()=>this.sweepIdleCliClients(),3e4),this.cliIdleTimer.unref(),this.wsHeartbeatTimer=setInterval(()=>this.sweepDeadWebSockets(),o.WS_HEARTBEAT_INTERVAL_MS),this.wsHeartbeatTimer.unref(),this.shouldWriteLockfile){try{if(E(),!X(this.buildLockfileSnapshot()))throw new Error("another sootsim daemon wrote the lockfile during startup \u2014 aborting")}catch(e){throw process.stderr.write(`ws bridge failed to claim daemon lockfile: ${String(e)}
|
|
16
|
+
`),e}this.heartbeatTimer=setInterval(()=>{try{this.writeLockfileSnapshot()}catch{}},Ce),this.heartbeatTimer.unref(),this.startRuntimeUpdater()}if(this.shouldWriteDevLockfile){try{this.writeDevLockfileSnapshot()}catch(e){process.stderr.write(`ws bridge failed to write dev bridge lockfile: ${String(e)}
|
|
17
|
+
`)}this.devHeartbeatTimer=setInterval(()=>{try{this.writeDevLockfileSnapshot()}catch{}},Ce),this.devHeartbeatTimer.unref()}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}}buildDevLockfileSnapshot(){return{schema:1,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,cwd:process.cwd(),startedAt:this.startedAt,heartbeatAt:Date.now(),source:"vite-dev"}}writeLockfileSnapshot(){q(this.buildLockfileSnapshot())}writeDevLockfileSnapshot(){z(this.buildDevLockfileSnapshot())}refreshActiveRuntime(){this.activeRuntimeVersion=$(),this.activeRuntimeDirPath=K()}runServerScan(){if(this.inflightScan)return this.inflightScan;let e=this.effectivePort>0?[this.effectivePort]:[];return this.inflightScan=P({excludePorts:e,buildIconProxyUrl:t=>`/__bundle-proxy?url=${encodeURIComponent(t)}`}).then(t=>(this.scanCache=t,this.scanCacheAt=Date.now(),t)).catch(t=>{let i=t instanceof Error?t.message:String(t);return console.error("[sootsim] /__server-scan failed:",i),this.scanCache??[]}).finally(()=>{this.inflightScan=null}),this.inflightScan}handleServerScan(e){let t=s=>{e.writeHead(200,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),e.end(JSON.stringify(s))},i=Date.now()-this.scanCacheAt;if(this.scanCache&&i<o.SCAN_FRESH_MS){t(this.scanCache);return}if(this.scanCache){t(this.scanCache),this.runServerScan().catch(()=>{});return}this.runServerScan().then(s=>t(s))}resolveRuntimeUpdateIntervalMs(){let e=Number(process.env[at]);return Number.isFinite(e)&&e>0?Math.max(100,Math.round(e)):ot}startRuntimeUpdater(){if(!this.shouldWriteLockfile||this.runtimeUpdateTimer)return;this.runRuntimeUpdate("startup");let e=this.resolveRuntimeUpdateIntervalMs();this.runtimeUpdateTimer=setInterval(()=>{this.runRuntimeUpdate("periodic")},e),this.runtimeUpdateTimer.unref()}runRuntimeUpdate(e){return this.runtimeUpdateInFlight?this.runtimeUpdateInFlight:(this.runtimeUpdateInFlight=(async()=>{try{e==="startup"&&process.stderr.write(`sootsim: checking for runtime updates\u2026
|
|
17
18
|
`);let t=await ne();if(!t.updated||!t.latestVersion){e==="startup"&&process.stderr.write(`sootsim: runtime ${this.activeRuntimeVersion??"(none)"} is current
|
|
18
19
|
`);return}let i=this.setActiveRuntime(t.latestVersion);process.stderr.write(`sootsim runtime updated to ${i.version} (${e})
|
|
19
20
|
`)}catch(t){process.stderr.write(`sootsim runtime update failed (${e}): ${t instanceof Error?t.message:String(t)}
|
|
20
21
|
`)}finally{if(this.runtimeUpdateInFlight=null,e==="startup"&&this.bootstrapping){if(this.bootstrapping=!1,this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}process.stderr.write(`sootsim: ready
|
|
21
|
-
`)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(V(e),this.refreshActiveRuntime(),this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}let t=JSON.stringify({type:"runtime:changed",version:e,runtimeDir:this.activeRuntimeDirPath});for(let i of this.sims.values())if(i.ws.readyState===h.OPEN)try{i.ws.send(t)}catch{}return{version:e,runtimeDir:this.activeRuntimeDirPath}}getActiveRuntime(){return{version:this.activeRuntimeVersion,runtimeDir:this.activeRuntimeDirPath}}removeLockfile(){if(this.shouldWriteLockfile)try{U()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy","credentialless"),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),ve(e.url)){Ae(e,t);return}if(we(e.url)&&ke(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let m=await fetch(d.toString(),{redirect:"follow"}),f={},S=m.headers.get("content-type");if(S&&(f["Content-Type"]=S),f["Cache-Control"]="no-store",t.writeHead(m.status,f),!m.body){t.end();return}let g=m.body.getReader();for(;;){let{done:b,value:v}=await g.read();if(b)break;t.write(Buffer.from(v))}t.end()}catch(m){t.writeHead(502,{"Content-Type":"text/plain"}),t.end(`bundle-proxy: upstream fetch failed: ${m instanceof Error?m.message:String(m)}`)}})();return}if(s.pathname==="/__server-scan"){this.handleServerScan(t);return}if(s.pathname==="/healthz"){t.writeHead(200,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify({ok:!0,pid:process.pid,platform:process.platform,bridgePort:this.effectivePort,runtimePort:this.effectivePort,activeRuntime:this.activeRuntimeVersion,startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(N())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of a.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=y.resolve(n,"."+a),c=n.endsWith(y.sep)?n:n+y.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}k.realpath(r,(l,d)=>{let u=l?r:d,p=u.endsWith(y.sep)?u:u+y.sep;if(!l){let m=(()=>{try{let f=k.realpathSync(n);return f.endsWith(y.sep)?f:f+y.sep}catch{return c}})();if(!p.startsWith(m)&&u+y.sep!==m){t.writeHead(403),t.end("forbidden");return}}k.stat(u,(m,f)=>{if(m||!f?.isFile()){let v=y.extname(a).toLowerCase();if(v&&v!==".html"){t.writeHead(404),t.end("not found");return}if(a.startsWith("/__")||a.startsWith("/api/")||a==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let M=y.join(n,"index.html");k.readFile(M,(Pe,Re)=>{if(Pe){t.writeHead(404),t.end("not found");return}if(t.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),i==="HEAD"){t.end();return}t.end(Te(Re,this.effectivePort,this.sootbeanOrigin))});return}let S=y.extname(u).toLowerCase(),g=dt[S]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(S===".html"){k.readFile(u,(v,M)=>{if(v){try{t.end()}catch{}return}t.end(Te(M,this.effectivePort,this.sootbeanOrigin))});return}let b=k.createReadStream(u);b.pipe(t),b.on("error",()=>{try{t.end()}catch{}})})})}sweepIdleCliClients(){let e=Date.now(),t=!1;for(let[i,s]of this.cliSimBySocket){let n=this.cliLastCommandAt.get(i)??0;if(!(e-n<o.CLI_IDLE_TIMEOUT_MS)){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[a,r]of this.cliBySentId)r.ws===i&&this.cliBySentId.delete(a);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}isAutomationSim(e){return e.meta?.sootsimHostDriver==="playwright"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n);if(c&&this.automationSimOwnerAlive(n))continue;let l=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=l){this.closeSimSocketFromHost(n.ws);continue}c&&i.push({sim:n,idleMs:r})}let s=this.maxConcurrentAutomationSims;if(i.length>s){i.sort((n,a)=>a.idleMs-n.idleMs);for(let{sim:n,idleMs:a}of i.slice(0,i.length-s))a<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(n.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==h.OPEN)continue;if(this.wsIsAlive.get(e)===!1){try{e.terminate()}catch{}continue}this.wsIsAlive.set(e,!1);try{e.ping()}catch{try{e.terminate()}catch{}}}}closeSimSocketFromHost(e){if(e.readyState!==h.OPEN)return;try{e.close(te,ie)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},nt);Ee(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let a=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,a=(c,l)=>new Promise(d=>{try{let u=Qe(c,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await a(c[0],[...c.slice(1),"-g",n]))return}await a("cursor",["-g",n])||await a("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await re(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{U()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=h.CLOSED}let i=this.getActiveLease(e);return{id:e.id,origin:e.origin,url:e.url,title:e.title,userAgent:e.userAgent,connectedAt:e.connectedAt,lastSeenAt:e.lastSeenAt,lastActiveAt:e.lastActiveAt||void 0,isPrimary:e.id===this.primarySimId,readyState:t===h.OPEN?"open":t===h.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),a=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-a)},bootedCount:0};if(r&&!c&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,a=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===a||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=a,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let s=this.sims.get(e);return s?.ws.readyState===h.OPEN?s:null}let t=this.primarySimId!=null?this.sims.get(this.primarySimId):null;if(t?.ws.readyState===h.OPEN&&t.url)return t;let i=null;for(let s of this.sims.values())if(s.ws.readyState===h.OPEN){if(s.url)return s;i??=s}return t?.ws.readyState===h.OPEN?t:i}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let n=0;n<i;n++){let a=this.getOpenSim(e);if(a)return a;await new Promise(r=>setTimeout(r,s))}throw new Error(e?`no sim connected with id ${e}`:"no sim connected")}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===h.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===h.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==h.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let a=Date.now();n.lastActiveAt=a,n.recentActions=[{label:s,at:a},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==h.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,a]of this.cliSimBySocket){if(a!==t||n.readyState!==h.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===h.OPEN)return!1;let n=this.getRestorableSimState(i),a=e.id;this.sims.delete(a),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===a&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===a&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id)}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function Ie(){let o=process.env.XPC_SERVICE_NAME||"";return!!(o.includes("dev.sootsim.daemon")||o.includes("dev.sootsim.server")||process.env.INVOCATION_ID)}async function $t(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
|
|
22
|
-
sootsim
|
|
22
|
+
`)}}})(),this.runtimeUpdateInFlight)}setActiveRuntime(e){if(J(e),this.refreshActiveRuntime(),this.shouldWriteLockfile&&this.httpServer)try{this.writeLockfileSnapshot()}catch{}let t=JSON.stringify({type:"runtime:changed",version:e,runtimeDir:this.activeRuntimeDirPath});for(let i of this.sims.values())if(i.ws.readyState===h.OPEN)try{i.ws.send(t)}catch{}return{version:e,runtimeDir:this.activeRuntimeDirPath}}getActiveRuntime(){return{version:this.activeRuntimeVersion,runtimeDir:this.activeRuntimeDirPath}}removeLockfile(){if(this.shouldWriteLockfile)try{U()}catch{}}handleHttpRequest(e,t){if(t.setHeader("Cross-Origin-Opener-Policy","same-origin"),t.setHeader("Cross-Origin-Embedder-Policy","credentialless"),t.setHeader("Cross-Origin-Resource-Policy","cross-origin"),t.setHeader("Document-Policy","js-profiling"),be(e.url)){Ae(e,t);return}if(we(e.url)&&ke(e,t))return;let i=(e.method||"GET").toUpperCase();if(i!=="GET"&&i!=="HEAD"){t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed");return}let s=new URL(e.url||"/","http://localhost");if(s.pathname==="/__bundle-proxy"){let l=s.searchParams.get("url");if(!l){t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: missing url query param");return}let d;try{d=new URL(l)}catch{t.writeHead(400,{"Content-Type":"text/plain"}),t.end("bundle-proxy: invalid url");return}let u=d.hostname;if(!(u==="localhost"||u==="127.0.0.1"||u==="::1"||u.endsWith(".localhost"))){t.writeHead(403,{"Content-Type":"text/plain"}),t.end("bundle-proxy: only loopback targets allowed");return}(async()=>{try{let m=await fetch(d.toString(),{redirect:"follow"}),f={},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,bridgeSource:this.shouldWriteDevLockfile?"vite-dev":this.shouldWriteLockfile?"daemon":"embedded",startedAt:this.startedAt,uptimeMs:this.startedAt>0?Date.now()-this.startedAt:0}));return}if(s.pathname==="/__sootsim/shared-config"){if(t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Cache-Control","no-store"),i==="GET"||i==="HEAD"){let l="{}";try{l=JSON.stringify(N())}catch{}t.writeHead(200,{"Content-Type":"application/json"}),i==="HEAD"?t.end():t.end(l);return}t.writeHead(405,{Allow:"GET, HEAD"}),t.end("method not allowed (use the bridge over WS for writes)");return}this.refreshActiveRuntime();let n=this.activeRuntimeDirPath;if(!n){t.writeHead(503,{"Content-Type":"text/plain; charset=utf-8"}),t.end("sootsim: no active runtime installed. run `sootsim runtime install` to fetch one.");return}let a=s.pathname;if(a==="/runtime"||a==="/runtime/"?a="/":a.startsWith("/runtime/")?a=a.slice(8):a==="/sootsim"||a==="/sootsim/"?a="/":a.startsWith("/sootsim/")&&(a=a.slice(8)),(a===""||a==="/")&&(a="/index.html"),a.includes("\0")){t.writeHead(400),t.end("bad request");return}if(process.platform!=="win32"&&a.includes("\\")){t.writeHead(400),t.end("bad request");return}for(let l of a.split("/"))if(l===".."){t.writeHead(403),t.end("forbidden");return}let r=S.resolve(n,"."+a),c=n.endsWith(S.sep)?n:n+S.sep;if(!r.startsWith(c)&&r!==n){t.writeHead(403),t.end("forbidden");return}k.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=k.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}}k.stat(u,(m,f)=>{if(m||!f?.isFile()){let b=S.extname(a).toLowerCase();if(b&&b!==".html"){t.writeHead(404),t.end("not found");return}if(a.startsWith("/__")||a.startsWith("/api/")||a==="/api"){t.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),t.end("not found");return}let D=S.join(n,"index.html");k.readFile(D,(Pe,Re)=>{if(Pe){t.writeHead(404),t.end("not found");return}if(t.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store"}),i==="HEAD"){t.end();return}t.end(Ie(Re,this.effectivePort,this.sootbeanOrigin))});return}let y=S.extname(u).toLowerCase(),g=ct[y]||"application/octet-stream";if(t.writeHead(200,{"Content-Type":g,"Cache-Control":"no-store"}),i==="HEAD"){t.end();return}if(y===".html"){k.readFile(u,(b,D)=>{if(b){try{t.end()}catch{}return}t.end(Ie(D,this.effectivePort,this.sootbeanOrigin))});return}let v=k.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<o.CLI_IDLE_TIMEOUT_MS)){this.cliSimBySocket.delete(i),this.cliLastCommandAt.delete(i);for(let[a,r]of this.cliBySentId)r.ws===i&&this.cliBySentId.delete(a);try{i.close(1e3,"idle timeout")}catch{}t=!0}}t&&this.broadcastSimClientStates(),this.sweepRestorableSims(e),this.reapIdleSims(e)}isAutomationSim(e){return e.meta?.sootsimHostDriver==="playwright"}automationSimOwnerAlive(e){let t=Number(e.meta?.sootsimHostPid);if(!Number.isInteger(t)||t<=1||t===process.pid)return!1;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}reapIdleSims(e=Date.now()){let t=new Set(this.cliSimBySocket.values()),i=[];for(let n of this.sims.values()){if(n.id===this.primarySimId||t.has(n.id)||this.getActiveLease(n))continue;let a=Math.max(n.lastActiveAt,n.connectedAt),r=e-a,c=this.isAutomationSim(n);if(c&&this.automationSimOwnerAlive(n))continue;let l=c?this.automationSimIdleReapTtlMs:this.simIdleReapTtlMs;if(r>=l){this.closeSimSocketFromHost(n.ws);continue}c&&i.push({sim:n,idleMs:r})}let s=this.maxConcurrentAutomationSims;if(i.length>s){i.sort((n,a)=>a.idleMs-n.idleMs);for(let{sim:n,idleMs:a}of i.slice(0,i.length-s))a<this.automationSimActiveGraceMs||this.closeSimSocketFromHost(n.ws)}}sweepDeadWebSockets(){if(this.wss)for(let e of this.wss.clients){if(e.readyState!==h.OPEN)continue;if(this.wsIsAlive.get(e)===!1){try{e.terminate()}catch{}continue}this.wsIsAlive.set(e,!1);try{e.ping()}catch{try{e.terminate()}catch{}}}}closeSimSocketFromHost(e){if(e.readyState!==h.OPEN)return;try{e.close(te,ie)}catch{try{e.terminate()}catch{}return}let t=setTimeout(()=>{if(e.readyState!==h.CLOSED)try{e.terminate()}catch{}},nt);Ee(t)}listSims(){return Array.from(this.sims.values()).sort((e,t)=>e.id===this.primarySimId?-1:t.id===this.primarySimId?1:e.connectedAt-t.connectedAt).map(e=>this.describeSim(e))}async sendCommand(e){let t=await this.waitForSim(e.simId),i=this.nextCommandId++;return new Promise((s,n)=>{let a=setTimeout(()=>{this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(new Error("command timed out after 30s"))},3e4);this.pendingCommands.set(i,{simId:t.id,resolve:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),s(l)},reject:l=>{clearTimeout(a),this.pendingCommands.delete(i),this.broadcastSimClientStates(),n(l)}}),this.broadcastSimClientStates();let{simId:r,...c}=e;t.ws.send(JSON.stringify({...c,id:i}))})}async evaluate(e,t){return this.sendCommand({type:"evaluate",code:e,simId:t})}async focusSim(e){return this.sendCommand({type:"focus",simId:e})}async closeSim(e){return this.sendCommand({type:"close",simId:e})}async openPathInEditor(e,t,i){let s=t!=null?`:${t}${i!=null?`:${i}`:""}`:"",n=`${e}${s}`,a=(c,l)=>new Promise(d=>{try{let u=Qe(c,l,{detached:!0,stdio:"ignore"}),p=!1;u.on("error",()=>{p||(p=!0,d(!1))}),u.on("spawn",()=>{p||(p=!0,u.unref(),d(!0))})}catch{d(!1)}}),r=process.env.REACT_EDITOR||process.env.EDITOR;if(r){let c=r.split(" ").filter(Boolean);if(c.length&&await a(c[0],[...c.slice(1),"-g",n]))return}await a("cursor",["-g",n])||await a("code",["-g",n])||await this.openUrl(e)}async openUrl(e,t={}){if(this.openUrlHandler){await this.openUrlHandler(e,t);return}await re(e,t)}async close(){if(this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.devHeartbeatTimer&&(clearInterval(this.devHeartbeatTimer),this.devHeartbeatTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null),this.shouldWriteLockfile)try{U()}catch{}if(this.shouldWriteDevLockfile)try{Y()}catch{}this.effectivePort=0,this.startedAt=0,this.agentHost.close();for(let[i,s]of this.pendingCommands)s.reject(new Error("server closing")),this.pendingCommands.delete(i);for(let i of this.sims.values())i.ws.close();this.sims.clear(),this.primarySimId=null;let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}describeSim(e){let t;try{t=e.ws.readyState}catch{t=h.CLOSED}let i=this.getActiveLease(e);return{id:e.id,origin:e.origin,url:e.url,title:e.title,userAgent:e.userAgent,connectedAt:e.connectedAt,lastSeenAt:e.lastSeenAt,lastActiveAt:e.lastActiveAt||void 0,isPrimary:e.id===this.primarySimId,readyState:t===h.OPEN?"open":t===h.CLOSING?"closing":"closed",attachedCliCount:this.getAttachedCliCount(e.id),lockedBy:i?i.cliLabel||i.cliIdentityKey:void 0,lockedByKind:i?i.kind:void 0,lockExpiresAt:i?i.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused,kind:e.kind,meta:e.meta}}getActiveLease(e){let t=e.cliLease;return t?Date.now()>=t.expiresAt?(e.cliLease=void 0,null):t:null}tryAcquireLease(e,t,i={}){let s=this.cliIdentityKeyBySocket.get(e)??(()=>{let u=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,u),u})(),n=this.cliLabelBySocket.get(e),a=Date.now(),r=this.getActiveLease(t),c=r&&r.cliIdentityKey===s,l=0;if(r&&!c&&!i.force)return{granted:!1,lease:r,lock:{by:r.cliLabel||r.cliIdentityKey,expiresInMs:Math.max(0,r.expiresAt-a)},bootedCount:0};if(r&&!c&&i.force)for(let[u,p]of this.cliSimBySocket){if(p!==t.id)continue;let m=this.cliIdentityKeyBySocket.get(u);if(m&&m!==s){this.cliSimBySocket.delete(u);try{u.close(1e3,"lease claimed by another cli")}catch{}l++}}let d={kind:"cli",cliIdentityKey:s,cliLabel:n,expiresAt:a+o.CLI_LEASE_TTL_MS};return t.cliLease=d,{granted:!0,lease:d,bootedCount:l}}updateUserFocusLease(e,t){let i=t.focused===!0,s=typeof t.visible=="boolean"?t.visible:void 0,n=typeof t.visibilityState=="string"?t.visibilityState:void 0,a=typeof t.documentFocused=="boolean"?t.documentFocused:void 0;e.userFocused===i&&e.userVisible===s&&e.visibilityState===n&&e.documentFocused===a||(e.userFocused=i,e.userVisible=s,e.visibilityState=n,e.documentFocused=a,this.broadcastSimClientStates())}updateUserActivity(e){let t=this.getActiveLease(e);if(t&&t.kind==="cli")return;let s=Date.now()+o.USER_ACTIVE_LEASE_TTL_MS,n=t&&t.kind==="user-active"?Math.max(t.expiresAt,s):s;e.cliLease={kind:"user-active",cliIdentityKey:"__user-active__",cliLabel:"active user",expiresAt:n},this.broadcastSimClientStates()}ensureCliIdentityKey(e){let t=this.cliIdentityKeyBySocket.get(e);if(t)return t;let i=`ws-${this.nextCliFallbackId++}`;return this.cliIdentityKeyBySocket.set(e,i),i}getOpenSim(e){if(e){let s=this.sims.get(e);return s?.ws.readyState===h.OPEN?s:null}let t=this.primarySimId!=null?this.sims.get(this.primarySimId):null;if(t?.ws.readyState===h.OPEN&&t.url)return t;let i=null;for(let s of this.sims.values())if(s.ws.readyState===h.OPEN){if(s.url)return s;i??=s}return t?.ws.readyState===h.OPEN?t:i}async waitForSim(e,t={}){let i=t.attempts??10,s=t.intervalMs??200;for(let n=0;n<i;n++){let a=this.getOpenSim(e);if(a)return a;await new Promise(r=>setTimeout(r,s))}throw new Error(e?`no sim connected with id ${e}`:"no sim connected")}shouldPromoteSim(e){let t=this.primarySimId?this.sims.get(this.primarySimId):null;if(!e.url)return!t;let i=t?.ws.readyState===h.OPEN;if(!t||!i||!t.url)return!0;let s=e.origin?.includes(":5173"),n=t.origin?.includes(":5173");return!!s||!n}broadcastSimAssignments(){for(let e of this.sims.values())e.ws.readyState===h.OPEN&&e.ws.send(JSON.stringify({type:"bridge:welcome",simId:e.id,isPrimary:e.id===this.primarySimId}))}broadcastSimClientStates(){for(let e of this.sims.values()){if(e.ws.readyState!==h.OPEN)continue;let t=this.getActiveLease(e),i={type:"bridge:client-state",attachedCliCount:this.getAttachedCliCount(e.id),activeAgentCommandCount:this.getActiveAgentCommandCount(e.id),recentActions:e.recentActions,lockedBy:t?t.cliLabel||t.cliIdentityKey:void 0,lockedByKind:t?t.kind:void 0,lockExpiresAt:t?t.expiresAt:void 0,userFocused:e.userFocused||void 0,userVisible:e.userVisible,visibilityState:e.visibilityState,documentFocused:e.documentFocused};e.ws.send(JSON.stringify(i))}}setCliSimTarget(e,t){let i=this.cliSimBySocket.get(e);i!==t&&(this.cliSimBySocket.set(e,t),this.recordSimAction(t,i?"cli switched sims":"cli connected",!1),this.broadcastSimClientStates())}recordSimAction(e,t,i=!0){let s=t?.trim();if(!s)return;let n=this.sims.get(e);if(!n)return;let a=Date.now();n.lastActiveAt=a,n.recentActions=[{label:s,at:a},...n.recentActions.filter(r=>r.label!==s)].slice(0,4),i&&this.broadcastSimClientStates()}describeForwardedCommand(e){switch(e?.type){case"evaluate":return"evaluated page state";case"screenshot":return"captured screenshot";case"tap":return"sent tap event";case"keyboard":return e?.action==="type"?"typed text":"used keyboard";case"tree":return"dumped tree";case"focus":return"focused sim";case"close":return"requested close";default:return typeof e?.type=="string"?e.type:null}}getAttachedCliCount(e){let t=new Set;for(let[i,s]of this.cliSimBySocket){if(s!==e||i.readyState!==h.OPEN)continue;let n=this.cliIdentityKeyBySocket.get(i);t.add(n??`ws-unknown-${t.size}`)}return t.size}getOtherCliIdentityCount(e,t){let i=this.cliIdentityKeyBySocket.get(e),s=new Set;for(let[n,a]of this.cliSimBySocket){if(a!==t||n.readyState!==h.OPEN)continue;let r=this.cliIdentityKeyBySocket.get(n);r&&r===i||s.add(r??`ws-unknown-${s.size}`)}return s.size}getActiveAgentCommandCount(e){let t=0;for(let i of this.pendingCommands.values())i.simId===e&&t++;return t}allocateSimId(){for(;;){let e=this.nextSimNumber.toString(16);if(this.nextSimNumber++,!this.sims.has(e)&&!this.restorableSims.has(e))return e}}tryRestoreSimId(e,t){let i=t?.trim();if(!i||i===e.id)return!1;let s=this.sims.get(i);if(s&&s!==e&&s.ws.readyState===h.OPEN)return!1;let n=this.getRestorableSimState(i),a=e.id;this.sims.delete(a),e.id=i,n&&(e.recentActions=n.recentActions.map(r=>({...r})),e.lastActiveAt=n.lastActiveAt,e.cliLease=n.cliLease?{...n.cliLease}:void 0,this.restorableSims.delete(i)),this.sims.set(e.id,e),this.primarySimId===a&&(this.primarySimId=e.id);for(let[r,c]of this.cliSimBySocket)c===a&&this.cliSimBySocket.set(r,e.id);return!0}rememberDisconnectedSim(e){let t=this.getActiveLease(e);this.restorableSims.set(e.id,{recentActions:e.recentActions.map(i=>({...i})),lastActiveAt:e.lastActiveAt,cliLease:t&&t.kind==="cli"?{...t}:void 0,expiresAt:Date.now()+o.SIM_RECONNECT_TTL_MS}),this.sims.delete(e.id)}getRestorableSimState(e){let t=this.restorableSims.get(e);return t?t.expiresAt<=Date.now()?(this.restorableSims.delete(e),null):(t.cliLease&&t.cliLease.expiresAt<=Date.now()&&(t.cliLease=void 0),t):null}sweepRestorableSims(e=Date.now()){for(let[t,i]of this.restorableSims)if(!(i.expiresAt>e)){this.restorableSims.delete(t);for(let[s,n]of this.cliSimBySocket)n===t&&this.cliSimBySocket.delete(s)}}resetServerState(){this.cliIdleTimer&&(clearInterval(this.cliIdleTimer),this.cliIdleTimer=null),this.wsHeartbeatTimer&&(clearInterval(this.wsHeartbeatTimer),this.wsHeartbeatTimer=null),this.runtimeUpdateTimer&&(clearInterval(this.runtimeUpdateTimer),this.runtimeUpdateTimer=null);let e=this.wss,t=this.httpServer;if(this.wss=null,this.httpServer=null,e)try{e.close()}catch{}if(t)try{t.close()}catch{}}};function dt(){return!!((process.env.XPC_SERVICE_NAME||"").includes("dev.sootsim.daemon")||process.env.INVOCATION_ID)}async function $t(o,e={}){(o.includes("--help")||o.includes("-h"))&&(console.log(`
|
|
23
|
+
sootsim serve \u2014 run the sootsim bridge in the foreground
|
|
23
24
|
|
|
24
25
|
hosts the WS bridge that CLI commands talk to. once running, any sootsim
|
|
25
26
|
renderer (browser, electron, headless playwright) that connects to port 7668
|
|
26
|
-
becomes drivable from 'sootsim describe', 'sootsim tap', etc.
|
|
27
|
+
becomes drivable from 'sootsim describe', 'sootsim do tap', etc.
|
|
27
28
|
|
|
28
29
|
usage:
|
|
29
|
-
sootsim
|
|
30
|
+
sootsim serve [options]
|
|
30
31
|
|
|
31
32
|
options:
|
|
32
33
|
--port <n> bridge port (defaults to ${7668})
|
|
33
34
|
--quiet suppress per-connection logging
|
|
34
35
|
|
|
35
36
|
examples:
|
|
36
|
-
sootsim
|
|
37
|
-
sootsim
|
|
38
|
-
`),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q")
|
|
39
|
-
`)},u=new Set,p=setInterval(()=>{let f=r.listSims(),
|
|
40
|
-
${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{$t as
|
|
37
|
+
sootsim serve
|
|
38
|
+
sootsim serve --port 7668 --quiet
|
|
39
|
+
`),process.exit(0));let t=o.indexOf("--port"),i=t>=0&&o[t+1]?Number(o[t+1]):e.port??7668;Number.isNaN(i)&&(console.error(` invalid --port value: ${o[t+1]}`),process.exit(1));let s=o.includes("--quiet")||o.includes("-q"),n=V();n&&G(n)&&(console.error(` a sootsim bridge is already running (pid ${n.pid}, port ${n.bridgePort})`),console.error(" stop it with 'sootsim daemon stop' first"),process.exit(1)),E();let a=await se(),r=new L({port:i,writeLockfile:!0,sootbeanOrigin:a}),c=await r.startAsync({silent:s}),l=Date.now(),d=f=>{s||process.stdout.write(`${f}
|
|
40
|
+
`)},u=new Set,p=setInterval(()=>{let f=r.listSims(),y=new Set(f.map(g=>g.id));for(let g of f)if(!u.has(g.id)){let 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:dt(),platform:process.platform,subsource:"daemon"}}),Q(),d(`sootsim bridge listening on ws://localhost:${c} (runtime http on same port)`),c!==i&&d(` (preferred port ${i} was taken \u2014 fell back to ${c})`),d(" ready for browser, electron, or headless playwright sims to connect"),d(" (ctrl-c to stop)");let m=async f=>{clearInterval(p),d(`
|
|
41
|
+
${f} received \u2014 shutting down after ${Math.round((Date.now()-l)/1e3)}s`);try{await r.close()}catch{}process.exit(0)};process.on("SIGINT",()=>m("SIGINT")),process.on("SIGTERM",()=>m("SIGTERM")),process.on("SIGHUP",()=>m("SIGHUP")),process.on("exit",()=>{try{r.removeLockfile()}catch{}}),await new Promise(()=>{})}export{$t as runServe};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{b as M,c as $}from"./chunk-547XSOJL.js";import{a as j,b as D}from"./chunk-XD66TGXU.js";import{a as P}from"./chunk-FJ2WDOTA.js";import"./chunk-LSZRVSXO.js";import"./chunk-RXBB4S3Q.js";import"./chunk-QIMO6SQX.js";import"./chunk-B77QXVTZ.js";import"./chunk-YPHT4BSL.js";import"./chunk-MBVNBHRK.js";import"./chunk-3OFDUWRM.js";import"./chunk-WXPG6OS6.js";import"./chunk-O54LARIO.js";import{I as b,K as v}from"./chunk-RULKWLIO.js";import"./chunk-AHOHHXWK.js";import"./chunk-RJZRI3P3.js";import"./chunk-CVLJ4RMA.js";import"./chunk-AOPGVSJW.js";import{execSync as H}from"child_process";import{existsSync as g,readFileSync as I,writeFileSync as w}from"fs";import{join as K,relative as h,resolve as m}from"path";import{existsSync as c,readFileSync as d,readdirSync as W,statSync as A}from"fs";import{basename as N,dirname as V,join as i}from"path";function O(e){let o=e;for(;;){if(c(i(o,"turbo.json"))||c(i(o,"nx.json"))||c(i(o,"lerna.json"))||c(i(o,"pnpm-workspace.yaml")))return o;let n=i(o,"package.json");if(c(n))try{if(JSON.parse(d(n,"utf8")).workspaces)return o}catch{}let t=V(o);if(t===o)break;o=t}return e}function J(e){return c(i(e,"bun.lock"))||c(i(e,"bun.lockb"))?"bun":c(i(e,"pnpm-lock.yaml"))?"pnpm":c(i(e,"yarn.lock"))?"yarn":"npm"}function B(e){if(c(i(e,"turbo.json")))return"turbo";if(c(i(e,"nx.json")))return"nx";if(c(i(e,"pnpm-workspace.yaml")))return"pnpm";let o=i(e,"package.json");if(c(o))try{if(JSON.parse(d(o,"utf8")).workspaces)return"npm-workspaces"}catch{}return"single"}function G(e){return e.one?"one":e.expo?"expo":e["react-native"]?"bare":"unknown"}function S(e){let o=i(e,"package.json");if(!c(o))return null;let n;try{n=JSON.parse(d(o,"utf8"))}catch{return null}let t={...n.dependencies,...n.devDependencies},r=G(t);return r==="unknown"?null:{dir:e,name:n.name||N(e),framework:r,hasViteConfig:c(i(e,"vite.config.ts"))||c(i(e,"vite.config.js")),hasMetroConfig:c(i(e,"metro.config.js"))||c(i(e,"metro.config.ts")),hasSootsimDependency:!!t.sootsim,devCommand:n.scripts?.dev||null}}function U(e){let o=[],n=i(e,"pnpm-workspace.yaml");if(c(n)){let s=d(n,"utf8").match(/packages:\s*\n((?:\s+-\s+.+\n?)+)/);if(s){let p=s[1].split(`
|
|
3
|
+
`).filter(Boolean);for(let u of p){let a=u.replace(/^\s*-\s*['"]?/,"").replace(/['"]?\s*$/,"");a&&o.push(...C(e,a))}}return o}let t=i(e,"package.json");if(c(t))try{let r=JSON.parse(d(t,"utf8")),s=Array.isArray(r.workspaces)?r.workspaces:r.workspaces?.packages||[];for(let p of s)o.push(...C(e,p))}catch{}return o}function C(e,o){let n=o.replace(/\/\*\*?$/,"").replace(/\*$/,""),t=i(e,n);if(!c(t))return[];try{return W(t).map(s=>i(t,s)).filter(s=>{try{return A(s).isDirectory()&&c(i(s,"package.json"))}catch{return!1}})}catch{return[]}}function _(e){let o=B(e),n=J(e);if(o==="single"){let p=S(e);return{root:e,type:o,packageManager:n,apps:p?[p]:[]}}let t=U(e),r=[],s=S(e);s&&r.push(s);for(let p of t){if(p===e)continue;let u=S(p);u&&r.push(u)}return{root:e,type:o,packageManager:n,apps:r}}function R(e){switch(e){case"bun":return"bun add -d sootsim";case"pnpm":return"pnpm add -D sootsim";case"yarn":return"yarn add -D sootsim";case"npm":return"npm install -D sootsim"}}async function xe(e){(e.includes("--help")||e.includes("-h"))&&(console.log(`
|
|
4
|
+
sootsim setup \u2014 set up this machine and, optionally, this repo
|
|
5
|
+
|
|
6
|
+
usage:
|
|
7
|
+
sootsim setup
|
|
8
|
+
sootsim setup --app <dir>
|
|
9
|
+
sootsim setup --yes
|
|
10
|
+
sootsim setup --dry-run
|
|
11
|
+
|
|
12
|
+
what it checks:
|
|
13
|
+
1. background daemon recommended; faster opens and runtime auto-updates
|
|
14
|
+
2. repo plugin optional; pins SootSim for your team and serves /__soot
|
|
15
|
+
3. sootsim.config.ts advanced; only for module/env/settings overrides
|
|
16
|
+
`),process.exit(0));let o=Q(e);g(o.appDir)||(console.error(` directory not found: ${o.appDir}`),process.exit(1)),console.log(`
|
|
17
|
+
sootsim setup
|
|
18
|
+
`),await X(o);let n=await Y(o);await Z(o,n)}function Q(e){let o=e.indexOf("--app");return{dryRun:e.includes("--dry-run"),yes:e.includes("--yes")||e.includes("-y"),appDir:o!==-1&&e[o+1]?m(e[o+1]):process.cwd()}}async function X(e){let o=M(),n=b(),t=v(n);if(console.log(" daemon:"),!o.supported){console.log(` unavailable on ${process.platform}`);return}if(o.installed){console.log(` installed${t&&n?`, running on port ${n.bridgePort}`:""}`);return}if(console.log(" not installed"),console.log(" recommended: installs the background bridge for faster opens and runtime auto-updates"),e.dryRun){console.log(" would install the background daemon");return}await x("install the background daemon?",!0,e)&&await $({port:7668,force:!1})}async function Y(e){let o=O(e.appDir),n=_(o);if(console.log(`
|
|
19
|
+
project integration:`),n.apps.length===0)return console.log(" no React Native, Expo, or One app detected"),console.log(" no repo setup is required for `sootsim open <port>`"),null;let t;if(n.type!=="single"&&n.apps.length>1){console.log(` monorepo detected (${n.type} + ${n.packageManager})`);let a=await D("which app?",n.apps.map(l=>`${(h(o,l.dir)||".").padEnd(30)} (${l.framework})`));t=n.apps[a]}else t=n.apps[0];let r=t.framework==="one"?"One/Vite":t.framework==="expo"?"Expo Metro":"Metro";console.log(` app: ${h(o,t.dir)||"."}`),console.log(` package: ${t.name}`),console.log(` bundler: ${r}`),console.log(" optional: add the repo plugin only when you want SootSim pinned and served from /__soot for the team");let s=ee(n.packageManager,t);if(s.length===0)return console.log(" already configured"),t;if(console.log(" would:"),s.forEach((a,l)=>console.log(` ${l+1}. ${a.label}`)),e.dryRun||!await x("install the repo plugin?",!1,e))return t;let p=0;for(let a=0;a<s.length;a++){let l=s[a];process.stdout.write(` [${a+1}/${s.length}] ${l.label}...`);try{await l.run(),console.log(" done")}catch(k){p++,console.log(` failed: ${se(k)}`),(l.label.includes("vite.config")||l.label.includes("metro.config"))&&re(t)}}P({event:"cli_setup_repo",properties:{framework:t.framework,package_manager:n.packageManager,workspace_type:n.type,step_count:s.length,step_failures:p}});let u=t.framework==="expo"?"npx expo start":t.framework==="one"?`${n.packageManager} run dev`:"npx react-native start";return console.log(`
|
|
20
|
+
start your dev server:
|
|
21
|
+
${u}
|
|
22
|
+
|
|
23
|
+
then:
|
|
24
|
+
sootsim open <dev server port>
|
|
25
|
+
`),t}async function Z(e,o){let n=o?.dir??e.appDir;if(!g(K(n,"package.json"))){console.log(`
|
|
26
|
+
config:`),console.log(" no package.json found; skipping sootsim.config.ts");return}let t=m(n,"sootsim.config.ts");if(console.log(`
|
|
27
|
+
config:`),g(t)){console.log(` already exists at ${h(process.cwd(),t)}`);return}if(console.log(" advanced: create only when you need module, environment, or simulator overrides"),e.dryRun){console.log(` would create ${h(process.cwd(),t)}`);return}await x("create sootsim.config.ts?",!1,e)&&(w(t,te()),console.log(` created ${h(process.cwd(),t)}`))}function ee(e,o){let n=[];if(!o.hasSootsimDependency){let t=R(e);n.push({label:"add sootsim as devDependency",run:()=>{H(t,{cwd:o.dir,stdio:"pipe"})}})}return o.framework==="one"&&o.hasViteConfig?n.push({label:"add sootsimPlugin() to vite.config.ts",run:()=>E(o.dir)}):(o.framework==="expo"||o.framework==="bare")&&o.hasMetroConfig?n.push({label:"add withSootsim() to metro.config.js",run:()=>oe(o.dir)}):o.framework==="one"?n.push({label:"add sootsimPlugin() to vite.config.ts",run:()=>E(o.dir)}):n.push({label:"create metro.config.js with withSootsim()",run:()=>ne(o.dir,o.framework)}),n}async function x(e,o,n){return n.yes?!0:j(e,o)}function E(e){let o=m(e,"vite.config.ts"),n=m(e,"vite.config.js"),t=g(o)?o:n;if(!g(t))throw new Error(`no vite config found at ${e}`);let r=I(t,"utf8");if(r.includes("sootsimPlugin")){console.log(" (already configured)");return}let s="import { sootsimPlugin } from 'sootsim/vite'",p=/^(import\s+.+)$/gm,u=0,a;for(;(a=p.exec(r))!==null;)u=a.index+a[0].length;u>0?r=r.slice(0,u)+`
|
|
28
|
+
`+s+r.slice(u):r=s+`
|
|
29
|
+
`+r;let l=r.match(/plugins\s*:\s*\[/);if(l&&l.index!==void 0){let k=l.index+l[0].length,y=1,f=k;for(;f<r.length&&y>0;)r[f]==="["&&y++,r[f]==="]"&&y--,y>0&&f++;let F=r.slice(0,f),L=r.slice(f),T=r.slice(k).match(/\n(\s+)\S/)?.[1]||" ",q=r.slice(r.lastIndexOf(`
|
|
30
|
+
`,f),f+1).match(/\n(\s*)/)?.[1]||" ";r=F.trimEnd()+`
|
|
31
|
+
`+T+`sootsimPlugin(),
|
|
32
|
+
`+q+L}else throw new Error("could not find plugins array in vite config");w(t,r)}function oe(e){let o=m(e,"metro.config.js"),n=m(e,"metro.config.ts"),t=g(o)?o:n;if(!g(t))throw new Error(`no metro config found at ${e}`);let r=I(t,"utf8");if(r.includes("withSootsim")){console.log(" (already configured)");return}r="const { withSootsim } = require('sootsim/metro')"+`
|
|
33
|
+
`+r,r=r.replace(/(module\.exports\s*=\s*)([^;]+)/,(p,u,a)=>`${u}withSootsim(${a.trim()})`),w(t,r)}function ne(e,o){let n=m(e,"metro.config.js");w(n,o==="expo"?`const { getDefaultConfig } = require('expo/metro-config')
|
|
34
|
+
const { withSootsim } = require('sootsim/metro')
|
|
35
|
+
|
|
36
|
+
const config = getDefaultConfig(__dirname)
|
|
37
|
+
|
|
38
|
+
module.exports = withSootsim(config)
|
|
39
|
+
`:`const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config')
|
|
40
|
+
const { withSootsim } = require('sootsim/metro')
|
|
41
|
+
|
|
42
|
+
const config = {}
|
|
43
|
+
|
|
44
|
+
module.exports = withSootsim(mergeConfig(getDefaultConfig(__dirname), config))
|
|
45
|
+
`)}function te(){return`import { defineConfig } from 'sootsim/config'
|
|
46
|
+
|
|
47
|
+
export default defineConfig({
|
|
48
|
+
// Advanced overrides only. Delete this file if you do not need them.
|
|
49
|
+
modules: {
|
|
50
|
+
// 'my-native-lib': 'noop',
|
|
51
|
+
// 'my-shim': { file: './shims/my-shim.ts' },
|
|
52
|
+
},
|
|
53
|
+
env: {
|
|
54
|
+
// API_URL: 'http://localhost:3000',
|
|
55
|
+
},
|
|
56
|
+
settings: {
|
|
57
|
+
// deviceModel: 'iphone-16',
|
|
58
|
+
// colorScheme: 'dark',
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
`}function re(e){e.framework==="one"?console.log(`
|
|
62
|
+
manual setup \u2014 add to your vite.config.ts:
|
|
63
|
+
|
|
64
|
+
import { sootsimPlugin } from 'sootsim/vite'
|
|
65
|
+
|
|
66
|
+
export default {
|
|
67
|
+
plugins: [
|
|
68
|
+
one({ /* ... */ }),
|
|
69
|
+
sootsimPlugin(),
|
|
70
|
+
],
|
|
71
|
+
}
|
|
72
|
+
`):console.log(`
|
|
73
|
+
manual setup \u2014 add to your metro.config.js:
|
|
74
|
+
|
|
75
|
+
const { withSootsim } = require('sootsim/metro')
|
|
76
|
+
module.exports = withSootsim(config)
|
|
77
|
+
`)}function se(e){return e instanceof Error?e.message:String(e)}export{xe as runSetup};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import"./chunk-AOPGVSJW.js";import*as r from"fs";import*as S from"os";import*as i from"path";import{fileURLToPath as g}from"url";function b(){try{let n=g(import.meta.resolve("sootsim/package.json"));return i.join(i.dirname(n),"skills")}catch{let n=i.dirname(g(import.meta.url));return i.resolve(n,"../../skills")}}var c=b(),$=new Set(["all","codex","claude"]);function k(){console.log(`sootsim skill
|
|
3
|
+
|
|
4
|
+
install and inspect bundled SootSim agent skills.
|
|
5
|
+
|
|
6
|
+
usage:
|
|
7
|
+
sootsim skill install [all|codex|claude] [skill-name...]
|
|
8
|
+
sootsim skill install --target <dir> [skill-name...]
|
|
9
|
+
sootsim skill show [skill-name]
|
|
10
|
+
|
|
11
|
+
commands:
|
|
12
|
+
install install skills; no target means all supported local agents
|
|
13
|
+
show list bundled skills, or print one skill markdown
|
|
14
|
+
|
|
15
|
+
targets:
|
|
16
|
+
all Codex and Claude Code (default)
|
|
17
|
+
codex $CODEX_HOME/skills, or ~/.codex/skills
|
|
18
|
+
claude $CLAUDE_CONFIG_DIR/skills, or ~/.claude/skills
|
|
19
|
+
`)}function p(){console.log(`sootsim skill install
|
|
20
|
+
|
|
21
|
+
install bundled SootSim skills in the agent skill layout: <skill>/SKILL.md.
|
|
22
|
+
|
|
23
|
+
usage:
|
|
24
|
+
sootsim skill install [all|codex|claude] [skill-name...]
|
|
25
|
+
sootsim skill install --target <dir> [skill-name...]
|
|
26
|
+
|
|
27
|
+
examples:
|
|
28
|
+
sootsim skill install
|
|
29
|
+
sootsim skill install codex
|
|
30
|
+
sootsim skill install codex sootsim-debug
|
|
31
|
+
`)}function u(n,t){let s=process.env[n]||i.join(S.homedir(),t);return i.join(s,"skills")}function x(){return[{label:"codex",dir:u("CODEX_HOME",".codex")},{label:"claude",dir:u("CLAUDE_CONFIG_DIR",".claude")}]}function _(n){if(n==="all")return x();if(n==="codex")return[{label:"codex",dir:u("CODEX_HOME",".codex")}];if(n==="claude")return[{label:"claude",dir:u("CLAUDE_CONFIG_DIR",".claude")}];console.error(` unknown skill install target: ${n}`),console.error(" expected all, codex, or claude"),process.exit(1)}function D(n){let t=n.match(/^---\n([\s\S]*?)\n---/);if(!t)return null;let s=t[1],l=h(s,"name");return l?{name:l,description:h(s,"description")||""}:null}function h(n,t){let s=n.split(`
|
|
32
|
+
`),l=`${t}:`;for(let e=0;e<s.length;e++){let o=s[e];if(!o.startsWith(l))continue;let a=o.slice(l.length).trim();if(a===">-"||a===">"||a==="|-"||a==="|"){let f=[];for(let m=e+1;m<s.length;m++){let d=s[m];if(/^[A-Za-z0-9_-]+:\s*/.test(d))break;if(d.trim()===""){f.push("");continue}if(!/^\s+/.test(d))break;f.push(d.trim())}return f.join(a.startsWith("|")?`
|
|
33
|
+
`:" ").trim()}return a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'")?a.slice(1,-1):a}return null}function I(){if(!r.existsSync(c))return[];let n=r.readdirSync(c).filter(s=>s.endsWith(".md")),t=[];for(let s of n){let l=r.readFileSync(i.join(c,s),"utf8"),e=D(l);e&&t.push({...e,filename:s})}return t.sort((s,l)=>s.name.localeCompare(l.name))}function y(n,t){if(t.length===0)return n;let s=n.filter(l=>t.some(e=>l.name.includes(e)||l.name.replace("sootsim-","").includes(e)||l.filename.includes(e)));return s.length===0&&(console.error(` no skills matched: ${t.join(", ")}`),console.error(" available: "+n.map(l=>l.name).join(", ")),process.exit(1)),s}function w(n,t){let s=i.join(c,n.filename),l=i.join(t,n.name),e=i.join(l,"SKILL.md");r.mkdirSync(l,{recursive:!0}),r.copyFileSync(s,e),console.log(` copied ${n.name} -> ${e}`)}function C(n){if(n.length===0){console.log(" no skills found");return}console.log(`
|
|
34
|
+
available skills:
|
|
35
|
+
`);for(let t of n)console.log(` ${t.name}`),console.log(` ${t.description}
|
|
36
|
+
`);console.log(" usage: sootsim skill install [all|codex|claude] [skill-name...]"),console.log(` usage: sootsim skill show [skill-name]
|
|
37
|
+
`)}function L(n){let t=null,s=[];for(let l=0;l<n.length;l++){let e=n[l];if((e==="--help"||e==="-h")&&(p(),process.exit(0)),e==="--target"){let o=n[l+1];(!o||o.startsWith("-"))&&(console.error(" --target requires a directory"),process.exit(1)),t&&(console.error(" pass only one install target"),process.exit(1)),t=[{label:"target",dir:o}],l++;continue}if(e.startsWith("-")&&(console.error(` unknown option: ${e}`),p(),process.exit(1)),!t&&$.has(e)){t=_(e);continue}s.push(e)}return{targets:t??x(),filters:s}}async function j(n){let t=I();t.length===0&&(console.error(" no skills found in sootsim package"),process.exit(1));let s=L(n),l=y(t,s.filters),e=s.targets.map(o=>({...o,dir:i.resolve(o.dir)}));for(let o of e)r.mkdirSync(o.dir,{recursive:!0}),r.statSync(o.dir).isDirectory()||(console.error(` target is not a directory: ${o.dir}`),process.exit(1));console.log(`
|
|
38
|
+
installing ${l.length} skill(s) to ${e.length} target(s)
|
|
39
|
+
`);for(let o of e){console.log(` target ${o.label}: ${o.dir}`);for(let a of l)w(a,o.dir);console.log("")}console.log(` done. restart the agent session to load newly installed skills.
|
|
40
|
+
`)}function T(n){let t=I(),s=n.find(o=>!o.startsWith("-"));if(!s){C(t);return}let[l]=y(t,[s]),e=r.readFileSync(i.join(c,l.filename),"utf8");console.log(e)}async function F(n){let[t,...s]=n;if(!t||t==="--help"||t==="-h"){k();return}if(t==="install"){await j(s);return}if(t==="show"||t==="list"){T(s);return}console.error(` unknown skill command: ${t}`),k(),process.exit(1)}export{F as runSkill};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{c as S,e as y,g as v,h as b,i as u}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.171 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{c as S,e as y,g as v,h as b,i as u}from"./chunk-CJTJX3H7.js";import"./chunk-WXPG6OS6.js";import"./chunk-O54LARIO.js";import"./chunk-RULKWLIO.js";import"./chunk-AOPGVSJW.js";import{mkdirSync as $,writeFileSync as x}from"node:fs";import{dirname as k,isAbsolute as B,join as C,resolve as E}from"node:path";var z=`
|
|
3
3
|
sootsim slides \u2014 compose App Store screenshots in the live sim
|
|
4
4
|
|
|
5
5
|
usage:
|