sootsim 0.1.149 → 0.1.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/dist-cli/bin.js +3 -3
  2. package/dist-cli/chunks/{agent-DTREOLFP.js → agent-LSSBQD6J.js} +2 -2
  3. package/dist-cli/chunks/{agent-wrapper-LEZW2CEK.js → agent-wrapper-HYZ3VS4M.js} +2 -2
  4. package/dist-cli/chunks/{app-fonts-EQ6CK5L6.js → app-fonts-XXHCZZVE.js} +2 -2
  5. package/dist-cli/chunks/{assert-UEVT3SCS.js → assert-7I2ANKDG.js} +2 -2
  6. package/dist-cli/chunks/auto-bootstrap-YJM7QYAO.js +2 -0
  7. package/dist-cli/chunks/beta-EQOZMXP3.js +2 -0
  8. package/dist-cli/chunks/{camera-SHCRQWYG.js → camera-4D7T4PZW.js} +2 -2
  9. package/dist-cli/chunks/{chunk-DEOS6HMP.js → chunk-36L4ANT2.js} +1 -1
  10. package/dist-cli/chunks/{chunk-WKSDGVRG.js → chunk-3CENW2HN.js} +2 -2
  11. package/dist-cli/chunks/{chunk-Q3MVIFGA.js → chunk-3J5I64W6.js} +2 -2
  12. package/dist-cli/chunks/{chunk-GBWFT53N.js → chunk-3K237XV5.js} +1 -1
  13. package/dist-cli/chunks/{chunk-WKJ5NKXN.js → chunk-3MWCUIK4.js} +2 -2
  14. package/dist-cli/chunks/{chunk-AEKDLIFW.js → chunk-3RRDJNXM.js} +2 -2
  15. package/dist-cli/chunks/{chunk-EKTBF3PU.js → chunk-45XLWBNT.js} +1 -1
  16. package/dist-cli/chunks/{chunk-MLXZI2VU.js → chunk-5Q464MLB.js} +1 -1
  17. package/dist-cli/chunks/{chunk-NHWVFX3R.js → chunk-65GDTEX7.js} +3 -3
  18. package/dist-cli/chunks/{chunk-DYSZWMKF.js → chunk-6SXJQK5R.js} +3 -3
  19. package/dist-cli/chunks/{chunk-K6DR7C5H.js → chunk-6UA5JZ4E.js} +2 -2
  20. package/dist-cli/chunks/{chunk-Q6QBFWIS.js → chunk-7YEISEQ2.js} +2 -2
  21. package/dist-cli/chunks/{chunk-UGMBWU7M.js → chunk-B43JOK5N.js} +1 -1
  22. package/dist-cli/chunks/{chunk-JDEZIU6A.js → chunk-BFGPENAX.js} +1 -1
  23. package/dist-cli/chunks/{chunk-BYL2ZXSO.js → chunk-BUKMAGA6.js} +2 -2
  24. package/dist-cli/chunks/{chunk-YHLH2UZO.js → chunk-BWVKFTFM.js} +1 -1
  25. package/dist-cli/chunks/{chunk-Y3BXVPQA.js → chunk-CDLPRRMH.js} +2 -2
  26. package/dist-cli/chunks/{chunk-ZU3Y3JSR.js → chunk-DNTULI35.js} +1 -1
  27. package/dist-cli/chunks/{chunk-SOGORN62.js → chunk-GXFEY4YV.js} +1 -1
  28. package/dist-cli/chunks/chunk-H5YQDCRA.js +1 -0
  29. package/dist-cli/chunks/{chunk-QFNCCWKQ.js → chunk-IADOI73U.js} +2 -2
  30. package/dist-cli/chunks/{chunk-MQ4ES4QV.js → chunk-IIJQQIAP.js} +2 -2
  31. package/dist-cli/chunks/{chunk-GG4I3SBM.js → chunk-JPWK6SFZ.js} +1 -1
  32. package/dist-cli/chunks/{chunk-QWHEYTUI.js → chunk-KIDONDPE.js} +2 -2
  33. package/dist-cli/chunks/{chunk-L4SMKJAF.js → chunk-KO4VABY3.js} +1 -1
  34. package/dist-cli/chunks/{chunk-WMMLJ7UY.js → chunk-LBZGVNQE.js} +1 -1
  35. package/dist-cli/chunks/{chunk-FFPNLA27.js → chunk-LPVQM4H7.js} +2 -2
  36. package/dist-cli/chunks/{chunk-DVANCABF.js → chunk-MFPT2P6I.js} +1 -1
  37. package/dist-cli/chunks/{chunk-CGBHDP72.js → chunk-NHDDW7WP.js} +1 -1
  38. package/dist-cli/chunks/{chunk-Q6KGWTG3.js → chunk-NI2TIFUK.js} +1 -1
  39. package/dist-cli/chunks/{chunk-FCLKD5U3.js → chunk-NISJ26VT.js} +7 -32
  40. package/dist-cli/chunks/{chunk-LEUPCPVX.js → chunk-NK5T7NYR.js} +1 -1
  41. package/dist-cli/chunks/{chunk-MPJTH4SZ.js → chunk-NSEXBZUW.js} +2 -2
  42. package/dist-cli/chunks/chunk-OYWQKX2A.js +2 -0
  43. package/dist-cli/chunks/{chunk-PXDREKKK.js → chunk-PFFELWZN.js} +2 -2
  44. package/dist-cli/chunks/{chunk-KQW5FXIA.js → chunk-PGAGVXOZ.js} +2 -2
  45. package/dist-cli/chunks/chunk-PHRIZLTZ.js +1 -0
  46. package/dist-cli/chunks/{chunk-UKIYBW22.js → chunk-QIGU47UD.js} +1 -1
  47. package/dist-cli/chunks/{chunk-NCTGR5CW.js → chunk-VJRAGYZ6.js} +2 -2
  48. package/dist-cli/chunks/{chunk-JMLOSEXB.js → chunk-WNJOX4AQ.js} +2 -2
  49. package/dist-cli/chunks/chunk-WQF5CLFD.js +463 -0
  50. package/dist-cli/chunks/{chunk-PO6ZZXU5.js → chunk-WZ5JKRIA.js} +2 -2
  51. package/dist-cli/chunks/chunk-YKWGZWBE.js +1 -0
  52. package/dist-cli/chunks/{chunk-XCLGRBR7.js → chunk-YLSVHL4W.js} +2 -2
  53. package/dist-cli/chunks/{chunk-UO5XXQ53.js → chunk-YSN32GSR.js} +2 -2
  54. package/dist-cli/chunks/cli-version-QHAJ7OMR.js +2 -0
  55. package/dist-cli/chunks/{compat-BLVO5WCI.js → compat-EPSPO3GI.js} +3 -3
  56. package/dist-cli/chunks/{config-3FJKPOWY.js → config-7YGGAVYO.js} +2 -2
  57. package/dist-cli/chunks/{control-VU5ZXVAD.js → control-TMFCD2NX.js} +2 -2
  58. package/dist-cli/chunks/{cpu-profile-4MF47DGH.js → cpu-profile-44YYVMOE.js} +2 -2
  59. package/dist-cli/chunks/{daemon-5WV3TEOV.js → daemon-4XLAN5CC.js} +2 -2
  60. package/dist-cli/chunks/{debug-UJ5SRPFT.js → debug-MUYM2RWK.js} +3 -3
  61. package/dist-cli/chunks/{detox-EI6UZQAT.js → detox-NZJVVCA3.js} +2 -2
  62. package/dist-cli/chunks/{device-WGUF7AKG.js → device-7HMHAQ2Q.js} +2 -2
  63. package/dist-cli/chunks/{diagnose-P6MU3RU3.js → diagnose-FXVOC7LV.js} +2 -2
  64. package/dist-cli/chunks/drivers-GM6GJG7Q.js +2 -0
  65. package/dist-cli/chunks/{electron-OGUHFWUK.js → electron-NKK6Z2F3.js} +3 -3
  66. package/dist-cli/chunks/flow-3E4SG5M7.js +2 -0
  67. package/dist-cli/chunks/help-VIYWVIUB.js +2 -0
  68. package/dist-cli/chunks/{hints-7N4GV3ZE.js → hints-BLVNUKRX.js} +2 -2
  69. package/dist-cli/chunks/{home-paths-AANZCIZ5.js → home-paths-2QMRDV5X.js} +2 -2
  70. package/dist-cli/chunks/{inspect-RII7IRDI.js → inspect-E6Z6N3PK.js} +34 -34
  71. package/dist-cli/chunks/install-U7C5NDWU.js +2 -0
  72. package/dist-cli/chunks/{install-desktop-OO4TEBLO.js → install-desktop-O2E7FC4R.js} +3 -3
  73. package/dist-cli/chunks/{keys-UOR7DA3Y.js → keys-GWXMM5CC.js} +2 -2
  74. package/dist-cli/chunks/{launch-FEBSZFD3.js → launch-KWMHPASG.js} +3 -3
  75. package/dist-cli/chunks/{login-RBLUCSMW.js → login-AJO4L3ZI.js} +4 -4
  76. package/dist-cli/chunks/{logout-YUX36SXZ.js → logout-ZVGPEGAB.js} +2 -2
  77. package/dist-cli/chunks/{maestro-FACL5FAI.js → maestro-4QX23OEI.js} +2 -2
  78. package/dist-cli/chunks/optional-demo-registry-LKCGAST6.js +2 -0
  79. package/dist-cli/chunks/{preview-JHPF7LKC.js → preview-CGBGA343.js} +2 -2
  80. package/dist-cli/chunks/{profile-ADYZQ5J6.js → profile-RLKDXLSK.js} +2 -2
  81. package/dist-cli/chunks/{react-LZQFPQ6B.js → react-W2VGA55C.js} +2 -2
  82. package/dist-cli/chunks/{record-SAQPU2IQ.js → record-CF2HMY5Y.js} +2 -2
  83. package/dist-cli/chunks/runtime-A7DUL4IU.js +2 -0
  84. package/dist-cli/chunks/{runtime-delivery-FZNUZSUT.js → runtime-delivery-DZWXR2A5.js} +2 -2
  85. package/dist-cli/chunks/{screenshot-KXMYCKUF.js → screenshot-YV7USPJA.js} +2 -2
  86. package/dist-cli/chunks/{screenshot-mode-K7KP3GHW.js → screenshot-mode-V27UKIG6.js} +2 -2
  87. package/dist-cli/chunks/{screenshots-Z7YQYHGB.js → screenshots-BUOMYKKW.js} +2 -2
  88. package/dist-cli/chunks/{server-RFPTQNPD.js → server-6EZSHZV3.js} +3 -3
  89. package/dist-cli/chunks/setup-repo-MCAZJVL5.js +2 -0
  90. package/dist-cli/chunks/{skills-AJQCRGJE.js → skills-NXDCB76R.js} +2 -2
  91. package/dist-cli/chunks/{slides-7SEKUGSB.js → slides-6LF76Q4J.js} +2 -2
  92. package/dist-cli/chunks/{start-3N2SXPTE.js → start-5VNJWI56.js} +4 -4
  93. package/dist-cli/chunks/store-SX54DA6L.js +2 -0
  94. package/dist-cli/chunks/telemetry-PHXMPEY3.js +2 -0
  95. package/dist-cli/chunks/{test-BPVERVNB.js → test-KPKJXRDI.js} +3 -3
  96. package/dist-cli/chunks/{three-mode-5GSDNLD6.js → three-mode-RWCVKNGM.js} +2 -2
  97. package/dist-cli/chunks/{timeline-66ZJ4PFG.js → timeline-SRG5UM44.js} +2 -2
  98. package/dist-cli/chunks/{upgrade-SSG22SMA.js → upgrade-LMUTKCI4.js} +2 -2
  99. package/dist-cli/chunks/upload-3YJQJYAD.js +2 -0
  100. package/dist-cli/chunks/{version-VCIYUELO.js → version-P4LKM55A.js} +2 -2
  101. package/dist-cli/chunks/{web-56FLXL2W.js → web-5ZYKOZJG.js} +2 -2
  102. package/dist-cli/chunks/{what-happened-NW3U7BQM.js → what-happened-AFWB7XTD.js} +2 -2
  103. package/dist-cli/chunks/{whoami-56CZBGT2.js → whoami-YXJ6KECJ.js} +2 -2
  104. package/dist-lib/agent-daemon-client.cjs +1 -1
  105. package/dist-lib/agent-events.cjs +1 -1
  106. package/dist-lib/agent-sessions.cjs +1 -1
  107. package/dist-lib/attached-projects.cjs +1 -1
  108. package/dist-lib/auth/shared-session.cjs +1 -1
  109. package/dist-lib/backend-origin.cjs +1 -1
  110. package/dist-lib/beta.cjs +1 -1
  111. package/dist-lib/beta.mjs +1 -1
  112. package/dist-lib/bridge-constants.cjs +1 -1
  113. package/dist-lib/cli-constants.cjs +1 -1
  114. package/dist-lib/config.cjs +1 -1
  115. package/dist-lib/detox/index.cjs +1 -1
  116. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  117. package/dist-lib/home-paths.cjs +1 -1
  118. package/dist-lib/host/bridge-host.cjs +1 -1
  119. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  120. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  121. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  122. package/dist-lib/host/websocket-proxy.cjs +1 -1
  123. package/dist-lib/index.cjs +1 -1
  124. package/dist-lib/metro.cjs +1 -1
  125. package/dist-lib/profiles.cjs +1 -1
  126. package/dist-lib/render-mode.cjs +1 -1
  127. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  128. package/dist-lib/sdk.cjs +1 -1
  129. package/dist-lib/sdk.mjs +1 -1
  130. package/dist-lib/skills.cjs +152 -55
  131. package/dist-lib/vite.cjs +1 -1
  132. package/package.json +1 -1
  133. package/dist-cli/chunks/auto-bootstrap-ZFEKV5N5.js +0 -2
  134. package/dist-cli/chunks/beta-FKWWIATG.js +0 -2
  135. package/dist-cli/chunks/chunk-6HSKGTN3.js +0 -1
  136. package/dist-cli/chunks/chunk-FE4WZMPN.js +0 -1
  137. package/dist-cli/chunks/chunk-ODLM2KEX.js +0 -1
  138. package/dist-cli/chunks/chunk-UM2U5JQE.js +0 -2
  139. package/dist-cli/chunks/chunk-YCZB7NKY.js +0 -386
  140. package/dist-cli/chunks/cli-version-XNIRTBJN.js +0 -2
  141. package/dist-cli/chunks/drivers-ISZDFEMB.js +0 -2
  142. package/dist-cli/chunks/flow-5WJLI3KM.js +0 -2
  143. package/dist-cli/chunks/help-25RH7GSX.js +0 -2
  144. package/dist-cli/chunks/install-LBOWGAGG.js +0 -2
  145. package/dist-cli/chunks/optional-demo-registry-RIDIENLK.js +0 -2
  146. package/dist-cli/chunks/runtime-TJT4YSOY.js +0 -2
  147. package/dist-cli/chunks/setup-repo-UQXTC4PO.js +0 -2
  148. package/dist-cli/chunks/store-BKCI7NRB.js +0 -2
  149. package/dist-cli/chunks/telemetry-H4J7ZTQF.js +0 -2
  150. package/dist-cli/chunks/upload-ITKMHX55.js +0 -2
