sootsim 0.1.210 → 0.1.212

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +10 -9
  2. package/dist-cli/bin.js +4 -4
  3. package/dist-cli/chunks/{agent-KAQZXQI7.js → agent-SEHSNZX6.js} +2 -2
  4. package/dist-cli/chunks/{agent-wrapper-2FEBECLE.js → agent-wrapper-YMUSFYO4.js} +2 -2
  5. package/dist-cli/chunks/{app-fonts-527RTD7E.js → app-fonts-P7IHVY46.js} +2 -2
  6. package/dist-cli/chunks/{assert-FD7ABNEJ.js → assert-AZZHFMFN.js} +2 -2
  7. package/dist-cli/chunks/{auth-U5CEZXAX.js → auth-QWPDQK3C.js} +2 -2
  8. package/dist-cli/chunks/beta-G6PO4MUG.js +2 -0
  9. package/dist-cli/chunks/{camera-OIURHC5C.js → camera-LQTWHUE6.js} +2 -2
  10. package/dist-cli/chunks/chunk-2ZF3OFCV.js +1 -0
  11. package/dist-cli/chunks/{chunk-PH46EVF3.js → chunk-3L6FBCSH.js} +2 -2
  12. package/dist-cli/chunks/chunk-44LPHPGF.js +2 -0
  13. package/dist-cli/chunks/{chunk-VVRIRW4K.js → chunk-4AEJLWKA.js} +1 -1
  14. package/dist-cli/chunks/{chunk-IPX2D5AJ.js → chunk-4IBUPIN6.js} +1 -1
  15. package/dist-cli/chunks/{chunk-3ZZ4QGEW.js → chunk-4RU6YTEP.js} +1 -1
  16. package/dist-cli/chunks/{chunk-MVIWCOR3.js → chunk-5FQMI3PB.js} +1 -1
  17. package/dist-cli/chunks/{chunk-VCFHK3EU.js → chunk-6DPNSUZZ.js} +1 -1
  18. package/dist-cli/chunks/{chunk-XRUPDNSR.js → chunk-7BH3S3L3.js} +2 -2
  19. package/dist-cli/chunks/{chunk-P6L7NTH2.js → chunk-7SYXBGM2.js} +2 -2
  20. package/dist-cli/chunks/{chunk-ATMXAOZC.js → chunk-7T4AAWY2.js} +2 -2
  21. package/dist-cli/chunks/{chunk-AYU7TPLY.js → chunk-ACGAAVPX.js} +2 -2
  22. package/dist-cli/chunks/{chunk-T7SAFPA6.js → chunk-AOUNFYEN.js} +1 -1
  23. package/dist-cli/chunks/{chunk-WTJP6C4W.js → chunk-ATFY2JZZ.js} +51 -51
  24. package/dist-cli/chunks/{chunk-BCDCPHIB.js → chunk-DOCQ4YBT.js} +2 -2
  25. package/dist-cli/chunks/{chunk-QMS2S3EF.js → chunk-DWL4WFZ2.js} +1 -1
  26. package/dist-cli/chunks/{chunk-KWAAJUF2.js → chunk-ERG3QCK4.js} +1 -1
  27. package/dist-cli/chunks/{chunk-NLRGBEDV.js → chunk-ETXSEPTH.js} +2 -2
  28. package/dist-cli/chunks/{chunk-XUXEKCY2.js → chunk-FMITPB4T.js} +2 -2
  29. package/dist-cli/chunks/{chunk-DO4AU4FA.js → chunk-FSJQB6FI.js} +2 -2
  30. package/dist-cli/chunks/{chunk-74SGAJAJ.js → chunk-HTX3YVCJ.js} +2 -2
  31. package/dist-cli/chunks/{chunk-NV7QTS3L.js → chunk-KOARSZSJ.js} +1 -1
  32. package/dist-cli/chunks/{chunk-LO7DZIFS.js → chunk-KRJRWLOW.js} +1 -1
  33. package/dist-cli/chunks/chunk-MTIPOS45.js +1 -0
  34. package/dist-cli/chunks/{chunk-GCW2PJGE.js → chunk-O7K44ZT6.js} +2 -2
  35. package/dist-cli/chunks/{chunk-VAMOANYW.js → chunk-OHRSRPEB.js} +11 -11
  36. package/dist-cli/chunks/{chunk-5S7BCA4C.js → chunk-QG3N3XNK.js} +3 -3
  37. package/dist-cli/chunks/{chunk-XTKTKQIT.js → chunk-QXDO6QT5.js} +2 -2
  38. package/dist-cli/chunks/{chunk-KEWZBN4M.js → chunk-SC67TYH6.js} +1 -1
  39. package/dist-cli/chunks/{chunk-7YKBZB7D.js → chunk-SPEEWUAK.js} +4 -4
  40. package/dist-cli/chunks/chunk-SX5MJUQC.js +119 -0
  41. package/dist-cli/chunks/{chunk-SX5M6VA3.js → chunk-TBLMSWZ6.js} +1 -1
  42. package/dist-cli/chunks/{chunk-KLPGPFZF.js → chunk-TKGMBU6V.js} +2 -2
  43. package/dist-cli/chunks/{chunk-USLCZL6I.js → chunk-TPD4GIHM.js} +2 -2
  44. package/dist-cli/chunks/{chunk-KCGE56W3.js → chunk-TUMOXM4E.js} +2 -2
  45. package/dist-cli/chunks/{chunk-FF7B5JFA.js → chunk-TWNBIOWX.js} +1 -1
  46. package/dist-cli/chunks/{chunk-FMIR4NMA.js → chunk-TWNZ24EL.js} +1 -1
  47. package/dist-cli/chunks/{chunk-2RJ57USW.js → chunk-W7RH3GDB.js} +2 -2
  48. package/dist-cli/chunks/{chunk-VMRT3K3M.js → chunk-WLFIL6JU.js} +2 -2
  49. package/dist-cli/chunks/{chunk-4X3L2WDG.js → chunk-WSI6YFMI.js} +3 -3
  50. package/dist-cli/chunks/{chunk-SVLKYHDO.js → chunk-YFXU4HRJ.js} +1 -1
  51. package/dist-cli/chunks/{chunk-PIONEQXI.js → chunk-YNEFNAKF.js} +2 -2
  52. package/dist-cli/chunks/cli-version-YGN377WG.js +2 -0
  53. package/dist-cli/chunks/{compat-2QLPOPPM.js → compat-GLOXSMDS.js} +3 -3
  54. package/dist-cli/chunks/{config-U3Z5QR5Q.js → config-QLSJASDG.js} +2 -2
  55. package/dist-cli/chunks/{control-YUIGGT7H.js → control-HW7J3XVA.js} +2 -2
  56. package/dist-cli/chunks/daemon-66EHUQG5.js +2 -0
  57. package/dist-cli/chunks/{debug-Z5LPQGQY.js → debug-Q2STL45F.js} +3 -3
  58. package/dist-cli/chunks/{desktop-2MG6MKXV.js → desktop-LJJVJIU3.js} +3 -3
  59. package/dist-cli/chunks/{detox-OWZNY37O.js → detox-WBTVTSHD.js} +4 -4
  60. package/dist-cli/chunks/{device-PQN5ZIOA.js → device-E3JPFQZM.js} +2 -2
  61. package/dist-cli/chunks/{diagnose-A5XCL535.js → diagnose-VECVKV6Z.js} +2 -2
  62. package/dist-cli/chunks/drivers-SOBHAYVL.js +2 -0
  63. package/dist-cli/chunks/flow-P3QRESKR.js +2 -0
  64. package/dist-cli/chunks/help-NHIRWWJQ.js +2 -0
  65. package/dist-cli/chunks/{home-paths-SD3NRI7J.js → home-paths-CRN2V4ZP.js} +2 -2
  66. package/dist-cli/chunks/inspect-DAGGHG65.js +2 -0
  67. package/dist-cli/chunks/install-desktop-HLFM6Q6M.js +2 -0
  68. package/dist-cli/chunks/{login-7V3C7LUJ.js → login-FZTKNUQU.js} +4 -4
  69. package/dist-cli/chunks/{logout-MMMVGJ65.js → logout-FBH74CJM.js} +2 -2
  70. package/dist-cli/chunks/{maestro-KPKOSHF5.js → maestro-NRDQGJYE.js} +17 -11
  71. package/dist-cli/chunks/maestro-generate-RFAXAENX.js +34 -0
  72. package/dist-cli/chunks/{mode-SPC2PQIA.js → mode-IXMJSPUT.js} +2 -2
  73. package/dist-cli/chunks/optional-demo-registry-ZDULKK6R.js +2 -0
  74. package/dist-cli/chunks/{perf-S6P6POGY.js → perf-K2IHHZXM.js} +2 -2
  75. package/dist-cli/chunks/{record-MSARERUQ.js → record-RE6KIPXY.js} +3 -3
  76. package/dist-cli/chunks/runtime-BFBAWZDT.js +2 -0
  77. package/dist-cli/chunks/{screenshot-command-BWEJO65L.js → screenshot-command-S47YKHRV.js} +6 -6
  78. package/dist-cli/chunks/{screenshots-capture-6O4U2QZP.js → screenshots-capture-ZTG4V52X.js} +2 -2
  79. package/dist-cli/chunks/{serve-B3GZM4I2.js → serve-3AWTKYDJ.js} +2 -2
  80. package/dist-cli/chunks/{setup-BVF7AE4F.js → setup-66M64ZEI.js} +3 -3
  81. package/dist-cli/chunks/{skills-OOGMXBUU.js → skills-2UDI5RNU.js} +2 -2
  82. package/dist-cli/chunks/{storage-B6KLLSZ5.js → storage-XNTIUIYR.js} +2 -2
  83. package/dist-cli/chunks/store-YOG762Q4.js +2 -0
  84. package/dist-cli/chunks/telemetry-ZANU3YOO.js +2 -0
  85. package/dist-cli/chunks/{timeline-DNEEKXNB.js → timeline-VMPCXPKA.js} +2 -2
  86. package/dist-cli/chunks/{upgrade-4QBAXVEE.js → upgrade-UYXVI3XZ.js} +2 -2
  87. package/dist-cli/chunks/upload-RNDBU5AE.js +2 -0
  88. package/dist-cli/chunks/{version-GZ3CPO3H.js → version-I62N7JTP.js} +2 -2
  89. package/dist-cli/chunks/{web-NTF5XYWV.js → web-42YNSI2X.js} +2 -2
  90. package/dist-cli/chunks/{what-happened-XIXJ455M.js → what-happened-3TVVRSN4.js} +2 -2
  91. package/dist-lib/agent-daemon-client.cjs +1 -1
  92. package/dist-lib/agent-events.cjs +1 -1
  93. package/dist-lib/agent-identity.cjs +1 -1
  94. package/dist-lib/agent-sessions.cjs +1 -1
  95. package/dist-lib/attached-projects.cjs +1 -1
  96. package/dist-lib/auth/shared-session.cjs +1 -1
  97. package/dist-lib/backend-origin.cjs +1 -1
  98. package/dist-lib/beta.cjs +1 -1
  99. package/dist-lib/beta.mjs +1 -1
  100. package/dist-lib/bridge-constants.cjs +1 -1
  101. package/dist-lib/cli-constants.cjs +1 -1
  102. package/dist-lib/config.cjs +1 -1
  103. package/dist-lib/detox/index.cjs +1 -1
  104. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  105. package/dist-lib/home-paths.cjs +1 -1
  106. package/dist-lib/host/bridge-host.cjs +1 -1
  107. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  108. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  109. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  110. package/dist-lib/host/websocket-proxy.cjs +1 -1
  111. package/dist-lib/index.cjs +1 -1
  112. package/dist-lib/jump-to-source-babel.cjs +1 -1
  113. package/dist-lib/menu.cjs +1 -1
  114. package/dist-lib/menu.mjs +1 -1
  115. package/dist-lib/metro.cjs +1 -1
  116. package/dist-lib/profiles.cjs +1 -1
  117. package/dist-lib/render-mode.cjs +1 -1
  118. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  119. package/dist-lib/sdk.cjs +1 -1
  120. package/dist-lib/sdk.mjs +1 -1
  121. package/dist-lib/skills.cjs +109 -109
  122. package/dist-lib/vite.cjs +1 -1
  123. package/package.json +1 -1
  124. package/skills/soot/SKILL.md +5 -7
  125. package/skills/sootsim-debug/SKILL.md +1 -1
  126. package/skills/sootsim-perf/SKILL.md +1 -1
  127. package/skills/sootsim-test/SKILL.md +36 -40
  128. package/src/skills/builtin/{test-flow.ts → maestro-test.ts} +6 -6
  129. package/src/skills/registry.ts +3 -3
  130. package/dist-cli/chunks/beta-77XRUQXG.js +0 -2
  131. package/dist-cli/chunks/chunk-2HT73DM2.js +0 -119
  132. package/dist-cli/chunks/chunk-CQHQSDDJ.js +0 -2
  133. package/dist-cli/chunks/chunk-JY6W7FJK.js +0 -1
  134. package/dist-cli/chunks/chunk-O4QDSXAR.js +0 -1
  135. package/dist-cli/chunks/cli-version-HFRMOBQC.js +0 -2
  136. package/dist-cli/chunks/daemon-6SB37NMK.js +0 -2
  137. package/dist-cli/chunks/drivers-JVQ2IGFA.js +0 -2
  138. package/dist-cli/chunks/flow-ENY24D57.js +0 -2
  139. package/dist-cli/chunks/help-O4NYJLMW.js +0 -2
  140. package/dist-cli/chunks/inspect-B4GJTKF4.js +0 -2
  141. package/dist-cli/chunks/install-desktop-PE662CEU.js +0 -2
  142. package/dist-cli/chunks/optional-demo-registry-ZXW3LBUE.js +0 -2
  143. package/dist-cli/chunks/runtime-S3TTT5GK.js +0 -2
  144. package/dist-cli/chunks/store-VT7DQ5SF.js +0 -2
  145. package/dist-cli/chunks/telemetry-7K33P734.js +0 -2
  146. package/dist-cli/chunks/test-TN3KDDT2.js +0 -69
  147. package/dist-cli/chunks/upload-T6F6NRSY.js +0 -2
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.210 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as he,c as fe,d as me,e as Ye,f as ge,g as we,h as Ze,i as ye,j as Xe}from"./chunk-7YKBZB7D.js";import{a as qe}from"./chunk-2RJ57USW.js";import{a as et}from"./chunk-BCDCPHIB.js";import{a as Qe}from"./chunk-VAMOANYW.js";import{h as Je,p as Ge,r as ze,v as Ke}from"./chunk-XUXEKCY2.js";import{f as Le}from"./chunk-74SGAJAJ.js";import{a as Be}from"./chunk-NV7QTS3L.js";import{h as pe,m as Ue}from"./chunk-USLCZL6I.js";import{I as V,m as Ce,n as Ne,o as He,p as We}from"./chunk-IPX2D5AJ.js";import{g as ce,h as ue,i as je}from"./chunk-KCGE56W3.js";import{a as Ve}from"./chunk-3ZZ4QGEW.js";import{a as Me,b as le}from"./chunk-P6L7NTH2.js";import{d as de,e as De}from"./chunk-QMS2S3EF.js";import{g as Oe,h as _e}from"./chunk-T7SAFPA6.js";import*as k from"fs";import{tmpdir as ie}from"os";import*as w from"path";import*as S from"fs";import*as b from"path";var vt="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",it=1;function xt(n){let e=_e(n),t=e.scale,i=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,r=e.width,o=e.height,a=i?e.width+58:e.width+e.bezelWidth*2,s=i?e.height+111+111:e.height+e.bezelWidth*2,l=9.5,u=it,p=a+l*2,m=s+it*2,x=l+(i?29:e.bezelWidth),g=i?111:e.bezelWidth,P=i?52:e.cornerRadius+e.bezelWidth,_=[{side:"right",top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:n,renderScale:t,outerWidth:Math.round(p*t),outerHeight:Math.round(m*t),logicalOuterWidth:p,logicalOuterHeight:m,logicalFrameWidth:a,logicalFrameHeight:s,logicalFrameLeft:l,logicalFrameTop:u,logicalScreenWidth:r,logicalScreenHeight:o,logicalScreenLeft:x,logicalScreenTop:g,logicalScreenRadius:i?0:e.cornerRadius,logicalFrameRadius:P,frameBackground:i?"linear-gradient(180deg, #1b1c20 0%, #0f1012 42%, #050608 100%)":"#000000",frameOutline:i?"0 0 0 1px #1f2125":"0 0 0 1px #333",metallicRingShadow:i?null:vt,buttons:_,legacyHomeButton:i?{top:111+e.height+47/2,left:e.width/2-64/2+29,size:64,ring:1.5}:null,showHomeIndicator:e.homeIndicatorHeight>0,logicalHomeIndicatorStripHeight:e.homeIndicatorHeight}}function Tt(n){let e=n.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
1
+ /*! sootsim v0.1.212 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as fe,c as me,d as ge,e as Ze,f as we,g as ye,h as Xe,i as be,j as Qe}from"./chunk-SPEEWUAK.js";import{a as Ye}from"./chunk-W7RH3GDB.js";import{a as tt}from"./chunk-DOCQ4YBT.js";import{a as et}from"./chunk-OHRSRPEB.js";import{h as Ge,p as ze,r as Ke,v as qe}from"./chunk-FMITPB4T.js";import{f as Ce}from"./chunk-HTX3YVCJ.js";import{a as Le}from"./chunk-KOARSZSJ.js";import{h as he,m as Ve}from"./chunk-TPD4GIHM.js";import{I as J,m as Ne,n as He,o as Ue,p as We}from"./chunk-4IBUPIN6.js";import{g as ue,h as pe,i as je}from"./chunk-TUMOXM4E.js";import{a as Je}from"./chunk-4RU6YTEP.js";import{a as Oe,b as ce}from"./chunk-7SYXBGM2.js";import{d as de,e as Be}from"./chunk-DWL4WFZ2.js";import{g as _e,h as De}from"./chunk-AOUNFYEN.js";import*as k from"fs";import{createHash as Ht,randomUUID as Ut}from"node:crypto";import{tmpdir as ie}from"os";import*as g from"path";import*as S from"fs";import*as b from"path";var Tt="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",it=1;function Et(n){let e=De(n),t=e.scale,r=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,i=e.width,o=e.height,a=r?e.width+58:e.width+e.bezelWidth*2,s=r?e.height+111+111:e.height+e.bezelWidth*2,l=9.5,u=it,p=a+l*2,m=s+it*2,x=l+(r?29:e.bezelWidth),w=r?111:e.bezelWidth,P=r?52:e.cornerRadius+e.bezelWidth,_=[{side:"right",top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:"left",top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:n,renderScale:t,outerWidth:Math.round(p*t),outerHeight:Math.round(m*t),logicalOuterWidth:p,logicalOuterHeight:m,logicalFrameWidth:a,logicalFrameHeight:s,logicalFrameLeft:l,logicalFrameTop:u,logicalScreenWidth:i,logicalScreenHeight:o,logicalScreenLeft:x,logicalScreenTop:w,logicalScreenRadius:r?0:e.cornerRadius,logicalFrameRadius:P,frameBackground:r?"linear-gradient(180deg, #1b1c20 0%, #0f1012 42%, #050608 100%)":"#000000",frameOutline:r?"0 0 0 1px #1f2125":"0 0 0 1px #333",metallicRingShadow:r?null:Tt,buttons:_,legacyHomeButton:r?{top:111+e.height+47/2,left:e.width/2-64/2+29,size:64,ring:1.5}:null,showHomeIndicator:e.homeIndicatorHeight>0,logicalHomeIndicatorStripHeight:e.homeIndicatorHeight}}function Ft(n){let e=n.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
3
3
  <div
4
4
  aria-hidden="true"
5
5
  style="
@@ -24,7 +24,7 @@ import{a as he,c as fe,d as me,e as Ye,f as ge,g as we,h as Ze,i as ye,j as Xe}f
24
24
  z-index:2;
25
25
  "
26
26
  ></div>
27
- `}function Et(n,e){let t=n.buttons.map(Tt).join(""),i=n.metallicRingShadow?`
27
+ `}function It(n,e){let t=n.buttons.map(Ft).join(""),r=n.metallicRingShadow?`
28
28
  <div
29
29
  aria-hidden="true"
30
30
  style="
@@ -36,7 +36,7 @@ import{a as he,c as fe,d as me,e as Ye,f as ge,g as we,h as Ze,i as ye,j as Xe}f
36
36
  z-index:10;
37
37
  "
38
38
  ></div>
39
- `:"",r=n.legacyHomeButton?`
39
+ `:"",i=n.legacyHomeButton?`
40
40
  <div
41
41
  aria-hidden="true"
42
42
  style="
@@ -155,8 +155,8 @@ import{a as he,c as fe,d as me,e as Ye,f as ge,g as we,h as Ze,i as ye,j as Xe}f
155
155
  "
156
156
  >
157
157
  ${t}
158
- ${i}
159
158
  ${r}
159
+ ${i}
160
160
  <div
161
161
  id="screen"
162
162
  style="
@@ -177,7 +177,7 @@ import{a as he,c as fe,d as me,e as Ye,f as ge,g as we,h as Ze,i as ye,j as Xe}f
177
177
  </div>
178
178
  </div>
179
179
  </body>
180
- </html>`}async function rt(n,e){let{chromium:t}=await import("playwright"),i=await t.launch({headless:!0});try{let r=await Ft(i);try{return await r.compose(n,e)}finally{await r.close()}}finally{await i.close()}}async function Ft(n){let e=new Map;async function t(i){let r=e.get(i);if(r)return r;let o=xt(i),a=await n.newContext({viewport:{width:o.outerWidth,height:o.outerHeight},deviceScaleFactor:1}),s=await a.newPage(),l={layout:o,context:a,page:s};return e.set(i,l),l}return{async compose(i,r){let o=await t(r),a=`data:image/png;base64,${i.toString("base64")}`;return await o.page.setContent(Et(o.layout,a),{waitUntil:"load"}),await o.page.waitForTimeout(20),await o.page.screenshot({type:"png",clip:{x:0,y:0,width:o.layout.outerWidth,height:o.layout.outerHeight},omitBackground:!0})},async close(){for(let i of e.values())await i.context.close();e.clear()}}}import{spawnSync as It}from"child_process";import*as C from"vm";var $t=3e5,kt=`
180
+ </html>`}async function nt(n,e){let{chromium:t}=await import("playwright"),r=await t.launch({headless:!0});try{let i=await $t(r);try{return await i.compose(n,e)}finally{await i.close()}}finally{await r.close()}}async function $t(n){let e=new Map;async function t(r){let i=e.get(r);if(i)return i;let o=Et(r),a=await n.newContext({viewport:{width:o.outerWidth,height:o.outerHeight},deviceScaleFactor:1}),s=await a.newPage(),l={layout:o,context:a,page:s};return e.set(r,l),l}return{async compose(r,i){let o=await t(i),a=`data:image/png;base64,${r.toString("base64")}`;return await o.page.setContent(It(o.layout,a),{waitUntil:"load"}),await o.page.waitForTimeout(20),await o.page.screenshot({type:"png",clip:{x:0,y:0,width:o.layout.outerWidth,height:o.layout.outerHeight},omitBackground:!0})},async close(){for(let r of e.values())await r.context.close();e.clear()}}}import{spawnSync as kt}from"child_process";import*as C from"vm";var Pt=3e5,At=`
181
181
  let input = '';
182
182
  process.stdin.on('data', (c) => { input += c });
183
183
  process.stdin.on('end', async () => {
@@ -199,7 +199,7 @@ process.stdin.on('end', async () => {
199
199
  process.exitCode = 1;
200
200
  }
201
201
  });
202
- `;function J(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let i={...process.env};for(let s of Object.keys(i))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete i[s];let r=It(process.execPath,["-e",kt],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:$t,maxBuffer:64*1024*1024,env:i});if(r.error)throw new Error(`http ${e} ${n} failed: ${r.error.message}`);let o;try{o=JSON.parse(r.stdout||"")}catch{throw new Error(`http ${e} ${n} failed: no response (${(r.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${n} failed: ${a.__error}`);return a}var Pt=/(?<!\\)\$\{([^$]*)\}/g,At=/\\(\$\{[^$]*\})/g,Rt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Y=class{context;envBinding=new Map;envScopeStack=[];syncedEnvKeys=new Set;output={};maestro;constructor(e={}){this.maestro={copiedText:null,platform:e.platform??"ios"};let t=e.onLog??(r=>console.log(`[flow] js: ${r}`)),i={output:this.output,maestro:this.maestro,http:{get:(r,o)=>J(r,"GET",o),post:(r,o)=>J(r,"POST",o),put:(r,o)=>J(r,"PUT",o),delete:(r,o)=>J(r,"DELETE",o),request:(r,o)=>J(r,(o?.method??"GET").toUpperCase(),o)},console:{log:(...r)=>t(r.map(o=>typeof o=="string"?o:nt(o)).join(" "))}};this.context=C.createContext(i),C.runInContext(`
202
+ `;function G(n,e,t){if(t?.multipartForm)throw new Error("http: multipartForm is not supported by sootsim yet");let r={...process.env};for(let s of Object.keys(r))(s.startsWith("BUN_INSPECT")||s==="NODE_OPTIONS")&&delete r[s];let i=kt(process.execPath,["-e",At],{input:JSON.stringify({url:n,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Pt,maxBuffer:64*1024*1024,env:r});if(i.error)throw new Error(`http ${e} ${n} failed: ${i.error.message}`);let o;try{o=JSON.parse(i.stdout||"")}catch{throw new Error(`http ${e} ${n} failed: no response (${(i.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${n} failed: ${a.__error}`);return a}var Rt=/(?<!\\)\$\{([^$]*)\}/g,Mt=/\\(\$\{[^$]*\})/g,Ot=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Z=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??(i=>console.log(`[flow] js: ${i}`)),r={output:this.output,maestro:this.maestro,http:{get:(i,o)=>G(i,"GET",o),post:(i,o)=>G(i,"POST",o),put:(i,o)=>G(i,"PUT",o),delete:(i,o)=>G(i,"DELETE",o),request:(i,o)=>G(i,(o?.method??"GET").toUpperCase(),o)},console:{log:(...i)=>t(i.map(o=>typeof o=="string"?o:ot(o)).join(" "))}};this.context=C.createContext(r),C.runInContext(`
203
203
  globalThis.__maestroScope = new Proxy(globalThis, {
204
204
  has() { return true },
205
205
  get(target, key) { return target[key] },
@@ -210,13 +210,13 @@ process.stdin.on('end', async () => {
210
210
  var yPercent = Math.ceil(y * 100) + '%'
211
211
  return xPercent + ',' + yPercent
212
212
  }
213
- `,this.context);for(let[r,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(r,o)}putEnv(e,t){this.envBinding.set(e,t)}setCopiedText(e){this.maestro.copiedText=e}enterEnvScope(){this.envScopeStack.push(new Map(this.envBinding))}leaveEnvScope(){let e=this.envScopeStack.pop();if(e){this.envBinding.clear();for(let[t,i]of e)this.envBinding.set(t,i)}}evaluate(e,t={}){let i=t.env;if(i&&Object.keys(i).length>0){this.enterEnvScope();try{for(let[r,o]of Object.entries(i))this.envBinding.set(r,o);return this.evalRaw(e)}finally{this.leaveEnvScope()}}return this.evalRaw(e)}evalRaw(e){this.syncEnvToContext();let t=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${");return C.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=C.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,i]of this.envBinding)try{e[t]=i,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(Pt,(i,r)=>{if(r.trim().length===0)return"";let o=this.evaluate(r);if(o===void 0&&Rt.test(r.trim()))throw new Error(`missing variable for flow placeholder: ${r.trim()}`);return nt(o)}).replace(At,(i,r)=>r)}interpolateStep(e){return this.interpolateValue(e,null)}interpolateValue(e,t){return typeof e=="string"?t==="evalScript"?e:this.evaluateStringTemplate(e):Array.isArray(e)?t==="commands"||t==="onFlowStart"||t==="onFlowComplete"?e:e.map(i=>this.interpolateValue(i,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,r])=>[i,this.interpolateValue(r,i)])):e}};function nt(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}function ot(n){if(n==null)return!1;if(typeof n=="boolean")return n;let e=String(n);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var Z=1e4,Q=393,N=852;function f(n){return new Promise(e=>setTimeout(e,n))}function xe(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function G(n,e){if(!xe(n))return null;let t=n[e];return typeof t=="string"&&t.length>0?t:null}function Mt(n,e){return xe(n)?n[e]===!0:!1}function Ot(n){if(!n)return null;let e=n.recentApps;if(Array.isArray(e))for(let i of e){let r=G(i,"id");if(r)return r}let t=n.surfaceBindings;return G(t,"app:one")||G(t,"app:two")||null}function _t(n){return n?b.basename(n)===".maestro"?b.dirname(n):n:process.cwd()}function Dt(n,e,t){let i=e.endsWith(".png")?e:`${e}.png`;if(b.isAbsolute(i))return i;if(t.mode==="flow"&&/[\\/]/.test(i)){let r=i.startsWith("./")||i.startsWith("../")?t.flowDir??process.cwd():_t(t.flowDir);return b.resolve(r,i)}return b.join(n,i)}function Bt(n){if(typeof n=="string")return{path:n,withFrame:!1};let e=n.path?.trim()||n.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:n.withFrame===!0,layers:n.layers}}function X(n,e){let[t,i]=n.split(",").map(s=>s.trim()),r=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+r(t,e?.width??Q),y:a+r(i,e?.height??N)}}function st(n){switch(n){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[n]:!0}}}function Lt(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,i=qe.parse(t);return Array.isArray(i)?i:[]}var ee=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new Y({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingStartedAtMs=null;lastRecordingDurationMs=null;lastRecordingFrameStats=null;flowTraceSteps=[];lastVisualSettledAtMs=0;simRouteHint=null;lastFailedStep=null;get simId(){return this.opts.simId}setSimRouteHint(e){this.simRouteHint=this.normalizeSimRoute(e)}normalizeSimRoute(e){if(!e)return null;try{let t=new URL(e);t.searchParams.delete("inspectOpen");let i=t.searchParams.toString();return`${t.origin}${t.pathname}${i?`?${i}`:""}`}catch{return e}}async refreshSimId(){if(this.opts.simId)try{let e=await this.bridge.listSims(),t=e.find(l=>l.id===this.opts.simId);if(t&&(this.simRouteHint=this.normalizeSimRoute(t.url||t.origin)),e.find(l=>l.id===this.opts.simId&&l.readyState==="open")||!this.simRouteHint)return;let r=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!r)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=r??o??a;s&&(this.opts.simId=s.id,console.log(` [flow] sim rotated to ${s.id}`))}catch{}}async evaluate(e,t){return this.bridge.send({type:"evaluate",simId:this.opts.simId,code:e},t?{timeoutMs:t}:void 0)}async callTest(e,...t){return this.bridge.send({type:"call",simId:this.opts.simId,path:`__sootsimTest.${e}`,args:t})}async waitForTree(e=Z){let t=Date.now()+e,i=Date.now(),r=null,o=0,a=0,s=-1,l=i;for(;Date.now()<t;){try{let p=await this.evaluate(Ce,8e3);if(o=0,p?.externalError)throw new Error(`app failed to load: ${p.externalError}`);if(p){let m=Date.now();p.nodes!==s&&(s=p.nodes,l=m);let x=p.flag===!0&&He(p),g=p.flag!==!0&&We(p);if((x||g)&&p.externalReady!==!1&&!p.externalError&&!p.loadingText&&m-l>=Ne)return}}catch(p){if(r=p instanceof Error?p:new Error(String(p)),r.message.startsWith("app failed to load:"))throw r;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${r.message}). it is likely a stale orphan \u2014 run \`sootsim list\`, then close it with \`sootsim close <id>\` or start a fresh one with \`sootsim open --new <port>\`.`);await this.refreshSimId()}let u=Date.now()-i;u-a>=5e3&&(a=u,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(u/1e3)}s)`)),await f(500)}throw r?.message.startsWith("app failed to load:")?r:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(this.opts.requireRecordingEntitlement&&await et("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
213
+ `,this.context);for(let[i,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(i,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,r]of e)this.envBinding.set(t,r)}}evaluate(e,t={}){let r=t.env;if(r&&Object.keys(r).length>0){this.enterEnvScope();try{for(let[i,o]of Object.entries(r))this.envBinding.set(i,o);return this.evalRaw(e)}finally{this.leaveEnvScope()}}return this.evalRaw(e)}evalRaw(e){this.syncEnvToContext();let t=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${");return C.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=C.runInContext("globalThis",this.context);for(let t of this.syncedEnvKeys)this.envBinding.has(t)||delete e[t];this.syncedEnvKeys=new Set;for(let[t,r]of this.envBinding)try{e[t]=r,this.syncedEnvKeys.add(t)}catch{}}evaluateStringTemplate(e){return e.replace(Rt,(r,i)=>{if(i.trim().length===0)return"";let o=this.evaluate(i);if(o===void 0&&Ot.test(i.trim()))throw new Error(`missing variable for flow placeholder: ${i.trim()}`);return ot(o)}).replace(Mt,(r,i)=>i)}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(r=>this.interpolateValue(r,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([r,i])=>[r,this.interpolateValue(i,r)])):e}};function ot(n){if(n===void 0)return"undefined";if(n===null)return"null";if(typeof n=="object")try{return JSON.stringify(n)}catch{return String(n)}return String(n)}function st(n){if(n==null)return!1;if(typeof n=="boolean")return n;let e=String(n);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var X=1e4,ee=393,N=852;function f(n){return new Promise(e=>setTimeout(e,n))}function Te(n){return!!(n&&typeof n=="object"&&!Array.isArray(n))}function z(n,e){if(!Te(n))return null;let t=n[e];return typeof t=="string"&&t.length>0?t:null}function _t(n,e){return Te(n)?n[e]===!0:!1}function Dt(n){if(!n)return null;let e=n.recentApps;if(Array.isArray(e))for(let r of e){let i=z(r,"id");if(i)return i}let t=n.surfaceBindings;return z(t,"app:one")||z(t,"app:two")||null}function Bt(n){return n?b.basename(n)===".maestro"?b.dirname(n):n:process.cwd()}function Lt(n,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(b.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let i=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():Bt(t.flowDir);return b.resolve(i,r)}return b.join(n,r)}function Ct(n){if(typeof n=="string")return{path:n,withFrame:!1};let e=n.path?.trim()||n.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:n.withFrame===!0,layers:n.layers}}function Q(n,e){let[t,r]=n.split(",").map(s=>s.trim()),i=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+i(t,e?.width??ee),y:a+i(r,e?.height??N)}}function at(n){switch(n){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[n]:!0}}}function Nt(n){let e=n.split(/^---$/m),t=e.length>1?e[e.length-1]:n,r=Ye.parse(t);return Array.isArray(r)?r:[]}var te=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new Z({platform:"ios",onLog:e=>console.log(`[flow] js: ${e}`)});firstLaunchDone=!1;profilingEnabled=!1;recordingEnabled=!1;recordingAccessChecked=!1;recordingStartedAtMs=null;lastRecordingStartedAtMs=null;lastRecordingDurationMs=null;lastRecordingFrameStats=null;flowTraceSteps=[];lastVisualSettledAtMs=0;simRouteHint=null;lastFailedStep=null;get simId(){return this.opts.simId}setSimRouteHint(e){this.simRouteHint=this.normalizeSimRoute(e)}normalizeSimRoute(e){if(!e)return null;try{let t=new URL(e);t.searchParams.delete("inspectOpen");let r=t.searchParams.toString();return`${t.origin}${t.pathname}${r?`?${r}`:""}`}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 i=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!i)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=i??o??a;s&&(this.opts.simId=s.id,console.log(` [flow] sim rotated to ${s.id}`))}catch{}}async evaluate(e,t){return this.bridge.send({type:"evaluate",simId:this.opts.simId,code:e},t?{timeoutMs:t}:void 0)}async callTest(e,...t){return this.bridge.send({type:"call",simId:this.opts.simId,path:`__sootsimTest.${e}`,args:t})}async waitForTree(e=X){let t=Date.now()+e,r=Date.now(),i=null,o=0,a=0,s=-1,l=r;for(;Date.now()<t;){try{let p=await this.evaluate(Ne,8e3);if(o=0,p?.externalError)throw new Error(`app failed to load: ${p.externalError}`);if(p){let m=Date.now();p.nodes!==s&&(s=p.nodes,l=m);let x=p.flag===!0&&Ue(p),w=p.flag!==!0&&We(p);if((x||w)&&p.externalReady!==!1&&!p.externalError&&!p.loadingText&&m-l>=He)return}}catch(p){if(i=p instanceof Error?p:new Error(String(p)),i.message.startsWith("app failed to load:"))throw i;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${i.message}). it is likely a stale orphan \u2014 run \`sootsim list\`, then close it with \`sootsim close <id>\` or start a fresh one with \`sootsim open --new <port>\`.`);await this.refreshSimId()}let u=Date.now()-r;u-a>=5e3&&(a=u,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(u/1e3)}s)`)),await f(500)}throw i?.message.startsWith("app failed to load:")?i:new Error(`app not ready after ${e}ms`)}async ensureRecordingStarted(){if(!this.opts.recordingOutputDir)throw new Error("recording output directory not configured");this.recordingAccessChecked||(this.opts.requireRecordingEntitlement&&await tt("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
214
214
  const rec = window.__sootsimRecorder
215
215
  if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
216
216
  const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
217
217
  if (rec.state() === 'recording') return { ok: true, format }
218
218
  return rec.start({ format, fps: 24 })
219
- })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=typeof t.startedAtMs=="number"&&Number.isFinite(t.startedAtMs)?t.startedAtMs:e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}getLastRecordingStartedAtMs(){return this.lastRecordingStartedAtMs}getLastRecordingFrameStats(){return this.lastRecordingFrameStats}getFlowTraceSteps(){return[...this.flowTraceSteps]}flowStepTargetLabel(e,t){if(t==="inputText"||t==="runScript"||t==="evalScript")return;let i=e[t];if(typeof i=="string")return i.slice(0,80);if(typeof i=="number"||typeof i=="boolean")return String(i);if(!i||typeof i!="object")return;let r=i,o=r.id??r.text??r.name??r.path;if(typeof o=="string"&&o)return o.slice(0,80);if(r.point&&typeof r.point=="string")return r.point.slice(0,80);if(typeof r.x=="number"&&typeof r.y=="number")return`${Math.round(r.x)}, ${Math.round(r.y)}`}recordFlowTraceStep(e){let t=Date.now(),i={stepIndex:e.stepIndex,stepName:e.stepName,...e.targetLabel?{targetLabel:e.targetLabel}:{},startedAtMs:e.startedAtMs,endedAtMs:t,durationMs:Math.max(0,t-e.startedAtMs),status:e.status};e.error!=null&&(i.error=e.error instanceof Error?e.error.message:String(e.error)),this.flowTraceSteps.push(i)}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,this.lastRecordingFrameStats=null,new Error(t?.error||"recording stop failed");this.lastRecordingStartedAtMs=this.recordingStartedAtMs,this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.lastRecordingFrameStats=t.frameStats??null,this.recordingStartedAtMs=null;let i=[],r=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${r}, chunk: 2097152 })`);if(!l||(i.push(Buffer.from(l.data,"base64")),r=l.offset,l.done))break}if(i.length===0)throw new Error("recording requested but no video buffer was produced");S.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=b.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return S.writeFileSync(s,Buffer.concat(i)),s}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await f(t);return}let i=await ye({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(i.settled?` [flow] recording tail settled in ${i.elapsed}ms`:` [flow] recording tail reached ${i.elapsed}ms budget`)}async findElement(e){if(e.childOf!=null||typeof e.index=="number")return this.findElementScoped(e);let t=!!e.text&&/[.*+?^$()[\]{}|\\]/.test(e.text);return this.evaluate(`(async () => {
219
+ })()`);if(!t?.ok)throw new Error(t?.error||"recording unavailable on this page");this.recordingStartedAtMs||(this.recordingStartedAtMs=typeof t.startedAtMs=="number"&&Number.isFinite(t.startedAtMs)?t.startedAtMs:e)}async startRecording(){this.recordingEnabled=!0,await this.ensureRecordingStarted()}prepareRecording(){this.recordingEnabled=!0}getLastRecordingDurationMs(){return this.lastRecordingDurationMs}getLastRecordingStartedAtMs(){return this.lastRecordingStartedAtMs}getLastRecordingFrameStats(){return this.lastRecordingFrameStats}getFlowTraceSteps(){return[...this.flowTraceSteps]}flowStepTargetLabel(e,t){if(t==="inputText"||t==="runScript"||t==="evalScript")return;let r=e[t];if(typeof r=="string")return r.slice(0,80);if(typeof r=="number"||typeof r=="boolean")return String(r);if(!r||typeof r!="object")return;let i=r,o=i.id??i.text??i.name??i.path;if(typeof o=="string"&&o)return o.slice(0,80);if(i.point&&typeof i.point=="string")return i.point.slice(0,80);if(typeof i.x=="number"&&typeof i.y=="number")return`${Math.round(i.x)}, ${Math.round(i.y)}`}recordFlowTraceStep(e){let t=Date.now(),r={stepIndex:e.stepIndex,stepName:e.stepName,...e.targetLabel?{targetLabel:e.targetLabel}:{},startedAtMs:e.startedAtMs,endedAtMs:t,durationMs:Math.max(0,t-e.startedAtMs),status:e.status};e.error!=null&&(r.error=e.error instanceof Error?e.error.message:String(e.error)),this.flowTraceSteps.push(r)}async stopRecording(){if(!this.recordingEnabled||!this.opts.recordingOutputDir)return null;this.recordingEnabled=!1;let e=Date.now(),t=await this.evaluate("window.__sootsimRecorder.stop()");if(!t?.ok)throw this.recordingStartedAtMs=null,this.lastRecordingFrameStats=null,new Error(t?.error||"recording stop failed");this.lastRecordingStartedAtMs=this.recordingStartedAtMs,this.lastRecordingDurationMs=this.recordingStartedAtMs?Math.max(1,e-this.recordingStartedAtMs):null,this.lastRecordingFrameStats=t.frameStats??null,this.recordingStartedAtMs=null;let r=[],i=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${i}, chunk: 2097152 })`);if(!l||(r.push(Buffer.from(l.data,"base64")),i=l.offset,l.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");S.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=b.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return S.writeFileSync(s,Buffer.concat(r)),s}async waitForRecordingTail(e){if(!this.recordingEnabled)return;let t=Math.max(0,Math.round(e.maxMs));if(t<=0)return;if(!e.smart){await f(t);return}let r=await be({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:80,stablePolls:6,strict:!0});await this.waitForVisualSettle(),console.log(r.settled?` [flow] recording tail settled in ${r.elapsed}ms`:` [flow] recording tail reached ${r.elapsed}ms budget`)}async findElement(e){if(e.childOf!=null||typeof e.index=="number")return this.findElementScoped(e);let t=!!e.text&&/[.*+?^$()[\]{}|\\]/.test(e.text);return this.evaluate(`(async () => {
220
220
  const test = window.__sootsimTest
221
221
  if (!test) return null
222
222
  let node = null
@@ -365,18 +365,18 @@ process.stdin.on('end', async () => {
365
365
  )
366
366
  }
367
367
  return direct
368
- })()`)}async tap(e,t,i){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:i})}async longPress(e,t,i,r){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:i,target:r})}async waitForElement(e,t=5e3){let i=Date.now()+t,r=await this.findElement(e);for(;!r&&Date.now()<i;)await f(150),r=await this.findElement(e);return r}replayTargetForElement(e,t,i){return{id:e.id??i?.target?.id??t.id??null,testID:e.id??i?.target?.testID??t.testID??null,text:e.text??i?.target?.text??i?.target?.accessibilityLabel??t.text??t.accessibilityLabel??null,type:i?.target?.type??t.type??null}}async resolveInteractionPoint(e){if(e.point&&!e.id&&!e.text&&e.index===void 0&&!e.childOf)return{...X(e.point),element:null,target:void 0};let t=await this.waitForElement(e);if(!t)return null;let i=typeof t.nodeId=="number"?await this.resolveTapTarget(t.nodeId):null,r=this.replayTargetForElement(e,t,i);return e.point?{...X(e.point,{x:t.absolutePosition.x,y:t.absolutePosition.y,width:t.layout.width,height:t.layout.height}),element:t,target:r}:{x:i?.cx??t.absolutePosition.x+t.layout.width/2,y:i?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:r}}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let o=await this.resolveInteractionPoint(t);if(!o)throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`);(await this.activatePressAt(o.x,o.y))?.ok||await this.tap(o.x,o.y,o.target),await f(300);return}let i=await this.waitForElement(t);if(i){let o=i.isTextInput?4:1;for(let a=0;a<o;a++){let s=a===0?i:await this.findElement({text:t.text,id:t.id});if(!s)break;let l=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,u=l?.cx??s.absolutePosition.x+s.layout.width/2,p=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(u,p,this.replayTargetForElement(t,s,l)))?.hit===!0){if(await f(300),!s.isTextInput||await this.waitForFocusedTextInput(600,s))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await f(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async longPressOn(e){let t=typeof e=="string"?{text:e}:e,i=await this.resolveInteractionPoint(t);if(!i)throw new Error(`longPressOn: element not found: ${JSON.stringify(t)}`);let r=await this.longPress(i.x,i.y,3e3,i.target);if(r?.ok===!1||r?.value===!1)throw new Error(`longPressOn: long press missed: ${JSON.stringify(t)}`);await f(300)}async tapAtCoords(e,t){await this.tap(e,t),await f(300)}async doubleTapAtCoords(e,t,i=80){let r=Math.max(0,Math.round(i));if(!await this.evaluate(`(async () => {
368
+ })()`)}async tap(e,t,r){return await this.bridge.send({type:"tap",simId:this.opts.simId,x:e,y:t,target:r})}async longPress(e,t,r,i){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:r,target:i})}async waitForElement(e,t=5e3){let r=Date.now()+t,i=await this.findElement(e);for(;!i&&Date.now()<r;)await f(150),i=await this.findElement(e);return i}replayTargetForElement(e,t,r){return{id:e.id??r?.target?.id??t.id??null,testID:e.id??r?.target?.testID??t.testID??null,text:e.text??r?.target?.text??r?.target?.accessibilityLabel??t.text??t.accessibilityLabel??null,type:r?.target?.type??t.type??null}}async resolveInteractionPoint(e){if(e.point&&!e.id&&!e.text&&e.index===void 0&&!e.childOf)return{...Q(e.point),element:null,target:void 0};let t=await this.waitForElement(e);if(!t)return null;let r=typeof t.nodeId=="number"?await this.resolveTapTarget(t.nodeId):null,i=this.replayTargetForElement(e,t,r);return e.point?{...Q(e.point,{x:t.absolutePosition.x,y:t.absolutePosition.y,width:t.layout.width,height:t.layout.height}),element:t,target:i}:{x:r?.cx??t.absolutePosition.x+t.layout.width/2,y:r?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:i}}async tapOn(e){let t=typeof e=="string"?{text:e}:e;if(t.point){let o=await this.resolveInteractionPoint(t);if(!o)throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`);(await this.activatePressAt(o.x,o.y))?.ok||await this.tap(o.x,o.y,o.target),await f(300);return}let r=await this.waitForElement(t);if(r){let o=r.isTextInput?4:1;for(let a=0;a<o;a++){let s=a===0?r:await this.findElement({text:t.text,id:t.id});if(!s)break;let l=typeof s.nodeId=="number"?await this.resolveTapTarget(s.nodeId):null,u=l?.cx??s.absolutePosition.x+s.layout.width/2,p=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(u,p,this.replayTargetForElement(t,s,l)))?.hit===!0){if(await f(300),!s.isTextInput||await this.waitForFocusedTextInput(600,s))return;continue}break}}if((await this.activatePressTarget(t))?.ok){await f(300);return}throw new Error(`tapOn: element not found: ${JSON.stringify(t)}`)}async longPressOn(e){let t=typeof e=="string"?{text:e}:e,r=await this.resolveInteractionPoint(t);if(!r)throw new Error(`longPressOn: element not found: ${JSON.stringify(t)}`);let i=await this.longPress(r.x,r.y,3e3,r.target);if(i?.ok===!1||i?.value===!1)throw new Error(`longPressOn: long press missed: ${JSON.stringify(t)}`);await f(300)}async tapAtCoords(e,t){await this.tap(e,t),await f(300)}async doubleTapAtCoords(e,t,r=80){let i=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
369
369
  const interact = window.__sootsimInteract
370
370
  if (interact?.doubleTap) {
371
- return !!(await interact.doubleTap(${e}, ${t}, ${r}))
371
+ return !!(await interact.doubleTap(${e}, ${t}, ${i}))
372
372
  }
373
373
  if (!interact?.tap) return false
374
374
  const first = await interact.tap(${e}, ${t})
375
375
  if (!first || first.hit === false) return false
376
- await new Promise((resolve) => setTimeout(resolve, ${r}))
376
+ await new Promise((resolve) => setTimeout(resolve, ${i}))
377
377
  const second = await interact.tap(${e}, ${t})
378
378
  return !!second && second.hit !== false
379
- })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await f(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 f(200)}let i=await this.findElement(t),r=i?` (matched node at y=${Math.round(i.absolutePosition.y)} h=${Math.round(i.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 i=await this.findElement(t),r=i?` at (${Math.round(i.absolutePosition.x)},${Math.round(i.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<N)}async inputText(e){if(!await this.waitForFocusedTextInput())throw new Error("inputText: no focused TextInput; tap the input and wait for focus before typing");await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await f(200)}focusedTextInputMatches(e,t){if(!t||typeof t.nodeId=="number"&&typeof e.nodeId=="number"&&t.nodeId===e.nodeId)return!0;let i=t.testID??null,r=e.testID??null;if(i&&r&&i===r)return!0;let o=t.id??null,a=e.id??null;return!!(o&&a&&o===a)}async waitForFocusedTextInput(e=1500,t){let i=Date.now()+e;for(;Date.now()<i;){try{let r=await this.callTest("getFocusedNode");if(r&&this.focusedTextInputMatches(r,t))return!0}catch{}await f(50)}return!1}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await f(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await f(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(`(() => {
379
+ })()`))throw new Error(`doubleTapAtCoords failed at (${e}, ${t})`);await f(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 f(200)}let r=await this.findElement(t),i=r?` (matched node at y=${Math.round(r.absolutePosition.y)} h=${Math.round(r.layout.height)} \u2014 off-screen)`:" (no matching node in tree)";throw new Error(`assertVisible: ${JSON.stringify(t)} not visible${i}`)}async assertNotVisible(e){let t=typeof e=="string"?{text:e}:e;if(await this.isElementVisible(t)){let r=await this.findElement(t),i=r?` at (${Math.round(r.absolutePosition.x)},${Math.round(r.absolutePosition.y)})`:"";throw new Error(`assertNotVisible: ${JSON.stringify(t)} IS visible${i}`)}}async isElementVisible(e){let t=await this.findElement(e);return!!(t&&t.absolutePosition.y+t.layout.height>0&&t.absolutePosition.y<N)}async inputText(e){if(!await this.waitForFocusedTextInput())throw new Error("inputText: no focused TextInput; tap the input and wait for focus before typing");await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"type",text:e}),await f(200)}focusedTextInputMatches(e,t){if(!t||typeof t.nodeId=="number"&&typeof e.nodeId=="number"&&t.nodeId===e.nodeId)return!0;let r=t.testID??null,i=e.testID??null;if(r&&i&&r===i)return!0;let o=t.id??null,a=e.id??null;return!!(o&&a&&o===a)}async waitForFocusedTextInput(e=1500,t){let r=Date.now()+e;for(;Date.now()<r;){try{let i=await this.callTest("getFocusedNode");if(i&&this.focusedTextInputMatches(i,t))return!0}catch{}await f(50)}return!1}async pressKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"press",text:e}),await f(120)}async dispatchKey(e){await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:e}),await f(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(`(() => {
380
380
  const keyboard =
381
381
  window.__sootsimKeyboard ??
382
382
  window.SootSim?.bridges?.keyboard ??
@@ -386,7 +386,7 @@ process.stdin.on('end', async () => {
386
386
  visible: !!keyboard?.isVisible?.(),
387
387
  focused: !!test?.isTextInputFocused?.(),
388
388
  }
389
- })()`);if(!t?.visible&&!t?.focused){await f(80);return}await f(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:"Backspace"});await f(100)}async waitFor(e){let t=Date.now()+(e.timeout||Z);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let i=await this.findElement(e),r=i?` (matched node y=${Math.round(i.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||Z}ms${r}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Bt(e),i=Dt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});S.mkdirSync(b.dirname(i),{recursive:!0});let r=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};r&&r!=="full"&&(o.layers=r);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let u=await this.readCurrentDeviceModel();if(!u)throw new Error("could not read current device model for framed screenshot");let p=await rt(l,u);S.writeFileSync(i,p),console.log(`[flow] screenshot: ${i} (frame: ${u})`);return}S.writeFileSync(i,l),console.log(`[flow] screenshot: ${i}`)}async readCurrentDeviceModel(){let e=await this.bridge.send({type:"call",simId:this.opts.simId,path:"SootSim.bridges.settings.get",args:[]}),t=e&&typeof e.deviceModel=="string"?e.deviceModel:null;return!t||!(t in Oe)?null:t}async captureFailureScreenshot(e){S.mkdirSync(b.dirname(e),{recursive:!0});let i=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");S.writeFileSync(e,Buffer.from(i,"base64"))}async captureFailureBundle(e,t){S.mkdirSync(e,{recursive:!0});let i=(p,m)=>{try{S.writeFileSync(b.join(e,p),m)}catch{}},r=async p=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:p})}catch{return null}},o=await r(`(async () => {
389
+ })()`);if(!t?.visible&&!t?.focused){await f(80);return}await f(80)}}async eraseText(e){for(let t=0;t<e;t++)await this.bridge.send({type:"keyboard",simId:this.opts.simId,action:"dispatchKey",text:"Backspace"});await f(100)}async waitFor(e){let t=Date.now()+(e.timeout||X);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let r=await this.findElement(e),i=r?` (matched node y=${Math.round(r.absolutePosition.y)} \u2014 still off-screen at deadline)`:"";throw new Error(`waitFor: ${JSON.stringify(e)} not found after ${e.timeout||X}ms${i}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Ct(e),r=Lt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});S.mkdirSync(b.dirname(r),{recursive:!0});let i=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};i&&i!=="full"&&(o.layers=i);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let u=await this.readCurrentDeviceModel();if(!u)throw new Error("could not read current device model for framed screenshot");let p=await nt(l,u);S.writeFileSync(r,p),console.log(`[flow] screenshot: ${r} (frame: ${u})`);return}S.writeFileSync(r,l),console.log(`[flow] screenshot: ${r}`)}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 _e)?null:t}async captureScreenshot(e){S.mkdirSync(b.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");S.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){S.mkdirSync(e,{recursive:!0});let r=(p,m)=>{try{S.writeFileSync(b.join(e,p),m)}catch{}},i=async p=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:p})}catch{return null}},o=await i(`(async () => {
390
390
  const out = {
391
391
  simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
392
392
  url: location.href,
@@ -410,7 +410,7 @@ process.stdin.on('end', async () => {
410
410
  }
411
411
  } catch {}
412
412
  return out
413
- })()`);i("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 m=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");i("screenshot.png",Buffer.from(m,"base64"))}catch{}let a=await r(`(async () => {
413
+ })()`);r("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 m=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(m,"base64"))}catch{}let a=await i(`(async () => {
414
414
  const t = window.__sootsimTest
415
415
  const mainShell = window.SootSim?.bridges?.mainShell
416
416
  if (!t) return { error: 'no test bridge' }
@@ -420,19 +420,19 @@ process.stdin.on('end', async () => {
420
420
  } catch {}
421
421
  const all = await t.queryAll({ pruneHidden: true })
422
422
  return { shell, nodes: all, url: location.href, title: document.title }
423
- })()`);a&&i("describe.json",JSON.stringify(a,null,2));let s=await r("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof s=="string"&&i("a11y.txt",s);let l=await r("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&i("tree.txt",l);let u=await r(`(() => {
423
+ })()`);a&&r("describe.json",JSON.stringify(a,null,2));let s=await i("(async () => await window.__sootsimTest?.dumpAccessibilityTree?.(20))()");typeof s=="string"&&r("a11y.txt",s);let l=await i("(async () => await window.__sootsimTest?.dumpTree?.(15))()");typeof l=="string"&&r("tree.txt",l);let u=await i(`(() => {
424
424
  const c = window.__sootsimConsole
425
425
  return {
426
426
  errors: c?.getErrors?.() ?? [],
427
427
  warnings: c?.getWarnings?.() ?? [],
428
428
  requests: (window.__sootsimGetFailedRequests?.() ?? []),
429
429
  }
430
- })()`);return u&&i("console.json",JSON.stringify(u,null,2)),e}async swipe(e="UP",t=300){let i=Q/2,r=N/2,o=200,a=i,s=r,l=i,u=r;switch(e.toUpperCase()){case"UP":s+=o,u-=o;break;case"DOWN":s-=o,u+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let p=Math.max(10,Math.round(t/16));await this.drag(a,s,l,u,p,16)}async drag(e,t,i,r,o=12,a=16){if(!(await this.evaluate(`(async () => {
430
+ })()`);return u&&r("console.json",JSON.stringify(u,null,2)),e}async swipe(e="UP",t=300){let r=ee/2,i=N/2,o=200,a=r,s=i,l=r,u=i;switch(e.toUpperCase()){case"UP":s+=o,u-=o;break;case"DOWN":s-=o,u+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let p=Math.max(10,Math.round(t/16));await this.drag(a,s,l,u,p,16)}async drag(e,t,r,i,o=12,a=16){if(!(await this.evaluate(`(async () => {
431
431
  const interact = window.__sootsimInteract
432
432
  if (!interact?.drag) return { ok: false }
433
- const value = await interact.drag(${e}, ${t}, ${i}, ${r}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(a))})
433
+ const value = await interact.drag(${e}, ${t}, ${r}, ${i}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(a))})
434
434
  return { ok: !!value, value }
435
- })()`))?.ok)throw new Error("drag failed");await f(300)}async swipeCoords(e,t,i=300){let r=X(e),o=X(t),a=Math.max(10,Math.round(i/16));await this.drag(r.x,r.y,o.x,o.y,a,16)}async swipeFrom(e,t="UP",i=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,a=r.absolutePosition.y+r.layout.height/2,s=180,l=o,u=a;switch(t.toUpperCase()){case"UP":u-=s;break;case"DOWN":u+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let p=Math.max(10,Math.round(i/16));await this.drag(o,a,l,u,p,16)}async scrollTo(e,t,i){let r=await this.callTest("scrollTo",e,t,i,!1);if(!r?.ok)throw new Error(`scrollTo failed: ${r?.reason||"unknown error"}`);await f(250)}async pinch(e){let t=await this.evaluate(`(async () => {
435
+ })()`))?.ok)throw new Error("drag failed");await f(300)}async swipeCoords(e,t,r=300){let i=Q(e),o=Q(t),a=Math.max(10,Math.round(r/16));await this.drag(i.x,i.y,o.x,o.y,a,16)}async swipeFrom(e,t="UP",r=300){let i=await this.findElement(e);if(!i)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=i.absolutePosition.x+i.layout.width/2,a=i.absolutePosition.y+i.layout.height/2,s=180,l=o,u=a;switch(t.toUpperCase()){case"UP":u-=s;break;case"DOWN":u+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let p=Math.max(10,Math.round(r/16));await this.drag(o,a,l,u,p,16)}async scrollTo(e,t,r){let i=await this.callTest("scrollTo",e,t,r,!1);if(!i?.ok)throw new Error(`scrollTo failed: ${i?.reason||"unknown error"}`);await f(250)}async pinch(e){let t=await this.evaluate(`(async () => {
436
436
  const interact = window.__sootsimInteract
437
437
  if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
438
438
  const ok = await interact.pinch(
@@ -441,7 +441,7 @@ process.stdin.on('end', async () => {
441
441
  ${e.steps||12}, ${e.stepMs||16}
442
442
  )
443
443
  return { ok: !!ok, reason: ok ? null : 'pinch returned false' }
444
- })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await f(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){let t=Math.max(0,Math.round(e));if(t<=0)return;(await ye({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:32,stablePolls:2,strict:!0})).settled&&this.markVisualSettled()}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),i=e.direction?.toUpperCase()||"DOWN",r=i==="DOWN"?"UP":i==="UP"?"DOWN":i;for(;Date.now()<t;){let o=await this.findElement({text:e.element});if(o&&o.absolutePosition.y>=0&&o.absolutePosition.y+o.layout.height>0&&o.absolutePosition.y<N-50){if(e.centerElement){let a=N/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),u=s>0?a-l:a+l;await this.drag(Q/2,a,Q/2,u,10,16)}}return}await this.swipe(r,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||Z);for(;Date.now()<t;){let i=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,r=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(i&&r)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let r=!1;for(let o=0;o<3&&!r;o++)try{r=await this.evaluate(he(!0),2e4)}catch{await f(1e3)}r||console.warn(" warn: tenant storage clear did not ack \u2014 hard-reloading anyway (worker reset follows)")}await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId()}async softReloadGuestApp(e){if(!await this.evaluate(he(e),12e4))throw new Error("guest app soft reload bridge unavailable")}async rearmCaptureAfterRuntimeReload(){if(!this.recordingEnabled&&!this.profilingEnabled)return;let e=Date.now()+1e4,t=null;for(;Date.now()<e;){await this.refreshSimId();try{this.recordingEnabled&&await this.ensureRecordingStarted(),this.profilingEnabled&&await this.startProfile();return}catch(i){t=i,await f(250)}}throw new Error(`capture re-arm failed after app reload: ${t instanceof Error?t.message:String(t)}`)}async launchApp(e){await this.refreshSimId(),e&&typeof e=="object"&&e.arguments&&console.log("[flow] launchApp.arguments ignored (sootsim has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),i=Mt(e,"resetRuntime");if(!this.firstLaunchDone&&!t){if(this.firstLaunchDone=!0,i){let r=await V(this.bridge).catch(()=>null),o=r?.state==="home"&&r.activeApp==null;await this.softReloadGuestApp(!1),await this.waitForTree(12e4),o&&(await pe(this.bridge,"goHome",1e3),await this.waitForShellHome(1e3)),await this.launchShellAppFromHomeIfNeeded(e,o?{...r??{},state:"home",activeApp:null}:null)}else await this.launchShellAppFromHomeIfNeeded(e);await this.waitForTree(3e4)}else if(this.firstLaunchDone=!0,await this.reloadGuestApp(t),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(r){console.warn(` warn: onAfterLaunch hook threw: ${r instanceof Error?r.message:r}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
444
+ })()`);if(!t?.ok)throw new Error(`pinch failed: ${t?.reason||"unknown error"}`);await f(250)}async dumpTree(e=6){let t=await this.bridge.send({type:"tree",simId:this.opts.simId,depth:e});return console.log("[flow] tree:"),console.log(typeof t=="string"?t:JSON.stringify(t,null,2)),typeof t=="string"?t:JSON.stringify(t)}async assertTreeContains(e){if(!(await this.dumpTree(8)).includes(e))throw new Error(`assertTreeContains: "${e}" not in tree`)}async waitForAnimationToEnd(e=2e3){let t=Math.max(0,Math.round(e));if(t<=0)return;(await be({bridge:this.bridge,simId:this.opts.simId,maxMs:t,pollMs:32,stablePolls:2,strict:!0})).settled&&this.markVisualSettled()}async back(){try{await this.tapOn("\u2039")}catch{await this.tapOn("<")}}async scrollUntilVisible(e){let t=Date.now()+(e.timeout||15e3),r=e.direction?.toUpperCase()||"DOWN",i=r==="DOWN"?"UP":r==="UP"?"DOWN":r;for(;Date.now()<t;){let o=await this.findElement({text:e.element});if(o&&o.absolutePosition.y>=0&&o.absolutePosition.y+o.layout.height>0&&o.absolutePosition.y<N-50){if(e.centerElement){let a=N/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),u=s>0?a-l:a+l;await this.drag(ee/2,a,ee/2,u,10,16)}}return}await this.swipe(i,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+(e.timeout||X);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,i=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&i)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let i=!1;for(let o=0;o<3&&!i;o++)try{i=await this.evaluate(fe(!0),2e4)}catch{await f(1e3)}i||console.warn(" warn: tenant storage clear did not ack \u2014 hard-reloading anyway (worker reset follows)")}await this.evaluate("window.location.reload()").catch(()=>{}),await f(500),await this.refreshSimId()}async softReloadGuestApp(e){if(!await this.evaluate(fe(e),12e4))throw new Error("guest app soft reload bridge unavailable")}async rearmCaptureAfterRuntimeReload(){if(!this.recordingEnabled&&!this.profilingEnabled)return;let e=Date.now()+1e4,t=null;for(;Date.now()<e;){await this.refreshSimId();try{this.recordingEnabled&&await this.ensureRecordingStarted(),this.profilingEnabled&&await this.startProfile();return}catch(r){t=r,await f(250)}}throw new Error(`capture re-arm failed after app reload: ${t instanceof Error?t.message:String(t)}`)}async launchApp(e){await this.refreshSimId(),e&&typeof e=="object"&&e.arguments&&console.log("[flow] launchApp.arguments ignored (sootsim has no native process)");let t=!!(e&&typeof e=="object"&&e.clearState),r=_t(e,"resetRuntime");if(!this.firstLaunchDone&&!t){if(this.firstLaunchDone=!0,r){let i=await J(this.bridge).catch(()=>null),o=i?.state==="home"&&i.activeApp==null;await this.softReloadGuestApp(!1),await this.waitForTree(12e4),o&&(await he(this.bridge,"goHome",1e3),await this.waitForShellHome(1e3)),await this.launchShellAppFromHomeIfNeeded(e,o?{...i??{},state:"home",activeApp:null}:null)}else await this.launchShellAppFromHomeIfNeeded(e);await this.waitForTree(3e4)}else if(this.firstLaunchDone=!0,await this.reloadGuestApp(t),await this.waitForTree(12e4),this.opts.onAfterLaunch)try{await this.opts.onAfterLaunch()}catch(i){console.warn(` warn: onAfterLaunch hook threw: ${i instanceof Error?i.message:i}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
445
445
  requestAnimationFrame(() => {
446
446
  requestAnimationFrame(() => {
447
447
  requestAnimationFrame(() => {
@@ -449,7 +449,7 @@ process.stdin.on('end', async () => {
449
449
  })
450
450
  })
451
451
  })
452
- })`),this.markVisualSettled()}catch{await f(180),this.markVisualSettled()}}markVisualSettled(){this.lastVisualSettledAtMs=Date.now()}hasFreshVisualSettle(){return Date.now()-this.lastVisualSettledAtMs<750}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(xe(e)){let i=G(e,"appId")||G(e,"id");if(i)return i}return Ot(t)||"connect"}async waitForShellAppLaunched(e,t){let i=Date.now()+t,r=null;for(;Date.now()<i;){try{r=await V(this.bridge)}catch{r=null}if(r?.state==="app"&&r.activeApp===e&&r.showSwitcher===!1&&typeof r.launchProgress=="number"&&r.launchProgress>=.98)return;await f(16)}}async waitForShellHome(e){let t=Date.now()+e;for(;Date.now()<t;){let i=await V(this.bridge).catch(()=>null);if(i?.state==="home"&&i.activeApp==null&&i.showSwitcher===!1)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e,t){let i=null;if(t)i=t;else try{i=await V(this.bridge)}catch{return!1}if(i?.state!=="home"||i.activeApp!=null)return!1;let r=this.resolveShellLaunchAppId(e,i);return this.recordingEnabled&&await this.ensureRecordingStarted(),await pe(this.bridge,"launchApp",1e3,r),await this.waitForShellAppLaunched(r,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
452
+ })`),this.markVisualSettled()}catch{await f(180),this.markVisualSettled()}}markVisualSettled(){this.lastVisualSettledAtMs=Date.now()}hasFreshVisualSettle(){return Date.now()-this.lastVisualSettledAtMs<750}resolveShellLaunchAppId(e,t){if(typeof e=="string"&&e.length>0)return e;if(Te(e)){let r=z(e,"appId")||z(e,"id");if(r)return r}return Dt(t)||"connect"}async waitForShellAppLaunched(e,t){let r=Date.now()+t,i=null;for(;Date.now()<r;){try{i=await J(this.bridge)}catch{i=null}if(i?.state==="app"&&i.activeApp===e&&i.showSwitcher===!1&&typeof i.launchProgress=="number"&&i.launchProgress>=.98)return;await f(16)}}async waitForShellHome(e){let t=Date.now()+e;for(;Date.now()<t;){let r=await J(this.bridge).catch(()=>null);if(r?.state==="home"&&r.activeApp==null&&r.showSwitcher===!1)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e,t){let r=null;if(t)r=t;else try{r=await J(this.bridge)}catch{return!1}if(r?.state!=="home"||r.activeApp!=null)return!1;let i=this.resolveShellLaunchAppId(e,r);return this.recordingEnabled&&await this.ensureRecordingStarted(),await he(this.bridge,"launchApp",1e3,i),await this.waitForShellAppLaunched(i,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
453
453
  if (!window.__sootsimShellPerf) {
454
454
  return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
455
455
  }
@@ -460,15 +460,15 @@ process.stdin.on('end', async () => {
460
460
  return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
461
461
  }
462
462
  return await window.__sootsimShellPerf.stop()
463
- })()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,i=await this.findElement(t);if(!i)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let r=i.text??i.testID??"";this.js.setCopiedText(r),this.js.putEnv("maestroCopiedText",r),console.log(`[flow] copied text: ${JSON.stringify(r)}`)}evalScript(e){let i=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);i!==void 0&&i!==""&&console.log("[flow] evalScript ->",i)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let i=b.resolve(this.opts.flowDir,t.file),r=S.readFileSync(i,"utf8");this.js.evaluate(r,{env:t.env}),console.log(`[flow] runScript: ${t.file} done`)}async openLink(e){let t=typeof e=="string"?e:e.link;if(!t)throw new Error("openLink: missing link");let i=await this.callTest("openDeepLink",t);if(!i?.ok)throw new Error(`openLink failed: ${i?.error||"no test bridge"}`);await f(300)}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()===this.js.maestro.platform.toLowerCase():e.true!==void 0?ot(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let i=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),r=i?i[1]:void 0;return!!(r&&typeof r=="object"&&"optional"in r&&r.optional)}async runStep(e,t){let i=typeof e=="string"?st(e):e,r=Object.keys(i).find(l=>l!=="when")||Object.keys(i)[0];console.log(`[flow] step ${t+1}: ${r}`);let o=Date.now(),a=this.flowStepTargetLabel(i,r),s;try{s=this.js.interpolateStep(i),a=this.flowStepTargetLabel(s,r)??a}catch(l){if(this.isOptional(i)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:r,target:i[r]},this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}if(s.when&&!await this.evaluateWhen(s.when)){console.log("[flow] (when: predicate false, skipped)"),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),u=1e4,p=this.runStepInner(s);if(l)await p;else{let x=null,g=new Promise((P,_)=>{x=setTimeout(()=>{_(new Error(`step watchdog: ${r} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{await Promise.race([p,g])}finally{x&&clearTimeout(x)}}let m=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!m&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"success"})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:r,target:s[r]},this.recordFlowTraceStep({stepIndex:t,stepName:r,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.longPressOn)await this.longPressOn(e.longPressOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else if(e.takeScreenshot)await this.takeScreenshot(e.takeScreenshot);else if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo){let t=typeof e.scrollTo.nodeId=="number"?{nodeId:e.scrollTo.nodeId}:e.scrollTo.id;if(!t)throw new Error("scrollTo requires id or nodeId");await this.scrollTo(t,e.scrollTo.x,e.scrollTo.y)}else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd){let t=e.waitForAnimationToEnd;await this.waitForAnimationToEnd(typeof t=="number"?t:typeof t=="object"&&typeof t.timeout=="number"?t.timeout:2e3)}else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await f(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat&&Array.isArray(e.repeat.commands)){let t=e.repeat.times,i=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(i))throw new Error(`repeat.times is not a number: ${t}`);let r=e.repeat.when??e.repeat.condition,o=async()=>r?this.evaluateWhen(r):!0,a=r?i:Math.min(i,1e3),s=0;for(;s<a&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);s++}}else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")this.evalScript(e.evalScript);else if(e.runScript){let t=e.runScript,i=typeof t=="string"?void 0:t.when;if(i&&!await this.evaluateWhen(i)){console.log("[flow] runScript skipped (when predicate false)");return}this.runScript(t)}else if(e.openLink!==void 0)await this.openLink(e.openLink);else if(e.runFlow){let t=e.runFlow,i=typeof t=="string"?t:t.file,r=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,a=typeof t=="string"?void 0:t.when;if(a&&!await this.evaluateWhen(a)){console.log(`[flow] runFlow skipped (when predicate false): ${i??"inline commands"}`);return}if(!i&&!r)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[s,l]of Object.entries(o))this.js.putEnv(s,l);if(i){let s=b.resolve(this.opts.flowDir,i),l=S.readFileSync(s,"utf8"),u=this.opts.flowDir;this.opts.flowDir=b.dirname(s);try{await this.runFlow(Lt(l))}finally{this.opts.flowDir=u}}else if(r)for(let s=0;s<r.length;s++)await this.runStep(r[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}liveStatus=null;async runFlow(e){let t=[],i=[],r=[];for(let a of e){let s=Object.keys(a);if(s.length===1&&s[0]==="onFlowStart"&&Array.isArray(a.onFlowStart)){t.push(...a.onFlowStart);continue}if(s.length===1&&s[0]==="onFlowComplete"&&Array.isArray(a.onFlowComplete)){i.push(...a.onFlowComplete);continue}r.push(a)}if(this.liveStatus&&await this.liveStatus.plan(r.map((a,s)=>{let l=typeof a=="string"?st(a):a,u=Object.keys(l).find(p=>p!=="when")??Object.keys(l)[0];return{index:s,name:u,target:this.flowStepTargetLabel(l,u)}})),t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let a=0;a<t.length;a++)await this.runStep(t[a],a)}let o=null;try{await this.runFlowBody(r)}catch(a){o=a instanceof Error?a:new Error(String(a))}if(i.length>0){console.log(`[flow] onFlowComplete (${i.length} steps)`);for(let a=0;a<i.length;a++)try{await this.runStep(i[a],a)}catch(s){console.warn(`[flow] onFlowComplete step ${a+1} failed: ${s instanceof Error?s.message:s}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let i=e[t],r=typeof i.wait=="number"?i.wait:0,o=typeof i.waitFor?.timeout=="number"?i.waitFor.timeout:0,a=Math.max(6e4,r+15e3,o+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let s=Date.now(),l=async(u,p)=>{if(!this.liveStatus)return;let m=this.flowTraceSteps[this.flowTraceSteps.length-1],x=m&&m.stepIndex===t&&m.startedAtMs>=s;await this.liveStatus.step(t,u?"failure":x&&m.status==="skipped"?"skipped":"success",{durationMs:Date.now()-s,error:u?p instanceof Error?p.message.slice(0,300):String(p).slice(0,300):x&&m.error||void 0})};try{i.runFlow||i.launchApp?await this.runStep(i,t):await Promise.race([this.runStep(i,t),new Promise((u,p)=>setTimeout(()=>p(new Error(`step ${t+1} (${Object.keys(i)[0]}) exceeded ${a}ms deadline`)),a))])}catch(u){throw await l(!0,u),u}await l(!1)}}};var te=class{constructor(e,t){this.bridge=e;this.flowName=t}disabled=!1;paused=!1;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async push(e){if(!this.disabled)try{let t=await this.bridge.send({type:"flowStatus",status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=t?.control?.paused===!0}catch(t){this.disabled=!0,console.log(`[flow] live status unavailable (${t instanceof Error?t.message.slice(0,120):t}) \u2014 continuing without the devtools rail`)}}async plan(e){await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,i){await this.push({phase:"step",state:"running",step:{index:e,status:t,...i}})}async end(e){await this.push({phase:"end",state:e})}async waitWhilePaused(){if(!this.disabled)for(;this.paused;){for(console.log("[flow] paused from devtools \u2014 waiting\u2026");this.paused&&!this.disabled;)await new Promise(e=>setTimeout(e,400)),await this.push({phase:"heartbeat",state:"paused"});this.disabled||console.log("[flow] resumed")}}};var Te=null;function Ii(){return Te}var Ee=[];function $i(){return Ee}async function Ct(n){if(!n)return"";let e=n.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let i=(await Be()).find(r=>r.name.toLowerCase()===e.toLowerCase());return i?String(i.preferredPort):e}async function Nt(){let n=await Le(),e=n.find(i=>i.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=n[0];return t?`http://localhost:${t.port}/__soot/`:null}async function lt(n){Te=null,Ee=[],(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
464
- sootsim flow \u2014 run flows or manage a draft
463
+ })()`);if(this.profilingEnabled=!1,e?.error)throw new Error(e.error);return e}async stopApp(){await this.reloadGuestApp(!1),await this.rearmCaptureAfterRuntimeReload()}async clearState(){await this.reloadGuestApp(!0),await this.rearmCaptureAfterRuntimeReload()}clearKeychain(){console.warn("[flow] clearKeychain: sootsim has no keychain surface \u2014 no-op (warning)")}async copyTextFrom(e){let t=typeof e=="string"?{id:e}:e,r=await this.findElement(t);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let i=r.text??r.testID??"";this.js.setCopiedText(i),this.js.putEnv("maestroCopiedText",i),console.log(`[flow] copied text: ${JSON.stringify(i)}`)}evalScript(e){let r=/(?<!\\)\$\{[^$]*\}/.test(e)?this.js.evaluateStringTemplate(e):this.js.evaluate(e);r!==void 0&&r!==""&&console.log("[flow] evalScript ->",r)}runScript(e){let t=typeof e=="string"?{file:e}:e;if(!t.file)throw new Error("runScript requires a file");let r=b.resolve(this.opts.flowDir,t.file),i=S.readFileSync(r,"utf8");this.js.evaluate(i,{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 r=await this.callTest("openDeepLink",t);if(!r?.ok)throw new Error(`openLink failed: ${r?.error||"no test bridge"}`);await f(300)}async evaluateWhen(e){if(e.visible!==void 0){let t=typeof e.visible=="string"?{text:e.visible}:e.visible;return!!await this.findElement(t)}if(e.notVisible!==void 0){let t=typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible;return!await this.findElement(t)}return e.platform!==void 0?e.platform.toLowerCase()===this.js.maestro.platform.toLowerCase():e.true!==void 0?st(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),i=r?r[1]:void 0;return!!(i&&typeof i=="object"&&"optional"in i&&i.optional)}async runStep(e,t){let r=typeof e=="string"?at(e):e,i=Object.keys(r).find(l=>l!=="when")||Object.keys(r)[0];console.log(`[flow] step ${t+1}: ${i}`);let o=Date.now(),a=this.flowStepTargetLabel(r,i),s;try{s=this.js.interpolateStep(r),a=this.flowStepTargetLabel(s,i)??a}catch(l){if(this.isOptional(r)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:i,target:r[i]},this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}if(s.when&&!await this.evaluateWhen(s.when)){console.log("[flow] (when: predicate false, skipped)"),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),u=1e4,p=this.runStepInner(s);if(l)await p;else{let x=null,w=new Promise((P,_)=>{x=setTimeout(()=>{_(new Error(`step watchdog: ${i} made no progress in ${u}ms \u2014 bridge or bundle probably hung`))},u)});try{await Promise.race([p,w])}finally{x&&clearTimeout(x)}}let m=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!m&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"success"})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:i,target:s[i]},this.recordFlowTraceStep({stepIndex:t,stepName:i,targetLabel:a,startedAtMs:o,status:"failure",error:l}),l}}async runStepInner(e){if(e.tapOn)await this.tapOn(e.tapOn);else if(e.longPressOn)await this.longPressOn(e.longPressOn);else if(e.scrollUntilVisible)await this.scrollUntilVisible(e.scrollUntilVisible);else if(e.extendedWaitUntil)await this.extendedWaitUntil(e.extendedWaitUntil);else if(e.assertVisible)await this.assertVisible(e.assertVisible);else if(e.assertNotVisible)await this.assertNotVisible(e.assertNotVisible);else if(e.inputText)await this.inputText(e.inputText);else if(e.pressKey)await this.pressKey(e.pressKey);else if(e.dispatchKey)await this.dispatchKey(e.dispatchKey);else if(e.waitFor)await this.waitFor(e.waitFor);else if(e.takeScreenshot)await this.takeScreenshot(e.takeScreenshot);else if(e.swipe)e.swipe.start&&e.swipe.end?await this.swipeCoords(e.swipe.start,e.swipe.end,e.swipe.duration):e.swipe.from?await this.swipeFrom(e.swipe.from,e.swipe.direction,e.swipe.duration):await this.swipe(e.swipe.direction,e.swipe.duration);else if(e.scroll)await this.swipe(e.scroll.direction==="DOWN"?"UP":"DOWN");else if(e.scrollTo){let t=typeof e.scrollTo.nodeId=="number"?{nodeId:e.scrollTo.nodeId}:e.scrollTo.id;if(!t)throw new Error("scrollTo requires id or nodeId");await this.scrollTo(t,e.scrollTo.x,e.scrollTo.y)}else if(e.pinch)await this.pinch(e.pinch);else if(e.waitForAnimationToEnd){let t=e.waitForAnimationToEnd;await this.waitForAnimationToEnd(typeof t=="number"?t:typeof t=="object"&&typeof t.timeout=="number"?t.timeout:2e3)}else if(e.back)await this.back();else if(e.hideKeyboard)await this.hideKeyboard();else if(e.launchApp)await this.launchApp(e.launchApp);else if(typeof e.wait=="number")await f(e.wait);else if(e.dumpTree)await this.dumpTree(e.dumpTree);else if(e.tapAtCoords)await this.tapAtCoords(e.tapAtCoords.x,e.tapAtCoords.y);else if(e.doubleTapAtCoords)await this.doubleTapAtCoords(e.doubleTapAtCoords.x,e.doubleTapAtCoords.y,e.doubleTapAtCoords.gapMs);else if(e.assertTreeContains)await this.assertTreeContains(e.assertTreeContains);else if(typeof e.eraseText=="number")await this.eraseText(e.eraseText);else if(e.repeat&&Array.isArray(e.repeat.commands)){let t=e.repeat.times,r=t==null||t===""?Number.MAX_SAFE_INTEGER:Number(t);if(!Number.isFinite(r))throw new Error(`repeat.times is not a number: ${t}`);let i=e.repeat.when??e.repeat.condition,o=async()=>i?this.evaluateWhen(i):!0,a=i?r:Math.min(r,1e3),s=0;for(;s<a&&await o();){for(let l=0;l<e.repeat.commands.length;l++)await this.runStep(e.repeat.commands[l],l);s++}}else if(e.stopApp!==void 0)await this.stopApp();else if(e.clearState!==void 0)await this.clearState();else if(e.clearKeychain!==void 0)this.clearKeychain();else if(e.copyTextFrom!==void 0)await this.copyTextFrom(e.copyTextFrom);else if(typeof e.evalScript=="string")this.evalScript(e.evalScript);else if(e.runScript){let t=e.runScript,r=typeof t=="string"?void 0:t.when;if(r&&!await this.evaluateWhen(r)){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,r=typeof t=="string"?t:t.file,i=typeof t=="string"?void 0:t.commands,o=typeof t=="string"?void 0:t.env,a=typeof t=="string"?void 0:t.when;if(a&&!await this.evaluateWhen(a)){console.log(`[flow] runFlow skipped (when predicate false): ${r??"inline commands"}`);return}if(!r&&!i)throw new Error("runFlow requires either file or commands");this.js.enterEnvScope();try{if(o)for(let[s,l]of Object.entries(o))this.js.putEnv(s,l);if(r){let s=b.resolve(this.opts.flowDir,r),l=S.readFileSync(s,"utf8"),u=this.opts.flowDir;this.opts.flowDir=b.dirname(s);try{await this.runFlow(Nt(l))}finally{this.opts.flowDir=u}}else if(i)for(let s=0;s<i.length;s++)await this.runStep(i[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}liveStatus=null;async runFlow(e){let t=[],r=[],i=[];for(let a of e){let s=Object.keys(a);if(s.length===1&&s[0]==="onFlowStart"&&Array.isArray(a.onFlowStart)){t.push(...a.onFlowStart);continue}if(s.length===1&&s[0]==="onFlowComplete"&&Array.isArray(a.onFlowComplete)){r.push(...a.onFlowComplete);continue}i.push(a)}if(this.liveStatus&&await this.liveStatus.plan(i.map((a,s)=>{let l=typeof a=="string"?at(a):a,u=Object.keys(l).find(p=>p!=="when")??Object.keys(l)[0];return{index:s,name:u,target:this.flowStepTargetLabel(l,u)}})),t.length>0){console.log(`[flow] onFlowStart (${t.length} steps)`);for(let a=0;a<t.length;a++)await this.runStep(t[a],a)}let o=null;try{await this.runFlowBody(i)}catch(a){o=a instanceof Error?a:new Error(String(a))}if(r.length>0){console.log(`[flow] onFlowComplete (${r.length} steps)`);for(let a=0;a<r.length;a++)try{await this.runStep(r[a],a)}catch(s){console.warn(`[flow] onFlowComplete step ${a+1} failed: ${s instanceof Error?s.message:s}`)}}if(o)throw o}async runFlowBody(e){for(let t=0;t<e.length;t++){let r=e[t],i=typeof r.wait=="number"?r.wait:0,o=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,a=Math.max(6e4,i+15e3,o+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let s=Date.now(),l=async(u,p)=>{if(!this.liveStatus)return;let m=this.flowTraceSteps[this.flowTraceSteps.length-1],x=m&&m.stepIndex===t&&m.startedAtMs>=s;await this.liveStatus.step(t,u?"failure":x&&m.status==="skipped"?"skipped":"success",{durationMs:Date.now()-s,error:u?p instanceof Error?p.message.slice(0,300):String(p).slice(0,300):x&&m.error||void 0})};try{r.runFlow||r.launchApp?await this.runStep(r,t):await Promise.race([this.runStep(r,t),new Promise((u,p)=>setTimeout(()=>p(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${a}ms deadline`)),a))])}catch(u){throw await l(!0,u),u}await l(!1)}}};var re=class{constructor(e,t){this.bridge=e;this.flowName=t}disabled=!1;paused=!1;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async push(e){if(!this.disabled)try{let t=await this.bridge.send({type:"flowStatus",status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=t?.control?.paused===!0}catch(t){this.disabled=!0,console.log(`[flow] live status unavailable (${t instanceof Error?t.message.slice(0,120):t}) \u2014 continuing without the devtools rail`)}}async plan(e){await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,r){await this.push({phase:"step",state:"running",step:{index:e,status:t,...r}})}async end(e){await this.push({phase:"end",state:e})}async waitWhilePaused(){if(!this.disabled)for(;this.paused;){for(console.log("[flow] paused from devtools \u2014 waiting\u2026");this.paused&&!this.disabled;)await new Promise(e=>setTimeout(e,400)),await this.push({phase:"heartbeat",state:"paused"});this.disabled||console.log("[flow] resumed")}}};var Ee=null;function Rr(){return Ee}var Fe=[];function Mr(){return Fe}async function Wt(n){if(!n)return"";let e=n.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let r=(await Le()).find(i=>i.name.toLowerCase()===e.toLowerCase());return r?String(r.preferredPort):e}async function jt(){let n=await Ce(),e=n.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=n[0];return t?`http://localhost:${t.port}/__soot/`:null}async function ct(n){Ee=null,Fe=[],(n.length===0||n.includes("--help")||n.includes("-h"))&&(console.log(`
464
+ sootsim maestro \u2014 author and run Maestro YAML flows
465
465
 
466
466
  usage:
467
- sootsim flow <flow.yaml> [options]
468
- sootsim flow start
469
- sootsim flow keep
470
- sootsim flow end [--output <path>] [--validate] [--video]
471
- sootsim flow validate <path>
467
+ sootsim maestro test <flow.yaml> [options]
468
+ sootsim maestro start
469
+ sootsim maestro keep
470
+ sootsim maestro end [--output <path>] [--validate] [--video]
471
+ sootsim maestro validate <path>
472
472
 
473
473
  options:
474
474
  --record record a webm artifact while the flow runs
@@ -525,43 +525,43 @@ default runtime:
525
525
  recording and profiling both run on the same bridge-backed path
526
526
 
527
527
  examples:
528
- sootsim flow login.yaml
529
- sootsim flow demo.yaml --url 8081 --record --slow 500 --out ./recordings
530
- sootsim flow demo.yaml --sim a2
531
- sootsim flow start
532
- sootsim flow keep
533
- sootsim flow end --output ./flows/draft.yaml
534
- sootsim flow end --output ./flows/draft.yaml --validate
535
- sootsim flow end --output ./flows/draft.yaml --video
536
- sootsim flow validate ./flows/draft.yaml
528
+ sootsim maestro test login.yaml
529
+ sootsim maestro test demo.yaml --url 8081 --record --slow 500 --out ./recordings
530
+ sootsim maestro test demo.yaml --sim a2
531
+ sootsim maestro start
532
+ sootsim maestro keep
533
+ sootsim maestro end --output ./.maestro/draft.yaml
534
+ sootsim maestro end --output ./.maestro/draft.yaml --validate
535
+ sootsim maestro end --output ./.maestro/draft.yaml --video
536
+ sootsim maestro validate ./.maestro/draft.yaml
537
537
 
538
538
  flow extension:
539
539
  takeScreenshot: hero
540
540
  takeScreenshot:
541
541
  path: marketing/hero
542
542
  withFrame: true
543
- `),process.exit(0));let e=n[0];k.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>n.find((d,y)=>n[y-1]===h),i=n.includes("--profile"),r=n.includes("--headed"),o=n.includes("--new")||r,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",u=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,p=t("--device")?.trim()||"",m=n.includes("--slow")?+(t("--slow")||"500"):0,x=n.includes("--electron"),g=n.includes("--preview"),P=await Qe(t("--preview-origin")),_=t("--preview-public-origin"),dt=n.includes("--preview-open"),Fe=t("--owner")?.trim()||"",Ie=t("--repo")?.trim()||"",H=t("--billing-kind")?.trim()||"";H&&H!=="test_run"&&(console.error(` error: invalid --billing-kind: ${H}`),process.exit(1));let ct=n.flatMap((h,d)=>n[d-1]==="--replace"?["--replace",h]:[]),ut=n.flatMap((h,d)=>n[d-1]==="--remap"?["--remap",h]:[]),A=n.includes("--record")||g,pt=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):A?g?6e3:2e3:0,ht=k.readFileSync(e,"utf8"),{frontmatter:E,steps:R}=fe(ht);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let W=p||E.device||"",z=x||E.electron===!0,ft=E.app===void 0||E.app===null?"":typeof E.app=="number"?String(E.app):E.app,re=await Ct(ft),$e={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless","--headed"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--remap","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver","--billing-kind","--owner","--repo"]},v=ce(n,$e),mt=t("--url")||"";z&&!Ve()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let ke=z?"desktop companion":"bridge",gt=re?` | target: ${re}`:"";console.log(`
544
- sootsim flow \u2014 ${w.basename(e)}
545
- ${R.length} steps | ${ke}${gt}${A?" | recording":""}${i?" | profiling":""}${m?` | ${m}ms delay`:""}
546
- `),g&&Me({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:R.length,mode:ke,electron:z,record:A,profile:i,previewOrigin:P}});let I=mt||re||"",ne=o||z&&v.simIdSource!=="flag",Pe=t("--driver")||"",oe=!1,se=new Set,Ae=!1;if(!I&&!ne&&v.simIdSource==="none"){let h=je(v);try{let d=await h.listSims(),y=d.find(L=>L.isPrimary&&L.readyState==="open"),$=d.find(L=>L.readyState==="open"),U=y??$;U&&(Ae=!0,console.log(` reusing active sim: ${U.id}`))}catch{}finally{h.close()}}if(!I&&!Ae&&(ne||v.simIdSource==="none")){let h=await Nt();h||(console.error(" error: no current sim and no sootsim target found"),await le(),process.exit(1)),I=h}if(I&&W){let h=new URL(await Je(I));h.searchParams.set("device",W),I=h.toString()}if(I){let h=[I];if(h.push(...ct),h.push(...ut),ne&&h.push("--new"),h.push("--no-describe"),v.simIdSource==="flag"&&v.simId&&h.push("--sim",v.simId),Pe&&(h.push("--driver",Pe),oe=!0),n.includes("--headless")&&!r&&h.push("--headless"),await ze(h,{port:v.wsPort,timeoutMs:v.commandTimeoutMs}),oe){let d=de();d&&se.add(d)}}let D=ce(n,$e),K=D.simIdSource==="flag"?D.simId:de()||D.simId,wt=D.simIdSource==="flag"?"flag":K?"saved":"none",F=ue(D.wsPort,{commandTimeoutMs:D.commandTimeoutMs,simId:K,simIdSource:wt}),c,Re=async()=>{if(!W)return!1;let h=await F.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof h=="string"&&h.length>0){let d=new URL(h);d.searchParams.set("device",W),c.setSimRouteHint(d.toString())}return!!await F.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",W]})};if(c=new ee(F,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:u,simId:K,recordingOutputDir:A?a:void 0,recordingFormat:g?"mp4":"webm",billingOriginOverride:g?P:void 0,allowGitHubRecording:g,requireRecordingEntitlement:g,onAfterLaunch:async()=>{await Re()&&await c.waitForTree(12e4),g&&await F.send({type:"evaluate",simId:c.simId,code:`(() => {
543
+ `),process.exit(0));let e=n[0];k.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>n.find((c,y)=>n[y-1]===h),r=n.includes("--profile"),i=n.includes("--headed"),o=n.includes("--new")||i,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",u=n.includes("--no-shell")?"tenant":n.includes("--shell-only")?"shell":void 0,p=t("--device")?.trim()||"",m=n.includes("--slow")?+(t("--slow")||"500"):0,x=n.includes("--electron"),w=n.includes("--preview"),P=await et(t("--preview-origin")),_=t("--preview-public-origin"),dt=n.includes("--preview-open"),Ie=t("--owner")?.trim()||"",$e=t("--repo")?.trim()||"",H=t("--billing-kind")?.trim()||"",ut=w?`maestro:${process.env.GITHUB_RUN_ID?`github:${process.env.GITHUB_RUN_ID}:attempt:${process.env.GITHUB_RUN_ATTEMPT||"1"}:job:${process.env.GITHUB_JOB||"preview"}`:`local:${Ut()}`}:flow:${Ht("sha256").update(g.relative(process.cwd(),g.resolve(e))).digest("hex").slice(0,16)}`:"";H&&H!=="test_run"&&(console.error(` error: invalid --billing-kind: ${H}`),process.exit(1));let pt=n.flatMap((h,c)=>n[c-1]==="--replace"?["--replace",h]:[]),ht=n.flatMap((h,c)=>n[c-1]==="--remap"?["--remap",h]:[]),A=n.includes("--record")||w,ft=n.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):A?w?6e3:2e3:0,mt=k.readFileSync(e,"utf8"),{frontmatter:E,steps:R}=me(mt);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let U=p||E.device||"",K=x||E.electron===!0,gt=E.app===void 0||E.app===null?"":typeof E.app=="number"?String(E.app):E.app,ne=await Wt(gt),ke={stripBooleanFlags:["--record","--profile","--electron","--new","--preview","--preview-open","--headless","--headed"],stripValueFlags:["--out","--device","--slow","--tail-wait","--url","--replace","--remap","--screenshots","--screenshot-paths","--preview-origin","--preview-public-origin","--driver","--billing-kind","--owner","--repo"]},v=ue(n,ke),wt=t("--url")||"";K&&!Je()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let Pe=K?"desktop companion":"bridge",yt=ne?` | target: ${ne}`:"";console.log(`
544
+ sootsim maestro \u2014 ${g.basename(e)}
545
+ ${R.length} steps | ${Pe}${yt}${A?" | recording":""}${r?" | profiling":""}${m?` | ${m}ms delay`:""}
546
+ `),w&&Oe({event:"preview_flow_started",properties:{flowName:g.basename(e),stepCount:R.length,mode:Pe,electron:K,record:A,profile:r,previewOrigin:P}});let I=wt||ne||"",oe=o||K&&v.simIdSource!=="flag",Ae=t("--driver")||"",se=!1,ae=new Set,Re=!1;if(!I&&!oe&&v.simIdSource==="none"){let h=je(v);try{let c=await h.listSims(),y=c.find(L=>L.isPrimary&&L.readyState==="open"),$=c.find(L=>L.readyState==="open"),V=y??$;V&&(Re=!0,console.log(` reusing active sim: ${V.id}`))}catch{}finally{h.close()}}if(!I&&!Re&&(oe||v.simIdSource==="none")){let h=await jt();h||(console.error(" error: no current sim and no sootsim target found"),await ce(),process.exit(1)),I=h}if(I&&U){let h=new URL(await Ge(I));h.searchParams.set("device",U),I=h.toString()}if(I){let h=[I];if(h.push(...pt),h.push(...ht),oe&&h.push("--new"),h.push("--no-describe"),v.simIdSource==="flag"&&v.simId&&h.push("--sim",v.simId),Ae&&(h.push("--driver",Ae),se=!0),n.includes("--headless")&&!i&&h.push("--headless"),await Ke(h,{port:v.wsPort,timeoutMs:v.commandTimeoutMs}),se){let c=de();c&&ae.add(c)}}let D=ue(n,ke),q=D.simIdSource==="flag"?D.simId:de()||D.simId,bt=D.simIdSource==="flag"?"flag":q?"saved":"none",F=pe(D.wsPort,{commandTimeoutMs:D.commandTimeoutMs,simId:q,simIdSource:bt}),d,Me=async()=>{if(!U)return!1;let h=await F.send({type:"evaluate",simId:d.simId,code:"window.location.href"});if(typeof h=="string"&&h.length>0){let c=new URL(h);c.searchParams.set("device",U),d.setSimRouteHint(c.toString())}return!!await F.send({type:"call",simId:d.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",U]})};if(d=new te(F,{screenshotDir:s,flowDir:g.dirname(g.resolve(e)),screenshotPathMode:l,screenshotLayers:u,simId:q,recordingOutputDir:A?a:void 0,recordingFormat:w?"mp4":"webm",billingOriginOverride:w?P:void 0,allowGitHubRecording:w,requireRecordingEntitlement:w,onAfterLaunch:async()=>{await Me()&&await d.waitForTree(12e4),w&&await F.send({type:"evaluate",simId:d.simId,code:`(() => {
547
547
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
548
548
  return r?.start?.() ?? false
549
- })()`})}}),m&&(c.stepDelay=m),c.liveStatus=new te(F,w.basename(e)),c.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),E.env&&typeof E.env=="object")for(let[h,d]of Object.entries(E.env))c.js.putEnv(h,d);let M=null,T=null,B=null,O=null,ae=null,j=0,q=!!R[0]?.launchApp;try{q||await c.waitForTree(12e4),await Re()&&!q&&await c.waitForTree(12e4),g&&!q&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),A&&(q?c.prepareRecording():await c.startRecording()),i&&await c.startProfile(),g&&(await F.send({type:"evaluate",simId:c.simId,code:`(() => {
549
+ })()`})}}),m&&(d.stepDelay=m),d.liveStatus=new re(F,g.basename(e)),d.js.putEnv("MAESTRO_FILENAME",g.basename(e,g.extname(e))),E.env&&typeof E.env=="object")for(let[h,c]of Object.entries(E.env))d.js.putEnv(h,c);let M=null,T=null,B=null,O=null,W=null,le=null,j=0,Y=!!R[0]?.launchApp;try{Y||await d.waitForTree(12e4),await Me()&&!Y&&await d.waitForTree(12e4),w&&!Y&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await d.launchApp({clearState:!0}),A&&(Y?d.prepareRecording():await d.startRecording()),r&&await d.startProfile(),w&&(await F.send({type:"evaluate",simId:d.simId,code:`(() => {
550
550
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
551
551
  return r?.start?.() ?? false
552
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(R),i&&(M=await c.stopProfile()),await c.waitForRecordingTail({maxMs:pt,smart:g}),A&&(T=await c.stopRecording(),B=c.getLastRecordingDurationMs()),g&&(O=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
552
+ })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await d.runFlow(R),r&&(M=await d.stopProfile()),await d.waitForRecordingTail({maxMs:ft,smart:w}),A&&(T=await d.stopRecording(),B=d.getLastRecordingDurationMs()),w&&(O=await F.send({type:"evaluate",simId:d.simId,code:`(() => {
553
553
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
554
554
  return r?.stop?.() ?? []
555
- })()`}),console.log(` captured ${O.length} replay events`));let d=R.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
556
- + completed (${R.length} steps)`),d>0&&console.log(` screenshots: ${d} \u2192 ${s}`),M&&at(M),T&&console.log(` video: ${T}`),console.log()}catch(h){if(i&&!M)try{M=await c.stopProfile()}catch{}if(A&&!T)try{T=await c.stopRecording(),B=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}if(g&&!O)try{O=await F.send({type:"evaluate",simId:c.simId,code:`(() => {
555
+ })()`}),console.log(` captured ${O.length} replay events`),W=g.join(s,"preview-final.png"),await d.captureScreenshot(W),console.log(` final screenshot: ${W}`));let c=R.filter(y=>y&&typeof y=="object"&&"takeScreenshot"in y).length;console.log(`
556
+ + completed (${R.length} steps)`),c>0&&console.log(` screenshots: ${c} \u2192 ${s}`),M&&lt(M),T&&console.log(` video: ${T}`),console.log()}catch(h){if(r&&!M)try{M=await d.stopProfile()}catch{}if(A&&!T)try{T=await d.stopRecording(),B=d.getLastRecordingDurationMs()}catch(c){console.warn(` recording stop failed: ${c?.message||String(c)}`)}if(w&&!O)try{O=await F.send({type:"evaluate",simId:d.simId,code:`(() => {
557
557
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
558
558
  return r?.stop?.() ?? []
559
- })()`}),console.log(` captured ${O.length} partial replay events`)}catch(d){console.warn(` event recorder stop failed: ${d?.message||String(d)}`)}console.error(`
559
+ })()`}),console.log(` captured ${O.length} partial replay events`)}catch(c){console.warn(` event recorder stop failed: ${c?.message||String(c)}`)}console.error(`
560
560
  x failed: ${h.message}
561
- `),M&&(console.log(" partial profile:"),at(M)),T&&console.log(` partial video: ${T}`);try{let d=c.lastFailedStep,y=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",$=w.join(s,y);await c.captureFailureBundle($,{error:h,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),ae=$,console.log(` failure bundle: ${$}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(d){try{let y=w.join(s,"error.png");await c.captureFailureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await Ue(F,{errorsCommand:`sootsim get errors 5${c.simId?` --sim ${c.simId}`:""}`,warningsCommand:`sootsim get warnings 5${c.simId?` --sim ${c.simId}`:""}`,requestsCommand:`sootsim get requests 5${c.simId?` --sim ${c.simId}`:""}`}),j=1}if(await c.liveStatus?.end(j===0?"passed":"failed"),g&&(j===0||T||O))try{let h=await Wt(O??[]),d=["--origin",P,"--events",h];_&&d.push("--public-origin",_),T&&d.push("--video",T),T&&B&&Number.isFinite(B)&&(d.push("--video-duration-ms",String(Math.round(B))),d.push("--recorded-duration-ms",String(Math.round(B))));let y=c.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&d.push("--recording-started-at-ms",String(Math.round(y))),v.wsPort&&d.push("--port",String(v.wsPort)),c.simId&&d.push("--sim",c.simId),dt&&d.push("--open"),Fe&&d.push("--owner",Fe),Ie&&d.push("--repo",Ie),H&&d.push("--billing-kind",H),console.log(`
562
- preparing preview upload\u2026`);let $=c.getFlowTraceSteps();$.length>0&&d.push("--timeline-events",await jt($)),ae&&d.push("--failure-bundle",ae);let U=c.getLastRecordingFrameStats();U&&d.push("--trace-frame-stats",await Ut(U));let{runUpload:L}=await import("./upload-T6F6NRSY.js");Te=await L(d,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),j=1}return Ee=c.getFlowTraceSteps(),F.close(),oe?(c.simId&&se.add(c.simId),await Ht(v.wsPort,v.commandTimeoutMs,[...se])):c.simId&&c.simId!==K&&De(c.simId),await le(),j}async function Ht(n,e,t){let i=[...new Set(t.filter(Boolean))];if(i.length===0)return;let r=ue(n,{commandTimeoutMs:e});try{let o=await r.listSims(),a=i.filter(l=>o.some(u=>u.id===l&&u.readyState==="open"));if(a.length===0)return;let s=await Ke(r,n,e,a);await Ge(o,a),s.closed.length>0&&console.log(` closed flow sim(s): ${s.closed.join(", ")}`),s.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${s.remaining.join(", ")}`)}catch(o){console.warn(` warn: failed to close flow sim(s): ${o instanceof Error?o.message:String(o)}`)}finally{r.close()}}async function Wt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
561
+ `),M&&(console.log(" partial profile:"),lt(M)),T&&console.log(` partial video: ${T}`);try{let c=d.lastFailedStep,y=c?`step-${String(c.index+1).padStart(2,"0")}-${c.kind}`:"unstaged",$=g.join(s,y);await d.captureFailureBundle($,{error:h,stepIndex:c?.index,stepKind:c?.kind,stepTarget:c?.target}),le=$,console.log(` failure bundle: ${$}`),console.log(" (contents: screenshot.png, describe.json, a11y.txt, tree.txt, console.json, error.json)")}catch(c){try{let y=g.join(s,"error.png");await d.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${c instanceof Error?c.message:String(c)})`)}await Ve(F,{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}`:""}`}),j=1}if(await d.liveStatus?.end(j===0?"passed":"failed"),w&&(j===0||T||O))try{let h=await Jt(O??[]),c=["--origin",P,"--events",h];_&&c.push("--public-origin",_),T&&c.push("--video",T),W&&c.push("--screenshot",W),T&&B&&Number.isFinite(B)&&(c.push("--video-duration-ms",String(Math.round(B))),c.push("--recorded-duration-ms",String(Math.round(B))));let y=d.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&c.push("--recording-started-at-ms",String(Math.round(y))),v.wsPort&&c.push("--port",String(v.wsPort)),d.simId&&c.push("--sim",d.simId),dt&&c.push("--open"),Ie&&c.push("--owner",Ie),$e&&c.push("--repo",$e),c.push("--run-scope",ut),H&&c.push("--billing-kind",H),console.log(`
562
+ preparing preview upload\u2026`);let $=d.getFlowTraceSteps();$.length>0&&c.push("--timeline-events",await Gt($)),le&&c.push("--failure-bundle",le);let V=d.getLastRecordingFrameStats();V&&c.push("--trace-frame-stats",await zt(V));let{runUpload:L}=await import("./upload-RNDBU5AE.js");Ee=await L(c,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),j=1}return Fe=d.getFlowTraceSteps(),F.close(),se?(d.simId&&ae.add(d.simId),await Vt(v.wsPort,v.commandTimeoutMs,[...ae])):d.simId&&d.simId!==q&&Be(d.simId),await ce(),j}async function Vt(n,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let i=pe(n,{commandTimeoutMs:e});try{let o=await i.listSims(),a=r.filter(l=>o.some(u=>u.id===l&&u.readyState==="open"));if(a.length===0)return;let s=await qe(i,n,e,a);await ze(o,a),s.closed.length>0&&console.log(` closed flow sim(s): ${s.closed.join(", ")}`),s.remaining.length>0&&console.warn(` warn: flow sim(s) still connected after close: ${s.remaining.join(", ")}`)}catch(o){console.warn(` warn: failed to close flow sim(s): ${o instanceof Error?o.message:String(o)}`)}finally{i.close()}}async function Jt(n){let{gzipSync:e}=await import("zlib"),t=n.map(o=>JSON.stringify(o)).join(`
563
563
  `)+(n.length?`
564
- `:""),i=e(Buffer.from(t,"utf8")),r=w.join(ie(),`sootsim-events-${Date.now()}.jsonl.gz`);return k.writeFileSync(r,i),console.log(` events: ${n.length} written to ${r} (${i.length} bytes gz)`),r}async function jt(n){let{gzipSync:e}=await import("zlib"),t=n.map((a,s)=>({schemaVersion:1,t:a.endedAtMs,seq:1e6+s,context:"host",kind:"flow-step",id:`flow-step-${a.stepIndex}`,data:{stepIndex:a.stepIndex,stepNumber:a.stepIndex+1,stepName:a.stepName,...a.targetLabel?{targetLabel:a.targetLabel}:{},status:a.status,durationMs:a.durationMs,startedAtMs:a.startedAtMs,endedAtMs:a.endedAtMs,...a.error?{error:a.error}:{}}})),i=t.map(a=>JSON.stringify(a)).join(`
564
+ `:""),r=e(Buffer.from(t,"utf8")),i=g.join(ie(),`sootsim-events-${Date.now()}.jsonl.gz`);return k.writeFileSync(i,r),console.log(` events: ${n.length} written to ${i} (${r.length} bytes gz)`),i}async function Gt(n){let{gzipSync:e}=await import("zlib"),t=n.map((a,s)=>({schemaVersion:1,t:a.endedAtMs,seq:1e6+s,context:"host",kind:"flow-step",id:`flow-step-${a.stepIndex}`,data:{stepIndex:a.stepIndex,stepNumber:a.stepIndex+1,stepName:a.stepName,...a.targetLabel?{targetLabel:a.targetLabel}:{},status:a.status,durationMs:a.durationMs,startedAtMs:a.startedAtMs,endedAtMs:a.endedAtMs,...a.error?{error:a.error}:{}}})),r=t.map(a=>JSON.stringify(a)).join(`
565
565
  `)+`
566
- `,r=e(Buffer.from(i,"utf8")),o=w.join(ie(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return k.writeFileSync(o,r),console.log(` flow trace: ${t.length} step events written to ${o} (${r.length} bytes gz)`),o}async function Ut(n){let e=w.join(ie(),`sootsim-frame-stats-${Date.now()}.json`);return k.writeFileSync(e,JSON.stringify(n)),console.log(` frame stats: written to ${e}`),e}async function Vt(n){let e=n[0],t=i=>n.find((r,o)=>n[o-1]===i);switch(e){case"start":{let{path:i,state:r}=Ye();console.log(" flow draft started"),console.log(` session: ${i}`),console.log(` steps: ${r.steps.length}`);return}case"keep":case"good":{let i=we();if(i.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!i.kept){console.log(" no pending action to keep");return}console.log(` kept: ${i.candidate.summary}`),console.log(` steps: ${i.stepCount}`);return}case"end":{let i=t("--output")||(n[1]&&!n[1].startsWith("-")?n[1]:void 0),r=n.includes("--validate")||n.includes("--video"),o=n.includes("--video"),a=we();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=Ze(i||(r?Gt():void 0));if(s.active||(console.error(" no active flow draft \u2014 run `sootsim flow start` first"),process.exit(1)),!s.valid){console.error(" flow draft is not valid:");for(let l of s.issues)console.error(` - ${l}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim flow start` to reset"),process.exit(1)}if(r){let l=zt(n,s.outputPath),u=await lt(l);if(u!==0){console.error(`
567
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}ge(),console.log(` flow draft validated (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath&&console.log(` saved: ${s.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(ge(),console.log(` flow draft ended (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath){console.log(` saved: ${s.outputPath}`),console.log(` next: sootsim flow ${s.outputPath} --record`);return}console.log(""),process.stdout.write(s.yaml);return}case"validate":{let i=n[1];(!i||i.startsWith("-"))&&(console.error(" usage: sootsim flow validate <path>"),process.exit(1));let r=me(i);if(r.length>0){console.error(` x ${i} failed validation:`);for(let o of r)console.error(` - ${o}`);process.exit(1)}console.log(` + ${i} looks valid`);return}}}function Jt(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function ki(n){let e=Jt(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Vt(e),0;let i=await lt(e);return i!==0&&(process.exitCode=i),i}function at(n){console.log(""),Xe(n)}function Gt(){return w.join(ie(),`sootsim-flow-draft-${Date.now()}.yaml`)}function zt(n,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let i=1;i<n.length;i++){let r=n[i];if(!(r==="--validate"||r==="--video")){if(r==="--output"){i+=1;continue}i===1&&!r.startsWith("-")||t.push(r)}}return!t.includes("--record")&&n.includes("--video")&&t.push("--record"),t}export{rt as a,Ft as b,Ii as c,$i as d,Nt as e,lt as f,Jt as g,ki as h};
566
+ `,i=e(Buffer.from(r,"utf8")),o=g.join(ie(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return k.writeFileSync(o,i),console.log(` flow trace: ${t.length} step events written to ${o} (${i.length} bytes gz)`),o}async function zt(n){let e=g.join(ie(),`sootsim-frame-stats-${Date.now()}.json`);return k.writeFileSync(e,JSON.stringify(n)),console.log(` frame stats: written to ${e}`),e}async function Kt(n){let e=n[0],t=r=>n.find((i,o)=>n[o-1]===r);switch(e){case"start":{let{path:r,state:i}=Ze();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${i.steps.length}`);return}case"keep":case"good":{let r=ye();if(r.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),process.exit(1)),!r.kept){console.log(" no pending action to keep");return}console.log(` kept: ${r.candidate.summary}`),console.log(` steps: ${r.stepCount}`);return}case"end":{let r=t("--output")||(n[1]&&!n[1].startsWith("-")?n[1]:void 0),i=n.includes("--validate")||n.includes("--video"),o=n.includes("--video"),a=ye();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=Xe(r||(i?Yt():void 0));if(s.active||(console.error(" no active flow draft \u2014 run `sootsim maestro start` first"),process.exit(1)),!s.valid){console.error(" flow draft is not valid:");for(let l of s.issues)console.error(` - ${l}`);console.error(" draft preserved \u2014 keep at least one real interaction or run `sootsim maestro start` to reset"),process.exit(1)}if(i){let l=Zt(n,s.outputPath),u=await ct(l);if(u!==0){console.error(`
567
+ validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=u;return}we(),console.log(` flow draft validated (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath&&console.log(` saved: ${s.outputPath}`),o&&console.log(" video: recorded during validation run");return}if(we(),console.log(` flow draft ended (${s.stepCount} step${s.stepCount===1?"":"s"})`),s.outputPath){console.log(` saved: ${s.outputPath}`),console.log(` next: sootsim maestro test ${s.outputPath} --record`);return}console.log(""),process.stdout.write(s.yaml);return}case"validate":{let r=n[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim maestro validate <path>"),process.exit(1));let i=ge(r);if(i.length>0){console.error(` x ${r} failed validation:`);for(let o of i)console.error(` - ${o}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function qt(n){return n[0]==="--sim"&&n.length>=2?[...n.slice(2),"--sim",n[1]]:n}async function Or(n){let e=qt(n),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await Kt(e),0;let r=await ct(e);return r!==0&&(process.exitCode=r),r}function lt(n){console.log(""),Qe(n)}function Yt(){return g.join(ie(),`sootsim-flow-draft-${Date.now()}.yaml`)}function Zt(n,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<n.length;r++){let i=n[r];if(!(i==="--validate"||i==="--video")){if(i==="--output"){r+=1;continue}r===1&&!i.startsWith("-")||t.push(i)}}return!t.includes("--record")&&n.includes("--video")&&t.push("--record"),t}export{nt as a,$t as b,Rr as c,Mr as d,jt as e,ct as f,qt as g,Or as h};
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.210 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as p}from"./chunk-VAMOANYW.js";import{a as c,b as l}from"./chunk-PIONEQXI.js";import{a}from"./chunk-GCW2PJGE.js";async function g(e,t){if(t)return t.replace(/\/$/,"");if(e.kind==="session"&&e.origin)return e.origin.replace(/\/$/,"");let i=a();return i?.origin?i.origin.replace(/\/$/,""):(await p()).replace(/\/$/,"")}async function m(e,t={}){let i=c();if(i||(process.stderr.write(`
1
+ /*! sootsim v0.1.212 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as p}from"./chunk-OHRSRPEB.js";import{a as c,b as l}from"./chunk-YNEFNAKF.js";import{a}from"./chunk-O7K44ZT6.js";async function g(e,t){if(t)return t.replace(/\/$/,"");if(e.kind==="session"&&e.origin)return e.origin.replace(/\/$/,"");let i=a();return i?.origin?i.origin.replace(/\/$/,""):(await p()).replace(/\/$/,"")}async function m(e,t={}){let i=c();if(i||(process.stderr.write(`
3
3
  sootsim ${e} needs auth before it can check recording access.
4
4
 
5
5
  pick one:
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.210 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! sootsim v0.1.212 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import{existsSync as A,mkdirSync as v,readFileSync as M,rmSync as f,writeFileSync as h}from"fs";import{tmpdir as w}from"os";import{dirname as B,join as U,resolve as V}from"path";import{execFileSync as b}from"child_process";import{readFileSync as _}from"fs";import{createRequire as y}from"module";var c=null,p=null;function m(r){c||(c=O());try{return c(r)}catch{return null}}function C(r){p||(p=T());try{return p(r)}catch{return null}}function T(){if(process.platform==="linux")return r=>{try{return _(`/proc/${r}/comm`,"utf8").trim()||null}catch{return null}};if(process.platform==="darwin"){let r=x();return r||F()}return()=>null}function O(){let r=Number(process.env.PPID);if(Number.isFinite(r)&&r>1&&r!==process.ppid)return()=>r;if(process.platform==="linux")return D();if(process.platform==="darwin"){let n=R();return n||k()}return()=>null}function D(){return r=>{try{let n=_(`/proc/${r}/stat`,"utf8"),t=n.lastIndexOf(")");if(t<0)return null;let e=n.slice(t+1).trim().split(/\s+/),i=Number(e[1]);return Number.isFinite(i)&&i>0?i:null}catch{return null}}}var E=3,l=216,P=16,S=48,L=16;function R(){if(!process.versions?.bun)return null;try{let r=y(import.meta.url),{dlopen:n,FFIType:t}=r("bun:ffi"),e=n("/usr/lib/libproc.dylib",{proc_pidinfo:{args:[t.i32,t.i32,t.u64,t.ptr,t.i32],returns:t.i32}}),i=Buffer.alloc(l);return o=>{if(Number(e.symbols.proc_pidinfo(o,E,0n,i,l))<=0)return null;let u=i.readUInt32LE(P);return u>0?u:null}}catch{return null}}function x(){if(!process.versions?.bun)return null;try{let r=y(import.meta.url),{dlopen:n,FFIType:t}=r("bun:ffi"),e=n("/usr/lib/libproc.dylib",{proc_pidinfo:{args:[t.i32,t.i32,t.u64,t.ptr,t.i32],returns:t.i32}}),i=Buffer.alloc(l);return o=>{if(Number(e.symbols.proc_pidinfo(o,E,0n,i,l))<=0)return null;let u=i.subarray(S,S+L),I=u.indexOf(0);return u.subarray(0,I<0?u.length:I).toString("utf8")||null}}catch{return null}}function F(){return r=>{try{let t=b("lsof",["-R","-p",String(r),"-d","cwd","-a"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).split(`
3
3
  `)[1];return t&&t.trim().split(/\s+/)[0]||null}catch{return null}}}function k(){return r=>{try{let t=b("lsof",["-R","-p",String(r),"-d","cwd","-a"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).split(`
4
4
  `)[1];if(!t)return null;let e=t.trim().split(/\s+/),i=Number(e[2]);return Number.isFinite(i)&&i>1?i:null}catch{return null}}}var d=1,N="SOOTSIM_CLI_CURRENT_SIM_PATH",W=["SOOTSIM_CLI_IDENTITY","AGENTBUS_SESSION","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","TERM_SESSION_ID","ITERM_SESSION_ID","TMUX_PANE","STY","KITTY_WINDOW_ID","WEZTERM_PANE","ALACRITTY_WINDOW_ID","WINDOWID","VSCODE_INJECTION"],$=/^(tmux|screen)/i;function g(r,n=20){let t=r,e=m(r);if(!e||e<=1)return null;for(let i=0;i<n;i++){let o=C(e);if(o&&$.test(o))return t;let s=m(e);if(!s||s<=1)return e;t=e,e=s}return e}function Y(){for(let n of W){let t=process.env[n];if(t&&t.trim())return{key:`${n}:${t.trim()}`,source:n,stable:!0}}let r=g(process.ppid);return r&&r>1?{key:`gppid-${r}`,source:"grand-ppid",stable:!0}:{key:`pid-${process.ppid}`,source:"ppid",stable:!1}}function H(){return Y().key}function tr(){return g(process.ppid)}function a(){if(process.env[N])return V(process.env[N]);let r=H();return U(w(),`sootsim-current-sim-${r}.json`)}function J(){let r=a();if(!A(r))return null;try{let n=JSON.parse(M(r,"utf8"));return n.version!==d||typeof n.simId!="string"||!n.simId.trim()||typeof n.updatedAt!="string"?(f(r,{force:!0}),null):{version:d,simId:n.simId.trim(),updatedAt:n.updatedAt}}catch{return f(r,{force:!0}),null}}function nr(){return J()?.simId||null}function er(r){let n=r.trim();if(!n)return;let t=a();v(B(t),{recursive:!0}),h(t,JSON.stringify({version:d,simId:n,updatedAt:new Date().toISOString()},null,2)+`
@@ -1,4 +1,4 @@
1
- /*! sootsim v0.1.210 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! sootsim v0.1.212 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
2
  import{randomUUID as I}from"node:crypto";import r from"node:fs";import{homedir as E}from"node:os";import o from"node:path";var _="SOOTSIM_HOME",P="active",j="daemon.json",F="dev-bridge.json",w="config.json",L=3e4;function u(){let e=process.env[_];return e&&e.length>0?o.resolve(e):o.join(E(),".sootsim")}function R(){if(process.env.SOOTSIM_FORCE_DAEMON_INSTALL==="1")return!1;let e=process.env.SOOTSIM_DEV;if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;let t=process.argv[1];if(!t)return!1;try{return r.realpathSync(t).includes(`${o.sep}packages${o.sep}sootsim${o.sep}`)}catch{return!1}}function T(){return process.env.SOOTSIM_FORCE_DAEMON_INSTALL==="1"?!1:process.env.IS_TAMAGUI_DEV==="1"}function z(){return R()||T()}function f(){return o.join(u(),"runtimes")}function B(e){return o.join(f(),e)}function O(){return o.join(f(),P)}function D(){return o.join(u(),"electron")}function Q(){return o.join(D(),"userData")}function Z(e){return o.join(D(),e)}function C(){return o.join(u(),"profiles")}function M(){return o.join(u(),"daemon-app")}function $(){return o.join(M(),"SootSim Daemon.app")}function ee(){return o.join($(),"Contents","MacOS","sootsim-daemon")}function U(){return o.join(u(),"cache")}function m(){return o.join(u(),j)}function d(){return o.join(u(),F)}function x(){return o.join(u(),w)}function h(){try{let e=r.readFileSync(x(),"utf8"),t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function N(e){l();let t=h(),i={...t,...e};e.settings&&typeof e.settings=="object"&&(i.settings={...t.settings&&typeof t.settings=="object"?t.settings:{},...e.settings});let c=`${x()}.tmp`;return r.writeFileSync(c,`${JSON.stringify(i,null,2)}
3
3
  `,"utf8"),r.renameSync(c,x()),i}function te(){return h().telemetry!==!1}function re(){let e=h().anonymousId;if(typeof e=="string"&&e.trim())return e;let t=`anon-cli-${I()}`;return N({anonymousId:t}),t}function ne(e){N({telemetry:e})}function g(){return o.join(u(),"runtime-upgraded.json")}function oe(e){l();let t=`${g()}.tmp`;r.writeFileSync(t,`${JSON.stringify(e)}
4
4
  `,"utf8"),r.renameSync(t,g())}function ie(){try{let e=r.readFileSync(g(),"utf8");r.unlinkSync(g());let t=JSON.parse(e);return typeof t?.to!="string"||!t.to?null:{from:typeof t.from=="string"?t.from:null,to:t.to,at:typeof t.at=="number"?t.at:0}}catch{return null}}function l(){r.mkdirSync(u(),{recursive:!0}),r.mkdirSync(f(),{recursive:!0}),r.mkdirSync(D(),{recursive:!0}),r.mkdirSync(C(),{recursive:!0}),r.mkdirSync(U(),{recursive:!0})}function J(){try{let e=r.readFileSync(O(),"utf8").trim();return e.length>0?e:null}catch{return null}}function se(e){r.mkdirSync(f(),{recursive:!0}),r.writeFileSync(O(),`${e}
@@ -1,5 +1,5 @@
1
- /*! sootsim v0.1.210 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as R,b as U}from"./chunk-P6L7NTH2.js";import{c as F}from"./chunk-VMRT3K3M.js";import{g as N,j as E,r as _,s as v,t as B}from"./chunk-KWAAJUF2.js";import{a as O}from"./chunk-SVLKYHDO.js";import{execFileSync as W,spawnSync as s}from"child_process";import{existsSync as a,mkdirSync as x,readFileSync as nt,realpathSync as ot,rmSync as $,writeFileSync as H}from"fs";import{homedir as P}from"os";import{basename as st,dirname as T,resolve as f,sep as Y}from"path";import{execFileSync as X}from"child_process";import{chmodSync as Q,mkdirSync as I,rmSync as z,writeFileSync as A}from"fs";import{dirname as L}from"path";var J="dev.sootsim.daemon",j="SootSim Daemon",M="0.1.36";function V(t,e,r){let n=v(),o=B(),c=L(L(o)),l=L(o),u=`${c}/Resources`;z(n,{recursive:!0,force:!0}),I(_(),{recursive:!0}),I(l,{recursive:!0}),I(u,{recursive:!0}),A(`${c}/Info.plist`,Z()),A(`${c}/PkgInfo`,"APPL????"),A(o,tt(t,e,r)),Q(o,493);try{X("codesign",["--force","--sign","-","--deep",n],{stdio:"pipe"})}catch(i){let p=i instanceof Error?i.message:String(i);console.warn(` warning: ad-hoc codesign of ${n} failed: ${p}
1
+ /*! sootsim v0.1.212 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import{a as R,b as U}from"./chunk-7SYXBGM2.js";import{c as F}from"./chunk-WLFIL6JU.js";import{g as N,j as E,r as _,s as v,t as B}from"./chunk-ERG3QCK4.js";import{a as O}from"./chunk-YFXU4HRJ.js";import{execFileSync as W,spawnSync as s}from"child_process";import{existsSync as a,mkdirSync as x,readFileSync as nt,realpathSync as ot,rmSync as $,writeFileSync as H}from"fs";import{homedir as P}from"os";import{basename as st,dirname as T,resolve as f,sep as Y}from"path";import{execFileSync as X}from"child_process";import{chmodSync as Q,mkdirSync as I,rmSync as z,writeFileSync as A}from"fs";import{dirname as L}from"path";var J="dev.sootsim.daemon",j="SootSim Daemon",M="0.1.36";function V(t,e,r){let n=v(),o=B(),c=L(L(o)),l=L(o),u=`${c}/Resources`;z(n,{recursive:!0,force:!0}),I(_(),{recursive:!0}),I(l,{recursive:!0}),I(u,{recursive:!0}),A(`${c}/Info.plist`,Z()),A(`${c}/PkgInfo`,"APPL????"),A(o,tt(t,e,r)),Q(o,493);try{X("codesign",["--force","--sign","-","--deep",n],{stdio:"pipe"})}catch(i){let p=i instanceof Error?i.message:String(i);console.warn(` warning: ad-hoc codesign of ${n} failed: ${p}
3
3
  the daemon will still run, but Login Items may show a generic name.`)}return{bundlePath:n,launcherPath:o}}function Z(){return`<?xml version="1.0" encoding="UTF-8"?>
4
4
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5
5
  <plist version="1.0">