@testmuai/kane-cli 0.7.2 → 0.8.2

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 (230) hide show
  1. package/dist/ChatSurface-B3ULYDYC.js +8 -0
  2. package/dist/{ChromeProfilePicker-DGDWGCZD.js → ChromeProfilePicker-T77E7ZSC.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-SYCZXSME.js → CliFeedbackPrompt-FQ2XV5DZ.js} +1 -1
  4. package/dist/{CliUploadProgress-VDEAKXJY.js → CliUploadProgress-TZ55LONO.js} +1 -1
  5. package/dist/ConfigView-WWQMH36G.js +2 -0
  6. package/dist/EvidenceViewOffer-L5FVBQNK.js +2 -0
  7. package/dist/FolderPicker-6Z3CYSHF.js +2 -0
  8. package/dist/{HelpView-ON6BFGJM.js → HelpView-XXPCPJNF.js} +1 -1
  9. package/dist/{InfoBox-B23NZ6IG.js → InfoBox-SHBRHQX5.js} +1 -1
  10. package/dist/{LinksBox-TI26VFFH.js → LinksBox-ENNF7TDJ.js} +1 -1
  11. package/dist/{ProfilesView-CRO5AH3H.js → ProfilesView-CNF2FXF3.js} +1 -1
  12. package/dist/{ProjectPicker-3N7LJOXU.js → ProjectPicker-PVPLS642.js} +1 -1
  13. package/dist/{SaveSessionPrompt-UTOEC5AW.js → SaveSessionPrompt-4QP4GNGO.js} +1 -1
  14. package/dist/SingleShotApp-M3HNSUMZ.js +2 -0
  15. package/dist/{SummaryBox-JK64EKC2.js → SummaryBox-HYNINDNN.js} +1 -1
  16. package/dist/TestMdRunView-ISOVQ7YP.js +2 -0
  17. package/dist/{WhoamiView-6QSLPNF6.js → WhoamiView-NN2HOK6H.js} +1 -1
  18. package/dist/adbkit-apkreader-ORZBGCJQ.js +184 -0
  19. package/dist/app-client-ZCCNE3RV.js +2 -0
  20. package/dist/app-download-5UJMXPF3.js +2 -0
  21. package/dist/{auth-IKFVW3NX.js → auth-QKBTOWQX.js} +1 -1
  22. package/dist/{bind-KCUSVJXG.js → bind-LVGP5KHO.js} +3 -3
  23. package/dist/{bootstrap-NFYYRGGR.js → bootstrap-RUJBMB2P.js} +1 -1
  24. package/dist/bridge-QDPBIIOW.js +2 -0
  25. package/dist/{changelog-AAH2ZBYO.js → changelog-HBPBPR2O.js} +1 -1
  26. package/dist/{chat-committer-UUC6JTRJ.js → chat-committer-ZWWCLJFD.js} +1 -1
  27. package/dist/{chat-controller-T2FAI55V.js → chat-controller-R4THYYPU.js} +1 -1
  28. package/dist/chunk-2E3ZWGIK.js +12 -0
  29. package/dist/chunk-2KH2JUGL.js +13 -0
  30. package/dist/{chunk-VWKVUOXU.js → chunk-2TYCUPCN.js} +1 -1
  31. package/dist/{chunk-GYNTNKNB.js → chunk-2ZZDNPFN.js} +1 -1
  32. package/dist/chunk-3654GK6O.js +66 -0
  33. package/dist/{chunk-M6FKJKC6.js → chunk-3NHO5R4P.js} +3 -3
  34. package/dist/{chunk-SFII7HPP.js → chunk-4II6VDXG.js} +1 -1
  35. package/dist/chunk-4J6DQFPC.js +4 -0
  36. package/dist/chunk-4JOD47QI.js +2 -0
  37. package/dist/{chunk-5FJJJNJK.js → chunk-4U4OSOA4.js} +1 -1
  38. package/dist/{chunk-QIGPXYMF.js → chunk-56PAQAX5.js} +6 -6
  39. package/dist/chunk-5NIYYD7O.js +2 -0
  40. package/dist/chunk-5SNT2MK5.js +2 -0
  41. package/dist/chunk-6IA6QMPH.js +2 -0
  42. package/dist/chunk-6J5T5FEY.js +2 -0
  43. package/dist/chunk-6N726QLP.js +349 -0
  44. package/dist/chunk-7F2ZV46B.js +2 -0
  45. package/dist/{chunk-7OYZR6JA.js → chunk-7S3JZ6FQ.js} +1 -1
  46. package/dist/chunk-A2SQD2AY.js +4 -0
  47. package/dist/chunk-AJQT4IWZ.js +2 -0
  48. package/dist/chunk-AN2ZPHCE.js +2 -0
  49. package/dist/{chunk-7QJ75SYR.js → chunk-ATGRRKEV.js} +2 -2
  50. package/dist/chunk-AXTPNZPX.js +2 -0
  51. package/dist/{chunk-ZRASQ63J.js → chunk-BKVDAZEJ.js} +1 -1
  52. package/dist/{chunk-2WVKOZ6W.js → chunk-BPMSNGXQ.js} +1 -1
  53. package/dist/chunk-BRIEBB2U.js +2 -0
  54. package/dist/chunk-BSYX225I.js +2 -0
  55. package/dist/{chunk-B5RS2XZU.js → chunk-CAMO26QU.js} +3 -3
  56. package/dist/chunk-DPUV6OSP.js +2 -0
  57. package/dist/chunk-ECZMYPLJ.js +19 -0
  58. package/dist/chunk-EYOCNMUM.js +2 -0
  59. package/dist/{chunk-DZPGG4S6.js → chunk-FNS2EAA5.js} +2 -2
  60. package/dist/{chunk-VMM4LC4V.js → chunk-GNIFMQNK.js} +3 -3
  61. package/dist/chunk-GUVM6SZF.js +2 -0
  62. package/dist/{chunk-ZBOWFJB2.js → chunk-HFFPPCZO.js} +2 -2
  63. package/dist/chunk-HRZOFTV7.js +4 -0
  64. package/dist/chunk-HWH3UYD6.js +4 -0
  65. package/dist/{chunk-JKM2PUHI.js → chunk-I7RQS65W.js} +1 -1
  66. package/dist/chunk-IUEEFGEW.js +11 -0
  67. package/dist/{chunk-KWIK22R6.js → chunk-IV76ZXCY.js} +1 -1
  68. package/dist/{chunk-HYSFJSIG.js → chunk-IZ2FJYHG.js} +1 -1
  69. package/dist/{chunk-4NFCAGRK.js → chunk-J7KT44IC.js} +1 -1
  70. package/dist/{chunk-VOOPWFHW.js → chunk-JEDLXUO5.js} +1 -1
  71. package/dist/chunk-JGOZUAMC.js +2 -0
  72. package/dist/{chunk-4LTXE3IX.js → chunk-JHKM7W5X.js} +1 -1
  73. package/dist/chunk-JJN76EXE.js +2 -0
  74. package/dist/{chunk-EOLFTMWF.js → chunk-JUVQQP42.js} +1 -1
  75. package/dist/chunk-KKRNTSLL.js +6 -0
  76. package/dist/chunk-KRKGZ2ZW.js +47 -0
  77. package/dist/{chunk-YTHQNN2L.js → chunk-LDCLZR2U.js} +1 -1
  78. package/dist/chunk-LQQXPY5B.js +4 -0
  79. package/dist/{chunk-UC7MNPIN.js → chunk-LVCY5IYI.js} +1 -1
  80. package/dist/{chunk-O75ZHGJG.js → chunk-LVN6VHFN.js} +1 -1
  81. package/dist/chunk-MMBBQ4OZ.js +2 -0
  82. package/dist/chunk-MSGW4JDG.js +2 -0
  83. package/dist/{chunk-VLWMMOMF.js → chunk-MTIC65NK.js} +1 -1
  84. package/dist/chunk-NHBYZCSX.js +4 -0
  85. package/dist/chunk-NRUD56FY.js +7 -0
  86. package/dist/chunk-NXFAEDHV.js +26 -0
  87. package/dist/{chunk-OIYGGEUL.js → chunk-NXXJ56QA.js} +1 -1
  88. package/dist/{chunk-AXTGYOMK.js → chunk-O3AHFP3K.js} +1 -1
  89. package/dist/chunk-OAVPM6YJ.js +2 -0
  90. package/dist/{chunk-FBHRBFHP.js → chunk-OJTCIZDK.js} +1 -1
  91. package/dist/{chunk-JPWLGHPM.js → chunk-OOEPLMKA.js} +1 -1
  92. package/dist/{chunk-VT54ARGE.js → chunk-PXCMEI73.js} +1 -1
  93. package/dist/{chunk-APPYQZFK.js → chunk-R4UCBA5R.js} +1 -1
  94. package/dist/chunk-RKXHVP2Z.js +2 -0
  95. package/dist/{chunk-AJ56AMT6.js → chunk-RN4PKQFR.js} +1 -1
  96. package/dist/chunk-RUCSRS4C.js +5 -0
  97. package/dist/chunk-TAOHYWEO.js +2 -0
  98. package/dist/chunk-TZXXJWHA.js +2 -0
  99. package/dist/{chunk-VRLUNZAK.js → chunk-U5GHOGLM.js} +1 -1
  100. package/dist/chunk-UJZZDPDY.js +2 -0
  101. package/dist/{chunk-VHZ4S57N.js → chunk-UODLRQQ4.js} +1 -1
  102. package/dist/chunk-VK3NU742.js +21 -0
  103. package/dist/{chunk-FDIPQRX4.js → chunk-VPRNGWIY.js} +1 -1
  104. package/dist/{chunk-RDNFVZEB.js → chunk-WOEQDUJ6.js} +1 -1
  105. package/dist/chunk-WQPQNL4S.js +2 -0
  106. package/dist/{chunk-SL6PCVM2.js → chunk-WV27D55O.js} +1 -1
  107. package/dist/{chunk-2WFZIQ62.js → chunk-WVCH66YH.js} +1 -1
  108. package/dist/{chunk-PLOWZLG5.js → chunk-YCLG3T5E.js} +2 -2
  109. package/dist/chunk-YGMC3FGJ.js +26 -0
  110. package/dist/{chunk-5SXMV66P.js → chunk-YHYTCENI.js} +1 -1
  111. package/dist/{chunk-KQZA2QSC.js → chunk-YSSYT5F5.js} +1 -1
  112. package/dist/{chunk-OR6MCL6Z.js → chunk-YTDSQAYN.js} +1 -1
  113. package/dist/{chunk-XUS4WKDS.js → chunk-ZEDAPY7M.js} +1 -1
  114. package/dist/{chunk-F7ISS545.js → chunk-ZGBSGZZM.js} +1 -1
  115. package/dist/chunk-ZI6UIJUN.js +11 -0
  116. package/dist/{config-CWZV6XPT.js → config-RLDXM5ZH.js} +1 -1
  117. package/dist/{controller-client-RD2YEMAH.js → controller-client-OB4WD2C4.js} +1 -1
  118. package/dist/{cover-cmd-NWIRJY5Z.js → cover-cmd-HDZZWJXG.js} +1 -1
  119. package/dist/{credentials-YHTJGKEO.js → credentials-CALNKQMN.js} +1 -1
  120. package/dist/deps-bundle-GVHIMZ5E.js +2 -0
  121. package/dist/deps-resolve-T6P4EACP.js +2 -0
  122. package/dist/{dispatch-WVNXB7AD.js → dispatch-ECUEAMXS.js} +1 -1
  123. package/dist/doctor-SIBHJVGC.js +2 -0
  124. package/dist/docx-convert-JMUMT5C4.js +2 -0
  125. package/dist/evidence-ZVQHPELX.js +2 -0
  126. package/dist/evolve-cmd-JGCFTXWA.js +2 -0
  127. package/dist/exec-P2IKJRRR.js +2 -0
  128. package/dist/exit-manager-3FVBTNYR.js +2 -0
  129. package/dist/{explain-cmd-IZEHWZV5.js → explain-cmd-3GEKR7O5.js} +1 -1
  130. package/dist/{explain-cmd-75MCF2ZV.js → explain-cmd-EX24XKD6.js} +1 -1
  131. package/dist/extract-bind-EXW32RUY.js +10 -0
  132. package/dist/{extract-cmd-ZRYMJ6IC.js → extract-cmd-7IOLJJCL.js} +2 -2
  133. package/dist/gaps-cmd-WPCJPLGB.js +3 -0
  134. package/dist/{generate-headless-D6BISWDC.js → generate-headless-U4GTG234.js} +3 -3
  135. package/dist/host-7GZPBA74.js +2 -0
  136. package/dist/index.js +84 -67
  137. package/dist/ingest-cmd-YYNAKI2U.js +2 -0
  138. package/dist/interactive-bind-Y65XV4Y5.js +25 -0
  139. package/dist/{lifecycle-cmd-EQSFAZG6.js → lifecycle-cmd-HO5VL7AM.js} +1 -1
  140. package/dist/{list-cmd-IRJSUCM5.js → list-cmd-N4KMA34H.js} +1 -1
  141. package/dist/list-commands-3EROWJWV.js +2 -0
  142. package/dist/login-flow-TRINUSBB.js +2 -0
  143. package/dist/{maintenance-cmd-MVFA6H74.js → maintenance-cmd-6XSVO6FO.js} +1 -1
  144. package/dist/mobile-prompts-TP3ODM5M.js +2 -0
  145. package/dist/persist-recorded-session-EHYT3PVN.js +3 -0
  146. package/dist/pipeline-5GOS2KV2.js +2 -0
  147. package/dist/prepare-target-BUEOZVJV.js +2 -0
  148. package/dist/reconcile-cmd-TY3MWZL3.js +2 -0
  149. package/dist/reconcile-deps-6KTJHBMJ.js +4 -0
  150. package/dist/reconcile-engine-O7QEZVX6.js +2 -0
  151. package/dist/{recording-banner-76GCIPUN.js → recording-banner-BWWFOJCR.js} +1 -1
  152. package/dist/registry-KXEDLM6X.js +2 -0
  153. package/dist/{require-project-folder-ACRDP5ZB.js → require-project-folder-CXDRRWEQ.js} +1 -1
  154. package/dist/resolve-run-intent-PZXEQTHC.js +7 -0
  155. package/dist/{resolver-SRPCFW7P.js → resolver-FTU5KO7H.js} +1 -1
  156. package/dist/{review-cmd-L3V5UP5T.js → review-cmd-DQRKQUMG.js} +1 -1
  157. package/dist/run-CMFBSYWF.js +2 -0
  158. package/dist/run-WKHPVWUN.js +2 -0
  159. package/dist/{run-test-md-KEHSRMCM.js → run-test-md-7HGOZJSU.js} +3 -3
  160. package/dist/session-items-2ATN7VXG.js +2 -0
  161. package/dist/session-target-UWROGOCY.js +2 -0
  162. package/dist/{sessions-cmd-ZVYGSRJ3.js → sessions-cmd-ZZIZN2VB.js} +1 -1
  163. package/dist/{skill-installer-HBN3A35K.js → skill-installer-QNUDLGPD.js} +1 -1
  164. package/dist/spawner-DQZRJIE6.js +2 -0
  165. package/dist/{structured-answers-A43Q25CZ.js → structured-answers-5EY2AZN7.js} +1 -1
  166. package/dist/tcg-generate-XKSTMCOG.js +2 -0
  167. package/dist/testmd-actions-IFRW7NGG.js +2 -0
  168. package/dist/{tms-client-VD3B3SMU.js → tms-client-V3TR4QW3.js} +1 -1
  169. package/dist/token-refresh-FP6JFLXB.js +2 -0
  170. package/dist/types-6E2HTDKJ.js +2 -0
  171. package/dist/{validate-basic-ZGWPBYB6.js → validate-basic-3CNUDDH7.js} +1 -1
  172. package/dist/{verdicts-SCETLY5J.js → verdicts-NYCSBWUC.js} +1 -1
  173. package/dist/{version-check-CJWKDAXV.js → version-check-7TSAVA6V.js} +1 -1
  174. package/dist/{view-cmd-SOVM64L2.js → view-cmd-KPJTP4DI.js} +1 -1
  175. package/dist/walk-session-AINBHZKB.js +2 -0
  176. package/dist/{with-telemetry-E7QWPGL6.js → with-telemetry-3DL7ZEZL.js} +1 -1
  177. package/package.json +12 -6
  178. package/dist/ChatSurface-E7QKI4LA.js +0 -8
  179. package/dist/ConfigView-HPKRQXMC.js +0 -2
  180. package/dist/EvidenceViewOffer-F5YG54OC.js +0 -2
  181. package/dist/FolderPicker-4NSDXQY5.js +0 -2
  182. package/dist/SingleShotApp-Y3YDFQSD.js +0 -2
  183. package/dist/TestMdRunView-O6JTHV5W.js +0 -2
  184. package/dist/bridge-JSKEO4N3.js +0 -2
  185. package/dist/chunk-23VPUWBD.js +0 -23
  186. package/dist/chunk-2WRBTLFN.js +0 -13
  187. package/dist/chunk-53IBTIL3.js +0 -12
  188. package/dist/chunk-5WXGMXGA.js +0 -26
  189. package/dist/chunk-5ZQZOVWY.js +0 -4
  190. package/dist/chunk-74HTO7K3.js +0 -11
  191. package/dist/chunk-AECMF3T2.js +0 -8
  192. package/dist/chunk-AFBKGZFG.js +0 -2
  193. package/dist/chunk-BXYWX4J3.js +0 -2
  194. package/dist/chunk-C3T7TKAC.js +0 -349
  195. package/dist/chunk-DBKNJRJG.js +0 -2
  196. package/dist/chunk-H32GM5G4.js +0 -2
  197. package/dist/chunk-J5FBU425.js +0 -62
  198. package/dist/chunk-KCCSWEGA.js +0 -4
  199. package/dist/chunk-MK7JUOYV.js +0 -6
  200. package/dist/chunk-ORQNKZ2Z.js +0 -5
  201. package/dist/chunk-OUJQVBUT.js +0 -7
  202. package/dist/chunk-QOFZSHSC.js +0 -47
  203. package/dist/chunk-RKWJG3WW.js +0 -19
  204. package/dist/chunk-STVP2XHO.js +0 -2
  205. package/dist/chunk-VFII6C46.js +0 -2
  206. package/dist/chunk-VGFTNLQQ.js +0 -2
  207. package/dist/chunk-WAOCHXJ5.js +0 -2
  208. package/dist/chunk-ZUGCHQFC.js +0 -2
  209. package/dist/docx-convert-CHLJUTFH.js +0 -2
  210. package/dist/evidence-IVDNXWPL.js +0 -2
  211. package/dist/evolve-cmd-XBX4SX5H.js +0 -2
  212. package/dist/exit-manager-XZL4KIJU.js +0 -2
  213. package/dist/extract-bind-5OWELRME.js +0 -10
  214. package/dist/gaps-cmd-XBRXKXDL.js +0 -3
  215. package/dist/ingest-cmd-YTGOICTC.js +0 -2
  216. package/dist/interactive-bind-XSRD36MO.js +0 -25
  217. package/dist/list-commands-RCYHJ5Y3.js +0 -2
  218. package/dist/login-flow-PYAPYCPY.js +0 -2
  219. package/dist/persist-recorded-session-DTYCLXTQ.js +0 -3
  220. package/dist/pipeline-MXFOD6ES.js +0 -2
  221. package/dist/reconcile-cmd-EG6BOU3A.js +0 -2
  222. package/dist/reconcile-deps-HTT6IPHT.js +0 -4
  223. package/dist/reconcile-engine-JQNXALNY.js +0 -2
  224. package/dist/run-GMZCDRDD.js +0 -2
  225. package/dist/run-TFRWPGXP.js +0 -2
  226. package/dist/spawner-GC5CFAJ7.js +0 -2
  227. package/dist/tcg-generate-V7YFNC5O.js +0 -2
  228. package/dist/testmd-actions-MNDOO76O.js +0 -2
  229. package/dist/token-refresh-3UYMCYG3.js +0 -2
  230. package/dist/walk-session-YUYRULPY.js +0 -2
