sootsim 0.1.293 → 0.1.294

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 (165) hide show
  1. package/detox/expectations.ts +4 -3
  2. package/detox/index.ts +2 -4
  3. package/dist-cli/bin.js +7 -5
  4. package/dist-cli/chunks/{agent-YWI2NWL7.js → agent-GDFF6G7N.js} +4 -2
  5. package/dist-cli/chunks/{agent-wrapper-IYJ7UZOA.js → agent-wrapper-ZUKQUOD2.js} +4 -2
  6. package/dist-cli/chunks/{app-fonts-FQFUC4LR.js → app-fonts-IMYBO6AQ.js} +4 -2
  7. package/dist-cli/chunks/{assert-XUCELWAC.js → assert-GXOGZUKO.js} +4 -2
  8. package/dist-cli/chunks/{auth-4DQTV3OW.js → auth-P7FAKLHQ.js} +4 -2
  9. package/dist-cli/chunks/beta-RXT5RU3A.js +4 -0
  10. package/dist-cli/chunks/{camera-RYOHBVZA.js → camera-RNVAC4IO.js} +4 -2
  11. package/dist-cli/chunks/{chunk-2XYCSFGN.js → chunk-24BJFJFB.js} +26 -24
  12. package/dist-cli/chunks/{chunk-WVMYRKSS.js → chunk-2M7OZ6Y4.js} +4 -2
  13. package/dist-cli/chunks/chunk-37ZXWXM3.js +4 -0
  14. package/dist-cli/chunks/{chunk-UOHGYYSO.js → chunk-3F2GAJ4Z.js} +3 -1
  15. package/dist-cli/chunks/{chunk-KC5SCOGS.js → chunk-4Z4URZOG.js} +4 -2
  16. package/dist-cli/chunks/{chunk-LOQLZFRK.js → chunk-5S3GPTX7.js} +4 -2
  17. package/dist-cli/chunks/chunk-6YN3IAWJ.js +4 -0
  18. package/dist-cli/chunks/{chunk-YRFWATLA.js → chunk-7HVMAGDK.js} +4 -2
  19. package/dist-cli/chunks/{chunk-4B4VFT73.js → chunk-7Q77LTPT.js} +7 -5
  20. package/dist-cli/chunks/{chunk-RKXHQ2Q3.js → chunk-AFLGWOX3.js} +18 -16
  21. package/dist-cli/chunks/{chunk-LA5DIO33.js → chunk-AMKQUZA2.js} +3 -1
  22. package/dist-cli/chunks/{chunk-TJS5IMOH.js → chunk-AO65WEF7.js} +3 -1
  23. package/dist-cli/chunks/{chunk-BQT5YDTV.js → chunk-BBVBMGTT.js} +5 -3
  24. package/dist-cli/chunks/{chunk-WPPMUUML.js → chunk-BXO2PTNM.js} +4 -2
  25. package/dist-cli/chunks/{chunk-2VKTOZQ5.js → chunk-CTMPC5DN.js} +4 -2
  26. package/dist-cli/chunks/{chunk-RV67J726.js → chunk-D2R7PDN5.js} +3 -1
  27. package/dist-cli/chunks/{chunk-RMLJXP7T.js → chunk-DI55E6CS.js} +4 -2
  28. package/dist-cli/chunks/chunk-DUHBRW7J.js +4 -0
  29. package/dist-cli/chunks/chunk-EXTV6NWM.js +74 -0
  30. package/dist-cli/chunks/{chunk-6IFJLHDA.js → chunk-FNCSUHUR.js} +3 -1
  31. package/dist-cli/chunks/{chunk-DE4ZA3NL.js → chunk-FSRRJGYC.js} +4 -2
  32. package/dist-cli/chunks/{chunk-UPKYK52K.js → chunk-I233T2T4.js} +4 -2
  33. package/dist-cli/chunks/{chunk-E5WYXRGV.js → chunk-ISJ4ACWL.js} +28 -26
  34. package/dist-cli/chunks/{chunk-AFRXWKTA.js → chunk-JFWEDISV.js} +3 -1
  35. package/dist-cli/chunks/chunk-JGGXQHXH.js +10 -0
  36. package/dist-cli/chunks/chunk-JUOQ4ZPA.js +7 -0
  37. package/dist-cli/chunks/{chunk-2M57EAWS.js → chunk-K53YCAQM.js} +3 -1
  38. package/dist-cli/chunks/{chunk-7B6RGFTM.js → chunk-KWIURH7N.js} +4 -2
  39. package/dist-cli/chunks/{chunk-VO74GDXL.js → chunk-N4MT5KEB.js} +5 -3
  40. package/dist-cli/chunks/{chunk-VZ44FQDG.js → chunk-O6I5ZGMY.js} +3 -1
  41. package/dist-cli/chunks/chunk-OKSGM6IG.js +4 -0
  42. package/dist-cli/chunks/chunk-OYYQQBKP.js +3 -0
  43. package/dist-cli/chunks/{chunk-NCCMRFXU.js → chunk-PSOUSJSZ.js} +3 -1
  44. package/dist-cli/chunks/{chunk-J6P2UPXH.js → chunk-PZTKQG6H.js} +4 -2
  45. package/dist-cli/chunks/{chunk-B7TX4WFB.js → chunk-RWUNC66S.js} +4 -2
  46. package/dist-cli/chunks/{chunk-547W23BB.js → chunk-SLMUW2WU.js} +4 -2
  47. package/dist-cli/chunks/{chunk-WI36YJ23.js → chunk-SPQKJDIK.js} +3 -1
  48. package/dist-cli/chunks/{chunk-PCAPHXN3.js → chunk-V2MYTL4C.js} +4 -2
  49. package/dist-cli/chunks/{chunk-JOPKZVOW.js → chunk-VVVORIQI.js} +3 -1
  50. package/dist-cli/chunks/chunk-VXGCZUX4.js +5 -0
  51. package/dist-cli/chunks/chunk-W44PDEQH.js +4 -0
  52. package/dist-cli/chunks/{chunk-WOWLO4LL.js → chunk-WQL3BLFD.js} +3 -1
  53. package/dist-cli/chunks/{chunk-U3564F2Y.js → chunk-WYRLRNIP.js} +4 -2
  54. package/dist-cli/chunks/{chunk-WP3TFHFL.js → chunk-XYFP466E.js} +4 -2
  55. package/dist-cli/chunks/chunk-ZFMJFX27.js +4 -0
  56. package/dist-cli/chunks/{chunk-67CIS55C.js → chunk-ZUX5PIGI.js} +3 -1
  57. package/dist-cli/chunks/{cleanup-BLFDJSFS.js → cleanup-74SKOD2P.js} +4 -2
  58. package/dist-cli/chunks/cli-version-2JGMYL4O.js +4 -0
  59. package/dist-cli/chunks/{compat-Q3WCSTB7.js → compat-ME6HXEEU.js} +5 -3
  60. package/dist-cli/chunks/{config-NHNMRRNB.js → config-PM67EWT3.js} +4 -2
  61. package/dist-cli/chunks/control-HV7GZXAH.js +4 -0
  62. package/dist-cli/chunks/daemon-LKRHF5OK.js +4 -0
  63. package/dist-cli/chunks/{debug-PGRMZFXA.js → debug-XUGWZLIW.js} +5 -3
  64. package/dist-cli/chunks/{desktop-NVTQ37LH.js → desktop-IO5HPX5Z.js} +5 -3
  65. package/dist-cli/chunks/{detox-W3JDXS76.js → detox-E42OEJJZ.js} +4 -2
  66. package/dist-cli/chunks/{device-KQYN3EVK.js → device-XA67L2EB.js} +4 -2
  67. package/dist-cli/chunks/{diagnose-CPUKSGNO.js → diagnose-36FD6ECF.js} +4 -2
  68. package/dist-cli/chunks/disk-cleanup-DDCFGFWK.js +4 -0
  69. package/dist-cli/chunks/drivers-C2SH3DWS.js +4 -0
  70. package/dist-cli/chunks/{film-VZGAZ2YY.js → film-XARTGFIZ.js} +11 -24
  71. package/dist-cli/chunks/flow-E64G5LF3.js +4 -0
  72. package/dist-cli/chunks/help-4ZSRG4F4.js +4 -0
  73. package/dist-cli/chunks/{hidden-runtime-alias-KWHABCNZ.js → hidden-runtime-alias-T4ZALBE2.js} +4 -2
  74. package/dist-cli/chunks/{home-paths-O4CGYVHF.js → home-paths-5L7N2FLS.js} +4 -2
  75. package/dist-cli/chunks/inspect-U2SV25ER.js +4 -0
  76. package/dist-cli/chunks/install-desktop-LTGVT7ID.js +4 -0
  77. package/dist-cli/chunks/{login-KPN4Z26Q.js → login-GF6WVVER.js} +6 -4
  78. package/dist-cli/chunks/logout-6F6UKUNI.js +4 -0
  79. package/dist-cli/chunks/{maestro-PYA4AHTS.js → maestro-FMPKHEMX.js} +13 -11
  80. package/dist-cli/chunks/{maestro-generate-KCMYWPWL.js → maestro-generate-QGPGNXI6.js} +5 -3
  81. package/dist-cli/chunks/{mode-AEB7G2SJ.js → mode-JSNMAHDZ.js} +4 -2
  82. package/dist-cli/chunks/optional-demo-registry-K4VERLJV.js +4 -0
  83. package/dist-cli/chunks/{perf-YLXGZI3E.js → perf-PO7ARUTG.js} +4 -2
  84. package/dist-cli/chunks/{permissions-7VMVZOUV.js → permissions-XI2QUAEZ.js} +4 -2
  85. package/dist-cli/chunks/{record-AVQO45PE.js → record-4CJCJAFD.js} +5 -3
  86. package/dist-cli/chunks/runtime-SN2RWDES.js +4 -0
  87. package/dist-cli/chunks/{screenshot-command-LACQLA4N.js → screenshot-command-NDVULWMZ.js} +5 -3
  88. package/dist-cli/chunks/{screenshots-capture-PROOBSGB.js → screenshots-capture-Q7UTXF3V.js} +4 -2
  89. package/dist-cli/chunks/{serve-FJN2FRGW.js → serve-UEUIBHCK.js} +4 -2
  90. package/dist-cli/chunks/{setup-IVV4NRYQ.js → setup-ZEEWYK4B.js} +5 -3
  91. package/dist-cli/chunks/{skills-WYR3PJOH.js → skills-NFG6VAO5.js} +4 -2
  92. package/dist-cli/chunks/{storage-GM7K4MGM.js → storage-POWCOUCQ.js} +4 -2
  93. package/dist-cli/chunks/store-BJK7V7FL.js +4 -0
  94. package/dist-cli/chunks/telemetry-EJP5EW7K.js +4 -0
  95. package/dist-cli/chunks/{timeline-R5UL3N4T.js → timeline-MNHZCVAL.js} +4 -2
  96. package/dist-cli/chunks/{upgrade-RWHSFZRX.js → upgrade-X57SIG7L.js} +4 -2
  97. package/dist-cli/chunks/upload-JABM3ITZ.js +4 -0
  98. package/dist-cli/chunks/{version-7K6TVQOW.js → version-V4IKIDX7.js} +4 -2
  99. package/dist-cli/chunks/web-F5CLF34I.js +4 -0
  100. package/dist-cli/chunks/{what-happened-K24TSJZX.js → what-happened-H74HHGRK.js} +4 -2
  101. package/dist-lib/agent-daemon-client.cjs +1 -1
  102. package/dist-lib/agent-events.cjs +1 -1
  103. package/dist-lib/agent-identity.cjs +3 -3
  104. package/dist-lib/agent-sessions.cjs +1 -1
  105. package/dist-lib/attached-projects.cjs +1 -1
  106. package/dist-lib/auth/shared-session.cjs +1 -1
  107. package/dist-lib/backend-origin.cjs +1 -1
  108. package/dist-lib/beta.cjs +1 -1
  109. package/dist-lib/beta.mjs +1 -1
  110. package/dist-lib/bridge-constants.cjs +1 -1
  111. package/dist-lib/cli-constants.cjs +1 -1
  112. package/dist-lib/config.cjs +1 -1
  113. package/dist-lib/detox/index.cjs +5 -4
  114. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  115. package/dist-lib/home-paths.cjs +1 -1
  116. package/dist-lib/host/bridge-host.cjs +3 -3
  117. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  118. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  119. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  120. package/dist-lib/host/websocket-proxy.cjs +1 -1
  121. package/dist-lib/index.cjs +1 -1
  122. package/dist-lib/jump-to-source-babel.cjs +1 -1
  123. package/dist-lib/menu.cjs +45 -4
  124. package/dist-lib/menu.mjs +42 -4
  125. package/dist-lib/metro.cjs +1 -1
  126. package/dist-lib/profiles.cjs +1 -1
  127. package/dist-lib/render-mode.cjs +1 -1
  128. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  129. package/dist-lib/sdk.cjs +5 -2
  130. package/dist-lib/sdk.mjs +4 -2
  131. package/dist-lib/skills.cjs +325 -182
  132. package/dist-lib/vite.cjs +1 -1
  133. package/package.json +6 -1
  134. package/scripts/postinstall.cjs +11 -2
  135. package/src/agent-identity.ts +2 -2
  136. package/src/menu.ts +53 -4
  137. package/src/vite-plugin.ts +102 -2
  138. package/dist-cli/chunks/beta-CFDAW6UN.js +0 -2
  139. package/dist-cli/chunks/chunk-3UX6AY2B.js +0 -2
  140. package/dist-cli/chunks/chunk-6VVLDYPV.js +0 -8
  141. package/dist-cli/chunks/chunk-7H34H74K.js +0 -72
  142. package/dist-cli/chunks/chunk-7H5G4HUK.js +0 -2
  143. package/dist-cli/chunks/chunk-ACSTEPSD.js +0 -2
  144. package/dist-cli/chunks/chunk-HKMWUN7F.js +0 -2
  145. package/dist-cli/chunks/chunk-K5JEUI5G.js +0 -5
  146. package/dist-cli/chunks/chunk-MOU2WLO4.js +0 -2
  147. package/dist-cli/chunks/chunk-QXDXUDJD.js +0 -1
  148. package/dist-cli/chunks/chunk-USJTVC7T.js +0 -2
  149. package/dist-cli/chunks/chunk-YNG4C3ZS.js +0 -2
  150. package/dist-cli/chunks/cli-version-TQHZOK4L.js +0 -2
  151. package/dist-cli/chunks/control-I7YBDRJT.js +0 -2
  152. package/dist-cli/chunks/daemon-4R3SZLZY.js +0 -2
  153. package/dist-cli/chunks/disk-cleanup-2COWZWBC.js +0 -2
  154. package/dist-cli/chunks/drivers-RRZM6E72.js +0 -2
  155. package/dist-cli/chunks/flow-VH6DFDQ4.js +0 -2
  156. package/dist-cli/chunks/help-3HQ2RINO.js +0 -2
  157. package/dist-cli/chunks/inspect-PKMJGXDH.js +0 -2
  158. package/dist-cli/chunks/install-desktop-K5TP3ZHJ.js +0 -2
  159. package/dist-cli/chunks/logout-E3UCJAMC.js +0 -2
  160. package/dist-cli/chunks/optional-demo-registry-AIWOBAAA.js +0 -2
  161. package/dist-cli/chunks/runtime-HOGETVVD.js +0 -2
  162. package/dist-cli/chunks/store-YLVHPKG7.js +0 -2
  163. package/dist-cli/chunks/telemetry-MQKB6PFX.js +0 -2
  164. package/dist-cli/chunks/upload-RBH4XGJ2.js +0 -2
  165. package/dist-cli/chunks/web-46ZPQCAL.js +0 -2
