sootsim 0.1.202 → 0.1.203
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/dist-cli/bin.js +4 -4
- package/dist-cli/chunks/{agent-SP6EE5XV.js → agent-PWM4XT5H.js} +2 -2
- package/dist-cli/chunks/{agent-wrapper-PWZVJ3OK.js → agent-wrapper-V2BSTANB.js} +2 -2
- package/dist-cli/chunks/{app-fonts-EMJB6QLM.js → app-fonts-7M4PTF6W.js} +2 -2
- package/dist-cli/chunks/{assert-H2B6TDXT.js → assert-SEW5OJL3.js} +2 -2
- package/dist-cli/chunks/{auth-SOHXBYLQ.js → auth-3YY55NBL.js} +2 -2
- package/dist-cli/chunks/beta-Y4ZJUKAM.js +2 -0
- package/dist-cli/chunks/{camera-ULLCBM5H.js → camera-CYXCASB3.js} +2 -2
- package/dist-cli/chunks/{chunk-4NM6JBYH.js → chunk-4NHPXU3X.js} +1 -1
- package/dist-cli/chunks/{chunk-2V43M57C.js → chunk-62AKBZTO.js} +1 -1
- package/dist-cli/chunks/{chunk-WILIVPUU.js → chunk-6DN4BD7O.js} +24 -24
- package/dist-cli/chunks/{chunk-RWXCSRNE.js → chunk-6M56UHEY.js} +2 -2
- package/dist-cli/chunks/{chunk-F2LLN4U7.js → chunk-A3FIOG7U.js} +2 -2
- package/dist-cli/chunks/{chunk-Z5VMWFCY.js → chunk-B7VBDZ3U.js} +1 -1
- package/dist-cli/chunks/{chunk-WVDWIXPH.js → chunk-BBOFH45Q.js} +2 -2
- package/dist-cli/chunks/{chunk-RS7QLHEH.js → chunk-BJJXNQHO.js} +2 -2
- package/dist-cli/chunks/{chunk-HZYHSLNH.js → chunk-BL67OSVN.js} +2 -2
- package/dist-cli/chunks/{chunk-CB7LDZKJ.js → chunk-EBH65V62.js} +3 -3
- package/dist-cli/chunks/{chunk-OG6TFGYF.js → chunk-FF3C57T5.js} +2 -2
- package/dist-cli/chunks/{chunk-JP7J325R.js → chunk-FUC7C5HS.js} +2 -2
- package/dist-cli/chunks/{chunk-AAQVPSIV.js → chunk-G5GRLVYA.js} +2 -2
- package/dist-cli/chunks/chunk-G5VOIXM7.js +1 -0
- package/dist-cli/chunks/{chunk-CGJ2U6ST.js → chunk-GMVAXDHH.js} +1 -1
- package/dist-cli/chunks/{chunk-RJVIUQK4.js → chunk-GTBF3M2H.js} +1 -1
- package/dist-cli/chunks/{chunk-LNDRRZP3.js → chunk-GYTATFQA.js} +2 -2
- package/dist-cli/chunks/{chunk-PL4GXELT.js → chunk-JLOAWSX6.js} +1 -1
- package/dist-cli/chunks/{chunk-B6JB4THC.js → chunk-K3CRSIGS.js} +2 -2
- package/dist-cli/chunks/{chunk-SQBX2HS7.js → chunk-LKJ5LA6K.js} +2 -2
- package/dist-cli/chunks/{chunk-6QFVYLX6.js → chunk-LTRNOX6N.js} +2 -2
- package/dist-cli/chunks/{chunk-K3UBHPVP.js → chunk-MQHSWXDS.js} +1 -1
- package/dist-cli/chunks/{chunk-3ZENZOIX.js → chunk-NHSO4473.js} +2 -2
- package/dist-cli/chunks/chunk-ODW7RHSD.js +97 -0
- package/dist-cli/chunks/{chunk-TANTCV45.js → chunk-OK7QEDHD.js} +2 -2
- package/dist-cli/chunks/{chunk-RZQO4Q7E.js → chunk-OXQOPTTB.js} +1 -1
- package/dist-cli/chunks/{chunk-EMOZJ773.js → chunk-P4GJL7OH.js} +2 -2
- package/dist-cli/chunks/{chunk-6FZ6SNVP.js → chunk-PELEQURX.js} +2 -2
- package/dist-cli/chunks/chunk-QKDII5UB.js +1 -0
- package/dist-cli/chunks/{chunk-DKBKU55D.js → chunk-R7GIVBTY.js} +2 -2
- package/dist-cli/chunks/{chunk-4KVSVFRF.js → chunk-RVOF6RIE.js} +1 -1
- package/dist-cli/chunks/{chunk-W4Y3JJX6.js → chunk-RZU5TDPJ.js} +3 -3
- package/dist-cli/chunks/{chunk-KRGHRSKY.js → chunk-U6OCMLMU.js} +2 -2
- package/dist-cli/chunks/{chunk-5SKKMM7E.js → chunk-UJ64GJSZ.js} +1 -1
- package/dist-cli/chunks/{chunk-DRJ4YWUG.js → chunk-UZGLGCLM.js} +1 -1
- package/dist-cli/chunks/{chunk-KYGUR727.js → chunk-WSOZGPIX.js} +2 -2
- package/dist-cli/chunks/{chunk-ENXHZGSL.js → chunk-WVF2EDZF.js} +1 -1
- package/dist-cli/chunks/{chunk-ROYBEBG2.js → chunk-XYMOH3HP.js} +1 -1
- package/dist-cli/chunks/{chunk-2CID4LNK.js → chunk-YJNJ5GVC.js} +3 -3
- package/dist-cli/chunks/{chunk-GUYKLSTX.js → chunk-YP3NIRTK.js} +1 -1
- package/dist-cli/chunks/{chunk-GZKT53SA.js → chunk-ZGM7N2AV.js} +1 -1
- package/dist-cli/chunks/{chunk-4KT2BGQE.js → chunk-ZRWVLKFL.js} +1 -1
- package/dist-cli/chunks/cli-version-N2RKZ2CU.js +2 -0
- package/dist-cli/chunks/{compat-YW3OJ7RX.js → compat-FK5MP535.js} +3 -3
- package/dist-cli/chunks/{config-ZGOXFEX4.js → config-T3W2HI67.js} +2 -2
- package/dist-cli/chunks/{control-75JRFOYV.js → control-ONFLGDEC.js} +2 -2
- package/dist-cli/chunks/daemon-FDI5YYZN.js +2 -0
- package/dist-cli/chunks/{debug-4APEP64L.js → debug-Z6NG4KY2.js} +3 -3
- package/dist-cli/chunks/{desktop-CS7S4CXK.js → desktop-BIWB2UYC.js} +3 -3
- package/dist-cli/chunks/{detox-7R7DOKQM.js → detox-6K7WFLQO.js} +2 -2
- package/dist-cli/chunks/{device-EIDKLBEK.js → device-TPD5WAP2.js} +2 -2
- package/dist-cli/chunks/{diagnose-J2F7MJAJ.js → diagnose-NACPOTYX.js} +2 -2
- package/dist-cli/chunks/drivers-G2YZR6G6.js +2 -0
- package/dist-cli/chunks/flow-OAW2MZCD.js +2 -0
- package/dist-cli/chunks/help-MY2CBECX.js +2 -0
- package/dist-cli/chunks/{home-paths-WVCREWI7.js → home-paths-WWFDX6YU.js} +2 -2
- package/dist-cli/chunks/inspect-ZPVPUSAK.js +2 -0
- package/dist-cli/chunks/install-desktop-QZWSSGJV.js +2 -0
- package/dist-cli/chunks/{login-EOBJ7CZ4.js → login-WGCO2V4S.js} +4 -4
- package/dist-cli/chunks/{logout-RL7D66VQ.js → logout-VWSSNYF5.js} +2 -2
- package/dist-cli/chunks/{maestro-F66ZIJKA.js → maestro-YED424Y6.js} +2 -2
- package/dist-cli/chunks/{mode-R2VIW66U.js → mode-QCOM4UM4.js} +2 -2
- package/dist-cli/chunks/optional-demo-registry-3KZFUZZD.js +2 -0
- package/dist-cli/chunks/{perf-PGYO5BBR.js → perf-FZHCFAID.js} +2 -2
- package/dist-cli/chunks/{record-IGDVHC67.js → record-NF3PKBSW.js} +3 -3
- package/dist-cli/chunks/runtime-ETELTKFT.js +2 -0
- package/dist-cli/chunks/screenshot-command-KLPOA5TW.js +151 -0
- package/dist-cli/chunks/screenshots-capture-MCTZSXLE.js +41 -0
- package/dist-cli/chunks/{serve-3TFVHYLY.js → serve-XBWYWHMC.js} +2 -2
- package/dist-cli/chunks/{setup-JSPPRVET.js → setup-W7EROACZ.js} +3 -3
- package/dist-cli/chunks/{skills-LK3B76W7.js → skills-RBGNF7GS.js} +2 -2
- package/dist-cli/chunks/{storage-NC5RNBUA.js → storage-3SFE2DUE.js} +2 -2
- package/dist-cli/chunks/store-Z3CHVRR3.js +2 -0
- package/dist-cli/chunks/telemetry-SWFOAVWP.js +2 -0
- package/dist-cli/chunks/{test-2CXPLH5N.js → test-UP6VTFKE.js} +5 -5
- package/dist-cli/chunks/{timeline-WDTEVELN.js → timeline-A54JB74A.js} +2 -2
- package/dist-cli/chunks/{upgrade-TT2IJSNJ.js → upgrade-H7XE3N76.js} +2 -2
- package/dist-cli/chunks/upload-X2BRKPBJ.js +2 -0
- package/dist-cli/chunks/{version-JUNH4FOR.js → version-4JV7HX23.js} +2 -2
- package/dist-cli/chunks/{web-BWCW26ZA.js → web-5OLZXKVF.js} +2 -2
- package/dist-cli/chunks/{what-happened-L6EEB6MB.js → what-happened-Q4L6SI4I.js} +2 -2
- package/dist-lib/agent-daemon-client.cjs +1 -1
- package/dist-lib/agent-events.cjs +1 -1
- package/dist-lib/agent-identity.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 +1 -1
- package/dist-lib/beta.mjs +1 -1
- 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 +1 -1
- package/dist-lib/dev-bundle-resolution.cjs +1 -1
- package/dist-lib/home-paths.cjs +1 -1
- package/dist-lib/host/bridge-host.cjs +1 -1
- 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 +1 -1
- package/dist-lib/jump-to-source-babel.cjs +1 -1
- package/dist-lib/menu.cjs +1 -1
- package/dist-lib/menu.mjs +1 -1
- package/dist-lib/metro.cjs +1 -1
- package/dist-lib/profiles.cjs +1 -1
- package/dist-lib/render-mode.cjs +1 -1
- package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
- package/dist-lib/sdk.cjs +1 -1
- package/dist-lib/sdk.mjs +1 -1
- package/dist-lib/skills.cjs +1 -1
- package/dist-lib/vite.cjs +1 -1
- package/package.json +1 -1
- package/dist-cli/chunks/beta-CCNQQ73A.js +0 -2
- package/dist-cli/chunks/chunk-5J63S2NM.js +0 -1
- package/dist-cli/chunks/chunk-BZ7AW7ZB.js +0 -92
- package/dist-cli/chunks/chunk-I6O7NBPZ.js +0 -1
- package/dist-cli/chunks/cli-version-Z4NGLJLH.js +0 -2
- package/dist-cli/chunks/daemon-SHFBQRHD.js +0 -2
- package/dist-cli/chunks/drivers-55L7BHDF.js +0 -2
- package/dist-cli/chunks/flow-AHWVTHJP.js +0 -2
- package/dist-cli/chunks/help-C4BTMPEE.js +0 -2
- package/dist-cli/chunks/inspect-M4Z4SSSB.js +0 -2
- package/dist-cli/chunks/install-desktop-PVRUAEMA.js +0 -2
- package/dist-cli/chunks/optional-demo-registry-ILX5YV34.js +0 -2
- package/dist-cli/chunks/runtime-43RJGUGS.js +0 -2
- package/dist-cli/chunks/screenshot-command-HX4GVUJM.js +0 -190
- package/dist-cli/chunks/store-3XMEKA6H.js +0 -2
- package/dist-cli/chunks/telemetry-CVJ5YZNS.js +0 -2
- package/dist-cli/chunks/upload-4HMNB4HA.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as he,c as fe,d as me,e as Ye,f as ge,g as we,h as Ze,i as ye,j as Xe}from"./chunk-YJNJ5GVC.js";import{a as qe}from"./chunk-G5GRLVYA.js";import{a as et}from"./chunk-LTRNOX6N.js";import{a as Qe}from"./chunk-ODW7RHSD.js";import{h as Je,p as Ge,r as ze,v as Ke}from"./chunk-K3CRSIGS.js";import{f as Le}from"./chunk-BBOFH45Q.js";import{a as Be}from"./chunk-4NHPXU3X.js";import{h as pe,m as Ue}from"./chunk-P4GJL7OH.js";import{I as V,m as Ce,n as Ne,o as He,p as We}from"./chunk-XYMOH3HP.js";import{g as ce,h as ue,i as je}from"./chunk-U6OCMLMU.js";import{a as Ve}from"./chunk-WVF2EDZF.js";import{a as Me,b as le}from"./chunk-WSOZGPIX.js";import{d as de,e as De}from"./chunk-OXQOPTTB.js";import{g as Oe,h as _e}from"./chunk-62AKBZTO.js";import*as k from"fs";import{tmpdir as ie}from"os";import*as w from"path";import*as S from"fs";import*as b from"path";var vt="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",it=1;function xt(n){let e=_e(n),t=e.scale,i=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,r=e.width,o=e.height,a=i?e.width+58:e.width+e.bezelWidth*2,s=i?e.height+111+111:e.height+e.bezelWidth*2,l=9.5,u=it,p=a+l*2,m=s+it*2,x=l+(i?29:e.bezelWidth),g=i?111:e.bezelWidth,P=i?52:e.cornerRadius+e.bezelWidth,_=[{side:"right",top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:n,renderScale:t,outerWidth:Math.round(p*t),outerHeight:Math.round(m*t),logicalOuterWidth:p,logicalOuterHeight:m,logicalFrameWidth:a,logicalFrameHeight:s,logicalFrameLeft:l,logicalFrameTop:u,logicalScreenWidth:r,logicalScreenHeight:o,logicalScreenLeft:x,logicalScreenTop:g,logicalScreenRadius:i?0:e.cornerRadius,logicalFrameRadius:P,frameBackground:i?"linear-gradient(180deg, #1b1c20 0%, #0f1012 42%, #050608 100%)":"#000000",frameOutline:i?"0 0 0 1px #1f2125":"0 0 0 1px #333",metallicRingShadow:i?null:vt,buttons:_,legacyHomeButton:i?{top:111+e.height+47/2,left:e.width/2-64/2+29,size:64,ring:1.5}:null,showHomeIndicator:e.homeIndicatorHeight>0,logicalHomeIndicatorStripHeight:e.homeIndicatorHeight}}function Tt(n){let e=n.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
|
|
3
3
|
<div
|
|
4
4
|
aria-hidden="true"
|
|
5
5
|
style="
|
|
@@ -24,7 +24,7 @@ import{a as pe,c as he,d as fe,e as qe,f as me,g as ge,h as Ye,i as we,j as Ze}f
|
|
|
24
24
|
z-index:2;
|
|
25
25
|
"
|
|
26
26
|
></div>
|
|
27
|
-
`}function
|
|
27
|
+
`}function Et(n,e){let t=n.buttons.map(Tt).join(""),i=n.metallicRingShadow?`
|
|
28
28
|
<div
|
|
29
29
|
aria-hidden="true"
|
|
30
30
|
style="
|
|
@@ -177,7 +177,7 @@ import{a as pe,c as he,d as fe,e as qe,f as me,g as ge,h as Ye,i as we,j as Ze}f
|
|
|
177
177
|
</div>
|
|
178
178
|
</div>
|
|
179
179
|
</body>
|
|
180
|
-
</html>`}async function
|
|
180
|
+
</html>`}async function rt(n,e){let{chromium:t}=await import("playwright"),i=await t.launch({headless:!0});try{let r=await Ft(i);try{return await r.compose(n,e)}finally{await r.close()}}finally{await i.close()}}async function Ft(n){let e=new Map;async function t(i){let r=e.get(i);if(r)return r;let o=xt(i),a=await n.newContext({viewport:{width:o.outerWidth,height:o.outerHeight},deviceScaleFactor:1}),s=await a.newPage(),l={layout:o,context:a,page:s};return e.set(i,l),l}return{async compose(i,r){let o=await t(r),a=`data:image/png;base64,${i.toString("base64")}`;return await o.page.setContent(Et(o.layout,a),{waitUntil:"load"}),await o.page.waitForTimeout(20),await o.page.screenshot({type:"png",clip:{x:0,y:0,width:o.layout.outerWidth,height:o.layout.outerHeight},omitBackground:!0})},async close(){for(let i of e.values())await i.context.close();e.clear()}}}import{spawnSync as It}from"child_process";import*as C from"vm";var $t=3e5,kt=`
|
|
181
181
|
let input = '';
|
|
182
182
|
process.stdin.on('data', (c) => { input += c });
|
|
183
183
|
process.stdin.on('end', async () => {
|
|
@@ -199,7 +199,7 @@ process.stdin.on('end', async () => {
|
|
|
199
199
|
process.exitCode = 1;
|
|
200
200
|
}
|
|
201
201
|
});
|
|
202
|
-
`;function J(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let i={...process.env};for(let s of Object.keys(i))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete i[s];let r=
|
|
202
|
+
`;function J(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let i={...process.env};for(let s of Object.keys(i))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete i[s];let r=It(process.execPath,["-e",kt],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:$t,maxBuffer:64*1024*1024,env:i});if(r.error)throw new Error(`http ${e} ${n} failed: ${r.error.message}`);let o;try{o=JSON.parse(r.stdout||"")}catch{throw new Error(`http ${e} ${n} failed: no response (${(r.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${n} failed: ${a.__error}`);return a}var Pt=/(?<!\\)\$\{([^$]*)\}/g,At=/\\(\$\{[^$]*\})/g,Rt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Y=class{context;envBinding=new Map;envScopeStack=[];syncedEnvKeys=new Set;output={};maestro;constructor(e={}){this.maestro={copiedText:null,platform:e.platform??"ios"};let t=e.onLog??(r=>console.log(`[flow] js: ${r}`)),i={output:this.output,maestro:this.maestro,http:{get:(r,o)=>J(r,"GET",o),post:(r,o)=>J(r,"POST",o),put:(r,o)=>J(r,"PUT",o),delete:(r,o)=>J(r,"DELETE",o),request:(r,o)=>J(r,(o?.method??"GET").toUpperCase(),o)},console:{log:(...r)=>t(r.map(o=>typeof o=="string"?o:nt(o)).join(" "))}};this.context=C.createContext(i),C.runInContext(`
|
|
203
203
|
globalThis.__maestroScope = new Proxy(globalThis, {
|
|
204
204
|
has() { return true },
|
|
205
205
|
get(target, key) { return target[key] },
|
|
@@ -210,13 +210,13 @@ process.stdin.on('end', async () => {
|
|
|
210
210
|
var yPercent = Math.ceil(y * 100) + '%'
|
|
211
211
|
return xPercent + ',' + yPercent
|
|
212
212
|
}
|
|
213
|
-
`,this.context);for(let[r,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(r,o)}putEnv(e,t){this.envBinding.set(e,t)}setCopiedText(e){this.maestro.copiedText=e}enterEnvScope(){this.envScopeStack.push(new Map(this.envBinding))}leaveEnvScope(){let e=this.envScopeStack.pop();if(e){this.envBinding.clear();for(let[t,i]of e)this.envBinding.set(t,i)}}evaluate(e,t={}){let i=t.env;if(i&&Object.keys(i).length>0){this.enterEnvScope();try{for(let[r,o]of Object.entries(i))this.envBinding.set(r,o);return this.evalRaw(e)}finally{this.leaveEnvScope()}}return this.evalRaw(e)}evalRaw(e){this.syncEnvToContext();let t=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${");return C.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=C.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,i]of this.envBinding)try{e[t]=i,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(
|
|
213
|
+
`,this.context);for(let[r,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(r,o)}putEnv(e,t){this.envBinding.set(e,t)}setCopiedText(e){this.maestro.copiedText=e}enterEnvScope(){this.envScopeStack.push(new Map(this.envBinding))}leaveEnvScope(){let e=this.envScopeStack.pop();if(e){this.envBinding.clear();for(let[t,i]of e)this.envBinding.set(t,i)}}evaluate(e,t={}){let i=t.env;if(i&&Object.keys(i).length>0){this.enterEnvScope();try{for(let[r,o]of Object.entries(i))this.envBinding.set(r,o);return this.evalRaw(e)}finally{this.leaveEnvScope()}}return this.evalRaw(e)}evalRaw(e){this.syncEnvToContext();let t=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${");return C.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=C.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,i]of this.envBinding)try{e[t]=i,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(Pt,(i,r)=>{if(r.trim().length===0)return"";let o=this.evaluate(r);if(o===void 0&&Rt.test(r.trim()))throw new Error(`missing variable for flow placeholder: ${r.trim()}`);return nt(o)}).replace(At,(i,r)=>r)}interpolateStep(e){return this.interpolateValue(e,null)}interpolateValue(e,t){return typeof e=="string"?t==="evalScript"?e:this.evaluateStringTemplate(e):Array.isArray(e)?t==="commands"||t==="onFlowStart"||t==="onFlowComplete"?e:e.map(i=>this.interpolateValue(i,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,r])=>[i,this.interpolateValue(r,i)])):e}};function nt(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}function ot(n){if(n==null)return!1;if(typeof n=="boolean")return n;let e=String(n);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var Z=1e4,Q=393,N=852;function f(n){return new Promise(e=>setTimeout(e,n))}function xe(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function G(n,e){if(!xe(n))return null;let t=n[e];return typeof t=="string"&&t.length>0?t:null}function Mt(n,e){return xe(n)?n[e]===!0:!1}function Ot(n){if(!n)return null;let e=n.recentApps;if(Array.isArray(e))for(let i of e){let r=G(i,"id");if(r)return r}let t=n.surfaceBindings;return G(t,"app:one")||G(t,"app:two")||null}function _t(n){return n?b.basename(n)===".maestro"?b.dirname(n):n:process.cwd()}function Dt(n,e,t){let i=e.endsWith(".png")?e:`${e}.png`;if(b.isAbsolute(i))return i;if(t.mode==="flow"&&/[\\/]/.test(i)){let r=i.startsWith("./")||i.startsWith("../")?t.flowDir??process.cwd():_t(t.flowDir);return b.resolve(r,i)}return b.join(n,i)}function Bt(n){if(typeof n=="string")return{path:n,withFrame:!1};let e=n.path?.trim()||n.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:n.withFrame===!0,layers:n.layers}}function X(n,e){let[t,i]=n.split(",").map(s=>s.trim()),r=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+r(t,e?.width??Q),y:a+r(i,e?.height??N)}}function st(n){switch(n){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[n]:!0}}}function Lt(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,i=qe.parse(t);return Array.isArray(i)?i:[]}var ee=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new Y({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingStartedAtMs=null;lastRecordingDurationMs=null;lastRecordingFrameStats=null;flowTraceSteps=[];lastVisualSettledAtMs=0;simRouteHint=null;lastFailedStep=null;get simId(){return this.opts.simId}setSimRouteHint(e){this.simRouteHint=this.normalizeSimRoute(e)}normalizeSimRoute(e){if(!e)return null;try{let t=new URL(e);t.searchParams.delete("inspectOpen");let i=t.searchParams.toString();return`${t.origin}${t.pathname}${i?`?${i}`:""}`}catch{return e}}async refreshSimId(){if(this.opts.simId)try{let e=await this.bridge.listSims(),t=e.find(l=>l.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(l=>l.id===this.opts.simId&&l.readyState==="open")||!this.simRouteHint)return;let r=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!r)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=r??o??a;s&&(this.opts.simId=s.id,console.log(` [flow] sim rotated to ${s.id}`))}catch{}}async evaluate(e,t){return this.bridge.send({type:"evaluate",simId:this.opts.simId,code:e},t?{timeoutMs:t}:void 0)}async callTest(e,...t){return this.bridge.send({type:"call",simId:this.opts.simId,path:`__sootsimTest.${e}`,args:t})}async waitForTree(e=Z){let t=Date.now()+e,i=Date.now(),r=null,o=0,a=0,s=-1,l=i;for(;Date.now()<t;){try{let p=await this.evaluate(Ce,8e3);if(o=0,p?.externalError)throw new Error(`app failed to load: ${p.externalError}`);if(p){let m=Date.now();p.nodes!==s&&(s=p.nodes,l=m);let x=p.flag===!0&&He(p),g=p.flag!==!0&&We(p);if((x||g)&&p.externalReady!==!1&&!p.externalError&&!p.loadingText&&m-l>=Ne)return}}catch(p){if(r=p instanceof Error?p:new Error(String(p)),r.message.startsWith("app failed to load:"))throw r;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${r.message}). it is likely a stale orphan \u2014 run \`sootsim list\`, then close it with \`sootsim close <id>\` or start a fresh one with \`sootsim open --new <port>\`.`);await this.refreshSimId()}let u=Date.now()-i;u-a>=5e3&&(a=u,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(u/1e3)}s)`)),await f(500)}throw r?.message.startsWith("app failed to load:")?r:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(this.opts.requireRecordingEntitlement&&await et("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
|
|
214
214
|
const rec = window.__sootsimRecorder
|
|
215
215
|
if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
|
|
216
216
|
const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
|
|
217
217
|
if (rec.state() === 'recording') return { ok: true, format }
|
|
218
218
|
return rec.start({ format, fps: 24 })
|
|
219
|
-
})()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=typeof t.startedAtMs=="number"&&Number.isFinite(t.startedAtMs)?t.startedAtMs:e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}getLastRecordingStartedAtMs(){return this.lastRecordingStartedAtMs}getLastRecordingFrameStats(){return this.lastRecordingFrameStats}getFlowTraceSteps(){return[...this.flowTraceSteps]}flowStepTargetLabel(e,t){if(t==="inputText"||t==="runScript"||t==="evalScript")return;let i=e[t];if(typeof i=="string")return i.slice(0,80);if(typeof i=="number"||typeof i=="boolean")return String(i);if(!i||typeof i!="object")return;let r=i,o=r.id??r.text??r.name??r.path;if(typeof o=="string"&&o)return o.slice(0,80);if(r.point&&typeof r.point=="string")return r.point.slice(0,80);if(typeof r.x=="number"&&typeof r.y=="number")return`${Math.round(r.x)}, ${Math.round(r.y)}`}recordFlowTraceStep(e){let t=Date.now(),i={stepIndex:e.stepIndex,stepName:e.stepName,...e.targetLabel?{targetLabel:e.targetLabel}:{},startedAtMs:e.startedAtMs,endedAtMs:t,durationMs:Math.max(0,t-e.startedAtMs),status:e.status};e.error!=null&&(i.error=e.error instanceof Error?e.error.message:String(e.error)),this.flowTraceSteps.push(i)}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,this.lastRecordingFrameStats=null,new Error(t?.error||"recording stop failed");this.lastRecordingStartedAtMs=this.recordingStartedAtMs,this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.lastRecordingFrameStats=t.frameStats??null,this.recordingStartedAtMs=null;let i=[],r=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${r}, chunk: 2097152 })`);if(!l||(i.push(Buffer.from(l.data,"base64")),r=l.offset,l.done))break}if(i.length===0)throw new Error("recording requested but no video buffer was produced");S.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=b.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return S.writeFileSync(s,Buffer.concat(i)),s}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await f(t);return}let i=await
|
|
219
|
+
})()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=typeof t.startedAtMs=="number"&&Number.isFinite(t.startedAtMs)?t.startedAtMs:e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}getLastRecordingStartedAtMs(){return this.lastRecordingStartedAtMs}getLastRecordingFrameStats(){return this.lastRecordingFrameStats}getFlowTraceSteps(){return[...this.flowTraceSteps]}flowStepTargetLabel(e,t){if(t==="inputText"||t==="runScript"||t==="evalScript")return;let i=e[t];if(typeof i=="string")return i.slice(0,80);if(typeof i=="number"||typeof i=="boolean")return String(i);if(!i||typeof i!="object")return;let r=i,o=r.id??r.text??r.name??r.path;if(typeof o=="string"&&o)return o.slice(0,80);if(r.point&&typeof r.point=="string")return r.point.slice(0,80);if(typeof r.x=="number"&&typeof r.y=="number")return`${Math.round(r.x)}, ${Math.round(r.y)}`}recordFlowTraceStep(e){let t=Date.now(),i={stepIndex:e.stepIndex,stepName:e.stepName,...e.targetLabel?{targetLabel:e.targetLabel}:{},startedAtMs:e.startedAtMs,endedAtMs:t,durationMs:Math.max(0,t-e.startedAtMs),status:e.status};e.error!=null&&(i.error=e.error instanceof Error?e.error.message:String(e.error)),this.flowTraceSteps.push(i)}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,this.lastRecordingFrameStats=null,new Error(t?.error||"recording stop failed");this.lastRecordingStartedAtMs=this.recordingStartedAtMs,this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.lastRecordingFrameStats=t.frameStats??null,this.recordingStartedAtMs=null;let i=[],r=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${r}, chunk: 2097152 })`);if(!l||(i.push(Buffer.from(l.data,"base64")),r=l.offset,l.done))break}if(i.length===0)throw new Error("recording requested but no video buffer was produced");S.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=b.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return S.writeFileSync(s,Buffer.concat(i)),s}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await f(t);return}let i=await ye({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(i.settled?` [flow] recording tail settled in ${i.elapsed}ms`:` [flow] recording tail reached ${i.elapsed}ms budget`)}async findElement(e){if(e.childOf!=null||typeof e.index=="number")return this.findElementScoped(e);let t=!!e.text&&/[.*+?^$()[\]{}|\\]/.test(e.text);return this.evaluate(`(async () => {
|
|
220
220
|
const test = window.__sootsimTest
|
|
221
221
|
if (!test) return null
|
|
222
222
|
let node = null
|
|
@@ -386,7 +386,7 @@ process.stdin.on('end', async () => {
|
|
|
386
386
|
visible: !!keyboard?.isVisible?.(),
|
|
387
387
|
focused: !!test?.isTextInputFocused?.(),
|
|
388
388
|
}
|
|
389
|
-
})()`);if(!t?.visible&&!t?.focused){await f(80);return}await f(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:"Backspace"});await f(100)}async waitFor(e){let t=Date.now()+(e.timeout||Z);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let i=await this.findElement(e),r=i?` (matched node y=${Math.round(i.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||Z}ms${r}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=
|
|
389
|
+
})()`);if(!t?.visible&&!t?.focused){await f(80);return}await f(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:"Backspace"});await f(100)}async waitFor(e){let t=Date.now()+(e.timeout||Z);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let i=await this.findElement(e),r=i?` (matched node y=${Math.round(i.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||Z}ms${r}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Bt(e),i=Dt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});S.mkdirSync(b.dirname(i),{recursive:!0});let r=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};r&&r!=="full"&&(o.layers=r);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let u=await this.readCurrentDeviceModel();if(!u)throw new Error("could not read current device model for framed screenshot");let p=await rt(l,u);S.writeFileSync(i,p),console.log(`[flow] screenshot: ${i} (frame: ${u})`);return}S.writeFileSync(i,l),console.log(`[flow] screenshot: ${i}`)}async readCurrentDeviceModel(){let e=await this.bridge.send({type:"call",simId:this.opts.simId,path:"SootSim.bridges.settings.get",args:[]}),t=e&&typeof e.deviceModel=="string"?e.deviceModel:null;return!t||!(t in Oe)?null:t}async captureFailureScreenshot(e){S.mkdirSync(b.dirname(e),{recursive:!0});let i=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");S.writeFileSync(e,Buffer.from(i,"base64"))}async captureFailureBundle(e,t){S.mkdirSync(e,{recursive:!0});let i=(p,m)=>{try{S.writeFileSync(b.join(e,p),m)}catch{}},r=async p=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:p})}catch{return null}},o=await r(`(async () => {
|
|
390
390
|
const out = {
|
|
391
391
|
simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
|
|
392
392
|
url: location.href,
|
|
@@ -441,7 +441,7 @@ process.stdin.on('end', async () => {
|
|
|
441
441
|
${e.steps||12}, ${e.stepMs||16}
|
|
442
442
|
)
|
|
443
443
|
return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
|
|
444
|
-
})()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await f(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){let t=Math.max(0,Math.round(e));if(t<=0)return;(await
|
|
444
|
+
})()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await f(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){let t=Math.max(0,Math.round(e));if(t<=0)return;(await ye({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:32,stablePolls:2,strict:!0})).settled&&this.markVisualSettled()}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),i=e.direction?.toUpperCase()||"DOWN",r=i==="DOWN"?"UP":i==="UP"?"DOWN":i;for(;Date.now()<t;){let o=await this.findElement({text:e.element});if(o&&o.absolutePosition.y>=0&&o.absolutePosition.y+o.layout.height>0&&o.absolutePosition.y<N-50){if(e.centerElement){let a=N/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),u=s>0?a-l:a+l;await this.drag(Q/2,a,Q/2,u,10,16)}}return}await this.swipe(r,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||Z);for(;Date.now()<t;){let i=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,r=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(i&&r)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let r=!1;for(let o=0;o<3&&!r;o++)try{r=await this.evaluate(he(!0),2e4)}catch{await f(1e3)}r||console.warn(" warn: tenant storage clear did not ack \u2014 hard-reloading anyway (worker reset follows)")}await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId()}async softReloadGuestApp(e){if(!await this.evaluate(he(e),12e4))throw new Error("guest app soft reload bridge unavailable")}async rearmCaptureAfterRuntimeReload(){if(!this.recordingEnabled&&!this.profilingEnabled)return;let e=Date.now()+1e4,t=null;for(;Date.now()<e;){await this.refreshSimId();try{this.recordingEnabled&&await this.ensureRecordingStarted(),this.profilingEnabled&&await this.startProfile();return}catch(i){t=i,await f(250)}}throw new Error(`capture re-arm failed after app reload: ${t instanceof Error?t.message:String(t)}`)}async launchApp(e){await this.refreshSimId(),e&&typeof e=="object"&&e.arguments&&console.log("[flow] launchApp.arguments ignored (sootsim has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),i=Mt(e,"resetRuntime");if(!this.firstLaunchDone&&!t){if(this.firstLaunchDone=!0,i){let r=await V(this.bridge).catch(()=>null),o=r?.state==="home"&&r.activeApp==null;await this.softReloadGuestApp(!1),await this.waitForTree(12e4),o&&(await pe(this.bridge,"goHome",1e3),await this.waitForShellHome(1e3)),await this.launchShellAppFromHomeIfNeeded(e,o?{...r??{},state:"home",activeApp:null}:null)}else await this.launchShellAppFromHomeIfNeeded(e);await this.waitForTree(3e4)}else if(this.firstLaunchDone=!0,await this.reloadGuestApp(t),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(r){console.warn(` warn: onAfterLaunch hook threw: ${r instanceof Error?r.message:r}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
|
|
445
445
|
requestAnimationFrame(() => {
|
|
446
446
|
requestAnimationFrame(() => {
|
|
447
447
|
requestAnimationFrame(() => {
|
|
@@ -449,7 +449,7 @@ process.stdin.on('end', async () => {
|
|
|
449
449
|
})
|
|
450
450
|
})
|
|
451
451
|
})
|
|
452
|
-
})`),this.markVisualSettled()}catch{await f(180),this.markVisualSettled()}}markVisualSettled(){this.lastVisualSettledAtMs=Date.now()}hasFreshVisualSettle(){return Date.now()-this.lastVisualSettledAtMs<750}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(
|
|
452
|
+
})`),this.markVisualSettled()}catch{await f(180),this.markVisualSettled()}}markVisualSettled(){this.lastVisualSettledAtMs=Date.now()}hasFreshVisualSettle(){return Date.now()-this.lastVisualSettledAtMs<750}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(xe(e)){let i=G(e,"appId")||G(e,"id");if(i)return i}return Ot(t)||"connect"}async waitForShellAppLaunched(e,t){let i=Date.now()+t,r=null;for(;Date.now()<i;){try{r=await V(this.bridge)}catch{r=null}if(r?.state==="app"&&r.activeApp===e&&r.showSwitcher===!1&&typeof r.launchProgress=="number"&&r.launchProgress>=.98)return;await f(16)}}async waitForShellHome(e){let t=Date.now()+e;for(;Date.now()<t;){let i=await V(this.bridge).catch(()=>null);if(i?.state==="home"&&i.activeApp==null&&i.showSwitcher===!1)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e,t){let i=null;if(t)i=t;else try{i=await V(this.bridge)}catch{return!1}if(i?.state!=="home"||i.activeApp!=null)return!1;let r=this.resolveShellLaunchAppId(e,i);return this.recordingEnabled&&await this.ensureRecordingStarted(),await pe(this.bridge,"launchApp",1e3,r),await this.waitForShellAppLaunched(r,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
|
|
453
453
|
if (!window.__sootsimShellPerf) {
|
|
454
454
|
return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
|
|
455
455
|
}
|
|
@@ -460,7 +460,7 @@ process.stdin.on('end', async () => {
|
|
|
460
460
|
return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
|
|
461
461
|
}
|
|
462
462
|
return await window.__sootsimShellPerf.stop()
|
|
463
|
-
})()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,i=await this.findElement(t);if(!i)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let r=i.text??i.testID??"";this.js.setCopiedText(r),this.js.putEnv("maestroCopiedText",r),console.log(`[flow] copied text: ${JSON.stringify(r)}`)}evalScript(e){let i=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);i!==void 0&&i!==""&&console.log("[flow] evalScript ->",i)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let i=b.resolve(this.opts.flowDir,t.file),r=S.readFileSync(i,"utf8");this.js.evaluate(r,{env:t.env}),console.log(`[flow] runScript: ${t.file} done`)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");let i=await this.callTest("openDeepLink",t);if(!i?.ok)throw new Error(`openLink failed: ${i?.error||"no test bridge"}`);await f(300)}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()===this.js.maestro.platform.toLowerCase():e.true!==void 0?nt(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let i=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),r=i?i[1]:void 0;return!!(r&&typeof r=="object"&&"optional"in r&&r.optional)}async runStep(e,t){let i=typeof e=="string"?ot(e):e,r=Object.keys(i).find(l=>l!=="when")||Object.keys(i)[0];console.log(`[flow] step ${t+1}: ${r}`);let o=Date.now(),a=this.flowStepTargetLabel(i,r),s;try{s=this.js.interpolateStep(i),a=this.flowStepTargetLabel(s,r)??a}catch(l){if(this.isOptional(i)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:r,target:i[r]},this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}if(s.when&&!await this.evaluateWhen(s.when)){console.log("[flow] (when: predicate false, skipped)"),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),u=1e4,p=this.runStepInner(s);if(l)await p;else{let x=null,g=new Promise((k,_)=>{x=setTimeout(()=>{_(new Error(`step watchdog: ${r} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{await Promise.race([p,g])}finally{x&&clearTimeout(x)}}let m=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!m&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"success"})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:r,target:s[r]},this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.longPressOn)await this.longPressOn(e.longPressOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else if(e.takeScreenshot)await this.takeScreenshot(e.takeScreenshot);else if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo){let t=typeof e.scrollTo.nodeId=="number"?{nodeId:e.scrollTo.nodeId}:e.scrollTo.id;if(!t)throw new Error("scrollTo requires id or nodeId");await this.scrollTo(t,e.scrollTo.x,e.scrollTo.y)}else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd){let t=e.waitForAnimationToEnd;await this.waitForAnimationToEnd(typeof t=="number"?t:typeof t=="object"&&typeof t.timeout=="number"?t.timeout:2e3)}else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await f(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat&&Array.isArray(e.repeat.commands)){let t=e.repeat.times,i=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(i))throw new Error(`repeat.times is not a number: ${t}`);let r=e.repeat.when??e.repeat.condition,o=async()=>r?this.evaluateWhen(r):!0,a=r?i:Math.min(i,1e3),s=0;for(;s<a&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);s++}}else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")this.evalScript(e.evalScript);else if(e.runScript){let t=e.runScript,i=typeof t=="string"?void 0:t.when;if(i&&!await this.evaluateWhen(i)){console.log("[flow] runScript skipped (when predicate false)");return}this.runScript(t)}else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let t=e.runFlow,i=typeof t=="string"?t:t.file,r=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,a=typeof t=="string"?void 0:t.when;if(a&&!await this.evaluateWhen(a)){console.log(`[flow] runFlow skipped (when predicate false): ${i??"inline commands"}`);return}if(!i&&!r)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[s,l]of Object.entries(o))this.js.putEnv(s,l);if(i){let s=b.resolve(this.opts.flowDir,i),l=S.readFileSync(s,"utf8"),u=this.opts.flowDir;this.opts.flowDir=b.dirname(s);try{await this.runFlow(Bt(l))}finally{this.opts.flowDir=u}}else if(r)for(let s=0;s<r.length;s++)await this.runStep(r[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}liveStatus=null;async runFlow(e){let t=[],i=[],r=[];for(let a of e){let s=Object.keys(a);if(s.length===1&&s[0]==="onFlowStart"&&Array.isArray(a.onFlowStart)){t.push(...a.onFlowStart);continue}if(s.length===1&&s[0]==="onFlowComplete"&&Array.isArray(a.onFlowComplete)){i.push(...a.onFlowComplete);continue}r.push(a)}if(this.liveStatus&&await this.liveStatus.plan(r.map((a,s)=>{let l=typeof a=="string"?ot(a):a,u=Object.keys(l).find(p=>p!=="when")??Object.keys(l)[0];return{index:s,name:u,target:this.flowStepTargetLabel(l,u)}})),t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let a=0;a<t.length;a++)await this.runStep(t[a],a)}let o=null;try{await this.runFlowBody(r)}catch(a){o=a instanceof Error?a:new Error(String(a))}if(i.length>0){console.log(`[flow] onFlowComplete (${i.length} steps)`);for(let a=0;a<i.length;a++)try{await this.runStep(i[a],a)}catch(s){console.warn(`[flow] onFlowComplete step ${a+1} failed: ${s instanceof Error?s.message:s}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let i=e[t],r=typeof i.wait=="number"?i.wait:0,o=typeof i.waitFor?.timeout=="number"?i.waitFor.timeout:0,a=Math.max(6e4,r+15e3,o+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let s=Date.now(),l=async(u,p)=>{if(!this.liveStatus)return;let m=this.flowTraceSteps[this.flowTraceSteps.length-1],x=m&&m.stepIndex===t&&m.startedAtMs>=s;await this.liveStatus.step(t,u?"failure":x&&m.status==="skipped"?"skipped":"success",{durationMs:Date.now()-s,error:u?p instanceof Error?p.message.slice(0,300):String(p).slice(0,300):x&&m.error||void 0})};try{i.runFlow||i.launchApp?await this.runStep(i,t):await Promise.race([this.runStep(i,t),new Promise((u,p)=>setTimeout(()=>p(new Error(`step ${t+1} (${Object.keys(i)[0]}) exceeded ${a}ms deadline`)),a))])}catch(u){throw await l(!0,u),u}await l(!1)}}};var te=class{constructor(e,t){this.bridge=e;this.flowName=t}disabled=!1;paused=!1;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async push(e){if(!this.disabled)try{let t=await this.bridge.send({type:"flowStatus",status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=t?.control?.paused===!0}catch(t){this.disabled=!0,console.log(`[flow] live status unavailable (${t instanceof Error?t.message.slice(0,120):t}) \u2014 continuing without the devtools rail`)}}async plan(e){await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,i){await this.push({phase:"step",state:"running",step:{index:e,status:t,...i}})}async end(e){await this.push({phase:"end",state:e})}async waitWhilePaused(){if(!this.disabled)for(;this.paused;){for(console.log("[flow] paused from devtools \u2014 waiting\u2026");this.paused&&!this.disabled;)await new Promise(e=>setTimeout(e,400)),await this.push({phase:"heartbeat",state:"paused"});this.disabled||console.log("[flow] resumed")}}};var xe=null;function Fi(){return xe}var Te=[];function Ii(){return Te}async function Lt(n){if(!n)return"";let e=n.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let i=(await De()).find(r=>r.name.toLowerCase()===e.toLowerCase());return i?String(i.preferredPort):e}async function Ct(){let n=await Be(),e=n.find(i=>i.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=n[0];return t?`http://localhost:${t.port}/__soot/`:null}async function at(n){xe=null,Te=[],(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
|
|
463
|
+
})()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,i=await this.findElement(t);if(!i)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let r=i.text??i.testID??"";this.js.setCopiedText(r),this.js.putEnv("maestroCopiedText",r),console.log(`[flow] copied text: ${JSON.stringify(r)}`)}evalScript(e){let i=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);i!==void 0&&i!==""&&console.log("[flow] evalScript ->",i)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let i=b.resolve(this.opts.flowDir,t.file),r=S.readFileSync(i,"utf8");this.js.evaluate(r,{env:t.env}),console.log(`[flow] runScript: ${t.file} done`)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");let i=await this.callTest("openDeepLink",t);if(!i?.ok)throw new Error(`openLink failed: ${i?.error||"no test bridge"}`);await f(300)}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()===this.js.maestro.platform.toLowerCase():e.true!==void 0?ot(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let i=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),r=i?i[1]:void 0;return!!(r&&typeof r=="object"&&"optional"in r&&r.optional)}async runStep(e,t){let i=typeof e=="string"?st(e):e,r=Object.keys(i).find(l=>l!=="when")||Object.keys(i)[0];console.log(`[flow] step ${t+1}: ${r}`);let o=Date.now(),a=this.flowStepTargetLabel(i,r),s;try{s=this.js.interpolateStep(i),a=this.flowStepTargetLabel(s,r)??a}catch(l){if(this.isOptional(i)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:r,target:i[r]},this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}if(s.when&&!await this.evaluateWhen(s.when)){console.log("[flow] (when: predicate false, skipped)"),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),u=1e4,p=this.runStepInner(s);if(l)await p;else{let x=null,g=new Promise((P,_)=>{x=setTimeout(()=>{_(new Error(`step watchdog: ${r} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{await Promise.race([p,g])}finally{x&&clearTimeout(x)}}let m=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!m&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"success"})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:r,target:s[r]},this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.longPressOn)await this.longPressOn(e.longPressOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else if(e.takeScreenshot)await this.takeScreenshot(e.takeScreenshot);else if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo){let t=typeof e.scrollTo.nodeId=="number"?{nodeId:e.scrollTo.nodeId}:e.scrollTo.id;if(!t)throw new Error("scrollTo requires id or nodeId");await this.scrollTo(t,e.scrollTo.x,e.scrollTo.y)}else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd){let t=e.waitForAnimationToEnd;await this.waitForAnimationToEnd(typeof t=="number"?t:typeof t=="object"&&typeof t.timeout=="number"?t.timeout:2e3)}else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await f(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat&&Array.isArray(e.repeat.commands)){let t=e.repeat.times,i=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(i))throw new Error(`repeat.times is not a number: ${t}`);let r=e.repeat.when??e.repeat.condition,o=async()=>r?this.evaluateWhen(r):!0,a=r?i:Math.min(i,1e3),s=0;for(;s<a&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);s++}}else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")this.evalScript(e.evalScript);else if(e.runScript){let t=e.runScript,i=typeof t=="string"?void 0:t.when;if(i&&!await this.evaluateWhen(i)){console.log("[flow] runScript skipped (when predicate false)");return}this.runScript(t)}else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let t=e.runFlow,i=typeof t=="string"?t:t.file,r=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,a=typeof t=="string"?void 0:t.when;if(a&&!await this.evaluateWhen(a)){console.log(`[flow] runFlow skipped (when predicate false): ${i??"inline commands"}`);return}if(!i&&!r)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[s,l]of Object.entries(o))this.js.putEnv(s,l);if(i){let s=b.resolve(this.opts.flowDir,i),l=S.readFileSync(s,"utf8"),u=this.opts.flowDir;this.opts.flowDir=b.dirname(s);try{await this.runFlow(Lt(l))}finally{this.opts.flowDir=u}}else if(r)for(let s=0;s<r.length;s++)await this.runStep(r[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}liveStatus=null;async runFlow(e){let t=[],i=[],r=[];for(let a of e){let s=Object.keys(a);if(s.length===1&&s[0]==="onFlowStart"&&Array.isArray(a.onFlowStart)){t.push(...a.onFlowStart);continue}if(s.length===1&&s[0]==="onFlowComplete"&&Array.isArray(a.onFlowComplete)){i.push(...a.onFlowComplete);continue}r.push(a)}if(this.liveStatus&&await this.liveStatus.plan(r.map((a,s)=>{let l=typeof a=="string"?st(a):a,u=Object.keys(l).find(p=>p!=="when")??Object.keys(l)[0];return{index:s,name:u,target:this.flowStepTargetLabel(l,u)}})),t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let a=0;a<t.length;a++)await this.runStep(t[a],a)}let o=null;try{await this.runFlowBody(r)}catch(a){o=a instanceof Error?a:new Error(String(a))}if(i.length>0){console.log(`[flow] onFlowComplete (${i.length} steps)`);for(let a=0;a<i.length;a++)try{await this.runStep(i[a],a)}catch(s){console.warn(`[flow] onFlowComplete step ${a+1} failed: ${s instanceof Error?s.message:s}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let i=e[t],r=typeof i.wait=="number"?i.wait:0,o=typeof i.waitFor?.timeout=="number"?i.waitFor.timeout:0,a=Math.max(6e4,r+15e3,o+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let s=Date.now(),l=async(u,p)=>{if(!this.liveStatus)return;let m=this.flowTraceSteps[this.flowTraceSteps.length-1],x=m&&m.stepIndex===t&&m.startedAtMs>=s;await this.liveStatus.step(t,u?"failure":x&&m.status==="skipped"?"skipped":"success",{durationMs:Date.now()-s,error:u?p instanceof Error?p.message.slice(0,300):String(p).slice(0,300):x&&m.error||void 0})};try{i.runFlow||i.launchApp?await this.runStep(i,t):await Promise.race([this.runStep(i,t),new Promise((u,p)=>setTimeout(()=>p(new Error(`step ${t+1} (${Object.keys(i)[0]}) exceeded ${a}ms deadline`)),a))])}catch(u){throw await l(!0,u),u}await l(!1)}}};var te=class{constructor(e,t){this.bridge=e;this.flowName=t}disabled=!1;paused=!1;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async push(e){if(!this.disabled)try{let t=await this.bridge.send({type:"flowStatus",status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=t?.control?.paused===!0}catch(t){this.disabled=!0,console.log(`[flow] live status unavailable (${t instanceof Error?t.message.slice(0,120):t}) \u2014 continuing without the devtools rail`)}}async plan(e){await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,i){await this.push({phase:"step",state:"running",step:{index:e,status:t,...i}})}async end(e){await this.push({phase:"end",state:e})}async waitWhilePaused(){if(!this.disabled)for(;this.paused;){for(console.log("[flow] paused from devtools \u2014 waiting\u2026");this.paused&&!this.disabled;)await new Promise(e=>setTimeout(e,400)),await this.push({phase:"heartbeat",state:"paused"});this.disabled||console.log("[flow] resumed")}}};var Te=null;function Ii(){return Te}var Ee=[];function $i(){return Ee}async function Ct(n){if(!n)return"";let e=n.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let i=(await Be()).find(r=>r.name.toLowerCase()===e.toLowerCase());return i?String(i.preferredPort):e}async function Nt(){let n=await Le(),e=n.find(i=>i.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=n[0];return t?`http://localhost:${t.port}/__soot/`:null}async function lt(n){Te=null,Ee=[],(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
|
|
464
464
|
sootsim flow \u2014 run flows or manage a draft
|
|
465
465
|
|
|
466
466
|
usage:
|
|
@@ -540,28 +540,28 @@ flow extension:
|
|
|
540
540
|
takeScreenshot:
|
|
541
541
|
path: marketing/hero
|
|
542
542
|
withFrame: true
|
|
543
|
-
`),process.exit(0));let e=n[0]
|
|
543
|
+
`),process.exit(0));let e=n[0];k.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>n.find((d,y)=>n[y-1]===h),i=n.includes("--profile"),r=n.includes("--headed"),o=n.includes("--new")||r,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",u=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,p=t("--device")?.trim()||"",m=n.includes("--slow")?+(t("--slow")||"500"):0,x=n.includes("--electron"),g=n.includes("--preview"),P=await Qe(t("--preview-origin")),_=t("--preview-public-origin"),dt=n.includes("--preview-open"),Fe=t("--owner")?.trim()||"",Ie=t("--repo")?.trim()||"",H=t("--billing-kind")?.trim()||"";H&&H!=="test_run"&&(console.error(` error: invalid --billing-kind: ${H}`),process.exit(1));let ct=n.flatMap((h,d)=>n[d-1]==="--replace"?["--replace",h]:[]),ut=n.flatMap((h,d)=>n[d-1]==="--remap"?["--remap",h]:[]),A=n.includes("--record")||g,pt=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):A?g?6e3:2e3:0,ht=k.readFileSync(e,"utf8"),{frontmatter:E,steps:R}=fe(ht);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let W=p||E.device||"",z=x||E.electron===!0,ft=E.app===void 0||E.app===null?"":typeof E.app=="number"?String(E.app):E.app,re=await Ct(ft),$e={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless","--headed"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--remap","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver","--billing-kind","--owner","--repo"]},v=ce(n,$e),mt=t("--url")||"";z&&!Ve()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let ke=z?"desktop companion":"bridge",gt=re?` | target: ${re}`:"";console.log(`
|
|
544
544
|
sootsim flow \u2014 ${w.basename(e)}
|
|
545
|
-
${
|
|
546
|
-
`),g&&
|
|
545
|
+
${R.length} steps | ${ke}${gt}${A?" | recording":""}${i?" | profiling":""}${m?` | ${m}ms delay`:""}
|
|
546
|
+
`),g&&Me({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:R.length,mode:ke,electron:z,record:A,profile:i,previewOrigin:P}});let I=mt||re||"",ne=o||z&&v.simIdSource!=="flag",Pe=t("--driver")||"",oe=!1,se=new Set,Ae=!1;if(!I&&!ne&&v.simIdSource==="none"){let h=je(v);try{let d=await h.listSims(),y=d.find(L=>L.isPrimary&&L.readyState==="open"),$=d.find(L=>L.readyState==="open"),U=y??$;U&&(Ae=!0,console.log(` reusing active sim: ${U.id}`))}catch{}finally{h.close()}}if(!I&&!Ae&&(ne||v.simIdSource==="none")){let h=await Nt();h||(console.error(" error: no current sim and no sootsim target found"),await le(),process.exit(1)),I=h}if(I&&W){let h=new URL(await Je(I));h.searchParams.set("device",W),I=h.toString()}if(I){let h=[I];if(h.push(...ct),h.push(...ut),ne&&h.push("--new"),h.push("--no-describe"),v.simIdSource==="flag"&&v.simId&&h.push("--sim",v.simId),Pe&&(h.push("--driver",Pe),oe=!0),n.includes("--headless")&&!r&&h.push("--headless"),await ze(h,{port:v.wsPort,timeoutMs:v.commandTimeoutMs}),oe){let d=de();d&&se.add(d)}}let D=ce(n,$e),K=D.simIdSource==="flag"?D.simId:de()||D.simId,wt=D.simIdSource==="flag"?"flag":K?"saved":"none",F=ue(D.wsPort,{commandTimeoutMs:D.commandTimeoutMs,simId:K,simIdSource:wt}),c,Re=async()=>{if(!W)return!1;let h=await F.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof h=="string"&&h.length>0){let d=new URL(h);d.searchParams.set("device",W),c.setSimRouteHint(d.toString())}return!!await F.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",W]})};if(c=new ee(F,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:u,simId:K,recordingOutputDir:A?a:void 0,recordingFormat:g?"mp4":"webm",billingOriginOverride:g?P:void 0,allowGitHubRecording:g,requireRecordingEntitlement:g,onAfterLaunch:async()=>{await Re()&&await c.waitForTree(12e4),g&&await F.send({type:"evaluate",simId:c.simId,code:`(() => {
|
|
547
547
|
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
548
548
|
return r?.start?.() ?? false
|
|
549
|
-
})()`})}}),m&&(c.stepDelay=m),c.liveStatus=new te(F,w.basename(e)),c.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),E.env&&typeof E.env=="object")for(let[h,d]of Object.entries(E.env))c.js.putEnv(h,d);let
|
|
549
|
+
})()`})}}),m&&(c.stepDelay=m),c.liveStatus=new te(F,w.basename(e)),c.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),E.env&&typeof E.env=="object")for(let[h,d]of Object.entries(E.env))c.js.putEnv(h,d);let M=null,T=null,B=null,O=null,ae=null,j=0,q=!!R[0]?.launchApp;try{q||await c.waitForTree(12e4),await Re()&&!q&&await c.waitForTree(12e4),g&&!q&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),A&&(q?c.prepareRecording():await c.startRecording()),i&&await c.startProfile(),g&&(await F.send({type:"evaluate",simId:c.simId,code:`(() => {
|
|
550
550
|
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
551
551
|
return r?.start?.() ?? false
|
|
552
|
-
})()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(
|
|
552
|
+
})()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(R),i&&(M=await c.stopProfile()),await c.waitForRecordingTail({maxMs:pt,smart:g}),A&&(T=await c.stopRecording(),B=c.getLastRecordingDurationMs()),g&&(O=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
|
|
553
553
|
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
554
554
|
return r?.stop?.() ?? []
|
|
555
|
-
})()`}),console.log(` captured ${
|
|
556
|
-
+ completed (${
|
|
555
|
+
})()`}),console.log(` captured ${O.length} replay events`));let d=R.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
|
|
556
|
+
+ completed (${R.length} steps)`),d>0&&console.log(` screenshots: ${d} \u2192 ${s}`),M&&at(M),T&&console.log(` video: ${T}`),console.log()}catch(h){if(i&&!M)try{M=await c.stopProfile()}catch{}if(A&&!T)try{T=await c.stopRecording(),B=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}if(g&&!O)try{O=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
|
|
557
557
|
const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
|
|
558
558
|
return r?.stop?.() ?? []
|
|
559
|
-
})()`}),console.log(` captured ${
|
|
559
|
+
})()`}),console.log(` captured ${O.length} partial replay events`)}catch(d){console.warn(` event recorder stop failed: ${d?.message||String(d)}`)}console.error(`
|
|
560
560
|
x failed: ${h.message}
|
|
561
|
-
`),
|
|
562
|
-
preparing preview upload\u2026`);let
|
|
561
|
+
`),M&&(console.log(" partial profile:"),at(M)),T&&console.log(` partial video: ${T}`);try{let d=c.lastFailedStep,y=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",$=w.join(s,y);await c.captureFailureBundle($,{error:h,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),ae=$,console.log(` failure bundle: ${$}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(d){try{let y=w.join(s,"error.png");await c.captureFailureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await Ue(F,{errorsCommand:`sootsim get errors 5${c.simId?` --sim ${c.simId}`:""}`,warningsCommand:`sootsim get warnings 5${c.simId?` --sim ${c.simId}`:""}`,requestsCommand:`sootsim get requests 5${c.simId?` --sim ${c.simId}`:""}`}),j=1}if(await c.liveStatus?.end(j===0?"passed":"failed"),g&&(j===0||T||O))try{let h=await Wt(O??[]),d=["--origin",P,"--events",h];_&&d.push("--public-origin",_),T&&d.push("--video",T),T&&B&&Number.isFinite(B)&&(d.push("--video-duration-ms",String(Math.round(B))),d.push("--recorded-duration-ms",String(Math.round(B))));let y=c.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&d.push("--recording-started-at-ms",String(Math.round(y))),v.wsPort&&d.push("--port",String(v.wsPort)),c.simId&&d.push("--sim",c.simId),dt&&d.push("--open"),Fe&&d.push("--owner",Fe),Ie&&d.push("--repo",Ie),H&&d.push("--billing-kind",H),console.log(`
|
|
562
|
+
preparing preview upload\u2026`);let $=c.getFlowTraceSteps();$.length>0&&d.push("--timeline-events",await jt($)),ae&&d.push("--failure-bundle",ae);let U=c.getLastRecordingFrameStats();U&&d.push("--trace-frame-stats",await Ut(U));let{runUpload:L}=await import("./upload-X2BRKPBJ.js");Te=await L(d,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),j=1}return Ee=c.getFlowTraceSteps(),F.close(),oe?(c.simId&&se.add(c.simId),await Ht(v.wsPort,v.commandTimeoutMs,[...se])):c.simId&&c.simId!==K&&De(c.simId),await le(),j}async function Ht(n,e,t){let i=[...new Set(t.filter(Boolean))];if(i.length===0)return;let r=ue(n,{commandTimeoutMs:e});try{let o=await r.listSims(),a=i.filter(l=>o.some(u=>u.id===l&&u.readyState==="open"));if(a.length===0)return;let s=await Ke(r,n,e,a);await Ge(o,a),s.closed.length>0&&console.log(` closed flow sim(s): ${s.closed.join(", ")}`),s.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${s.remaining.join(", ")}`)}catch(o){console.warn(` warn: failed to close flow sim(s): ${o instanceof Error?o.message:String(o)}`)}finally{r.close()}}async function Wt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
|
|
563
563
|
`)+(n.length?`
|
|
564
|
-
`:""),i=e(Buffer.from(t,"utf8")),r=w.join(ie(),`sootsim-events-${Date.now()}.jsonl.gz`);return
|
|
564
|
+
`:""),i=e(Buffer.from(t,"utf8")),r=w.join(ie(),`sootsim-events-${Date.now()}.jsonl.gz`);return k.writeFileSync(r,i),console.log(` events: ${n.length} written to ${r} (${i.length} bytes gz)`),r}async function jt(n){let{gzipSync:e}=await import("zlib"),t=n.map((a,s)=>({schemaVersion:1,t:a.endedAtMs,seq:1e6+s,context:"host",kind:"flow-step",id:`flow-step-${a.stepIndex}`,data:{stepIndex:a.stepIndex,stepNumber:a.stepIndex+1,stepName:a.stepName,...a.targetLabel?{targetLabel:a.targetLabel}:{},status:a.status,durationMs:a.durationMs,startedAtMs:a.startedAtMs,endedAtMs:a.endedAtMs,...a.error?{error:a.error}:{}}})),i=t.map(a=>JSON.stringify(a)).join(`
|
|
565
565
|
`)+`
|
|
566
|
-
`,r=e(Buffer.from(i,"utf8")),o=w.join(ie(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return
|
|
567
|
-
validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}
|
|
566
|
+
`,r=e(Buffer.from(i,"utf8")),o=w.join(ie(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return k.writeFileSync(o,r),console.log(` flow trace: ${t.length} step events written to ${o} (${r.length} bytes gz)`),o}async function Ut(n){let e=w.join(ie(),`sootsim-frame-stats-${Date.now()}.json`);return k.writeFileSync(e,JSON.stringify(n)),console.log(` frame stats: written to ${e}`),e}async function Vt(n){let e=n[0],t=i=>n.find((r,o)=>n[o-1]===i);switch(e){case"start":{let{path:i,state:r}=Ye();console.log(" flow draft started"),console.log(` session: ${i}`),console.log(` steps: ${r.steps.length}`);return}case"keep":case"good":{let i=we();if(i.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!i.kept){console.log(" no pending action to keep");return}console.log(` kept: ${i.candidate.summary}`),console.log(` steps: ${i.stepCount}`);return}case"end":{let i=t("--output")||(n[1]&&!n[1].startsWith("-")?n[1]:void 0),r=n.includes("--validate")||n.includes("--video"),o=n.includes("--video"),a=we();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=Ze(i||(r?Gt():void 0));if(s.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!s.valid){console.error(" flow draft is not valid:");for(let l of s.issues)console.error(` - ${l}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim flow start` to reset"),process.exit(1)}if(r){let l=zt(n,s.outputPath),u=await lt(l);if(u!==0){console.error(`
|
|
567
|
+
validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}ge(),console.log(` flow draft validated (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath&&console.log(` saved: ${s.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(ge(),console.log(` flow draft ended (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath){console.log(` saved: ${s.outputPath}`),console.log(` next: sootsim flow ${s.outputPath} --record`);return}console.log(""),process.stdout.write(s.yaml);return}case"validate":{let i=n[1];(!i||i.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let r=me(i);if(r.length>0){console.error(` x ${i} failed validation:`);for(let o of r)console.error(` - ${o}`);process.exit(1)}console.log(` + ${i} looks valid`);return}}}function Jt(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function ki(n){let e=Jt(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Vt(e),0;let i=await lt(e);return i!==0&&(process.exitCode=i),i}function at(n){console.log(""),Xe(n)}function Gt(){return w.join(ie(),`sootsim-flow-draft-${Date.now()}.yaml`)}function zt(n,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let i=1;i<n.length;i++){let r=n[i];if(!(r==="--validate"||r==="--video")){if(r==="--output"){i+=1;continue}i===1&&!r.startsWith("-")||t.push(r)}}return!t.includes("--record")&&n.includes("--video")&&t.push("--record"),t}export{rt as a,Ft as b,Ii as c,$i as d,Nt as e,lt as f,Jt as g,ki as h};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{o as d}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{o as d}from"./chunk-ZGM7N2AV.js";import{chmodSync as S,existsSync as f,mkdirSync as k,readFileSync as A,rmSync as i,writeFileSync as y}from"node:fs";import{dirname as c,join as D,resolve as m}from"node:path";var s=1,p="SOOTSIM_SHARED_AUTH_FILE",u="https://sootbean.com";function w(){let t=process.env[p];return t?.trim()?c(m(t)):d()}function a(){let t=process.env[p];return t?.trim()?m(t):D(w(),"desktop-auth.json")}function g(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.id!="string"||!e.id.trim()?null:{id:e.id.trim(),name:typeof e.name=="string"?e.name:void 0,email:typeof e.email=="string"?e.email:void 0,image:typeof e.image=="string"?e.image:void 0,githubUsername:typeof e.githubUsername=="string"?e.githubUsername:void 0,teams:Array.isArray(e.teams)?e.teams.map(r=>{if(!r||typeof r!="object")return null;let n=r;return typeof n.id!="string"||typeof n.name!="string"?null:{id:n.id,name:n.name,role:n.role==="owner"?"owner":"member",githubOrg:typeof n.githubOrg=="string"?n.githubOrg:null}}).filter(r=>!!r):void 0}}function v(t){if(!t||typeof t!="object")return null;let e=t;if(e.version!==s||typeof e.token!="string"||!e.token.trim())return null;let r=typeof e.origin=="string"&&e.origin.trim()?e.origin.trim():u,n=e.source==="cli"||e.source==="electron"||e.source==="browser"||e.source==="unknown"?e.source:"unknown",o=typeof e.updatedAt=="string"&&e.updatedAt?e.updatedAt:new Date().toISOString(),h=typeof e.validatedAt=="string"&&e.validatedAt?e.validatedAt:void 0;return{version:s,token:e.token.trim(),user:g(e.user),origin:r,source:n,updatedAt:o,validatedAt:h}}function b(){let t=a();if(!f(t))return null;try{let e=JSON.parse(A(t,"utf8")),r=v(e);return r||(i(t,{force:!0}),null)}catch{return i(t,{force:!0}),null}}function O(t){let e=a();k(c(e),{recursive:!0});let r={version:s,token:t.token.trim(),user:t.user?g(t.user):null,origin:t.origin?.trim()||u,source:t.source,updatedAt:t.updatedAt||new Date().toISOString(),validatedAt:t.validatedAt};y(e,JSON.stringify(r,null,2)+`
|
|
3
3
|
`);try{S(e,384)}catch{}return r}function l(){i(a(),{force:!0})}async function E(t){let e=b();if(!e?.token)return null;let r=t||e.origin||u;try{let n=await fetch(`${r.replace(/\/$/,"")}/api/auth/me`,{headers:{authorization:`Bearer ${e.token}`}});if(n.status===401)return l(),null;if(!n.ok)return e;let o=await n.json();return o.user?.id?O({token:e.token,user:o.user,origin:r,source:e.source,validatedAt:new Date().toISOString()}):(l(),null)}catch{return e}}export{b as a,O as b,l as c,E as d};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{j as n}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{j as n}from"./chunk-62AKBZTO.js";var i=[];for(let[t,e]of Object.entries(n))e.cliFlag&&i.push({name:`--${e.cliFlag}`,short:e.cliFlagShort?`-${e.cliFlagShort}`:void 0,key:t,type:e.type==="enum"?"string":e.type,description:e.description,options:e.options,default:e.default});var a=i;function g(){let t=[];for(let e of a){let s=e.short?`${e.short}, ${e.name}`:` ${e.name}`,o=e.options?` [${e.options.join("|")}]`:"",r=e.default!==void 0?` (default: ${e.default})`:"";t.push(` ${s.padEnd(24)}${e.description}${o}${r}`)}return t.join(`
|
|
3
3
|
`)}export{g as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
2
|
var c="sootsim-agent-prompt-v1";function r(n){return typeof n=="string"?n.trim():""}function m(n){let e=r(n.text);if(!e)return"";let t=r(n.displayText),s=r(n.inspectSummary),o=r(n.inspectTrace);return!!s||!!o||/[\r\n]/.test(e)||!!t&&t!==e?JSON.stringify({__sootsimAgentPrompt:c,text:e,displayText:t,inspectSummary:s,inspectTrace:o}):e}function u(n){let e=r(n);if(!e)return null;try{let t=JSON.parse(e);if(t.__sootsimAgentPrompt!==c)return{text:e};let s=r(typeof t.text=="string"?t.text:void 0);if(!s)return null;let o=r(typeof t.displayText=="string"?t.displayText:void 0),i=r(typeof t.inspectSummary=="string"?t.inspectSummary:void 0),p=r(typeof t.inspectTrace=="string"?t.inspectTrace:void 0);return{text:s,...o?{displayText:o}:{},...i?{inspectSummary:i}:{},...p?{inspectTrace:p}:{}}}catch{return{text:e}}}export{m as a,u as b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as E,b as D}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as E,b as D}from"./chunk-4NHPXU3X.js";import{H as T}from"./chunk-ZGM7N2AV.js";var N="sootsimConfig";function p(e){return!!e&&Object.keys(e).length>0}function $(e){return e?p(e.modules)||p(e.turboModules)||p(e.nativeModules)||p(e.env)||p(e.network?.remap)||p(e.settings)||p(e.initialState):!1}function j(e,t){let n=new URL(e);return $(t)?n.searchParams.set(N,JSON.stringify(t)):n.searchParams.delete(N),n.toString()}var me="/index.bundle?platform=ios&dev=true&hot=true&minify=false";function A(e){return/^https?:\/\//i.test(e)}function O(e){return e.endsWith(".bundle")}function H(e){process.env.SOOTSIM_PREVIEW_PROD_BUNDLE&&(e.searchParams.set("dev","false"),e.searchParams.set("minify","true"),e.searchParams.has("hot")&&e.searchParams.set("hot","false"))}function I(e){try{let t=A(e),n=new URL(e,"http://soot.local");return n.pathname=n.pathname.replace(/\.\.bundle$/,".bundle"),O(n.pathname)?(n.searchParams.delete("transform.bytecode"),n.searchParams.get("lazy")==="true"&&n.searchParams.set("lazy","false"),H(n),t?n.toString():`${n.pathname}${n.search}${n.hash}`):e}catch{return e}}function pe(e,t){try{let n=A(e),o=new URL(e,"http://soot.local");return O(o.pathname)?(o.searchParams.set("hot",t?"true":"false"),n?o.toString():`${o.pathname}${o.search}${o.hash}`):e}catch{return e}}import{exec as W}from"child_process";import B from"http";import F from"net";import{promisify as G}from"util";var _=G(W);E();var z=250,J=1500,K=120;function V(e,t=K){return new Promise(n=>{let o=new F.Socket,s=!1,i=a=>{s||(s=!0,o.destroy(),n(a))};o.setTimeout(t),o.once("connect",()=>i(!0)),o.once("timeout",()=>i(!1)),o.once("error",()=>i(!1)),o.connect(e,"localhost")})}function h(e,t,n="GET",o=z,s={}){return new Promise(i=>{let a=B.request({hostname:"localhost",port:e,path:t,method:n,timeout:o,headers:s},r=>{let c="";r.on("data",l=>c+=l.toString());let u=(()=>{let l=r.headers["content-type"];if(typeof l=="string")return l;if(Array.isArray(l))return l[0]})();r.on("end",()=>i({statusCode:r.statusCode||0,body:c,contentType:u}))});a.on("error",()=>i(null)),a.setTimeout(o,()=>{a.destroy(),i(null)}),a.end()})}var q=[8081,8082,8083,8084,8085,8086,3e3,3001,19e3].map(e=>({port:e,pid:0}));function C(e,t){return!(e<=0||e>=2e4||t.has(e)||e>=5170&&e<=5200)}async function Y(e=[]){let t=new Set(e);try{let{stdout:n}=await _("lsof -iTCP -sTCP:LISTEN -P -n 2>/dev/null | grep -E '^(node|bun)'",{encoding:"utf8",timeout:2e3});if(n.trim()){let o=new Map;for(let s of n.trim().split(`
|
|
3
3
|
`)){let i=s.trim().split(/\s+/);if(i.length<9)continue;let a=Number(i[1]),c=i[8].match(/:(\d+)$/);if(!c)continue;let u=Number(c[1]);C(u,t)&&(o.has(u)||o.set(u,a))}if(o.size>0)return[...o.entries()].map(([s,i])=>({port:s,pid:i}))}}catch{}try{let{stdout:n}=await _(`ss -tlnp 2>/dev/null | grep -E '"(node|bun)"'`,{encoding:"utf8",timeout:2e3});if(n.trim()){let o=new Map;for(let s of n.trim().split(`
|
|
4
4
|
`)){let i=s.match(/:(\d+)\s/),a=s.match(/pid=(\d+)/);if(!i)continue;let r=Number(i[1]),c=a?Number(a[1]):0;C(r,t)&&(o.has(r)||o.set(r,c))}if(o.size>0)return[...o.entries()].map(([s,i])=>({port:s,pid:i}))}}catch{}return q.filter(n=>C(n.port,t))}var x=new Map;async function Q(e){if(e<=0)return null;let t=x.get(e);if(t)return t;try{let{stdout:n}=await _(`lsof -p ${e} -a -d cwd -Fn 2>/dev/null`,{encoding:"utf8",timeout:1500});for(let o of n.split(`
|
|
5
5
|
`))if(o.startsWith("n")&&o.length>1){let s=o.slice(1).trim();if(s)return x.set(e,s),s}}catch{}return null}function X(e,t){return{port:e,framework:t,bundleUrl:S(e,`http://localhost:${e}/index.bundle?platform=ios&dev=true&hot=true&minify=false`),hmrUrl:`ws://localhost:${e}/hot`,lastSeen:Date.now()}}function S(e,t){let n=D().find(s=>s.preferredPort===e),o=n?.runtimeConfig?j(t,n.runtimeConfig):t;return I(o)}function Z(e){return e.includes("/node_modules/one/metro-entry.bundle")}function ee(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}function w(e,t,n){if(!t)return e;try{let o=JSON.parse(t.body),s=o?.extra?.expoClient||o?.extra||{};s.name&&(e.projectName=s.name),s.ios?.bundleIdentifier&&(e.bundleId=s.ios.bundleIdentifier),e.framework==="metro"&&s.sdkVersion&&(e.framework="expo");let i=o?.launchAsset?.url;i&&!e.patched&&!Z(e.bundleUrl)&&(e.bundleUrl=S(e.port,i));let a=s.iconUrl||s.ios?.iconUrl||s.icon||s.ios?.icon;if(a)if(e.iconPath=a,n)if(a.startsWith("http"))e.iconUrl=n(a);else{let r=a.replace(/^\.\//,"");e.iconUrl=n(`http://localhost:${e.port}/assets/${r}`)}else e.iconUrl=a.startsWith("http")?a:`http://localhost:${e.port}/assets/${a.replace(/^\.\//,"")}`}catch{}return e}var ne=2e4,v=new Map,k=new Set;function M(e,t){if(e.projectName)return e;let n=v.get(e.port);if(n)return n.projectName&&(e.projectName=n.projectName),n.iconUrl&&!e.iconUrl&&(e.iconUrl=n.iconUrl,e.iconPath=n.iconPath),n.bundleId&&!e.bundleId&&(e.bundleId=n.bundleId),e;if(!k.has(e.port)){k.add(e.port);let o=e.port;te(o,t).finally(()=>k.delete(o))}return e}async function te(e,t){let n=await h(e,"/","GET",ne,{"expo-platform":"ios"});if(!n||n.statusCode!==200)return;let o=w({port:e,framework:"one",bundleUrl:"",lastSeen:0},n,t);!o.projectName&&!o.iconUrl||(v.set(e,{projectName:o.projectName,iconUrl:o.iconUrl,iconPath:o.iconPath,bundleId:o.bundleId}),b.delete(e))}var d=new Set,g=new Set,y=new Set;async function oe(e,t){if(!await V(e))return null;let n="/node_modules/one/metro-entry.bundle?platform=ios&dev=true",[o,s,i,a]=await Promise.all([d.has(e)?Promise.resolve(null):h(e,"/__soot/"),h(e,"/status"),y.has(e)?Promise.resolve(null):h(e,"/","GET",J,{"expo-platform":"ios"}),g.has(e)?Promise.resolve(null):h(e,"/_expo/status")]);a&&a.statusCode===200?g.delete(e):g.has(e)||g.add(e);let r=i?ee(i.body):null,c=typeof r?.launchAsset?.url=="string"?r.launchAsset.url:null,u=r?.extra?.expoClient||r?.extra||{};if(r&&(c||typeof u.name=="string")){d.add(e);let U=c||`http://localhost:${e}/index.bundle?platform=ios&dev=true&hot=true&minify=false`,L=U.includes("/one/metro-entry.bundle")?"one":"expo";return w({port:e,framework:L,bundleUrl:S(e,U),hmrUrl:`ws://localhost:${e}/hot`,lastSeen:Date.now()},i,t)}if(s&&s.body.includes("packager-status:running"))return d.add(e),M(w(X(e,a&&a.statusCode===200?"expo":"metro"),i,t),t);if(o&&o.statusCode===200&&o.body.includes("sootsim-patched"))return d.delete(e),M(w({port:e,framework:"one",bundleUrl:S(e,`http://localhost:${e}/__soot/bundle.js`),hmrUrl:`ws://localhost:${e}/hot`,lastSeen:Date.now(),patched:!0},i,t),t);if(s&&s.statusCode===200||a&&a.statusCode===200||i&&i.statusCode===200&&r!=null)return null;let m=await h(e,n,"HEAD");return m&&m.statusCode>0&&m.statusCode<400&&/application\/javascript/i.test(m.contentType||"")?(d.add(e),y.add(e),M(w({port:e,framework:"one",bundleUrl:S(e,`http://localhost:${e}${n}&minify=false`),hmrUrl:`ws://localhost:${e}/hot`,lastSeen:Date.now()},i,t),t)):(d.add(e),null)}function re(e){return!!e.bundleId?.trim().toLowerCase()?.startsWith("dev.sootsim.")}var b=new Map,se=3e4,ie=1500;function ae(e){return!e||e.framework==="metro"||e.framework==="unknown"}function ce(e){return e?S(e.port,e.bundleUrl)===e.bundleUrl:!0}function ue(e,t,n=Date.now()){if(t===0||e.pid!==t||!ce(e.result))return!1;let o=n-e.cachedAt;return!(e.result===null&&o>=se||ae(e.result)&&o>=ie)}async function xe(e={}){let t=await Y(e.excludePorts),n=new Set(t.map(r=>r.port));for(let r of[...b.keys()])n.has(r)||b.delete(r);for(let r of[...d])n.has(r)||d.delete(r);for(let r of[...g])n.has(r)||g.delete(r);for(let r of[...y])n.has(r)||y.delete(r);for(let r of[...v.keys()])n.has(r)||v.delete(r);let o=[],s=[];for(let{port:r,pid:c}of t){let u=b.get(r);if(u&&ue(u,c)){u.result&&o.push(u.result);continue}u&&u.pid!==c&&(d.delete(r),g.delete(r),y.delete(r),v.delete(r)),s.push({port:r,pid:c})}s.length>0&&(await Promise.all(s.map(c=>oe(c.port,e.buildIconProxyUrl)))).forEach((c,u)=>{let{port:l,pid:m}=s[u];m!==0&&b.set(l,{pid:m,result:c,cachedAt:Date.now()}),c&&o.push(c)});let i=new Map;for(let{port:r,pid:c}of t)c>0&&i.set(r,c);await Promise.all(o.map(async r=>{let c=i.get(r.port);if(!c)return;r.pid=c;let u=await Q(c);u&&(r.cwd=u)}));let a=new Set(i.values());for(let r of[...x.keys()])a.has(r)||x.delete(r);return o.filter(r=>!re(r))}import R from"fs";import f from"path";import{fileURLToPath as le}from"url";var P;function de(){if(P!==void 0)return P;let e=f.dirname(le(import.meta.url));for(let t=0;t<12&&e!==f.dirname(e);t++){if(R.existsSync(f.join(e,"packages/sootsim-engine/package.json"))&&R.existsSync(f.join(e,"public/sootsim")))return P=e,e;e=f.dirname(e)}return P=null,null}function Te(){if(process.env.SOOTSIM_HOME&&T())return null;let e=de();if(!e)return null;let t=f.join(e,"public/sootsim");return R.existsSync(f.join(t,"index.html"))&&R.existsSync(f.join(t,"engine/index.html"))&&R.existsSync(f.join(t,"engine-tenant/worker.js"))?t:null}export{j as a,me as b,I as c,pe as d,oe as e,xe as f,Te as g};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as c}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as c}from"./chunk-GYTATFQA.js";import{a as u,b as f,c as s,d as a}from"./chunk-LKJ5LA6K.js";import{a as e}from"./chunk-A3FIOG7U.js";import{c as n}from"./chunk-JLOAWSX6.js";import{a as i}from"./chunk-MQHSWXDS.js";import{a as m,c as p}from"./chunk-UJ64GJSZ.js";function g(){return`sootsim CLI v${i()} \xB7 ${c().primary}`}function C(){let r=f({bridgePort:7668,defaultShellUrl:n},e()),o=`
|
|
3
3
|
${p}
|
|
4
4
|
`;console.log(`${g()}
|
|
5
5
|
${o}${r}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as m,b as I}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as m,b as I}from"./chunk-WVF2EDZF.js";import{a as w,b as _,c as T}from"./chunk-UZGLGCLM.js";import{c as O}from"./chunk-OXQOPTTB.js";import{G as k,o as D,q as f}from"./chunk-ZGM7N2AV.js";import h from"fs";import v from"path";var c="default",F="profiles.json",a=1;function s(e){let r=e.trim();if(!r)throw new Error("profile id is required");if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(r))throw new Error("profile ids must start with a letter or number and contain only letters, numbers, dot, dash, or underscore");if(r==="."||r==="..")throw new Error(`invalid profile id: ${r}`);return r}function g(){return v.join(f(),F)}function G(e){return`sootsim-profile-${s(e)}`}function H(e){return v.join(D(),"Partitions",G(e))}function y(e){return v.join(f(),"playwright",s(e))}function b(){try{let e=JSON.parse(h.readFileSync(g(),"utf8"));if(!e||e.version!==a)return{version:a,profiles:[]};let r=Array.isArray(e.profiles)?e.profiles.filter(t=>!!t&&typeof t.id=="string"&&typeof t.createdAt=="string"&&typeof t.updatedAt=="string").map(t=>({id:s(t.id),createdAt:t.createdAt,updatedAt:t.updatedAt})):[];return{version:a,profiles:r}}catch{return{version:a,profiles:[]}}}function A(e){return[...e].sort((r,t)=>r.id===c?-1:t.id===c?1:r.id.localeCompare(t.id))}function P(e){if(e.profiles.some(t=>t.id===c))return{...e,profiles:A(e.profiles)};let r=new Date().toISOString();return{version:a,profiles:A([{id:c,createdAt:r,updatedAt:r},...e.profiles])}}function S(e){k();let r=P(e),t=`${g()}.tmp`;return h.writeFileSync(t,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`,"utf8"),h.renameSync(t,g()),r}function q(){return S(b()).profiles}function z(e){let r=s(e);return q().find(t=>t.id===r)??null}function E(e=c){let r=s(e),t=z(r);return t||j(r)}function j(e){let r=s(e),t=P(b());if(t.profiles.some(i=>i.id===r))throw new Error(`profile already exists: ${r}`);let o=new Date().toISOString(),n={id:r,createdAt:o,updatedAt:o};return S({version:a,profiles:[...t.profiles,n]}),n}function pe(e){let r=s(e);if(r===c)throw new Error("the default profile cannot be deleted; clear it instead");let t=P(b()),o=t.profiles.find(n=>n.id===r);if(!o)throw new Error(`profile not found: ${r}`);return S({version:a,profiles:t.profiles.filter(n=>n.id!==r)}),B(r),o}function B(e){let r=s(e);for(let t of[H(r),y(r)])try{h.rmSync(t,{recursive:!0,force:!0})}catch{}}function Y(){let e=w();return e?{available:!0,reason:null,detail:e}:{available:!1,reason:"no chromium-family browser found (chrome, chromium, edge, brave, arc)"}}async function K(e){if(e.headless)return{launched:!1,message:"the chromium driver launches a visible browser window and cannot run headless \u2014 a headless `chrome --headless=new` process exits immediately and the sim never connects. for headless automation use `--driver playwright`."};let r=w();if(!r)return{launched:!1,message:"chromium not found \u2014 install chrome or run `sootsim list --drivers`"};if(!e.url)return{launched:!1,message:"chromium driver requires a target url"};if(e.profileId||e.ephemeralProfile)return{launched:!1,message:"profiles require electron or playwright; browser tabs use your current Chrome profile"};try{let t=await T(e.url,{detached:e.detached??!0});return{launched:!0,message:`chromium launched \u2192 ${e.url}`,pid:t.pid,target:t.target??r,attachUrl:e.url}}catch(t){return{launched:!1,message:`chromium spawn failed: ${t instanceof Error?t.message:String(t)}`}}}var M={id:"chromium",name:"chromium",description:"system chrome / chromium / edge \u2014 visible window (headless: use playwright)",kind:"browser",availability:Y,launch:K};function V(){let e=m();return e?{available:!0,reason:null,detail:`${e.kind} @ ${e.path}`}:{available:!1,reason:"sootsim desktop app not installed (run `sootsim desktop install`)"}}async function J(e){let r=m();if(!r)return{launched:!1,message:"sootsim desktop app not installed"};try{let t=await I(e.url,r,{device:e.device,profileId:e.profileId,ephemeralProfile:e.ephemeralProfile});return t.launched?{launched:!0,message:e.url?`electron launched via ${t.via} \u2192 ${e.url}`:`electron launched via ${t.via}`,target:t.target,attachUrl:e.url}:{launched:!1,message:"desktop companion failed to start"}}catch(t){return{launched:!1,message:`electron launch failed: ${t instanceof Error?t.message:String(t)}`}}}var C={id:"electron",name:"electron",description:"sootsim desktop companion app (native window, menu bar)",kind:"native",availability:V,launch:J};import{spawn as X}from"child_process";import{closeSync as Z,mkdtempSync as Q,openSync as ee,readFileSync as re}from"fs";import{createRequire as te}from"module";import{tmpdir as L}from"os";import{join as W}from"path";var oe=`
|
|
4
4
|
const modulePath = process.env.SOOTSIM_PW_MODULE;
|
|
5
5
|
const url = process.env.SOOTSIM_PW_URL;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as x}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as x}from"./chunk-YP3NIRTK.js";import{a as k}from"./chunk-WVF2EDZF.js";import{spawn as v,spawnSync as u}from"child_process";import{chmodSync as S,copyFileSync as T,createWriteStream as E,existsSync as w,mkdirSync as y,rmSync as g,statSync as P,unlinkSync as D}from"fs";import{tmpdir as M}from"os";import{dirname as A,join as f,resolve as b}from"path";var h="https://sootbean.com/api/electron-release";function O(){let n=process.arch;if(process.platform==="darwin"){let o=n==="arm64"?"mac-arm64":"mac-x64",e=`sootsim-latest-${o}.dmg`;return{platform:o,filename:e,url:`${h}/${e}`,install:L}}if(process.platform==="linux"){let o=n==="arm64"?"linux-arm64":"linux-x64",e=`sootsim-latest-${o}.AppImage`;return{platform:o,filename:e,url:`${h}/${e}`,install:C}}if(process.platform==="win32"){let o="sootsim-latest-win-x64.exe";return{platform:"win-x64",filename:o,url:`${h}/${o}`,install:B}}return null}async function I({url:n,dest:o,onProgress:e}){let s=await fetch(n,{redirect:"follow"});if(!s.ok)throw new Error(`${s.status} ${s.statusText} (${n})`);let t=s.headers.get("content-length"),a=t?Number(t):null;if(!s.body)throw new Error(`empty response body (${n})`);y(A(o),{recursive:!0});let i=E(o),d=s.body.getReader(),c=0;try{for(;;){let{done:l,value:p}=await d.read();if(l)break;i.write(Buffer.from(p)),c+=p.byteLength,e?.(c,a)}}finally{await new Promise((l,p)=>{i.end(r=>r?p(r):l())})}}function _(n,o){let e=(n/1048576).toFixed(1);if(!o)return` ${e} MB`;let s=Math.min(100,Math.round(n/o*100)),t=(o/(1024*1024)).toFixed(1),a=24,i=Math.round(s/100*a);return` ${"\u2588".repeat(i)+"\u2591".repeat(a-i)} ${s}% ${e} / ${t} MB`}async function L(n){let o=u("hdiutil",["attach","-nobrowse","-readonly",n],{encoding:"utf8"});if(o.status!==0)throw new Error(`hdiutil attach failed: ${o.stderr||o.stdout}`.trim());let e=o.stdout.trim().split(`
|
|
3
3
|
`),t=e[e.length-1].split(" ").pop()?.trim();if(!t||!w(t))throw new Error(`could not determine dmg mount point (output: ${o.stdout})`);let a=f(t,"sootsim.app");if(!w(a))throw u("hdiutil",["detach","-force",t]),new Error(`sootsim.app not found inside ${t}`);let i="/Applications",d=b(process.env.HOME||"","Applications"),c=i;try{let m=f(i,`.sootsim-write-probe-${process.pid}`);u("touch",[m]),w(m)?g(m,{force:!0}):c=d}catch{c=d}c===d&&y(c,{recursive:!0});let l=f(c,"sootsim.app");w(l)&&g(l,{recursive:!0,force:!0});let p=u("cp",["-R",a,l]),r=u("hdiutil",["detach","-force",t]);if(p.status!==0)throw new Error(`copy to ${l} failed: ${p.stderr?.toString()||""}`.trim());return r.status!==0&&console.warn(` warning: failed to unmount ${t} (${r.stderr?.toString().trim()||"unknown error"})`),u("xattr",["-dr","com.apple.quarantine",l]),l}async function C(n){let o=b(process.env.HOME||"","Applications");y(o,{recursive:!0});let e=f(o,"sootsim.AppImage");return w(e)&&g(e,{force:!0}),T(n,e),D(n),S(e,493),e}async function B(n){return await new Promise((o,e)=>{let s=v("cmd",["/c","start",'""',"/wait",n],{stdio:"inherit"});s.once("error",e),s.once("exit",t=>{t===0?o():e(new Error(`installer exited with code ${t}`))})}),n}async function q(n){(n.includes("--help")||n.includes("-h"))&&(console.log(`
|
|
4
4
|
sootsim desktop install \u2014 download and install the optional desktop GUI
|
|
5
5
|
|
|
@@ -20,4 +20,4 @@ examples:
|
|
|
20
20
|
`),process.exit(0));let o=n.includes("--yes")||n.includes("-y")||process.env.SOOTSIM_NO_PROMPT==="1"||process.env.CI==="1"||!process.stdin.isTTY,e=n.includes("--force"),s=k();if(s&&!e){console.log(` sootsim desktop already installed at: ${s.path}`),console.log(" pass --force to reinstall.");return}let t=O();if(t||(console.error(` no desktop build available for ${process.platform}/${process.arch}.`),console.error(" supported: darwin-arm64, darwin-x64, linux-x64, linux-arm64, win32-x64"),process.exit(1)),console.log(` platform: ${t.platform}`),console.log(` download: ${t.url}`),console.log(),!o){if(!await x("download and install now?",!0)){console.log(" cancelled.");return}console.log()}let a=f(M(),`sootsim-install-${Date.now()}`),i=f(a,t.filename),d=0;process.stdout.write(` downloading ${t.filename}...
|
|
21
21
|
`);try{await I({url:t.url,dest:i,onProgress:(r,m)=>{let $=Date.now();$-d<100&&r<(m??1/0)||(d=$,process.stdout.isTTY&&process.stdout.write(`\r\x1B[2K${_(r,m)}`))}})}catch(r){g(a,{recursive:!0,force:!0});let m=r instanceof Error?r.message:String(r);console.error(`
|
|
22
22
|
download failed: ${m}`),console.error(` the ${t.platform} desktop build may not be published yet, or your`),console.error(" network blocked the request. check your connection and try again later;"),console.error(" the CLI + daemon work without the desktop app (run: sootsim --help)."),process.exit(1)}process.stdout.isTTY&&process.stdout.write(`
|
|
23
|
-
`);let c=P(i).size;console.log(` downloaded ${(c/(1024*1024)).toFixed(1)} MB`),console.log(),console.log(" installing...");let{trackCliEvent:l,flushCliTelemetry:p}=await import("./telemetry-
|
|
23
|
+
`);let c=P(i).size;console.log(` downloaded ${(c/(1024*1024)).toFixed(1)} MB`),console.log(),console.log(" installing...");let{trackCliEvent:l,flushCliTelemetry:p}=await import("./telemetry-SWFOAVWP.js");try{let r=await t.install(i);l({event:"cli_install_desktop_succeeded",properties:{platform:t.platform,size_bytes:c}}),console.log(` installed: ${r}`)}catch(r){l({event:"cli_install_desktop_failed",properties:{platform:t.platform,error:r instanceof Error?r.message:String(r)}}),await p(),console.error(` install failed: ${r instanceof Error?r.message:String(r)}`),console.error(` keeping download at ${i} for manual install.`),process.exit(1)}finally{g(a,{recursive:!0,force:!0})}console.log(),console.log(" next steps:"),console.log(" sootsim desktop launch the desktop app"),console.log(" sootsim open <target> open a demo or bundle in it")}export{q as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{h as w,j as u,k as m,l}from"./chunk-
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{h as w,j as u,k as m,l}from"./chunk-62AKBZTO.js";var p="sootsim:settings",v=["errorReporting","colorScheme","a11yMode","a11yDepth","screenshotCanvas","screenshotBackground","screenshotText","screenshotPose","screenshotDynamicSize","alwaysShowLiveWebViews","agentProvider","onboardingComplete","betaConsentVersion","detailedTelemetry"];function S(){if(typeof window>"u")return null;let e=window.sootsimElectron;return e&&typeof e=="object"?e:null}function g(e){let t={};for(let n of v){if(!(n in e))continue;let r=e[n],o=u[n];o.validate&&!o.validate(r)||o.options&&!o.options.includes(r)||(t[n]=r)}return t}function h(e){let t={};for(let n of v)t[n]=e[n];return t}function _(){if(typeof localStorage>"u")return{};try{let e=localStorage.getItem(p);return e?g(JSON.parse(e)):{}}catch{return{}}}function V(e){if(!(typeof localStorage>"u"))try{localStorage.setItem(p,JSON.stringify(h(e)))}catch{}}function E(){let t=S()?.sharedConfig?.settings;return!t||typeof t!="object"?{}:g(t)}function K(e){let t=S();if(t?.writeSharedConfig)try{t.writeSharedConfig({settings:h(e)})}catch{}}function b(){if(typeof window>"u")return null;let e=window.__sootsimSharedConfig;return e&&typeof e=="object"?e:null}function j(){let e=b()?.settings;return!e||typeof e!="object"?{}:g(e)}function D(e){if(!b())return;let t={settings:h(e)};try{if(globalThis.__sootsimBridgeRequest?.writeSharedConfig?.(t))return}catch{}if(!(typeof fetch>"u"))try{fetch("/__sootsim/shared-config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0}).catch(()=>{})}catch{}}function k(){let e=_(),t=j(),n=E();return{...e,...t,...n}}function R(e){V(e),K(e),D(e)}function C(e){if(typeof window>"u")return()=>{};let t=i=>{if(!(i.key!==p||i.newValue==null))try{e(g(JSON.parse(i.newValue)))}catch{}};window.addEventListener("storage",t);let n=S(),r;n?.onSharedConfigChanged&&(r=n.onSharedConfigChanged(i=>{let d=i?.settings;!d||typeof d!="object"||e(g(d))}));let c=globalThis.__sootsimBridgeRequest?.subscribeSharedConfig?.(i=>{let d=i?.settings;!d||typeof d!="object"||e(g(d))});return()=>{window.removeEventListener("storage",t),r?.(),c?.()}}var M=l(),P=k();for(let e of Object.keys(m()))delete P[e];var s={...M,...P},f=[],a=null;function y(){for(let e of f)e();R(s)}C(e=>{let t={...s},n=!1;for(let[r,o]of Object.entries(e)){let c=r;t[c]!==o&&(t[c]=o,n=!0)}if(n){s=t,a=null;for(let r of f)r()}});var L={get(e){return s[e]},set(e,t){let n=u[e];n.validate&&!n.validate(t)||n.options&&!n.options.includes(t)||s[e]!==t&&(s={...s,[e]:t},e==="deviceModel"&&(a=null),y())},getAll(){return s},apply(e){let t=!1,n={...s};for(let[r,o]of Object.entries(e)){if(o===void 0)continue;let c=r,i=u[c];i&&(i.validate&&!i.validate(o)||i.options&&!i.options.includes(o)||n[c]!==o&&(n[c]=o,t=!0))}t&&(s=n,a=null,y())},reset(){s=l(),a=null,y()},subscribe(e){return f.push(e),()=>{f=f.filter(t=>t!==e)}},getDeviceSpec(){return a||(a=w(s.deviceModel)),a},getA11yMode(){return s.a11yMode},setA11yMode(e){this.set("a11yMode",e)},getInspectMode(){return s.inspectMode},setInspectMode(e){this.set("inspectMode",e)}};export{L as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! sootsim v0.1.
|
|
2
|
-
import{a as R}from"./chunk-Z5VMWFCY.js";import{o as D}from"./chunk-GZKT53SA.js";import{a as T}from"./chunk-4KT2BGQE.js";function Y(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.type=="string"&&typeof t.ts=="number"}function I(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return Y(r)?r:null}catch{return null}}import{randomBytes as G,createHash as q}from"node:crypto";import m from"node:fs";import h from"node:path";var N=null;function _(){if(N)return N;let e=process.env.SOOTSIM_USER_DATA_DIR;return e||D()}function y(){return _()}function U(){return h.join(_(),"attached-projects.json")}function $(){return{version:1,attachedProjects:[],previewAttachments:[],agentSessions:[]}}function S(){let e=U(),t;try{t=m.readFileSync(e,"utf8")}catch(r){if(r.code==="ENOENT")return $();throw r}try{let r=JSON.parse(t);if(!r||typeof r!="object")throw new Error("not an object");return{version:1,attachedProjects:Array.isArray(r.attachedProjects)?r.attachedProjects:[],previewAttachments:Array.isArray(r.previewAttachments)?r.previewAttachments:[],agentSessions:Array.isArray(r.agentSessions)?r.agentSessions:[]}}catch(r){let n=`${e}.corrupt-${Date.now()}`;try{m.renameSync(e,n),console.warn(`[sootsim] attached-projects.json was unparseable; quarantined to ${n}. original error: ${r.message}`)}catch{}return $()}}function X(e){let t=U();m.mkdirSync(h.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Date.now()}`,n=m.openSync(r,"w",384);try{m.writeFileSync(n,JSON.stringify(e,null,2)),m.fsyncSync(n)}finally{m.closeSync(n)}m.renameSync(r,t)}function w(e){let t=S();return e(t),X(t),t}function B(e){return q("sha256").update(h.resolve(e)).digest("hex").slice(0,16)}function K(){return`s_${G(10).toString("hex")}`}function ge(e){let t=h.resolve(e.cwd),r=B(t),n;return w(o=>{let s=o.attachedProjects.find(c=>c.id===r);if(s){let c={...s,...e,id:r,cwd:t,sourceRoots:e.sourceRoots??s.sourceRoots,knownBundleUrls:e.knownBundleUrls??s.knownBundleUrls,pinnedSourceResolutions:e.pinnedSourceResolutions??s.pinnedSourceResolutions,telemetry:e.telemetry??s.telemetry,updatedAt:Date.now(),createdAt:s.createdAt},g=o.attachedProjects.indexOf(s);o.attachedProjects[g]=c,n=c;return}let a=Date.now(),d={id:r,name:e.name??h.basename(t),cwd:t,repoRoot:e.repoRoot,sourceRoots:e.sourceRoots??[t],framework:e.framework??"unknown",bundleId:e.bundleId,knownBundleUrls:e.knownBundleUrls??[],preferredProvider:e.preferredProvider??"codex",preferredTransport:e.preferredTransport??"tmux",editorOpenCommand:e.editorOpenCommand,moshiWebhookToken:e.moshiWebhookToken,pinnedSourceResolutions:e.pinnedSourceResolutions??{},isolateDiscovery:e.isolateDiscovery,git:e.git,telemetry:e.telemetry??{lastOpened:0,runsCompleted:0},createdAt:a,updatedAt:a};o.attachedProjects.push(d),n=d}),n}function F(e){return S().attachedProjects.find(t=>t.id===e)??null}function he(){return S().attachedProjects}var Q=336*60*60*1e3;function ye(e,t={}){w(r=>{let n=r.attachedProjects.find(s=>s.id===e);if(!n)return;let o=t.ts??Date.now();if(n.telemetry.runsCompleted=(n.telemetry.runsCompleted??0)+1,typeof t.usd=="number"&&Number.isFinite(t.usd)&&t.usd>=0){let s=n.telemetry.costHistory??[],a=o-Q,d=s.filter(c=>c.ts>=a);d.push({ts:o,usd:t.usd}),n.telemetry.costHistory=d}n.updatedAt=o})}function Se(e,t=Date.now()){let r=t-6048e5,n=e.telemetry.costHistory??[],o=0;for(let s of n)s.ts>=r&&(o+=s.usd);return o}function we(e){w(t=>{t.attachedProjects=t.attachedProjects.filter(r=>r.id!==e),t.agentSessions=t.agentSessions.filter(r=>r.projectId!==e),t.previewAttachments=t.previewAttachments.filter(r=>r.projectId!==e)})}function M(e){let t;return w(r=>{if(e.id){let a=r.agentSessions.find(d=>d.id===e.id);if(a){let d={...a,...e,lastSeenAt:Date.now()},c=r.agentSessions.indexOf(a);r.agentSessions[c]=d,t=d;return}}let n=r.attachedProjects.find(a=>a.id===e.projectId);if(!n)throw new Error(`upsertSession: no AttachedProject with id=${e.projectId}`);let o=Date.now(),s={id:e.id??K(),projectId:e.projectId,provider:e.provider,transport:e.transport??n.preferredTransport,cwd:e.cwd??n.cwd,claudeSessionUuid:e.claudeSessionUuid,tmuxSessionName:e.tmuxSessionName,wrapperPid:e.wrapperPid,status:e.status??"idle",needsAttention:e.needsAttention??!1,lastPrompt:e.lastPrompt,lastSummary:e.lastSummary,lastTurnFiles:e.lastTurnFiles,currentlyEditing:e.currentlyEditing,lastSeenAt:o,createdAt:o};r.agentSessions.push(s),t=s}),t}function k(e){return S().agentSessions.find(t=>t.id===e)??null}function C(e){let t=S().agentSessions;return e?t.filter(r=>r.projectId===e):t}function v(e,t){w(r=>{let n=r.agentSessions.find(s=>s.id===e);if(!n)return;let o=r.agentSessions.indexOf(n);r.agentSessions[o]={...n,...t,id:n.id,projectId:n.projectId,createdAt:n.createdAt,lastSeenAt:Date.now()}})}async function ve(){if(S().attachedProjects.length>0)return;let{loadOptionalDemoApps:t}=await import("./optional-demo-registry-ILX5YV34.js"),r=await t();r.length!==0&&w(n=>{for(let o of r){if(!m.existsSync(o.dir))continue;let s=h.resolve(o.dir),a=B(s);if(n.attachedProjects.some(c=>c.id===a))continue;let d=Date.now();n.attachedProjects.push({id:a,name:o.label,cwd:s,sourceRoots:[s],framework:o.framework,knownBundleUrls:[`http://localhost:${o.preferredPort}/index.bundle`],preferredProvider:"codex",preferredTransport:"tmux",pinnedSourceResolutions:{},telemetry:{lastOpened:0,runsCompleted:0},createdAt:d,updatedAt:d})}})}import{spawn as V,spawnSync as z}from"node:child_process";import{randomUUID as Z}from"node:crypto";import i,{constants as f}from"node:fs";import u from"node:path";import ee from"node:readline";function j(e){return u.join(y(),"sessions",e)}function W(e){return u.join(j(e),"prompt.in")}function J(e){return u.join(j(e),"events.out")}function te(e){return u.join(y(),"transcripts",`${e}.log`)}function O(e,t){if(!e)return!1;try{process.kill(e,0)}catch{return!1}return!(t&&!i.existsSync(j(t)))}function re(){if(process.env.SOOTSIM_BIN)return{cmd:process.env.SOOTSIM_BIN,prefixArgs:[]};if(process.versions.electron){let n=process.resourcesPath;if(n){let o=[u.join(n,"bin","sootsim"),u.join(n,"bin",`sootsim-${process.platform}-${process.arch}`)];for(let s of o)if(i.existsSync(s))return{cmd:s,prefixArgs:[]}}}let e=ne();if(e)return e;let t=process.argv[0],r=process.argv[1];if(r&&/\.(ts|tsx|mjs|cjs|js)$/.test(r))return{cmd:t,prefixArgs:[r]};if(!r||r.includes("/.bin/"))throw new Error("sootsim CLI not found. set SOOTSIM_BIN to the path of the sootsim binary, or build the workspace CLI via `bun run --cwd packages/sootsim build:cli`.");return{cmd:t,prefixArgs:[]}}function ne(){try{let e=se();if(!e)return null;let t=`sootsim-${process.platform}-${process.arch}`,r=u.join(e,"dist-bin",t);if(i.existsSync(r))return{cmd:r,prefixArgs:[]};let n=u.join(e,"dist-cli","bin.js");if(i.existsSync(n)){try{let o=u.join(e,"cli","commands","agent-wrapper.ts");if(i.existsSync(o)){let s=i.statSync(o).mtimeMs;i.statSync(n).mtimeMs<s&&console.warn("[sootsim] dist-cli/bin.js is older than agent-wrapper.ts \u2014 rebuild with `bun run --cwd packages/sootsim build:cli` (watch:cli:binary builds dist-bin/ instead).")}}catch{}return{cmd:process.execPath,prefixArgs:[n]}}return null}catch{return null}}function se(){try{let r=T.resolve("sootsim/package.json");return u.dirname(r)}catch{}let e=oe();if(!e)return null;let t=u.dirname(e);for(let r=0;r<8;r++){let n=u.join(t,"package.json");try{if(i.existsSync(n)&&JSON.parse(i.readFileSync(n,"utf8")).name==="sootsim")return t}catch{}let o=u.dirname(t);if(o===t)break;t=o}return null}function oe(){try{let e=import.meta.url;return!e||!e.startsWith("file://")?null:decodeURIComponent(e.slice(7))}catch{return null}}async function ie(e,t,r){let n=u.join(y(),"locks");i.mkdirSync(n,{recursive:!0});try{i.chmodSync(n,448)}catch{}let o=u.join(n,`start-${e}-${t}.lock`),s=Date.now()+4e3,a=null;for(;a===null;)try{a=i.openSync(o,f.O_WRONLY|f.O_CREAT|f.O_EXCL,384)}catch(d){if(d.code!=="EEXIST")throw d;try{let c=Number(i.readFileSync(o,"utf8").trim());if(c&&!ce(c)){i.unlinkSync(o);continue}}catch{}if(Date.now()>s)throw new Error(`another start is in progress for project=${e} provider=${t} (lock: ${o})`);await new Promise(c=>setTimeout(c,50))}try{return i.writeFileSync(a,String(process.pid)),await r()}finally{try{i.closeSync(a)}catch{}try{i.unlinkSync(o)}catch{}}}function ce(e){try{return process.kill(e,0),!0}catch{return!1}}function L(e){let t=u.dirname(e);i.mkdirSync(t,{recursive:!0});try{i.chmodSync(t,448)}catch{}if(i.existsSync(e))try{if(i.statSync(e).isFIFO()){try{i.chmodSync(e,384)}catch{}return}i.unlinkSync(e)}catch{i.unlinkSync(e)}let r=z("mkfifo",["-m","600",e]);if(r.status!==0)throw new Error(`mkfifo(${e}) failed: ${r.stderr?.toString().trim()||"unknown error"}`)}var l=class extends Error{code;constructor(t,r){super(r),this.code=t}};async function Te(e){let t=F(e.projectId);if(!t)throw new l("NO_PROJECT",`no project with id=${e.projectId}`);let r=e.provider||t.preferredProvider||"codex";return ie(t.id,r,async()=>{let n=C(t.id).find(p=>p.provider===r&&p.status!=="ended"&&O(p.wrapperPid,p.id));if(n)throw new l("ALREADY_RUNNING",`session already running for project=${t.id} provider=${r} (session ${n.id}, pid ${n.wrapperPid}). end it first with \`sootsim agent end <sessionId>\`.`);let o=r==="claude"?Z():void 0,s=M({projectId:t.id,provider:r,transport:"pty",cwd:t.cwd,status:"idle",claudeSessionUuid:o}),a=W(s.id),d=J(s.id),c=te(s.id);L(a),L(d);let g=u.dirname(c);i.mkdirSync(g,{recursive:!0});try{i.chmodSync(g,448)}catch{}let{cmd:A,prefixArgs:H}=re(),x=[...H,"agent-wrapper","--session-id",s.id,"--project-id",t.id,"--provider",r,"--cwd",t.cwd,"--prompt-in",a,"--events-out",d,"--transcript",c];e.codexBin&&x.push("--codex-bin",e.codexBin),e.claudeBin&&x.push("--claude-bin",e.claudeBin),e.freshThread&&x.push("--fresh-thread"),o&&x.push("--claude-session-uuid",o);let P=V(A,x,{detached:!0,stdio:"ignore",env:{...process.env,SOOTSIM_USER_DATA_DIR:y()}});P.unref();let E=e.readyTimeoutMs??6e3,b=await ae(d,p=>p.type==="ready"||p.type==="error",E);if(!b||b.type==="error"){if(P.pid)try{process.kill(P.pid,"SIGTERM")}catch{}try{i.rmSync(j(s.id),{recursive:!0,force:!0})}catch{}v(s.id,{status:"ended"});let p=b&&b.type==="error"?b.message:`no ready event within ${E}ms`;throw new l("WRAPPER_FAILED",p)}return v(s.id,{wrapperPid:P.pid,status:"idle"}),{session:k(s.id),wrapperPid:P.pid}})}async function De(e,t){let r=k(e);if(!r)throw new l("NO_SESSION",`no session with id=${e}`);if(!O(r.wrapperPid,e))throw v(e,{status:"ended"}),new l("NOT_ALIVE",`session wrapper is not alive (pid=${r.wrapperPid}). start a new session.`);let n=W(e);if(!i.existsSync(n))throw new l("NO_FIFO",`prompt FIFO missing: ${n}`);let o=i.openSync(n,f.O_WRONLY);try{let s=R(t);if(!s)throw new l("EMPTY_PROMPT","prompt text is empty");i.writeSync(o,s+`
|
|
1
|
+
/*! sootsim v0.1.203 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
|
|
2
|
+
import{a as R}from"./chunk-B7VBDZ3U.js";import{o as D}from"./chunk-ZGM7N2AV.js";import{a as T}from"./chunk-ZRWVLKFL.js";function Y(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.type=="string"&&typeof t.ts=="number"}function I(e){let t=e.trim();if(!t)return null;try{let r=JSON.parse(t);return Y(r)?r:null}catch{return null}}import{randomBytes as G,createHash as q}from"node:crypto";import m from"node:fs";import h from"node:path";var N=null;function _(){if(N)return N;let e=process.env.SOOTSIM_USER_DATA_DIR;return e||D()}function y(){return _()}function U(){return h.join(_(),"attached-projects.json")}function $(){return{version:1,attachedProjects:[],previewAttachments:[],agentSessions:[]}}function S(){let e=U(),t;try{t=m.readFileSync(e,"utf8")}catch(r){if(r.code==="ENOENT")return $();throw r}try{let r=JSON.parse(t);if(!r||typeof r!="object")throw new Error("not an object");return{version:1,attachedProjects:Array.isArray(r.attachedProjects)?r.attachedProjects:[],previewAttachments:Array.isArray(r.previewAttachments)?r.previewAttachments:[],agentSessions:Array.isArray(r.agentSessions)?r.agentSessions:[]}}catch(r){let n=`${e}.corrupt-${Date.now()}`;try{m.renameSync(e,n),console.warn(`[sootsim] attached-projects.json was unparseable; quarantined to ${n}. original error: ${r.message}`)}catch{}return $()}}function X(e){let t=U();m.mkdirSync(h.dirname(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Date.now()}`,n=m.openSync(r,"w",384);try{m.writeFileSync(n,JSON.stringify(e,null,2)),m.fsyncSync(n)}finally{m.closeSync(n)}m.renameSync(r,t)}function w(e){let t=S();return e(t),X(t),t}function B(e){return q("sha256").update(h.resolve(e)).digest("hex").slice(0,16)}function K(){return`s_${G(10).toString("hex")}`}function ge(e){let t=h.resolve(e.cwd),r=B(t),n;return w(o=>{let s=o.attachedProjects.find(c=>c.id===r);if(s){let c={...s,...e,id:r,cwd:t,sourceRoots:e.sourceRoots??s.sourceRoots,knownBundleUrls:e.knownBundleUrls??s.knownBundleUrls,pinnedSourceResolutions:e.pinnedSourceResolutions??s.pinnedSourceResolutions,telemetry:e.telemetry??s.telemetry,updatedAt:Date.now(),createdAt:s.createdAt},g=o.attachedProjects.indexOf(s);o.attachedProjects[g]=c,n=c;return}let a=Date.now(),d={id:r,name:e.name??h.basename(t),cwd:t,repoRoot:e.repoRoot,sourceRoots:e.sourceRoots??[t],framework:e.framework??"unknown",bundleId:e.bundleId,knownBundleUrls:e.knownBundleUrls??[],preferredProvider:e.preferredProvider??"codex",preferredTransport:e.preferredTransport??"tmux",editorOpenCommand:e.editorOpenCommand,moshiWebhookToken:e.moshiWebhookToken,pinnedSourceResolutions:e.pinnedSourceResolutions??{},isolateDiscovery:e.isolateDiscovery,git:e.git,telemetry:e.telemetry??{lastOpened:0,runsCompleted:0},createdAt:a,updatedAt:a};o.attachedProjects.push(d),n=d}),n}function F(e){return S().attachedProjects.find(t=>t.id===e)??null}function he(){return S().attachedProjects}var Q=336*60*60*1e3;function ye(e,t={}){w(r=>{let n=r.attachedProjects.find(s=>s.id===e);if(!n)return;let o=t.ts??Date.now();if(n.telemetry.runsCompleted=(n.telemetry.runsCompleted??0)+1,typeof t.usd=="number"&&Number.isFinite(t.usd)&&t.usd>=0){let s=n.telemetry.costHistory??[],a=o-Q,d=s.filter(c=>c.ts>=a);d.push({ts:o,usd:t.usd}),n.telemetry.costHistory=d}n.updatedAt=o})}function Se(e,t=Date.now()){let r=t-6048e5,n=e.telemetry.costHistory??[],o=0;for(let s of n)s.ts>=r&&(o+=s.usd);return o}function we(e){w(t=>{t.attachedProjects=t.attachedProjects.filter(r=>r.id!==e),t.agentSessions=t.agentSessions.filter(r=>r.projectId!==e),t.previewAttachments=t.previewAttachments.filter(r=>r.projectId!==e)})}function M(e){let t;return w(r=>{if(e.id){let a=r.agentSessions.find(d=>d.id===e.id);if(a){let d={...a,...e,lastSeenAt:Date.now()},c=r.agentSessions.indexOf(a);r.agentSessions[c]=d,t=d;return}}let n=r.attachedProjects.find(a=>a.id===e.projectId);if(!n)throw new Error(`upsertSession: no AttachedProject with id=${e.projectId}`);let o=Date.now(),s={id:e.id??K(),projectId:e.projectId,provider:e.provider,transport:e.transport??n.preferredTransport,cwd:e.cwd??n.cwd,claudeSessionUuid:e.claudeSessionUuid,tmuxSessionName:e.tmuxSessionName,wrapperPid:e.wrapperPid,status:e.status??"idle",needsAttention:e.needsAttention??!1,lastPrompt:e.lastPrompt,lastSummary:e.lastSummary,lastTurnFiles:e.lastTurnFiles,currentlyEditing:e.currentlyEditing,lastSeenAt:o,createdAt:o};r.agentSessions.push(s),t=s}),t}function k(e){return S().agentSessions.find(t=>t.id===e)??null}function C(e){let t=S().agentSessions;return e?t.filter(r=>r.projectId===e):t}function v(e,t){w(r=>{let n=r.agentSessions.find(s=>s.id===e);if(!n)return;let o=r.agentSessions.indexOf(n);r.agentSessions[o]={...n,...t,id:n.id,projectId:n.projectId,createdAt:n.createdAt,lastSeenAt:Date.now()}})}async function ve(){if(S().attachedProjects.length>0)return;let{loadOptionalDemoApps:t}=await import("./optional-demo-registry-3KZFUZZD.js"),r=await t();r.length!==0&&w(n=>{for(let o of r){if(!m.existsSync(o.dir))continue;let s=h.resolve(o.dir),a=B(s);if(n.attachedProjects.some(c=>c.id===a))continue;let d=Date.now();n.attachedProjects.push({id:a,name:o.label,cwd:s,sourceRoots:[s],framework:o.framework,knownBundleUrls:[`http://localhost:${o.preferredPort}/index.bundle`],preferredProvider:"codex",preferredTransport:"tmux",pinnedSourceResolutions:{},telemetry:{lastOpened:0,runsCompleted:0},createdAt:d,updatedAt:d})}})}import{spawn as V,spawnSync as z}from"node:child_process";import{randomUUID as Z}from"node:crypto";import i,{constants as f}from"node:fs";import u from"node:path";import ee from"node:readline";function j(e){return u.join(y(),"sessions",e)}function W(e){return u.join(j(e),"prompt.in")}function J(e){return u.join(j(e),"events.out")}function te(e){return u.join(y(),"transcripts",`${e}.log`)}function O(e,t){if(!e)return!1;try{process.kill(e,0)}catch{return!1}return!(t&&!i.existsSync(j(t)))}function re(){if(process.env.SOOTSIM_BIN)return{cmd:process.env.SOOTSIM_BIN,prefixArgs:[]};if(process.versions.electron){let n=process.resourcesPath;if(n){let o=[u.join(n,"bin","sootsim"),u.join(n,"bin",`sootsim-${process.platform}-${process.arch}`)];for(let s of o)if(i.existsSync(s))return{cmd:s,prefixArgs:[]}}}let e=ne();if(e)return e;let t=process.argv[0],r=process.argv[1];if(r&&/\.(ts|tsx|mjs|cjs|js)$/.test(r))return{cmd:t,prefixArgs:[r]};if(!r||r.includes("/.bin/"))throw new Error("sootsim CLI not found. set SOOTSIM_BIN to the path of the sootsim binary, or build the workspace CLI via `bun run --cwd packages/sootsim build:cli`.");return{cmd:t,prefixArgs:[]}}function ne(){try{let e=se();if(!e)return null;let t=`sootsim-${process.platform}-${process.arch}`,r=u.join(e,"dist-bin",t);if(i.existsSync(r))return{cmd:r,prefixArgs:[]};let n=u.join(e,"dist-cli","bin.js");if(i.existsSync(n)){try{let o=u.join(e,"cli","commands","agent-wrapper.ts");if(i.existsSync(o)){let s=i.statSync(o).mtimeMs;i.statSync(n).mtimeMs<s&&console.warn("[sootsim] dist-cli/bin.js is older than agent-wrapper.ts \u2014 rebuild with `bun run --cwd packages/sootsim build:cli` (watch:cli:binary builds dist-bin/ instead).")}}catch{}return{cmd:process.execPath,prefixArgs:[n]}}return null}catch{return null}}function se(){try{let r=T.resolve("sootsim/package.json");return u.dirname(r)}catch{}let e=oe();if(!e)return null;let t=u.dirname(e);for(let r=0;r<8;r++){let n=u.join(t,"package.json");try{if(i.existsSync(n)&&JSON.parse(i.readFileSync(n,"utf8")).name==="sootsim")return t}catch{}let o=u.dirname(t);if(o===t)break;t=o}return null}function oe(){try{let e=import.meta.url;return!e||!e.startsWith("file://")?null:decodeURIComponent(e.slice(7))}catch{return null}}async function ie(e,t,r){let n=u.join(y(),"locks");i.mkdirSync(n,{recursive:!0});try{i.chmodSync(n,448)}catch{}let o=u.join(n,`start-${e}-${t}.lock`),s=Date.now()+4e3,a=null;for(;a===null;)try{a=i.openSync(o,f.O_WRONLY|f.O_CREAT|f.O_EXCL,384)}catch(d){if(d.code!=="EEXIST")throw d;try{let c=Number(i.readFileSync(o,"utf8").trim());if(c&&!ce(c)){i.unlinkSync(o);continue}}catch{}if(Date.now()>s)throw new Error(`another start is in progress for project=${e} provider=${t} (lock: ${o})`);await new Promise(c=>setTimeout(c,50))}try{return i.writeFileSync(a,String(process.pid)),await r()}finally{try{i.closeSync(a)}catch{}try{i.unlinkSync(o)}catch{}}}function ce(e){try{return process.kill(e,0),!0}catch{return!1}}function L(e){let t=u.dirname(e);i.mkdirSync(t,{recursive:!0});try{i.chmodSync(t,448)}catch{}if(i.existsSync(e))try{if(i.statSync(e).isFIFO()){try{i.chmodSync(e,384)}catch{}return}i.unlinkSync(e)}catch{i.unlinkSync(e)}let r=z("mkfifo",["-m","600",e]);if(r.status!==0)throw new Error(`mkfifo(${e}) failed: ${r.stderr?.toString().trim()||"unknown error"}`)}var l=class extends Error{code;constructor(t,r){super(r),this.code=t}};async function Te(e){let t=F(e.projectId);if(!t)throw new l("NO_PROJECT",`no project with id=${e.projectId}`);let r=e.provider||t.preferredProvider||"codex";return ie(t.id,r,async()=>{let n=C(t.id).find(p=>p.provider===r&&p.status!=="ended"&&O(p.wrapperPid,p.id));if(n)throw new l("ALREADY_RUNNING",`session already running for project=${t.id} provider=${r} (session ${n.id}, pid ${n.wrapperPid}). end it first with \`sootsim agent end <sessionId>\`.`);let o=r==="claude"?Z():void 0,s=M({projectId:t.id,provider:r,transport:"pty",cwd:t.cwd,status:"idle",claudeSessionUuid:o}),a=W(s.id),d=J(s.id),c=te(s.id);L(a),L(d);let g=u.dirname(c);i.mkdirSync(g,{recursive:!0});try{i.chmodSync(g,448)}catch{}let{cmd:A,prefixArgs:H}=re(),x=[...H,"agent-wrapper","--session-id",s.id,"--project-id",t.id,"--provider",r,"--cwd",t.cwd,"--prompt-in",a,"--events-out",d,"--transcript",c];e.codexBin&&x.push("--codex-bin",e.codexBin),e.claudeBin&&x.push("--claude-bin",e.claudeBin),e.freshThread&&x.push("--fresh-thread"),o&&x.push("--claude-session-uuid",o);let P=V(A,x,{detached:!0,stdio:"ignore",env:{...process.env,SOOTSIM_USER_DATA_DIR:y()}});P.unref();let E=e.readyTimeoutMs??6e3,b=await ae(d,p=>p.type==="ready"||p.type==="error",E);if(!b||b.type==="error"){if(P.pid)try{process.kill(P.pid,"SIGTERM")}catch{}try{i.rmSync(j(s.id),{recursive:!0,force:!0})}catch{}v(s.id,{status:"ended"});let p=b&&b.type==="error"?b.message:`no ready event within ${E}ms`;throw new l("WRAPPER_FAILED",p)}return v(s.id,{wrapperPid:P.pid,status:"idle"}),{session:k(s.id),wrapperPid:P.pid}})}async function De(e,t){let r=k(e);if(!r)throw new l("NO_SESSION",`no session with id=${e}`);if(!O(r.wrapperPid,e))throw v(e,{status:"ended"}),new l("NOT_ALIVE",`session wrapper is not alive (pid=${r.wrapperPid}). start a new session.`);let n=W(e);if(!i.existsSync(n))throw new l("NO_FIFO",`prompt FIFO missing: ${n}`);let o=i.openSync(n,f.O_WRONLY);try{let s=R(t);if(!s)throw new l("EMPTY_PROMPT","prompt text is empty");i.writeSync(o,s+`
|
|
3
3
|
`)}finally{i.closeSync(o)}v(e,{lastPrompt:t.displayText??t.text,status:"working"})}async function Re(e){let t=k(e);if(!t)throw new l("NO_SESSION",`no session with id=${e}`);if(O(t.wrapperPid,e))try{process.kill(t.wrapperPid,"SIGTERM")}catch{}let r=j(e),n=y();if(r.startsWith(n))try{i.rmSync(r,{recursive:!0,force:!0})}catch{}v(e,{status:"ended",wrapperPid:void 0})}function Ne(e,t){let r=J(e);if(!i.existsSync(r))throw new l("NO_FIFO",`events FIFO missing: ${r}`);let n=i.openSync(r,f.O_RDWR),o=i.createReadStream("",{fd:n,autoClose:!0}),s=ee.createInterface({input:o,crlfDelay:1/0});s.on("line",d=>{let c=I(d);c&&t(c)});let a=!1;return()=>{if(!a){a=!0;try{s.close()}catch{}try{o.destroy()}catch{}}}}async function ae(e,t,r){let n=i.openSync(e,f.O_RDWR|f.O_NONBLOCK),o=Buffer.alloc(8192),s="",a=Date.now()+r;try{for(;Date.now()<a;){let d=0;try{d=i.readSync(n,o,0,o.length,null)}catch(c){if(c.code!=="EAGAIN")throw c;d=0}if(d>0){s+=o.subarray(0,d).toString("utf8");let c;for(;(c=s.indexOf(`
|
|
4
4
|
`))>=0;){let g=s.slice(0,c);s=s.slice(c+1);let A=I(g);if(A&&t(A))return A}}else await new Promise(c=>setTimeout(c,30))}return null}finally{i.closeSync(n)}}export{I as a,y as b,ge as c,F as d,he as e,ye as f,Se as g,we as h,k as i,C as j,v as k,ve as l,j as m,W as n,J as o,te as p,O as q,re as r,l as s,Te as t,De as u,Re as v,Ne as w};
|