@@ -0,0 +1,6 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as Y,b as Z,c as nn,d as en,e as tn}from"./chunk-NRUD56FY.js";import{b as rn,c as sn}from"./chunk-6IA6QMPH.js";import{m as X,o as P}from"./chunk-56PAQAX5.js";import{a as jn}from"./chunk-6YGTRKDT.js";import{e as Pn}from"./chunk-UR6MHSHU.js";function on(i){return{command:"start",...i}}function an(i,e,o){return{command:"run",run_id:i,kind:e,...o}}function un(i){return{command:"cancel",...i?{run_id:i}:{}}}function dn(i){return{command:"ask_user_response",answer:i}}function ln(){return{command:"shutdown"}}var z=Symbol("run-queue-end"),G=class{items=[];waiting=null;ended=!1;error=null;push(e){if(this.waiting){let{resolve:o}=this.waiting;this.waiting=null,o(e)}else this.items.push(e)}end(){if(this.ended=!0,this.waiting){let{resolve:e}=this.waiting;this.waiting=null,e(z)}}fail(e){if(this.error=e,this.waiting){let{reject:o}=this.waiting;this.waiting=null,o(e)}}next(){return this.items.length>0?Promise.resolve(this.items.shift()):this.error?Promise.reject(this.error):this.ended?Promise.resolve(z):new Promise((e,o)=>{this.waiting={resolve:e,reject:o}})}},D=class{env;runner;log;sessionId;spawnFn;proc=null;activeRun=null;pendingReady=null;shuttingDown=!1;finalized=!1;exitInfo=null;exitedUnexpectedly=!1;exitResolve;exited;constructor(e){this.env=e.env,this.runner=e.runner,this.log=e.log,this.sessionId=e.sessionId,this.spawnFn=e.spawn??Z;let o;this.exited=new Promise(c=>{o=c}),this.exitResolve=o}async start(e){if(this.proc)throw new Error("PersistentRunner.start called twice");this.proc=this.spawnFn({env:this.env,runner:this.runner,log:this.log,sessionId:this.sessionId}),this.consume();let o=new Promise((c,g)=>{this.pendingReady={resolve:c,reject:g}});this.writeCommand(on(e)),await o}async*run(e,o,c){if(!this.proc)throw new Error("PersistentRunner.run called before start");if(this.finalized)throw new Error(`v16-runner is not running (exited code=${this.exitInfo?.code??"null"}, signal=${this.exitInfo?.signal??"none"}) \u2014 cannot start run '${e}'`);if(this.activeRun)throw new Error(`PersistentRunner.run overlap: '${this.activeRun.runId}' still in flight`);let g=new G,w={runId:e,queue:g};this.activeRun=w,this.writeCommand(an(e,o,c));try{for(;;){let v=await g.next();if(v===z||(yield v,v.type==="run_end"&&(v.run_id===void 0||v.run_id===e)))break}}finally{this.activeRun===w&&(this.activeRun=null)}}sendUserResponse(e){this.writeCommand(dn(e))}cancel(e){this.writeCommand(un(e))}kill(){this.proc?.child.kill("SIGTERM")}async shutdown(){this.shuttingDown=!0,this.proc&&(this.writeCommand(ln()),await this.exited)}get stderr(){return this.proc?.getStderr()??""}get diedUnexpectedly(){return this.exitedUnexpectedly}writeCommand(e){let o=JSON.stringify(e)+`
3
+ `;try{this.proc?.child.stdin?.write(o)}catch{}}async consume(){if(!this.proc)return;try{for await(let c of this.proc.events){if(c.type==="ready"){this.onReady();continue}this.routeEvent(c)}}catch(c){this.log?.("error","PERSISTENT_RUNNER_STREAM_ERROR","Runner stdout stream errored",{error:c instanceof Error?c.message:String(c)})}let{code:e,signal:o}=await this.proc.exited;this.onExit(e,o)}onReady(){if(this.pendingReady){let{resolve:e}=this.pendingReady;this.pendingReady=null,e()}}routeEvent(e){let o=this.activeRun;if(!o){this.log?.("warn","PERSISTENT_RUNNER_ORPHAN_EVENT","Runner event with no active run",{event_type:e.type});return}o.queue.push(e)}onExit(e,o){if(!this.finalized){if(this.finalized=!0,this.exitInfo={code:e,signal:o},this.shuttingDown||(this.exitedUnexpectedly=!0),this.exitResolve({code:e,signal:o}),this.pendingReady){let{reject:c}=this.pendingReady;this.pendingReady=null,c(new Error(`v16-runner exited before ready (code=${e}, signal=${o??"none"})`))}if(this.activeRun){let{queue:c}=this.activeRun;if(this.activeRun=null,this.shuttingDown)c.end();else{let g=this.proc?.getStderr()?.slice(-500)??"";c.fail(new Error(`v16-runner exited unexpectedly mid-run (code=${e}, signal=${o??"none"})${g?`
4
+ ${g}`:""}`))}}}}};var p=Pn(jn(),1);function cn(i){let e={cdp_endpoint:i.cdp_endpoint,ws_endpoint:i.ws_endpoint,width:i.width,height:i.height,headless:i.headless,model:i.model,max_steps:i.max_steps,network_ws:i.network_ws,network_sse:i.network_sse,session_id:i.session_id};return i.device&&(e.device=i.device),i.auth&&(e.auth=i.auth),i.username&&(e.username=i.username),i.access_key&&(e.access_key=i.access_key),e}function j(i,e){let o=null,c=(g,w)=>{for(let v=0;v<g.length;v++){let b=g[v],h=[...w,v];e(b)&&(o===null||h.length>o.length)&&(o=h),b.children&&b.children.length>0&&c(b.children,h)}};return c(i,[]),o}function N(i,e,o){if(e.length===0)return[...i];let c=e[0],g=[...i],w=g[c];if(e.length===1)g[c]=o(w);else{let v=e.slice(1),b=N(w.children??[],v,o);g[c]={...w,children:b}}return g}function pn(){return{steps:[],maxOrdinal:0}}function Nn(i,e){if(e.type==="run_start"&&e.child_id)return e.environment?.resolution?{...i,resolution:e.environment.resolution}:i;if(e.type==="run_start"){let o=sn(i.runnerEnvironment,rn(e.environment));if(o)return{...i,runnerEnvironment:o,...o.resolution?{resolution:o.resolution}:{}}}if(e.type==="step_end"&&typeof e.ordinal=="number"&&e.id){let o={id:e.id,ordinal:e.ordinal,status:e.status,...e.kind?{kind:e.kind}:{},...typeof e.duration=="number"?{duration_ms:Math.round(e.duration*1e3)}:{},...typeof e.action_id=="string"&&e.action_id?{action_id:e.action_id}:{}};return{...i,steps:[...i.steps,o],maxOrdinal:Math.max(i.maxOrdinal,e.ordinal)}}return i}function V(i){let e=i.indexOf(": ");return e>0&&e<15?i.slice(e+2):i}function W(i){return i.map(e=>{let o=e.children?W(e.children):e.children;return e.status==="running"?{...e,status:"stopped",phase:void 0,children:o}:o!==e.children?{...e,children:o}:e})}function Gn(i,e,o,c,g){let[w,v]=(0,p.useState)(!1),[b,h]=(0,p.useState)([]),[hn,T]=(0,p.useState)(null),[fn,B]=(0,p.useState)(null),[mn,I]=(0,p.useState)(null),[vn,J]=(0,p.useState)(null),[gn,H]=(0,p.useState)([]),[Rn,K]=(0,p.useState)(null),[Sn,yn]=(0,p.useState)(void 0),[wn,$]=(0,p.useState)(0),y=(0,p.useRef)(null),E=(0,p.useRef)(null),S=(0,p.useRef)(null),_=(0,p.useRef)(0),F=(0,p.useRef)(!1),U=(0,p.useRef)(pn()),O=(0,p.useRef)(null),xn=(0,p.useCallback)(async(m,x)=>{let Q=O.current;if(Q)try{await Q}catch{}h([]),T(null),B(null),I(null),J(null),H([]),K(null),yn(m.max_steps),v(!0),S.current=null,_.current=0,U.current=pn();let k=y.current;if(k&&E.current!==m.session_id){try{k.kill()}catch{}y.current=null,E.current=null,$(n=>n+1),k=null}if(!k){let n=Y();if(!n){I("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available."),v(!1);return}let d=en({environment:x?.environment,mode:x?.mode,assertionMode:x?.assertionMode,finalValidation:x?.finalValidation,username:m.username,accessKey:m.access_key,sessionId:m.session_id});m.device?.platform&&await nn(d,m.device);let u=new D({env:d,runner:n,log:x?.log,sessionId:m.session_id});y.current=u,E.current=m.session_id,k=u,X("runner",()=>{try{u.kill()}catch{}});let s=cn(m);try{await u.start(s)}catch(a){I(a instanceof Error?a.message:String(a)),v(!1),P("runner","Runner start failed"),y.current=null,E.current=null,$(t=>t+1);return}}let M={...m};delete M.run_id,tn(M,{environment:x?.environment});let kn=`run-${m.run_index}`,Cn=m.mode==="replay"?"replay":"author",L=k,q=(async()=>{F.current=!1;for await(let n of L.run(kn,Cn,M)){if(F.current)break;switch(U.current=Nn(U.current,n),n.type){case"run_start":if(n.child_id)break;if(S.current&&!S.current.isSingleFlow){let d=_.current;_.current++,h(u=>u.map((s,a)=>a===d?{...s,status:"running"}:s.status==="running"&&!s.children?.some(t=>t.status==="running")?{...s,status:s.children?.some(t=>t.status==="failed")?"failed":"passed"}:s))}break;case"bifurcation":{let d=n.flows??[],u=n.count??d.length,s={flows:d,isSingleFlow:n.is_single_flow??u<=1};J(s),S.current=s,_.current=0,h(d.map((a,t)=>({index:t+1,objective:a??`Flow ${t+1}`,status:"pending"})));break}case"step_start":{e?.("STEP_START",`Step ${n.index} started`,{index:n.index,objective:n.objective,child_id:n.child_id});let d=n.index,u=n.objective??`Step ${d}`,s=n.child_id,a=S.current&&!S.current.isSingleFlow;if(s)h(t=>{let r=j(t,l=>l.branchChildId===s)??j(t,l=>l.status==="running");return r?N(t,r,l=>{let f=(l.children??[]).map(R=>R.status==="running"&&R.childId===s?{...R,status:"stopped",phase:void 0}:R);return f.push({index:d,objective:u,status:"running",childId:s}),{...l,children:f}}):t});else if(a){let t=Math.max(0,_.current-1);h(r=>{let l=[...r];if(t>=l.length)return r;let f={...l[t]},C=[...f.children??[]].map(A=>A.status==="running"&&A.childId===void 0?{...A,status:"stopped",phase:void 0}:A);return C.push({index:d,objective:u,status:"running"}),f.children=C,f.status="running",l[t]=f,l})}else h(t=>{let r=W(t);return r.some(f=>f.index===d)?r.map(f=>f.index===d?{...f,status:"running",objective:u}:f):[...r,{index:d,objective:u,status:"running"}]});break}case"step_event":{e?.("STEP_EVENT",`Step ${n.index} ${n.event}`,{index:n.index,phase:n.event,action_type:n.action_type,detail:n.detail,child_id:n.child_id});let d=n.child_id,u=S.current&&!S.current.isSingleFlow;if(n.event==="cm_init"&&n.checkpoint_count!=null){H(s=>[...s,n.checkpoint_count]);break}if(n.event==="replay_started"){K({recordingLength:n.recording_length??0});break}if(n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&o?.(n.detail),d){let s=t=>{if(t.index!==n.index||t.childId!==d)return t;let r={phase:n.event};return n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&(r.objective=n.detail),n.action_type&&(r.actionType=n.action_type),{...t,...r}},a=t=>t.map(r=>{let l=s(r);return l!==r?l:r.children&&r.children.length>0?{...r,children:a(r.children)}:r});h(t=>t.map(r=>r.children?{...r,children:a(r.children)}:r))}else if(u){let s=Math.max(0,_.current-1);h(a=>{let t=[...a];if(s>=t.length)return a;let r={...t[s]},l=[...r.children??[]];if(!l.some(R=>R.index===n.index&&R.childId===void 0))l.push({index:n.index,objective:`Step ${n.index}`,status:"running",phase:n.event,actionType:n.action_type});else for(let R=0;R<l.length;R++){if(l[R].index!==n.index||l[R].childId!==void 0)continue;let C={phase:n.event};n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&(C.objective=n.detail),n.action_type&&(C.actionType=n.action_type),l[R]={...l[R],...C}}return r.children=l,t[s]=r,t})}else h(s=>s.some(t=>t.index===n.index)?s.map(t=>{if(t.index!==n.index)return t;let r={phase:n.event};return n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&(r.objective=n.detail),n.action_type&&(r.actionType=n.action_type),{...t,...r}}):[...W(s),{index:n.index,objective:`Step ${n.index}`,status:"running",phase:n.event,actionType:n.action_type}]);break}case"step_end":{e?.("STEP_END",`Step ${n.index} ${n.status}`,{index:n.index,status:n.status,duration:n.duration,summary:n.summary,child_id:n.child_id}),c?.();let d=n.child_id,u=S.current&&!S.current.isSingleFlow;if(d){let s=t=>t.index===n.index&&t.childId===d?{...t,status:n.status,duration:n.duration,phase:void 0,objective:t.objective.startsWith("Step ")?V(n.summary||t.objective):t.objective}:t,a=t=>t.map(r=>{let l=s(r);return l!==r?l:r.children&&r.children.length>0?{...r,children:a(r.children)}:r});h(t=>t.map(r=>r.children?{...r,children:a(r.children)}:r))}else if(u){let s=Math.max(0,_.current-1);h(a=>{let t=[...a];if(s>=t.length)return a;let r={...t[s]},l=(r.children??[]).map(f=>f.index===n.index&&f.childId===void 0?{...f,status:n.status,duration:n.duration,phase:void 0,objective:f.objective.startsWith("Step ")?V(n.summary||f.objective):f.objective}:f);return r.children=l,t[s]=r,t})}else h(s=>s.map(a=>a.index===n.index?{...a,status:n.status,duration:n.duration,phase:void 0,objective:a.objective.startsWith("Step ")?V(n.summary||a.objective):a.objective}:a));{let a=S.current&&!S.current.isSingleFlow?Math.max(0,_.current-1):0,t=typeof n.ordinal=="number"&&n.id?{ordinal:n.ordinal,id:n.id}:void 0;i?.(n.index,a,n.child_id,t)}break}case"child_agent_start":{let d=n.objective??"",u=n.child_id;h(s=>{let a=j(s,t=>t.status==="running");return a?N(s,a,t=>({...t,objective:`${d} (branch)`,phase:`child: ${d.slice(0,50)}`,branchObjective:d,branchChildId:u})):s});break}case"child_agent_end":{let d=n.child_id,u=`child ${n.success?"done":"failed"}`;h(s=>{let a=j(s,t=>t.branchChildId===d);return a?N(s,a,t=>({...t,phase:u})):s.map(t=>t.phase?.startsWith("child:")?{...t,phase:u}:t)});break}case"describe_trigger":g?.(n);break;case"ask_user":T(n.question??"");break;case"run_end":h(d=>d.map(u=>u.status==="running"?{...u,status:n.status,phase:void 0}:u)),v(!1),B(n);break;case"error":v(!1),I(n.message??"Runner error"),h(d=>d.map(u=>u.status==="running"?{...u,status:"failed",phase:void 0}:u));break}}})().catch(n=>{if(y.current!==L)return;let u=[n instanceof Error?n.message:String(n)],s=L.stderr;s&&!u.join(`
5
+ `).includes(s)&&u.push(s),I(u.join(`
6
+ `)),v(!1),h(a=>a.map(t=>t.status==="running"?{...t,status:"failed",phase:void 0}:t)),P("runner","Runner died mid-run"),y.current=null,E.current=null,$(a=>a+1)});O.current=q,q.finally(()=>{O.current===q&&(O.current=null)})},[i,e,o,c,g]),bn=(0,p.useCallback)(m=>{y.current?.sendUserResponse(m),T(null)},[]),_n=(0,p.useCallback)(()=>{let m=y.current;m&&(m.cancel(),v(!1),T(null))},[]),En=(0,p.useCallback)(async()=>{let m=y.current;if(m){try{await Promise.race([m.shutdown(),new Promise(x=>setTimeout(x,5e3))])}catch{}P("runner","Runner shut down"),y.current=null,E.current=null,$(x=>x+1)}},[]),In=(0,p.useCallback)(()=>{h([]),B(null),I(null)},[]);return(0,p.useEffect)(()=>()=>{F.current=!0,P("runner","Component unmounted"),y.current=null,E.current=null},[]),{isRunning:w,steps:b,askingUser:hn,lastRunEnd:fn,runError:mn,bifurcationInfo:vn,cmInitCounts:gn,replayInfo:Rn,maxSteps:Sn,sessionGen:wn,startRun:xn,sendAnswer:bn,cancelRun:_n,shutdownRunner:En,clearLastRun:In,getEvidenceState:()=>U.current}}export{D as a,cn as b,pn as c,Nn as d,Gn as e};
@@ -0,0 +1,47 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as Ot,b as Mt}from"./chunk-2UIHS2FH.js";import{a as vt}from"./chunk-BKHXPBWN.js";import{a as kt}from"./chunk-N2P4MI32.js";import{b as wt}from"./chunk-NVGBE2DR.js";import{a as Nt,b as Ft,c as St}from"./chunk-MSGW4JDG.js";import{c as G,e as Rt}from"./chunk-UR6MHSHU.js";var Lt=G(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.CHAR=`
3
+ \r -\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}`;x.S=` \r
4
+ `;x.NAME_START_CHAR=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";x.NAME_CHAR="-"+x.NAME_START_CHAR+".0-9\xB7\u0300-\u036F\u203F-\u2040";x.CHAR_RE=new RegExp("^["+x.CHAR+"]$","u");x.S_RE=new RegExp("^["+x.S+"]+$","u");x.NAME_START_CHAR_RE=new RegExp("^["+x.NAME_START_CHAR+"]$","u");x.NAME_CHAR_RE=new RegExp("^["+x.NAME_CHAR+"]$","u");x.NAME_RE=new RegExp("^["+x.NAME_START_CHAR+"]["+x.NAME_CHAR+"]*$","u");x.NMTOKEN_RE=new RegExp("^["+x.NAME_CHAR+"]+$","u");var tt=9,et=10,st=13,it=32;x.S_LIST=[it,et,st,tt];function Ne(e){return e>=it&&e<=55295||e===et||e===st||e===tt||e>=57344&&e<=65533||e>=65536&&e<=1114111}x.isChar=Ne;function Fe(e){return e===it||e===et||e===st||e===tt}x.isS=Fe;function Pt(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}x.isNameStartChar=Pt;function Se(e){return Pt(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}x.isNameChar=Se});var Ht=G(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.CHAR="-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}";f.RESTRICTED_CHAR="-\b\v\f-\x7F-\x84\x86-\x9F";f.S=` \r
5
+ `;f.NAME_START_CHAR=":A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";f.NAME_CHAR="-"+f.NAME_START_CHAR+".0-9\xB7\u0300-\u036F\u203F-\u2040";f.CHAR_RE=new RegExp("^["+f.CHAR+"]$","u");f.RESTRICTED_CHAR_RE=new RegExp("^["+f.RESTRICTED_CHAR+"]$","u");f.S_RE=new RegExp("^["+f.S+"]+$","u");f.NAME_START_CHAR_RE=new RegExp("^["+f.NAME_START_CHAR+"]$","u");f.NAME_CHAR_RE=new RegExp("^["+f.NAME_CHAR+"]$","u");f.NAME_RE=new RegExp("^["+f.NAME_START_CHAR+"]["+f.NAME_CHAR+"]*$","u");f.NMTOKEN_RE=new RegExp("^["+f.NAME_CHAR+"]+$","u");var yt=9,It=10,Bt=13,Xt=32;f.S_LIST=[Xt,It,Bt,yt];function we(e){return e>=1&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}f.isChar=we;function ke(e){return e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e>=127&&e<=132||e>=134&&e<=159}f.isRestrictedChar=ke;function ve(e){return e===9||e===10||e===13||e>31&&e<127||e===133||e>159&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}f.isCharAndNotRestricted=ve;function Oe(e){return e===Xt||e===It||e===Bt||e===yt}f.isS=Oe;function $t(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}f.isNameStartChar=$t;function Me(e){return $t(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}f.isNameChar=Me});var Ut=G(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.NC_NAME_START_CHAR="A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}";N.NC_NAME_CHAR="-"+N.NC_NAME_START_CHAR+".0-9\xB7\u0300-\u036F\u203F-\u2040";N.NC_NAME_START_CHAR_RE=new RegExp("^["+N.NC_NAME_START_CHAR+"]$","u");N.NC_NAME_CHAR_RE=new RegExp("^["+N.NC_NAME_CHAR+"]$","u");N.NC_NAME_RE=new RegExp("^["+N.NC_NAME_START_CHAR+"]["+N.NC_NAME_CHAR+"]*$","u");function Wt(e){return e>=65&&e<=90||e===95||e>=97&&e<=122||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8204&&e<=8205||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}N.isNCNameStartChar=Wt;function Pe(e){return Wt(e)||e===45||e===46||e>=48&&e<=57||e===183||e>=768&&e<=879||e>=8255&&e<=8256}N.isNCNameChar=Pe});var Ct=G(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.SaxesParser=B.EVENTS=void 0;var X=Lt(),Le=Ht(),xt=Ut(),F=X.isS,ye=X.isChar,W=X.isNameStartChar,Vt=X.isNameChar,ne=X.S_LIST,Ie=X.NAME_RE,Be=Le.isChar,Xe=xt.isNCNameStartChar,$e=xt.isNCNameChar,He=xt.NC_NAME_RE,K="http://www.w3.org/XML/1998/namespace",I="http://www.w3.org/2000/xmlns/",We={__proto__:null,xml:K,xmlns:I},Ue={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},C=-1,k=-2,Gt=0,Ve=1,nt=2,Ge=3,P=4,qe=5,je=6,ze=7,rt=8,Ye=9,Qe=10,Ke=11,Ze=12,A=13,q=14,at=15,Je=16,ot=17,ts=18,es=19,ht=20,ss=21,is=22,ns=23,qt=24,lt=25,j=26,jt=27,rs=28,as=29,zt=30,os=31,hs=32,O=33,ls=34,ct=35,U=36,ut=37,cs=38,Yt=39,Qt=40,us=41,Kt=42,ds=43,fs=44,dt=9,w=10,ft=13,Zt=32,Jt=33,re=34,V=38,ae=39,z=45,Y=47,ps=59,v=60,L=61,D=62,T=63,oe=91,y=93,te=133,ee=8232,Q=e=>e===re||e===ae,he=[re,ae],ms=[...he,oe,D],gs=[...he,v,y],xs=[L,T,...ne],Cs=[...ne,D,V,v];function mt(e,t,s){switch(t){case"xml":s!==K&&e.fail(`xml prefix must be bound to ${K}.`);break;case"xmlns":s!==I&&e.fail(`xmlns prefix must be bound to ${I}.`);break;default:}switch(s){case I:e.fail(t===""?`the default namespace may not be set to ${s}.`:`may not assign a prefix (even "xmlns") to the URI ${I}.`);break;case K:switch(t){case"xml":break;case"":e.fail(`the default namespace may not be set to ${s}.`);break;default:e.fail("may not assign the xml namespace to another prefix.")}break;default:}}function _s(e,t){for(let s of Object.keys(t))mt(e,s,t[s])}var Es=e=>He.test(e),Ds=e=>Ie.test(e),M=0,se=1,pt=2;B.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var ie={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"},gt=class{constructor(t){this.opt=t??{},this.fragmentOpt=!!this.opt.fragment;let s=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,s){this.nameStartCheck=Xe,this.nameCheck=$e,this.isName=Es,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},We);let i=this.opt.additionalNamespaces;i!=null&&(_s(this,i),Object.assign(this.ns,i))}else this.nameStartCheck=W,this.nameCheck=Vt,this.isName=Ds,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var t;this.openWakaBang="",this.text="",this.name="",this.piTarget="",this.entity="",this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk="",this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=M,this.attribList=[];let{fragmentOpt:s}=this;this.state=s?A:Gt,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=s,this.xmlDeclPossible=!s,this.xmlDeclExpects=["version"],this.entityReturnState=void 0;let{defaultXMLVersion:i}=this.opt;if(i===void 0){if(this.opt.forceXMLVersion===!0)throw new Error("forceXMLVersion set but defaultXMLVersion is not set");i="1.0"}this.setXMLVersion(i),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(Ue),(t=this.readyHandler)===null||t===void 0||t.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(t,s){this[ie[t]]=s}off(t){this[ie[t]]=void 0}makeError(t){var s;let i=(s=this.fileName)!==null&&s!==void 0?s:"";return this.trackPosition&&(i.length>0&&(i+=":"),i+=`${this.line}:${this.column}`),i.length>0&&(i+=": "),new Error(i+t)}fail(t){let s=this.makeError(t),i=this.errorHandler;if(i===void 0)throw s;return i(s),this}write(t){if(this.closed)return this.fail("cannot write after close; assign an onready handler.");let s=!1;t===null?(s=!0,t=""):typeof t=="object"&&(t=t.toString()),this.carriedFromPrevious!==void 0&&(t=`${this.carriedFromPrevious}${t}`,this.carriedFromPrevious=void 0);let i=t.length,n=t.charCodeAt(i-1);!s&&(n===ft||n>=55296&&n<=56319)&&(this.carriedFromPrevious=t[i-1],i--,t=t.slice(0,i));let{stateTable:r}=this;for(this.chunk=t,this.i=0;this.i<i;)r[this.state].call(this);return this.chunkPosition+=i,s?this.end():this}close(){return this.write(null)}getCode10(){let{chunk:t,i:s}=this;if(this.prevI=s,this.i=s+1,s>=t.length)return C;let i=t.charCodeAt(s);if(this.column++,i<55296){if(i>=Zt||i===dt)return i;switch(i){case w:return this.line++,this.column=0,this.positionAtNewLine=this.position,w;case ft:return t.charCodeAt(s+1)===w&&(this.i=s+2),this.line++,this.column=0,this.positionAtNewLine=this.position,k;default:return this.fail("disallowed character."),i}}if(i>56319)return i>=57344&&i<=65533||this.fail("disallowed character."),i;let n=65536+(i-55296)*1024+(t.charCodeAt(s+1)-56320);return this.i=s+2,n>1114111&&this.fail("disallowed character."),n}getCode11(){let{chunk:t,i:s}=this;if(this.prevI=s,this.i=s+1,s>=t.length)return C;let i=t.charCodeAt(s);if(this.column++,i<55296){if(i>31&&i<127||i>159&&i!==ee||i===dt)return i;switch(i){case w:return this.line++,this.column=0,this.positionAtNewLine=this.position,w;case ft:{let r=t.charCodeAt(s+1);(r===w||r===te)&&(this.i=s+2)}case te:case ee:return this.line++,this.column=0,this.positionAtNewLine=this.position,k;default:return this.fail("disallowed character."),i}}if(i>56319)return i>=57344&&i<=65533||this.fail("disallowed character."),i;let n=65536+(i-55296)*1024+(t.charCodeAt(s+1)-56320);return this.i=s+2,n>1114111&&this.fail("disallowed character."),n}getCodeNorm(){let t=this.getCode();return t===k?w:t}unget(){this.i=this.prevI,this.column--}captureTo(t){let{i:s}=this,{chunk:i}=this;for(;;){let n=this.getCode(),r=n===k,a=r?w:n;if(a===C||t.includes(a))return this.text+=i.slice(s,this.prevI),a;r&&(this.text+=`${i.slice(s,this.prevI)}
6
+ `,s=this.i)}}captureToChar(t){let{i:s}=this,{chunk:i}=this;for(;;){let n=this.getCode();switch(n){case k:this.text+=`${i.slice(s,this.prevI)}
7
+ `,s=this.i,n=w;break;case C:return this.text+=i.slice(s),!1;default:}if(n===t)return this.text+=i.slice(s,this.prevI),!0}}captureNameChars(){let{chunk:t,i:s}=this;for(;;){let i=this.getCode();if(i===C)return this.name+=t.slice(s),C;if(!Vt(i))return this.name+=t.slice(s,this.prevI),i===k?w:i}}skipSpaces(){for(;;){let t=this.getCodeNorm();if(t===C||!F(t))return t}}setXMLVersion(t){this.currentXMLVersion=t,t==="1.0"?(this.isChar=ye,this.getCode=this.getCode10):(this.isChar=Be,this.getCode=this.getCode11)}sBegin(){this.chunk.charCodeAt(0)===65279&&(this.i++,this.column++),this.state=Ve}sBeginWhitespace(){let t=this.i,s=this.skipSpaces();switch(this.prevI!==t&&(this.xmlDeclPossible=!1),s){case v:if(this.state=at,this.text.length!==0)throw new Error("no-empty text at start");break;case C:break;default:this.unget(),this.state=A,this.xmlDeclPossible=!1}}sDoctype(){var t;let s=this.captureTo(ms);switch(s){case D:{(t=this.doctypeHandler)===null||t===void 0||t.call(this,this.text),this.text="",this.state=A,this.doctype=!0;break}case C:break;default:this.text+=String.fromCodePoint(s),s===oe?this.state=P:Q(s)&&(this.state=Ge,this.q=s)}}sDoctypeQuote(){let t=this.q;this.captureToChar(t)&&(this.text+=String.fromCodePoint(t),this.q=null,this.state=nt)}sDTD(){let t=this.captureTo(gs);t!==C&&(this.text+=String.fromCodePoint(t),t===y?this.state=nt:t===v?this.state=je:Q(t)&&(this.state=qe,this.q=t))}sDTDQuoted(){let t=this.q;this.captureToChar(t)&&(this.text+=String.fromCodePoint(t),this.state=P,this.q=null)}sDTDOpenWaka(){let t=this.getCodeNorm();switch(this.text+=String.fromCodePoint(t),t){case Jt:this.state=ze,this.openWakaBang="";break;case T:this.state=Ke;break;default:this.state=P}}sDTDOpenWakaBang(){let t=String.fromCodePoint(this.getCodeNorm()),s=this.openWakaBang+=t;this.text+=t,s!=="-"&&(this.state=s==="--"?rt:P,this.openWakaBang="")}sDTDComment(){this.captureToChar(z)&&(this.text+="-",this.state=Ye)}sDTDCommentEnding(){let t=this.getCodeNorm();this.text+=String.fromCodePoint(t),this.state=t===z?Qe:rt}sDTDCommentEnded(){let t=this.getCodeNorm();this.text+=String.fromCodePoint(t),t===D?this.state=P:(this.fail("malformed comment."),this.state=rt)}sDTDPI(){this.captureToChar(T)&&(this.text+="?",this.state=Ze)}sDTDPIEnding(){let t=this.getCodeNorm();this.text+=String.fromCodePoint(t),t===D&&(this.state=P)}sText(){this.tags.length!==0?this.handleTextInRoot():this.handleTextOutsideRoot()}sEntity(){let{i:t}=this,{chunk:s}=this;t:for(;;)switch(this.getCode()){case k:this.entity+=`${s.slice(t,this.prevI)}
8
+ `,t=this.i;break;case ps:{let{entityReturnState:i}=this,n=this.entity+s.slice(t,this.prevI);this.state=i;let r;n===""?(this.fail("empty entity name."),r="&;"):(r=this.parseEntity(n),this.entity=""),(i!==A||this.textHandler!==void 0)&&(this.text+=r);break t}case C:this.entity+=s.slice(t);break t;default:}}sOpenWaka(){let t=this.getCode();if(W(t))this.state=ls,this.unget(),this.xmlDeclPossible=!1;else switch(t){case Y:this.state=ds,this.xmlDeclPossible=!1;break;case Jt:this.state=Je,this.openWakaBang="",this.xmlDeclPossible=!1;break;case T:this.state=ns;break;default:this.fail("disallowed character in tag name"),this.state=A,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0),this.state=ht,this.openWakaBang="";break;case"--":this.state=ot,this.openWakaBang="";break;case"DOCTYPE":this.state=nt,(this.doctype||this.sawRoot)&&this.fail("inappropriately located doctype declaration."),this.openWakaBang="";break;default:this.openWakaBang.length>=7&&this.fail("incorrect syntax.")}}sComment(){this.captureToChar(z)&&(this.state=ts)}sCommentEnding(){var t;let s=this.getCodeNorm();s===z?(this.state=es,(t=this.commentHandler)===null||t===void 0||t.call(this,this.text),this.text=""):(this.text+=`-${String.fromCodePoint(s)}`,this.state=ot)}sCommentEnded(){let t=this.getCodeNorm();t!==D?(this.fail("malformed comment."),this.text+=`--${String.fromCodePoint(t)}`,this.state=ot):this.state=A}sCData(){this.captureToChar(y)&&(this.state=ss)}sCDataEnding(){let t=this.getCodeNorm();t===y?this.state=is:(this.text+=`]${String.fromCodePoint(t)}`,this.state=ht)}sCDataEnding2(){var t;let s=this.getCodeNorm();switch(s){case D:{(t=this.cdataHandler)===null||t===void 0||t.call(this,this.text),this.text="",this.state=A;break}case y:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(s)}`,this.state=ht}}sPIFirstChar(){let t=this.getCodeNorm();this.nameStartCheck(t)?(this.piTarget+=String.fromCodePoint(t),this.state=qt):t===T||F(t)?(this.fail("processing instruction without a target."),this.state=t===T?j:lt):(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(t),this.state=qt)}sPIRest(){let{chunk:t,i:s}=this;for(;;){let i=this.getCodeNorm();if(i===C){this.piTarget+=t.slice(s);return}if(!this.nameCheck(i)){this.piTarget+=t.slice(s,this.prevI);let n=i===T;n||F(i)?this.piTarget==="xml"?(this.xmlDeclPossible||this.fail("an XML declaration must be at the start of the document."),this.state=n?O:jt):this.state=n?j:lt:(this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(i));break}}}sPIBody(){if(this.text.length===0){let t=this.getCodeNorm();t===T?this.state=j:F(t)||(this.text=String.fromCodePoint(t))}else this.captureToChar(T)&&(this.state=j)}sPIEnding(){var t;let s=this.getCodeNorm();if(s===D){let{piTarget:i}=this;i.toLowerCase()==="xml"&&this.fail("the XML declaration must appear at the start of the document."),(t=this.piHandler)===null||t===void 0||t.call(this,{target:i,body:this.text}),this.piTarget=this.text="",this.state=A}else s===T?this.text+="?":(this.text+=`?${String.fromCodePoint(s)}`,this.state=lt);this.xmlDeclPossible=!1}sXMLDeclNameStart(){let t=this.skipSpaces();if(t===T){this.state=O;return}t!==C&&(this.state=rs,this.name=String.fromCodePoint(t))}sXMLDeclName(){let t=this.captureTo(xs);if(t===T){this.state=O,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(F(t)||t===L){if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=t===L?zt:as}}sXMLDeclEq(){let t=this.getCodeNorm();if(t===T){this.state=O,this.fail("XML declaration is incomplete.");return}F(t)||(t!==L&&this.fail("value required."),this.state=zt)}sXMLDeclValueStart(){let t=this.getCodeNorm();if(t===T){this.state=O,this.fail("XML declaration is incomplete.");return}F(t)||(Q(t)?this.q=t:(this.fail("value must be quoted."),this.q=Zt),this.state=os)}sXMLDeclValue(){let t=this.captureTo([this.q,T]);if(t===T){this.state=O,this.text="",this.fail("XML declaration is incomplete.");return}if(t===C)return;let s=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let i=s;this.xmlDecl.version=i,/^1\.[0-9]+$/.test(i)?this.opt.forceXMLVersion||this.setXMLVersion(i):this.fail("version number must match /^1\\.[0-9]+$/.");break}case"encoding":/^[A-Za-z][A-Za-z0-9._-]*$/.test(s)||this.fail("encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/."),this.xmlDeclExpects=["standalone"],this.xmlDecl.encoding=s;break;case"standalone":s!=="yes"&&s!=="no"&&this.fail('standalone value must match "yes" or "no".'),this.xmlDeclExpects=[],this.xmlDecl.standalone=s;break;default:}this.name="",this.state=hs}sXMLDeclSeparator(){let t=this.getCodeNorm();if(t===T){this.state=O;return}F(t)||(this.fail("whitespace required."),this.unget()),this.state=jt}sXMLDeclEnding(){var t;this.getCodeNorm()===D?(this.piTarget!=="xml"?this.fail("processing instructions are not allowed before root."):this.name!=="version"&&this.xmlDeclExpects.includes("version")&&this.fail("XML declaration must contain a version."),(t=this.xmldeclHandler)===null||t===void 0||t.call(this,this.xmlDecl),this.name="",this.piTarget=this.text="",this.state=A):this.fail("The character ? is disallowed anywhere in XML declarations."),this.xmlDeclPossible=!1}sOpenTag(){var t;let s=this.captureNameChars();if(s===C)return;let i=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name="",this.xmlnsOpt&&(this.topNS=i.ns=Object.create(null)),(t=this.openTagStartHandler)===null||t===void 0||t.call(this,i),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail("documents may contain only one root."),s){case D:this.openTag();break;case Y:this.state=ct;break;default:F(s)||this.fail("disallowed character in tag name."),this.state=U}}sOpenTagSlash(){this.getCode()===D?this.openSelfClosingTag():(this.fail("forward-slash in opening tag not followed by >."),this.state=U)}sAttrib(){let t=this.skipSpaces();t!==C&&(W(t)?(this.unget(),this.state=ut):t===D?this.openTag():t===Y?this.state=ct:this.fail("disallowed character in attribute name."))}sAttribName(){let t=this.captureNameChars();t===L?this.state=Yt:F(t)?this.state=cs:t===D?(this.fail("attribute without value."),this.pushAttrib(this.name,this.name),this.name=this.text="",this.openTag()):t!==C&&this.fail("disallowed character in attribute name.")}sAttribNameSawWhite(){let t=this.skipSpaces();switch(t){case C:return;case L:this.state=Yt;break;default:this.fail("attribute without value."),this.text="",this.name="",t===D?this.openTag():W(t)?(this.unget(),this.state=ut):(this.fail("disallowed character in attribute name."),this.state=U)}}sAttribValue(){let t=this.getCodeNorm();Q(t)?(this.q=t,this.state=Qt):F(t)||(this.fail("unquoted attribute value."),this.state=Kt,this.unget())}sAttribValueQuoted(){let{q:t,chunk:s}=this,{i}=this;for(;;)switch(this.getCode()){case t:this.pushAttrib(this.name,this.text+s.slice(i,this.prevI)),this.name=this.text="",this.q=null,this.state=us;return;case V:this.text+=s.slice(i,this.prevI),this.state=q,this.entityReturnState=Qt;return;case w:case k:case dt:this.text+=`${s.slice(i,this.prevI)} `,i=this.i;break;case v:this.text+=s.slice(i,this.prevI),this.fail("disallowed character.");return;case C:this.text+=s.slice(i);return;default:}}sAttribValueClosed(){let t=this.getCodeNorm();F(t)?this.state=U:t===D?this.openTag():t===Y?this.state=ct:W(t)?(this.fail("no whitespace between attributes."),this.unget(),this.state=ut):this.fail("disallowed character in attribute name.")}sAttribValueUnquoted(){let t=this.captureTo(Cs);switch(t){case V:this.state=q,this.entityReturnState=Kt;break;case v:this.fail("disallowed character.");break;case C:break;default:this.text.includes("]]>")&&this.fail('the string "]]>" is disallowed in char data.'),this.pushAttrib(this.name,this.text),this.name=this.text="",t===D?this.openTag():this.state=U}}sCloseTag(){let t=this.captureNameChars();t===D?this.closeTag():F(t)?this.state=fs:t!==C&&this.fail("disallowed character in closing tag.")}sCloseTagSawWhite(){switch(this.skipSpaces()){case D:this.closeTag();break;case C:break;default:this.fail("disallowed character in closing tag.")}}handleTextInRoot(){let{i:t,forbiddenState:s}=this,{chunk:i,textHandler:n}=this;t:for(;;)switch(this.getCode()){case v:{if(this.state=at,n!==void 0){let{text:r}=this,a=i.slice(t,this.prevI);r.length!==0?(n(r+a),this.text=""):a.length!==0&&n(a)}s=M;break t}case V:this.state=q,this.entityReturnState=A,n!==void 0&&(this.text+=i.slice(t,this.prevI)),s=M;break t;case y:switch(s){case M:s=se;break;case se:s=pt;break;case pt:break;default:throw new Error("impossible state")}break;case D:s===pt&&this.fail('the string "]]>" is disallowed in char data.'),s=M;break;case k:n!==void 0&&(this.text+=`${i.slice(t,this.prevI)}
9
+ `),t=this.i,s=M;break;case C:n!==void 0&&(this.text+=i.slice(t));break t;default:s=M}this.forbiddenState=s}handleTextOutsideRoot(){let{i:t}=this,{chunk:s,textHandler:i}=this,n=!1;t:for(;;){let r=this.getCode();switch(r){case v:{if(this.state=at,i!==void 0){let{text:a}=this,o=s.slice(t,this.prevI);a.length!==0?(i(a+o),this.text=""):o.length!==0&&i(o)}break t}case V:this.state=q,this.entityReturnState=A,i!==void 0&&(this.text+=s.slice(t,this.prevI)),n=!0;break t;case k:i!==void 0&&(this.text+=`${s.slice(t,this.prevI)}
10
+ `),t=this.i;break;case C:i!==void 0&&(this.text+=s.slice(t));break t;default:F(r)||(n=!0)}}n&&(!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0))}pushAttribNS(t,s){var i;let{prefix:n,local:r}=this.qname(t),a={name:t,prefix:n,local:r,value:s};if(this.attribList.push(a),(i=this.attributeHandler)===null||i===void 0||i.call(this,a),n==="xmlns"){let o=s.trim();this.currentXMLVersion==="1.0"&&o===""&&this.fail("invalid attempt to undefine prefix in XML 1.0"),this.topNS[r]=o,mt(this,r,o)}else if(t==="xmlns"){let o=s.trim();this.topNS[""]=o,mt(this,"",o)}}pushAttribPlain(t,s){var i;let n={name:t,value:s};this.attribList.push(n),(i=this.attributeHandler)===null||i===void 0||i.call(this,n)}end(){var t,s;this.sawRoot||this.fail("document must contain a root element.");let{tags:i}=this;for(;i.length>0;){let r=i.pop();this.fail(`unclosed tag: ${r.name}`)}this.state!==Gt&&this.state!==A&&this.fail("unexpected end.");let{text:n}=this;return n.length!==0&&((t=this.textHandler)===null||t===void 0||t.call(this,n),this.text=""),this._closed=!0,(s=this.endHandler)===null||s===void 0||s.call(this),this._init(),this}resolve(t){var s,i;let n=this.topNS[t];if(n!==void 0)return n;let{tags:r}=this;for(let a=r.length-1;a>=0;a--)if(n=r[a].ns[t],n!==void 0)return n;return n=this.ns[t],n!==void 0?n:(i=(s=this.opt).resolvePrefix)===null||i===void 0?void 0:i.call(s,t)}qname(t){let s=t.indexOf(":");if(s===-1)return{prefix:"",local:t};let i=t.slice(s+1),n=t.slice(0,s);return(n===""||i===""||i.includes(":"))&&this.fail(`malformed name: ${t}.`),{prefix:n,local:i}}processAttribsNS(){var t;let{attribList:s}=this,i=this.tag;{let{prefix:a,local:o}=this.qname(i.name);i.prefix=a,i.local=o;let c=i.uri=(t=this.resolve(a))!==null&&t!==void 0?t:"";a!==""&&(a==="xmlns"&&this.fail('tags may not have "xmlns" as prefix.'),c===""&&(this.fail(`unbound namespace prefix: ${JSON.stringify(a)}.`),i.uri=a))}if(s.length===0)return;let{attributes:n}=i,r=new Set;for(let a of s){let{name:o,prefix:c,local:_}=a,p,d;c===""?(p=o==="xmlns"?I:"",d=o):(p=this.resolve(c),p===void 0&&(this.fail(`unbound namespace prefix: ${JSON.stringify(c)}.`),p=c),d=`{${p}}${_}`),r.has(d)&&this.fail(`duplicate attribute: ${d}.`),r.add(d),a.uri=p,n[o]=a}this.attribList=[]}processAttribsPlain(){let{attribList:t}=this,s=this.tag.attributes;for(let{name:i,value:n}of t)s[i]!==void 0&&this.fail(`duplicate attribute: ${i}.`),s[i]=n;this.attribList=[]}openTag(){var t;this.processAttribs();let{tags:s}=this,i=this.tag;i.isSelfClosing=!1,(t=this.openTagHandler)===null||t===void 0||t.call(this,i),s.push(i),this.state=A,this.name=""}openSelfClosingTag(){var t,s,i;this.processAttribs();let{tags:n}=this,r=this.tag;r.isSelfClosing=!0,(t=this.openTagHandler)===null||t===void 0||t.call(this,r),(s=this.closeTagHandler)===null||s===void 0||s.call(this,r),(this.tag=(i=n[n.length-1])!==null&&i!==void 0?i:null)===null&&(this.closedRoot=!0),this.state=A,this.name=""}closeTag(){let{tags:t,name:s}=this;if(this.state=A,this.name="",s===""){this.fail("weird empty close tag."),this.text+="</>";return}let i=this.closeTagHandler,n=t.length;for(;n-- >0;){let r=this.tag=t.pop();if(this.topNS=r.ns,i?.(r),r.name===s)break;this.fail("unexpected close tag.")}n===0?this.closedRoot=!0:n<0&&(this.fail(`unmatched closing tag: ${s}.`),this.text+=`</${s}>`)}parseEntity(t){if(t[0]!=="#"){let i=this.ENTITIES[t];return i!==void 0?i:(this.fail(this.isName(t)?"undefined entity.":"disallowed character in entity name."),`&${t};`)}let s=NaN;return t[1]==="x"&&/^#x[0-9a-f]+$/i.test(t)?s=parseInt(t.slice(2),16):/^#[0-9]+$/.test(t)&&(s=parseInt(t.slice(1),10)),this.isChar(s)?String.fromCodePoint(s):(this.fail("malformed character entity."),`&${t};`)}};B.SaxesParser=gt});var ue=Rt(Ct(),1);var Ts=1e4,bs=5e7,As=25e7,de=5e6,fe=256,pe=65536,_t=256,me=3e4,l=class extends Error{constructor(s,i){super(`${s}: ${i}`);this.code=s}},Rs="http://schemas.openxmlformats.org/package/2006/relationships",Ns="http://schemas.openxmlformats.org/package/2006/content-types",Fs=new Set(["http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument","http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument"]),Ss=["application/vnd.openxmlformats-officedocument.wordprocessingml.document.main","application/vnd.ms-word.document.main"];function ge(e){return e.length===0?"empty name":e.includes("\\")?"backslash":e.includes("\0")?"NUL byte":e.startsWith("/")?"absolute path":/^[a-zA-Z]:/.test(e)?"drive letter":e.split("/").some(t=>t==="..")?"dot-dot segment":null}function ws(e,t){let s=Math.max(0,e.length-65557),i=-1;for(let _=e.length-22;_>=s;_--)if(e.readUInt32LE(_)===101010256){i=_;break}if(i<0)throw new l("DOCX_UNREADABLE","not a zip archive (no end-of-central-directory)");let n=e.readUInt16LE(i+10);if(n>t)throw new l("DOCX_TOO_MANY_PARTS",`${n} entries > ${t} cap`);let r=e.readUInt32LE(i+16),a=[],o=new Set,c=r;for(let _=0;_<n;_++){if(c+46>e.length||e.readUInt32LE(c)!==33639248)throw new l("DOCX_UNREADABLE","malformed central directory");let p=e.readUInt32LE(c+16),d=e.readUInt16LE(c+28),h=e.readUInt16LE(c+30),m=e.readUInt16LE(c+32),u=e.subarray(c+46,c+46+d).toString("utf8"),b=ge(u);if(b!==null)throw new l("DOCX_UNREADABLE",`unsafe entry name (${b}): ${JSON.stringify(u)}`);if(o.has(u))throw new l("DOCX_UNREADABLE",`duplicate entry: ${u}`);o.add(u),a.push({name:u,crc:p}),c+=46+d+h+m}return a}function ks(e,t){let s=new Map,i=0,n=null,r=o=>{n||(n=o)},a=new St(o=>{let c=ge(o.name);if(c!==null){r(new l("DOCX_UNREADABLE",`unsafe entry name (${c}): ${JSON.stringify(o.name)}`));return}let _=[],p=0;o.ondata=(d,h,m)=>{if(d){r(new l("DOCX_UNREADABLE",`entry ${o.name}: ${d.message??String(d)}`));return}if(h&&h.length>0){if(p+=h.length,i+=h.length,p>t.maxPartBytes){r(new l("DOCX_PART_TOO_LARGE",`${o.name}: ${p} actual bytes > ${t.maxPartBytes} cap`));return}if(i>t.maxTotalBytes){r(new l("DOCX_BOMB",`total actual inflated bytes exceed ${t.maxTotalBytes} cap`));return}_.push(h)}m&&!n&&s.set(o.name,Buffer.concat(_))},o.start()});a.register(Nt),a.register(Ft);try{for(let o=0;o<e.length;o+=65536)if(a.push(e.subarray(o,Math.min(o+65536,e.length)),o+65536>=e.length),n)throw n}catch(o){throw o instanceof l?o:new l("DOCX_UNREADABLE",`zip stream: ${o instanceof Error?o.message:String(o)}`)}if(n)throw n;return s}function xe(e,t,s){let i=new ue.SaxesParser({xmlns:!0}),n=null;if(i.on("doctype",()=>{n=new l("DOCX_UNREADABLE",`DOCTYPE not allowed (${t})`)}),i.on("error",r=>{n=n??new l("DOCX_UNREADABLE",`${t}: ${r.message}`)}),i.on("opentag",r=>{if(n)return;let a={};for(let[o,c]of Object.entries(r.attributes))a[c.local||o]=c.value;s(r.uri??"",r.local,a)}),i.write(e).close(),n)throw n}function le(e,t){let s=new Map;return xe(e,t,(i,n,r)=>{i===Rs&&n==="Relationship"&&r.Id&&r.Type&&r.Target!==void 0&&s.set(r.Id,{type:r.Type,target:r.Target,targetMode:r.TargetMode==="External"?"External":"Internal"})}),s}function vs(e){let t=new Map,s=new Map;return xe(e,"[Content_Types].xml",(i,n,r)=>{i===Ns&&(n==="Default"&&r.Extension&&r.ContentType?t.set(r.Extension.toLowerCase(),r.ContentType):n==="Override"&&r.PartName&&r.ContentType&&s.set(r.PartName.replace(/^\//,""),r.ContentType))}),{defaults:t,overrides:s}}function Os(e,t){let s=e.overrides.get(t);if(s)return s;let i=t.lastIndexOf(".");if(!(i<0))return e.defaults.get(t.slice(i+1).toLowerCase())}function ce(e,t){if(/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(t)||t.includes("\\")||t.includes("\0"))return null;let s;try{s=decodeURIComponent(t)}catch{return null}let i=s.startsWith("/")?[]:e.split("/").slice(0,-1).filter(n=>n.length>0);for(let n of s.split("/"))if(!(n===""||n===".")){if(n===".."){if(i.length===0)return null;i.pop();continue}i.push(n)}return i.length>0?i.join("/"):null}var Ms=Buffer.from([208,207,17,224,161,177,26,225]);function $(e){try{return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?new TextDecoder("utf-8",{fatal:!0}).decode(e.subarray(3)):e.length>=2&&e[0]===255&&e[1]===254?new TextDecoder("utf-16le",{fatal:!0}).decode(e.subarray(2)):e.length>=2&&e[0]===254&&e[1]===255?new TextDecoder("utf-16be",{fatal:!0}).decode(e.subarray(2)):new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new l("DOCX_UNREADABLE","XML part is not valid UTF-8/UTF-16 text")}}function Ce(e,t){if(e.length>=8&&e.subarray(0,8).equals(Ms))throw new l("DOCX_ENCRYPTED_OR_LEGACY","password-protected Office file (or a legacy .doc renamed .docx) \u2014 remove the password / save as .docx and re-ingest");let s={maxEntries:t?.maxEntries??Ts,maxPartBytes:t?.maxPartBytes??bs,maxTotalBytes:t?.maxTotalBytes??As},i=ws(e,s.maxEntries),n=ks(e,s),r=new Map(i.map(h=>[h.name,h]));if(n.size!==i.length)throw new l("DOCX_UNREADABLE",`central directory lists ${i.length} entries, stream produced ${n.size}`);for(let[h,m]of n){let u=r.get(h);if(!u)throw new l("DOCX_UNREADABLE",`entry ${h} missing from central directory`);if(vt(m)!==u.crc)throw new l("DOCX_UNREADABLE",`CRC mismatch: ${h}`)}let a=n.get("_rels/.rels");if(!a)throw new l("DOCX_NOT_WORDPROCESSING","no package relationships (_rels/.rels missing)");let o=le($(a),"_rels/.rels"),c=null;for(let h of o.values()){if(!Fs.has(h.type)||h.targetMode!=="Internal")continue;let m=ce("",h.target);if(m!==null&&n.has(m)){c=m;break}}if(c===null)throw new l("DOCX_NOT_WORDPROCESSING","this zip is not a Word document (no officeDocument relationship)");let _=n.get("[Content_Types].xml");if(!_)throw new l("DOCX_NOT_WORDPROCESSING","package has no [Content_Types].xml");let p=Os(vs($(_)),c);if(!p||!Ss.some(h=>p.startsWith(h)))throw new l("DOCX_NOT_WORDPROCESSING",`this zip is not a Word document (main part content type: ${p??"unknown"} \u2014 pptx/xlsx or unknown package)`);let d=new Map;return{parts:n,mainPart:c,relsFor(h){let m=d.get(h);if(m)return m;let u=h.lastIndexOf("/"),b=`${u>=0?h.slice(0,u+1):""}_rels/${u>=0?h.slice(u+1):h}.rels`,g=n.get(b),E=g?le($(g),b):new Map;return d.set(h,E),E},resolveTarget:ce}}var Ee=Rt(Ct(),1);var Z=new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main","http://purl.oclc.org/ooxml/wordprocessingml/main"]),Ps=new Set(["http://schemas.openxmlformats.org/drawingml/2006/main","http://purl.oclc.org/ooxml/drawingml/main"]),Ls=new Set(["http://schemas.openxmlformats.org/officeDocument/2006/math","http://purl.oclc.org/ooxml/officeDocument/math"]),_e="urn:schemas-microsoft-com:vml",Et="http://schemas.openxmlformats.org/markup-compatibility/2006",J=class{constructor(t,s,i=n=>this.tokens.push(n)){this.partName=t;this.budget=s;this.sink=i}tokens=[];storyRefs=[];stack=[];skipUntilDepth=[];fields=[];runVanish=[];acStack=[];txbxDepths=[];drawing=null;failed=null;setSink(t){this.sink=t}fail(t){this.failed||(this.failed=t)}abort(t){throw!this.failed&&t instanceof l&&(this.failed=t),t}emit(t){this.failed||(this.drawing&&t.t==="text"&&this.txbxDepths.length>0&&(this.drawing.emittedContent=!0),this.sink(t))}suppressed(){return this.skipUntilDepth.length>0}inInstruction(){return this.fields.some(t=>!t.hasSeparate)}parent(){return this.stack.length>=2?this.stack[this.stack.length-2]:void 0}depth(){return this.stack.length}onOpen(t,s,i){if(this.failed)return;this.budget.nodesRemaining-=1,this.budget.nodesRemaining<0&&this.abort(new l("DOCX_UNREADABLE",`XML node budget exhausted (${this.partName})`)),(this.budget.nodesRemaining&4095)===0&&this.budget.deadline!==void 0&&Date.now()>this.budget.deadline&&this.abort(new l("DOCX_UNREADABLE",`conversion budget exhausted (${this.partName})`)),this.stack.push({uri:t,local:s});let n=this.depth();if(n>_t&&this.abort(new l("DOCX_UNREADABLE",`XML nesting exceeds ${_t} (${this.partName})`)),this.suppressed())return;if(t===Et&&s==="AlternateContent"){this.acStack.push({branchTaken:!1});return}if(t===Et&&(s==="Choice"||s==="Fallback")){let a=this.acStack[this.acStack.length-1];if(!a)return;a.branchTaken?this.skipUntilDepth.push(n):a.branchTaken=!0;return}let r=Z.has(t);if((r&&s==="txbxContent"||t===_e&&s==="textbox")&&this.txbxDepths.push(n),r&&(s==="del"||s==="moveFrom"||s==="sdtPr"||s==="delText"||s==="pPrChange"||s==="rPrChange"||s==="sectPrChange"||s==="tblPrChange"||s==="trPrChange"||s==="tcPrChange")){this.skipUntilDepth.push(n);return}if(Ls.has(t)&&(s==="oMath"||s==="oMathPara")){this.emit({t:"marker",value:"[equation omitted]"}),this.skipUntilDepth.push(n);return}if(r&&s==="altChunk"){this.emit({t:"marker",value:"[embedded content omitted]"}),this.skipUntilDepth.push(n);return}if(r&&s==="tabs"){this.skipUntilDepth.push(n);return}if(r){switch(s){case"r":this.runVanish.push(!1);break;case"vanish":{let a=i.val;this.parent()?.local==="rPr"&&a!=="false"&&a!=="0"&&this.runVanish.length>0&&(this.runVanish[this.runVanish.length-1]=!0);break}case"fldChar":{let a=i.fldCharType;if(a==="begin")this.fields.push({hasSeparate:!1});else if(a==="separate"){let o=this.fields[this.fields.length-1];o&&(o.hasSeparate=!0)}else if(a==="end"){let o=this.fields.pop();o&&!o.hasSeparate&&this.emit({t:"marker",value:"[field: no stored result]"})}break}case"tab":this.parent()?.local==="r"&&!this.textSuppressed()&&this.emit({t:"tab"});break;case"br":case"cr":this.textSuppressed()||this.emit({t:"break"});break;case"noBreakHyphen":this.textSuppressed()||this.emit({t:"text",value:"\u2011"});break;case"softHyphen":break;case"sym":this.textSuppressed()||this.emit({t:"marker",value:"[symbol]"});break;case"numPr":this.parent()?.local==="pPr"&&this.emit({t:"marker",value:"- "});break;case"footnoteReference":i.id!==void 0&&!this.textSuppressed()&&this.emit({t:"note-ref",noteKind:"footnote",id:i.id});break;case"endnoteReference":i.id!==void 0&&!this.textSuppressed()&&this.emit({t:"note-ref",noteKind:"endnote",id:i.id});break;case"headerReference":case"footerReference":{let a=i.id;if(a){let o=i.type==="first"?"first":i.type==="even"?"even":"default";this.storyRefs.push({kind:s==="headerReference"?"header":"footer",type:o,relId:a})}break}case"drawing":this.drawing||(this.drawing={relId:null,kind:"drawing",external:!1,found:!1,emittedContent:!1});break;case"pict":case"object":this.drawing||(this.drawing={relId:null,kind:"vml",external:!1,found:!1,emittedContent:!1});break}return}if(Ps.has(t)&&s==="blip"&&this.drawing&&!this.drawing.found){let a=this.relAttr(i,"embed"),o=this.relAttr(i,"link");a?(this.drawing.relId=a,this.drawing.external=!1,this.drawing.found=!0):o&&(this.drawing.relId=o,this.drawing.external=!0,this.drawing.found=!0);return}if(t===_e&&s==="imagedata"&&this.drawing&&!this.drawing.found){let a=this.relAttr(i,"id")??i.relid;a&&(this.drawing.relId=a,this.drawing.kind="vml",this.drawing.found=!0);return}}onClose(){let t=this.depth();this.skipUntilDepth[this.skipUntilDepth.length-1]===t&&this.skipUntilDepth.pop(),this.txbxDepths[this.txbxDepths.length-1]===t&&this.txbxDepths.pop();let i=this.stack.pop();if(!(!i||this.failed)&&!this.suppressed()){if(i.uri===Et&&i.local==="AlternateContent"){this.acStack.pop();return}if(Z.has(i.uri))switch(i.local){case"r":this.runVanish.pop();break;case"p":this.emit({t:"para-end"});break;case"tc":this.emit({t:"table-cell-end"});break;case"tr":this.emit({t:"table-row-end"});break;case"drawing":case"pict":case"object":{let n=this.drawing;if(this.drawing=null,!n)break;n.found?this.emit({t:"image",relId:n.relId,kind:n.kind,external:n.external}):n.emittedContent||this.emit({t:"marker",value:"[object omitted: drawing]"});break}}}}onText(t){if(this.failed||this.suppressed()||t.length===0)return;let s=this.stack[this.stack.length-1];!s||!Z.has(s.uri)||s.local==="t"&&(this.textSuppressed()||(this.budget.textCharsRemaining!==void 0&&(this.budget.textCharsRemaining-=t.length,this.budget.textCharsRemaining<0&&this.abort(new Error(`PROJECTION_TOO_LARGE: projection text exceeds the conversion cap during the walk (${this.partName}) \u2014 split the document and re-ingest`))),this.emit({t:"text",value:t})))}textSuppressed(){return this.inInstruction()?!0:this.runVanish.length>0&&this.runVanish[this.runVanish.length-1]}relAttr(t,s){return t[s]}run(t){let s=new Ee.SaxesParser({xmlns:!0});if(s.on("doctype",()=>{this.fail(new l("DOCX_UNREADABLE",`DOCTYPE not allowed (${this.partName})`))}),s.on("error",i=>{this.fail(new l("DOCX_UNREADABLE",`${this.partName}: ${i.message}`))}),s.on("opentag",i=>{let n={},r=Object.entries(i.attributes);r.length>fe&&this.abort(new l("DOCX_UNREADABLE",`too many attributes (${this.partName})`));for(let[a,o]of r)o.value.length>pe&&this.abort(new l("DOCX_UNREADABLE",`oversized attribute (${this.partName})`)),n[o.local||a]=o.value;this.onOpen(i.uri??"",i.local,n)}),s.on("closetag",()=>this.onClose()),s.on("text",i=>this.onText(i)),s.write(t).close(),this.failed)throw this.failed}};function De(e,t){let s=t.budget??{nodesRemaining:Number.MAX_SAFE_INTEGER},i=new J(t.partName,s);return i.run(e),{tokens:i.tokens,storyRefs:i.storyRefs}}var Dt=class extends J{notes=new Map;current=null;noteDepth=0;constructor(t,s){super(t,s),this.setSink(i=>this.current?.push(i))}onOpen(t,s,i){super.onOpen(t,s,i),!(!Z.has(t)||s!=="footnote"&&s!=="endnote")&&(i.type!==void 0&&i.type!=="normal"||(this.current=[],i.id!==void 0&&this.notes.set(i.id,this.current),this.noteDepth=this.depth()))}onClose(){let t=this.depth();super.onClose(),this.noteDepth===t&&(this.current=null,this.noteDepth=0)}};function Te(e,t){let s=new Dt(t.partName,t.budget??{nodesRemaining:Number.MAX_SAFE_INTEGER});return s.run(e),s.notes}var Is="v1",Bs="1.0.0+saxes6.0.0+fflate0.8.3+pngjs7.0.0+jpeg-js0.4.4",Xs=64,$s=16,Hs=12e6,Ws=6e6,Us=5e7,Vs=new Set(["http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes","http://purl.oclc.org/ooxml/officeDocument/relationships/footnotes"]),Gs=new Set(["http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes","http://purl.oclc.org/ooxml/officeDocument/relationships/endnotes"]),qs={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},js=new Set(["png","jpeg","webp"]);function zs(e){if(e==="body")return"in body";if(e.startsWith("header:"))return"in header";if(e.startsWith("footer:"))return"in footer";let t=/^(footnote|endnote):(.+)$/.exec(e);return t?`in ${t[1]} ${t[2]}`:`in ${e}`}var At=class{constructor(t,s){this.pkg=t;this.caps=s}inventory=[];blobs=new Map;delivered=[];n=0;deliveredBytes=0;firstRefByFp=new Map;count(){return this.n}occurrence(t,s,i){this.n+=1;let n=`i${this.n}`,r=zs(i),a=(g,E,S)=>{this.inventory.push({ref:n,loc:i,media_type:g,...S?.blob?{blob:S.blob}:{},...S?.appearance?{appearance:S.appearance}:{},delivery:E,...S?.duplicate_of?{duplicate_of:S.duplicate_of}:{}})},o=g=>`[img#${n} omitted: ${g}]`,c=t.relId!==null?this.pkg.relsFor(s).get(t.relId):void 0;if(t.external||c?.targetMode==="External")return a("application/octet-stream","external-image-not-fetched"),o("external-image-not-fetched");let _=c?this.pkg.resolveTarget(s,c.target):null,p=_!==null?this.pkg.parts.get(_):void 0;if(!p)return a("application/octet-stream","undecodable"),o("undecodable");let d=Ot(p),h=qs[d.format],m=wt(p);if(this.blobs.set(m,p),!js.has(d.format)){let g=d.format==="gif"||d.format==="bmp"||d.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";return a(h,g,{blob:m}),o(g)}if(d.width===void 0||d.height===void 0||d.width*d.height>this.caps.maxPixels)return a(h,"undecodable",{blob:m}),o("undecodable");let u;if(d.format==="png"||d.format==="jpeg"){let g=Mt(p,d.format);if(g===null)return a(h,"undecodable",{blob:m}),o("undecodable");u=kt(g.data,{width:g.width,height:g.height,channels:g.channels})}if(d.width<this.caps.dimensionFloor||d.height<this.caps.dimensionFloor)return a(h,"below-dimension-floor",{blob:m,appearance:u}),o("below-dimension-floor");let b=this.firstRefByFp.get(m);return b!==void 0?(a(h,"duplicate",{blob:m,appearance:u,duplicate_of:b}),`[img#${n}: image ${r} \u2014 same as img#${b}; cite img#${b}]`):p.byteLength>this.caps.imageMaxBytes?(a(h,"image-too-large",{blob:m,appearance:u}),o("image-too-large")):this.deliveredBytes+p.byteLength>this.caps.visionByteBudget?(a(h,"vision-byte-budget-reached",{blob:m,appearance:u}),o("vision-byte-budget-reached")):this.delivered.length>=this.caps.imageCap?(a(h,"image-cap-reached",{blob:m,appearance:u}),o("image-cap-reached")):(this.firstRefByFp.set(m,n),this.deliveredBytes+=p.byteLength,this.delivered.push(n),a(h,"selected",{blob:m,appearance:u}),`[img#${n}: image ${r}]`)}};function Tt(e,t){let s=[];for(let i of e)switch(i.t){case"text":s.push(i.value);break;case"tab":s.push(" ");break;case"break":s.push(`
11
+ `);break;case"para-end":s.push(`
12
+ `);break;case"table-cell-end":s[s.length-1]===`
13
+ `&&s.pop(),s.push(" ");break;case"table-row-end":s[s.length-1]===" "&&s.pop(),s.push(`
14
+ `);break;case"marker":s.push(i.value);break;case"note-ref":s.push(`[${i.noteKind} ${i.id}]`);break;case"image":{let n=t(i);n!==null&&s.push(n);break}}return s.join("")}function bt(e){let t=0;for(let s of e)s.t==="text"&&(t+=s.value.length);return t}function be(e,t,s){let i=e.parts.get(t);if(!i)throw new l("DOCX_UNREADABLE",`referenced part missing: ${t}`);return De($(i),{partName:t,budget:s})}async function ci(e,t){let s=Date.now()+(t?.budgetMs??me),i=u=>{if(Date.now()>s)throw new l("DOCX_UNREADABLE",`conversion budget exhausted (${u})`)},n=Ce(e),r={nodesRemaining:de,textCharsRemaining:2*4e5,deadline:s},a={dimensionFloor:t?.caps?.dimensionFloor??Xs,imageCap:t?.caps?.imageCap??$s,visionByteBudget:t?.caps?.visionByteBudget??Hs,imageMaxBytes:t?.caps?.imageMaxBytes??Ws,maxPixels:t?.caps?.maxPixels??Us},o=new At(n,a),c=be(n,n.mainPart,r);i(n.mainPart);let _=bt(c.tokens),p=[Tt(c.tokens,u=>o.occurrence(u,n.mainPart,"body"))],d=n.relsFor(n.mainPart),h=new Set;for(let u of["header","footer"])for(let b of c.storyRefs.filter(g=>g.kind===u)){let g=d.get(b.relId);if(!g||g.targetMode!=="Internal")continue;let E=n.resolveTarget(n.mainPart,g.target);if(E===null||!n.parts.has(E)||h.has(E))continue;h.add(E);let S=be(n,E,r);i(E),_+=bt(S.tokens);let R=b.type==="default"?`[${u}]`:`[${u} ${b.type}]`;p.push(`${R}
15
+ ${Tt(S.tokens,H=>o.occurrence(H,E,`${u}:${E}`))}`)}for(let[u,b]of[["footnote",Vs],["endnote",Gs]]){let g=[];for(let R of c.tokens)R.t==="note-ref"&&R.noteKind===u&&!g.includes(R.id)&&g.push(R.id);if(g.length===0)continue;let E=null;for(let R of d.values())if(b.has(R.type)&&R.targetMode==="Internal"){E=n.resolveTarget(n.mainPart,R.target);break}if(E===null||!n.parts.has(E))continue;let S=Te($(n.parts.get(E)),{partName:E,budget:r});i(E);for(let R of g){let H=S.get(R);if(!H)continue;_+=bt(H);let Ae=E;p.push(`[${u} ${R}]
16
+ ${Tt(H,Re=>o.occurrence(Re,Ae,`${u}:${R}`))}`)}}if(_===0&&o.count()===0)throw new l("DOCX_NO_TEXT","no extractable text or images \u2014 nothing citable in this document");let m=p.join("");return m.endsWith(`
17
+ `)||(m+=`
18
+ `),{projection:m,inventory:o.inventory,blobs:o.blobs,delivered:o.delivered,converter:{name:"ooxml-walk",version:Bs,policy:Is}}}export{Is as a,Bs as b,Xs as c,$s as d,Hs as e,Ws as f,Us as g,Tt as h,ci as i};
19
+ /*! Bundled license information:
20
+
21
+ xmlchars/xml/1.0/ed5.js:
22
+ (**
23
+ * Character classes and associated utilities for the 5th edition of XML 1.0.
24
+ *
25
+ * @author Louis-Dominique Dubeau
26
+ * @license MIT
27
+ * @copyright Louis-Dominique Dubeau
28
+ *)
29
+
30
+ xmlchars/xml/1.1/ed2.js:
31
+ (**
32
+ * Character classes and associated utilities for the 2nd edition of XML 1.1.
33
+ *
34
+ * @author Louis-Dominique Dubeau
35
+ * @license MIT
36
+ * @copyright Louis-Dominique Dubeau
37
+ *)
38
+
39
+ xmlchars/xmlns/1.0/ed3.js:
40
+ (**
41
+ * Character class utilities for XML NS 1.0 edition 3.
42
+ *
43
+ * @author Louis-Dominique Dubeau
44
+ * @license MIT
45
+ * @copyright Louis-Dominique Dubeau
46
+ *)
47
+ */
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as w,b as O}from"./chunk-R5T4RLF5.js";import{a as I}from"./chunk-KBM3XHAM.js";import{e as L}from"./chunk-IDX3TOPY.js";import{a as N,b as k}from"./chunk-BKM2LWU2.js";import{a as R,b as y,c as T,d as m,e as A,f as b,g as r}from"./chunk-QIGPXYMF.js";import{b as x}from"./chunk-5EOX4MEY.js";import{a as E}from"./chunk-RZ4F3BHX.js";import{a as g,j as v}from"./chunk-ZUGCHQFC.js";import{platform as X,arch as Y}from"os";import P from"fs";import M from"fs";import D from"path";var V=1e3,d=0,j=new Set([130,3]),a=class t{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,n={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=n}get enabled(){return this.logger!==null}event(e,n={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let i=m(this.ids,e,n);this.logger.log(R[e],e,e,C(i))}error(e,n={}){this.logger&&(this.logger.escalate(d),this.event("ASR_ERROR",{...n,error_code:e}))}child(e,n){return new t({...this.opts,envelope:{...this.ids,operation_id:n,parent_operation_id:this.ids.operation_id,verb:"design"}},this.errorState)}async lateBindContext(e){if(!(!this.logger||this.ids.context_instance_id))try{let{ensureStoreIds:n}=await import("./store-id-EOSGEKVK.js"),{ids:i,cloned:s}=n(e);this.ids.context_lineage_id=i.context_lineage_id,this.ids.context_instance_id=i.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}agentSession(e){this.ids.agent_session_id=e}spawnEnv(){if(!this.opts.telemetryEnabled)return{};let e={TESTMUAI_USER_SESSION_ID:this.ids.session_id,TESTMUAI_OPERATION_ID:this.ids.operation_id,TESTMUAI_CLIENT_VERSION:this.opts.clientVersion,TESTMUAI_TELEMETRY_PROXY_URL:this.opts.proxyUrl};return this.ids.context_instance_id&&(e.TESTMUAI_CONTEXT_INSTANCE_ID=this.ids.context_instance_id),e}traceTee(){return e=>{if(!this.logger)return;let n=typeof e.kind=="string"?e.kind.slice(0,64):"trace",i={...C(m(this.ids,"ASR_CMD_START",{})),trace_kind:n};typeof e.code=="string"&&(i.trace_code=e.code.slice(0,64)),delete i.event,this.logger.logStep(d,`trace_${n}`,n,i)}}wireTrace(e,n,i){if(!this.logger)return;i&&this.agentSession(i);let s=n&&typeof n=="object"?n:{};switch(e){case"spawn":this.event("ASR_AGENT_SPAWN",{tier:s.tier});break;case"session_paused":this.event("ASR_SESSION_PAUSED",s);break;case"commit":this.event("ASR_COMMIT",s);break;default:this.traceTee()({kind:e,code:typeof s.code=="string"?s.code:void 0})}}banner(){return`session: ${this.ids.session_id}`}supportFooter(){return`if this keeps failing, share this id with support: ${this.ids.session_id}`}async end(e){if(!this.ended){if(this.ended=!0,e.duration_ms===void 0&&(e={...e,duration_ms:Date.now()-this.createdAt}),this.logger)if(e.exit_code===0?this.logger.discardSteps(d):this.logger.escalate(d),e.exit_code>0&&!j.has(e.exit_code)&&!this.errorState.emitted&&this.event("ASR_ERROR",{error_code:e.exit_code===2?"usage_exit_unattributed":`exit_${e.exit_code}_unattributed`,exit_code:e.exit_code}),this.event("ASR_CMD_END",e),this.opts.longSession)await this.logger.shutdown();else{let n=await this.logger.flushOnce(V);(n==="failed"||n==="timeout")&&A(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),r(null)}}writeManifestLine(e){try{let n=x(this.ids.context_instance_id??null);M.mkdirSync(D.dirname(n),{recursive:!0});let i={ts:new Date().toISOString(),session_id:this.ids.session_id,operation_id:this.ids.operation_id,agent_session_id:this.ids.agent_session_id,verb:this.ids.verb,mode:this.ids.mode,exit_code:e};M.appendFileSync(n,JSON.stringify(i)+`
2
+ import{a as w,b as O}from"./chunk-R5T4RLF5.js";import{a as I}from"./chunk-KBM3XHAM.js";import{e as L}from"./chunk-IDX3TOPY.js";import{a as N,b as k}from"./chunk-BKM2LWU2.js";import{a as R,b as y,c as T,d as m,e as A,f as b,g as r}from"./chunk-56PAQAX5.js";import{b as x}from"./chunk-5EOX4MEY.js";import{a as E}from"./chunk-RZ4F3BHX.js";import{a as g,j as v}from"./chunk-7F2ZV46B.js";import{platform as X,arch as Y}from"os";import P from"fs";import M from"fs";import D from"path";var V=1e3,d=0,j=new Set([130,3]),a=class t{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,n={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=n}get enabled(){return this.logger!==null}event(e,n={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let i=m(this.ids,e,n);this.logger.log(R[e],e,e,C(i))}error(e,n={}){this.logger&&(this.logger.escalate(d),this.event("ASR_ERROR",{...n,error_code:e}))}child(e,n){return new t({...this.opts,envelope:{...this.ids,operation_id:n,parent_operation_id:this.ids.operation_id,verb:"design"}},this.errorState)}async lateBindContext(e){if(!(!this.logger||this.ids.context_instance_id))try{let{ensureStoreIds:n}=await import("./store-id-EOSGEKVK.js"),{ids:i,cloned:s}=n(e);this.ids.context_lineage_id=i.context_lineage_id,this.ids.context_instance_id=i.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}agentSession(e){this.ids.agent_session_id=e}spawnEnv(){if(!this.opts.telemetryEnabled)return{};let e={TESTMUAI_USER_SESSION_ID:this.ids.session_id,TESTMUAI_OPERATION_ID:this.ids.operation_id,TESTMUAI_CLIENT_VERSION:this.opts.clientVersion,TESTMUAI_TELEMETRY_PROXY_URL:this.opts.proxyUrl};return this.ids.context_instance_id&&(e.TESTMUAI_CONTEXT_INSTANCE_ID=this.ids.context_instance_id),e}traceTee(){return e=>{if(!this.logger)return;let n=typeof e.kind=="string"?e.kind.slice(0,64):"trace",i={...C(m(this.ids,"ASR_CMD_START",{})),trace_kind:n};typeof e.code=="string"&&(i.trace_code=e.code.slice(0,64)),delete i.event,this.logger.logStep(d,`trace_${n}`,n,i)}}wireTrace(e,n,i){if(!this.logger)return;i&&this.agentSession(i);let s=n&&typeof n=="object"?n:{};switch(e){case"spawn":this.event("ASR_AGENT_SPAWN",{tier:s.tier});break;case"session_paused":this.event("ASR_SESSION_PAUSED",s);break;case"commit":this.event("ASR_COMMIT",s);break;default:this.traceTee()({kind:e,code:typeof s.code=="string"?s.code:void 0})}}banner(){return`session: ${this.ids.session_id}`}supportFooter(){return`if this keeps failing, share this id with support: ${this.ids.session_id}`}async end(e){if(!this.ended){if(this.ended=!0,e.duration_ms===void 0&&(e={...e,duration_ms:Date.now()-this.createdAt}),this.logger)if(e.exit_code===0?this.logger.discardSteps(d):this.logger.escalate(d),e.exit_code>0&&!j.has(e.exit_code)&&!this.errorState.emitted&&this.event("ASR_ERROR",{error_code:e.exit_code===2?"usage_exit_unattributed":`exit_${e.exit_code}_unattributed`,exit_code:e.exit_code}),this.event("ASR_CMD_END",e),this.opts.longSession)await this.logger.shutdown();else{let n=await this.logger.flushOnce(V);(n==="failed"||n==="timeout")&&A(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),r(null)}}writeManifestLine(e){try{let n=x(this.ids.context_instance_id??null);M.mkdirSync(D.dirname(n),{recursive:!0});let i={ts:new Date().toISOString(),session_id:this.ids.session_id,operation_id:this.ids.operation_id,agent_session_id:this.ids.agent_session_id,verb:this.ids.verb,mode:this.ids.mode,exit_code:e};M.appendFileSync(n,JSON.stringify(i)+`
3
3
  `,{flag:"a",mode:384})}catch{}}};function C(t){let e={event:t.event,session_id:t.session_id,operation_id:t.operation_id,verb:t.verb,mode:t.mode,component:t.component,seq:t.seq,context_lineage_id:t.context_lineage_id,context_instance_id:t.context_instance_id};t.parent_operation_id&&(e.parent_operation_id=t.parent_operation_id),t.agent_session_id&&(e.agent_session_id=t.agent_session_id);for(let[n,i]of Object.entries(t.context))e[n]=i;return e}var u=process.env.KANE_TELEMETRY_URL||v;function B(){return process.env.TESTMUAI_BASE_URL?"custom":process.env.TESTMUAI_ENV==="stage"?"stage":"prod"}function _e(t){let e=process.env.KANE_TELEMETRY!=="0"&&(!process.env.VITEST||process.env.KANE_TELEMETRY==="1"),n=t.env??B(),i=null;if(t.resumeSid&&t.contextRoot)try{let o=L(t.contextRoot,t.resumeSid);o?.user_session_id&&(i=o.user_session_id)}catch{}if(!i&&t.applyPlanPath)try{let o=JSON.parse(P.readFileSync(t.applyPlanPath,"utf8"));o.telemetry?.user_session_id&&(i=o.telemetry.user_session_id)}catch{}let s=i!==null;i||(i=y());let l=null,c=null,f=!1;if(t.contextRoot&&P.existsSync(t.contextRoot))if(t.write&&e){let o=k(t.contextRoot);l=o.ids.context_lineage_id,c=o.ids.context_instance_id,f=o.cloned}else{let o=N(t.contextRoot);l=o?.context_lineage_id??null,c=o?.context_instance_id??null}let h={session_id:i,operation_id:T(),context_lineage_id:l,context_instance_id:c,verb:t.verb,mode:t.mode,component:"kane-cli"},_=null;if(e){let o=I(n),S={org_id:o.org_id??"",user_id:o.user_id??"",machine_id:o.machine_id,email:null,email_domain:"",user_type:o.user_type??"unknown",env:o.env,plan:o.plan??"unknown"},U=t.mode==="interactive"||t.mode==="cli"?"cli":"agent";_=new w({proxyUrl:u,sessionId:i,identity:S,device:{cli_version:g,platform:X(),arch:Y(),host_agent:O(),invocation_mode:U},getToken:async()=>null}),t.longSession&&_.start()}let p=new a({envelope:h,logger:_,longSession:!!t.longSession,proxyUrl:u,clientVersion:`kane-cli/${g}`,telemetryEnabled:e});return e&&(r(h),p.event("ASR_CMD_START",{resumed:s,applied_plan:!!t.applyPlanPath}),f&&p.event("ASR_CONTEXT_CLONED"),b(async o=>{try{return(await E(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok}catch{return!1}}).catch(()=>{})),p}export{B as a,_e as b};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{d as ae,e as ue}from"./chunk-AXTPNZPX.js";import{a as oe}from"./chunk-L2TV4G56.js";import{b as K,d as se}from"./chunk-6KPPGMO2.js";import{d as ie}from"./chunk-NVGBE2DR.js";var ge=new Set(["approve","edit","reject"]);function pe(s,t){return`chatop:${t}:${s.target??"new"}:${s.op}:${s.seq}`}function me(s,t,y,k){let c=pe(s,t),h=s.payload;switch(s.op){case"approve":return{kind:"approve",target:s.target,expectedCid:s.expected_cid,eventId:c};case"edit":{let{reason:o,...v}=h;return{kind:"edit",target:s.target,expectedCid:s.expected_cid,edit:v,reason:o,eventId:c}}case"enhance":return{kind:"enhance",target:s.target,expectedCid:s.expected_cid,edges:h.edges??[],eventId:c};case"reject":return{kind:"reject",target:s.target,expectedCid:s.expected_cid,reason:h.reason??"",redirectTo:h.redirect_to,eventId:c};case"add":{let o=h.proposal_item??{},v=String(o.label??"");if(!y.mint_gate.includes(v))throw new Error(`GATED_LABEL: cannot mint "${v}" (gate: ${y.mint_gate.join(", ")})`);let l=o.cite??{},m=o.conv_source_id??k;if(!m||typeof l.turn!="number"||!l.quote)throw new Error("INVALID_ADD: a chat add requires a conversation cite {turn, quote} and conv_source_id");let _=o.content,C=_&&typeof _=="object"&&!Array.isArray(_)&&Object.keys(_).length>0?_:null,w=new Set(["label","cite","conv_source_id","content","rationale","edges"]),x=C??Object.fromEntries(Object.entries(o).filter(([D])=>!w.has(D)));return{kind:"add",label:v,content:x,cite:{turn:l.turn,quote:l.quote},convSourceId:m,rationale:o.rationale,eventId:c}}}}function ce(s,t,y={}){let k=y.turn??0,c=[],h=[];for(let l of s)(l.op==="add"||l.op==="enhance")&&h.push(l);let o=new Map;for(let l of s){if(!ge.has(l.op)||!l.target)continue;let m=o.get(l.target)??[];m.push(l),o.set(l.target,m)}for(let[l,m]of o){let _=Math.max(...m.map(w=>w.seq)),C=m.filter(w=>w.seq===_);if(C.length>1){c.push({target:l,seq:_,kinds:C.map(w=>w.op)});continue}h.push(C[0])}return{chatOps:h.sort((l,m)=>l.seq-m.seq).map(l=>me(l,k,t,y.convSourceId)),ambiguous:c}}function fe(s){let t=[];return s.questions.forEach((y,k)=>{if(s.resolution[k])return;let c=y.recommended_index!=null?y.options[y.recommended_index]?.label:void 0;c!=null&&t.push(y.risk==="high"?`${c} \u203C`:c)}),t.length>3?`${t.slice(0,3).join(" \xB7 ")} \xB7 +${t.length-3} more`:t.join(" \xB7 ")}function le(s){let t=s.text.replace(/\?+\s*$/,"");return t.length<=36?t:`${t.slice(0,33)}\u2026`}function he(s){return s.use_cases??[]}var ke={acs:"acceptance criteria",scenarios:"scenarios",exercises:"exercises",tests:"tests",gaps:"gaps"};function be(s){let t=[],y=[],k=(o,v)=>{v.length!==0&&(y.push(o),t.push(...v))},c=o=>typeof o=="string"&&/^[a-z]{1,4}\d{1,4}$/i.test(o)?o:null,h=o=>{let v=c(o.automates)??"1 scenario",l=o.verifies??[],m=l.map(c).filter(w=>w!==null).slice(0,2),_=l.length-m.length,C=m.length?`${m.join(" ")}${_>0?` +${_}`:""}`:`${l.length} ACs`;return`covers ${v} \xB7 verifies ${C}`};return k("acs",(s.acs??[]).map(o=>({temp_ref:o.temp_ref,title:o.text,kind:"ac",badge:String(o.kind),extra:{...o.expected_answer?{expects:`${String(o.expected_answer.operator??"")} \xB7 ${String(o.expected_answer.operand??"")}`}:{},"scoped to":o.scoped_to??"(use-case)"}}))),k("scenarios",(s.scenarios??[]).map(o=>({temp_ref:o.temp_ref,title:o.title,kind:"scenario",badge:o.case_type,why:o.intent,depends_on_hint:o.depends_on??[],extra:{technique:o.technique_notes}}))),k("exercises",(s.exercises??[]).map(o=>({temp_ref:c(o.scenario)??"wiring",title:`${c(o.scenario)??"scenario"} exercises ${c(o.ac)??"1 AC"}`,kind:"exercise",badge:"wires",why:o.rationale}))),k("tests",(s.tests??[]).map(o=>({temp_ref:o.temp_ref,title:o.title,kind:"test",why:h(o),depends_on_hint:o.reuses??[],extra:{automates:String(o.automates??"?"),verifies:(o.verifies??[]).join(", "),check:o.check?`${String(o.check.kind)} vs ${String(o.check.verified_against)}`:"?"}}))),k("gaps",(s.gaps??[]).map(o=>({temp_ref:o.temp_ref??o.ref??"?",title:String(o.question?.header??o.kind),kind:"gap",badge:o.kind,why:o.risk_rationale}))),{items:t,heading:y.join(" + ")||"design"}}function Se(s={}){let t={turns:[],thinking:ae(),pending:null,confirm:null,status:"idle",ledger:[],activeTurn:null,stream:null,checkpoint:!1},y=e=>{let n=[],r=e.minted.map(a=>a.slug).filter(Boolean);r.length&&n.push(`added ${r.join(", ")}`);let i=e.applied.length-e.minted.length;return i>0&&n.push(`${i} change${i===1?"":"s"} applied`),e.staleDelta.length&&n.push(`stales ${e.staleDelta.length}`),n.join(" \xB7 ")||"no changes"},k=[];s.onRender&&k.push(s.onRender);let c=0,h=0,o=null,v=null,l=null,m=[],_=0,C=e=>{if(!(!l||!s.contextDir||!e.trim()))try{let n=s.refreshGraph?.()??s.graph;if(!n)return;se({contextDir:s.contextDir,graph:n,sourceId:l,text:e,by:s.by??{kind:"human",id:"owner"}})}catch{}},w=e=>{if(!l||!s.contextDir)return;let n=s.refreshGraph?.()??s.graph,r=n?.heads.get(l),i=n?.convChains.get(l);if(!n||typeof r!="string"||!i)return;let a=n.getNode(r)?.content?.blob,u=typeof a=="string"?ie(s.contextDir,a)?.toString("utf8")??"":"";if(u)for(let f of e){if(f.kind!=="add"||f.convSourceId!==l)continue;let F=K(u,f.cite.turn);if(!(F!==null&&F.includes(f.cite.quote)))for(let $=i.turns;$>=1;$--){let z=K(u,$);if(z!==null&&z.includes(f.cite.quote)){f.cite={...f.cite,turn:$};break}}}},x={startedAt:null,thinkMs:0,toolCalls:0,tools:new Map},D=()=>{x.startedAt??=Date.now()},A=()=>{if(x.toolCalls>0){let e=x.startedAt!=null?Math.max(1,Math.round((Date.now()-x.startedAt)/1e3)):Math.max(1,Math.round(x.thinkMs/1e3));g({kind:"worked",durS:e,toolCalls:x.toolCalls,tools:[...x.tools.entries()].map(([n,r])=>({name:n,n:r}))})}x.startedAt=null,x.thinkMs=0,x.toolCalls=0,x.tools.clear()},I=null,G=new Map,V=e=>JSON.stringify([e.id,e.text,e.options.map(n=>n.label)]),q=null,J=new Map,U=new Map,Y=null,p=()=>{j&&(clearTimeout(j),j=null);for(let e of k)e()},j=null,X=()=>{j||(j=setTimeout(()=>{j=null;for(let e of k)e()},80))},B=0,g=e=>{e.kind==="childClose"&&B>0&&(B-=1),B>0&&e.kind!=="childOpen"&&e.kind!=="childBack"&&(e.era=B),e.kind==="childOpen"&&(B+=1),t.ledger.push(e)},E=null,W=!1,L=(e=!1)=>{E?g({kind:"agent",text:E}):e&&W&&g({kind:"note",text:'chat to refine ("looks good" approves; /done finishes)'}),E=null,W=!1},de=()=>{E=null,W=!1},P=null,H=e=>{if(P){if(e)for(let n of P.items){let r=e.get(n.temp_ref);r&&(n.logical_id=r)}g({kind:"turn",...P}),P=null}},M=()=>{H(),t.activeTurn&&(t.activeTurn=null)},Z=(e,n)=>n.choice||(n.selected_index!=null?e.options[n.selected_index]?.label??"?":"?"),N=()=>{let e=t.pending;if(!e)return;if(!e.resolution.every(Boolean)){e.cursor=e.resolution.findIndex(i=>i===null);return}let n=e.questions.map((i,a)=>{let u=e.resolution[a];return u.form==="deferred"?{id:i.id,selected_index:null,free_text:null}:{id:i.id,selected_index:u.selected_index,free_text:u.free_text}});t.pending=null,t.status=t.status==="pausing"?"pausing":"streaming",t.status==="streaming"&&(t.busySince=Date.now());let r=I;I=null,r?.(n)},R=(e,n)=>{let r=t.pending,i=r.questions[e],a=r.resolution[e];r.resolution[e]=n;let u=le(i);a?g({kind:"answer",receipt:{form:"changed",qNum:e+1,stub:u,choice:Z(i,n),prev:a.choice}}):n.form==="deferred"?g({kind:"answer",receipt:{form:"deferred",qNum:e+1,stub:u}}):g({kind:"answer",receipt:{form:n.form,qNum:e+1,stub:u,choice:Z(i,n)}})},ee=()=>{let e=t.pending;e&&(e.questions.forEach((n,r)=>{e.resolution[r]||R(r,{form:"deferred",selected_index:null,free_text:null,choice:""})}),N())},Q=new Map,te=e=>{Q.clear();let n={high:0,med:1,low:2};return e=e.map((r,i)=>({q:r,i})).sort((r,i)=>(n[r.q.risk]??3)-(n[i.q.risk]??3)||r.i-i.i).map(({q:r})=>r),{questions:e,cursor:0,resolution:e.map(()=>null)}};return{state:t,explainLines(e){if(!s.explain||!s.graph||s.contextDir===void 0)return null;let n=s.explain(s.contextDir,s.graph,e);return n.target?[`${n.target.label} ${n.target.slug??n.target.cid.slice(0,19)}:`,...n.entries.map(r=>` [${r.kind}] ${r.rationale??r.detail}`)]:null},explainRef(e){if(!s.explain||!s.graph||s.contextDir===void 0){g({kind:"note",text:"explain isn't available here"}),p();return}let n=s.explain(s.contextDir,s.graph,e),r=n.target?[`${n.target.label} ${n.target.slug??n.target.cid.slice(0,19)}:`,...n.entries.map(i=>` [${i.kind}] ${i.rationale??i.detail}`)].join(`
3
+ `):`unknown ref: ${e}`;g({kind:"note",text:r}),p()},subscribe(e){return k.push(e),()=>{let n=k.indexOf(e);n>=0&&k.splice(n,1)}},submit(e){if(t.confirm&&(t.confirm=null),!t.pending){if(!o){t.turns.push({role:"user",text:e}),g({kind:"user",text:e}),t.notice="the agent isn't running \u2014 nothing sent",p();return}for(t.notice=void 0,t.checkpoint=!1,L(),t.turns.push({role:"user",text:e}),g({kind:"user",text:e}),C(e),t.status="streaming",t.busySince=Date.now(),D(),t.error=void 0,h+=1;m.length>0;)h+=1,o({type:"user_message",message_id:`u${h}-receipt`,text:m.shift()});o({type:"user_message",message_id:`u${h}`,text:e}),p()}},attachSender(e){let n=o;return o=e,()=>{o=n}},attachOnCommitted(e){v=e},attachConversationSource(e){l=e},attachSession(e){s.session=e},holdReceipt(e){m.push(e),t.checkpoint=!0,p()},drainHeldReceipts(){return m.splice(0,m.length)},peekHeldReceipts(){return[...m]},submitAnswer(e,n){let r=t.pending,i=r?.questions[e],a=i?.options[n]?.label;!r||!i||a==null||(R(e,{form:"answered",selected_index:n,free_text:null,choice:a}),N(),p())},submitFreeText(e,n){let r=t.pending,i=r?.questions[e],a=n.trim();!r||!i||!a||(R(e,{form:"answered",selected_index:null,free_text:a,choice:a}),N(),p())},deferBatch(e){let n=t.pending;if(!n||!I)return;n.questions.forEach((i,a)=>{let u=n.resolution[a];u&&u.form==="answered"&&G.set(V(i),u)}),t.pending=null,t.status=t.status==="pausing"?"pausing":"streaming",t.status==="streaming"&&(t.busySince=Date.now()),g({kind:"note",text:`questions set aside \u2014 source ${e.source_id} landed; the agent reads it next`});let r=I;I=null,r({deferred:!0,ingested:e}),p()},submitAnswerWithText(e,n,r){let i=t.pending,a=i?.questions[e],u=a?.options[n]?.label;if(!i||!a||u==null)return;let f=r.trim();R(e,{form:"answered",selected_index:n,free_text:f||null,choice:f?`${u} \u2014 ${f}`:u}),N(),p()},toggleOption(e,n){let r=t.pending?.questions[e];if(!r||r.options[n]==null)return;let i=Q.get(e)??new Set;i.has(n)?i.delete(n):i.add(n),Q.set(e,i),p()},multiSelection(e){return[...Q.get(e)??[]].sort((n,r)=>n-r)},confirmMulti(e){let n=t.pending,r=n?.questions[e];if(!n||!r)return;let i=[...Q.get(e)??[]].sort((u,f)=>u-f).map(u=>r.options[u]?.label).filter(u=>u!=null);if(i.length===0)return;Q.delete(e);let a=i.join(", ");R(e,{form:"answered",selected_index:null,free_text:a,choice:a}),N(),p()},goWithRecommendations(){let e=t.pending;if(!e)return{picks:""};let n=fe(e),r=null;return e.questions.forEach((i,a)=>{if(e.resolution[a])return;let u=i.recommended_index,f=u!=null?i.options[u]?.label:void 0;if(f==null){r===null&&(r=a);return}R(a,{form:"assumed",selected_index:u,free_text:null,choice:f})}),r!==null?(e.cursor=r,p(),{blocked:r}):(N(),p(),{picks:n})},reopenQuestion(){let e=t.pending;if(!e)return;let n=e.cursor<0?e.questions.length:e.cursor;for(let r=n-1;r>=0;r--)if(e.resolution[r]){e.cursor=r,p();return}},continueParked(){if(o){for(t.checkpoint=!1,g({kind:"continued"});m.length>0;)h+=1,o({type:"user_message",message_id:`u${h}-receipt`,text:m.shift()});h+=1,o({type:"user_message",message_id:`u${h}`,text:"continue"}),t.status="streaming",t.busySince=Date.now(),D(),p()}},note(e){g({kind:"note",text:e}),p()},finalizeForExit(){M(),A(),L(),t.stream=null,p()},aliasOf(e){return U.get(e)},registerAliases(e){for(let n of e)U.set(n.ref,n.cid);H(new Map(e.filter(n=>n.id).map(n=>[n.ref,n.id]))),p()},setWorking(e){if(e!=null){if(t.status!=="idle"&&t.status!=="working")return;t.status==="idle"&&(t.busySince=Date.now()),D(),t.status="working",t.workingLabel=e}else{if(t.status!=="working")return;t.status="idle",t.workingLabel=void 0,t.busySince=void 0}p()},ledger(e){e.kind==="commit"&&H(),e.kind==="error"&&(M(),A(),L()),g(e),e.kind==="commit"&&(e.ok?L(!0):de()),p()},senderAlive(){return o!=null},completeSession(){ee(),o?.({type:"session_complete"}),t.status="idle",t.busySince=void 0,p()},requestPause(){ee(),t.status="pausing",t.busySince=void 0;let e=o;Promise.resolve().then(()=>e?.({type:"pause"})),p()},ask(e){t.pending=te(e),J=new Map(e.map((r,i)=>[r.id,i+1])),t.status="awaiting-input",t.busySince=void 0;let n=new Promise(r=>{I=r});if(G.size>0){let r=0;e.forEach((i,a)=>{let u=V(i),f=G.get(u);f&&(G.delete(u),R(a,{...f}),r+=1)}),r>0&&g({kind:"note",text:`your earlier answer${r>1?"s are":" is"} pre-filled \u2014 press enter to send, or pick a different answer`})}return p(),n},attachIngest(e){let n=q;return q=e,()=>{q===e&&(q=n)}},canIngest(){return q!==null},async ingestAttach(e){let n=q,r=e.trim();if(!n||!r)return;let i;try{i=await n(r)}catch(a){i={ok:!1,error:a instanceof Error?a.message:String(a)}}i.ok||(g({kind:"note",text:i.error??"the source could not be ingested"}),p())},noteCoercion(e,n){g({kind:"answer",receipt:{form:"assumed",qNum:J.get(e.id)??0,stub:le(e),choice:n,note:"your typed answer couldn't be used here"}}),p()},onAgentEvent(e){switch(e.type){case"reasoning_delta":case"reasoning_done":case"tool_activity":case"decision_activity":{let n=t.thinking;if(t.thinking=ue(n,e),t.thinking!==n&&(e.type==="reasoning_done"&&e.present?(D(),x.thinkMs+=e.took_ms):e.type==="tool_activity"&&e.status!=="started"&&(D(),x.toolCalls+=1,x.tools.set(e.name,(x.tools.get(e.name)??0)+1))),e.type==="reasoning_delta"){X();return}break}case"usage":t.credits={turn:e.credits,total:e.total_credits};break;case"text_delta":{let n=Y;if(n&&(e.turn_id<n.turn_id||e.turn_id===n.turn_id&&e.attempt<n.attempt))return;(!n||n.turn_id!==e.turn_id||n.attempt!==e.attempt)&&(Y={turn_id:e.turn_id,attempt:e.attempt},t.stream={text:""}),t.stream={text:(t.stream?.text??"")+e.text},X();return}case"progress":break;case"proposal":{c+=1,M(),t.stream=null,t.busySince=void 0,A();let n=he(e.proposal),r=s.dedupFlags?.(e.proposal);if(r)for(let i of n){let a=r.get(i.temp_ref);a&&(i.matches_existing=a)}t.turns.push({role:"agent",turnIndex:c,items:n,text:e.narrative}),E=e.narrative??null,W=!0,t.activeTurn={turnIndex:c,heading:"use-cases",items:n},P={turnIndex:c,heading:"use-cases",items:n},(t.status==="streaming"||t.status==="working")&&(t.status="idle"),t.workingLabel=void 0;break}case"design":{c+=1,M(),t.stream=null,t.busySince=void 0,A();let{items:n,heading:r}=be(e.design),i=e.design.phase==="wiring"?"acceptance criteria + exercises":r.split(" + ").map(a=>ke[a]??a).join(" + ");g({kind:"banner",text:`designing: ${i}`}),t.turns.push({role:"agent",turnIndex:c,items:n,itemsHeading:r,text:e.narrative}),E=e.narrative??null,W=!0,t.activeTurn={turnIndex:c,heading:r,items:n},P={turnIndex:c,heading:r,items:n},(t.status==="streaming"||t.status==="working")&&(t.status="idle"),t.workingLabel=void 0;break}case"ask_user":A(),t.pending=te(e.questions),t.status="awaiting-input",t.busySince=void 0;break;case"chat_ops":{c+=1,M(),A(),t.stream=null,(t.status==="streaming"||t.status==="working")&&(t.status="idle",t.busySince=void 0,t.workingLabel=void 0);let n=e.chat_ops??e,r=Array.isArray(n.ops)?n.ops:[],i=n.text??e.text??"",a=s.refreshGraph?.()??s.graph,u=d=>U.get(d)??d,f=r.map(d=>{if(!d.target)return d;let b=u(d.target),S=d.expected_cid;if(S==null&&a){let re=a.resolve(b);re&&(S=a.tipOf(re.cid))}let O=d.payload?.redirect_to,T=O&&u(O);return b===d.target&&S===d.expected_cid&&T===O?d:{...d,target:b,expected_cid:S,...T!==O?{payload:{...d.payload,redirect_to:T}}:{}}}),F;try{if(!Array.isArray(n.ops))throw new Error("the agent sent an unreadable change set (no ops array) \u2014 say it again in different words");F=ce(f,s.descriptor??{mint_gate:[]},{turn:c,...l?{convSourceId:l}:{}})}catch(d){t.error=d instanceof Error?d.message:String(d),t.turns.push({role:"agent",turnIndex:c,text:i,narration:t.error}),i&&g({kind:"agent",text:i}),g({kind:"error",title:t.error,detail:[]});break}let{chatOps:$,ambiguous:z}=F;if(z.length>0){let d=z[0];t.confirm={kind:"ambiguity-confirm",prompt:`did you mean edit or ${d.kinds.filter(b=>b!=="edit").join("/")} on ${d.target}?`},t.turns.push({role:"agent",turnIndex:c,text:i}),i&&g({kind:"agent",text:i});break}if(w($),s.commitChatTurn&&$.length>0){let d=s.commitChatTurn({contextDir:s.contextDir??"",graph:s.refreshGraph?.()??s.graph,ops:$,by:s.by??{kind:"human",id:"owner"},...s.descriptor?.mint_gate?{mintable:s.descriptor.mint_gate}:{},...s.session?.state?.sid?{sid:s.session.state.sid}:{}});if(d.errors)t.error=d.errors.map(b=>b.detail).join("; "),t.turns.push({role:"agent",turnIndex:c,text:i}),g({kind:"commit",ok:!1,line:"commit failed \u2014 nothing landed",warnings:d.errors.map(b=>`${b.code}: ${b.detail}`)}),m.push(["COMMIT FAILED (chat turn) \u2014 nothing landed; do not assume any of your last ops applied.",...d.errors.map(b=>`- ${b.code}: ${b.detail}`),...d.errors.some(b=>b.code==="UNKNOWN_FIELD")?["If you were changing citations or matched-existing content, that is proposal territory (approve/re-propose) \u2014 a chat edit can only replace a node's own schema fields."]:[]].join(`
4
+ `)),i&&g({kind:"agent",text:i});else{d.applied.length>0&&s.session?.markApplied(d.applied);let b=y(d);t.turns.push({role:"agent",turnIndex:c,text:i,narration:b}),g({kind:"commit",ok:!0,line:b});let S=s.refreshGraph?.();if(S&&v&&v(S),S)try{_+=1;let ne=s.descriptor?.mint_gate?.includes("usecase")?"extract":"design",O=oe({verb:ne,commitN:_,phase:"chat",committed:d.minted.map(T=>({cid:T.cid,...T.slug?{logical_id:T.slug}:{}}))},S);m.push(O.text)}catch{}i&&g({kind:"agent",text:i})}}else t.turns.push({role:"agent",turnIndex:c,text:i}),i&&g({kind:"agent",text:i});C(i);break}case"done":case"session_complete":M(),A(),L(),t.status="idle",t.busySince=void 0,o=null;break;case"error":M(),A(),L(),t.stream=null,t.status="idle",t.busySince=void 0,t.error=e.message,o=null,g({kind:"error",title:e.message,detail:[]});break;case"session_paused":break;default:break}p()}}}export{fe as a,le as b,Se as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as b}from"./chunk-4NFCAGRK.js";import{c as k}from"./chunk-RFHMDQXZ.js";import{a as C}from"./chunk-VT54ARGE.js";import{q as m,r as u,s as f,t as x,u as y}from"./chunk-ZUGCHQFC.js";import{createServer as S}from"http";import{randomBytes as A}from"crypto";import{URL as L}from"url";var P=class{profile;environment;creds;oauth;constructor(r="default",o="prod",e){this.profile=r,this.environment=o,this.creds=e??new C,this.oauth=new b(o)}async login(){let{server:r,port:o}=await this.startCallbackServer(),e=y(o);try{let t=this.creds.loadClient(this.profile,this.environment),i=t?.redirect_uris;(!t||!i?.includes(e))&&(t=await this.oauth.registerClient(e),this.creds.saveClient(this.profile,this.environment,t));let c=t.client_id,[h,d]=b.generatePkce(),a=A(32).toString("hex"),n=this.oauth.buildAuthorizationUrl(c,d,a,e),l=await this.waitForCallback(r,o,n,a);if(!l)throw new Error("Login cancelled or timed out");let p=await this.oauth.exchangeCode(l,c,h,e),g={access_token:p.access_token,refresh_token:p.refresh_token,expires_at:Math.floor(Date.now()/1e3)+p.expires_in,scope:p.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,g),this.creds.setActiveProfile(this.profile),g}catch(t){throw r.close(),t}}startCallbackServer(){return new Promise((r,o)=>{let e=u,t=()=>{let i=S();i.on("error",c=>{c.code==="EADDRINUSE"&&e<f?(e++,t()):o(new Error(`Failed to start callback server: ${c.message}. Ports ${u}-${f} are all in use.`))}),i.listen(e,m,()=>{r({server:i,port:e})})};t()})}waitForCallback(r,o,e,t){return new Promise(i=>{let c=!1,h=setTimeout(()=>d(null),12e4),d=a=>{c||(c=!0,clearTimeout(h),r.close(),i(a))};r.on("request",(a,n)=>{let l=new L(a.url??"/",`http://${m}:${o}`);if(l.pathname!==x){n.writeHead(404),n.end();return}let p=l.searchParams.get("state"),g=l.searchParams.get("code");if(l.searchParams.get("error")){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),d(null);return}if(p!==t){n.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),d(null);return}n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),d(g)}),k(e).catch(a=>{let n=a instanceof Error?a.message:String(a);process.stderr.write(`[auth] Could not open browser: ${n}
2
+ import{c as k}from"./chunk-RFHMDQXZ.js";import{a as b}from"./chunk-J7KT44IC.js";import{a as C}from"./chunk-PXCMEI73.js";import{q as m,r as u,s as f,t as x,u as y}from"./chunk-7F2ZV46B.js";import{createServer as S}from"http";import{randomBytes as A}from"crypto";import{URL as L}from"url";var P=class{profile;environment;creds;oauth;constructor(r="default",o="prod",e){this.profile=r,this.environment=o,this.creds=e??new C,this.oauth=new b(o)}async login(){let{server:r,port:o}=await this.startCallbackServer(),e=y(o);try{let t=this.creds.loadClient(this.profile,this.environment),i=t?.redirect_uris;(!t||!i?.includes(e))&&(t=await this.oauth.registerClient(e),this.creds.saveClient(this.profile,this.environment,t));let c=t.client_id,[h,d]=b.generatePkce(),a=A(32).toString("hex"),n=this.oauth.buildAuthorizationUrl(c,d,a,e),l=await this.waitForCallback(r,o,n,a);if(!l)throw new Error("Login cancelled or timed out");let p=await this.oauth.exchangeCode(l,c,h,e),g={access_token:p.access_token,refresh_token:p.refresh_token,expires_at:Math.floor(Date.now()/1e3)+p.expires_in,scope:p.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,g),this.creds.setActiveProfile(this.profile),g}catch(t){throw r.close(),t}}startCallbackServer(){return new Promise((r,o)=>{let e=u,t=()=>{let i=S();i.on("error",c=>{c.code==="EADDRINUSE"&&e<f?(e++,t()):o(new Error(`Failed to start callback server: ${c.message}. Ports ${u}-${f} are all in use.`))}),i.listen(e,m,()=>{r({server:i,port:e})})};t()})}waitForCallback(r,o,e,t){return new Promise(i=>{let c=!1,h=setTimeout(()=>d(null),12e4),d=a=>{c||(c=!0,clearTimeout(h),r.close(),i(a))};r.on("request",(a,n)=>{let l=new L(a.url??"/",`http://${m}:${o}`);if(l.pathname!==x){n.writeHead(404),n.end();return}let p=l.searchParams.get("state"),g=l.searchParams.get("code");if(l.searchParams.get("error")){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),d(null);return}if(p!==t){n.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),d(null);return}n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),d(g)}),k(e).catch(a=>{let n=a instanceof Error?a.message:String(a);process.stderr.write(`[auth] Could not open browser: ${n}
3
3
  Please open this URL manually: ${e}
4
4
  `)})})}};function v(s){let r=s.state==="success",o=r?"#22c55e":"#ef4444",e=r?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)",t=r?'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg>':'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',i=s.autoClose?"<script>setTimeout(function(){try{window.close();}catch(e){}}, 1500);</script>":"";return`<!doctype html>
5
5
  <html lang="en">
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{x as s}from"./chunk-ZUGCHQFC.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost}}export{n as a};
2
+ import{x as s}from"./chunk-7F2ZV46B.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{join as e}from"path";function t(o=process.env){let r=o.KANE_ANDROID_HOME?.trim();return r?{root:r,platformToolsDir:e(r,"platform-tools")}:null}export{t as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{createRequire as Sr}from"module";var Ur=Sr("/"),H,Fr,Cr;try{H=Ur("worker_threads"),Fr=H.Worker,Cr=H.isMarkedAsUntransferable}catch{}var g=Uint8Array,k=Uint16Array,Dr=Int32Array,cr=new g([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),pr=new g([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Tr=new g([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gr=function(n,r){for(var t=new k(31),e=0;e<31;++e)t[e]=r+=1<<n[e-1];for(var i=new Dr(t[30]),e=1;e<30;++e)for(var l=t[e];l<t[e+1];++l)i[l]=l-t[e]<<5|e;return{b:t,r:i}},H=gr(cr,2),yr=H.b,Ir=H.r;yr[28]=258,Ir[258]=28;var wr=gr(pr,0),Br=wr.b,Rr=wr.r,or=new k(32768);for(f=0;f<32768;++f)B=(f&43690)>>1|(f&21845)<<1,B=(B&52428)>>2|(B&13107)<<2,B=(B&61680)>>4|(B&3855)<<4,or[f]=((B&65280)>>8|(B&255)<<8)>>1;var B,f,Q=(function(n,r,t){for(var e=n.length,i=0,l=new k(r);i<e;++i)n[i]&&++l[n[i]-1];var u=new k(r);for(i=1;i<r;++i)u[i]=u[i-1]+l[i-1]<<1;var o;if(t){o=new k(1<<r);var v=15-r;for(i=0;i<e;++i)if(n[i])for(var s=i<<4|n[i],c=r-n[i],a=u[n[i]-1]++<<c,h=a|(1<<c)-1;a<=h;++a)o[or[a]>>v]=s}else for(o=new k(e),i=0;i<e;++i)n[i]&&(o[i]=or[u[n[i]-1]++]>>15-n[i]);return o}),X=new g(288);for(f=0;f<144;++f)X[f]=8;var f;for(f=144;f<256;++f)X[f]=9;var f;for(f=256;f<280;++f)X[f]=7;var f;for(f=280;f<288;++f)X[f]=8;var f,mr=new g(32);for(f=0;f<32;++f)mr[f]=5;var f;var Zr=Q(X,9,1);var Er=Q(mr,5,1),er=function(n){for(var r=n[0],t=1;t<n.length;++t)n[t]>r&&(r=n[t]);return r},C=function(n,r,t){var e=r/8|0;return(n[e]|n[e+1]<<8)>>(r&7)&t},ir=function(n,r){var t=r/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(r&7)},qr=function(n){return(n+7)/8|0},L=function(n,r,t){return(r==null||r<0)&&(r=0),(t==null||t>n.length)&&(t=n.length),new g(n.subarray(r,t))};var Gr=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],p=function(n,r,t){var e=new Error(r||Gr[n]);if(e.code=n,Error.captureStackTrace&&Error.captureStackTrace(e,p),!t)throw e;return e},xr=function(n,r,t,e){var i=n.length,l=e?e.length:0;if(!i||r.f&&!r.l)return t||new g(0);var u=!t,o=u||r.i!=2,v=r.i;u&&(t=new g(i*3));var s=function(ur){var lr=t.length;if(ur>lr){var vr=new g(Math.max(lr*2,ur));vr.set(t),t=vr}},c=r.f||0,a=r.p||0,h=r.b||0,M=r.l,y=r.d,T=r.m,D=r.n,S=i*8;do{if(!M){c=C(n,a,1);var q=C(n,a+1,3);if(a+=3,q)if(q==1)M=Zr,y=Er,T=9,D=5;else if(q==2){var G=C(n,a,31)+257,O=C(n,a+10,15)+4,P=G+C(n,a+5,31)+1;a+=14;for(var E=new g(P),V=new g(19),w=0;w<O;++w)V[Tr[w]]=C(n,a+w*3,7);a+=O*3;for(var N=er(V),I=(1<<N)-1,$=Q(V,N,1),w=0;w<P;){var j=$[C(n,a,I)];a+=j&15;var z=j>>4;if(z<16)E[w++]=z;else{var x=0,U=0;for(z==16?(U=3+C(n,a,3),a+=2,x=E[w-1]):z==17?(U=3+C(n,a,7),a+=3):z==18&&(U=11+C(n,a,127),a+=7);U--;)E[w++]=x}}var d=E.subarray(0,G),F=E.subarray(G);T=er(d),D=er(F),M=Q(d,T,1),y=Q(F,D,1)}else p(1);else{var z=qr(a)+4,W=n[z-4]|n[z-3]<<8,R=z+W;if(R>i){v&&p(0);break}o&&s(h+W),t.set(n.subarray(z,R),h),r.b=h+=W,r.p=a=R*8,r.f=c;continue}if(a>S){v&&p(0);break}}o&&s(h+131072);for(var b=(1<<T)-1,rr=(1<<D)-1,Y=a;;Y=a){var x=M[ir(n,a)&b],Z=x>>4;if(a+=x&15,a>S){v&&p(0);break}if(x||p(2),Z<256)t[h++]=Z;else if(Z==256){Y=a,M=null;break}else{var _=Z-254;if(Z>264){var w=Z-257,J=cr[w];_=C(n,a,(1<<J)-1)+yr[w],a+=J}var nr=y[ir(n,a)&rr],tr=nr>>4;nr||p(3),a+=nr&15;var F=Br[tr];if(tr>3){var J=pr[tr];F+=ir(n,a)&(1<<J)-1,a+=J}if(a>S){v&&p(0);break}o&&s(h+131072);var fr=h+_;if(h<F){var hr=l-F,Mr=Math.min(F,fr);for(hr+h<0&&p(3);h<Mr;++h)t[h]=e[hr+h]}for(;h<fr;++h)t[h]=t[h-F]}}r.l=M,r.p=Y,r.b=h,r.f=c,M&&(c=1,r.m=T,r.d=y,r.n=D)}while(!c);return h!=t.length&&u?L(t,0,h):t.subarray(0,h)};var K=new g(0);var A=function(n,r){return n[r]|n[r+1]<<8},m=function(n,r){return(n[r]|n[r+1]<<8|n[r+2]<<16|n[r+3]<<24)>>>0},ar=function(n,r){return m(n,r)+m(n,r+4)*4294967296};var Or=(function(){function n(r,t){typeof r=="function"&&(t=r,r={}),this.ondata=t;var e=r&&r.dictionary&&r.dictionary.subarray(-32768);this.s={i:0,b:e?e.length:0},this.o=new g(32768),this.p=new g(0),e&&this.o.set(e)}return n.prototype.e=function(r){if(this.ondata||p(5),this.d&&p(4),!this.p.length)this.p=r;else if(r.length){var t=new g(this.p.length+r.length);t.set(this.p),t.set(r,this.p.length),this.p=t}},n.prototype.c=function(r){this.s.i=+(this.d=r||!1);var t=this.s.b,e=xr(this.p,this.s,this.o);this.ondata(L(e,t,this.s.b),this.d),this.o=L(e,this.s.b-32768),this.s.b=this.o.length,this.p=L(this.p,this.s.p/8|0),this.s.p&=7},n.prototype.push=function(r,t){this.e(r),this.c(t)},n})();function Pr(n,r){return xr(n,{i:2},r&&r.out,r&&r.dictionary)}var sr=typeof TextDecoder<"u"&&new TextDecoder,Nr=0;try{sr.decode(K,{stream:!0}),Nr=1}catch{}var dr=function(n){for(var r="",t=0;;){var e=n[t++],i=(e>127)+(e>223)+(e>239);if(t+i>n.length)return{s:r,r:L(n,t-1)};i?i==3?(e=((e&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,r+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?r+=String.fromCharCode((e&31)<<6|n[t++]&63):r+=String.fromCharCode((e&15)<<12|(n[t++]&63)<<6|n[t++]&63):r+=String.fromCharCode(e)}};function zr(n,r){if(r){for(var t="",e=0;e<n.length;e+=16384)t+=String.fromCharCode.apply(null,n.subarray(e,e+16384));return t}else{if(sr)return sr.decode(n);var i=dr(n),l=i.s,t=i.r;return t.length&&p(8),l}}var kr=function(n,r){return r+30+A(n,r+26)+A(n,r+28)},Hr=function(n,r,t){var e=A(n,r+28),i=A(n,r+30),l=zr(n.subarray(r+46,r+46+e),!(A(n,r+8)&2048)),u=r+46+e,o=Ar(n,u,i,t,m(n,r+20),m(n,r+24),m(n,r+42)),v=o[0],s=o[1],c=o[2];return[A(n,r+10),v,s,l,u+i+A(n,r+32),c]},Ar=function(n,r,t,e,i,l,u){var o=i==4294967295,v=l==4294967295,s=u==4294967295,c=r+t,a=o+v+s;if(e&&a){for(;r+4<c;r+=4+A(n,r+2))if(A(n,r)==1)return[o?ar(n,r+4+8*v):i,v?ar(n,r+4):l,s?ar(n,r+4+8*(v+o)):u,1];e<2&&p(13)}return[i,l,u,0]};var Lr=(function(){function n(){}return n.prototype.push=function(r,t){this.ondata(null,r,t)},n.compression=0,n})();var Vr=(function(){function n(){var r=this;this.i=new Or(function(t,e){r.ondata(null,t,e)})}return n.prototype.push=function(r,t){try{this.i.push(r,t)}catch(e){this.ondata(e,null,t)}},n.compression=8,n})();var Yr=(function(){function n(r){this.onfile=r,this.k=[],this.o={0:Lr},this.p=K}return n.prototype.push=function(r,t){var e=this;if(this.onfile||p(5),this.p||p(4),this.c>0){var i=Math.min(this.c,r.length),l=r.subarray(0,i);if(this.c-=i,this.d?this.d.push(l,!this.c):this.k[0].push(l),r=r.subarray(i),r.length)return this.push(r,t)}else{var u=0,o=0,v=void 0,s=void 0;this.p.length?r.length?(s=new g(this.p.length+r.length),s.set(this.p),s.set(r,this.p.length)):s=this.p:s=r;for(var c=s.length,a=this.c,h=a&&this.d,M=function(){var S=m(s,o);if(S==67324752){u=1,v=o,y.d=null,y.c=0;var q=A(s,o+6),z=A(s,o+8),W=q&2048,R=q&8,G=A(s,o+26),O=A(s,o+28);if(c>o+30+G+O){var P=[];y.k.unshift(P),u=2;var E=m(s,o+18),V=m(s,o+22),w=zr(s.subarray(o+30,o+=30+G),!W),N=Ar(s,o,O,2,E,V,0),I=N[0],$=N[1],j=N[3];R&&(I=-1-j),o+=O,y.c=I;var x,U={name:w,compression:z,start:function(){if(U.ondata||p(5),!I)U.ondata(null,K,!0);else{var d=e.o[z];d||U.ondata(p(14,"unknown compression type "+z,1),null,!1),x=I<0?new d(w):new d(w,I,$),x.ondata=function(Y,Z,_){U.ondata(Y,Z,_)};for(var F=0,b=P;F<b.length;F++){var rr=b[F];x.push(rr,!1)}e.k[0]==P&&e.c?e.d=x:x.push(K,!0)}},terminate:function(){x&&x.terminate&&x.terminate()}};I>=0&&(U.size=I,U.originalSize=$),y.onfile(U)}return"break"}else if(a){if(S==134695760)return v=o+=12+(a==-2&&8),u=3,y.c=0,"break";if(S==33639248)return v=o-=4,u=3,y.c=0,"break"}},y=this;o<c-4;++o){var T=M();if(T==="break")break}if(this.p=K,a<0){var D=u?s.subarray(0,v-12-(a==-2&&8)-(m(s,v-16)==134695760&&4)):s.subarray(0,o);h?h.push(D,!!u):this.k[+(u==2)].push(D)}if(u&2)return this.push(s.subarray(o),t);this.p=s.subarray(o)}t&&(this.c&&p(13),this.p=null)},n.prototype.register=function(r){this.o[r.compression]=r},n})();function Jr(n,r){for(var t={},e=n.length-22;m(n,e)!=101010256;--e)(!e||n.length-e>65558)&&p(13);var i=A(n,e+8);if(!i)return{};var l=m(n,e+16),u=m(n,e-20)==117853008;if(u){var o=m(n,e-12);u=m(n,o)==101075792,u&&(i=m(n,o+32),l=m(n,o+48))}for(var v=r&&r.filter,s=0;s<i;++s){var c=Hr(n,l,u),a=c[0],h=c[1],M=c[2],y=c[3],T=c[4],D=c[5],S=kr(n,D);l=T,(!v||v({name:y,size:h,originalSize:M,compression:a}))&&(a?a==8?t[y]=Pr(n.subarray(S,S+h),{out:new g(M)}):p(14,"unknown compression type "+a):t[y]=L(n,S,S+h))}return t}export{Lr as a,Vr as b,Yr as c,Jr as d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as u,c as p}from"./chunk-DBKNJRJG.js";import{spawn as h}from"child_process";var k=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint"]);function v(g,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:u();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=g.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=h(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(g.session_id,n.auth)});if(t.stdin.write(JSON.stringify(g)+`
2
+ import{c as u,d as p}from"./chunk-WQPQNL4S.js";import{spawn as h}from"child_process";var k=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint"]);function v(g,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:u();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=g.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=h(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(g.session_id,n.auth)});if(t.stdin.write(JSON.stringify(g)+`
3
3
  `),n.onStderr){let e="";t.stderr.on("data",r=>{e+=r.toString("utf8");let i;for(;(i=e.indexOf(`
4
4
  `))>=0;){let o=e.slice(0,i);e=e.slice(i+1),o.trim()&&n.onStderr(o)}})}let d=new Promise(e=>{t.on("exit",(r,i)=>e({code:r,signal:i}))});async function*m(){let e="",r=!1;for await(let i of t.stdout){e+=i.toString("utf8");let o;for(;(o=e.indexOf(`
5
5
  `))>=0;){let l=e.slice(0,o).trim();if(e=e.slice(o+1),!l)continue;let c;try{c=JSON.parse(l)}catch{n.onWarn?.(`agent: skipping malformed line: ${l.slice(0,120)}`);continue}let s=c;if(!s||typeof s!="object"||!k.has(s.type)){n.onWarn?.(`agent: skipping unknown event type "${s&&typeof s=="object"?String(s.type??"?"):"?"}"`);continue}if(yield s,s.type==="done"){r=!0;break}}if(r)break}await d.catch(()=>{})}return{events:m(),send:e=>{t.stdin&&!t.stdin.destroyed&&t.stdin.write(JSON.stringify(e)+`
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as $}from"./chunk-MMBBQ4OZ.js";import{j as h}from"./chunk-IUEEFGEW.js";import{a as w}from"./chunk-RZ4F3BHX.js";import{c as v}from"./chunk-7F2ZV46B.js";import{spawn as V,spawnSync as _}from"child_process";import{createServer as K}from"net";import{mkdirSync as g,openSync as W,readFileSync as I,renameSync as j,rmSync as x,statSync as Y,writeFileSync as M}from"fs";import{readFile as q}from"fs/promises";import{dirname as l,join as y}from"path";var G=[4723,4724,4725,4726,4727,4728,4729,4730],X={emulator:4750,simulator:4790},z=40,E=2e3,D=3e4,T=500,Ce=["emulator","simulator"];function Q(e){return y(v,"mobile",`appium-server-${e}.log`)}function m(){return y(v,"mobile","appium-servers.json")}function Z(){return y(v,"mobile","appium-servers.lock")}var ee=1e4,re=50;function C(e){let r=Z();try{g(l(r),{recursive:!0})}catch{return e()}let n=!1;for(let o=0;o<re;o++)try{g(r),n=!0;break}catch{try{Date.now()-Y(r).mtimeMs>ee&&x(r,{recursive:!0,force:!0})}catch{}ne(10)}try{return e()}finally{if(n)try{x(r,{recursive:!0,force:!0})}catch{}}}function ne(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{}}function te(){try{let e=JSON.parse(I(m(),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}function oe(e){let r=m();g(l(r),{recursive:!0});let n=`${r}.tmp`;M(n,JSON.stringify(e,null,2)),j(n,r)}function se(e,r,n){return`Another mobile session is already running${n?` on ${n}`:""}. Wait for it to finish, or close the terminal running it.`}var A=class extends Error{constructor(n,o){super(n);this.port=o;this.name="DeviceBusyError"}};function ie(e){return w(e,{signal:AbortSignal.timeout(E)}).then(r=>r.ok,()=>!1)}async function ae(e,r){try{return(await w(`http://127.0.0.1:${e}/session/${r}`,{method:"DELETE",signal:AbortSignal.timeout(E)})).ok}catch{return!1}}function R(e){let r=e?.value;return Array.isArray(r)?r.map(n=>{let o=n??{},t=o.capabilities??o;return{...typeof o.id=="string"?{id:o.id}:{},caps:t}}):[]}async function ue(e){try{let r=await w(`http://127.0.0.1:${e}/sessions`,{signal:AbortSignal.timeout(E)});return r.ok?R(await r.json()):[]}catch{return[]}}var ce=["udid","appium:udid","deviceUDID","appium:deviceUDID","deviceName","appium:deviceName"];function L(){let e=r=>{try{let n=_("curl",["-s","--noproxy","*","--max-time","2",...r],{encoding:"utf8",timeout:5e3});return{ok:n.status===0,stdout:n.stdout??""}}catch{return{ok:!1,stdout:""}}};return{readState:()=>{try{let r=JSON.parse(I(m(),"utf8"));return Array.isArray(r)?r:[]}catch{return[]}},alive:b,getJson:r=>{let n=e([r]);if(n.ok)try{return JSON.parse(n.stdout)}catch{return}},del:r=>{let n=e(["-o","/dev/null","-w","%{http_code}","-X","DELETE",r]);return n.ok&&/^2\d\d$/.test(n.stdout.trim())}}}function Le(e,r={}){let n={...L(),...r},o=0;try{for(let t of n.readState()){if(!n.alive(t.pid))continue;let i=R(n.getJson(`http://127.0.0.1:${t.port}/sessions`));for(let s of i)s.id&&de(s.caps,e.udid,e.displayName)&&n.del(`http://127.0.0.1:${t.port}/session/${s.id}`)&&(o+=1)}}catch{}return o}function de(e,r,n){let o=[r,n].filter(t=>!!t).map(t=>t.toLowerCase());for(let t of ce){let i=e[t];if(typeof i=="string"&&o.includes(i.toLowerCase()))return!0}return!1}function pe(e,r,n){let o=W(n.logPath,"a"),t=V(e,r,{stdio:["ignore",o,o],detached:!0,env:{...process.env,...n.env}});return t.unref(),t.pid}async function le(e,r){for(let n=e;n<e+r;n++)if(await new Promise(t=>{let i=K();i.once("error",()=>t(!1)),i.once("listening",()=>i.close(()=>t(!0))),i.listen(n)}))return n;throw new Error(`No free port for the managed Appium server in ${e}-${e+r-1}.`)}function b(e){try{return process.kill(e,0),!0}catch{return!1}}function P(e){try{let r=_("ps",["-o","comm=","-p",String(e)],{encoding:"utf8",timeout:2e3});if(r.status!==0)return!1;let n=r.stdout.trim().toLowerCase();return n===""?!0:n.includes("node")||n.includes("kane")}catch{return!0}}function k(e){try{process.kill(e)}catch{}}async function me(){try{let e=JSON.parse(await q(m(),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}async function fe(e){let r=process.pid,n=e.filter(o=>o.owner===r);C(()=>{let o=[];for(let t of te())t.owner!==r&&(Se(t)?o.push(t):b(t.pid)&&k(t.pid));oe([...o,...n])})}function Se(e){return e.owner===void 0?!1:b(e.owner)&&P(e.owner)}function ve(){return{probe:ie,sessions:ue,deleteSession:ae,spawn:pe,freePort:le,alive:b,kill:k,readState:me,writeState:fe,owner:process.pid,depsEnv:e=>h().environment(e),bundleVersion:async e=>(await h().status(e)).version,nodeBinary:process.execPath,env:process.env,os:process.platform,now:()=>Date.now(),sleep:e=>new Promise(r=>setTimeout(r,e))}}function we(e,r,n){if(!e.platformToolsDir)return{};let o=n==="win32"?";":":",t=$(r),i=t?.root??l(e.platformToolsDir),s=t?.platformToolsDir??e.platformToolsDir;return{ANDROID_HOME:i,ANDROID_SDK_ROOT:i,PATH:r.PATH?`${s}${o}${r.PATH}`:s}}async function ge(e){let r=await e.readState(),n=[],o=[];for(let t of r)t.owner!==void 0&&e.alive(t.owner)&&(e.ownerIsOurs??P)(t.owner)?n.push(t):o.push(t);for(let t of o){let i=e.ownerIsOurs??P;e.alive(t.pid)&&i(t.pid)&&e.kill(t.pid)}return o.length>0&&await e.writeState(n),n}async function Je(e,r={}){if(r.appiumUrl)return{result:"external",url:r.appiumUrl};let n={...ve(),...r.deps},o=await ge(n),t=o.filter(a=>a.owner===n.owner),i=new Set(t.map(a=>a.port)),s=new Set(o.map(a=>a.port));if(r.device){let a=await ye(n,s,i,e);if(a!==null)throw new A(se(r.device,a.port,a.device),a.port)}let c=await n.bundleVersion(e),u=t.find(a=>a.deviceClass===e&&(a.bundleVersion??c)===c);if(u&&await n.probe(`http://127.0.0.1:${u.port}/status`))return{result:"reused",url:`http://127.0.0.1:${u.port}`};for(let a of t.filter(S=>S.deviceClass===e&&S!==u))n.kill(a.pid);u&&n.kill(u.pid);let d=await n.depsEnv(e);if(!d.appiumHome)throw new Error(`The managed dependencies for the ${e} class are not installed.
3
+ Run \`kane-cli doctor --target ${e} --install\` to install them, or pass --appium-url for an external server.`);let p=await n.freePort(X[e],z),O=`http://127.0.0.1:${p}`,J=l(d.appiumHome),U=y(J,"appium","node_modules","appium","index.js"),N=Q(e);r.onProgress?.(`starting the managed Appium server (${e}, port ${p})\u2026`);let f=n.spawn(n.nodeBinary,[U,"--port",String(p)],{env:{APPIUM_HOME:d.appiumHome,...we(d,n.env,n.os)},logPath:N}),B=n.now()+D,F=Math.ceil(D/T)+1;for(let a=0;a<F&&n.now()<B;a++)if(await n.sleep(T),await n.probe(`${O}/status`)){if(f!==void 0){let S=t.filter(H=>H.deviceClass!==e);await n.writeState([...S,{port:p,pid:f,owner:n.owner,deviceClass:e,...c?{bundleVersion:c}:{},startedAt:new Date(n.now()).toISOString()}])}return r.onProgress?.("Appium server ready"),{result:"started",url:O}}throw f!==void 0&&n.kill(f),new Error(`The managed Appium server (${e}) did not answer on ${p} within ${D/1e3}s.
4
+ Check its log: ${N}`)}async function ye(e,r=[],n=[],o){let t=new Set(n),i=new Set([...G,...r]);for(let s of i)if(!t.has(s))for(let c of await e.sessions(s)){if(!c.id)continue;if(o){let d=be(c.caps);if(d&&d!==o)continue}let u=De(c.caps);return{port:s,...u?{device:u}:{}}}return null}function be(e){let r=t=>{let i=e[t];return typeof i=="string"?i.toLowerCase():""},n=r("platformName")||r("appium:platformName");if(n.includes("ios"))return"simulator";if(n.includes("android"))return"emulator";let o=r("appium:automationName")||r("automationName");if(o.includes("xcuitest"))return"simulator";if(o.includes("uiautomator"))return"emulator"}var he=["appium:deviceName","deviceName","appium:udid","udid","appium:deviceUDID","deviceUDID"];function De(e){for(let r of he){let n=e[r];if(typeof n=="string"&&n.trim())return n}}function Ue(e={}){let r={...L(),kill:k,writeState:Ae,...e.deps};try{let n=r.readState(),o=e.owner??process.pid,t=n.filter(s=>s.owner===o&&(!e.deviceClass||s.deviceClass===e.deviceClass));for(let s of t){if(!r.alive(s.pid))continue;let c=R(r.getJson(`http://127.0.0.1:${s.port}/sessions`));for(let u of c)u.id&&r.del(`http://127.0.0.1:${s.port}/session/${u.id}`);r.kill(s.pid)}let i=new Set(t.map(s=>`${s.port}:${s.pid}`));C(()=>{r.writeState(r.readState().filter(s=>!i.has(`${s.port}:${s.pid}`)))})}catch{}}function Ae(e){try{let r=m();g(l(r),{recursive:!0}),M(r,JSON.stringify(e,null,2))}catch{}}export{Ce as a,Q as b,se as c,Le as d,ve as e,Je as f,ye as g,Ue as h};
@@ -0,0 +1,7 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as R}from"./chunk-TDPWFYTJ.js";import{a as x}from"./chunk-HRZOFTV7.js";import{d as S}from"./chunk-ECZMYPLJ.js";import{a as y}from"./chunk-MMBBQ4OZ.js";import{a as p}from"./chunk-LVN6VHFN.js";import{e as g,j as E}from"./chunk-7F2ZV46B.js";import{spawn as M,execSync as h}from"child_process";import{appendFileSync as b,existsSync as m,mkdirSync as C}from"fs";import{homedir as L}from"os";import{join as V,resolve as s,dirname as v,delimiter as T}from"path";import{fileURLToPath as U}from"url";import{createInterface as I}from"readline";async function*A(e){let n=I({input:e,crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let i=JSON.parse(o);i&&typeof i.type=="string"&&(yield i)}catch{}}}function O(e){return e==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_BIFURCATION_PHASES:"1"},unset:["V16_NETWORK_WS","V16_NETWORK_SSE"]}:{set:{V16_BIFURCATION_PHASES:"1"},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_NETWORK_WS","V16_NETWORK_SSE"]}}function w(e){return e?{set:{},unset:["V16_AGENT_SKIP_CP_FINAL"]}:{set:{V16_AGENT_SKIP_CP_FINAL:"true"},unset:[]}}function N(e){return e==="dom"?{set:{V16_AGENT_ENABLE_TEXTUAL_VISUAL:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_TEXTUAL_VISUAL"]}}var c=v(U(import.meta.url));function k(){for(let e of["python3","python"])try{return h(`${e} --version`,{stdio:"ignore"}),e}catch{}return null}function D(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",r={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"linux-arm64":["@testmuai/kane-cli-linux-arm64","@lambdatestincprivate/kane-cli-linux-arm64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},o=`${process.platform}-${process.arch}`,i=r[o];if(i)for(let t of i){let a=[s(c,"..","node_modules",t,"bin",n),s(c,"..","..","node_modules",t,"bin",n),s(c,"..","..","..","node_modules",t,"bin",n),s(c,"..","..","..","..","node_modules",t,"bin",n)];for(let u of a)if(m(u))return{cmd:u,args:[]}}let d=[s(c,"bin",n),s(c,"..","bin",n),s(c,"..","..","..","..","v16-runner","dist",n),s(c,"..","..","..","v16-runner","dist",n),s(c,"..","..","v16-runner","dist",n),s(process.cwd(),"v16-runner","dist",n),s(process.cwd(),"..","v16-runner","dist",n)];for(let t of d)if(m(t))return{cmd:t,args:[]};let l=[s(c,"..","..","v16-runner"),s(c,"..","..","..","..","v16-runner"),s(c,"..","..","..","v16-runner"),s(process.cwd(),"v16-runner"),s(process.cwd(),"..","v16-runner")];for(let t of l)if(m(s(t,"main.py"))){for(let u of[s(t,".venv","bin","python"),s(t,"..",".venv","bin","python"),s(t,"..","browser-agent",".venv","bin","python")])if(m(u))return{cmd:u,args:["main.py"],cwd:t};let a=k();if(a)return{cmd:a,args:["main.py"],cwd:t}}return null}function P(e){return e?V(L(),".testmuai","kaneai","sessions",e,"runner-stderr.log"):null}function K(e){let n=M(e.runner.cmd,e.runner.args,{stdio:["pipe","pipe","pipe"],env:e.env,cwd:e.runner.cwd});n.stdin.on("error",()=>{});let r=P(e.sessionId);if(r)try{C(v(r),{recursive:!0})}catch{}let o=1e5,i="";n.stderr.on("data",u=>{if(i+=u.toString(),i.length>o&&(i=i.slice(-o)),r)try{b(r,u)}catch{}}),n.on("error",u=>{e.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:u.message})});let d=null,l=null,t=new Promise(u=>{n.on("close",(f,_)=>{d=f,l=_?String(_):null,e.log?.("info","RUNNER_EXIT","Runner exited",{code:f,signal:l??"none"}),u({code:f,signal:l})})}),a=A(n.stdout);return{child:n,events:a,getStderr:()=>i,getExitCode:()=>d,getExitSignal:()=>l,exited:t}}async function B(e,n){if(!n?.platform||!n.target_kind)return;let r=await S(n.platform)?.toolEnv(n.target_kind)??{dirs:[]};if(r.dirs.length>0&&(e.PATH=[...r.dirs,e.PATH??""].filter(Boolean).join(T)),r.appiumHome&&(e.APPIUM_HOME=r.appiumHome),r.wdaRoot&&(e.TESTMU_IOS_WDA_DERIVED_DATA=r.wdaRoot),n.platform==="android"){let o=y();o&&(e.PATH=[o.platformToolsDir,e.PATH??""].filter(Boolean).join(T),e.ANDROID_HOME=o.root,e.ANDROID_SDK_ROOT=o.root)}}function H(e){let n={...process.env};e.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8",n.PYTHONUTF8="1");let r=p(e.environment);n.V16_SERVER_API_HOST=r.v16ServerHost,n.ATMS_URL=r.tmsBaseUrl.replace(/\/api\/?$/,""),e.username&&e.accessKey&&(n.LT_USERNAME=e.username,n.LT_ACCESS_KEY=e.accessKey),e.sessionId&&(n.TESTMUAI_SESSION_ID=e.sessionId);let o=O(e.mode??"testing");Object.assign(n,o.set);for(let a of o.unset)delete n[a];let i=new x().load(),d=N(e.assertionMode??(i.assertion_mode==="visual"?"visual":"dom"));Object.assign(n,d.set);for(let a of d.unset)delete n[a];let l=e.finalValidation??i.final_validation,t=w(l);Object.assign(n,t.set);for(let a of t.unset)delete n[a];return n}function G(e,n){let r=p(n?.environment),o=R();o!==void 0&&e.ap_mode===void 0&&(e.ap_mode=o),e.telemetry_proxy_url===void 0&&process.env.KANE_TELEMETRY!=="0"&&(e.telemetry_proxy_url=E),e.media_upload===void 0&&e.org_id&&e.username&&e.access_key&&(e.media_upload={url:r.shareApiBaseUrl.replace(/\/$/,"")+"/mfs/v1.0/media/upload",artefacts_host:r.mediaArtefactsHost,org_id:e.org_id,media_dir:g})}async function oe(e,n){let r=D();if(!r)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");process.env.KANE_SPAWN_DEBUG&&process.stderr.write(`[spawn-debug] ${JSON.stringify(r)}
3
+ `);let o=H({environment:n?.environment,mode:n?.mode,assertionMode:n?.assertionMode,finalValidation:n?.finalValidation,username:e.username,accessKey:e.access_key,sessionId:e.session_id});e.device?.platform&&await B(o,e.device),G(e,{environment:n?.environment});let i=K({env:o,runner:r,log:n?.log,sessionId:e.session_id}),d=i.child;d.stdin.write(JSON.stringify(e)+`
4
+ `);let l=P(e.session_id);if(l)try{C(v(l),{recursive:!0}),b(l,`--- runner spawn ${new Date().toISOString()} run_index=${e.run_index} ---
5
+ `)}catch{}return{child:d,events:i.events,sendUserResponse(t){let a=JSON.stringify({type:"user_response",answer:t});try{d.stdin.write(a+`
6
+ `)}catch{}},sendCancel(t){let a=JSON.stringify({type:"cancel",reason:t});try{d.stdin.write(a+`
7
+ `)}catch{}},cancel(){d.kill("SIGTERM")},get stderr(){return i.getStderr()},get exitCode(){return i.getExitCode()},get exitSignal(){return i.getExitSignal()},exited:i.exited}}export{D as a,K as b,B as c,H as d,G as e,oe as f};
@@ -0,0 +1,26 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as B,b as H,c as ie}from"./chunk-3NHO5R4P.js";import{a as j,b as N}from"./chunk-OOEPLMKA.js";import{a as C,b as G,e as M,f as te,m as re,n as ne}from"./chunk-VK3NU742.js";import{a as oe,b as se}from"./chunk-2YQ6TW77.js";import{a as L}from"./chunk-HRZOFTV7.js";import{a as ee}from"./chunk-5SNT2MK5.js";import{a as q}from"./chunk-LVN6VHFN.js";import{a as Z}from"./chunk-DPUV6OSP.js";import{a as A}from"./chunk-RZ4F3BHX.js";import{a as O}from"./chunk-PXCMEI73.js";import{y as h}from"./chunk-7F2ZV46B.js";import{a as F}from"./chunk-HCBYKLMW.js";import{a as k,b as m,i as Q}from"./chunk-C44QQJR4.js";import{a as X}from"./chunk-6YGTRKDT.js";import{e as v}from"./chunk-UR6MHSHU.js";var D=v(X(),1);import{existsSync as P,readFileSync as Ge,rmSync as he,unlinkSync as He}from"fs";import{resolve as z}from"path";import{promises as ae,realpathSync as be}from"fs";import{homedir as Te}from"os";import{join as V,parse as Ee,relative as ce,resolve as le}from"path";var ue=new Set(["node_modules",".git","dist","build",".next",".venv","venv","target","__pycache__"]),R=class extends Error{constructor(s){super(`refusing to scan '${s}'. Run from your project root, or pass --root <dir>.`);this.cwd=s;this.name="HomeRefusedError"}};function de(e){try{return be(le(e))}catch{return le(e)}}function Se(e){let r=de(e),s=de(Te()),n=Ee(r).root;if(process.platform==="win32"){let o=t=>t.toLowerCase();return o(r)===o(s)||o(r)===o(n)}return r===s||r===n}async function U(e){if(Se(e.root))throw new R(e.root);let r=e.maxEntries??5e4,s=e.maxResults??5e3,n=new Set(e.ignore??[]),o=[],t=0,i=0,c=!1,f,l=[e.root];for(;l.length>0&&!c;){let a=l.shift(),g;try{g=await ae.readdir(a,{withFileTypes:!0})}catch{continue}i++;for(let b of g){if(t++,t>r){c=!0,f="max_entries";break}let x=b.name,E=V(a,x);if(b.isDirectory()){if(ue.has(x)||x.startsWith(".")||x.startsWith("output-")||n.has(x))continue;l.push(E)}else if(b.isFile()&&x.endsWith("_test.md")&&(o.push({path:E,relPath:ce(e.root,E),source:"cwd"}),o.length>=s)){c=!0,f="max_results";break}}e.onProgress?.(i,o.length)}if(!c){let g=[{dir:V(e.root,".testmuai","tests"),depth:0}];for(;g.length>0&&!c;){let{dir:b,depth:x}=g.shift(),E;try{E=await ae.readdir(b,{withFileTypes:!0})}catch{continue}i++;for(let u of E){if(t++,t>r){c=!0,f="max_entries";break}let w=u.name,y=V(b,w);if(u.isDirectory()){if(x>=20||w.startsWith(".")||w.startsWith("output-")||ue.has(w))continue;g.push({dir:y,depth:x+1})}else if(u.isFile()&&w.endsWith("_test.md")&&(o.push({path:y,relPath:ce(e.root,y),source:"tests-dir"}),o.length>=s)){c=!0,f="max_results";break}}}}return{results:o,aborted:c,abortReason:f,dirsScanned:i}}import{readFileSync as ve}from"fs";function Re(e){let r;try{r=ve(e,"utf8")}catch{return{tags:[]}}try{let{global:s}=re(e,r),n=ne(s);return{tags:s.tags??[],...n?{mobileTarget:n}:{}}}catch{return{tags:[],...Me(r)?{mobileTarget:Pe}:{}}}}var Pe={platform:"",app:""};function Me(e){let r=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);if(!r)return!1;let s=r[1].split(/\r?\n/);if(s.some(o=>/^target:\s*['"]?(emulator|simulator)['"]?\s*$/.test(o)))return!0;let n=s.findIndex(o=>/^target:\s*$/.test(o));return n<0?!1:s.slice(n+1).some(o=>/^\s+\S/.test(o))}function W(e){return Re(e).tags}import{mkdirSync as De,writeFileSync as $e}from"fs";import{join as Ce}from"path";function fe(e,r){return`Basic ${Buffer.from(`${e}:${r}`).toString("base64")}`}async function Ie(e){let r=oe({tmsBaseUrl:e.tmsBaseUrl,testcaseId:e.testcaseId,codeExport:{enabled:!0,language:e.language,skipValidation:e.skipValidation}}),s=await A(r.url,{method:"POST",headers:{"content-type":"application/json",authorization:fe(e.auth.username,e.auth.access_key)},body:JSON.stringify(r.body)});if(!s.ok)throw new Error(`code-export trigger failed: ${s.status} ${await s.text()}`);e.log("info","CODE_EXPORT_TRIGGERED","Code export triggered",{testcase_id:e.testcaseId})}async function Fe(e){let r=se({tmsBaseUrl:e.tmsBaseUrl,testcaseId:e.testcaseId}),s=e.pollIntervalMs??5e3,n=e.timeoutMs??3e5,o=Date.now()+n;for(;Date.now()<o;){let t=await A(r,{headers:{authorization:fe(e.auth.username,e.auth.access_key),accept:"application/json"}});if(!t.ok){await new Promise(l=>setTimeout(l,s));continue}let c=(await t.json()).data?.find(l=>l.code_name==="kane-cli-trigger");if(!c){await new Promise(l=>setTimeout(l,s));continue}let f=(c.status??"").toLowerCase();if(f==="in progress"||f==="in_progress"||f==="pending"){await new Promise(l=>setTimeout(l,s));continue}if(!c.url||c.url.length===0)throw new Error(`code-export status=${c.status} but no files returned`);De(e.outDir,{recursive:!0});for(let l of c.url){let a=Ce(e.outDir,l.file_name),g=await A(l.file_url);if(!g.ok){e.log("warn","CODE_EXPORT_FILE_FAILED","Failed to download file",{file_name:l.file_name,status:g.status});continue}let b=await g.text();$e(a,b,"utf-8")}return e.log("info","CODE_EXPORT_DOWNLOADED","Code export saved",{out_dir:e.outDir,file_count:c.url.length}),e.outDir}throw new Error("code-export polling timed out")}async function ge(e){return await Ie(e),await Fe(e)}var T=v(X(),1);import{existsSync as Oe,readFileSync as Ae}from"fs";var p=v(F(),1);function Le(e){B(e);let r=M(e);if(!Oe(r))return null;try{return JSON.parse(Ae(r,"utf8"))}catch{return{}}}function Be(e){return e===null?"never_run":e.testcase_id?"synced":"local_only"}function je(e){return e==="synced"?"\u2601":e==="local_only"?"\u25A3":"\u25CB"}function Ne(e){return e==="tests-dir"?"\u2726":" "}function Ue(e,r){return r==="all"?!0:r==="synced"?e.status==="synced":r==="local"?e.status==="local_only":r==="never_run"?e.status==="never_run":r==="cli"?e.source==="tests-dir":r==="hand"?e.source==="cwd":!0}var Y=["all","synced","local","never_run","cli","hand"];function We(e){let r=Y.indexOf(e);return Y[(r+1)%Y.length]}function me({root:e,currentOrgId:r,onSelect:s,onCancel:n}){let[o,t]=(0,T.useState)([]),[i,c]=(0,T.useState)(null),[f,l]=(0,T.useState)(!0),[a,g]=(0,T.useState)("all");(0,T.useEffect)(()=>{(async()=>{try{let u=await U({root:e}),w=[];for(let y of u.results){let K=Le(y.path);K?.org_id!==void 0&&K.org_id!==r||w.push({path:y.path,relPath:y.relPath,name:C(y.path),status:Be(K),source:y.source,tags:W(y.path)})}t(w),l(!1)}catch(u){u instanceof R,c(u.message),l(!1)}})()},[e,r]);let b=(0,T.useMemo)(()=>o.filter(u=>Ue(u,a)).map(u=>({id:u.path,label:`${je(u.status)} ${Ne(u.source)} ${u.relPath}${u.tags.length>0?` [${u.tags.join(", ")}]`:""}`})),[o,a]),x=(0,T.useMemo)(()=>Ke(a,o),[a,o]);if(i)return(0,p.jsxs)(k,{flexDirection:"column",borderStyle:"round",borderColor:h.red,paddingX:2,paddingY:1,children:[(0,p.jsx)(m,{color:h.red,bold:!0,children:"testmd"}),(0,p.jsx)(k,{marginTop:1,children:(0,p.jsx)(m,{color:h.red,children:i})})]});let E=a==="all"?"all":Je(a);return(0,p.jsx)(ee,{title:`testmd \xB7 filter: ${E}`,items:b,loading:f,itemNoun:"tests",onSelect:u=>{let w=o.find(y=>y.path===u.id);w&&s(w)},onCancel:n,onTab:()=>g(u=>We(u)),extraHint:"cycle filter",footer:x})}function Je(e){return e==="synced"?"synced (\u2601)":e==="local"?"local (\u25A3)":e==="never_run"?"never run (\u25CB)":e==="cli"?"cli-generated (\u2726)":e==="hand"?"hand-written":"all"}function Ke(e,r){let s={synced:r.filter(o=>o.status==="synced").length,local:r.filter(o=>o.status==="local_only").length,never:r.filter(o=>o.status==="never_run").length,cli:r.filter(o=>o.source==="tests-dir").length,hand:r.filter(o=>o.source==="cwd").length},n=o=>o?h.orange:h.dim;return(0,p.jsxs)(k,{flexDirection:"column",children:[(0,p.jsx)(m,{color:h.dim,children:"legend:"}),(0,p.jsxs)(k,{children:[(0,p.jsx)(m,{color:n(e==="synced"),children:` \u2601 synced (${s.synced}) `}),(0,p.jsx)(m,{color:n(e==="local"),children:`\u25A3 local (${s.local}) `}),(0,p.jsx)(m,{color:n(e==="never_run"),children:`\u25CB never run (${s.never})`})]}),(0,p.jsxs)(k,{children:[(0,p.jsx)(m,{color:n(e==="cli"),children:` \u2726 cli-generated (${s.cli}) `}),(0,p.jsx)(m,{color:n(e==="hand"),children:` hand-written (${s.hand})`})]})]})}var I=v(X(),1);import{existsSync as Xe,readFileSync as qe}from"fs";var d=v(F(),1);function pe({path:e,relPath:r,onAction:s,onBack:n,onView:o}){let[t,i]=(0,I.useState)(null),[c,f]=(0,I.useState)(!1);(0,I.useEffect)(()=>{let a=M(e);if(Xe(a))try{i(JSON.parse(qe(a,"utf8")))}catch{i(null)}},[e]),Q((a,g)=>{if(g.escape){if(c){f(!1);return}n();return}if(c){a==="y"||a==="Y"?(f(!1),s("delete")):(a==="n"||a==="N")&&f(!1);return}a==="r"&&s("run"),a==="e"&&t?.testcase_id&&s("export"),a==="d"&&f(!0),a==="v"&&o&&o()});let l=({k:a,v:g})=>g?(0,d.jsxs)(m,{children:[(0,d.jsx)(m,{color:h.dim,children:a.padEnd(14)}),g]}):null;return(0,d.jsxs)(k,{flexDirection:"column",borderStyle:"round",borderColor:h.orange,paddingX:2,paddingY:1,children:[(0,d.jsx)(m,{color:h.orange,bold:!0,children:r}),(0,d.jsx)(k,{marginTop:1,flexDirection:"column",children:t?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(l,{k:"test_id",v:t.test_id}),(0,d.jsx)(l,{k:"testcase_id",v:t.testcase_id}),(0,d.jsx)(l,{k:"project_id",v:t.project_id}),(0,d.jsx)(l,{k:"folder_id",v:t.folder_id}),(0,d.jsx)(l,{k:"org_id",v:t.org_id}),(0,d.jsx)(l,{k:"session_name",v:t.session_name}),(0,d.jsx)(l,{k:"commit_id",v:t.commit_id})]}):(0,d.jsx)(m,{color:h.dim,children:"(never run \u2014 no meta.json)"})}),c?(0,d.jsx)(k,{marginTop:1,children:(0,d.jsxs)(m,{color:h.red,bold:!0,children:["Delete ",r," and its output dir? [y/n]"]})}):(0,d.jsx)(k,{marginTop:1,children:(0,d.jsxs)(m,{color:h.dim,children:["[r] run [e] export",t?.testcase_id?"":" (need testcase_id)"," [d] delete",o?" [v] view":""," [Esc] back"]})})]})}function $(e){B(e);let r=M(e);if(!P(r))return null;try{return JSON.parse(Ge(r,"utf8"))}catch{return null}}function _e(e,r){return!e||e.org_id===void 0?!0:e.org_id===r}function J(e,r){return _e(e,r)?null:(process.stderr.write(`error: this test belongs to org ${e.org_id}; you are logged in as org ${r}.
3
+ Switch profiles with \`kane-cli profiles switch\` to act on it.
4
+ `),2)}async function Xt(e={}){let r=!!process.stdin.isTTY&&!e.json,s=new O,n=new L;await H({isInteractive:r,creds:s,config:n});let o=s.getDefaultEnv()??"prod";try{let t=await N({creds:s,env:o,log:()=>{}});return t.resolvedCreds?.org_id===void 0?(process.stderr.write("error: TMS did not return an org_id. Run `kane-cli login` again.\n"),{ok:!1,code:2}):{ok:!0,orgId:String(t.resolvedCreds.org_id)}}catch(t){if(t instanceof j)return process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),{ok:!1,code:2};throw t}}async function qt(e,r){if(process.stdin.isTTY&&!e.json)return await ze(r,e.root);let s=e.root??process.cwd(),n;try{n=await U({root:s,ignore:e.ignore})}catch(o){if(o instanceof R)return process.stderr.write(`error: ${o.message}
5
+ `),2;throw o}for(let o of n.results){let t=$(o.path);if(!_e(t,r))continue;let i={path:o.relPath.startsWith(".")?o.relPath:`./${o.relPath}`,name:C(o.path),has_meta:t!==null,source:o.source,synced:!!t?.testcase_id,tags:W(o.path)};t&&(t.test_id&&(i.test_id=t.test_id),t.testcase_id&&(i.testcase_id=t.testcase_id),t.org_id&&(i.org_id=t.org_id),t.project_id&&(i.project_id=t.project_id),t.folder_id&&(i.folder_id=t.folder_id)),process.stdout.write(JSON.stringify(i)+`
6
+ `)}return n.aborted&&process.stderr.write(`warn: walk aborted (${n.abortReason}). Pass --root or --ignore to narrow.
7
+ `),0}var ye=-1001,xe=-1002,we=-1003,_={action:null,path:null};function Ve(e,r){return _.action=e,_.path=r,e==="run"?ye:e==="export"?xe:we}function Ye({root:e,currentOrgId:r,onComplete:s}){let[n,o]=D.default.useState({kind:"list"});return D.default.useEffect(()=>{n.kind==="exiting"&&s(n.code)},[n,s]),n.kind==="list"?D.default.createElement(me,{root:e,currentOrgId:r,onSelect:t=>o({kind:"inspect",path:t.path,relPath:t.relPath}),onCancel:()=>o({kind:"exiting",code:0})}):n.kind==="inspect"?D.default.createElement(pe,{path:n.path,relPath:n.relPath,onAction:async t=>{o({kind:"exiting",code:Ve(t,n.path)})},onBack:()=>o({kind:"list"})}):null}async function ze(e,r){let s=r??process.cwd(),{render:n}=await import("./build-JIKYOZUH.js"),o=await new Promise(t=>{let{unmount:i,waitUntilExit:c}=n(D.default.createElement(Ye,{root:s,currentOrgId:e,onComplete:f=>{i(),t(f)}}),{stdout:process.stderr,exitOnCtrlC:!0});c().then(()=>t(0)).catch(()=>t(0))});if(o===ye&&_.path){let{runTestMdFile:t}=await import("./run-test-md-7HGOZJSU.js"),i=await t(_.path,{});return _.action=null,_.path=null,i}if(o===xe&&_.path){let t=await Ze(_.path,{},e);return _.action=null,_.path=null,t}if(o===we&&_.path){let t=await Qe(_.path,!0,e);return _.action=null,_.path=null,t}return o}async function Gt(e,r){let s=z(e);if(!P(s))return process.stderr.write(`error: file not found: ${s}
8
+ `),2;let n=$(s),o=J(n,r);if(o!==null)return o;let t={path:s,name:C(s),has_meta:n!==null};return n&&(n.commit_id&&(t.commit_id=n.commit_id),n.test_id&&(t.test_id=n.test_id),n.testcase_id&&(t.testcase_id=n.testcase_id),n.project_id&&(t.project_id=n.project_id),n.folder_id&&(t.folder_id=n.folder_id),n.org_id&&(t.org_id=n.org_id),n.session_name&&(t.session_name=n.session_name)),process.stdout.write(JSON.stringify(t)+`
9
+ `),0}async function Qe(e,r,s){let n=z(e);if(!P(n))return process.stderr.write(`error: file not found: ${n}
10
+ `),2;let o=$(n),t=J(o,s);if(t!==null)return t;if(!r)return process.stderr.write(`error: refusing to delete without --yes.
11
+ This will remove '${n}' and '${G(n)}/'.
12
+ `),2;let i=G(n);if(P(i))try{he(i,{recursive:!0,force:!0})}catch(c){return process.stderr.write(`error: failed to remove ${i}: ${c.message}
13
+ `),2}try{He(n)}catch(c){return process.stderr.write(`error: failed to remove ${n}: ${c.message}
14
+ `),2}return process.stderr.write(`removed ${n} and ${i}/
15
+ `),0}var S=class extends Error{kind;constructor(r,s){super(s),this.name="ExportError",this.kind=r}};async function Ht(e,r){let{codeDir:s}=await ke(e,r);return{codeDir:s}}async function ke(e,r){let s=$(e);if(!s?.testcase_id)throw new S("not-synced","this test has not been synced to TMS \u2014 run `kane-cli testmd run` first.");let n=new L().load(),o=r.language??n.code_export?.language;if(!o)throw new S("no-language","--language not provided and no default in tui-config.");let t=r.output??te(e,"playwright",o),i=P(t);if(i&&!r.force){let a=!1;try{let{readdirSync:g}=await import("fs");a=g(t).length>0}catch{}if(a)return{kind:"reused",codeDir:t}}i&&r.force&&he(t,{recursive:!0,force:!0});let c=new O,f=r.env??c.getDefaultEnv()??"prod",l;try{l=await N({creds:c,env:f,log:()=>{}})}catch(a){throw a instanceof j?new S("auth-fail","not authenticated. Run `kane-cli login` first."):a}if(!l.basicAuth)throw new S("auth-incomplete","TMS basic auth could not be resolved. Run `kane-cli login` again.");try{let a=q(f);await ge({tmsBaseUrl:a.tmsBaseUrl,testcaseId:s.testcase_id,auth:l.basicAuth,language:o,framework:"playwright",skipValidation:n.code_export?.skip_validation??!0,outDir:t,log:()=>{}})}catch(a){throw new S("export-fail",`code export failed: ${a.message}`)}return{kind:"exported",codeDir:t}}async function Ze(e,r,s){let n=z(e);if(!P(n))return process.stderr.write(`error: file not found: ${n}
16
+ `),2;let o=$(n),t=J(o,s);if(t!==null)return t;try{let i=await ke(n,r);return i.kind==="reused"?process.stderr.write(`reusing existing export at ${i.codeDir}
17
+ `):process.stderr.write(`exported to ${i.codeDir}
18
+ `),0}catch(i){if(i instanceof S)return i.kind==="not-synced"?(process.stderr.write("error: this test has not been synced to TMS \u2014 run `kane-cli testmd run` first.\n"),2):i.kind==="no-language"?(process.stderr.write(`error: --language not provided and no default in tui-config.
19
+ `),2):i.kind==="auth-fail"?(process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),2):i.kind==="auth-incomplete"?(process.stderr.write("error: TMS basic auth could not be resolved. Run `kane-cli login` again.\n"),2):(process.stderr.write(`error: ${i.message}
20
+ `),2);throw i}}async function Vt(e={}){let r=!!process.stdin.isTTY,s=new O,n=new L;await H({isInteractive:r,creds:s,config:n});let o=e.env??s.getDefaultEnv()??"prod";try{let t=await N({creds:s,env:o,usernameFlag:e.username,accessKeyFlag:e.accessKey,log:()=>{}});return t.resolvedCreds?.org_id===void 0||!t.basicAuth?(process.stderr.write("error: could not resolve TMS credentials. Run `kane-cli login` again.\n"),{ok:!1,code:2}):{ok:!0,orgId:String(t.resolvedCreds.org_id),basicAuth:t.basicAuth,controllerBaseUrl:q(o).controllerBaseUrl}}catch(t){if(t instanceof j)return process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),{ok:!1,code:2};throw t}}async function Yt(e,r,s=ie){if(!P(e))return process.stderr.write(`error: file not found: ${e}
21
+ `),2;if(!e.endsWith("_test.md"))return process.stderr.write(`error: not a *_test.md file: ${e}
22
+ `),2;let n=$(e),o=J(n,r.orgId);if(o!==null)return o;if(!n?.commit_id||!n?.test_id)return process.stderr.write(`error: ${e} is not authored \u2014 run \`kane-cli testmd run ${e}\` first.
23
+ `),2;let t=await s({sourcePath:e,testId:n.test_id,sessionId:n.commit_id,commitId:n.commit_id,controller:new Z(r.controllerBaseUrl,{username:r.basicAuth.username,accessKey:r.basicAuth.access_key})}),i={type:"test_md_bundle_sync",status:t.ok?"ok":"failed",commit_id:n.commit_id,...t.ok?{bytes:t.bytes}:{stage:t.stage}};return process.stdout.write(JSON.stringify(i)+`
24
+ `),t.ok?(process.stderr.write(`synced: ${n.commit_id}-testmd.zip (${t.bytes} bytes)
25
+ `),0):(process.stderr.write(`error: bundle sync failed at ${t.stage}: ${t.error}
26
+ `),t.stage==="collect"?2:1)}export{U as a,Re as b,me as c,pe as d,$ as e,_e as f,J as g,Xt as h,qt as i,ze as j,Gt as k,Qe as l,S as m,Ht as n,Ze as o,Vt as p,Yt as q};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as G,c as P,e as J,h as q,i as z,j as Q,m as V,n as X,o as T}from"./chunk-RKWJG3WW.js";import{e as U}from"./chunk-EHN5HTUD.js";import{copyFileSync as ae,cpSync as le,existsSync as w,mkdirSync as ue,readFileSync as Oe,readdirSync as pe,rmSync as Te,writeFileSync as _e}from"fs";import{dirname as Ae,isAbsolute as Le,join as R,relative as Ee,resolve as Ne}from"path";import{writeFileSync as ge,mkdirSync as Se,readFileSync as Re}from"fs";import{dirname as Ie,basename as Y}from"path";function ee(e){let t=e.outPath??P(e.sourcePath);Se(Ie(t),{recursive:!0});let s=[];s.push("---"),s.push(`test: ../${Y(e.sourcePath)}`),s.push(`status: ${e.overallStatus}`),s.push(`started: ${e.startedISO}`),s.push(`duration_s: ${e.durationS}`),s.push(`session_id: ${e.sessionId}`),s.push("---",""),s.push(`# ${e.title??Y(e.sourcePath)} \u2014 Result`,"");for(let l=0;l<e.rootSteps.length;l++){let a=e.rootSteps[l],i=e.outcomes.find(p=>p.rootStepIndex===l+1);if(s.push(ye(a,i)),i?.stepMd5&&s.push(`md5: ${i.stepMd5}`),i?.status==="failed"&&i.reason&&s.push(`Reason: ${i.reason}`),i?.softFailures?.length)for(let p of i.softFailures){let o=p.reason?`: ${p.reason}`:"";s.push(`\u26A0 optional sub-step ${p.subStepIndex} failed${o}`)}a.body.kind==="objective"&&i?.status!=="skipped"&&s.push(a.body.text),s.push("")}return ge(t,s.join(`
2
+ import{b as G,c as P,e as J,h as q,i as z,j as Q,m as V,o as X,p as T}from"./chunk-VK3NU742.js";import{e as U}from"./chunk-EHN5HTUD.js";import{copyFileSync as ae,cpSync as le,existsSync as w,mkdirSync as ue,readFileSync as Oe,readdirSync as pe,rmSync as Te,writeFileSync as _e}from"fs";import{dirname as Ae,isAbsolute as Le,join as R,relative as Ee,resolve as Ne}from"path";import{writeFileSync as ge,mkdirSync as Se,readFileSync as Re}from"fs";import{dirname as Ie,basename as Y}from"path";function ee(e){let t=e.outPath??P(e.sourcePath);Se(Ie(t),{recursive:!0});let s=[];s.push("---"),s.push(`test: ../${Y(e.sourcePath)}`),s.push(`status: ${e.overallStatus}`),s.push(`started: ${e.startedISO}`),s.push(`duration_s: ${e.durationS}`),s.push(`session_id: ${e.sessionId}`),s.push("---",""),s.push(`# ${e.title??Y(e.sourcePath)} \u2014 Result`,"");for(let l=0;l<e.rootSteps.length;l++){let a=e.rootSteps[l],i=e.outcomes.find(p=>p.rootStepIndex===l+1);if(s.push(ye(a,i)),i?.stepMd5&&s.push(`md5: ${i.stepMd5}`),i?.status==="failed"&&i.reason&&s.push(`Reason: ${i.reason}`),i?.softFailures?.length)for(let p of i.softFailures){let o=p.reason?`: ${p.reason}`:"";s.push(`\u26A0 optional sub-step ${p.subStepIndex} failed${o}`)}a.body.kind==="objective"&&i?.status!=="skipped"&&s.push(a.body.text),s.push("")}return ge(t,s.join(`
3
3
  `),"utf8"),t}function ye(e,t){if(!t)return`## ${e.heading} (no outcome)`;let s=t.duration_s!=null?`${t.duration_s}s`:"\u2014";if(t.status==="skipped")return`## ${e.heading} \u23ED skipped`;let l=t.softFailed?" (optional)":"";if(t.refKind&&t.status==="passed"){let a=t.helperResultRelPath?` \u2192 ${t.helperResultRelPath}`:"";return`## ${e.heading} \u2713 passed (via @${t.refKind} ${t.refLabel} \u2014 ${t.inlinedCount} inlined steps, ${s}${a})`}if(t.refKind&&t.status==="failed"){let a=t.failedSubStepIndex&&t.failedSubStepIndex.length>0?` \u2014 at sub-step ${t.failedSubStepIndex.join(" \u2192 sub-step ")}`:"",i=t.helperResultRelPath?` \u2192 ${t.helperResultRelPath}`:"";return`## ${e.heading} \u2717 failed${l} (via @${t.refKind} ${t.refLabel}${a}, ${s}${i})`}return t.status==="passed"?`## ${e.heading} \u2713 passed (${s})`:`## ${e.heading} \u2717 failed${l} (${s})`}var xe=/^##\s+(.+?)\s+(✓ passed|✗ failed(?:\s+\(optional\))?|⏭ skipped)(?:\s+\((.*)\))?\s*$/,be=/via\s+@\w+\s+(\S+).*?(?:→\s+(\S+))?\s*$/,ke=/^md5:\s+([a-f0-9]{32})\s*$/;function Z(e,t){for(let s=t;s<e.length&&!/^##\s/.test(e[s]);s++){if(e[s].trim()==="")continue;let l=ke.exec(e[s]);return l?l[1]:null}return null}function $(e){let s=Re(e,"utf8").split(`
4
4
  `),l="passed";if(s[0]?.trim()==="---")for(let i=1;i<s.length&&s[i].trim()!=="---";i++){let p=/^status:\s+(passed|failed|interrupted)\s*$/.exec(s[i]);p&&(l=p[1])}let a=[];for(let i=0;i<s.length;i++){let p=xe.exec(s[i]);if(!p)continue;let o=p[1],r=p[2],c=p[3]??"",m=r.startsWith("\u2713")?"passed":r.startsWith("\u23ED")?"skipped":"failed";if(/via\s+@/.test(c)){let f=be.exec(c),b=f?.[1]??"",g=f?.[2]??null;a.push({kind:"import",heading:o,status:m,md5:Z(s,i+1),importPath:b,helperResultRelPath:g})}else a.push({kind:"objective",heading:o,status:m,md5:Z(s,i+1)})}return{overallStatus:l,steps:a}}import{copyFileSync as te,existsSync as K,mkdirSync as ve,writeFileSync as se,promises as Ge}from"fs";import{join as D,dirname as re,basename as Pe}from"path";async function ne(e){for(let t=0;t<e.totalRunDirs;t++){let s=e.runIndex+t,l=D(e.sessionDir,"runs",String(s)),a=D(e.stagingStepDir,"flows",String(t));ve(a,{recursive:!0});let i=D(a,"actions.ndjson");if(e.packTestDir){let r=D(e.packTestDir,"logs",`${s}-actions.ndjson`);if(K(r)){te(r,i);continue}let c=re(re(e.packTestDir)),m=Pe(e.packTestDir),I=K(c)?await U(c,`tests/${m}/logs/${s}-actions.ndjson`).catch(()=>null):null;se(i,I??"");continue}let p=[D(l,"run-test","actions.ndjson"),D(l,"actions.ndjson")],o=!1;for(let r of p)if(K(r)){te(r,i),o=!0;break}o||se(i,"")}}import{existsSync as _,readdirSync as we}from"fs";import{dirname as $e,join as M,basename as C}from"path";function et(e){let t=[],s=new Set,l=new Map;function a(r){if(l.has(r))return l.get(r);let c=P(r),m=_(c)?$(c):null;return l.set(r,m),m}let i=new Map;function p(r){if(i.has(r))return i.get(r);let c=M(r,"Result.md"),m=_(c)?$(c):null;return i.set(r,m),m}function o(r){for(let c=1;c<r.trace.length;c++){let m=r.trace[c-1],I=a(m.file);if(!I)continue;let f=I.steps[m.stepIndex-1];if(f){if(f.kind!=="import")return{kind:"author",reason:"structure-mismatch"};if(C(f.importPath)!==C(r.trace[c].file))return{kind:"author",reason:"structure-mismatch"};if(f.md5!=null&&f.md5!==m.rowMd5)return{kind:"author",reason:"structure-mismatch"}}}return null}for(let r of e.steps){let c=r.trace[r.trace.length-1].stepIndex,m=s.has(r.owningFile);for(let g=0;g<r.trace.length-1&&!m;g++)s.has(r.trace[g].file)&&(m=!0);if(m){t.push({kind:"author",reason:a(r.owningFile)===null?"no-result-md":"downstream-of-divergence"});continue}let I=o(r);if(I){t.push(I);for(let g=0;g<r.trace.length;g++)s.add(r.trace[g].file);continue}let f=a(r.owningFile),b;if(f===null&&r.trace.length>1){let g=H(r.trace);b=ie(r,p(g),c,g)}else b=ie(r,f,c);if(t.push(b),b.kind==="author"){s.add(r.owningFile);for(let g=0;g<r.trace.length-1;g++)s.add(r.trace[g].file)}}return t}function ie(e,t,s,l=null){if(!t)return{kind:"author",reason:"no-result-md"};let a=t.steps[s-1];if(!a)return{kind:"author",reason:"no-result-md"};if(a.kind!=="objective")return{kind:"author",reason:"structure-mismatch"};if(a.status!=="passed")return{kind:"author",reason:"recorded-failed"};let i=T(e);if(i!==a.md5)return{kind:"author",reason:"md5-mismatch"};let p=l===null?Q(e.owningFile,s,i.slice(0,8)):M(l,".internal","steps",`${s}-${i.slice(0,8)}`),o=De(p);return o===0?{kind:"author",reason:"missing-recording"}:{kind:"replay",recordingDir:p,flowCount:o}}function De(e){let t=M(e,"flows");if(!_(t))return 0;let s;try{s=we(t,{withFileTypes:!0}).filter(a=>a.isDirectory()&&/^\d+$/.test(a.name)).map(a=>parseInt(a.name,10))}catch{return 0}if(s.length===0)return 0;let l=Math.max(...s);for(let a=0;a<=l;a++)if(!_(M(t,String(a),"actions.ndjson")))return 0;return l+1}function tt(e){return e.some(t=>t.kind==="author")}function st(e){for(let t=0;t<e.length;t++)if(e[t].kind==="author")return t;return e.length}function H(e){let t=i=>{let p=C(i);return p.endsWith("_test.md")?p.slice(0,-8):p.endsWith(".md")?p.slice(0,-3):p},s=t(e[0].file),l=t(e[e.length-1].file),a=e.slice(0,-1).map(i=>String(i.stepIndex));return M($e(e[e.length-1].file),`helper-output-${l}-${s}-${a.join("-")}`)}function rt(e){return Array.from({length:e.flowCount},(t,s)=>M(e.recordingDir,"flows",String(s),"actions.ndjson"))}import{existsSync as oe,mkdirSync as Me,rmSync as je,cpSync as Fe}from"fs";function de(e,t){oe(e)&&(oe(t)&&je(t,{recursive:!0,force:!0}),Me(t,{recursive:!0}),Fe(e,t,{recursive:!0}))}async function gt(e){let t=new Map;for(let o of e.stepRunRecords)t.set(o.testmdStepIndex,o);let s=e.authoredFlatIdx??new Set,l=[],a=[],i=new Map,p=o=>{if(i.has(o))return i.get(o);let r=R(o,"Result.md"),c=w(r)?$(r):null;return i.set(o,c),c};for(let o of e.resolvedTest.unitFiles){let r=o.file===e.resolvedTest.rootPath,c=V(o.file,Oe(o.file,"utf8")),m=P(o.file),I=w(m)?$(m):null,f=[],b=[],g=[],j=[];if(!r)for(let d of e.resolvedTest.steps){if(d.owningFile!==o.file||d.trace.length<2)continue;let n=H(d.trace);j.includes(n)||j.push(n)}let F=d=>{if(I!==null)return null;for(let n of j){let v=p(n)?.steps[d-1];if(v)return{row:v,dir:n}}return null},W=[],A=!1,B=!1,L=!1,E=!1;for(let d of c.steps){let n=d.index,u=I?.steps[n-1];if(d.body.kind==="objective"){let h=e.resolvedTest.steps.filter(S=>S.owningFile===o.file&&S.trace[S.trace.length-1].stepIndex===n&&t.has(S.flatIndex)),y=h.length>0?h[h.length-1]:null;if(y){A=!0,s.has(y.flatIndex)&&(B=!0);let S=T(y),x;r?x=e.outcomes.find(he=>he.rootStepIndex===n)??{rootStepIndex:n,status:"skipped"}:x={rootStepIndex:n,status:ce(y,e.outcomes)},x.status==="failed"&&(L=!0),x.stepMd5==null&&(x.stepMd5=S),f.push(x),b.push({stepIndex:n,md5:S,rec:t.get(y.flatIndex)}),(!u||u.kind!=="objective"||u.status!==x.status||x.status==="passed"&&u.md5!==S)&&(E=!0)}else if(u&&u.kind==="objective")f.push({rootStepIndex:n,status:u.status,...u.md5?{stepMd5:u.md5}:{}}),g.push(n);else if(!r&&F(n)?.row.kind==="objective"){let S=F(n),x=S.row;f.push({rootStepIndex:n,status:x.status,...x.md5?{stepMd5:x.md5}:{}}),W.push({psIdx:n,dir:S.dir})}else r?f.push(e.outcomes.find(S=>S.rootStepIndex===n)??{rootStepIndex:n,status:"skipped"}):f.push({rootStepIndex:n,status:"skipped"});continue}let v=Le(d.body.path)?d.body.path:Ne(Ae(o.file),d.body.path),O=X({path:d.body.path,bindings:d.body.bindings,optional:d.optional??!1}),me=Ee(G(o.file),P(v)),N=e.resolvedTest.steps.filter(h=>h.trace.some((y,S)=>S<h.trace.length-1&&y.file===o.file&&y.stepIndex===n)&&t.has(h.flatIndex));if(N.length>0){A=!0;let h;if(r)h=e.outcomes.find(y=>y.rootStepIndex===n)??{rootStepIndex:n,status:"passed",refKind:"import",refLabel:d.body.path};else{let y=N.some(S=>ce(S,e.outcomes)==="failed");h={rootStepIndex:n,status:y?"failed":"passed",refKind:"import",refLabel:d.body.path,inlinedCount:N.length}}h.status==="failed"&&(L=!0),h.stepMd5==null&&(h.stepMd5=O),h.helperResultRelPath==null&&(h.helperResultRelPath=me),f.push(h),(!u||u.kind!=="import"||u.status!==h.status||u.md5!==O)&&(E=!0)}else if(u&&u.kind==="import")f.push({rootStepIndex:n,status:u.status,refKind:"import",refLabel:u.importPath,...u.md5?{stepMd5:u.md5}:{},...u.helperResultRelPath?{helperResultRelPath:u.helperResultRelPath}:{}});else if(!r&&F(n)?.row.kind==="import"){let h=F(n).row;f.push({rootStepIndex:n,status:h.status,refKind:"import",refLabel:d.body.path})}else r?f.push(e.outcomes.find(h=>h.rootStepIndex===n)??{rootStepIndex:n,status:"skipped",refKind:"import",refLabel:d.body.path}):f.push({rootStepIndex:n,status:"skipped",refKind:"import",refLabel:d.body.path})}if(!(r||A&&(B||L||I===null||E)))continue;l.push(o.file);let k=q(o.file);ue(R(k,".internal"),{recursive:!0});for(let d of b){let n=R(k,".internal","steps",`${d.stepIndex}-${d.md5.slice(0,8)}`);ue(n,{recursive:!0}),await ne({sessionDir:e.sessionDir,runIndex:d.rec.runIndex,totalRunDirs:d.rec.totalRunDirs,stagingStepDir:n,packTestDir:e.packTestDir})}if(g.length>0){let d=z(o.file);if(w(d))for(let n of pe(d)){let u=parseInt(n.split("-")[0]??"",10);!Number.isNaN(u)&&g.includes(u)&&le(R(d,n),R(k,".internal","steps",n),{recursive:!0})}}for(let d of W){let n=R(d.dir,".internal","steps");if(w(n))for(let u of pe(n))parseInt(u.split("-")[0]??"",10)===d.psIdx&&le(R(n,u),R(k,".internal","steps",u),{recursive:!0})}let fe=f.some(d=>d.status==="failed");if(ee({sourcePath:o.file,title:c.title,rootSteps:c.steps,outcomes:f,overallStatus:r?e.overallStatus:fe?"failed":"passed",startedISO:e.startedISO,durationS:r?e.durationS:0,sessionId:e.sessionId,outPath:R(k,"Result.md")}),r){let d={};e.commitId&&(d.commit_id=e.commitId),e.tmsIds.testId&&(d.test_id=e.tmsIds.testId),e.tmsIds.testcaseId&&(d.testcase_id=e.tmsIds.testcaseId),e.tmsIds.projectId&&(d.project_id=e.tmsIds.projectId),e.tmsIds.folderId&&(d.folder_id=e.tmsIds.folderId),e.tmsIds.orgId&&(d.org_id=e.tmsIds.orgId),e.tmsIds.sessionName&&(d.session_name=e.tmsIds.sessionName),_e(R(k,".internal","meta.json"),JSON.stringify(d,null,2)+`
5
5
  `,"utf8");let n=R(e.sessionDir,"execution.json");if(w(n))try{ae(n,R(k,".internal","execution.json"))}catch{}if(e.codeExportDir){let u=e.codeExportLanguage??"python",v=R(k,`playwright-${u}-code`);try{de(e.codeExportDir,v)}catch(O){process.stderr.write(`warn: codegen copy failed: ${O.message}
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{y as m}from"./chunk-ZUGCHQFC.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a as u,b as a,j as g}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as f}from"./chunk-UR6MHSHU.js";var T=f(b(),1);function k(i,n){if(!n)return i;let l=i.trim()||n;return`\x1B]8;;${n}\x07${l}\x1B]8;;\x07`}var r=f(x(),1);function $({shareableLink:i,testCaseLink:n,codeExportDir:l,recordedTestPath:s,outputDir:o,autoExit:p=!0}){let{exit:c}=g();(0,T.useEffect)(()=>{if(!p)return;let t=setTimeout(()=>c(),100);return()=>clearTimeout(t)},[c,p]);let e=[];return s&&e.push({label:"Test",url:s,linkUrl:`file://${s}`}),o&&e.push({label:"Output",url:o,linkUrl:`file://${o}`}),i&&e.push({label:"ShareLink",url:i}),n&&e.push({label:"TestCase",url:n}),l&&!o&&e.push({label:"CodeExport",url:l,linkUrl:`file://${l}`}),e.length===0?(0,r.jsx)(r.Fragment,{}):(0,r.jsx)(u,{flexDirection:"column",marginTop:1,marginLeft:1,children:e.map(t=>(0,r.jsxs)(u,{flexDirection:"column",marginBottom:1,children:[(0,r.jsxs)(a,{color:m.orange,children:[t.label,":"]}),(0,r.jsx)(a,{color:m.dim,children:k(t.url,t.linkUrl??t.url)})]},t.label))})}export{$ as a};
2
+ import{y as m}from"./chunk-7F2ZV46B.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a as u,b as a,j as g}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as f}from"./chunk-UR6MHSHU.js";var T=f(b(),1);function k(i,n){if(!n)return i;let l=i.trim()||n;return`\x1B]8;;${n}\x07${l}\x1B]8;;\x07`}var r=f(x(),1);function $({shareableLink:i,testCaseLink:n,codeExportDir:l,recordedTestPath:s,outputDir:o,autoExit:p=!0}){let{exit:c}=g();(0,T.useEffect)(()=>{if(!p)return;let t=setTimeout(()=>c(),100);return()=>clearTimeout(t)},[c,p]);let e=[];return s&&e.push({label:"Test",url:s,linkUrl:`file://${s}`}),o&&e.push({label:"Output",url:o,linkUrl:`file://${o}`}),i&&e.push({label:"ShareLink",url:i}),n&&e.push({label:"TestCase",url:n}),l&&!o&&e.push({label:"CodeExport",url:l,linkUrl:`file://${l}`}),e.length===0?(0,r.jsx)(r.Fragment,{}):(0,r.jsx)(u,{flexDirection:"column",marginTop:1,marginLeft:1,children:e.map(t=>(0,r.jsxs)(u,{flexDirection:"column",marginBottom:1,children:[(0,r.jsxs)(a,{color:m.orange,children:[t.label,":"]}),(0,r.jsx)(a,{color:m.dim,children:k(t.url,t.linkUrl??t.url)})]},t.label))})}export{$ as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as V,c as H,d as W,e as re,f as ie}from"./chunk-ZI6UIJUN.js";import{a as se}from"./chunk-JJN76EXE.js";import{c as ee}from"./chunk-WV27D55O.js";import{a as te}from"./chunk-HRZOFTV7.js";import{a as oe}from"./chunk-YTDSQAYN.js";import{b as Y}from"./chunk-OJTCIZDK.js";import{b as Z}from"./chunk-IZ2FJYHG.js";import{a as L}from"./chunk-BPMSNGXQ.js";import{a as T,b as j,d as ne}from"./chunk-VE3SUJMA.js";import{b as J}from"./chunk-TZXXJWHA.js";import{p as b}from"./chunk-56PAQAX5.js";import{b as Q}from"./chunk-AJQT4IWZ.js";import{a as D}from"./chunk-LVN6VHFN.js";import{a as B,e as K}from"./chunk-EYOCNMUM.js";import{a as z}from"./chunk-PXCMEI73.js";import{a as q}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as I,j as G}from"./chunk-C44QQJR4.js";import{a as me}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var s=F(me(),1);import{basename as ve}from"path";var o=F(q(),1);function Ne({resultRef:x,mode:g="singleshot",loginCompleteRef:d}){let{exit:m}=G(),A=(0,s.useRef)(new z),E=(0,s.useRef)(new te),v=(0,s.useRef)(new ee),n=A.current,l=E.current,O=v.current,le=V(),[h,f]=(0,s.useState)(g==="login"?"login":"gate"),[M,ae]=(0,s.useState)(null),[xe,R]=(0,s.useState)(null),[Pe,$]=(0,s.useState)(null),[X,ce]=(0,s.useState)(null),[N,_]=(0,s.useState)([]),P=(0,s.useCallback)((e,t,i,r)=>O.log(e,t,i,r),[O]),we=(0,s.useCallback)((e,t)=>{e?T(n,l,e,t):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[n,l]),C=(0,s.useCallback)(()=>{if(g==="login")d&&(d.current=!0),m();else{let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(t.kind==="unset"||t.kind==="choose-mobile")&&J();f(i?"target":"input")}},[g,m,d,l]),S=(0,s.useCallback)((e,t)=>{let i=T(n,l,e,t);if(g==="login"){f("ensure-project");return}ne(i)?C():i.projectId?f("ensure-folder"):f("ensure-project")},[n,l,C,g]);I((e,t)=>{t.ctrl&&e==="c"&&b(0,"Ctrl+C exit")});let U=(0,s.useRef)(!1);s.default.useEffect(()=>{U.current||(U.current=!0,g!=="login"&&ie(n,P).then(e=>{ae(e),e.status==="authenticated"?S(e.result.profile,e.result.env):e.status==="needs_pick"?f("pick"):(R(e.profile??null),$(e.env??null),f("login"))}).catch(e=>{ce(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[n,P]);let ue=(0,s.useCallback)(e=>{x.current={objective:e},m()},[x,m]),fe=(0,s.useCallback)(async(e,t)=>{n.setActiveProfile(e),n.setDefaultEnv(t),(await re(n,e,t,P)).status==="authenticated"?S(e,t):(R(e),$(t),f("login"))},[n,P,S]),w=(0,s.useCallback)(()=>{let e=n.getActiveProfile(),t=n.getDefaultEnv();if(!e)return null;let i=D(t),r=n.loadBasicAuth(e,t);return new oe(i.controllerBaseUrl,async()=>n.loadCredentials(e,t)?.access_token??null,r,P)},[n,P]),de=(0,s.useCallback)(async()=>{let e=w();if(!e)return null;let t=e.cached??await e.resolve();if(!t)return null;let i=D(n.getDefaultEnv()),r=new L(i.tmsBaseUrl,t.username,t.access_key);try{let p=(await r.listProjects()).find(k=>k.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let y=await r.createProject("KaneAI Generated");return{id:y.id,name:y.name}}catch{return null}},[w,n]),ge=(0,s.useCallback)(async e=>{let t=w();if(!t)return null;let i=t.cached??await t.resolve();if(!i)return null;let r=D(n.getDefaultEnv()),a=new L(r.tmsBaseUrl,i.username,i.access_key);try{let y=(await a.listFolders(e)).find(pe=>pe.name==="Untitled");if(y)return{id:y.id,name:y.name};let k=await a.createFolder(e,"Untitled");return{id:k.id,name:k.name}}catch{return null}},[w,n]);if(h==="gate")return(0,o.jsx)(c,{paddingX:1,children:(0,o.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(X)return(0,o.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,o.jsx)(u,{color:"red",children:X}),(0,o.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(h==="pick"&&M?.status==="needs_pick")return(0,o.jsx)(he,{profiles:M.profiles,onSelect:fe});if(h==="login")return(0,o.jsx)(W,{devMode:process.env.KANE_DEV_MODE==="1",profiles:n.listProfiles(),onBasicLogin:async(e,t,i,r)=>{let{validateBasicAuth:a}=await import("./validate-basic-3CNUDDH7.js");await a(t,i,r),n.saveBasicAuth(e,t,{username:i,access_key:r}),n.setActiveProfile(e),n.setDefaultEnv(t)},onOAuthLogin:async(e,t)=>{let{LoginFlow:i}=await import("./login-flow-TRINUSBB.js");n.setDefaultEnv(t),n.setActiveProfile(e),await new i(e,t,n).login()},onComplete:(e,t)=>{R(e),$(t),n.setActiveProfile(e),n.setDefaultEnv(t),S(e,t)},onCancel:()=>{b(0,"Login cancelled")}});if(h==="ensure-project"){let e=n.getActiveProfile()??"default",t=n.getDefaultEnv(),i=()=>{if(g==="login"){f("ensure-folder");return}T(n,l,e,t).folderId?C():f("ensure-folder")};return(0,o.jsxs)(c,{flexDirection:"column",children:[(0,o.jsx)(c,{paddingX:1,marginBottom:1,children:(0,o.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,o.jsx)(Y,{resolver:w(),currentProjectId:l.load().project_id,env:t,onSelect:(r,a)=>{j(n,l,e,t,{projectId:r,projectName:a}),_(p=>[...p,`\u2713 Project: ${a} (${r})`]),i()},onCancel:async()=>{let r=await de();r&&(j(n,l,e,t,{projectId:r.id,projectName:r.name}),_(a=>[...a,`\u2713 Default project: ${r.name} (${r.id})`]),i())}})]})}if(h==="ensure-folder"){let e=n.getActiveProfile()??"default",t=n.getDefaultEnv(),i=n.loadProfileConfig(e,t);return(0,o.jsxs)(c,{flexDirection:"column",children:[(0,o.jsx)(c,{paddingX:1,marginBottom:1,children:(0,o.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,o.jsx)(Z,{resolver:w(),projectId:i?.project_id??"",currentFolderId:l.load().folder_id,env:t,onSelect:(r,a)=>{j(n,l,e,t,{folderId:r,folderName:a}),_(p=>[...p,`\u2713 Folder: ${a} (${r})`]),C()},onCancel:async()=>{if(!i?.project_id)return;let r=await ge(i.project_id);r&&(j(n,l,e,t,{folderId:r.id,folderName:r.name}),_(a=>[...a,`\u2713 Default folder: ${r.name} (${r.id})`]),C())}})]})}if(h==="target"){let e=B(l.load().mobile?.tui_target,l.load().mobile?.default_target?.kind).kind==="choose-mobile";return(0,o.jsx)(c,{paddingX:1,children:(0,o.jsx)(se,{mode:e?"mobile-only":"all",onSelect:t=>{l.setMobile({tui_target:t}),f("input")},onCancel:()=>f("input")})})}if(h==="input"){let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(()=>{if(t.kind==="emulator"||t.kind==="simulator"){let r=e?.default_target?.id??"(no device)",a=e?.default_app?Q(e.default_app)?e.default_app:ve(e.default_app):"(no app)";return`Config: ${K(t.kind)} \xB7 ${r} \xB7 ${a}`}return"Config: Desktop \xB7 Chrome"})();return(0,o.jsxs)(c,{flexDirection:"column",children:[N.length>0&&(0,o.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:N.map((r,a)=>(0,o.jsx)(u,{color:"green",children:r},a))}),(0,o.jsx)(c,{paddingX:1,children:(0,o.jsx)(u,{color:"gray",children:i})}),(0,o.jsx)(H,{onSubmit:ue,onEscape:()=>b(0,"User pressed Escape"),history:le,placeholder:"Type an objective..."})]})}return(0,o.jsx)(o.Fragment,{})}function he({profiles:x,onSelect:g}){let[d,m]=(0,s.useState)(0),[A,E]=(0,s.useState)(!1);return I((v,n)=>{if(!A){if(n.escape){b(0,"Profile picker cancelled");return}if(n.upArrow&&d>0&&m(l=>l-1),n.downArrow&&d<x.length-1&&m(l=>l+1),n.return){E(!0);let l=x[d];g(l.profile,l.env).catch(()=>E(!1))}}}),(0,o.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,o.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,o.jsx)(c,{marginTop:1,flexDirection:"column",children:x.map((v,n)=>(0,o.jsxs)(u,{children:[n===d?"\u276F ":" ",(0,o.jsx)(u,{color:n===d?"#ff9500":"white",bold:n===d,children:v.profile}),(0,o.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),A&&(0,o.jsx)(c,{marginTop:1,children:(0,o.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{Ne as a};