@@ -0,0 +1,74 @@
1
+ /*! sootsim v0.1.294 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
4
+ import{c as j,d as H}from"./chunk-ZFMJFX27.js";import{c as Y}from"./chunk-JGGXQHXH.js";import{K as F,M,g as R,j as E,r as O,s as x,t as U}from"./chunk-WQL3BLFD.js";import{a as V}from"./chunk-PSOUSJSZ.js";import{execFileSync as Z,spawnSync as c}from"child_process";import{existsSync as n,mkdirSync as L,readFileSync as le,realpathSync as ue,rmSync as h,writeFileSync as K}from"fs";import{homedir as v}from"os";import{basename as pe,dirname as C,resolve as u,sep as X}from"path";import{execFileSync as re}from"child_process";import{chmodSync as oe,mkdirSync as A,rmSync as se,writeFileSync as I}from"fs";import{dirname as T}from"path";var ne="dev.sootsim.daemon",G="SootSim Daemon",q="0.1.36";function W(e,t,r){let s=x(),o=U(),a=T(T(o)),l=T(o),p=`${a}/Resources`;se(s,{recursive:!0,force:!0}),A(O(),{recursive:!0}),A(l,{recursive:!0}),A(p,{recursive:!0}),I(`${a}/Info.plist`,ie()),I(`${a}/PkgInfo`,"APPL????"),I(o,ae(e,t,r)),oe(o,493);try{re("codesign",["--force","--sign","-","--deep",s],{stdio:"pipe"})}catch(i){let f=i instanceof Error?i.message:String(i);console.warn(` warning: ad-hoc codesign of ${s} failed: ${f}
5
+ the daemon will still run, but Login Items may show a generic name.`)}return{bundlePath:s,launcherPath:o}}function ie(){return`<?xml version="1.0" encoding="UTF-8"?>
6
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
7
+ <plist version="1.0">
8
+ <dict>
9
+ <key>CFBundleDevelopmentRegion</key><string>en</string>
10
+ <key>CFBundleDisplayName</key><string>${G}</string>
11
+ <key>CFBundleExecutable</key><string>sootsim-daemon</string>
12
+ <key>CFBundleIdentifier</key><string>${ne}</string>
13
+ <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
14
+ <key>CFBundleName</key><string>${G}</string>
15
+ <key>CFBundlePackageType</key><string>APPL</string>
16
+ <key>CFBundleShortVersionString</key><string>${q}</string>
17
+ <key>CFBundleSignature</key><string>????</string>
18
+ <key>CFBundleVersion</key><string>${q}</string>
19
+ <key>LSBackgroundOnly</key><true/>
20
+ <key>LSUIElement</key><true/>
21
+ <key>LSMinimumSystemVersion</key><string>13.0</string>
22
+ <key>NSHumanReadableCopyright</key><string>Tamagui LLC</string>
23
+ </dict>
24
+ </plist>
25
+ `}function ae(e,t,r){let o=[e.executable,...e.prefixArgs,"serve","--quiet","--port",String(t)].map(_).join(" "),a=_(r.stdout),l=_(r.stderr);return`#!/bin/sh
26
+ # SootSim Daemon launcher \u2014 auto-generated by 'sootsim setup'.
27
+ # launchd spawns this; we exec the real sootsim invocation in place so
28
+ # launchd tracks the daemon process, not the shell wrapper.
29
+ #
30
+ # stdout: ${r.stdout}
31
+ # stderr: ${r.stderr}
32
+ # a missing or broken executable can make launchd retry forever. truncate a
33
+ # retry log before it passes 10 MiB so that failure stays bounded on disk.
34
+ for log_path in ${a} ${l}; do
35
+ if [ -f "$log_path" ]; then
36
+ log_bytes=$(wc -c < "$log_path" 2>/dev/null || echo 0)
37
+ if [ "$log_bytes" -gt 10485760 ]; then
38
+ : > "$log_path"
39
+ fi
40
+ fi
41
+ done
42
+ exec ${o}
43
+ `}function _(e){return`'${e.replace(/'/g,"'\\''")}'`}var ee=60,y="dev.sootsim.daemon",N="dev.sootsim.server",g="sootsim-daemon",m=u(v(),"Library/Logs/sootsim"),D=u(v(),".local/state/sootsim");async function We(e,t={}){let[r,...s]=e,o=t.port??7668;if(!r||r==="--help"||r==="-h"){Q();return}new Set(["install","uninstall","restart","start","stop","logs"]).has(r)&&j({event:`daemon_${r}`,properties:{platform:process.platform,subsource:"daemon"}});try{switch(r){case"install":return await we({port:o,force:s.includes("--force")});case"uninstall":return await De();case"status":return await Le();case"restart":return await Pe();case"start":return await Ee();case"stop":return await Ae();case"logs":return await Ie(s);default:console.error(` unknown daemon subcommand: ${r}`),Q(),process.exit(1)}}finally{await H()}}function Q(){Y("daemon")}function de(){let e=ge();if(e)return e;let t=he();return{executable:process.execPath,prefixArgs:[t]}}function ge(){if(!me())return null;let e=fe();if(!e)return null;let t=V(),r=t==="0.0.0"?"sootsim":`sootsim@${t}`;return{executable:process.execPath,prefixArgs:[e,"exec","--yes","--package",r,"--","sootsim"]}}function me(){let e=process.argv[1];return process.env.npm_command==="exec"?!0:e?P(e).includes(`${X}_npx${X}`):!1}function fe(){try{let t=Z("which",["npm"],{encoding:"utf8"}).trim();if(t&&n(t))return z(t)}catch{}let e=process.env.npm_execpath;return e&&n(e)?z(e):null}function z(e){let t=P(e);if(pe(t)==="npx-cli.js"){let r=u(C(t),"npm-cli.js");if(n(r))return r}return t}function he(){try{let t=Z("which",["sootsim"],{encoding:"utf8"}).trim();if(t&&n(t))return P(t)}catch{}let e=process.argv[1];if(e&&n(e))return P(e);throw new Error("could not locate the sootsim binary")}function P(e){try{return ue(e)}catch{return e}}function ye(e,t){L(m,{recursive:!0});let r=u(m,"bridge.out.log"),s=u(m,"bridge.err.log"),{launcherPath:o}=W(e,t,{stdout:r,stderr:s}),a=` <string>${be(o)}</string>`;return`<?xml version="1.0" encoding="UTF-8"?>
44
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
45
+ <plist version="1.0">
46
+ <dict>
47
+ <key>Label</key><string>${y}</string>
48
+ <key>ProgramArguments</key>
49
+ <array>
50
+ ${a}
51
+ </array>
52
+ <key>RunAtLoad</key><true/>
53
+ <key>KeepAlive</key><true/>
54
+ <key>ThrottleInterval</key><integer>${ee}</integer>
55
+ <key>ProcessType</key><string>Background</string>
56
+ <key>StandardOutPath</key><string>${r}</string>
57
+ <key>StandardErrorPath</key><string>${s}</string>
58
+ </dict>
59
+ </plist>
60
+ `}function $e(e,t){return L(D,{recursive:!0}),`[Unit]
61
+ Description=sootsim bridge daemon
62
+ After=default.target
63
+
64
+ [Service]
65
+ Type=simple
66
+ ExecStart=${[e.executable,...e.prefixArgs].map(ke).join(" ")} serve --quiet --port ${t}
67
+ Restart=always
68
+ RestartSec=${ee}
69
+
70
+ [Install]
71
+ WantedBy=default.target
72
+ `}function be(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function ke(e){return/[^\w@%+=:,./-]/.test(e)?`'${e.replace(/'/g,"'\\''")}'`:e}function $(){return u(v(),"Library/LaunchAgents",`${y}.plist`)}function ve(e=v()){return u(e,"Library/LaunchAgents",`${N}.plist`)}function b(){return u(v(),".config/systemd/user",`${g}.service`)}function Ke(){if(E())return{supported:!1,installed:!1};if(process.platform==="darwin"){let e=$();return{supported:!0,installed:n(e),path:e}}if(process.platform==="linux"){let e=b();return{supported:!0,installed:n(e),path:e}}return{supported:!1,installed:!1}}async function we({port:e,force:t}){if(E())throw new Error("background daemon setup is unavailable in this environment");let r=de();if(console.log(` binary: ${[r.executable,...r.prefixArgs].join(" ")}`),console.log(` port: ${e}`),process.platform==="darwin"){te().missing||console.log(` removed legacy ${N} service`);let o=$();if(n(o)&&!t){console.log(` already installed at ${o}`),console.log(" pass --force to overwrite, or use 'sootsim daemon restart' to reload");return}L(C(o),{recursive:!0}),K(o,ye(r,e)),console.log(` wrote ${o}`);let a=`gui/${process.getuid()}`,l=`${a}/${y}`,p=()=>{let d=c("launchctl",["bootstrap",a,o],{stdio:"pipe",encoding:"utf8"}),S=(d.stderr||d.stdout||"").trim();if(d.status!==0)return{ok:!1,reason:`bootstrap exit ${d.status}${S?`: ${S}`:""}`};let B=c("launchctl",["print",l],{encoding:"utf8"});return B.status!==0?{ok:!1,reason:`bootstrap returned 0 but service not registered (print exit ${B.status})`}:{ok:!0}},i=p();if(!i.ok){let d=i.reason;if(c("launchctl",["bootout",l],{stdio:"ignore"}),i=p(),!i.ok)throw new Error(`launchctl bootstrap failed: ${i.reason}`+(d!==i.reason?` (initial: ${d})`:"")+" \u2014 try `sootsim daemon uninstall` then retry, or reboot if launchd state is stuck.")}let f=Date.now()+4e3,k,w;for(;Date.now()<f;){let d=c("launchctl",["print",l],{encoding:"utf8"});if(d.status===0&&(k=d.stdout?.match(/state\s*=\s*(\w+)/)?.[1],w=d.stdout?.match(/pid\s*=\s*(\d+)/)?.[1],k==="running"||w))break;await new Promise(S=>setTimeout(S,150))}if(k!=="running"&&!w)throw new Error(`daemon registered but did not reach running state within 4s (last state: ${k||"unknown"}). check ${u(m,"bridge.err.log")} \u2014 typically a stale runtime or a port already bound by another process.`);console.log(` registered (state: ${k||"unknown"}${w?`, pid ${w}`:""}, log: ${u(m,"bridge.err.log")})`);return}if(process.platform==="linux"){let s=b();if(n(s)&&!t){console.log(` already installed at ${s}`),console.log(" pass --force to overwrite, or use 'sootsim daemon restart' to reload");return}L(C(s),{recursive:!0}),K(s,$e(r,e)),console.log(` wrote ${s}`);let o=c("systemctl",["--user","daemon-reload"],{stdio:"pipe",encoding:"utf8"});if(o.status!==0){let i=(o.stderr||o.stdout||"").trim();throw new Error(`systemctl daemon-reload failed${i?`: ${i}`:""}`)}let a=c("systemctl",["--user","enable","--now",g],{stdio:"pipe",encoding:"utf8"});if(a.status!==0){let i=(a.stderr||a.stdout||"").trim();throw new Error(`systemctl enable --now failed${i?`: ${i}`:""} \u2014 try \`sootsim daemon uninstall\` then retry.`)}let p=(c("systemctl",["--user","is-active",g],{encoding:"utf8"}).stdout||"").trim()||"unknown";console.log(` registered (state: ${p}, journalctl --user -u ${g} to tail logs)`);try{let i=process.env.USER||process.env.LOGNAME||"";if(i){let f=c("loginctl",["show-user",i,"--property=Linger","--value"],{encoding:"utf8"});!((f.stdout||"").trim().toLowerCase()==="yes")&&f.status===0&&console.log(` note: linger is not enabled for "${i}". the daemon will exit at logout.
73
+ enable persistence with: sudo loginctl enable-linger ${i}`)}}catch{}return}console.error(` background daemon is not supported on ${process.platform}`),console.error(" run 'sootsim serve' in a persistent shell instead"),process.exit(1)}function te(e={}){let t=e.userHome??v(),r=ve(t),s=u(t,"Library/Logs/sootsim"),o=[];if(n(r)){let a=`${e.launchTarget??`gui/${process.getuid?.()??0}`}/${N}`;(e.bootout??(p=>{c("launchctl",["bootout",p],{stdio:"ignore"})}))(a),h(r,{force:!0}),o.push(r)}for(let a of["server.err.log","server.out.log"]){let l=u(s,a);n(l)&&(h(l,{force:!0}),o.push(l))}return{removed:o,missing:o.length===0}}function Se(){let e=[];if(process.platform==="darwin"){let t=te();e.push(...t.removed);let r=$();n(r)&&(c("launchctl",["bootout",`gui/${process.getuid()}/${y}`],{stdio:"ignore"}),h(r,{force:!0}),e.push(r));let s=x();return n(s)&&(h(s,{recursive:!0,force:!0}),e.push(s)),n(m)&&(h(m,{recursive:!0,force:!0}),e.push(m)),{removed:e,missing:e.length===0}}if(process.platform==="linux"){let t=b();return n(t)&&(c("systemctl",["--user","disable","--now",g],{stdio:"ignore"}),h(t,{force:!0}),c("systemctl",["--user","daemon-reload"],{stdio:"ignore"}),c("systemctl",["--user","reset-failed",g],{stdio:"ignore"}),e.push(t)),n(D)&&(h(D,{recursive:!0,force:!0}),e.push(D)),{removed:e,missing:e.length===0}}return{removed:e,missing:!0}}function xe(){let e=[],t=R();return n(t)&&(h(t,{recursive:!0,force:!0}),e.push(t)),{removed:e,missing:e.length===0}}async function De(){let e=Se();for(let r of e.removed)console.log(` removed ${r}`);let t=xe();for(let r of t.removed)console.log(` removed ${r}`);e.missing&&t.missing&&console.log(" not installed")}function J(){let e=F();if(M(e)){console.log(` bridge: responding on port ${e.bridgePort} (pid ${e.pid})`);return}console.log(e?" bridge: NOT responding \u2014 stale lockfile; check `sootsim daemon logs`":" bridge: NOT responding \u2014 no lockfile; check `sootsim daemon logs`")}async function Le(){if(process.platform==="darwin"){let e=$();if(!n(e)){console.log(" installed: no");return}console.log(` installed: yes (${e})`);let t=Te(e);t&&console.log(` binary: ${t}`);let r=c("launchctl",["print",`gui/${process.getuid()}/${y}`],{encoding:"utf8"});if(r.status===0){let s=r.stdout.match(/state\s*=\s*(\w+)/)?.[1],o=r.stdout.match(/pid\s*=\s*(\d+)/)?.[1];console.log(` state: ${s||"unknown"}${o?` (pid ${o})`:""}`)}else console.log(" state: not running");J();return}if(process.platform==="linux"){let e=b();if(!n(e)){console.log(" installed: no");return}console.log(` installed: yes (${e})`);let t=c("systemctl",["--user","is-active",g],{encoding:"utf8"});console.log(` state: ${t.stdout.trim()||"unknown"}`),J();return}console.error(` unsupported platform: ${process.platform}`),process.exit(1)}async function Pe(){if(process.platform==="darwin"){let e=$();n(e)||(console.error(" daemon not registered \u2014 run `sootsim setup`"),process.exit(1));let t=c("launchctl",["kickstart","-k",`gui/${process.getuid()}/${y}`],{stdio:"pipe",encoding:"utf8"});t.status!==0&&(console.error(` kickstart failed: ${t.stderr?.trim()}`),process.exit(1)),console.log(" restarted");return}if(process.platform==="linux"){let e=b();n(e)||(console.error(" daemon not registered \u2014 run `sootsim setup`"),process.exit(1));let t=c("systemctl",["--user","restart",g],{stdio:"pipe",encoding:"utf8"});t.status!==0&&(console.error(` restart failed: ${t.stderr?.trim()}`),process.exit(1)),console.log(" restarted");return}console.error(` unsupported platform: ${process.platform}`),process.exit(1)}async function Ee(){if(process.platform==="darwin"){let e=$();n(e)||(console.error(" daemon not registered \u2014 run `sootsim setup`"),process.exit(1));let t=c("launchctl",["kickstart",`gui/${process.getuid()}/${y}`],{stdio:"pipe",encoding:"utf8"});t.status!==0&&(console.error(` start failed: ${t.stderr?.trim()}`),process.exit(1)),console.log(" started");return}if(process.platform==="linux"){let e=b();n(e)||(console.error(" daemon not registered \u2014 run `sootsim setup`"),process.exit(1));let t=c("systemctl",["--user","start",g],{stdio:"pipe",encoding:"utf8"});t.status!==0&&(console.error(` start failed: ${t.stderr?.trim()}`),process.exit(1)),console.log(" started");return}console.error(` unsupported platform: ${process.platform}`),process.exit(1)}async function Ae(){if(process.platform==="darwin"){let e=$();n(e)||(console.error(" daemon not registered \u2014 nothing to stop"),process.exit(1));let t=c("launchctl",["bootout",`gui/${process.getuid()}/${y}`],{stdio:"pipe",encoding:"utf8"});t.status!==0&&(console.error(` stop failed: ${t.stderr?.trim()}`),process.exit(1)),console.log(" stopped");return}if(process.platform==="linux"){let e=b();n(e)||(console.error(" daemon not registered \u2014 nothing to stop"),process.exit(1));let t=c("systemctl",["--user","stop",g],{stdio:"pipe",encoding:"utf8"});t.status!==0&&(console.error(` stop failed: ${t.stderr?.trim()}`),process.exit(1)),console.log(" stopped");return}console.error(` unsupported platform: ${process.platform}`),process.exit(1)}async function Ie(e){let t=e.find(o=>/^-n\d+$|^--lines=\d+$|^\d+$/.test(o)),r=t?Number(t.replace(/\D/g,"")):200,s=e.includes("-f")||e.includes("--follow");if(process.platform==="darwin"){let o=u(m,"bridge.out.log"),a=u(m,"bridge.err.log"),l=[o,a].filter(i=>n(i));l.length===0&&(console.error(` no daemon logs yet at ${m} \u2014 run \`sootsim setup\` to install the daemon`),process.exit(1));let p=s?["-n",String(r),"-F",...l]:["-n",String(r),...l];c("tail",p,{stdio:"inherit"});return}if(process.platform==="linux"){let o=`${g}.service`,a=["--user","-u",o,"-n",String(r),"--no-pager"],l=c("journalctl",s?[...a,"-f"]:a,{encoding:"utf8",stdio:s?"inherit":"pipe"});if(s)return;let p=`${l.stdout||""}${l.stderr||""}`,i=/insufficient permissions|No journal files were opened/i.test(p);if(l.status===0&&!i){process.stdout.write(l.stdout||"");return}let f=c("journalctl",[`_SYSTEMD_USER_UNIT=${o}`,"-n",String(r),"--no-pager"],{encoding:"utf8"});if(f.status===0&&(f.stdout||"").trim()){process.stdout.write(f.stdout);return}console.error(` could not read --user journal for ${o} (this user isn't in the systemd-journal group yet).
74
+ run: sudo journalctl _SYSTEMD_USER_UNIT=${o} -n ${r} --no-pager`),process.exit(1)}console.error(` unsupported platform: ${process.platform}`),process.exit(1)}function Te(e){try{return le(e,"utf8").match(/<array>\s*<string>([^<]+)<\/string>/)?.[1]||null}catch{return null}}export{We as a,Ke as b,we as c,te as d,Se as e,xe as f};
@@ -1,2 +1,4 @@
1
- /*! sootsim v0.1.293 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
1
+ /*! sootsim v0.1.294 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
2
4
  var e="./demo-app-registry.ts",o=null;async function p(){if(o)return o;try{let r=await import(e);o=Array.isArray(r.APPS)?r.APPS:[]}catch{o=[]}return o}function n(){return o??[]}function i(r){let t=o;return o=r,{restore:()=>{o=t}}}export{p as a,n as b,i as c};
@@ -1,2 +1,4 @@
1
- /*! sootsim v0.1.293 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as o}from"./chunk-547W23BB.js";var c=["ghs_","ghp_","gho_","ghu_","github_pat_"];function d(n){return!!(n&&n.length>=20&&c.some(t=>n.startsWith(t)))}function p(){let n=process.env.CONTRAST_INSTALLATION_TOKEN?.trim(),t=process.env.GITHUB_TOKEN?.trim(),e=n||t;if(!d(e))return null;let r=(process.env.CONTRAST_REPO||process.env.GITHUB_REPOSITORY||"").trim();if(!r)return null;let[i,s]=r.includes("/")?r.split("/",2):[null,null],u=(process.env.CONTRAST_REPO_ID||process.env.GITHUB_REPOSITORY_ID||"").trim(),l=(process.env.CONTRAST_INSTALLATION_ID||process.env.GITHUB_APP_INSTALLATION_ID||"").trim();return{kind:"github",token:e,repoId:r,repositoryId:u||null,owner:i||null,repo:s||null,installationId:l||null,source:n?"contrast-runner":"github-actions"}}function a(){let n=process.env.SOOTSIM_API_KEY?.trim();if(n&&n.startsWith("sk_sootsim_"))return{kind:"api-key",secret:n,source:"env"};let t=p();if(t)return t;let e=o();return e?.token?{kind:"session",token:e.token,origin:e.origin}:null}function g(n){return n.kind==="api-key"?`Bearer ${n.secret}`:`Bearer ${n.token}`}function _(n){return!n||n.kind!=="github"?null:{repoId:n.repoId,owner:n.owner??void 0,repo:n.repo??void 0,installationId:n.installationId}}export{a,g as b,_ as c};
1
+ /*! sootsim v0.1.294 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
4
+ import{a as o}from"./chunk-SLMUW2WU.js";var c=["ghs_","ghp_","gho_","ghu_","github_pat_"];function d(n){return!!(n&&n.length>=20&&c.some(t=>n.startsWith(t)))}function p(){let n=process.env.CONTRAST_INSTALLATION_TOKEN?.trim(),t=process.env.GITHUB_TOKEN?.trim(),e=n||t;if(!d(e))return null;let r=(process.env.CONTRAST_REPO||process.env.GITHUB_REPOSITORY||"").trim();if(!r)return null;let[i,s]=r.includes("/")?r.split("/",2):[null,null],u=(process.env.CONTRAST_REPO_ID||process.env.GITHUB_REPOSITORY_ID||"").trim(),l=(process.env.CONTRAST_INSTALLATION_ID||process.env.GITHUB_APP_INSTALLATION_ID||"").trim();return{kind:"github",token:e,repoId:r,repositoryId:u||null,owner:i||null,repo:s||null,installationId:l||null,source:n?"contrast-runner":"github-actions"}}function a(){let n=process.env.SOOTSIM_API_KEY?.trim();if(n&&n.startsWith("sk_sootsim_"))return{kind:"api-key",secret:n,source:"env"};let t=p();if(t)return t;let e=o();return e?.token?{kind:"session",token:e.token,origin:e.origin}:null}function g(n){return n.kind==="api-key"?`Bearer ${n.secret}`:`Bearer ${n.token}`}function _(n){return!n||n.kind!=="github"?null:{repoId:n.repoId,owner:n.owner??void 0,repo:n.repo??void 0,installationId:n.installationId}}export{a,g as b,_ as c};
@@ -1,2 +1,4 @@
1
- /*! sootsim v0.1.293 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{H as t,L as n,N as l,j as r}from"./chunk-WOWLO4LL.js";function m(){let e=t(),i=r()?n():null;return i&&l(i)?{primary:`engine dev source (:${i.bridgePort})`,installedRuntime:e?`installed runtime v${e}`:null,isDevBridge:!0}:{primary:e?`runtime v${e}`:"runtime not installed",installedRuntime:null,isDevBridge:!1}}export{m as a};
1
+ /*! sootsim v0.1.294 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
4
+ import{H as t,L as n,N as l,j as r}from"./chunk-WQL3BLFD.js";function m(){let e=t(),i=r()?n():null;return i&&l(i)?{primary:`engine dev source (:${i.bridgePort})`,installedRuntime:e?`installed runtime v${e}`:null,isDevBridge:!0}:{primary:e?`runtime v${e}`:"runtime not installed",installedRuntime:null,isDevBridge:!1}}export{m as a};
@@ -1,5 +1,7 @@
1
- /*! sootsim v0.1.293 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
- import{a as st}from"./chunk-YRFWATLA.js";import{a as it}from"./chunk-2M57EAWS.js";import{a as ge,c as we,d as ye,e as tt,f as be,g as Se,h as rt,i as ve,j as nt}from"./chunk-2XYCSFGN.js";import{a as et}from"./chunk-U3564F2Y.js";import{e as ot}from"./chunk-WPPMUUML.js";import{h as Ye,p as Ze,r as Xe,v as Qe}from"./chunk-4B4VFT73.js";import{f as We}from"./chunk-WP3TFHFL.js";import{h as me,m as qe}from"./chunk-B7TX4WFB.js";import{a as ze}from"./chunk-LA5DIO33.js";import{I as G,m as je,n as Ve,o as Je,p as Ge}from"./chunk-RKXHQ2Q3.js";import{a as Ue}from"./chunk-6IFJLHDA.js";import{g as he,h as fe,i as Ke}from"./chunk-J6P2UPXH.js";import{c as Be,d as ue}from"./chunk-7H5G4HUK.js";import{a as Le,b as Ne,c as Ce}from"./chunk-YNG4C3ZS.js";import{e as pe,f as He}from"./chunk-K5JEUI5G.js";import*as $ from"fs";import{createHash as Kt,randomUUID as qt}from"node:crypto";import{tmpdir as Y}from"os";import*as w from"path";import*as v from"fs";import*as S from"path";var Pt="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",lt=1;function kt(i){let e=Ce(i),t=e.scale,r=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,n=e.width,o=e.height,a=Le(e),s=r?e.width+58:a.frameWidth,l=r?e.height+111+111:a.frameHeight,p=9.5,u=lt,m=s+p*2,b=l+lt*2,g=p+(r?29:a.screenLeft),P=r?111:a.screenTop,k=r?52:a.frameRadius,H=[{side:e.hardwareButtons.lock.side,top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.ringToggle.side,top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeUp.side,top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeDown.side,top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:i,renderScale:t,outerWidth:Math.round(m*t),outerHeight:Math.round(b*t),logicalOuterWidth:m,logicalOuterHeight:b,logicalFrameWidth:s,logicalFrameHeight:l,logicalFrameLeft:p,logicalFrameTop:u,logicalScreenWidth:n,logicalScreenHeight:o,logicalScreenLeft:g,logicalScreenTop:P,logicalScreenRadius:r?0:a.screenRadius,logicalFrameRadius:k,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:Pt,buttons:H,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 At(i){let e=i.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
1
+ /*! sootsim v0.1.294 | (c) 2026 Tamagui LLC | Proprietary — see LICENSE */
2
+ import { createRequire as __sootsimCreateRequire } from 'node:module'
3
+ var require = __sootsimCreateRequire(import.meta.url)
4
+ import{a as at}from"./chunk-7HVMAGDK.js";import{a as ot}from"./chunk-K53YCAQM.js";import{a as me,c as ge,d as we,e as rt,f as ye,g as be,h as nt,i as Se,j as it}from"./chunk-24BJFJFB.js";import{a as tt}from"./chunk-WYRLRNIP.js";import{e as st}from"./chunk-BXO2PTNM.js";import{h as Ze,p as Xe,r as Qe,v as et}from"./chunk-7Q77LTPT.js";import{f as Ue}from"./chunk-XYFP466E.js";import{h as qe,m as ze}from"./chunk-RWUNC66S.js";import{a as Ye}from"./chunk-AMKQUZA2.js";import{J as pe,m as We,n as je,o as Ve,p as Je,q as Ge}from"./chunk-AFLGWOX3.js";import{a as He}from"./chunk-FNCSUHUR.js";import{g as he,h as fe,i as Ke}from"./chunk-PZTKQG6H.js";import{c as De,d as ce}from"./chunk-ZFMJFX27.js";import{a as Be,b as Le,c as Ne}from"./chunk-VXGCZUX4.js";import{e as ue,f as Ce}from"./chunk-JUOQ4ZPA.js";import*as $ from"fs";import{createHash as qt,randomUUID as zt}from"node:crypto";import{tmpdir as z}from"os";import*as w from"path";import*as v from"fs";import*as S from"path";var Pt="inset 0 0 0 0.5px #000, inset 0 0 0 2px #757575, inset 0 0 0 5px #212121",dt=1;function At(i){let e=Ne(i),t=e.scale,r=e.statusBarHeight>0&&!e.dynamicIsland&&e.homeIndicatorHeight===0&&e.cornerRadius===0,n=e.width,o=e.height,a=Be(e),s=r?e.width+58:a.frameWidth,l=r?e.height+111+111:a.frameHeight,p=9.5,u=dt,g=s+p*2,b=l+dt*2,m=p+(r?29:a.screenLeft),k=r?111:a.screenTop,P=r?52:a.frameRadius,H=[{side:e.hardwareButtons.lock.side,top:e.hardwareButtons.lock.top,height:e.hardwareButtons.lock.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.ringToggle.side,top:e.hardwareButtons.ringToggle.top,height:e.hardwareButtons.ringToggle.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeUp.side,top:e.hardwareButtons.volumeUp.top,height:e.hardwareButtons.volumeUp.height,width:e.hardwareButtons.width},{side:e.hardwareButtons.volumeDown.side,top:e.hardwareButtons.volumeDown.top,height:e.hardwareButtons.volumeDown.height,width:e.hardwareButtons.width}];return{model:i,renderScale:t,outerWidth:Math.round(g*t),outerHeight:Math.round(b*t),logicalOuterWidth:g,logicalOuterHeight:b,logicalFrameWidth:s,logicalFrameHeight:l,logicalFrameLeft:p,logicalFrameTop:u,logicalScreenWidth:n,logicalScreenHeight:o,logicalScreenLeft:m,logicalScreenTop:k,logicalScreenRadius:r?0:a.screenRadius,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:Pt,buttons:H,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 Mt(i){let e=i.side==="right",t=e?"inset(-3px -3px -3px 0)":"inset(-3px 0 -3px -3px)";return`
3
5
  <div
4
6
  aria-hidden="true"
5
7
  style="
@@ -24,7 +26,7 @@ import{a as st}from"./chunk-YRFWATLA.js";import{a as it}from"./chunk-2M57EAWS.js
24
26
  z-index:2;
25
27
  "
26
28
  ></div>
27
- `}function Mt(i,e){let t=i.buttons.map(At).join(""),r=i.metallicRingShadow?`
29
+ `}function Rt(i,e){let t=i.buttons.map(Mt).join(""),r=i.metallicRingShadow?`
28
30
  <div
29
31
  aria-hidden="true"
30
32
  style="
@@ -177,7 +179,7 @@ import{a as st}from"./chunk-YRFWATLA.js";import{a as it}from"./chunk-2M57EAWS.js
177
179
  </div>
178
180
  </div>
179
181
  </body>
180
- </html>`}async function dt(i,e){let{chromium:t}=await import("playwright"),r=await it(n=>t.launch(n),{headless:!0});try{let n=await Rt(r);try{return await n.compose(i,e)}finally{await n.close()}}finally{await r.close()}}async function Rt(i){let e=new Map;async function t(r){let n=e.get(r);if(n)return n;let o=kt(r),a=await i.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,n){let o=await t(n),a=`data:image/png;base64,${r.toString("base64")}`;return await o.page.setContent(Mt(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 _t}from"child_process";import*as N from"vm";var Ot=3e5,Dt=`
182
+ </html>`}async function ct(i,e){let{chromium:t}=await import("playwright"),r=await ot(n=>t.launch(n),{headless:!0});try{let n=await _t(r);try{return await n.compose(i,e)}finally{await n.close()}}finally{await r.close()}}async function _t(i){let e=new Map;async function t(r){let n=e.get(r);if(n)return n;let o=At(r),a=await i.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,n){let o=await t(n),a=`data:image/png;base64,${r.toString("base64")}`;return await o.page.setContent(Rt(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 Ot}from"child_process";import*as N from"vm";var Dt=3e5,Bt=`
181
183
  let input = '';
182
184
  process.stdin.on('data', (c) => { input += c });
183
185
  process.stdin.on('end', async () => {
@@ -199,7 +201,7 @@ process.stdin.on('end', async () => {
199
201
  process.exitCode = 1;
200
202
  }
201
203
  });
202
- `;function K(i,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 n=_t(process.execPath,["-e",Dt],{input:JSON.stringify({url:i,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Ot,maxBuffer:64*1024*1024,env:r});if(n.error)throw new Error(`http ${e} ${i} failed: ${n.error.message}`);let o;try{o=JSON.parse(n.stdout||"")}catch{throw new Error(`http ${e} ${i} failed: no response (${(n.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${i} failed: ${a.__error}`);return a}var Bt=/(?<!\\)\$\{([^$]*)\}/g,Lt=/\\(\$\{[^$]*\})/g,Nt=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ee=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??(n=>console.log(`[flow] js: ${n}`)),r={output:this.output,maestro:this.maestro,http:{get:(n,o)=>K(n,"GET",o),post:(n,o)=>K(n,"POST",o),put:(n,o)=>K(n,"PUT",o),delete:(n,o)=>K(n,"DELETE",o),request:(n,o)=>K(n,(o?.method??"GET").toUpperCase(),o)},console:{log:(...n)=>t(n.map(o=>typeof o=="string"?o:ct(o)).join(" "))}};this.context=N.createContext(r),N.runInContext(`
204
+ `;function G(i,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 n=Ot(process.execPath,["-e",Bt],{input:JSON.stringify({url:i,method:e,headers:t?.headers,body:t?.body}),encoding:"utf8",timeout:Dt,maxBuffer:64*1024*1024,env:r});if(n.error)throw new Error(`http ${e} ${i} failed: ${n.error.message}`);let o;try{o=JSON.parse(n.stdout||"")}catch{throw new Error(`http ${e} ${i} failed: no response (${(n.stderr||"").trim().slice(0,200)})`)}let a=o;if(a.__error)throw new Error(`http ${e} ${i} failed: ${a.__error}`);return a}var Lt=/(?<!\\)\$\{([^$]*)\}/g,Nt=/\\(\$\{[^$]*\})/g,Ct=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Q=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??(n=>console.log(`[flow] js: ${n}`)),r={output:this.output,maestro:this.maestro,http:{get:(n,o)=>G(n,"GET",o),post:(n,o)=>G(n,"POST",o),put:(n,o)=>G(n,"PUT",o),delete:(n,o)=>G(n,"DELETE",o),request:(n,o)=>G(n,(o?.method??"GET").toUpperCase(),o)},console:{log:(...n)=>t(n.map(o=>typeof o=="string"?o:ut(o)).join(" "))}};this.context=N.createContext(r),N.runInContext(`
203
205
  globalThis.__maestroScope = new Proxy(globalThis, {
204
206
  has() { return true },
205
207
  get(target, key) { return target[key] },
@@ -210,13 +212,13 @@ process.stdin.on('end', async () => {
210
212
  var yPercent = Math.ceil(y * 100) + '%'
211
213
  return xPercent + ',' + yPercent
212
214
  }
213
- `,this.context);for(let[n,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(n,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[n,o]of Object.entries(r))this.envBinding.set(n,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 N.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=N.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(Bt,(r,n)=>{if(n.trim().length===0)return"";let o=this.evaluate(n);if(o===void 0&&Nt.test(n.trim()))throw new Error(`missing variable for flow placeholder: ${n.trim()}`);return ct(o)}).replace(Lt,(r,n)=>n)}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,n])=>[r,this.interpolateValue(n,r)])):e}};function ct(i){if(i===void 0)return"undefined";if(i===null)return"null";if(typeof i=="object")try{return JSON.stringify(i)}catch{return String(i)}return String(i)}function ut(i){if(i==null)return!1;if(typeof i=="boolean")return i;let e=String(i);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var te=1e4,Ct=Math.min(10,Math.max(1,Number(process.env.SOOTSIM_FLOW_TIMEOUT_SCALE)||1)),q=i=>Math.round(i*Ct),ne=393,C=852;function f(i){return new Promise(e=>setTimeout(e,i))}function Ie(i){return!!(i&&typeof i=="object"&&!Array.isArray(i))}function z(i,e){if(!Ie(i))return null;let t=i[e];return typeof t=="string"&&t.length>0?t:null}function Ht(i,e){return Ie(i)?i[e]===!0:!1}function Ut(i){if(!i)return null;let e=i.recentApps;if(Array.isArray(e))for(let r of e){let n=z(r,"id");if(n)return n}let t=i.surfaceBindings;return z(t,"app:one")||z(t,"app:two")||null}function Wt(i){return i?S.basename(i)===".maestro"?S.dirname(i):i:process.cwd()}function jt(i,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(S.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let n=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():Wt(t.flowDir);return S.resolve(n,r)}return S.join(i,r)}function Vt(i){if(typeof i=="string")return{path:i,withFrame:!1};let e=i.path?.trim()||i.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:i.withFrame===!0,layers:i.layers}}function re(i,e){let[t,r]=i.split(",").map(s=>s.trim()),n=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+n(t,e?.width??ne),y:a+n(r,e?.height??C)}}function pt(i){switch(i){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[i]:!0}}}function Jt(i){let e=i.split(/^---$/m),t=e.length>1?e[e.length-1]:i,r=et.parse(t);return Array.isArray(r)?r:[]}var ie=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new ee({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 n=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!n)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=n??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=te){let t=Date.now()+q(e),r=Date.now(),n=null,o=0,a=0,s=-1,l=r;for(;Date.now()<t;){try{let u=await this.evaluate(je,8e3);if(o=0,u?.externalError)throw new Error(`app failed to load: ${u.externalError}`);if(u){let m=Date.now();u.nodes!==s&&(s=u.nodes,l=m);let b=u.flag===!0&&Je(u),g=u.flag!==!0&&Ge(u);if((b||g)&&u.externalReady!==!1&&!u.externalError&&!u.loadingText&&m-l>=Ve)return}}catch(u){if(n=u instanceof Error?u:new Error(String(u)),n.message.startsWith("app failed to load:"))throw n;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${n.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 p=Date.now()-r;p-a>=5e3&&(a=p,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(p/1e3)}s)`)),await f(500)}throw n?.message.startsWith("app failed to load:")?n: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 st("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
215
+ `,this.context);for(let[n,o]of Object.entries(process.env))o!==void 0&&this.envBinding.set(n,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[n,o]of Object.entries(r))this.envBinding.set(n,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 N.runInContext(`(function(){ with(__maestroScope){ return eval(\`${t}\`) } })()`,this.context)}syncEnvToContext(){let e=N.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(Lt,(r,n)=>{if(n.trim().length===0)return"";let o=this.evaluate(n);if(o===void 0&&Ct.test(n.trim()))throw new Error(`missing variable for flow placeholder: ${n.trim()}`);return ut(o)}).replace(Nt,(r,n)=>n)}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,n])=>[r,this.interpolateValue(n,r)])):e}};function ut(i){if(i===void 0)return"undefined";if(i===null)return"null";if(typeof i=="object")try{return JSON.stringify(i)}catch{return String(i)}return String(i)}function pt(i){if(i==null)return!1;if(typeof i=="boolean")return i;let e=String(i);if(e.trim().length===0||e.toLowerCase()==="false"||e==="undefined"||e==="null")return!1;let t=Number(e);return!(!Number.isNaN(t)&&t===0)}var ee=1e4,Ht=Math.min(10,Math.max(1,Number(process.env.SOOTSIM_FLOW_TIMEOUT_SCALE)||1)),K=i=>Math.round(i*Ht),re=393,C=852;function f(i){return new Promise(e=>setTimeout(e,i))}function Ee(i){return!!(i&&typeof i=="object"&&!Array.isArray(i))}function q(i,e){if(!Ee(i))return null;let t=i[e];return typeof t=="string"&&t.length>0?t:null}function Ut(i,e){return Ee(i)?i[e]===!0:!1}function Wt(i){if(!i)return null;let e=i.recentApps;if(Array.isArray(e))for(let r of e){let n=q(r,"id");if(n)return n}let t=i.surfaceBindings;return q(t,"app:one")||q(t,"app:two")||null}function jt(i){return i?S.basename(i)===".maestro"?S.dirname(i):i:process.cwd()}function Vt(i,e,t){let r=e.endsWith(".png")?e:`${e}.png`;if(S.isAbsolute(r))return r;if(t.mode==="flow"&&/[\\/]/.test(r)){let n=r.startsWith("./")||r.startsWith("../")?t.flowDir??process.cwd():jt(t.flowDir);return S.resolve(n,r)}return S.join(i,r)}function Jt(i){if(typeof i=="string")return{path:i,withFrame:!1};let e=i.path?.trim()||i.name?.trim();if(!e)throw new Error("takeScreenshot object form requires path or name");return{path:e,withFrame:i.withFrame===!0,layers:i.layers}}function te(i,e){let[t,r]=i.split(",").map(s=>s.trim()),n=(s,l)=>s.endsWith("%")?Number.parseFloat(s)/100*l:Number.parseFloat(s),o=e?.x??0,a=e?.y??0;return{x:o+n(t,e?.width??re),y:a+n(r,e?.height??C)}}function ht(i){switch(i){case"back":return{back:!0};case"hideKeyboard":return{hideKeyboard:!0};case"waitForAnimationToEnd":return{waitForAnimationToEnd:!0};case"stopApp":return{stopApp:!0};case"clearState":return{clearState:!0};case"clearKeychain":return{clearKeychain:!0};case"eraseText":return{eraseText:50};case"scroll":case"scrollDown":return{scroll:{direction:"DOWN"}};case"scrollUp":return{scroll:{direction:"UP"}};default:return{[i]:!0}}}function Gt(i){let e=i.split(/^---$/m),t=e.length>1?e[e.length-1]:i,r=tt.parse(t);return Array.isArray(r)?r:[]}var ne=class{constructor(e,t){this.bridge=e;this.opts=t}stepDelay=0;js=new Q({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 n=this.simRouteHint&&e.find(l=>l.readyState==="open"&&this.normalizeSimRoute(l.url||l.origin)===this.simRouteHint);if(!n)return;let o=e.find(l=>l.isPrimary&&l.readyState==="open"),a=e.find(l=>l.readyState==="open"),s=n??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=ee){let t=Date.now()+K(e),r=Date.now(),n=null,o=0,a=0,s=-1,l=r;for(;Date.now()<t;){try{let u=await this.evaluate(We,8e3);if(o=0,u?.externalError)throw new Error(`app failed to load: ${u.externalError}`);if(u){let g=Date.now();u.nodes!==s&&(s=u.nodes,l=g);let b=u.flag===!0&&Je(u),m=u.flag!==!0&&Ge(u);if((b||m)&&u.externalReady!==!1&&!u.externalError&&!u.loadingText&&g-l>=je)return}}catch(u){if(n=u instanceof Error?u:new Error(String(u)),n.message.startsWith("app failed to load:"))throw n;if(o++,o>=4)throw new Error(`target sim is not responding to the bridge (${n.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 p=Date.now()-r;p-a>=5e3&&(a=p,console.log(` [flow] waiting for app to be ready\u2026 (${Math.round(p/1e3)}s)`)),await f(Ve)}throw n?.message.startsWith("app failed to load:")?n: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 at("flow --video",{originOverride:this.opts.billingOriginOverride,allowGitHubAuth:this.opts.allowGitHubRecording}),this.recordingAccessChecked=!0);let e=Date.now(),t=await this.evaluate(`(() => {
214
216
  const rec = window.__sootsimRecorder
215
217
  if (!rec) return { ok: false, error: 'recorder unavailable on this page' }
216
218
  const format = ${JSON.stringify(this.opts.recordingFormat??"webm")}
217
219
  if (rec.state() === 'recording') return { ok: true, format }
218
220
  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 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 n=r,o=n.id??n.text??n.name??n.path;if(typeof o=="string"&&o)return o.slice(0,80);let a=n.visible??n.notVisible;if(typeof a=="string"&&a)return a.slice(0,80);if(a&&typeof a=="object"){let s=a,l=s.id??s.text;if(typeof l=="string"&&l)return l.slice(0,80)}if(n.point&&typeof n.point=="string")return n.point.slice(0,80);if(typeof n.x=="number"&&typeof n.y=="number")return`${Math.round(n.x)}, ${Math.round(n.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)),e.screenshotPath&&(r.screenshotPath=e.screenshotPath),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=[],n=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${n}, chunk: 2097152 })`);if(!l||(r.push(Buffer.from(l.data,"base64")),n=l.offset,l.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");v.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=S.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return v.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 ve({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 () => {
221
+ })()`);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 n=r,o=n.id??n.text??n.name??n.path;if(typeof o=="string"&&o)return o.slice(0,80);let a=n.visible??n.notVisible;if(typeof a=="string"&&a)return a.slice(0,80);if(a&&typeof a=="object"){let s=a,l=s.id??s.text;if(typeof l=="string"&&l)return l.slice(0,80)}if(n.point&&typeof n.point=="string")return n.point.slice(0,80);if(typeof n.x=="number"&&typeof n.y=="number")return`${Math.round(n.x)}, ${Math.round(n.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)),e.screenshotPath&&(r.screenshotPath=e.screenshotPath),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=[],n=0;for(;;){let l=await this.evaluate(`window.__sootsimRecorder.getBlobBase64({ offset: ${n}, chunk: 2097152 })`);if(!l||(r.push(Buffer.from(l.data,"base64")),n=l.offset,l.done))break}if(r.length===0)throw new Error("recording requested but no video buffer was produced");v.mkdirSync(this.opts.recordingOutputDir,{recursive:!0});let a=(t.mime||this.opts.recordingFormat||"video/webm").includes("mp4")?"mp4":"webm",s=S.join(this.opts.recordingOutputDir,`sootsim-${Date.now()}.${a}`);return v.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 Se({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
222
  const test = window.__sootsimTest
221
223
  if (!test) return null
222
224
  let node = null
@@ -365,7 +367,7 @@ process.stdin.on('end', async () => {
365
367
  )
366
368
  }
367
369
  return direct
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,n){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:r,target:n})}async waitForElement(e,t=5e3){let r=Date.now()+t,n=await this.findElement(e);for(;!n&&Date.now()<r;)await f(150),n=await this.findElement(e);if(!n)return n;let o=Date.now()+1200,a=n;for(;Date.now()<o;){await f(120);let s=await this.findElement(e);if(!s)break;let l=Math.abs(s.absolutePosition.x-a.absolutePosition.x)>.5||Math.abs(s.absolutePosition.y-a.absolutePosition.y)>.5||Math.abs(s.layout.width-a.layout.width)>.5||Math.abs(s.layout.height-a.layout.height)>.5;if(n=s,!l)return n;a=s}return n}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{...re(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,n=this.replayTargetForElement(e,t,r);return e.point?{...re(e.point,{x:t.absolutePosition.x,y:t.absolutePosition.y,width:t.layout.width,height:t.layout.height}),element:t,target:n}:{x:r?.cx??t.absolutePosition.x+t.layout.width/2,y:r?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:n}}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,p=l?.cx??s.absolutePosition.x+s.layout.width/2,u=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(p,u,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 n=await this.longPress(r.x,r.y,3e3,r.target);if(n?.ok===!1||n?.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 n=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
370
+ })()`)}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,n){return await this.bridge.send({type:"longPress",simId:this.opts.simId,x:e,y:t,durationMs:r,target:n})}async waitForElement(e,t=5e3){let r=Date.now()+t,n=await this.findElement(e);for(;!n&&Date.now()<r;)await f(150),n=await this.findElement(e);if(!n)return n;let o=Date.now()+1200,a=n;for(;Date.now()<o;){await f(120);let s=await this.findElement(e);if(!s)break;let l=Math.abs(s.absolutePosition.x-a.absolutePosition.x)>.5||Math.abs(s.absolutePosition.y-a.absolutePosition.y)>.5||Math.abs(s.layout.width-a.layout.width)>.5||Math.abs(s.layout.height-a.layout.height)>.5;if(n=s,!l)return n;a=s}return n}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{...te(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,n=this.replayTargetForElement(e,t,r);return e.point?{...te(e.point,{x:t.absolutePosition.x,y:t.absolutePosition.y,width:t.layout.width,height:t.layout.height}),element:t,target:n}:{x:r?.cx??t.absolutePosition.x+t.layout.width/2,y:r?.cy??t.absolutePosition.y+t.layout.height/2,element:t,target:n}}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,p=l?.cx??s.absolutePosition.x+s.layout.width/2,u=l?.cy??s.absolutePosition.y+s.layout.height/2;if((await this.tap(p,u,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 n=await this.longPress(r.x,r.y,3e3,r.target);if(n?.ok===!1||n?.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 n=Math.max(0,Math.round(r));if(!await this.evaluate(`(async () => {
369
371
  const interact = window.__sootsimInteract
370
372
  if (interact?.doubleTap) {
371
373
  return !!(await interact.doubleTap(${e}, ${t}, ${n}))
@@ -386,7 +388,7 @@ process.stdin.on('end', async () => {
386
388
  visible: !!keyboard?.isVisible?.(),
387
389
  focused: !!test?.isTextInputFocused?.(),
388
390
  }
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()+q(e.timeout||te);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let r=await this.findElement(e),n=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||te}ms${n}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Vt(e),r=jt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});v.mkdirSync(S.dirname(r),{recursive:!0});let n=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};n&&n!=="full"&&(o.layers=n);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let p=await this.readCurrentDeviceModel();if(!p)throw new Error("could not read current device model for framed screenshot");let u=await dt(l,p);return v.writeFileSync(r,u),console.log(`[flow] screenshot: ${r} (frame: ${p})`),r}return v.writeFileSync(r,l),console.log(`[flow] screenshot: ${r}`),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 Ne)?null:t}async captureScreenshot(e){v.mkdirSync(S.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");v.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){v.mkdirSync(e,{recursive:!0});let r=(u,m)=>{try{v.writeFileSync(S.join(e,u),m)}catch{}},n=async u=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:u})}catch{return null}},o=await n(`(async () => {
391
+ })()`);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()+K(e.timeout||ee);for(;Date.now()<t;){if(await this.findElement(e))return;await f(200)}let r=await this.findElement(e),n=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||ee}ms${n}`)}async takeScreenshot(e){if(!this.hasFreshVisualSettle())try{await this.waitForVisualSettle(),await f(250)}catch{}let t=Jt(e),r=Vt(this.opts.screenshotDir,t.path,{mode:this.opts.screenshotPathMode??"dir",flowDir:this.opts.flowDir});v.mkdirSync(S.dirname(r),{recursive:!0});let n=t.layers??this.opts.screenshotLayers,o={type:"screenshot",simId:this.opts.simId};n&&n!=="full"&&(o.layers=n);let s=(await this.bridge.send(o)).replace(/^data:image\/png;base64,/,""),l=Buffer.from(s,"base64");if(t.withFrame){let p=await this.readCurrentDeviceModel();if(!p)throw new Error("could not read current device model for framed screenshot");let u=await ct(l,p);return v.writeFileSync(r,u),console.log(`[flow] screenshot: ${r} (frame: ${p})`),r}return v.writeFileSync(r,l),console.log(`[flow] screenshot: ${r}`),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 Le)?null:t}async captureScreenshot(e){v.mkdirSync(S.dirname(e),{recursive:!0});let r=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");v.writeFileSync(e,Buffer.from(r,"base64"))}async captureFailureBundle(e,t){v.mkdirSync(e,{recursive:!0});let r=(u,g)=>{try{v.writeFileSync(S.join(e,u),g)}catch{}},n=async u=>{try{return await this.bridge.send({type:"evaluate",simId:this.opts.simId,code:u})}catch{return null}},o=await n(`(async () => {
390
392
  const out = {
391
393
  simId: window.__sootsimBridge?.id ?? window.SootSim?.state?.simId ?? null,
392
394
  url: location.href,
@@ -410,7 +412,7 @@ process.stdin.on('end', async () => {
410
412
  }
411
413
  } catch {}
412
414
  return out
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 n(`(async () => {
415
+ })()`);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 g=(await this.bridge.send({type:"screenshot",simId:this.opts.simId})).replace(/^data:image\/png;base64,/,"");r("screenshot.png",Buffer.from(g,"base64"))}catch{}let a=await n(`(async () => {
414
416
  const t = window.__sootsimTest
415
417
  const mainShell = window.SootSim?.bridges?.mainShell
416
418
  if (!t) return { error: 'no test bridge' }
@@ -427,12 +429,12 @@ process.stdin.on('end', async () => {
427
429
  warnings: c?.getWarnings?.() ?? [],
428
430
  requests: (window.__sootsimGetFailedRequests?.() ?? []),
429
431
  }
430
- })()`);return p&&r("console.json",JSON.stringify(p,null,2)),e}async swipe(e="UP",t=300){let r=ne/2,n=C/2,o=200,a=r,s=n,l=r,p=n;switch(e.toUpperCase()){case"UP":s+=o,p-=o;break;case"DOWN":s-=o,p+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let u=Math.max(10,Math.round(t/16));await this.drag(a,s,l,p,u,16)}async drag(e,t,r,n,o=12,a=16){if(!(await this.evaluate(`(async () => {
432
+ })()`);return p&&r("console.json",JSON.stringify(p,null,2)),e}async swipe(e="UP",t=300){let r=re/2,n=C/2,o=200,a=r,s=n,l=r,p=n;switch(e.toUpperCase()){case"UP":s+=o,p-=o;break;case"DOWN":s-=o,p+=o;break;case"LEFT":a+=o,l-=o;break;case"RIGHT":a-=o,l+=o;break}let u=Math.max(10,Math.round(t/16));await this.drag(a,s,l,p,u,16)}async drag(e,t,r,n,o=12,a=16){if(!(await this.evaluate(`(async () => {
431
433
  const interact = window.__sootsimInteract
432
434
  if (!interact?.drag) return { ok: false }
433
435
  const value = await interact.drag(${e}, ${t}, ${r}, ${n}, ${Math.max(1,Math.round(o))}, ${Math.max(0,Math.round(a))})
434
436
  return { ok: !!value, value }
435
- })()`))?.ok)throw new Error("drag failed");await f(300)}async swipeCoords(e,t,r=300){let n=re(e),o=re(t),a=Math.max(10,Math.round(r/16));await this.drag(n.x,n.y,o.x,o.y,a,16)}async swipeFrom(e,t="UP",r=300){let n=await this.findElement(e);if(!n)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=n.absolutePosition.x+n.layout.width/2,a=n.absolutePosition.y+n.layout.height/2,s=180,l=o,p=a;switch(t.toUpperCase()){case"UP":p-=s;break;case"DOWN":p+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let u=Math.max(10,Math.round(r/16));await this.drag(o,a,l,p,u,16)}async scrollTo(e,t,r){let n=await this.callTest("scrollTo",e,t,r,!1);if(!n?.ok)throw new Error(`scrollTo failed: ${n?.reason||"unknown error"}`);await f(250)}async pinch(e){let t=await this.evaluate(`(async () => {
437
+ })()`))?.ok)throw new Error("drag failed");await f(300)}async swipeCoords(e,t,r=300){let n=te(e),o=te(t),a=Math.max(10,Math.round(r/16));await this.drag(n.x,n.y,o.x,o.y,a,16)}async swipeFrom(e,t="UP",r=300){let n=await this.findElement(e);if(!n)throw new Error(`swipeFrom: element not found: ${JSON.stringify(e)}`);let o=n.absolutePosition.x+n.layout.width/2,a=n.absolutePosition.y+n.layout.height/2,s=180,l=o,p=a;switch(t.toUpperCase()){case"UP":p-=s;break;case"DOWN":p+=s;break;case"LEFT":l-=s;break;case"RIGHT":l+=s;break}let u=Math.max(10,Math.round(r/16));await this.drag(o,a,l,p,u,16)}async scrollTo(e,t,r){let n=await this.callTest("scrollTo",e,t,r,!1);if(!n?.ok)throw new Error(`scrollTo failed: ${n?.reason||"unknown error"}`);await f(250)}async pinch(e){let t=await this.evaluate(`(async () => {
436
438
  const interact = window.__sootsimInteract
437
439
  if (!interact?.pinch) return { ok: false, reason: 'no interact.pinch' }
438
440
  const ok = await interact.pinch(
@@ -441,7 +443,7 @@ process.stdin.on('end', async () => {
441
443
  ${e.steps||12}, ${e.stepMs||16}
442
444
  )
443
445
  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 ve({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",n=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<C-50){if(e.centerElement){let a=C/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),p=s>0?a-l:a+l;await this.drag(ne/2,a,ne/2,p,10,16)}}return}await this.swipe(n,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+q(e.timeout||te);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,n=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&n)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let n=!1;for(let o=0;o<3&&!n;o++)try{n=await this.evaluate(ge(!0),2e4)}catch{await f(1e3)}n||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(ge(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=Ht(e,"resetRuntime");if(!this.firstLaunchDone&&!t){if(this.firstLaunchDone=!0,r){let n=await G(this.bridge).catch(()=>null),o=n?.state==="home"&&n.activeApp==null;await this.softReloadGuestApp(!1),await this.waitForTree(12e4),o&&(await me(this.bridge,"goHome",1e3),await this.waitForShellHome(1e3)),await this.launchShellAppFromHomeIfNeeded(e,o?{...n??{},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(n){console.warn(` warn: onAfterLaunch hook threw: ${n instanceof Error?n.message:n}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
446
+ })()`);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 Se({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",n=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<C-50){if(e.centerElement){let a=C/2,s=o.absolutePosition.y-a;if(Math.abs(s)>100){let l=Math.min(150,Math.abs(s)*.5),p=s>0?a-l:a+l;await this.drag(re/2,a,re/2,p,10,16)}}return}await this.swipe(n,250),await f(500)}throw new Error(`scrollUntilVisible: "${e.element}" not found`)}async extendedWaitUntil(e){let t=Date.now()+K(e.timeout||ee);for(;Date.now()<t;){let r=e.visible?await this.isElementVisible(typeof e.visible=="string"?{text:e.visible}:e.visible):!0,n=e.notVisible?!await this.isElementVisible(typeof e.notVisible=="string"?{text:e.notVisible}:e.notVisible):!0;if(r&&n)return;await f(200)}throw new Error("extendedWaitUntil timed out")}async reloadGuestApp(e){if(e){let n=!1;for(let o=0;o<3&&!n;o++)try{n=await this.evaluate(me(!0),2e4)}catch{await f(1e3)}n||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(me(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=Ut(e,"resetRuntime");if(!this.firstLaunchDone&&!t)this.firstLaunchDone=!0,r?(await this.launchShellAppFromHomeIfNeeded(e)&&await this.waitForTree(12e4),await this.softReloadGuestApp(!1),await this.waitForTree(12e4)):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(n){console.warn(` warn: onAfterLaunch hook threw: ${n instanceof Error?n.message:n}`)}this.profilingEnabled&&await this.startProfile(),this.recordingEnabled&&(await this.waitForVisualSettle(),await this.ensureRecordingStarted())}async waitForVisualSettle(){try{await this.evaluate(`new Promise((resolve) => {
445
447
  requestAnimationFrame(() => {
446
448
  requestAnimationFrame(() => {
447
449
  requestAnimationFrame(() => {
@@ -449,7 +451,7 @@ process.stdin.on('end', async () => {
449
451
  })
450
452
  })
451
453
  })
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(Ie(e)){let r=z(e,"appId")||z(e,"id");if(r)return r}return Ut(t)||"connect"}async waitForShellAppLaunched(e,t){let r=Date.now()+t,n=null;for(;Date.now()<r;){try{n=await G(this.bridge)}catch{n=null}if(n?.state==="app"&&n.activeApp===e&&n.showSwitcher===!1&&typeof n.launchProgress=="number"&&n.launchProgress>=.98)return;await f(16)}}async waitForShellHome(e){let t=Date.now()+e;for(;Date.now()<t;){let r=await G(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 G(this.bridge)}catch{return!1}if(r?.state!=="home"||r.activeApp!=null)return!1;let n=this.resolveShellLaunchAppId(e,r);return this.recordingEnabled&&await this.ensureRecordingStarted(),await me(this.bridge,"launchApp",1e3,n),await this.waitForShellAppLaunched(n,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
454
+ })`),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(Ee(e)){let r=q(e,"appId")||q(e,"id");if(r)return r}return Wt(t)||"connect"}async waitForShellAppLaunched(e,t){let r=Date.now()+t,n=null;for(;Date.now()<r;){try{n=await pe(this.bridge)}catch{n=null}if(n?.state==="app"&&n.activeApp===e&&n.showSwitcher===!1&&typeof n.launchProgress=="number"&&n.launchProgress>=.98)return;await f(16)}}async launchShellAppFromHomeIfNeeded(e){let t=null;try{t=await pe(this.bridge)}catch{return!1}if(t?.state!=="home"||t.activeApp!=null)return!1;let r=this.resolveShellLaunchAppId(e,t);return this.recordingEnabled&&await this.ensureRecordingStarted(),await qe(this.bridge,"launchApp",1e3,r),await this.waitForShellAppLaunched(r,1e3),!0}async startProfile(){let e=await this.evaluate(`(() => {
453
455
  if (!window.__sootsimShellPerf) {
454
456
  return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
455
457
  }
@@ -460,7 +462,7 @@ process.stdin.on('end', async () => {
460
462
  return { error: "shell frame profile unavailable (__sootsimShellPerf missing on the page)" }
461
463
  }
462
464
  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,r=await this.findElement(t);if(!r)throw new Error(`copyTextFrom: element not found: ${JSON.stringify(t)}`);let n=r.text??r.testID??"";this.js.setCopiedText(n),this.js.putEnv("maestroCopiedText",n),console.log(`[flow] copied text: ${JSON.stringify(n)}`)}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=S.resolve(this.opts.flowDir,t.file),n=v.readFileSync(r,"utf8");this.js.evaluate(n,{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?ut(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),n=r?r[1]:void 0;return!!(n&&typeof n=="object"&&"optional"in n&&n.optional)}async runStep(e,t){let r=typeof e=="string"?pt(e):e,n=Object.keys(r).find(l=>l!=="when")||Object.keys(r)[0];console.log(`[flow] step ${t+1}: ${n}`);let o=Date.now(),a=this.flowStepTargetLabel(r,n),s;try{s=this.js.interpolateStep(r),a=this.flowStepTargetLabel(s,n)??a}catch(l){if(this.isOptional(r)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:r[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,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:n,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),p=1e4,u=this.runStepInner(s),m;if(l){let g=await u;typeof g=="string"&&(m=g)}else{let g=null,P=new Promise((k,H)=>{g=setTimeout(()=>{H(new Error(`step watchdog: ${n} made no progress in ${p}ms \u2014 bridge or bundle probably hung`))},p)});try{let k=await Promise.race([u,P]);typeof k=="string"&&(m=k)}finally{g&&clearTimeout(g)}}let b=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!b&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"success",screenshotPath:m})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:s[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,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)return this.takeScreenshot(e.takeScreenshot);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 n=e.repeat.when??e.repeat.condition,o=async()=>n?this.evaluateWhen(n):!0,a=n?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,n=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&&!n)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=S.resolve(this.opts.flowDir,r),l=v.readFileSync(s,"utf8"),p=this.opts.flowDir;this.opts.flowDir=S.dirname(s);try{await this.runFlow(Jt(l))}finally{this.opts.flowDir=p}}else if(n)for(let s=0;s<n.length;s++)await this.runStep(n[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}}liveStatus=null;async runFlow(e){let t=[],r=[],n=[];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}n.push(a)}if(this.liveStatus&&await this.liveStatus.plan(n.map((a,s)=>{let l=typeof a=="string"?pt(a):a,p=Object.keys(l).find(u=>u!=="when")??Object.keys(l)[0];return{index:s,name:p,target:this.flowStepTargetLabel(l,p)}})),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(n)}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],n=typeof r.wait=="number"?r.wait:0,o=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,a=typeof r.extendedWaitUntil?.timeout=="number"?r.extendedWaitUntil.timeout:0,s=Math.max(6e4,n+15e3,q(o)+15e3,q(a)+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let l=Date.now(),p=async(u,m)=>{if(!this.liveStatus)return;let b=this.flowTraceSteps[this.flowTraceSteps.length-1],g=b&&b.stepIndex===t&&b.startedAtMs>=l;await this.liveStatus.step(t,u?"failure":g&&b.status==="skipped"?"skipped":"success",{durationMs:Date.now()-l,error:u?m instanceof Error?m.message.slice(0,300):String(m).slice(0,300):g&&b.error||void 0})};try{r.runFlow||r.launchApp?await this.runStep(r,t):await Promise.race([this.runStep(r,t),new Promise((u,m)=>setTimeout(()=>m(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}catch(u){let m=this.flowTraceSteps[this.flowTraceSteps.length-1];if(!(m&&m.stepIndex===t&&m.startedAtMs>=l)){let b=Object.keys(r)[0];this.lastFailedStep={index:t,kind:b,target:r[b]},this.recordFlowTraceStep({stepIndex:t,stepName:b,targetLabel:this.flowStepTargetLabel(r,b),startedAtMs:l,status:"failure",error:u})}throw await p(!0,u),u}await p(!1)}}};function Gt(i){if(typeof i!="object"||i==null||!("control"in i))return!1;let e=i.control;return typeof e=="object"&&e!=null&&"paused"in e&&e.paused===!0}var oe=class{constructor(e,t,r){this.bridge=e;this.flowName=t;this.getSimId=r}disabled=!1;paused=!1;lastSimId;plannedSteps=null;completedSteps=new Map;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async send(e,t){let r=await this.bridge.send({type:"flowStatus",simId:t,status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=Gt(r)}async push(e){if(!this.disabled)try{let t=this.getSimId?.();if(t!==this.lastSimId&&this.lastSimId!=null&&this.plannedSteps&&e.phase!=="plan"){await this.send({phase:"plan",state:"running",steps:this.plannedSteps},t);for(let r of this.completedSteps.values())await this.send({phase:"step",state:"running",step:r},t)}this.lastSimId=t,await this.send(e,t)}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){this.plannedSteps=e.map(t=>({...t})),this.completedSteps.clear(),await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,r){let n={index:e,status:t,...r};await this.push({phase:"step",state:"running",step:n}),this.completedSteps.set(e,n)}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 Fe=null;function Hr(){return Fe}var $e=[];function Ur(){return $e}async function zt(i){if(!i)return"";let e=i.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let r=(await Ue()).find(n=>n.name.toLowerCase()===e.toLowerCase());return r?String(r.preferredPort):e}async function Yt(){let i=await We(),e=i.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=i[0];return t?`http://localhost:${t.port}/__soot/`:null}async function ft(i){Fe=null,$e=[],(i.length===0||i.includes("--help")||i.includes("-h"))&&(console.log(`
465
+ })()`);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 n=r.text??r.testID??"";this.js.setCopiedText(n),this.js.putEnv("maestroCopiedText",n),console.log(`[flow] copied text: ${JSON.stringify(n)}`)}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=S.resolve(this.opts.flowDir,t.file),n=v.readFileSync(r,"utf8");this.js.evaluate(n,{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?pt(e.true):!0}isOptional(e){if(e.optional===!0)return!0;let r=Object.entries(e).find(([o])=>o!=="when"&&o!=="optional"),n=r?r[1]:void 0;return!!(n&&typeof n=="object"&&"optional"in n&&n.optional)}async runStep(e,t){let r=typeof e=="string"?ht(e):e,n=Object.keys(r).find(l=>l!=="when")||Object.keys(r)[0];console.log(`[flow] step ${t+1}: ${n}`);let o=Date.now(),a=this.flowStepTargetLabel(r,n),s;try{s=this.js.interpolateStep(r),a=this.flowStepTargetLabel(s,n)??a}catch(l){if(this.isOptional(r)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:r[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,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:n,targetLabel:a,startedAtMs:o,status:"skipped"});return}try{let l=!!(s.extendedWaitUntil||s.waitFor||s.scrollUntilVisible||s.launchApp||s.runFlow||s.runScript),p=1e4,u=this.runStepInner(s),g;if(l){let m=await u;typeof m=="string"&&(g=m)}else{let m=null,k=new Promise((P,H)=>{m=setTimeout(()=>{H(new Error(`step watchdog: ${n} made no progress in ${p}ms \u2014 bridge or bundle probably hung`))},p)});try{let P=await Promise.race([u,k]);typeof P=="string"&&(g=P)}finally{m&&clearTimeout(m)}}let b=!!(s.assertVisible||s.assertNotVisible||s.extendedWaitUntil||s.waitFor);this.stepDelay>0&&!b&&await f(this.stepDelay),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"success",screenshotPath:g})}catch(l){if(this.isOptional(s)){console.log(`[flow] (optional, skipped: ${l.message.slice(0,80)})`),this.recordFlowTraceStep({stepIndex:t,stepName:n,targetLabel:a,startedAtMs:o,status:"skipped",error:l});return}throw this.lastFailedStep={index:t,kind:n,target:s[n]},this.recordFlowTraceStep({stepIndex:t,stepName:n,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)return this.takeScreenshot(e.takeScreenshot);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 n=e.repeat.when??e.repeat.condition,o=async()=>n?this.evaluateWhen(n):!0,a=n?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,n=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&&!n)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=S.resolve(this.opts.flowDir,r),l=v.readFileSync(s,"utf8"),p=this.opts.flowDir;this.opts.flowDir=S.dirname(s);try{await this.runFlow(Gt(l))}finally{this.opts.flowDir=p}}else if(n)for(let s=0;s<n.length;s++)await this.runStep(n[s],s)}finally{this.js.leaveEnvScope()}}else throw new Error(`unsupported flow step: ${JSON.stringify(e)}`)}}liveStatus=null;async runFlow(e){let t=[],r=[],n=[];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}n.push(a)}if(this.liveStatus&&await this.liveStatus.plan(n.map((a,s)=>{let l=typeof a=="string"?ht(a):a,p=Object.keys(l).find(u=>u!=="when")??Object.keys(l)[0];return{index:s,name:p,target:this.flowStepTargetLabel(l,p)}})),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(n)}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],n=typeof r.wait=="number"?r.wait:0,o=typeof r.waitFor?.timeout=="number"?r.waitFor.timeout:0,a=typeof r.extendedWaitUntil?.timeout=="number"?r.extendedWaitUntil.timeout:0,s=Math.max(6e4,n+15e3,K(o)+15e3,K(a)+15e3);this.liveStatus&&(await this.liveStatus.waitWhilePaused(),await this.liveStatus.step(t,"running"));let l=Date.now(),p=async(u,g)=>{if(!this.liveStatus)return;let b=this.flowTraceSteps[this.flowTraceSteps.length-1],m=b&&b.stepIndex===t&&b.startedAtMs>=l;await this.liveStatus.step(t,u?"failure":m&&b.status==="skipped"?"skipped":"success",{durationMs:Date.now()-l,error:u?g instanceof Error?g.message.slice(0,300):String(g).slice(0,300):m&&b.error||void 0})};try{r.runFlow||r.launchApp?await this.runStep(r,t):await Promise.race([this.runStep(r,t),new Promise((u,g)=>setTimeout(()=>g(new Error(`step ${t+1} (${Object.keys(r)[0]}) exceeded ${s}ms deadline`)),s))])}catch(u){let g=this.flowTraceSteps[this.flowTraceSteps.length-1];if(!(g&&g.stepIndex===t&&g.startedAtMs>=l)){let b=Object.keys(r)[0];this.lastFailedStep={index:t,kind:b,target:r[b]},this.recordFlowTraceStep({stepIndex:t,stepName:b,targetLabel:this.flowStepTargetLabel(r,b),startedAtMs:l,status:"failure",error:u})}throw await p(!0,u),u}await p(!1)}}};function Kt(i){if(typeof i!="object"||i==null||!("control"in i))return!1;let e=i.control;return typeof e=="object"&&e!=null&&"paused"in e&&e.paused===!0}var ie=class{constructor(e,t,r){this.bridge=e;this.flowName=t;this.getSimId=r}disabled=!1;paused=!1;lastSimId;plannedSteps=null;completedSteps=new Map;runId=`flr_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;async send(e,t){let r=await this.bridge.send({type:"flowStatus",simId:t,status:{runId:this.runId,flowName:this.flowName,...e}});this.paused=Kt(r)}async push(e){if(!this.disabled)try{let t=this.getSimId?.();if(t!==this.lastSimId&&this.lastSimId!=null&&this.plannedSteps&&e.phase!=="plan"){await this.send({phase:"plan",state:"running",steps:this.plannedSteps},t);for(let r of this.completedSteps.values())await this.send({phase:"step",state:"running",step:r},t)}this.lastSimId=t,await this.send(e,t)}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){this.plannedSteps=e.map(t=>({...t})),this.completedSteps.clear(),await this.push({phase:"plan",state:"running",steps:e})}async step(e,t,r){let n={index:e,status:t,...r};await this.push({phase:"step",state:"running",step:n}),this.completedSteps.set(e,n)}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 Ie=null;function Ur(){return Ie}var Fe=[];function Wr(){return Fe}async function Yt(i){if(!i)return"";let e=i.trim();if(!e)return"";if(/^\d+$/.test(e)||e.startsWith("http://")||e.startsWith("https://"))return e;let r=(await He()).find(n=>n.name.toLowerCase()===e.toLowerCase());return r?String(r.preferredPort):e}async function Zt(){let i=await Ue(),e=i.find(r=>r.patched);if(e)return`http://localhost:${e.port}/__soot/`;let t=i[0];return t?`http://localhost:${t.port}/__soot/`:null}async function mt(i){Ie=null,Fe=[],(i.length===0||i.includes("--help")||i.includes("-h"))&&(console.log(`
464
466
  sootsim maestro \u2014 author and run Maestro YAML flows
465
467
 
466
468
  usage:
@@ -540,28 +542,28 @@ flow extension:
540
542
  takeScreenshot:
541
543
  path: marketing/hero
542
544
  withFrame: true
543
- `),process.exit(0));let e=i[0];$.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>i.find((d,y)=>i[y-1]===h),r=i.includes("--profile"),n=i.includes("--headed"),o=i.includes("--new")||n,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",p=i.includes("--no-shell")?"tenant":i.includes("--shell-only")?"shell":void 0,u=t("--device")?.trim()||"",m=i.includes("--slow")?+(t("--slow")||"500"):0,b=i.includes("--electron"),g=i.includes("--preview"),P=await ot(t("--preview-origin")),k=t("--preview-public-origin"),H=i.includes("--preview-open"),Pe=t("--owner")?.trim()||"",ke=t("--repo")?.trim()||"",U=t("--billing-kind")?.trim()||"",mt=g?`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:${qt()}`}:flow:${Kt("sha256").update(w.relative(process.cwd(),w.resolve(e))).digest("hex").slice(0,16)}`:"";U&&U!=="test_run"&&(console.error(` error: invalid --billing-kind: ${U}`),process.exit(1));let gt=i.flatMap((h,d)=>i[d-1]==="--replace"?["--replace",h]:[]),wt=i.flatMap((h,d)=>i[d-1]==="--remap"?["--remap",h]:[]),M=i.includes("--record")||g,yt=i.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):M?g?6e3:2e3:0,bt=$.readFileSync(e,"utf8"),{frontmatter:T,steps:R}=we(bt);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let W=u||T.device||"",Ae=T.theme||"",Z=b||T.electron===!0,St=T.app===void 0||T.app===null?"":typeof T.app=="number"?String(T.app):T.app,se=await zt(St),Me={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"]},x=he(i,Me),vt=t("--url")||"";Z&&!ze()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let Re=Z?"desktop companion":"bridge",xt=se?` | target: ${se}`:"";console.log(`
545
+ `),process.exit(0));let e=i[0];$.existsSync(e)||(console.error(` error: ${e} not found`),process.exit(1));let t=h=>i.find((d,y)=>i[y-1]===h),r=i.includes("--profile"),n=i.includes("--headed"),o=i.includes("--new")||n,a=t("--out")||"/tmp/sootsim-recordings",s=t("--screenshots")||(t("--out")?a:"/tmp/sootsim-flow"),l=t("--screenshot-paths")==="flow"?"flow":"dir",p=i.includes("--no-shell")?"tenant":i.includes("--shell-only")?"shell":void 0,u=t("--device")?.trim()||"",g=i.includes("--slow")?+(t("--slow")||"500"):0,b=i.includes("--electron"),m=i.includes("--preview"),k=m?await st(t("--preview-origin")):"",P=t("--preview-public-origin"),H=i.includes("--preview-open"),$e=t("--owner")?.trim()||"",ke=t("--repo")?.trim()||"",U=t("--billing-kind")?.trim()||"",gt=m?`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:${zt()}`}:flow:${qt("sha256").update(w.relative(process.cwd(),w.resolve(e))).digest("hex").slice(0,16)}`:"";U&&U!=="test_run"&&(console.error(` error: invalid --billing-kind: ${U}`),process.exit(1));let wt=i.flatMap((h,d)=>i[d-1]==="--replace"?["--replace",h]:[]),yt=i.flatMap((h,d)=>i[d-1]==="--remap"?["--remap",h]:[]),M=i.includes("--record")||m,bt=i.includes("--tail-wait")?Math.max(0,+(t("--tail-wait")||"2000")):M?m?6e3:2e3:0,St=$.readFileSync(e,"utf8"),{frontmatter:T,steps:R}=ge(St);R.length===0&&(console.error(" error: flow file must contain a YAML array of steps"),process.exit(1));let W=u||T.device||"",Pe=T.theme||"",Y=b||T.electron===!0,vt=T.app===void 0||T.app===null?"":typeof T.app=="number"?String(T.app):T.app,oe=await Yt(vt),Ae={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"]},x=he(i,Ae),xt=t("--url")||"";Y&&!Ye()&&(console.error(" error: desktop companion not found. install or build it first with `bun run build:electron`"),process.exit(1));let Me=Y?"desktop companion":"bridge",Tt=oe?` | target: ${oe}`:"";console.log(`
544
546
  sootsim maestro \u2014 ${w.basename(e)}
545
- ${R.length} steps | ${Re}${xt}${M?" | recording":""}${r?" | profiling":""}${m?` | ${m}ms delay`:""}
546
- `),g&&Be({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:R.length,mode:Re,electron:Z,record:M,profile:r,previewOrigin:P}});let A=vt||se||"",ae=o||Z&&x.simIdSource!=="flag",_e=t("--driver")||"",le=!1,de=new Set,Oe=!1;if(!A&&!ae&&x.simIdSource==="none"){let h=Ke(x);try{let d=await h.listSims(),y=d.find(D=>D.isPrimary&&D.readyState==="open"),F=d.find(D=>D.readyState==="open"),J=y??F;J&&(Oe=!0,console.log(` reusing active sim: ${J.id}`))}catch{}finally{h.close()}}if(!A&&!Oe&&(ae||x.simIdSource==="none")){let h=await Yt();h||(console.error(" error: no current sim and no sootsim target found"),await ue(),process.exit(1)),A=h}if(A&&W){let h=new URL(await Ye(A));h.searchParams.set("device",W),A=h.toString()}if(A){let h=[A];if(h.push(...gt),h.push(...wt),ae&&h.push("--new"),h.push("--no-describe"),x.simIdSource==="flag"&&x.simId&&h.push("--sim",x.simId),_e&&(h.push("--driver",_e),le=!0),i.includes("--headless")&&!n&&h.push("--headless"),await Xe(h,{port:x.wsPort,timeoutMs:x.commandTimeoutMs}),le){let d=pe();d&&de.add(d)}}let B=he(i,Me),X=B.simIdSource==="flag"?B.simId:pe()||B.simId,Tt=B.simIdSource==="flag"?"flag":X?"saved":"none",E=fe(B.wsPort,{commandTimeoutMs:B.commandTimeoutMs,simId:X,simIdSource:Tt}),c,De=async()=>{let h=T.env?.SOOTSIM_STATUS_BAR_TIME;if(h){if(!/^(?:[1-9]|1[0-2]):[0-5][0-9]$/.test(h))throw new Error("SOOTSIM_STATUS_BAR_TIME must be a 12-hour time such as 9:41");await E.send({type:"evaluate",simId:c.simId,code:`window.dispatchEvent(new CustomEvent('sootsim:statusBarOverride', { detail: { time: ${JSON.stringify(h)} } }))`})}if(Ae&&await E.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["colorScheme",Ae]}),!W)return!1;let d=await E.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof d=="string"&&d.length>0){let y=new URL(d);y.searchParams.set("device",W),c.setSimRouteHint(y.toString())}return!!await E.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",W]})};if(c=new ie(E,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:p,simId:X,recordingOutputDir:M?a:void 0,recordingFormat:g?"mp4":"webm",billingOriginOverride:g?P:void 0,allowGitHubRecording:g,requireRecordingEntitlement:g,onAfterLaunch:async()=>{await De()&&await c.waitForTree(12e4),g&&await E.send({type:"evaluate",simId:c.simId,code:`(() => {
547
+ ${R.length} steps | ${Me}${Tt}${M?" | recording":""}${r?" | profiling":""}${g?` | ${g}ms delay`:""}
548
+ `),m&&De({event:"preview_flow_started",properties:{flowName:w.basename(e),stepCount:R.length,mode:Me,electron:Y,record:M,profile:r,previewOrigin:k}});let A=xt||oe||"",se=o||Y&&x.simIdSource!=="flag",Re=t("--driver")||"",ae=!1,le=new Set,_e=!1;if(!A&&!se&&x.simIdSource==="none"){let h=Ke(x);try{let d=await h.listSims(),y=d.find(D=>D.isPrimary&&D.readyState==="open"),F=d.find(D=>D.readyState==="open"),J=y??F;J&&(_e=!0,console.log(` reusing active sim: ${J.id}`))}catch{}finally{h.close()}}if(!A&&!_e&&(se||x.simIdSource==="none")){let h=await Zt();h||(console.error(" error: no current sim and no sootsim target found"),await ce(),process.exit(1)),A=h}if(A&&W){let h=new URL(await Ze(A));h.searchParams.set("device",W),A=h.toString()}if(A){let h=[A];if(h.push(...wt),h.push(...yt),se&&h.push("--new"),h.push("--no-describe"),x.simIdSource==="flag"&&x.simId&&h.push("--sim",x.simId),Re&&(h.push("--driver",Re),ae=!0),i.includes("--headless")&&!n&&h.push("--headless"),await Qe(h,{port:x.wsPort,timeoutMs:x.commandTimeoutMs}),ae){let d=ue();d&&le.add(d)}}let B=he(i,Ae),Z=B.simIdSource==="flag"?B.simId:ue()||B.simId,Et=B.simIdSource==="flag"?"flag":Z?"saved":"none",E=fe(B.wsPort,{commandTimeoutMs:B.commandTimeoutMs,simId:Z,simIdSource:Et}),c,Oe=async()=>{let h=T.env?.SOOTSIM_STATUS_BAR_TIME;if(h){if(!/^(?:[1-9]|1[0-2]):[0-5][0-9]$/.test(h))throw new Error("SOOTSIM_STATUS_BAR_TIME must be a 12-hour time such as 9:41");await E.send({type:"evaluate",simId:c.simId,code:`window.dispatchEvent(new CustomEvent('sootsim:statusBarOverride', { detail: { time: ${JSON.stringify(h)} } }))`})}if(Pe&&await E.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["colorScheme",Pe]}),!W)return!1;let d=await E.send({type:"evaluate",simId:c.simId,code:"window.location.href"});if(typeof d=="string"&&d.length>0){let y=new URL(d);y.searchParams.set("device",W),c.setSimRouteHint(y.toString())}return!!await E.send({type:"call",simId:c.simId,path:"SootSim.bridges.settings.set",args:["deviceModel",W]})};if(c=new ne(E,{screenshotDir:s,flowDir:w.dirname(w.resolve(e)),screenshotPathMode:l,screenshotLayers:p,simId:Z,recordingOutputDir:M?a:void 0,recordingFormat:m?"mp4":"webm",billingOriginOverride:m?k:void 0,allowGitHubRecording:m,requireRecordingEntitlement:m,onAfterLaunch:async()=>{await Oe()&&await c.waitForTree(12e4),m&&await E.send({type:"evaluate",simId:c.simId,code:`(() => {
547
549
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
548
550
  return r?.start?.() ?? false
549
- })()`})}}),m&&(c.stepDelay=m),c.liveStatus=new oe(E,w.basename(e),()=>c.simId),c.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),T.env&&typeof T.env=="object")for(let[h,d]of Object.entries(T.env))c.js.putEnv(h,d);let _=null,I=null,L=null,O=null,j=null,ce=null,V=0,Q=!!R[0]?.launchApp;try{Q||await c.waitForTree(12e4),await De()&&!Q&&await c.waitForTree(12e4),g&&!Q&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),M&&(Q?c.prepareRecording():await c.startRecording()),r&&await c.startProfile(),g&&(await E.send({type:"evaluate",simId:c.simId,code:`(() => {
551
+ })()`})}}),g&&(c.stepDelay=g),c.liveStatus=new ie(E,w.basename(e),()=>c.simId),c.js.putEnv("MAESTRO_FILENAME",w.basename(e,w.extname(e))),T.env&&typeof T.env=="object")for(let[h,d]of Object.entries(T.env))c.js.putEnv(h,d);let _=null,I=null,L=null,O=null,j=null,de=null,V=0,X=!!R[0]?.launchApp;try{X||await c.waitForTree(12e4),await Oe()&&!X&&await c.waitForTree(12e4),m&&!X&&!process.env.SOOTSIM_PREVIEW_RESET_DONE&&await c.launchApp({clearState:!0}),M&&(X?c.prepareRecording():await c.startRecording()),r&&await c.startProfile(),m&&(await E.send({type:"evaluate",simId:c.simId,code:`(() => {
550
552
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
551
553
  return r?.start?.() ?? false
552
- })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(R),r&&(_=await c.stopProfile()),await c.waitForRecordingTail({maxMs:yt,smart:g}),M&&(I=await c.stopRecording(),L=c.getLastRecordingDurationMs()),g&&(O=await E.send({type:"evaluate",simId:c.simId,code:`(() => {
554
+ })()`})||console.warn(" warn: eventRecorder.start() returned false \u2014 preview will upload bundle without replay events")),await c.runFlow(R),r&&(_=await c.stopProfile()),await c.waitForRecordingTail({maxMs:bt,smart:m}),M&&(I=await c.stopRecording(),L=c.getLastRecordingDurationMs()),m&&(O=await E.send({type:"evaluate",simId:c.simId,code:`(() => {
553
555
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
554
556
  return r?.stop?.() ?? []
555
557
  })()`}),console.log(` captured ${O.length} replay events`),j=w.join(s,"preview-final.png"),await c.captureScreenshot(j),console.log(` final screenshot: ${j}`));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}`),_&&ht(_),I&&console.log(` video: ${I}`),console.log()}catch(h){if(r&&!_)try{_=await c.stopProfile()}catch{}if(M&&!I)try{I=await c.stopRecording(),L=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}if(g&&!O)try{O=await E.send({type:"evaluate",simId:c.simId,code:`(() => {
558
+ + completed (${R.length} steps)`),d>0&&console.log(` screenshots: ${d} \u2192 ${s}`),_&&ft(_),I&&console.log(` video: ${I}`),console.log()}catch(h){if(r&&!_)try{_=await c.stopProfile()}catch{}if(M&&!I)try{I=await c.stopRecording(),L=c.getLastRecordingDurationMs()}catch(d){console.warn(` recording stop failed: ${d?.message||String(d)}`)}if(m&&!O)try{O=await E.send({type:"evaluate",simId:c.simId,code:`(() => {
557
559
  const r = window.SootSim?.bridges?.eventRecorder ?? window.__sootsimEventRecorder
558
560
  return r?.stop?.() ?? []
559
561
  })()`}),console.log(` captured ${O.length} partial replay events`)}catch(d){console.warn(` event recorder stop failed: ${d?.message||String(d)}`)}console.error(`
560
562
  x failed: ${h.message}
561
- `),_&&(console.log(" partial profile:"),ht(_)),I&&console.log(` partial video: ${I}`);try{let d=c.lastFailedStep,y=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",F=w.join(s,y);await c.captureFailureBundle(F,{error:h,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),ce=F,console.log(` failure bundle: ${F}`),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.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await qe(E,{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}`:""}`}),V=1}if(await c.liveStatus?.end(V===0?"passed":"failed"),g&&(V===0||I||O))try{let h=await Xt(O??[]),d=["--origin",P,"--events",h];k&&d.push("--public-origin",k),I&&d.push("--video",I),j&&d.push("--screenshot",j),I&&L&&Number.isFinite(L)&&(d.push("--video-duration-ms",String(Math.round(L))),d.push("--recorded-duration-ms",String(Math.round(L))));let y=c.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&d.push("--recording-started-at-ms",String(Math.round(y))),x.wsPort&&d.push("--port",String(x.wsPort)),c.simId&&d.push("--sim",c.simId),H&&d.push("--open"),Pe&&d.push("--owner",Pe),ke&&d.push("--repo",ke),d.push("--run-scope",mt),U&&d.push("--billing-kind",U),console.log(`
562
- preparing preview upload\u2026`);let F=c.getFlowTraceSteps();F.length>0&&d.push("--timeline-events",await Qt(F));let J=await er(F,y);J&&d.push("--snapshot-manifest",J),ce&&d.push("--failure-bundle",ce);let D=c.getLastRecordingFrameStats();D&&d.push("--trace-frame-stats",await tr(D));let{runUpload:Et}=await import("./upload-RBH4XGJ2.js");Fe=await Et(d,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),V=1}return $e=c.getFlowTraceSteps(),E.close(),le?(c.simId&&de.add(c.simId),await Zt(x.wsPort,x.commandTimeoutMs,[...de])):c.simId&&c.simId!==X&&He(c.simId),await ue(),V}async function Zt(i,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let n=fe(i,{commandTimeoutMs:e});try{let o=await n.listSims(),a=r.filter(l=>o.some(p=>p.id===l&&p.readyState==="open"));if(a.length===0)return;let s=await Qe(n,i,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{n.close()}}async function Xt(i){let{gzipSync:e}=await import("zlib"),t=i.map(o=>JSON.stringify(o)).join(`
563
+ `),_&&(console.log(" partial profile:"),ft(_)),I&&console.log(` partial video: ${I}`);try{let d=c.lastFailedStep,y=d?`step-${String(d.index+1).padStart(2,"0")}-${d.kind}`:"unstaged",F=w.join(s,y);await c.captureFailureBundle(F,{error:h,stepIndex:d?.index,stepKind:d?.kind,stepTarget:d?.target}),de=F,console.log(` failure bundle: ${F}`),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.captureScreenshot(y),console.log(` error screenshot: ${y}`)}catch{}console.log(` (failure bundle capture failed: ${d instanceof Error?d.message:String(d)})`)}await ze(E,{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}`:""}`}),V=1}if(await c.liveStatus?.end(V===0?"passed":"failed"),m&&(V===0||I||O))try{let h=await Qt(O??[]),d=["--origin",k,"--events",h];P&&d.push("--public-origin",P),I&&d.push("--video",I),j&&d.push("--screenshot",j),I&&L&&Number.isFinite(L)&&(d.push("--video-duration-ms",String(Math.round(L))),d.push("--recorded-duration-ms",String(Math.round(L))));let y=c.getLastRecordingStartedAtMs();y&&Number.isFinite(y)&&d.push("--recording-started-at-ms",String(Math.round(y))),x.wsPort&&d.push("--port",String(x.wsPort)),c.simId&&d.push("--sim",c.simId),H&&d.push("--open"),$e&&d.push("--owner",$e),ke&&d.push("--repo",ke),d.push("--run-scope",gt),U&&d.push("--billing-kind",U),console.log(`
564
+ preparing preview upload\u2026`);let F=c.getFlowTraceSteps();F.length>0&&d.push("--timeline-events",await er(F));let J=await tr(F,y);J&&d.push("--snapshot-manifest",J),de&&d.push("--failure-bundle",de);let D=c.getLastRecordingFrameStats();D&&d.push("--trace-frame-stats",await rr(D));let{runUpload:It}=await import("./upload-JABM3ITZ.js");Ie=await It(d,{})}catch(h){console.error(` preview upload failed: ${h?.message||h}`),V=1}return Fe=c.getFlowTraceSteps(),E.close(),ae?(c.simId&&le.add(c.simId),await Xt(x.wsPort,x.commandTimeoutMs,[...le])):c.simId&&c.simId!==Z&&Ce(c.simId),await ce(),V}async function Xt(i,e,t){let r=[...new Set(t.filter(Boolean))];if(r.length===0)return;let n=fe(i,{commandTimeoutMs:e});try{let o=await n.listSims(),a=r.filter(l=>o.some(p=>p.id===l&&p.readyState==="open"));if(a.length===0)return;let s=await et(n,i,e,a);await Xe(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{n.close()}}async function Qt(i){let{gzipSync:e}=await import("zlib"),t=i.map(o=>JSON.stringify(o)).join(`
563
565
  `)+(i.length?`
564
- `:""),r=e(Buffer.from(t,"utf8")),n=w.join(Y(),`sootsim-events-${Date.now()}.jsonl.gz`);return $.writeFileSync(n,r),console.log(` events: ${i.length} written to ${n} (${r.length} bytes gz)`),n}async function Qt(i){let{gzipSync:e}=await import("zlib"),t=i.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(`
566
+ `:""),r=e(Buffer.from(t,"utf8")),n=w.join(z(),`sootsim-events-${Date.now()}.jsonl.gz`);return $.writeFileSync(n,r),console.log(` events: ${i.length} written to ${n} (${r.length} bytes gz)`),n}async function er(i){let{gzipSync:e}=await import("zlib"),t=i.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
567
  `)+`
566
- `,n=e(Buffer.from(r,"utf8")),o=w.join(Y(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return $.writeFileSync(o,n),console.log(` flow trace: ${t.length} step events written to ${o} (${n.length} bytes gz)`),o}async function er(i,e){if(!e)return null;let t=i.flatMap(n=>n.screenshotPath?[{id:`flow-step-${n.stepIndex}`,label:n.targetLabel??`Step ${n.stepIndex+1}`,kind:"interaction",t:Math.max(0,n.endedAtMs-e),path:n.screenshotPath}]:[]);if(t.length===0)return null;let r=w.join(Y(),`sootsim-flow-snapshots-${Date.now()}.json`);return $.writeFileSync(r,JSON.stringify(t)),console.log(` flow snapshots: ${t.length} written to ${r}`),r}async function tr(i){let e=w.join(Y(),`sootsim-frame-stats-${Date.now()}.json`);return $.writeFileSync(e,JSON.stringify(i)),console.log(` frame stats: written to ${e}`),e}async function rr(i){let e=i[0],t=r=>i.find((n,o)=>i[o-1]===r);switch(e){case"start":{let{path:r,state:n}=tt();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${n.steps.length}`);return}case"keep":case"good":{let r=Se();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")||(i[1]&&!i[1].startsWith("-")?i[1]:void 0),n=i.includes("--validate")||i.includes("--video"),o=i.includes("--video"),a=Se();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=rt(r||(n?ir():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(n){let l=or(i,s.outputPath),p=await ft(l);if(p!==0){console.error(`
567
- validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=p;return}be(),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(be(),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=i[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim maestro validate <path>"),process.exit(1));let n=ye(r);if(n.length>0){console.error(` x ${r} failed validation:`);for(let o of n)console.error(` - ${o}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function nr(i){return i[0]==="--sim"&&i.length>=2?[...i.slice(2),"--sim",i[1]]:i}async function Wr(i){let e=nr(i),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await rr(e),0;let r=await ft(e);return r!==0&&(process.exitCode=r),r}function ht(i){console.log(""),nt(i)}function ir(){return w.join(Y(),`sootsim-flow-draft-${Date.now()}.yaml`)}function or(i,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<i.length;r++){let n=i[r];if(!(n==="--validate"||n==="--video")){if(n==="--output"){r+=1;continue}r===1&&!n.startsWith("-")||t.push(n)}}return!t.includes("--record")&&i.includes("--video")&&t.push("--record"),t}export{dt as a,Rt as b,Hr as c,Ur as d,Yt as e,ft as f,nr as g,Wr as h};
568
+ `,n=e(Buffer.from(r,"utf8")),o=w.join(z(),`sootsim-flow-steps-${Date.now()}.jsonl.gz`);return $.writeFileSync(o,n),console.log(` flow trace: ${t.length} step events written to ${o} (${n.length} bytes gz)`),o}async function tr(i,e){if(!e)return null;let t=i.flatMap(n=>n.screenshotPath?[{id:`flow-step-${n.stepIndex}`,label:n.targetLabel??`Step ${n.stepIndex+1}`,kind:"interaction",t:Math.max(0,n.endedAtMs-e),path:n.screenshotPath}]:[]);if(t.length===0)return null;let r=w.join(z(),`sootsim-flow-snapshots-${Date.now()}.json`);return $.writeFileSync(r,JSON.stringify(t)),console.log(` flow snapshots: ${t.length} written to ${r}`),r}async function rr(i){let e=w.join(z(),`sootsim-frame-stats-${Date.now()}.json`);return $.writeFileSync(e,JSON.stringify(i)),console.log(` frame stats: written to ${e}`),e}async function nr(i){let e=i[0],t=r=>i.find((n,o)=>i[o-1]===r);switch(e){case"start":{let{path:r,state:n}=rt();console.log(" flow draft started"),console.log(` session: ${r}`),console.log(` steps: ${n.steps.length}`);return}case"keep":case"good":{let r=be();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")||(i[1]&&!i[1].startsWith("-")?i[1]:void 0),n=i.includes("--validate")||i.includes("--video"),o=i.includes("--video"),a=be();a.active&&a.kept&&console.log(` auto-kept trailing action: ${a.candidate.summary}`);let s=nt(r||(n?or():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(n){let l=sr(i,s.outputPath),p=await mt(l);if(p!==0){console.error(`
569
+ validation failed \u2014 draft preserved so you can keep iterating`),process.exitCode=p;return}ye(),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(ye(),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=i[1];(!r||r.startsWith("-"))&&(console.error(" usage: sootsim maestro validate <path>"),process.exit(1));let n=we(r);if(n.length>0){console.error(` x ${r} failed validation:`);for(let o of n)console.error(` - ${o}`);process.exit(1)}console.log(` + ${r} looks valid`);return}}}function ir(i){return i[0]==="--sim"&&i.length>=2?[...i.slice(2),"--sim",i[1]]:i}async function jr(i){let e=ir(i),t=e[0];if(t==="start"||t==="keep"||t==="good"||t==="end"||t==="validate")return await nr(e),0;let r=await mt(e);return r!==0&&(process.exitCode=r),r}function ft(i){console.log(""),it(i)}function or(){return w.join(z(),`sootsim-flow-draft-${Date.now()}.yaml`)}function sr(i,e){if(!e)throw new Error("validated flow draft requires an output path");let t=[e];for(let r=1;r<i.length;r++){let n=i[r];if(!(n==="--validate"||n==="--video")){if(n==="--output"){r+=1;continue}r===1&&!n.startsWith("-")||t.push(n)}}return!t.includes("--record")&&i.includes("--video")&&t.push("--record"),t}export{ct as a,_t as b,Ur as c,Wr as d,Zt as e,mt as f,ir as g,jr as h};