@@ -0,0 +1,463 @@
1
+ /*! sootsim v0.1.150 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as Be}from"./chunk-PFFELWZN.js";import{a as Le}from"./chunk-IADOI73U.js";import{a as je}from"./chunk-BUKMAGA6.js";import{a as Se,b as Ee,c as ne,d as re,e as Ie,f as ie,h as oe,i as Pe,j as Me}from"./chunk-NISJ26VT.js";import{g as Re,n as Ne,p as Ce,t as De}from"./chunk-3CENW2HN.js";import{e as Oe}from"./chunk-VJRAGYZ6.js";import{m as ke}from"./chunk-IIJQQIAP.js";import{m as xe,n as Te,o as $e,p as Fe}from"./chunk-QIGU47UD.js";import{c as ee,d as te,e as ve}from"./chunk-6UA5JZ4E.js";import{a as Ae}from"./chunk-BFGPENAX.js";import{a as _e}from"./chunk-LBZGVNQE.js";import{d as Q,e as be}from"./chunk-NI2TIFUK.js";import{a as ge,b as Z}from"./chunk-PGAGVXOZ.js";import{g as ye}from"./chunk-BWVKFTFM.js";import*as _ from"fs";import{tmpdir as He}from"os";import*as b from"path";import*as v from"fs";import*as g from"path";import{spawnSync as nt}from"child_process";import*as A from"vm";var rt=3e5,it=`
3
+ let input = '';
4
+ process.stdin.on('data', (c) => { input += c });
5
+ process.stdin.on('end', async () => {
6
+ try {
7
+ const req = JSON.parse(input);
8
+ const res = await fetch(req.url, {
9
+ method: req.method,
10
+ headers: req.headers,
11
+ body: req.body === undefined || req.body === null ? undefined : req.body,
12
+ });
13
+ const body = await res.text();
14
+ const headers = {};
15
+ for (const [k, v] of res.headers.entries()) {
16
+ headers[k] = headers[k] ? headers[k] + ',' + v : v;
17
+ }
18
+ process.stdout.write(JSON.stringify({ ok: res.ok, status: res.status, body, headers }));
19
+ } catch (err) {
20
+ process.stdout.write(JSON.stringify({ __error: (err && err.message) || String(err) }));
21
+ process.exitCode = 1;
22
+ }
23
+ });
24
+ `;function D(i,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let n={...process.env};for(let a of Object.keys(n))(a.startsWith("BUN_INSPECT")||a==="NODE_OPTIONS")&&delete n[a];let r=nt(process.execPath,["-e",it],{input:JSON.stringify({url:i,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:rt,maxBuffer:64*1024*1024,env:n});if(r.error)throw new Error(`http ${e} ${i} failed: ${r.error.message}`);let o;try{o=JSON.parse(r.stdout||"")}catch{throw new Error(`http ${e} ${i} failed: no response (${(r.stderr||"").trim().slice(0,200)})`)}let s=o;if(s.__error)throw new Error(`http ${e} ${i} failed: ${s.__error}`);return s}var ot=/(?<!\\)\$\{([^$]*)\}/g,st=/\\(\$\{[^$]*\})/g,at=/^[A-Za-z_$][A-Za-z0-9_$]*$/,U=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}`)),n={output:this.output,maestro:this.maestro,http:{get:(r,o)=>D(r,"GET",o),post:(r,o)=>D(r,"POST",o),put:(r,o)=>D(r,"PUT",o),delete:(r,o)=>D(r,"DELETE",o),request:(r,o)=>D(r,(o?.method??"GET").toUpperCase(),o)},console:{log:(...r)=>t(r.map(o=>typeof o=="string"?o:Ve(o)).join(" "))}};this.context=A.createContext(n),A.runInContext(`
25
+ globalThis.__maestroScope = new Proxy(globalThis, {
26
+ has() { return true },
27
+ get(target, key) { return target[key] },
28
+ })
29
+ function json(text) { return JSON.parse(text) }
30
+ function relativePoint(x, y) {
31
+ var xPercent = Math.ceil(x * 100) + '%'
32
+ var yPercent = Math.ceil(y * 100) + '%'
33
+ return xPercent + ',' + yPercent
34
+ }
35
+ `,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,n]of e)this.envBinding.set(t,n)}}evaluate(e,t={}){let n=t.env;if(n&&Object.keys(n).length>0){this.enterEnvScope();try{for(let[r,o]of Object.entries(n))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 A.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=A.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,n]of this.envBinding)try{e[t]=n,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(ot,(n,r)=>{if(r.trim().length===0)return"";let o=this.evaluate(r);if(o===void 0&&at.test(r.trim()))throw new Error(`missing variable for flow placeholder: ${r.trim()}`);return Ve(o)}).replace(st,(n,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(n=>this.interpolateValue(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,this.interpolateValue(r,n)])):e}};function Ve(i){if(i===void 0)return"undefined";if(i===null)return"null";if(typeof i=="object")try{return JSON.stringify(i)}catch{return String(i)}return String(i)}function Je(i){if(i==null)return!1;if(typeof i=="boolean")return i;let e=String(i);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 W=1e4,H=393,O=852,Ue="__sootsimCliPerf";function p(i){return new Promise(e=>setTimeout(e,i))}function lt(i){return i?g.basename(i)===".maestro"?g.dirname(i):i:process.cwd()}function ct(i,e,t){let n=e.endsWith(".png")?e:`${e}.png`;if(g.isAbsolute(n))return n;if(t.mode==="flow"&&/[\\/]/.test(n)){let r=n.startsWith("./")||n.startsWith("../")?t.flowDir??process.cwd():lt(t.flowDir);return g.resolve(r,n)}return g.join(i,n)}function dt(i){if(typeof i=="string")return{path:i,withFrame:!1};let e=i.path?.trim()||i.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:i.withFrame===!0,layers:i.layers}}function se(i){let[e,t]=i.split(",").map(r=>r.trim()),n=(r,o)=>r.endsWith("%")?Number.parseFloat(r)/100*o:Number.parseFloat(r);return{x:n(e,H),y:n(t,O)}}function ut(i){switch(i){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{[i]:!0}}}function ft(i){let e=i.split(/^---$/m),t=e.length>1?e[e.length-1]:i,n=Ee.parse(t);return Array.isArray(n)?n:[]}var K=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new U({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingDurationMs=null;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 n=t.searchParams.toString();return`${t.origin}${t.pathname}${n?`?${n}`:""}`}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"),s=e.find(l=>l.readyState==="open"),a=r??o??s;a&&(this.opts.simId=a.id,console.log(` [flow] sim rotated to ${a.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=W){let t=Date.now()+e,n=Date.now(),r=null,o=0,s=0,a=-1,l=n;for(;Date.now()<t;){try{let c=await this.evaluate(xe,8e3);if(o=0,c?.externalError)throw new Error(`app failed to load: ${c.externalError}`);if(c){let h=Date.now();c.nodes!==a&&(a=c.nodes,l=h);let P=c.flag===!0&&$e(c),w=c.flag!==!0&&Fe(c);if((P||w)&&c.externalReady!==!1&&!c.externalError&&!c.loadingText&&h-l>=Te)return}}catch(c){if(r=c instanceof Error?c:new Error(String(c)),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 f=Date.now()-n;f-s>=5e3&&(s=f,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(f/1e3)}s)`)),await p(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||(await Le("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
36
+ const rec = window.__sootsimRecorder
37
+ if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
38
+ const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
39
+ if (rec.state() === 'recording') return { ok: true, format }
40
+ return rec.start({ format, fps: 24 })
41
+ })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}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,new Error(t?.error||"recording stop failed");this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.recordingStartedAtMs=null;let n=[],r=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${r}, chunk: 2097152 })`);if(!l||(n.push(Buffer.from(l.data,"base64")),r=l.offset,l.done))break}if(n.length===0)throw new Error("recording requested but no video buffer was produced");v.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let s=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",a=g.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${s}`);return v.writeFileSync(a,Buffer.concat(n)),a}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await p(t);return}let n=await Me({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(n.settled?` [flow] recording tail settled in ${n.elapsed}ms`:` [flow] recording tail reached ${n.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 () => {
42
+ const test = window.__sootsimTest
43
+ if (!test) return null
44
+ let node = null
45
+ if (${JSON.stringify(!!e.text)}) {
46
+ node = await test.findByText(${JSON.stringify(e.text||"")})
47
+ // maestro matches a text selector against the element's ACCESSIBILITY
48
+ // text too, not just rendered glyphs \u2014 icon-only buttons (e.g. bluesky's
49
+ // "Pin to Home" / "Mute accounts" pin/menu controls) carry the label on
50
+ // accessibilityLabel with no visible text node, so findByText misses
51
+ // them. fall back to an exact a11y-label match, mirroring the real
52
+ // driver. findByLabel resolves a node, but its info shape omits nodeId/
53
+ // isTextInput; re-resolve through findByTestId/findById when it exposes
54
+ // an id so tapOn still gets a resolveTapTarget-able nodeId.
55
+ if (!node) {
56
+ const labelled = await test.findByLabel?.(${JSON.stringify(e.text||"")})
57
+ if (labelled) {
58
+ const reId = labelled.testID || labelled.id
59
+ node =
60
+ (reId &&
61
+ ((await test.findByTestId?.(reId)) || (await test.findById?.(reId)))) ||
62
+ labelled
63
+ }
64
+ }
65
+ if (!node && ${JSON.stringify(t)} && test.queryAll) {
66
+ // regex selector fallback: match the pattern against each visible
67
+ // node's text; prefer the narrowest matching node so a tight <text>
68
+ // wins over a wide container that merely contains it.
69
+ let re = null
70
+ try { re = new RegExp(${JSON.stringify(e.text||"")}) } catch (e) { re = null }
71
+ if (re) {
72
+ const all = (await test.queryAll({ pruneHidden: true })) || []
73
+ const hits = all.filter(
74
+ (n) =>
75
+ n && n.absolutePosition && n.layout &&
76
+ typeof n.text === 'string' && re.test(n.text),
77
+ )
78
+ hits.sort((a, b) => (a.text || '').length - (b.text || '').length)
79
+ if (hits[0]) node = hits[0]
80
+ }
81
+ }
82
+ }
83
+ if (!node && ${JSON.stringify(!!e.id)}) {
84
+ node = (await test.findByTestId(${JSON.stringify(e.id||"")})) || (await test.findById(${JSON.stringify(e.id||"")}))
85
+ }
86
+ if (!node || !node.absolutePosition || !node.layout) return null
87
+ return {
88
+ nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
89
+ id: node.id || null,
90
+ testID: node.testID || null,
91
+ text: node.text || null,
92
+ absolutePosition: node.absolutePosition,
93
+ layout: node.layout,
94
+ isTextInput: !!node.isTextInput,
95
+ }
96
+ })()`)}async findElementScoped(e){let t=typeof e.index=="number"?e.index:0;return this.evaluate(`(async () => {
97
+ const test = window.__sootsimTest
98
+ if (!test || !test.queryAll) return null
99
+ // NOT pruneHidden: that over-filters (it dropped every postDropdownBtn in a
100
+ // feed and made index:0 resolve to nothing \u2014 worse than findByTestId). reach
101
+ // for the same set findByTestId sees, then PREFER on-screen ones below.
102
+ const filter = {}
103
+ if (${JSON.stringify(!!e.id)}) filter.hasId = ${JSON.stringify(e.id||"")}
104
+ if (${JSON.stringify(!!e.text)}) filter.hasText = ${JSON.stringify(e.text||"")}
105
+ let candidates = (await test.queryAll(filter)) || []
106
+ // a11y-label fallback (icon-only buttons) for text matchers, mirroring
107
+ // findElement's simple path.
108
+ if (${JSON.stringify(!!e.text)} && candidates.length === 0) {
109
+ const all = (await test.queryAll({})) || []
110
+ candidates = all.filter((n) => (n.accessibilityLabel || '') === ${JSON.stringify(e.text||"")})
111
+ }
112
+ candidates = candidates.filter((n) => n && n.absolutePosition && n.layout)
113
+ // prefer on-screen matches (findByTestId's visible-first behavior); only
114
+ // fall back to off-screen ones when nothing is on-screen, so index: still
115
+ // resolves a target that needs scrolling into view.
116
+ const onScreen = candidates.filter((n) => {
117
+ const cy = n.absolutePosition.y + n.layout.height / 2
118
+ return cy > 0 && cy < ${O}
119
+ })
120
+ if (onScreen.length > 0) candidates = onScreen
121
+ ${e.childOf?`
122
+ const container = ${e.childOf.id?`(await test.findByTestId(${JSON.stringify(e.childOf.id)})) || (await test.findById(${JSON.stringify(e.childOf.id)}))`:`await test.findByText(${JSON.stringify(e.childOf.text||"")})`}
123
+ if (!container || !container.absolutePosition || !container.layout) return null
124
+ const x0 = container.absolutePosition.x
125
+ const y0 = container.absolutePosition.y
126
+ const x1 = x0 + container.layout.width
127
+ const y1 = y0 + container.layout.height
128
+ candidates = candidates.filter((n) => {
129
+ const cx = n.absolutePosition.x + n.layout.width / 2
130
+ const cy = n.absolutePosition.y + n.layout.height / 2
131
+ return cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1
132
+ })`:""}
133
+ const node = candidates[${t}]
134
+ if (!node) return null
135
+ return {
136
+ nodeId: typeof node.nodeId === 'number' ? node.nodeId : null,
137
+ id: node.id || null,
138
+ testID: node.testID || null,
139
+ text: node.text || null,
140
+ absolutePosition: node.absolutePosition,
141
+ layout: node.layout,
142
+ isTextInput: !!node.isTextInput,
143
+ }
144
+ })()`)}async resolveTapTarget(e){return this.evaluate(`(async () => {
145
+ const test = window.__sootsimTest
146
+ if (!test?.resolveTapTarget) return null
147
+ return await test.resolveTapTarget(${e})
148
+ })()`)}async activatePressTarget(e){let t=e.id?{id:e.id,testID:e.id,text:null}:{id:null,testID:null,text:e.text??null};return this.evaluate(`(async () => {
149
+ const test = window.__sootsimTest
150
+ if (!test) return null
151
+ const node = ${e.id?`(await test.findByTestId?.(${JSON.stringify(e.id)})) || (await test.findById?.(${JSON.stringify(e.id)}))`:`await test.findByText?.(${JSON.stringify(e.text||"")})`}
152
+ let point = null
153
+ if (node?.absolutePosition && node?.layout) {
154
+ point = {
155
+ x: node.absolutePosition.x + node.layout.width / 2,
156
+ y: node.absolutePosition.y + node.layout.height / 2,
157
+ }
158
+ if (typeof node.nodeId === 'number' && test.resolveTapTarget) {
159
+ const resolved = await test.resolveTapTarget(node.nodeId)
160
+ if (
161
+ resolved &&
162
+ Number.isFinite(resolved.cx) &&
163
+ Number.isFinite(resolved.cy)
164
+ ) {
165
+ point = { x: resolved.cx, y: resolved.cy }
166
+ }
167
+ }
168
+ }
169
+ ${e.id?`const direct = await test.activatePressById?.(${JSON.stringify(e.id)})`:`const direct = await test.activatePressByText?.(${JSON.stringify(e.text||"")})`}
170
+ if (direct?.ok && point) {
171
+ window.dispatchEvent(
172
+ new CustomEvent('sootsim:agentAction', {
173
+ detail: { type: 'tap', x: point.x, y: point.y, target: ${JSON.stringify(t)} },
174
+ }),
175
+ )
176
+ }
177
+ return direct || null
178
+ })()`)}async activatePressAt(e,t){return this.evaluate(`(async () => {
179
+ const test = window.__sootsimTest
180
+ if (!test?.activatePressAt) return null
181
+ const direct = await test.activatePressAt(${e}, ${t})
182
+ if (direct?.ok) {
183
+ window.dispatchEvent(
184
+ new CustomEvent('sootsim:agentAction', {
185
+ detail: { type: 'tap', x: ${e}, y: ${t} },
186
+ }),
187
+ )
188
+ }
189
+ return direct
190
+ })()`)}async tap(e,t,n){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:n})}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let l=se(t.point);(await this.activatePressAt(l.x,l.y))?.ok||await this.tap(l.x,l.y),await p(300);return}let n=5e3,r=150,o=Date.now()+n,s=await this.findElement({text:t.text,id:t.id});for(;!s&&Date.now()<o;)await p(r),s=await this.findElement({text:t.text,id:t.id});if(s){let l=s.isTextInput?4:1;for(let f=0;f<l;f++){let c=f===0?s:await this.findElement({text:t.text,id:t.id});if(!c)break;let h=typeof c.nodeId=="number"?await this.resolveTapTarget(c.nodeId):null,P=h?.cx??c.absolutePosition.x+c.layout.width/2,w=h?.cy??c.absolutePosition.y+c.layout.height/2;if((await this.tap(P,w,{id:t.id??h?.target?.id??c.id??null,testID:t.id??h?.target?.testID??c.testID??null,text:t.text??h?.target?.text??h?.target?.accessibilityLabel??c.text??c.accessibilityLabel??null,type:h?.target?.type??c.type??null}))?.hit===!0){if(await p(300),!c.isTextInput||await this.waitForFocusedTextInput(600))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await p(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async tapAtCoords(e,t){await this.tap(e,t),await p(300)}async doubleTapAtCoords(e,t,n=80){let r=Math.max(0,Math.round(n));if(!await this.evaluate(`(async () => {
191
+ const interact = window.__sootsimInteract
192
+ if (interact?.doubleTap) {
193
+ return !!(await interact.doubleTap(${e}, ${t}, ${r}))
194
+ }
195
+ if (!interact?.tap) return false
196
+ const first = await interact.tap(${e}, ${t})
197
+ if (!first || first.hit === false) return false
198
+ await new Promise((resolve) => setTimeout(resolve, ${r}))
199
+ const second = await interact.tap(${e}, ${t})
200
+ return !!second && second.hit !== false
201
+ })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await p(300)}async assertVisible(e){let t=typeof e=="string"?{text:e}:e;for(let o=0;o<15;o++){if(await this.isElementVisible(t))return;await p(200)}let n=await this.findElement(t),r=n?` (matched node at y=${Math.round(n.absolutePosition.y)} h=${Math.round(n.layout.height)} \u2014 off-screen)`:" (no matching node in tree)";throw new Error(`assertVisible: ${JSON.stringify(t)} not visible${r}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let n=await this.findElement(t),r=n?` at (${Math.round(n.absolutePosition.x)},${Math.round(n.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${r}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<O)}async inputText(e){await this.waitForFocusedTextInput(),await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await p(200)}async waitForFocusedTextInput(e=1500){let t=Date.now()+e;for(;Date.now()<t;){try{if(await this.callTest("getFocusedNode"))return!0}catch{}await p(50)}return!1}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await p(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await p(120)}async hideKeyboard(){try{await this.callTest("blurFocusedTextInput")}catch{}await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dismiss"});let e=Date.now()+3e3;for(;Date.now()<e;){let t=await this.evaluate(`(() => {
202
+ const keyboard =
203
+ window.__sootsimKeyboard ??
204
+ window.SootSim?.bridges?.keyboard ??
205
+ null
206
+ const test = window.__sootsimTest
207
+ return {
208
+ visible: !!keyboard?.isVisible?.(),
209
+ focused: !!test?.isTextInputFocused?.(),
210
+ }
211
+ })()`);if(!t?.visible&&!t?.focused){await p(80);return}await p(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.pressKey("Backspace");await p(100)}async waitFor(e){let t=Date.now()+(e.timeout||W);for(;Date.now()<t;){if(await this.findElement(e))return;await p(200)}let n=await this.findElement(e),r=n?` (matched node y=${Math.round(n.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||W}ms${r}`)}async takeScreenshot(e){try{await this.waitForVisualSettle()}catch{}await p(250);let t=dt(e),n=ct(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});v.mkdirSync(g.dirname(n),{recursive:!0});let r=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};r&&r!=="full"&&(o.layers=r);let a=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(a,"base64");if(t.withFrame){let f=await this.readCurrentDeviceModel();if(!f)throw new Error("could not read current device model for framed screenshot");let c=await Be(l,f);v.writeFileSync(n,c),console.log(`[flow] screenshot: ${n} (frame: ${f})`);return}v.writeFileSync(n,l),console.log(`[flow] screenshot: ${n}`)}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 ye)?null:t}async captureFailureScreenshot(e){v.mkdirSync(g.dirname(e),{recursive:!0});let n=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");v.writeFileSync(e,Buffer.from(n,"base64"))}async captureFailureBundle(e,t){v.mkdirSync(e,{recursive:!0});let n=(c,h)=>{try{v.writeFileSync(g.join(e,c),h)}catch{}},r=async c=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:c})}catch{return null}},o=await r(`(async () => {
212
+ const out = {
213
+ simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
214
+ url: location.href,
215
+ title: document.title,
216
+ hidden: document.hidden,
217
+ }
218
+ try {
219
+ const params = new URL(location.href).searchParams
220
+ const bundle = params.get('bundle')
221
+ if (bundle) {
222
+ const baseMatch = bundle.match(/^https?:\\/\\/[^/]+/)
223
+ if (baseMatch) {
224
+ const res = await fetch(baseMatch[0] + '/', {
225
+ headers: { 'expo-platform': 'ios' },
226
+ cache: 'no-store',
227
+ })
228
+ if (res.ok) {
229
+ out.manifest = await res.json().catch(() => null)
230
+ }
231
+ }
232
+ }
233
+ } catch {}
234
+ return out
235
+ })()`);n("error.json",JSON.stringify({message:t.error.message,stack:t.error.stack,stepIndex:t.stepIndex,stepKind:t.stepKind,stepTarget:t.stepTarget,capturedAt:new Date().toISOString(),sim:o??null},null,2));try{let h=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");n("screenshot.png",Buffer.from(h,"base64"))}catch{}let s=await r(`(async () => {
236
+ const t = window.__sootsimTest
237
+ const mainShell = window.SootSim?.bridges?.mainShell
238
+ if (!t) return { error: 'no test bridge' }
239
+ let shell = null
240
+ try {
241
+ shell = typeof mainShell?.getState === 'function' ? await mainShell.getState() : null
242
+ } catch {}
243
+ const all = await t.queryAll({ pruneHidden: true })
244
+ return { shell, nodes: all, url: location.href, title: document.title }
245
+ })()`);s&&n("describe.json",JSON.stringify(s,null,2));let a=await r("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof a=="string"&&n("a11y.txt",a);let l=await r("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&n("tree.txt",l);let f=await r(`(() => {
246
+ const c = window.__sootsimConsole
247
+ return {
248
+ errors: c?.getErrors?.() ?? [],
249
+ warnings: c?.getWarnings?.() ?? [],
250
+ requests: (window.__sootsimGetFailedRequests?.() ?? []),
251
+ }
252
+ })()`);return f&&n("console.json",JSON.stringify(f,null,2)),e}async swipe(e="UP",t=300){let n=H/2,r=O/2,o=200,s=n,a=r,l=n,f=r;switch(e.toUpperCase()){case"UP":a+=o,f-=o;break;case"DOWN":a-=o,f+=o;break;case"LEFT":s+=o,l-=o;break;case"RIGHT":s-=o,l+=o;break}let c=Math.max(10,Math.round(t/16));await this.drag(s,a,l,f,c,16)}async drag(e,t,n,r,o=12,s=16){if(!(await this.evaluate(`(async () => {
253
+ const interact = window.__sootsimInteract
254
+ if (!interact?.drag) return { ok: false }
255
+ const value = await interact.drag(${e}, ${t}, ${n}, ${r}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(s))})
256
+ return { ok: !!value, value }
257
+ })()`))?.ok)throw new Error("drag failed");await p(300)}async swipeCoords(e,t,n=300){let r=se(e),o=se(t),s=Math.max(10,Math.round(n/16));await this.drag(r.x,r.y,o.x,o.y,s,16)}async swipeFrom(e,t="UP",n=300){let r=await this.findElement(e);if(!r)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=r.absolutePosition.x+r.layout.width/2,s=r.absolutePosition.y+r.layout.height/2,a=180,l=o,f=s;switch(t.toUpperCase()){case"UP":f-=a;break;case"DOWN":f+=a;break;case"LEFT":l-=a;break;case"RIGHT":l+=a;break}let c=Math.max(10,Math.round(n/16));await this.drag(o,s,l,f,c,16)}async scrollTo(e,t,n){let r=await this.callTest("scrollTo",e,t,n,!1);if(!r?.ok)throw new Error(`scrollTo failed: ${r?.reason||"unknown error"}`);await p(250)}async pinch(e){let t=await this.evaluate(`(async () => {
258
+ const interact = window.__sootsimInteract
259
+ if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
260
+ const ok = await interact.pinch(
261
+ ${e.from[0]}, ${e.from[1]}, ${e.from[2]}, ${e.from[3]},
262
+ ${e.to[0]}, ${e.to[1]}, ${e.to[2]}, ${e.to[3]},
263
+ ${e.steps||12}, ${e.stepMs||16}
264
+ )
265
+ return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
266
+ })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await p(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){await p(e)}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),n=e.direction?.toUpperCase()||"DOWN",r=n==="DOWN"?"UP":n==="UP"?"DOWN":n;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<O-50){if(e.centerElement){let s=O/2,a=o.absolutePosition.y-s;if(Math.abs(a)>100){let l=Math.min(150,Math.abs(a)*.5),f=a>0?s-l:s+l;await this.drag(H/2,s,H/2,f,10,16)}}return}await this.swipe(r,250),await p(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||W);for(;Date.now()<t;){let n=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(n&&r)return;await p(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(Se(!0),2e4)}catch{await p(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 p(500),await this.refreshSimId()}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);if(!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,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(n){console.warn(` warn: onAfterLaunch hook threw: ${n instanceof Error?n.message:n}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
267
+ requestAnimationFrame(() => {
268
+ requestAnimationFrame(() => {
269
+ requestAnimationFrame(() => {
270
+ setTimeout(resolve, 180)
271
+ })
272
+ })
273
+ })
274
+ })`)}catch{await p(180)}}async startProfile(){await this.evaluate(`((sessionKey) => {
275
+ const perf = window.__sootsimPerf
276
+ const a11y = window.__sootsimA11y
277
+ perf?.enableFrameStats?.(true)
278
+ perf?.resetFrameStats?.()
279
+ a11y?.resetProfile?.()
280
+ window[sessionKey] = {
281
+ active: true,
282
+ mode: window.__sootsimRenderHost ? 'render-worker' : 'main-thread',
283
+ lastSamples: [],
284
+ startedAt: performance.now(),
285
+ }
286
+ })(${JSON.stringify(Ue)})`),this.profilingEnabled=!0}async stopProfile(){let e=await this.evaluate(`(async (sessionKey) => {
287
+ const host = window.__sootsimRenderHost
288
+ if (host?.flushSamples) {
289
+ const perf = window.__sootsimPerf
290
+ const session = window[sessionKey] || {}
291
+ const priorSamples = session.active && Array.isArray(session.lastSamples)
292
+ ? session.lastSamples
293
+ : []
294
+ const flushedSamples = await host.flushSamples()
295
+ await perf?.disableFrameStats?.()
296
+ const samples = priorSamples.concat(flushedSamples)
297
+ window[sessionKey] = {
298
+ ...session,
299
+ active: false,
300
+ mode: 'render-worker',
301
+ lastSamples: samples,
302
+ stoppedAt: performance.now(),
303
+ }
304
+
305
+ const frameTimes = samples.map((sample) => Number(sample?.[1]) || 0)
306
+ const sorted = [...frameTimes].sort((a, b) => a - b)
307
+ const worstFrames = samples
308
+ .slice()
309
+ .sort((a, b) => (Number(b?.[1]) || 0) - (Number(a?.[1]) || 0))
310
+ .slice(0, 10)
311
+ .map((sample) => [
312
+ Number(sample?.[0]) || 0,
313
+ Number(sample?.[1]) || 0,
314
+ Number(sample?.[2]) || 0,
315
+ Number(sample?.[3]) || 0,
316
+ Number(sample?.[4]) || 0,
317
+ ])
318
+
319
+ return {
320
+ mode: 'render-worker',
321
+ frames: frameTimes.length,
322
+ totalMs: frameTimes.reduce((sum, value) => sum + value, 0),
323
+ avgMs: frameTimes.length ? frameTimes.reduce((sum, value) => sum + value, 0) / frameTimes.length : 0,
324
+ maxMs: sorted[sorted.length - 1] || 0,
325
+ layoutTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0),
326
+ renderTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0),
327
+ copyTotalMs: samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0),
328
+ layoutAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[2]) || 0), 0) / frameTimes.length : 0,
329
+ renderAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[3]) || 0), 0) / frameTimes.length : 0,
330
+ copyAvgMs: frameTimes.length ? samples.reduce((sum, sample) => sum + (Number(sample?.[4]) || 0), 0) / frameTimes.length : 0,
331
+ p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
332
+ p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
333
+ p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
334
+ jankFrames: frameTimes.filter((value) => value > 16.67).length,
335
+ sampleCount: frameTimes.length,
336
+ worstFrames,
337
+ }
338
+ }
339
+
340
+ const perf = window.__sootsimPerf
341
+ const a11y = window.__sootsimA11y
342
+ if (!perf && !a11y) return { error: 'no perf globals available' }
343
+
344
+ const stoppedStats = await perf?.disableFrameStats?.()
345
+ const frameStats = stoppedStats || await perf?.getFrameStats?.() || {}
346
+ const profile = a11y?.profile?.() || {}
347
+ const recent = Array.isArray(frameStats.recentFrames) ? frameStats.recentFrames : []
348
+ const sorted = [...recent].sort((a, b) => a - b)
349
+
350
+ return {
351
+ mode: 'main-thread',
352
+ frames: frameStats.frames || profile.syncCount || 0,
353
+ totalMs: frameStats.totalMs || 0,
354
+ avgMs: frameStats.totalMs && frameStats.frames ? frameStats.totalMs / frameStats.frames : profile.avgSyncMs || 0,
355
+ maxMs: frameStats.maxMs || profile.maxSyncMs || 0,
356
+ layoutTotalMs: frameStats.layoutTotalMs || 0,
357
+ p50: sorted[Math.floor(sorted.length * 0.5)] || 0,
358
+ p95: sorted[Math.floor(sorted.length * 0.95)] || 0,
359
+ p99: sorted[Math.floor(sorted.length * 0.99)] || 0,
360
+ jankFrames: recent.filter((value) => value > 16.67).length,
361
+ sampleCount: recent.length,
362
+ worstFrames: recent.slice().sort((a, b) => b - a).slice(0, 10),
363
+ }
364
+ })(${JSON.stringify(Ue)})`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!0)}async clearState(){await this.reloadGuestApp(!0)}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,n=await this.findElement(t);if(!n)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let r=n.text??n.testID??"";this.js.setCopiedText(r),this.js.putEnv("maestroCopiedText",r),console.log(`[flow] copied text: ${JSON.stringify(r)}`)}evalScript(e){let n=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);n!==void 0&&n!==""&&console.log("[flow] evalScript ->",n)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let n=g.resolve(this.opts.flowDir,t.file),r=v.readFileSync(n,"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 n=await this.callTest("openDeepLink",t);if(!n?.ok)throw new Error(`openLink failed: ${n?.error||"no test bridge"}`);await p(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?Je(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let n=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),r=n?n[1]:void 0;return!!(r&&typeof r=="object"&&"optional"in r&&r.optional)}async runStep(e,t){let n=typeof e=="string"?ut(e):e,r=Object.keys(n).find(s=>s!=="when")||Object.keys(n)[0];console.log(`[flow] step ${t+1}: ${r}`);let o;try{o=this.js.interpolateStep(n)}catch(s){if(this.isOptional(n)){console.log(`[flow] (optional, skipped: ${s.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:n[r]},s}if(o.when&&!await this.evaluateWhen(o.when)){console.log("[flow] (when: predicate false, skipped)");return}try{let s=!!(o.extendedWaitUntil||o.waitFor||o.scrollUntilVisible||o.launchApp||o.runFlow||o.runScript),a=1e4,l=this.runStepInner(o);if(s)await l;else{let c=null,h=new Promise((P,w)=>{c=setTimeout(()=>{w(new Error(`step watchdog: ${r} made no progress in ${a}ms \u2014 bridge or bundle probably hung`))},a)});try{await Promise.race([l,h])}finally{c&&clearTimeout(c)}}let f=!!(o.assertVisible||o.assertNotVisible||o.extendedWaitUntil||o.waitFor);this.stepDelay>0&&!f&&await p(this.stepDelay)}catch(s){if(this.isOptional(o)){console.log(`[flow] (optional, skipped: ${s.message.slice(0,80)})`);return}throw this.lastFailedStep={index:t,kind:r,target:o[r]},s}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);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)await this.waitForAnimationToEnd(typeof e.waitForAnimationToEnd=="number"?e.waitForAnimationToEnd: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 p(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,n=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(n))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,s=r?n:Math.min(n,1e3),a=0;for(;a<s&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);a++}}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,n=typeof t=="string"?void 0:t.when;if(n&&!await this.evaluateWhen(n)){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,n=typeof t=="string"?t:t.file,r=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,s=typeof t=="string"?void 0:t.when;if(s&&!await this.evaluateWhen(s)){console.log(`[flow] runFlow skipped (when predicate false): ${n??"inline commands"}`);return}if(!n&&!r)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[a,l]of Object.entries(o))this.js.putEnv(a,l);if(n){let a=g.resolve(this.opts.flowDir,n),l=v.readFileSync(a,"utf8"),f=this.opts.flowDir;this.opts.flowDir=g.dirname(a);try{await this.runFlow(ft(l))}finally{this.opts.flowDir=f}}else if(r)for(let a=0;a<r.length;a++)await this.runStep(r[a],a)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}async runFlow(e){let t=[],n=[],r=[];for(let s of e){let a=Object.keys(s);if(a.length===1&&a[0]==="onFlowStart"&&Array.isArray(s.onFlowStart)){t.push(...s.onFlowStart);continue}if(a.length===1&&a[0]==="onFlowComplete"&&Array.isArray(s.onFlowComplete)){n.push(...s.onFlowComplete);continue}r.push(s)}if(t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let s=0;s<t.length;s++)await this.runStep(t[s],s)}let o=null;try{await this.runFlowBody(r)}catch(s){o=s instanceof Error?s:new Error(String(s))}if(n.length>0){console.log(`[flow] onFlowComplete (${n.length} steps)`);for(let s=0;s<n.length;s++)try{await this.runStep(n[s],s)}catch(a){console.warn(`[flow] onFlowComplete step ${s+1} failed: ${a instanceof Error?a.message:a}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let n=e[t],r=typeof n.wait=="number"?n.wait:0,o=typeof n.waitFor?.timeout=="number"?n.waitFor.timeout:0,s=Math.max(6e4,r+15e3,o+15e3);if(n.runFlow||n.launchApp){await this.runStep(n,t);continue}await Promise.race([this.runStep(n,t),new Promise((a,l)=>setTimeout(()=>l(new Error(`step ${t+1} (${Object.keys(n)[0]}) exceeded ${s}ms deadline`)),s))])}}};async function mt(i){if(!i)return"";let e=i.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let n=(await Ae()).find(r=>r.name.toLowerCase()===e.toLowerCase());return n?String(n.preferredPort):e}async function pt(){let i=await Oe(),e=i.find(n=>n.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=i[0];return t?`http://localhost:${t.port}/__soot/`:null}async function Ke(i){(i.length===0||i.includes("--help")||i.includes("-h"))&&(console.log(`
365
+ sootsim flow \u2014 run flows or manage a draft
366
+
367
+ usage:
368
+ sootsim flow <flow.yaml> [options]
369
+ sootsim flow start
370
+ sootsim flow keep
371
+ sootsim flow end [--output <path>] [--validate] [--video]
372
+ sootsim flow validate <path>
373
+
374
+ options:
375
+ --record record a webm artifact while the flow runs
376
+ --profile capture perf stats while the flow runs
377
+ --out <dir> output directory (default: /tmp/sootsim-recordings)
378
+ --device <model> override the flow frontmatter device for this run
379
+ --slow <ms> delay between steps for natural pacing
380
+ --tail-wait <ms> hold the recording open after the last step so the
381
+ final UI state is captured (default: smart idle up to
382
+ 6000ms for --preview, fixed 2000ms for --record, 0 otherwise)
383
+ --url <url> load this target before running the flow
384
+ --screenshot-paths <mode>
385
+ screenshot path mode: dir (default) or flow
386
+ --no-shell capture every screenshot tenant-only (no status bar,
387
+ keyboard, notification center, or other shell overlays).
388
+ use for clean demo asset sets. per-step \`layers:\`
389
+ still wins over this default.
390
+ --shell-only inverse \u2014 capture shell chrome only
391
+ --replace <m>=<f> replace a Metro module with a local file for this run
392
+ --new open a fresh sim before running the flow
393
+ --driver <id> when paired with --new, launch through a specific
394
+ driver from the registry (e.g. playwright for
395
+ hermetic CI runs); see 'sootsim list --drivers'
396
+ --headless pass headless=true to the launch driver (useful
397
+ with --driver playwright)
398
+ --headed force a fresh, VISIBLE window for this run (implies
399
+ --new; overrides --headless). use when you want to
400
+ watch the flow run live even if the current sim is
401
+ headless or stale
402
+ --electron prefer opening the target in the desktop companion
403
+ --sim <id> target a specific current sim
404
+ --validate replay the drafted flow before clearing it
405
+ --video replay and record the drafted flow before clearing it
406
+ --preview record events+video, upload, and print /preview/<id>
407
+ --preview-open open the uploaded preview link after a successful run
408
+ --preview-origin <url>
409
+ upload target for --preview (default: auto)
410
+ --preview-public-origin <url>
411
+ public link origin for --preview (default: sootsim.com
412
+ for prod uploads)
413
+ --owner <org> associate preview upload with a linked org repo
414
+ --repo <repo> repo name for --owner; user must belong to the team
415
+
416
+ frontmatter (top of flow.yaml between --- markers):
417
+ app: 8081 load this target before the flow starts
418
+ device: iphone-14 set the live device model for this flow run
419
+ electron: true prefer the desktop companion sim for this flow
420
+
421
+ default runtime:
422
+ bridge-backed flow playback against the current sim
423
+ if no current sim exists, flow opens the discovered target first
424
+ recording and profiling both run on the same bridge-backed path
425
+
426
+ examples:
427
+ sootsim flow login.yaml
428
+ sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
429
+ sootsim flow demo.yaml --sim a2
430
+ sootsim flow start
431
+ sootsim flow keep
432
+ sootsim flow end --output ./flows/draft.yaml
433
+ sootsim flow end --output ./flows/draft.yaml --validate
434
+ sootsim flow end --output ./flows/draft.yaml --video
435
+ sootsim flow validate ./flows/draft.yaml
436
+
437
+ flow extension:
438
+ takeScreenshot: hero
439
+ takeScreenshot:
440
+ path: marketing/hero
441
+ withFrame: true
442
+ `),process.exit(0));let e=i[0];_.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=m=>i.find((u,y)=>i[y-1]===m),n=i.includes("--profile"),r=i.includes("--headed"),o=i.includes("--new")||r,s=t("--out")||"/tmp/sootsim-recordings",a=t("--screenshots")||(t("--out")?s:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",f=i.includes("--no-shell")?"tenant":i.includes("--shell-only")?"shell":void 0,c=t("--device")?.trim()||"",h=i.includes("--slow")?+(t("--slow")||"500"):0,P=i.includes("--electron"),w=i.includes("--preview"),R=await je(t("--preview-origin")),ae=t("--preview-public-origin"),qe=i.includes("--preview-open"),le=t("--owner")?.trim()||"",ce=t("--repo")?.trim()||"",Ge=i.flatMap((m,u)=>i[u-1]==="--replace"?["--replace",m]:[]),ze=i.flatMap((m,u)=>i[u-1]==="--remap"?["--remap",m]:[]),$=i.includes("--record")||w,Ye=i.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):$?w?6e3:2e3:0,Xe=_.readFileSync(e,"utf8"),{frontmatter:x,steps:E}=ne(Xe);E.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let N=c||x.device||"",B=P||x.electron===!0,Ze=x.app===void 0||x.app===null?"":typeof x.app=="number"?String(x.app):x.app,q=await mt(Ze),de={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"]},S=ee(i,de),Qe=t("--url")||"";B&&!_e()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let ue=B?"desktop companion":"bridge",et=q?` | target: ${q}`:"";console.log(`
443
+ sootsim flow \u2014 ${b.basename(e)}
444
+ ${E.length} steps | ${ue}${et}${$?" | recording":""}${n?" | profiling":""}${h?` | ${h}ms delay`:""}
445
+ `),w&&ge({event:"preview_flow_started",properties:{flowName:b.basename(e),stepCount:E.length,mode:ue,electron:B,record:$,profile:n,previewOrigin:R}});let F=Qe||q||"",G=o||B&&S.simIdSource!=="flag",fe=t("--driver")||"",z=!1,Y=new Set,me=!1;if(!F&&!G&&S.simIdSource==="none"){let m=ve(S);try{let u=await m.listSims(),y=u.find(J=>J.isPrimary&&J.readyState==="open"),V=u.find(J=>J.readyState==="open"),we=y??V;we&&(me=!0,console.log(` reusing active sim: ${we.id}`))}catch{}finally{m.close()}}if(!F&&!me&&(G||S.simIdSource==="none")){let m=await pt();m||(console.error(" error: no current sim and no sootsim target found"),await Z(),process.exit(1)),F=m}if(F&&N){let m=new URL(await Re(F));m.searchParams.set("device",N),F=m.toString()}if(F){let m=[F];if(m.push(...Ge),m.push(...ze),G&&m.push("--new"),S.simIdSource==="flag"&&S.simId&&m.push("--sim",S.simId),fe&&(m.push("--driver",fe),z=!0),i.includes("--headless")&&!r&&m.push("--headless"),await Ce(m,{port:S.wsPort,timeoutMs:S.commandTimeoutMs}),z){let u=Q();u&&Y.add(u)}}let M=ee(i,de),j=M.simIdSource==="flag"?M.simId:Q()||M.simId,tt=M.simIdSource==="flag"?"flag":j?"saved":"none",k=te(M.wsPort,{commandTimeoutMs:M.commandTimeoutMs,simId:j,simIdSource:tt}),d,pe=async()=>{if(!N)return!1;let m=await k.send({type:"evaluate",simId:d.simId,code:"window.location.href"});if(typeof m=="string"&&m.length>0){let u=new URL(m);u.searchParams.set("device",N),d.setSimRouteHint(u.toString())}return!!await k.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",N]})};if(d=new K(k,{screenshotDir:a,flowDir:b.dirname(b.resolve(e)),screenshotPathMode:l,screenshotLayers:f,simId:j,recordingOutputDir:$?s:void 0,recordingFormat:w?"mp4":"webm",billingOriginOverride:w?R:void 0,allowGitHubRecording:$,onAfterLaunch:async()=>{await pe()&&await d.waitForTree(12e4),w&&await k.send({type:"evaluate",simId:d.simId,code:`(() => {
446
+ const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
447
+ return r?.start?.() ?? false
448
+ })()`})}}),h&&(d.stepDelay=h),d.js.putEnv("MAESTRO_FILENAME",b.basename(e,b.extname(e))),x.env&&typeof x.env=="object")for(let[m,u]of Object.entries(x.env))d.js.putEnv(m,u);let I=null,T=null,C=null,X=null,L=0,he=!!E[0]?.launchApp;try{await d.waitForTree(12e4),await pe()&&await d.waitForTree(12e4),w&&!he&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await d.launchApp({clearState:!0}),$&&(he?d.prepareRecording():await d.startRecording()),n&&await d.startProfile(),w&&(await k.send({type:"evaluate",simId:d.simId,code:`(() => {
449
+ const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
450
+ return r?.start?.() ?? false
451
+ })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await d.runFlow(E),n&&(I=await d.stopProfile()),await d.waitForRecordingTail({maxMs:Ye,smart:w}),$&&(T=await d.stopRecording(),C=d.getLastRecordingDurationMs()),w&&(X=await k.send({type:"evaluate",simId:d.simId,code:`(() => {
452
+ const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
453
+ return r?.stop?.() ?? []
454
+ })()`}),console.log(` captured ${X.length} replay events`));let u=E.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
455
+ + completed (${E.length} steps)`),u>0&&console.log(` screenshots: ${u} \u2192 ${a}`),I&&We(I),T&&console.log(` video: ${T}`),console.log()}catch(m){if(n&&!I)try{I=await d.stopProfile()}catch{}if($&&!T)try{T=await d.stopRecording(),C=d.getLastRecordingDurationMs()}catch(u){console.warn(` recording stop failed: ${u?.message||String(u)}`)}console.error(`
456
+ x failed: ${m.message}
457
+ `),I&&(console.log(" partial profile:"),We(I)),T&&console.log(` partial video: ${T}`);try{let u=d.lastFailedStep,y=u?`step-${String(u.index+1).padStart(2,"0")}-${u.kind}`:"unstaged",V=b.join(a,y);await d.captureFailureBundle(V,{error:m,stepIndex:u?.index,stepKind:u?.kind,stepTarget:u?.target}),console.log(` failure bundle: ${V}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(u){try{let y=b.join(a,"error.png");await d.captureFailureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${u instanceof Error?u.message:String(u)})`)}await ke(k,{errorsCommand:`sootsim get errors 5${d.simId?` --sim ${d.simId}`:""}`,warningsCommand:`sootsim get warnings 5${d.simId?` --sim ${d.simId}`:""}`,requestsCommand:`sootsim get requests 5${d.simId?` --sim ${d.simId}`:""}`}),L=1}finally{k.close()}if(L===0&&w)try{let m=await wt(X??[]),u=["--origin",R,"--events",m];ae&&u.push("--public-origin",ae),T&&u.push("--video",T),T&&C&&Number.isFinite(C)&&u.push("--video-duration-ms",String(Math.round(C))),d.simId&&u.push("--sim",d.simId),qe&&u.push("--open"),le&&u.push("--owner",le),ce&&u.push("--repo",ce),console.log(`
458
+ preparing preview upload\u2026`);let{runUpload:y}=await import("./upload-3YJQJYAD.js");await y(u,{})}catch(m){console.error(` preview upload failed: ${m?.message||m}`),L=1}return z?(d.simId&&Y.add(d.simId),await ht(S.wsPort,S.commandTimeoutMs,[...Y])):d.simId&&d.simId!==j&&be(d.simId),await Z(),L}async function ht(i,e,t){let n=[...new Set(t.filter(Boolean))];if(n.length===0)return;let r=te(i,{commandTimeoutMs:e});try{let o=await r.listSims(),s=n.filter(l=>o.some(f=>f.id===l&&f.readyState==="open"));if(s.length===0)return;let a=await De(r,i,e,s);await Ne(o,s),a.closed.length>0&&console.log(` closed flow sim(s): ${a.closed.join(", ")}`),a.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${a.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(i){let{gzipSync:e}=await import("zlib"),t=i.map(o=>JSON.stringify(o)).join(`
459
+ `)+(i.length?`
460
+ `:""),n=e(Buffer.from(t,"utf8")),r=b.join(He(),`sootsim-events-${Date.now()}.jsonl.gz`);return _.writeFileSync(r,n),console.log(` events: ${i.length} written to ${r} (${n.length} bytes gz)`),r}async function gt(i){let e=i[0],t=n=>i.find((r,o)=>i[o-1]===n);switch(e){case"start":{let{path:n,state:r}=Ie();console.log(" flow draft started"),console.log(` session: ${n}`),console.log(` steps: ${r.steps.length}`);return}case"keep":case"good":{let n=oe();if(n.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!n.kept){console.log(" no pending action to keep");return}console.log(` kept: ${n.candidate.summary}`),console.log(` steps: ${n.stepCount}`);return}case"end":{let n=t("--output")||(i[1]&&!i[1].startsWith("-")?i[1]:void 0),r=i.includes("--validate")||i.includes("--video"),o=i.includes("--video"),s=oe();s.active&&s.kept&&console.log(` auto-kept trailing action: ${s.candidate.summary}`);let a=Pe(n||(r?bt():void 0));if(a.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!a.valid){console.error(" flow draft is not valid:");for(let l of a.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=vt(i,a.outputPath),f=await Ke(l);if(f!==0){console.error(`
461
+ validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=f;return}ie(),console.log(` flow draft validated (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath&&console.log(` saved: ${a.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(ie(),console.log(` flow draft ended (${a.stepCount} step${a.stepCount===1?"":"s"})`),a.outputPath){console.log(` saved: ${a.outputPath}`),console.log(` next: sootsim flow ${a.outputPath} --record`);return}console.log(""),process.stdout.write(a.yaml);return}case"validate":{let n=i[1];(!n||n.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let r=re(n);if(r.length>0){console.error(` x ${n} failed validation:`);for(let o of r)console.error(` - ${o}`);process.exit(1)}console.log(` + ${n} looks valid`);return}}}function yt(i){return i[0]==="--sim"&&i.length>=2?[...i.slice(2),"--sim",i[1]]:i}async function Ht(i){let e=yt(i),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await gt(e),0;let n=await Ke(e);return n!==0&&(process.exitCode=n),n}function We(i){let e=i.avgMs>0?(1e3/i.avgMs).toFixed(1):"?",t=i.sampleCount>0?(i.jankFrames/i.sampleCount*100).toFixed(1):"0";console.log(`
462
+ profile:`),console.log(` frames: ${i.frames}`),console.log(` total: ${i.totalMs.toFixed(1)}ms`),console.log(` avg: ${i.avgMs.toFixed(2)}ms (${e} fps)`),console.log(` max: ${i.maxMs.toFixed(2)}ms`),i.layoutAvgMs!==void 0&&console.log(` breakdown: layout ${i.layoutAvgMs.toFixed(2)}ms | render ${i.renderAvgMs?.toFixed(2)||"0.00"}ms | copy ${i.copyAvgMs?.toFixed(2)||"0.00"}ms`),console.log(` p95: ${i.p95.toFixed(2)}ms`),console.log(` p99: ${i.p99.toFixed(2)}ms`),console.log(` jank: ${i.jankFrames}/${i.sampleCount} (${t}%) >16.67ms`);let n=Array.isArray(i.worstFrames)?i.worstFrames:[];if(n.length!==0){if(console.log(`
463
+ worst frames:`),i.mode==="render-worker"){console.log(" total layout render copy t+");for(let r of n){let[o,s,a,l,f]=r;console.log(` ${s.toFixed(2).padStart(7)} ${a.toFixed(2).padStart(7)} ${l.toFixed(2).padStart(7)} ${f.toFixed(2).padStart(7)} ${String(o).padStart(5)}`)}return}console.log(` ${n.map(r=>r.toFixed(2)).join(", ")}`)}}function bt(){return b.join(He(),`sootsim-flow-draft-${Date.now()}.yaml`)}function vt(i,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let n=1;n<i.length;n++){let r=i[n];if(!(r==="--validate"||r==="--video")){if(r==="--output"){n+=1;continue}n===1&&!r.startsWith("-")||t.push(r)}}return!t.includes("--record")&&i.includes("--video")&&t.push("--record"),t}export{pt as a,Ke as b,yt as c,Ht as d};
@@ -1,3 +1,3 @@
1
- /*! sootsim v0.1.149 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{b as y}from"./chunk-Q6KGWTG3.js";import{existsSync as S,mkdirSync as h,readFileSync as b,writeFileSync as H,rmSync as p}from"fs";import{tmpdir as m}from"os";import{dirname as v,join as w}from"path";var d=new Map;function s(e,r){d.set(e,r)}var c=1;function i(){return w(m(),`sootsim-cli-hints-${y()}.json`)}function l(){return w(m(),"sootsim-cli-hints-global.json")}function u(e){if(!S(e))return{version:c,shown:{}};try{let r=JSON.parse(b(e,"utf8"));return r?.version!==c||!r?.shown?{version:c,shown:{}}:r}catch{return{version:c,shown:{}}}}function f(e,r){try{h(v(e),{recursive:!0}),H(e,JSON.stringify(r)+`
1
+ /*! sootsim v0.1.150 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{b as y}from"./chunk-NI2TIFUK.js";import{existsSync as S,mkdirSync as h,readFileSync as b,writeFileSync as H,rmSync as p}from"fs";import{tmpdir as m}from"os";import{dirname as v,join as w}from"path";var d=new Map;function s(e,r){d.set(e,r)}var c=1;function i(){return w(m(),`sootsim-cli-hints-${y()}.json`)}function l(){return w(m(),"sootsim-cli-hints-global.json")}function u(e){if(!S(e))return{version:c,shown:{}};try{let r=JSON.parse(b(e,"utf8"));return r?.version!==c||!r?.shown?{version:c,shown:{}}:r}catch{return{version:c,shown:{}}}}function f(e,r){try{h(v(e),{recursive:!0}),H(e,JSON.stringify(r)+`
3
3
  `)}catch{}}function F(){let e=(process.env.SOOTSIM_HINTS||"").toLowerCase();return e==="off"||e==="0"||e==="false"?"off":e==="always"||e==="verbose"?"always":"normal"}function x(e,r){let o=F();if(o==="off")return!1;if(o==="always"||r==="always")return!0;let n=Date.now();if(r==="once-per-identity"){let t=u(i());return t.shown[e]?!1:(t.shown[e]=n,f(i(),t),!0)}if(r==="once-ever"){let t=u(l());return t.shown[e]?!1:(t.shown[e]=n,f(l(),t),!0)}if(typeof r=="object"&&"cooldownMs"in r){let t=u(i()),a=t.shown[e]??0;return n-a<r.cooldownMs?!1:(t.shown[e]=n,f(i(),t),!0)}return!0}function k(e,...r){let o=d.get(e);if(!o)return process.env.SOOTSIM_HINTS_DEBUG&&console.error(` [hints] no hint registered for id "${e}"`),!1;if(!x(e,o.frequency))return!1;let n=o.render(...r);if(n==null)return!1;let t=Array.isArray(n)?n:[n],a=o.stream==="error"?console.error:console.log;for(let g of t)a(` hint: ${g}`);return!0}function M(){p(i(),{force:!0})}function O(){p(l(),{force:!0})}function T(){return Array.from(d.entries()).map(([e,r])=>({id:e,frequency:r.frequency}))}s("app-still-loading",{frequency:{cooldownMs:6e4},render:e=>`app may still be loading (${e} nodes). run \`sootsim wait ready\` first.`});s("wait-selector-for-missing-testid",{frequency:"once-per-identity",render:e=>`sootsim wait selector ${e}`,stream:"error"});s("prefer-cli-over-eval",{frequency:"once-per-identity",render:e=>e.length?["try the CLI shortcut instead:",...e.map(r=>` ${r}`)]:null,stream:"error"});s("describe-use-filters",{frequency:"once-per-identity",render:()=>["describe output is long. narrow it with:"," sootsim describe --only '*Bottom Sheet*'"," sootsim describe --testid-like 'swap-*'"," sootsim describe --subtree <testID>"]});s("describe-filter-context",{frequency:"once-per-identity",render:()=>["filtered describe is search output, not current-route proof.","run `sootsim describe` without filters after navigation; clipped nodes are marked `(clipped:...)`."]});s("subtree-root-not-found",{frequency:"always",render:e=>`no node with testID/id "${e}" \u2014 try \`sootsim find --testid ${e}\` to discover available ids.`,stream:"error"});export{k as a,M as b,O as c,T as d};
@@ -0,0 +1 @@
1
+ /*! sootsim v0.1.150 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.149 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as R}from"./chunk-GG4I3SBM.js";import{n as D}from"./chunk-CGBHDP72.js";import{a as T}from"./chunk-DVANCABF.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-RIDIENLK.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.150 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as R}from"./chunk-JPWK6SFZ.js";import{n as D}from"./chunk-NHDDW7WP.js";import{a as T}from"./chunk-MFPT2P6I.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-LKCGAST6.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};