@testmuai/kane-cli 0.10.3 → 0.10.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ChatSurface-DN7VVN3Y.js +2 -0
- package/dist/ChromeProfilePicker-TVGWXTUU.js +2 -0
- package/dist/{CliFeedbackPrompt-JWCTMIGI.js → CliFeedbackPrompt-L5ILK66U.js} +1 -1
- package/dist/{CliUploadProgress-XFRRFRL4.js → CliUploadProgress-IU6BQLMV.js} +1 -1
- package/dist/{ConfigView-6JF4DOJN.js → ConfigView-LU5IRRQU.js} +1 -1
- package/dist/EvidenceViewOffer-DNTARDEL.js +2 -0
- package/dist/FolderPicker-6E5GE2K2.js +2 -0
- package/dist/InfoBox-SFFPLWCV.js +2 -0
- package/dist/LinksBox-6YDTIO6I.js +2 -0
- package/dist/ProfilesView-6C5HJQ3Y.js +2 -0
- package/dist/ProjectPicker-YIQIVXGK.js +2 -0
- package/dist/SaveSessionPrompt-X3N6OGYB.js +2 -0
- package/dist/SingleShotApp-MXNJPU6A.js +2 -0
- package/dist/SummaryBox-T7PDXDKS.js +2 -0
- package/dist/TestMdRunView-HRJSBP2C.js +2 -0
- package/dist/TestrunEvidenceTable-OGMWTJQF.js +2 -0
- package/dist/{WhoamiView-H7JNLLCY.js → WhoamiView-WGCWD7GP.js} +1 -1
- package/dist/{app-client-U2YYF65L.js → app-client-2RR5ATI6.js} +1 -1
- package/dist/app-download-ZS6ZMX2Z.js +2 -0
- package/dist/{assurance-job-F4L3T4VJ.js → assurance-job-QO4VJJCL.js} +1 -1
- package/dist/{binary-K3XMILST.js → binary-CCCTW3QQ.js} +1 -1
- package/dist/bind-JU4XPDN3.js +2 -0
- package/dist/bootstrap-BV7HAARR.js +2 -0
- package/dist/{bridge-2UHJOVLX.js → bridge-SPGIYAAG.js} +1 -1
- package/dist/{catalog-YCU6OHNV.js → catalog-ZAROGOJA.js} +1 -1
- package/dist/{catalog-client-MVEEHTG2.js → catalog-client-QLHCEPPZ.js} +1 -1
- package/dist/{changelog-5UB3AQT6.js → changelog-6L7W76ZH.js} +1 -1
- package/dist/chat-committer-7E3TRZ6P.js +2 -0
- package/dist/chat-controller-5ZBG23L6.js +2 -0
- package/dist/child-MNLSG77W.js +2 -0
- package/dist/{chunk-LRNUGKYH.js → chunk-2CJ75THZ.js} +1 -1
- package/dist/{chunk-UWPG5MWM.js → chunk-2EKLTUY2.js} +1 -1
- package/dist/{chunk-C4KAPGBS.js → chunk-2KPJ62RZ.js} +3 -3
- package/dist/{chunk-SMGRXKXX.js → chunk-2VLM4L3S.js} +1 -1
- package/dist/{chunk-ZHAMVLQZ.js → chunk-3A4KK22B.js} +1 -1
- package/dist/{chunk-L3BUPFAQ.js → chunk-3CFAE36M.js} +1 -1
- package/dist/{chunk-TU2KPOW2.js → chunk-3DFBFYTD.js} +2 -2
- package/dist/{chunk-6FFX4S7N.js → chunk-3HGKFRFL.js} +1 -1
- package/dist/{chunk-VKVYT6KZ.js → chunk-3JATEWA5.js} +2 -2
- package/dist/{chunk-GXQYFOBD.js → chunk-3O2RPYPM.js} +1 -1
- package/dist/chunk-3UY4WPMQ.js +8 -0
- package/dist/{chunk-6HRNG4CK.js → chunk-3VSAAB2W.js} +1 -1
- package/dist/{chunk-RNHSULQM.js → chunk-454IWKHT.js} +1 -1
- package/dist/{chunk-ZMWTRXFH.js → chunk-4DRFMDAW.js} +1 -1
- package/dist/{chunk-HRIDAK6Y.js → chunk-4FA44D6S.js} +1 -1
- package/dist/{chunk-YVVFXBT5.js → chunk-4G2T54FE.js} +1 -1
- package/dist/{chunk-N7IWR45S.js → chunk-4KFSSETE.js} +1 -1
- package/dist/chunk-4QV2RL6P.js +34 -0
- package/dist/{chunk-ERRIDBE7.js → chunk-4WFN23DE.js} +1 -1
- package/dist/{chunk-NPAUSUNM.js → chunk-4WKFM72U.js} +1 -1
- package/dist/{chunk-BLVDV3QQ.js → chunk-55W3WAAL.js} +1 -1
- package/dist/{chunk-YQZ736IQ.js → chunk-56NUPYFG.js} +1 -1
- package/dist/{chunk-PI7OXS62.js → chunk-5EAJO372.js} +1 -1
- package/dist/{chunk-35WUYKGO.js → chunk-5HJRYEOT.js} +1 -1
- package/dist/{chunk-Y3RJHWNK.js → chunk-5OGYXLOR.js} +1 -1
- package/dist/{chunk-CQDCNP7V.js → chunk-5ORBAYTU.js} +1 -1
- package/dist/{chunk-KKLCXRW6.js → chunk-642LB5R2.js} +1 -1
- package/dist/{chunk-OBNVGD5H.js → chunk-662MCICY.js} +1 -1
- package/dist/{chunk-PCQK62MP.js → chunk-6CMBA5SG.js} +1 -1
- package/dist/{chunk-X6FCXBXU.js → chunk-6FVGPKVX.js} +1 -1
- package/dist/{chunk-32HED7X2.js → chunk-6KUUSONE.js} +1 -1
- package/dist/{chunk-VCVEZEVS.js → chunk-6PURZLKM.js} +1 -1
- package/dist/{chunk-ZCBOHWN3.js → chunk-73EHVDL5.js} +1 -1
- package/dist/{chunk-QHH42RH5.js → chunk-7KASYSFM.js} +1 -1
- package/dist/{chunk-SJQTTEXQ.js → chunk-7V6JPZBM.js} +1 -1
- package/dist/{chunk-WE7HRAGO.js → chunk-7WWCIS2B.js} +1 -1
- package/dist/{chunk-M7A66MSK.js → chunk-A74JRNNX.js} +1 -1
- package/dist/{chunk-ENRFXGID.js → chunk-ABAUIIPD.js} +1 -1
- package/dist/{chunk-YILRYMMG.js → chunk-ABNQL3PQ.js} +1 -1
- package/dist/{chunk-GQAWZEA4.js → chunk-ACBNVGVJ.js} +1 -1
- package/dist/{chunk-YPGZ5E4I.js → chunk-AFOP7DVG.js} +1 -1
- package/dist/{chunk-JTNEF5ZP.js → chunk-AL6IAMYV.js} +1 -1
- package/dist/chunk-APXJRWIJ.js +2 -0
- package/dist/{chunk-EBJW6POT.js → chunk-ATCJ7EHL.js} +1 -1
- package/dist/{chunk-IZ66FKPC.js → chunk-BIGOLVK6.js} +1 -1
- package/dist/{chunk-LHJSIHLC.js → chunk-BIXABKSK.js} +1 -1
- package/dist/chunk-BK3LWNKB.js +102 -0
- package/dist/{chunk-X2MDL6S4.js → chunk-BPTWMV5L.js} +1 -1
- package/dist/{chunk-4CJQ7XZP.js → chunk-BV7NUIRT.js} +1 -1
- package/dist/{chunk-UJ37XGSP.js → chunk-BXAPTB2H.js} +3 -3
- package/dist/{chunk-X7S7IGCV.js → chunk-BXJNL22L.js} +1 -1
- package/dist/{chunk-Z24SD2EJ.js → chunk-C3DMMAFP.js} +1 -1
- package/dist/chunk-CBEMXSWF.js +2 -0
- package/dist/{chunk-IEHJG6J4.js → chunk-CVVZ6NWR.js} +1 -1
- package/dist/{chunk-OZNYQONA.js → chunk-DAV4ONGS.js} +3 -3
- package/dist/{chunk-MEBEVHGP.js → chunk-DBMDAWTA.js} +1 -1
- package/dist/{chunk-CNHKZE4F.js → chunk-DJ76NDW6.js} +1 -1
- package/dist/{chunk-ZPU3WAC4.js → chunk-DRWHVVW6.js} +1 -1
- package/dist/{chunk-Z47ZEFH7.js → chunk-DXXHCLFC.js} +1 -1
- package/dist/{chunk-35BG2EMW.js → chunk-E3C4OWSD.js} +1 -1
- package/dist/{chunk-KQ4XKTIZ.js → chunk-ECPSBI2Z.js} +1 -1
- package/dist/{chunk-X45RZIAJ.js → chunk-EG3B52WU.js} +1 -1
- package/dist/{chunk-EJGCIGQY.js → chunk-EOLMWSLX.js} +1 -1
- package/dist/{chunk-GAKBHNC4.js → chunk-EUGFABAS.js} +1 -1
- package/dist/{chunk-OTMHCHH6.js → chunk-EWK3UPEN.js} +1 -1
- package/dist/{chunk-NI3TIAD7.js → chunk-EWSNJ3IX.js} +1 -1
- package/dist/{chunk-SALZ6WSF.js → chunk-F4XCCOWC.js} +1 -1
- package/dist/{chunk-YNDELIXL.js → chunk-FH4FWIET.js} +1 -1
- package/dist/chunk-FQ2AMM3E.js +3 -0
- package/dist/{chunk-5YYCCM6K.js → chunk-FTP2K6RS.js} +1 -1
- package/dist/{chunk-JBKHX5ES.js → chunk-GJYMR4RT.js} +1 -1
- package/dist/{chunk-NHGPMYM3.js → chunk-GMSWZIAS.js} +1 -1
- package/dist/{chunk-AHT2ORJT.js → chunk-GPIVYCHQ.js} +1 -1
- package/dist/{chunk-ZDCXWEQG.js → chunk-GRQKMOKE.js} +1 -1
- package/dist/{chunk-E4GIGM5V.js → chunk-H6IPGZTP.js} +1 -1
- package/dist/{chunk-7Y55CO42.js → chunk-H6QHG62O.js} +1 -1
- package/dist/{chunk-MINDIQET.js → chunk-HBGYEA3O.js} +1 -1
- package/dist/{chunk-VO2NNXKR.js → chunk-HGKAUG7L.js} +1 -1
- package/dist/{chunk-Q4SMITTV.js → chunk-HMGM4KO6.js} +1 -1
- package/dist/{chunk-CTHUX7O4.js → chunk-I3G3IUKY.js} +1 -1
- package/dist/{chunk-MD3RABID.js → chunk-IDWAG6L4.js} +1 -1
- package/dist/{chunk-TM6VLC6V.js → chunk-IPIARGHE.js} +1 -1
- package/dist/chunk-IQMJJN52.js +3 -0
- package/dist/{chunk-WEJR2V7R.js → chunk-J3XOEMKO.js} +1 -1
- package/dist/{chunk-GJXO6FF7.js → chunk-JBUKEIYL.js} +1 -1
- package/dist/{chunk-7RELCXRW.js → chunk-JE5M5QIK.js} +1 -1
- package/dist/{chunk-QEM5ZRDN.js → chunk-JJDD4HPX.js} +1 -1
- package/dist/{chunk-NRAPCFI2.js → chunk-JM45SLKV.js} +2 -2
- package/dist/{chunk-GEZVC4S3.js → chunk-JM6AKCN4.js} +1 -1
- package/dist/{chunk-3KY7HHQU.js → chunk-JSSM2TWY.js} +1 -1
- package/dist/{chunk-3MD2XLE7.js → chunk-JYSIPTX3.js} +9 -8
- package/dist/{chunk-AVLYSNEG.js → chunk-KJZD2ADR.js} +1 -1
- package/dist/chunk-KLY6IQD5.js +26 -0
- package/dist/{chunk-LTPOMMAB.js → chunk-LB5NIDW6.js} +1 -1
- package/dist/{chunk-HV2CDY4K.js → chunk-LCBDNZL3.js} +1 -1
- package/dist/{chunk-SIHX5FW5.js → chunk-LJKTIKZY.js} +1 -1
- package/dist/{chunk-SXBPUUQ5.js → chunk-LLDEAV3W.js} +1 -1
- package/dist/{chunk-PTLOOVV4.js → chunk-LV7OWLJK.js} +1 -1
- package/dist/{chunk-TUSG7DIL.js → chunk-MNELOQ4J.js} +1 -1
- package/dist/{chunk-3ZC7GSMM.js → chunk-MOAZZKIZ.js} +1 -1
- package/dist/{chunk-YWWVF5OU.js → chunk-MQU6EA44.js} +1 -1
- package/dist/chunk-MTMHB5LF.js +2 -0
- package/dist/{chunk-Q4ALB7SH.js → chunk-MWLRLQ27.js} +1 -1
- package/dist/{chunk-OHGL4GEJ.js → chunk-MZ4GTIO2.js} +1 -1
- package/dist/chunk-NKJRAQ6L.js +6 -0
- package/dist/{chunk-LPJKNX6D.js → chunk-NMCE7VR2.js} +1 -1
- package/dist/{chunk-7V34ZMMS.js → chunk-OKCVG7AG.js} +1 -1
- package/dist/{chunk-LZGAFKYH.js → chunk-OMCJD4LH.js} +1 -1
- package/dist/{chunk-OOGKX4Y6.js → chunk-OSEXVHEN.js} +1 -1
- package/dist/{chunk-EZMRWXRT.js → chunk-OVB5GVRB.js} +1 -1
- package/dist/{chunk-ND6OP3O2.js → chunk-OX3ZAGCH.js} +1 -1
- package/dist/{chunk-LXK4B2FE.js → chunk-P43YHCF3.js} +1 -1
- package/dist/{chunk-ZMIKNNO6.js → chunk-P7V24ZXP.js} +1 -1
- package/dist/{chunk-3NWUXRSI.js → chunk-PBVNX43X.js} +1 -1
- package/dist/{chunk-MEMXFTLD.js → chunk-PEHVBCXM.js} +1 -1
- package/dist/{chunk-4UX5N7YI.js → chunk-PHKJIJ7D.js} +1 -1
- package/dist/{chunk-BBJAKSA7.js → chunk-PMYN3XMN.js} +2 -2
- package/dist/{chunk-R6TFRAMZ.js → chunk-PUNFWBRW.js} +1 -1
- package/dist/chunk-Q5B54TR5.js +2 -0
- package/dist/{chunk-KCXLRR3Q.js → chunk-QEBVYQNC.js} +1 -1
- package/dist/{chunk-PB6RXDWQ.js → chunk-QFA6JPVE.js} +2 -2
- package/dist/{chunk-TAY7J5VS.js → chunk-QLGQDNA3.js} +1 -1
- package/dist/{chunk-7SU53QGU.js → chunk-QOXUGYEA.js} +1 -1
- package/dist/{chunk-LV7224DG.js → chunk-QXZGBYGQ.js} +1 -1
- package/dist/{chunk-4KL3TSTT.js → chunk-QYWWL7M7.js} +4 -4
- package/dist/{chunk-M2E5CPPV.js → chunk-RG3FNO37.js} +1 -1
- package/dist/{chunk-YCVEI7BT.js → chunk-RNKJXVG2.js} +1 -1
- package/dist/{chunk-HBLHKQR7.js → chunk-S5PIVHPC.js} +1 -1
- package/dist/{chunk-LUA25RYS.js → chunk-S74NLCFZ.js} +1 -1
- package/dist/chunk-SBW3QVHN.js +7 -0
- package/dist/{chunk-2TK4MDF2.js → chunk-SMSQVGLH.js} +1 -1
- package/dist/{chunk-Y2HQMJGS.js → chunk-SO3IXFAJ.js} +1 -1
- package/dist/{chunk-T77LTLAD.js → chunk-SULRMI2J.js} +1 -1
- package/dist/{chunk-KL7XFNSD.js → chunk-SZQNYDST.js} +1 -1
- package/dist/chunk-T5FQRUI2.js +47 -0
- package/dist/{chunk-HVOXMCKE.js → chunk-TCK7WR3M.js} +1 -1
- package/dist/{chunk-OCMPWCKQ.js → chunk-TELSHQ3W.js} +1 -1
- package/dist/{chunk-FOLUB336.js → chunk-TFSWG7AS.js} +1 -1
- package/dist/{chunk-2JFRN62I.js → chunk-TLYFHPNM.js} +2 -2
- package/dist/{chunk-CB2BWDHG.js → chunk-TO2ROHIJ.js} +4 -4
- package/dist/{chunk-PRBWZXFA.js → chunk-TOOJTCON.js} +6 -6
- package/dist/{chunk-DQXQJJOP.js → chunk-TXRWH6HL.js} +2 -2
- package/dist/chunk-U5V3L5QH.js +2 -0
- package/dist/{chunk-WIVKLNIO.js → chunk-UVBPUZC4.js} +1 -1
- package/dist/{chunk-23DKB2MT.js → chunk-UVL6XQHU.js} +1 -1
- package/dist/{chunk-DC5F2ADJ.js → chunk-UZKVV3LW.js} +1 -1
- package/dist/{chunk-YDB72F4K.js → chunk-V4SL74TK.js} +1 -1
- package/dist/chunk-V57R4X3O.js +5 -0
- package/dist/{chunk-LLQWEGXD.js → chunk-W5EDS4DF.js} +1 -1
- package/dist/{chunk-6QH75BPJ.js → chunk-WB4JZ67W.js} +1 -1
- package/dist/{chunk-W54BX6HC.js → chunk-WCIRLITM.js} +1 -1
- package/dist/{chunk-OCVDMZWB.js → chunk-WHMCVH3T.js} +1 -1
- package/dist/{chunk-XKOVEMVZ.js → chunk-WMIR4UXG.js} +1 -1
- package/dist/chunk-WMXBRC4B.js +21 -0
- package/dist/{chunk-RQKMSNEU.js → chunk-WTMCDYR3.js} +1 -1
- package/dist/{chunk-DXIQVBMI.js → chunk-WZ3FE5MT.js} +1 -1
- package/dist/{chunk-3RO2YGKH.js → chunk-X3O4VGTM.js} +1 -1
- package/dist/{chunk-GLM5UGTF.js → chunk-X66NIHT4.js} +1 -1
- package/dist/{chunk-B7ZX5HEN.js → chunk-XDAFRUAJ.js} +1 -1
- package/dist/{chunk-JNPFEBUR.js → chunk-XDAHKZ4J.js} +1 -1
- package/dist/{chunk-ZCL7XIVS.js → chunk-XKJZG4GR.js} +1 -1
- package/dist/chunk-XTQUCCJH.js +2 -0
- package/dist/{chunk-SVIIUKJ2.js → chunk-Y7GSOKXS.js} +1 -1
- package/dist/chunk-YIBLZIXF.js +13 -0
- package/dist/{chunk-J4FIESTB.js → chunk-YKOZBFR3.js} +1 -1
- package/dist/{chunk-TM45NPWL.js → chunk-YWQNZRJG.js} +1 -1
- package/dist/chunk-YZP4F23B.js +18 -0
- package/dist/{chunk-QE4AWNOV.js → chunk-Z4O5HOFX.js} +6 -6
- package/dist/{chunk-KBGMQYMD.js → chunk-ZFKR5I3J.js} +1 -1
- package/dist/{chunk-6QCCTZO3.js → chunk-ZHENGHYZ.js} +1 -1
- package/dist/{chunk-SSOUYKVG.js → chunk-ZIRSTOEV.js} +1 -1
- package/dist/{chunk-AT7AT3AR.js → chunk-ZVSZ6DIQ.js} +5 -5
- package/dist/command-span-HZSKIZH7.js +2 -0
- package/dist/commands-X5T6YANK.js +2 -0
- package/dist/{committer-UO3B3S5Y.js → committer-L2HXEODA.js} +1 -1
- package/dist/{config-7WTZPMAH.js → config-F5Q6QX27.js} +1 -1
- package/dist/cover-cmd-PWUZU4HK.js +2 -0
- package/dist/{credentials-5WIFF5DG.js → credentials-D5KQMHCK.js} +1 -1
- package/dist/{deps-bundle-BLLJ2BQ4.js → deps-bundle-R7FNIV4M.js} +1 -1
- package/dist/{deps-resolve-WQ6J6RLI.js → deps-resolve-IF6P6NWI.js} +1 -1
- package/dist/design-chat-HYK3HNIM.js +2 -0
- package/dist/{design-committer-7YIPFKMO.js → design-committer-ZKNW5LUS.js} +1 -1
- package/dist/design-headless-DR7WB37W.js +2 -0
- package/dist/design-remote-TGUNEWEM.js +3 -0
- package/dist/device-env-LZB3PKMA.js +2 -0
- package/dist/dispatch-BGH5PVZ4.js +2 -0
- package/dist/doctor-PLFEA2HM.js +2 -0
- package/dist/{docx-convert-DO5AQYD3.js → docx-convert-PA5S2S7P.js} +1 -1
- package/dist/{dossier-5XKNAK6Q.js → dossier-B6KBSRJY.js} +1 -1
- package/dist/evidence-SRWISQMQ.js +2 -0
- package/dist/evolve-cmd-2BALEYZU.js +2 -0
- package/dist/evolve-remote-OHOUWO65.js +2 -0
- package/dist/exit-manager-UZ7DGXS4.js +2 -0
- package/dist/{explain-cmd-KNDORU2D.js → explain-cmd-A5YMPXAJ.js} +1 -1
- package/dist/explain-cmd-VTDAMXAW.js +12 -0
- package/dist/explore-UZWQRJ7H.js +2 -0
- package/dist/explore-context-tty-PAKJVDJU.js +2 -0
- package/dist/explore-entry-ZOPO7DBZ.js +6 -0
- package/dist/{explore-live-XIWWUV52.js → explore-live-RUAAZGX4.js} +1 -1
- package/dist/{explore-run-tty-M56I23IF.js → explore-run-tty-DYLMHI7F.js} +2 -2
- package/dist/{extract-bind-LZ22VFKB.js → extract-bind-WPICR4IC.js} +3 -3
- package/dist/extract-chat-KVUB5HPM.js +2 -0
- package/dist/{extract-cmd-46E2XDWZ.js → extract-cmd-OJ7LXSKL.js} +2 -2
- package/dist/extract-headless-OQJSUSG4.js +2 -0
- package/dist/{feeder-NGWIPZ26.js → feeder-VAY4NYBX.js} +1 -1
- package/dist/folder-flags-MEZUAXTT.js +2 -0
- package/dist/gaps-cmd-2R4RMWN6.js +3 -0
- package/dist/gate-SM4HPJLA.js +2 -0
- package/dist/gate-VJ7W5QIH.js +2 -0
- package/dist/{generate-headless-HXAVEAEZ.js → generate-headless-XR3RVULC.js} +3 -3
- package/dist/hold-passthrough-ZHOC2Q26.js +2 -0
- package/dist/identity-66TGWITQ.js +2 -0
- package/dist/{impact-cmd-TJTUFAFO.js → impact-cmd-EL3QSOAF.js} +2 -2
- package/dist/index.js +185 -184
- package/dist/ingest-6UQGSQYU.js +2 -0
- package/dist/ingest-cmd-N3USC7TW.js +8 -0
- package/dist/ingest-remote-2VKWAFJZ.js +2 -0
- package/dist/install-3IEM3I3X.js +2 -0
- package/dist/{interactive-bind-SOD7VTAY.js → interactive-bind-F7QTQOKC.js} +4 -4
- package/dist/{interactive-remote-7ZSTI66T.js → interactive-remote-A33J4KMP.js} +2 -2
- package/dist/lane-EHU4JRRU.js +2 -0
- package/dist/lattice-auth-IJT542IF.js +2 -0
- package/dist/lifecycle-cmd-OKUFZKEX.js +2 -0
- package/dist/list-cmd-7OTI66MQ.js +3 -0
- package/dist/list-commands-FZPVH76I.js +2 -0
- package/dist/{list-remote-EFCET42K.js → list-remote-BQ4NILCA.js} +1 -1
- package/dist/{locks-cmd-AZKCSGHI.js → locks-cmd-76IU4JB7.js} +1 -1
- package/dist/{logical-ids-74PLU3VR.js → logical-ids-YMNV2MDB.js} +1 -1
- package/dist/login-flow-BYQ7SYGB.js +2 -0
- package/dist/maintenance-cmd-BLV7K4RK.js +2 -0
- package/dist/mobile-prompts-5TGLJUBV.js +2 -0
- package/dist/onboarding-F4EIJ4GD.js +5 -0
- package/dist/open-provider-LXCPVNUU.js +2 -0
- package/dist/{pdf-convert-YB6PJFMI.js → pdf-convert-N2C3KB4Q.js} +1 -1
- package/dist/persist-recorded-session-WYMOHDTB.js +3 -0
- package/dist/phase-seed-G5JSYKSL.js +2 -0
- package/dist/pipeline-XYM6HIDZ.js +2 -0
- package/dist/{policy-commands-4PUGESCW.js → policy-commands-AOLVAZZD.js} +1 -1
- package/dist/prepare-target-P4AZWC37.js +2 -0
- package/dist/pull-cmd-C4HMYD4I.js +2 -0
- package/dist/pull-route-MHW5PWDW.js +2 -0
- package/dist/readmodel-FARAAPUU.js +2 -0
- package/dist/real-device-run-WAOWKEFJ.js +2 -0
- package/dist/reconcile-cmd-VXY737OT.js +5 -0
- package/dist/reconcile-deps-TILDRCHG.js +2 -0
- package/dist/{reconcile-remote-3W6ZTO3G.js → reconcile-remote-UGW2433E.js} +2 -2
- package/dist/recording-banner-EPOTSMYF.js +2 -0
- package/dist/registry-WTWTFRXD.js +2 -0
- package/dist/remote-entry-SPA4CSJJ.js +2 -0
- package/dist/remote-mode-QO6BDGXM.js +4 -0
- package/dist/remote-words-TAZT4YBT.js +2 -0
- package/dist/{require-project-folder-3DTI2CVB.js → require-project-folder-WBCAVVMB.js} +1 -1
- package/dist/resolve-run-intent-RBOCIYEA.js +2 -0
- package/dist/{resolver-CDF7QKVD.js → resolver-3BGIXYYJ.js} +1 -1
- package/dist/revert-F6MKJ73M.js +2 -0
- package/dist/review-cmd-WE6I5XTY.js +5 -0
- package/dist/run-EABFRFOF.js +2 -0
- package/dist/run-LX3ARF53.js +2 -0
- package/dist/run-remote-6Y62RWMJ.js +2 -0
- package/dist/run-startup-gate-Q7FP2IRE.js +2 -0
- package/dist/run-test-md-24MBKBC6.js +20 -0
- package/dist/session-worker.js +2 -2
- package/dist/{sessions-cmd-TLUITRG5.js → sessions-cmd-5NS5P4CP.js} +2 -2
- package/dist/{sessions-remote-INO7AWKB.js → sessions-remote-75PDRPOY.js} +1 -1
- package/dist/{skill-installer-7JH5QCJF.js → skill-installer-7PK64TZE.js} +1 -1
- package/dist/store-AVYBL5HB.js +2 -0
- package/dist/store-choice-ZWU3PDNL.js +2 -0
- package/dist/store-guard-ETUXXG7X.js +2 -0
- package/dist/{store-site-K5NHLI7D.js → store-site-AFXB6SBW.js} +1 -1
- package/dist/{stream-warnings-GM7YEOVG.js → stream-warnings-I5LUWVFU.js} +1 -1
- package/dist/support-id-RISKXA53.js +2 -0
- package/dist/sync-cmd-CSTMT6E6.js +2 -0
- package/dist/sync-setup-Y53K6TJ6.js +2 -0
- package/dist/tcg-generate-VQLI6NGK.js +2 -0
- package/dist/{test-definition-53XNBEDE.js → test-definition-GXEKFRRB.js} +1 -1
- package/dist/testmd-actions-BE4YJ6ZZ.js +2 -0
- package/dist/{testmd-sync-LYHEXWCT.js → testmd-sync-QZWVWTZZ.js} +1 -1
- package/dist/token-refresh-PZ3TOKAL.js +2 -0
- package/dist/{use-case-ref-44BPIP4N.js → use-case-ref-E3PJDHQB.js} +1 -1
- package/dist/{validate-basic-66XDPA3S.js → validate-basic-QWPESO74.js} +1 -1
- package/dist/verdicts-KB6YTIY6.js +2 -0
- package/dist/{version-check-SHNVYTMU.js → version-check-EOYWTY3Z.js} +1 -1
- package/dist/{view-cmd-QOB3O6YW.js → view-cmd-KG4HI334.js} +1 -1
- package/dist/walk-session-WM4S2JMV.js +2 -0
- package/dist/with-telemetry-RJM3JKL6.js +2 -0
- package/package.json +11 -11
- package/dist/ChatSurface-Z26BOE5U.js +0 -2
- package/dist/ChromeProfilePicker-ODRIAXL3.js +0 -2
- package/dist/EvidenceViewOffer-6344EX74.js +0 -2
- package/dist/FolderPicker-4PCYHE75.js +0 -2
- package/dist/InfoBox-NJ2DL7YC.js +0 -2
- package/dist/LinksBox-HNDNFVUT.js +0 -2
- package/dist/ProfilesView-DEJKJOHY.js +0 -2
- package/dist/ProjectPicker-DTWMWOH7.js +0 -2
- package/dist/SaveSessionPrompt-3GCLB3ZT.js +0 -2
- package/dist/SingleShotApp-HMOXO5DW.js +0 -2
- package/dist/SummaryBox-7PPDMSSM.js +0 -2
- package/dist/TestMdRunView-QLKRUU4V.js +0 -2
- package/dist/TestrunEvidenceTable-T2JUB4TE.js +0 -2
- package/dist/app-download-GKRF2EIM.js +0 -2
- package/dist/bind-SSHAZAB3.js +0 -2
- package/dist/bootstrap-XGKU4WXB.js +0 -2
- package/dist/chat-committer-ZKEKJA2R.js +0 -2
- package/dist/chat-controller-FXRJXUG3.js +0 -2
- package/dist/child-JHYENXE7.js +0 -2
- package/dist/chunk-2RBMQTYS.js +0 -26
- package/dist/chunk-5F5IVART.js +0 -8
- package/dist/chunk-6SD4XTYC.js +0 -6
- package/dist/chunk-7YV2FCN4.js +0 -3
- package/dist/chunk-A2DODRHG.js +0 -2
- package/dist/chunk-BJO6J5X2.js +0 -3
- package/dist/chunk-DIOK3SER.js +0 -34
- package/dist/chunk-DREQ3RAA.js +0 -2
- package/dist/chunk-HC6VLPUB.js +0 -5
- package/dist/chunk-NZJSGINB.js +0 -47
- package/dist/chunk-SXRHKXSE.js +0 -2
- package/dist/chunk-UJLULWSR.js +0 -21
- package/dist/chunk-ULIIYKZB.js +0 -7
- package/dist/chunk-UXGMKRS4.js +0 -102
- package/dist/chunk-VO66KP2W.js +0 -2
- package/dist/chunk-X52YIWGG.js +0 -13
- package/dist/chunk-ZIHQ5JGB.js +0 -18
- package/dist/commands-JBFLLT7A.js +0 -2
- package/dist/cover-cmd-DU6ZYJFL.js +0 -2
- package/dist/design-chat-ZICGVYIH.js +0 -2
- package/dist/design-headless-HYWZIIDS.js +0 -2
- package/dist/design-remote-HPX4VZ63.js +0 -3
- package/dist/device-env-4P4GUVBW.js +0 -2
- package/dist/dispatch-BV6XMCN3.js +0 -2
- package/dist/doctor-Z2YQ2DBX.js +0 -2
- package/dist/evidence-BJIID6VT.js +0 -2
- package/dist/evolve-cmd-GZCUSCEK.js +0 -2
- package/dist/evolve-remote-LILOAHYH.js +0 -2
- package/dist/exit-manager-EGWAZHCR.js +0 -2
- package/dist/explain-cmd-LXIVHGN7.js +0 -12
- package/dist/explore-SA2P3SGX.js +0 -2
- package/dist/explore-context-tty-PERKIWXD.js +0 -2
- package/dist/explore-entry-E6EY3VV3.js +0 -6
- package/dist/extract-chat-Z64LEAJ5.js +0 -2
- package/dist/extract-headless-XLS56LMN.js +0 -2
- package/dist/folder-flags-ZIDJVDKX.js +0 -2
- package/dist/gaps-cmd-XYOBJVTO.js +0 -3
- package/dist/gate-AK44VDHC.js +0 -2
- package/dist/gate-NB5CJMTN.js +0 -2
- package/dist/hold-passthrough-JGHWMYDM.js +0 -2
- package/dist/identity-HL5CJJXR.js +0 -2
- package/dist/ingest-ZHHHBUXR.js +0 -2
- package/dist/ingest-cmd-OJSKTSQK.js +0 -8
- package/dist/ingest-remote-2WM6PYUW.js +0 -2
- package/dist/install-JBWBF3WX.js +0 -2
- package/dist/lane-CNGO7LH5.js +0 -2
- package/dist/lattice-auth-UQPFQSG7.js +0 -2
- package/dist/lifecycle-cmd-DGIO3VAO.js +0 -2
- package/dist/list-cmd-HQIN3HX4.js +0 -3
- package/dist/list-commands-OFRRBU3D.js +0 -2
- package/dist/login-flow-SYKXXDLH.js +0 -2
- package/dist/maintenance-cmd-X5247RSJ.js +0 -2
- package/dist/mobile-prompts-I66ENBDW.js +0 -2
- package/dist/onboarding-6HIP3KW6.js +0 -5
- package/dist/open-provider-XDJKT3W3.js +0 -2
- package/dist/persist-recorded-session-RSSMTVF3.js +0 -3
- package/dist/phase-seed-ZZSJME7M.js +0 -2
- package/dist/pipeline-NTJDH5TC.js +0 -2
- package/dist/prepare-target-AI3GGZF6.js +0 -2
- package/dist/pull-cmd-NRVB5ZN7.js +0 -2
- package/dist/pull-route-FWCZW76M.js +0 -2
- package/dist/readmodel-TRV4E3MW.js +0 -2
- package/dist/real-device-run-NQ7RNH7C.js +0 -2
- package/dist/reconcile-cmd-7B7THAFJ.js +0 -5
- package/dist/reconcile-deps-UDQBWSLE.js +0 -2
- package/dist/recording-banner-WVDTWTSE.js +0 -2
- package/dist/registry-PFOSXOIH.js +0 -2
- package/dist/remote-entry-BZU4NFNS.js +0 -2
- package/dist/remote-mode-NXUKDUXG.js +0 -4
- package/dist/remote-words-JRDDNOZ6.js +0 -2
- package/dist/resolve-run-intent-QCL7QXIB.js +0 -2
- package/dist/revert-QKHPCRT6.js +0 -2
- package/dist/review-cmd-XBK3TGRE.js +0 -5
- package/dist/run-CSYGVV3D.js +0 -2
- package/dist/run-YUHHD54J.js +0 -2
- package/dist/run-remote-SFR3F2T5.js +0 -2
- package/dist/run-startup-gate-QSFJRYUY.js +0 -2
- package/dist/run-test-md-ZSREINDQ.js +0 -20
- package/dist/store-X4UK4AP7.js +0 -2
- package/dist/store-choice-27HDIFTU.js +0 -2
- package/dist/store-guard-ZXKB5DQH.js +0 -2
- package/dist/sync-cmd-2PCO7LZA.js +0 -2
- package/dist/sync-setup-5WQO73Y5.js +0 -2
- package/dist/tcg-generate-DGJD5KSM.js +0 -2
- package/dist/testmd-actions-XE2JPQHB.js +0 -2
- package/dist/token-refresh-E4FTJVHY.js +0 -2
- package/dist/verdicts-PVB7TV5S.js +0 -2
- package/dist/walk-session-WIEROYOT.js +0 -2
- package/dist/with-telemetry-T2PWI5CY.js +0 -2
package/dist/chunk-5F5IVART.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as Be}from"./chunk-IZ66FKPC.js";import{a as Te}from"./chunk-GLM5UGTF.js";import{a as ce,b as Pe,c as Ue,d as ae,e as le,f as ue}from"./chunk-W5HFUBXD.js";import{a as Ne,b as je}from"./chunk-63EKRZKI.js";import{c as Le,d as Ge}from"./chunk-ZHAMVLQZ.js";import{g as Me}from"./chunk-SIHX5FW5.js";import{i as De}from"./chunk-X7S7IGCV.js";import{a as Ce}from"./chunk-FNUGDPTS.js";import{Ea as Re,Ia as $e,M as L,Na as Ie,Oa as Oe,e as be,sa as Ae,v as U}from"./chunk-PI7OXS62.js";import{e as ve,n as Se}from"./chunk-DBMW3VUN.js";import{g as xe}from"./chunk-KU3YHPWZ.js";import{a as Ee}from"./chunk-ZAQGIC33.js";import{o as ie}from"./chunk-HYJVYYAZ.js";var ht=()=>null;function Zt(e){return e.telemetryIds?(e.provider??ht)({verb:e.verb,contextInstanceId:e.telemetryIds.context_instance_id??null,sessionId:e.telemetryIds.session_id}):e.storeLocalPath}function en(e,t){return e?t(e):"(no local trace)"}function nn(e){let t=process.env.HOME??"";return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}import{randomBytes as Ut}from"crypto";function de(e,t){let n=Math.min(e.length,t.length),s=0,r=0,c=0;for(let o=0;o<n;o++)s+=e[o]*t[o],r+=e[o]*e[o],c+=t[o]*t[o];return r===0||c===0?0:s/(Math.sqrt(r)*Math.sqrt(c))}function fe(e,t,n){return n*e+(1-n)*t}var ge=.7;var He=e=>e.lines!==void 0?[[e.lines[0],e.lines[1]]]:(e.segments??[]).map(([t,n])=>[t,n]);function Fe(e){let t=[];for(let[n,s]of He(e))for(let r=n;r<=s;r++)t.push(r);return t}function pt(e,t,n,s,r){let c=new Map(t.units.map(a=>[a.id,a]));if(r.some(a=>!c.has(a)))return null;let o=new Map;for(let a of e.units)r.includes(a.id)&&Fe(a).forEach((d,m)=>o.set(d,{unit:a,nth:m}));let g=new Map,u=[],f=!0;for(let a=n;a<=s&&f;a++){let d=o.get(a),m=d===void 0?void 0:c.get(d.unit.id);if(d===void 0||m===void 0||m.text!==d.unit.text){f=!1;break}let h=g.get(m.id);h===void 0&&g.set(m.id,h=Fe(m));let w=h[d.nth];w===void 0?f=!1:u.push(w)}return f&&u.length>0&&u.every((a,d)=>d===0||a===u[d-1]+1)?{anchor:`L${u[0]}-L${u[u.length-1]}`}:{units_at_head:r.flatMap(a=>He(c.get(a)).map(([d,m])=>({unit:a,anchor:`L${d}-L${m}`})))}}function Qe(e){let t=new Map,n=r=>{let c=e.mediaOf(r)?.plugin?.index;if(c===void 0)return null;let o=t.get(c);return o===void 0&&t.set(c,o=Se(e.getBlob(c))),o},s=new Map;return r=>{if(r.type!==xe.DERIVES||!Array.isArray(r.props.units)||r.props.units.length===0)return null;let c=r.props.units,o=e.headOf(String(r.props.source_id)),g=String(r.props.source_cid);if(o==null||o===g)return null;let u=s.get(o);u===void 0&&s.set(o,u=ve(o,w=>e.mediaOf(w)?.plugin));let f=u?.distance.get(g);if(u==null||f===void 0||c.some(w=>(u.touchedAt.get(w)??1/0)<=f))return null;let a=be(String(r.props.anchor));if(a?.kind!=="lines")return null;let d=n(g),m=n(o);if(d===null||m===null)return null;let h=pt(d,m,Math.min(a.a,a.b),Math.max(a.a,a.b),c);return h===null?null:{head:o,...h}}}var _t=["get_node","get_edges","find_by_provenance","match_by_type","stale_nodes","search_similar","search_similar_batch","history"],yt=["source_read","source_grep","source_list"],wt=[..._t,...yt],We=50,Xe=200,me=10,qe=50,Ve=20,kt=200,xt=50;function K(e,t,n){let s=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):t;return Math.max(1,Math.min(s,n))}function M(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new x(`param "${t}" must be a non-empty string`);return n}function O(e,t){let n=e[t];if(n==null)return null;if(typeof n!="string")throw new x(`param "${t}" must be a string when present`);return n}var x=class extends Error{},ze=24,bt=10,vt=10;function St(e){let t=e.cursor;if(t==null)return 0;if(typeof t=="string"&&/^\d+$/.test(t))return Number.parseInt(t,10);throw new x(`BAD_CURSOR: cursor ${JSON.stringify(t)} is not a cursor this store minted`)}function Ye(e,t){let n=t.fields;if(!Array.isArray(n)||n.length===0)return e;let s=new Set(n.filter(r=>typeof r=="string"));return e.map(r=>Object.fromEntries(Object.entries(r).filter(([c])=>s.has(c))))}function he(e,t,n=We,s=Xe){let r=St(t),c=K(t.limit,n,s),o=e.slice(r,r+c),g=r+o.length<e.length;return{rows:Ye(o,t),truncated:g,next_cursor:g?String(r+o.length):null}}var Et=e=>e.cursor!=null||e.fields!=null;function W(e,t,n=We){let s=he(e,t,n);return Et(t)||s.truncated?{rows:s.rows,truncated:s.truncated,next_cursor:s.next_cursor}:s.rows}function pe(e,t){let n=e.getNode(t);return n?{cid:t,label:n.label,content:n.content,trust:e.trust.get(t)??null,freshness:e.stale(t)}:null}function Ke(e){return new Set(e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").split(" ").filter(Boolean))}function X(e,...t){let n=Ke(e);if(n.size===0)return 0;let s=e.trim().toLowerCase(),r=0;for(let c of t){let o=Ke(c);if(o.size===0)continue;let g=0;for(let a of n)o.has(a)&&g++;let u=n.size+o.size-g,f=u===0?0:g/u;s&&c.toLowerCase().includes(s)&&(f=Math.max(f,.9)),r=Math.max(r,f)}return r}function At(e,t,n){let s=M(t,"cid"),r=O(t,"type"),c=O(t,"direction")??"both";if(!["out","in","both"].includes(c))throw new x('param "direction" must be out|in|both');let o=e.edgesFrom(s),g=e.edgesInto(s);if(o.length===0&&g.length===0&&!e.hasNode(s)&&![...e.heads.values()].includes(s))throw new x(`${s} names nothing in this project; read the cid again from where it was shown`);let u=[];(c==="out"||c==="both")&&u.push(...o),(c==="in"||c==="both")&&u.push(...g);let f=n===void 0?null:Qe({mediaOf:d=>e.mediaOf(d),getBlob:d=>n.getBlob(d),headOf:d=>e.heads.get(d)}),a=u.filter(d=>r==null||d.type===r).map(d=>{let m=f===null?null:f(d);return m===null?d:"anchor"in m?{...d,props:{...d.props,source_cid:m.head,anchor:m.anchor},pinned:{source_cid:d.props.source_cid,anchor:d.props.anchor}}:{...d,units_at_head:m.units_at_head}});return W(a,t)}function Rt(e,t){let n=M(t,"source_id"),s=e.heads.get(n)??null,r=[];for(let c of e.nodeLabel.keys()){let o=e.derivesInto(c).filter(u=>u.props.source_id===n).map(u=>({source_cid:u.props.source_cid,anchor:u.props.anchor??null}));if(o.length===0)continue;let g=pe(e,c);g&&r.push({...g,pins:o,pinned_to_head:s!=null&&o.some(u=>u.source_cid===s)})}return W(r,t,Xe)}function $t(e,t){let n=M(t,"label"),s=O(t,"trust"),r=O(t,"freshness"),c=[];for(let{cid:o}of e.byLabel(n)){let g=pe(e,o);g&&(s!=null&&g.trust!==s||r!=null&&g.freshness!==r||c.push(g))}return W(c,t)}function It(e,t={}){let n=O(t,"label"),s=e.staleList().map(({cid:r,state:c})=>{let o=e.getNode(r);return{cid:r,state:c,label:o?.label??null,title:o?.content.title??null}}).filter(r=>n==null||r.label===n);return W(s,t)}function Ot(e,t,n){let s=t.extracted,r=O(t,"kind"),c=[];for(let f of[...e.heads.keys()].sort()){let a=e.heads.get(f);if(typeof a!="string")continue;let m=e.mediaOf(a).format;if(r!=null&&m!==r)continue;let h=e.extractedSourceCids.has(a);if(typeof s=="boolean"&&h!==s)continue;let w=0;if(m!=="image"){let y=U(n,e,a);y&&(w=y.toString("utf8").replace(/\n$/,"").split(`
|
|
3
|
-
`).length)}let k=e.extractionCompleteness.get(f);c.push({source_id:f,kind:m,lines:w,head_cid:a,extracted:h,last_extract_at:k?.at??null,extractor_version:k?.extractor_version??null})}let{rows:o,truncated:g,next_cursor:u}=he(c,t);return{sources:o,truncated:g,next_cursor:u}}function Mt(e,t,n){let s=M(t,"ref"),r=e.resolve(s);if(!r)throw new x(`UNKNOWN_REF: ${s} names nothing in the graph`);let c=r.tip,o=new Map,g=v=>e.nodeLabel.get(v);for(let[v,A]of e.superseded)typeof A=="string"&&A!==v&&!Ae(v,A,g)&&o.set(A,[...o.get(A)??[],v]);let u=[],f=[c],a=new Set;for(;f.length>0;){let v=f.pop();a.has(v)||(a.add(v),u.push(v),f.push(...o.get(v)??[]))}let d=n.recordsSince(null),m=new Map,h=new Map;for(let v of d){for(let A of v.nodes)m.has(A.cid)||m.set(A.cid,v.ts);for(let A of v.supersessions)A.kind==="node"&&h.set(A.old,{by_cid:A.new,reason:A.reason})}let w=u.map(v=>({cid:v,minted_at:m.get(v)??null,superseded_by:h.get(v)?.by_cid??null,reason:h.get(v)?.reason??null,change_note:null})),{rows:k,truncated:y,next_cursor:D}=he(w,t,vt);return{root_logical_id:e.displayNameOf(c),live_tip:e.superseded.has(c)?null:c,truncated:y,next_cursor:D,chain:k}}function Je(e){let t=e.queries;if(!Array.isArray(t)||t.length<1||t.length>ze)throw new x(`param "queries" must be 1..${ze} entries`);return t.map((n,s)=>{if(typeof n!="object"||n===null)throw new x(`queries[${s}] must be an object`);let r=n;if(typeof r.qid!="string"||r.qid.length===0)throw new x(`queries[${s}].qid must be a non-empty string`);if(typeof r.text!="string"||r.text.length===0)throw new x(`queries[${s}].text must be a non-empty string`);return{qid:r.qid,text:r.text,topK:K(r.top_k,me,bt)}})}function Ze(e){let t=[];for(let{cid:n,content:s}of e.byLabel("usecase"))e.superseded.has(n)||t.push({cid:n,title:String(s.title??""),summary:String(s.summary??""),description:String(s.description??"")});return t}function et(e,t,n){let s=Ze(e);return t.map(r=>{let c=[];for(let o of s){let g=n(r,o);g<=0||c.push({cid:o.cid,logical_id:e.displayNameOf(o.cid),title:o.title,score:Math.round(g*1e3)/1e3,trust:e.trust.get(o.cid)??null,superseded:!1})}return c.sort((o,g)=>g.score-o.score||o.cid.localeCompare(g.cid)),{qid:r.qid,truncated:c.length>r.topK,matches:c.slice(0,r.topK)}})}function tt(e,t){let n=Je(t);return{results:et(e,n,(s,r)=>X(s.text,r.title,r.summary,r.description)),scorer:"lexical_fallback"}}function Dt(e,t){let n=M(t,"text"),s=O(t,"label")??"usecase",r=K(t.k,me,qe),c=[];for(let{cid:o,content:g}of e.byLabel(s)){let u=String(g.title??""),f=String(g.summary??""),a=X(n,u,f);a<=0||c.push({cid:o,title:u,summary:f,score:Math.round(a*1e3)/1e3,trust:e.trust.get(o)??null,freshness:e.stale(o)})}return c.sort((o,g)=>g.score-o.score||o.cid.localeCompare(g.cid)),c.slice(0,r)}function nt(e,t,n){let s=e.heads.get(n);if(typeof s!="string"){let c=[...e.heads.keys()].sort().join(", ");throw new x(`unknown source_id "${n}" \u2014 known: ${c||"(none)"}`)}if(e.mediaOf(s).format==="image")throw new x(`source "${n}" is an image \u2014 no line window (cite img#whole)`);let r=U(t,e,s);if(r==null)throw new x(`source "${n}" blob is missing from the store`);return{head:s,lines:r.toString("utf8").replace(/\n$/,"").split(`
|
|
4
|
-
`)}}function Ct(e,t,n){return e.slice(t-1,n).map((s,r)=>`${String(t+r).padStart(4,"0")}| ${s}`).join(`
|
|
5
|
-
`)}function Tt(e,t,n){let s=M(t,"source_id"),r=O(t,"anchor"),c=t.line_range;if(r!=null&&c!=null)throw new x("give anchor OR line_range, not both");let{head:o,lines:g}=nt(e,n,s),u=g.length,f,a;if(r!=null){let d=/^L(\d+)-L(\d+)$/.exec(r);if(!d)throw new x(`anchor "${r}" is not L<a>-L<b>`);let m=Number(d[1]),h=Number(d[2]);if(m<1||h<m||h>u)throw new x(`anchor "${r}" does not resolve (source has ${u} lines)`);f=Math.max(1,m-Ve),a=Math.min(u,h+Ve)}else if(c!=null){if(!Array.isArray(c)||c.length!==2||!c.every(h=>Number.isInteger(h)))throw new x('param "line_range" must be [from_line, to_line]');let[d,m]=c;if(d<1||m<d)throw new x('param "line_range" must be 1-based with from \u2264 to');if(d>u)throw new x(`line_range starts past the end (source has ${u} lines)`);f=d,a=Math.min(m,u)}else f=1,a=u;return a=Math.min(a,f+kt-1),{window:Ct(g,f,a),from_line:f,to_line:a,source_cid:o,total_lines:u}}function Lt(e,t,n){let s=M(t,"pattern"),r=O(t,"source_id"),c;try{c=new RegExp(s,"u")}catch(f){throw new x(`invalid pattern: ${f instanceof Error?f.message:String(f)}`)}let o=r!=null?[r]:[...e.heads.keys()].sort(),g=[],u=!1;e:for(let f of o){if(r==null){let d=e.heads.get(f);if(typeof d!="string"||e.mediaOf(d).format==="image")continue}let{lines:a}=nt(e,n,f);for(let d=0;d<a.length;d++)if(c.test(a[d])){if(g.length>=xt){u=!0;break e}g.push({source_id:f,line:d+1,text:a[d]})}}return{matches:g,truncated:u}}function Gt(e,t,n,s){try{switch(t){case"get_node":{let r=pe(e,M(n,"cid"));return r==null?{ok:!0,result:null}:{ok:!0,result:Ye([r],n)[0]}}case"get_edges":return{ok:!0,result:At(e,n,s)};case"find_by_provenance":return{ok:!0,result:Rt(e,n)};case"match_by_type":return{ok:!0,result:$t(e,n)};case"stale_nodes":return{ok:!0,result:It(e,n)};case"search_similar":return{ok:!0,result:Dt(e,n)};case"search_similar_batch":return{ok:!0,result:tt(e,n)};case"history":{if(s==null)throw new x("history unavailable (no context store)");return{ok:!0,result:Mt(e,n,s)}}case"source_list":{if(s==null)throw new x("source roster unavailable (no context store)");return{ok:!0,result:Ot(e,n,s)}}case"source_read":case"source_grep":{if(s==null)throw new x("source text unavailable (no context store)");return{ok:!0,result:(t==="source_read"?Tt:Lt)(e,n,s)}}default:return{ok:!1,error:`unknown method: ${t} \u2014 available: ${wt.join(", ")}`}}}catch(r){return r instanceof x?{ok:!1,error:`${t}: ${r.message}`}:{ok:!1,error:`${t}: graph read failed: ${r instanceof Error?r.message:String(r)}`}}}var I="assurance.sim";function Nt(e){return[e.title,e.summary,e.description].filter(Boolean).join(`
|
|
6
|
-
`)}async function jt(e,t,n){let s=M(t,"text"),r=O(t,"label")??"usecase",c=K(t.k,me,qe),o=[];for(let{cid:u,content:f}of e.byLabel(r)){if(e.superseded.has(u))continue;let a=String(f.title??""),d=String(f.summary??""),m=String(f.description??"");o.push({cid:u,title:a,summary:d,description:m,lex:X(s,a,d,m)})}let g=u=>{let f=[];for(let a of o){let d=u(a);d.score<=0||f.push({cid:a.cid,title:a.title,summary:a.summary,score:Math.round(d.score*1e3)/1e3,trust:e.trust.get(a.cid)??null,freshness:e.stale(a.cid),...d.dense!==void 0?{dense_score:Math.round(d.dense*1e3)/1e3,lexical_score:Math.round(a.lex*1e3)/1e3}:{}})}return f.sort((a,d)=>d.score-a.score||a.cid.localeCompare(d.cid)),f.slice(0,c)};try{let u=n.alpha??ge,{alias:f,dims:a}=await n.resolveAlias(I);ue(n.store,f,I,a);let d=new Map,m=[];for(let w of o){let k=ae(n.store,f,I,w.cid);k?d.set(w.cid,k):m.push({cid:w.cid,text:Nt(w)})}let[h]=await ce(w=>n.embed(I,w),[s],m,(w,k)=>{d.set(w,k),le(n.store,f,I,w,k)});return g(w=>{let k=d.get(w.cid),y=k?de(h,k):0;return{score:fe(y,w.lex,u),dense:y}})}catch{return n.onDegraded?.(),g(u=>({score:u.lex}))}}async function Pt(e,t,n){let s=Je(t),r=Ze(e);try{let c=n.alpha??ge,{alias:o,dims:g}=await n.resolveAlias(I);ue(n.store,o,I,g);let u=new Map,f=[];for(let m of r){let h=ae(n.store,o,I,m.cid);h?u.set(m.cid,h):f.push({cid:m.cid,text:[m.title,m.summary,m.description].filter(Boolean).join(`
|
|
7
|
-
`)})}let a=await ce(m=>n.embed(I,m),s.map(m=>m.text),f,(m,h)=>{u.set(m,h),le(n.store,o,I,m,h)}),d=new Map(s.map((m,h)=>[m.qid,h]));return{results:et(e,s,(m,h)=>{let w=u.get(h.cid),k=w?de(a[d.get(m.qid)],w):0;return fe(k,X(m.text,h.title,h.summary,h.description),c)}),scorer:"embedding"}}catch{return n.onDegraded?.(),tt(e,t)}}async function rt(e,t,n,s){if((t==="search_similar"||t==="search_similar_batch")&&s)try{return{ok:!0,result:t==="search_similar"?await jt(e,n,s):await Pt(e,n,s)}}catch(r){return r instanceof x?{ok:!1,error:`${t}: ${r.message}`}:{ok:!1,error:`${t}: graph read failed: ${r instanceof Error?r.message:String(r)}`}}return Gt(e,t,n,s?.store)}var Bt=2,st=10,Ft=2;function Ht(e,t){return t?e.type==="usage"?{...e,total_credits:t+e.total_credits}:e.type==="state_checkpoint"?{...e,usage_total:{...e.usage_total,credits:t+e.usage_total.credits}}:e:e}function ot(e,t,n){return e.map(s=>{let r=t.find(c=>c.id===s.id);if(r&&r.selected_index!=null&&r.selected_index>=0&&r.selected_index<s.options.length){let o=(s.allow_free_text||s.options[r.selected_index]?.input===!0)&&r.free_text!=null?r.free_text:null;return{id:s.id,resolution:"answered",selected_index:r.selected_index,free_text:o}}return r&&r.free_text!=null&&s.allow_free_text?{id:s.id,resolution:"answered",selected_index:-1,free_text:r.free_text}:n.explicitAcceptDefaults?{id:s.id,resolution:"assumed-default",selected_index:s.recommended_index,flagged:!0}:{id:s.id,resolution:"deferred",selected_index:null}})}function Qt(e){return Number.isInteger(e.recommended_index)&&e.recommended_index>=0&&e.recommended_index<e.options.length}function An(e,t){let n=e.map(s=>s.header?`"${s.header}" (${s.id})`:s.id).join(", ");return`error: ${e.length===1?"a question has":`${e.length} questions have`} no recommended option to take${t?` for ${t}`:""}: ${n} \u2014 nothing was guessed; answer it with --mode agent, or in a terminal`}async function Rn(e,t,n,s,r=()=>{},c){let o=(_,i)=>r(_,i,e.session_id),g=(process.env.ASSURANCE_LOG_LEVEL??"info").toLowerCase()==="debug",u=t.similarity??Pe(),f=u.calls(()=>({env:process.env,auth:t.auth})),a=_=>_.catch(i=>{throw Ue(u,o),i}),d={store:t.store,resolveAlias:_=>a(f.resolveAlias(_)),embed:(_,i)=>a(f.embed(_,i)),...t.onEmbedDegraded?{onDegraded:t.onEmbedDegraded}:{}},m=0,h=t.agent(e,{auth:t.auth,onWarn:_=>{o("warn",_),t.out(_)},onStderr:_=>o("agent_stderr",_)}),w=null,k=null,y,D,v=h.send.bind(h),A=new Set(["user_response","user_message","session_complete"]),G=null,Y=!1,J,Z=[],N=[],E=_=>{if(_.type==="session_complete"&&(Y=!0),_.type==="user_message"&&Le(_.message_id)&&!N.includes(_.message_id)&&N.push(_.message_id),G!==null&&A.has(_.type)){Z.push(_),o("belt_withheld",{type:_.type,unacked_seq:G});return}v(_)};if(e.checkpoints&&!t.checkpoint)throw h.kill(),new Error("run_config.checkpoints is on but DriverDeps.checkpoint sink is absent (programming error)");let ye=!1,ee=t.pendingDeferral??null,B=!1,dt=t.chat?.attachSender?.((_,i)=>{_.type==="user_message"&&i&&(i.by==="person"?o("user_message_sent",{chars:_.text.length,chat:!0,...i.continued?{continued:!0}:{}}):o("kane_message_sent",{chars:_.text.length,kind:i.receipt?"receipt":"repair"})),E(_)}),ft=e.resend_last_output===!0?{checkIn:!1}:void 0;for(let _ of t.heldAtSpawn??[])t.chat?.peekHeldReceipts?.().includes(_)||t.chat?.holdReceipt?.(_,ft);t.readyAtSpawn&&(t.chat?.setWorking?.(null),t.chat?.resumedParked?.(),t.checkInAtSpawn&&t.chat?.restoreCheckIn?.());for(let _ of t.redeliverAtSpawn??[])E({type:"user_message",message_id:_.message_id,text:_.text}),o("user_message_sent",{chars:_.text.length,redelivered:!0});t.initialMessage&&(E({type:"user_message",message_id:`msg-${e.session_id}-${Ut(3).toString("hex")}`,text:t.initialMessage}),o("user_message_sent",{chars:t.initialMessage.length}),t.emit?.({type:"message_sent",sid:e.session_id,chars:t.initialMessage.length}),t.initialMessageUnannounced||t.chat?.note("\u21B3 delivered to the agent")),t.completeAtSpawn&&(E({type:"session_complete"}),o("session_complete_sent",{at_spawn:!0}));let te,F,H=0,Q=0,V=0,ne,$=Ne(),j=t.progress??t.out;try{for await(let _ of h.events){let i=Ht(_,t.creditsBefore);try{t.chat?t.chat.onAgentEvent(i):t.narrate?.(i)}catch(l){o("chat_mirror_error",{event_type:i.type,message:l instanceof Error?l.message:String(l)})}if(i.type==="reasoning_delta"?(m+=i.text.length,process.env.KANE_TRACE_REASONING&&o("reasoning_delta",i.text)):i.type==="state_checkpoint"&&!process.env.KANE_TRACE_REASONING?o("state_checkpoint",{seq:i.seq,items:i.delta_items.length,bytes:JSON.stringify(i.delta_items).length}):o(i.type,i),i.type==="reasoning_done"&&o("reasoning_chars",m),i.type==="turn_retry")t.chat||t.out(ie().text("note.model_retry",{seconds:Math.round(i.wait_s)})),t.emit?.({type:"turn_retry",code:i.code,wait_s:i.wait_s});else if(i.type==="progress")j(`\u2026 ${i.stage}${i.n?` #${i.n}`:""}`),t.emit?.({type:"agent_activity",kind:"progress",label:`${i.stage}${i.n?` #${i.n}`:""}`});else if(i.type==="reasoning_delta"||i.type==="reasoning_done"||i.type==="tool_activity"||i.type==="decision_activity"){t.onStreamEvent?.(i);let l=$;if($=je($,i),$===l)continue;i.type==="reasoning_delta"?$.liveThinking===i.text&&j("\u2237 thinking\u2026"):i.type==="reasoning_done"?i.present&&(j(`thought for ${(i.took_ms/1e3).toFixed(1)}s`),t.emit?.({type:"agent_activity",kind:"thinking_done",label:`thought for ${(i.took_ms/1e3).toFixed(1)}s`})):i.type==="tool_activity"?i.status!=="done"&&(j($.activity[$.activity.length-1].label),t.emit?.({type:"agent_activity",kind:"tool",label:$.activity[$.activity.length-1].label})):(j(`\xB7 ${$.activity[$.activity.length-1].label}`),t.emit?.({type:"agent_activity",kind:"decision",label:$.activity[$.activity.length-1].label}))}else if(i.type==="usage"){ne=i.total_credits;let l=S=>Math.round(S*100)/100;t.emit?.({type:"usage",credits:l(i.credits),total_credits:l(i.total_credits)})}else if(i.type==="graph_query"){let l=await rt(t.graphSlot?.current??s,i.method,i.params??{},d),S=l.ok?{type:"graph_result",id:i.id,ok:!0,result:l.result}:{type:"graph_result",id:i.id,ok:!1,error:l.error};o("graph_result",g?{id:i.id,method:i.method,ok:l.ok,result:l.ok?l.result:l.error}:{id:i.id,method:i.method,ok:l.ok}),E(S)}else if(i.type==="ingest_request")if(t.ingest){let l;try{l=await t.ingest({id:i.id,ref:i.ref,purpose:i.purpose??null})}catch(C){o("ingest_executor_threw",{id:i.id,error:C instanceof Error?C.message:String(C)}),l={ok:!1,error:{code:"INGEST_FAILED",message:"the landing failed \u2014 see the trace for detail"}}}let S=l.ok?{type:"ingest_result",id:i.id,ok:!0,result:l.result}:{type:"ingest_result",id:i.id,ok:!1,error:l.error};o("ingest_result",l.ok?{id:i.id,ok:!0,source_id:l.result.source_id}:{id:i.id,ok:!1,code:l.error.code}),E(S)}else{let l={type:"ingest_result",id:i.id,ok:!1,error:{code:"INGEST_UNAVAILABLE",message:"this session has no ingest executor"}};o("ingest_result",{id:i.id,ok:!1,code:l.error.code}),E(l)}else if(i.type==="state_checkpoint"){if(!t.checkpoint)throw new Error("state_checkpoint arrived with no checkpoint sink (programming error)");G=i.seq;try{for(let l of Ge(i.delta_items)){let S=N.indexOf(l);S>=0&&N.splice(S,1)}for(t.checkpoint.persist(i,{sentUnread:N}),G=null,v({type:"checkpoint_ack",seq:i.seq}),o("checkpoint_acked",{seq:i.seq,at:i.at});Z.length>0&&G===null;)E(Z.shift())}catch(l){let S=l instanceof Error?l.message:String(l);if(!ye){ye=!0;let C=l instanceof Ie||l instanceof Oe||l instanceof $e,re=l instanceof Re&&!C;t.out(ie().text("note.checkpoint_not_saved",{error:S,chain_unverified:re}))}o("checkpoint_persist_failed",{seq:i.seq,message:S}),v({type:"pause"})}}else if(i.type==="session_paused")B=!0,D=i;else if(i.type==="done")B=!0;else if(i.type==="ask_user"){i.text&&(t.chat?t.chat.ledger({kind:"agent",text:i.text}):t.out(i.text),t.emit?.({type:"agent_message",text:i.text}));let l=e.mode;if(ee){let p=ee;ee=null,t.emit?.({type:"ask_deferred",source_id:p.ingested.source_id,cid:p.ingested.cid,questions:i.questions.length}),o("ask_deferred",{source_id:p.ingested.source_id,questions:i.questions.length}),E({type:"user_response",answers:[],deferral:{deferred:!0,ingested:p.ingested}});continue}if(l!=="interactive"){if(l==="agent"){o("pause_requested",{questions:i.questions.map(b=>b.id)}),E({type:"pause"});continue}if(l==="ci"){let b=i.questions.filter(T=>T.risk==="high");if(b.length>0){te=b,h.kill();break}}let p=i.questions.filter(b=>!Qt(b));if(p.length>0){F=p,o("no_default",{questions:p.map(b=>b.id)}),h.kill();break}let R=ot(i.questions,[],{explicitAcceptDefaults:!0});H+=R.length;for(let b of R)o("assumed_default",{id:b.id,resolution:b.resolution}),t.emit?.({type:"assumed_default",id:b.id,selected_index:b.selected_index,risk:i.questions.find(T=>T.id===b.id)?.risk});let z={type:"user_response",answers:R.map(b=>({id:b.id,selected_index:b.resolution==="deferred"?null:b.selected_index,free_text:null}))};E(z);continue}let S=await t.ask(i.questions);if(!Array.isArray(S)&&"paused"in S){o("pause_requested",{questions:i.questions.map(p=>p.id)}),E({type:"pause"});continue}if(!Array.isArray(S)){E({type:"user_response",answers:[],deferral:S});continue}let C=S,re=ot(i.questions,C,{explicitAcceptDefaults:!1}),se=i.questions.map(p=>{let R=C.find(b=>b.id===p.id);if(R?.free_text!=null){let b=R.selected_index!=null&&R.selected_index>=0&&R.selected_index<p.options.length?R.selected_index:null;if(b!=null){let P=p.allow_free_text||p.options[b]?.input===!0;return P&&R.free_text!=null&&n.set(p.id,(n.get(p.id)??0)+1),{id:p.id,selected_index:b,free_text:P?R.free_text:null}}let T=n.get(p.id)??0;if(!p.allow_free_text||T>=Bt){let P=p.options[p.recommended_index]?.label??"recommended option";if(H+=1,t.emit?.({type:"assumed_default",id:p.id,selected_index:p.recommended_index,risk:p.risk}),t.chat?.noteCoercion)t.chat.noteCoercion(p,P);else{let oe=p.text.replace(/\?+\s*$/,""),mt=oe.length<=36?oe:`${oe.slice(0,33)}\u2026`;t.out(`note: couldn't use a typed answer for "${mt}" \u2014 kept the recommended option (${P})`)}return{id:p.id,selected_index:p.recommended_index,free_text:null}}return n.set(p.id,T+1),{id:p.id,selected_index:null,free_text:R.free_text}}let z=re.find(b=>b.id===p.id);return z.resolution==="deferred"?{id:p.id,selected_index:null,free_text:null}:{id:p.id,selected_index:z.selected_index,free_text:null}}),ke=se.filter(p=>p.free_text!=null);o("user_answer_sent",{answers:se.filter(p=>p.selected_index!=null||p.free_text!=null).length,typed:ke.length,chars:ke.reduce((p,R)=>p+(R.free_text?.length??0),0)}),E({type:"user_response",answers:se})}else if(i.type==="chat_ops"&&!t.chat){let l=i.chat_ops??i,S=Array.isArray(l.ops)?l.ops.length:0;if(S===0)l.text&&(t.out(l.text),t.emit?.({type:"agent_message",text:l.text})),J=l.text??"",E({type:"session_complete"}),o("headless_zero_op_chat_turn_complete",{chars:l.text?.length??0});else if(V<Ft)V+=1,E({type:"user_message",message_id:`nochat-${e.session_id}-${V}`,text:"[auto-repair] chat ops are unavailable in this mode \u2014 commit through finalize_design, or finish if nothing remains."}),o("headless_chat_ops_nudge",{n:V,ops:S});else{k="the agent kept trying to hold a conversation in a non-interactive run",t.out("error: the agent kept trying to hold a conversation in a non-interactive run \u2014 session closed; re-run interactively, or retry"),o("headless_chat_ops_terminal",{ops:S}),h.kill();break}}else if(i.type===(c.terminalEventType??"proposal")){let l=await c.onProposalEvent(i[i.type]);if(w=l.proposal,l.error&&(k=l.error),l.fatal){o("proposal_fatal",{error:l.error}),h.kill();break}if(l.receipt)t.emit?.(l.receipt.event),e.mode!=="interactive"?(Q+=1,l.sessionComplete||Q>=st?(l.sessionComplete||(t.out(`warning: ${st} commits without completion \u2014 closing the session (runaway guard)`),o("receipt_runaway_cap",{commits:Q})),E({type:"session_complete"}),o("session_complete_sent",{commit_n:l.receipt.event.commit_n,runaway:!l.sessionComplete})):(E({type:"user_message",message_id:`receipt-${e.session_id}-${String(l.receipt.event.commit_n??0)}`,text:l.receipt.text}),o("receipt_sent",{commit_n:l.receipt.event.commit_n,chars:l.receipt.text.length}))):t.chat?.holdReceipt&&(t.chat.holdReceipt(l.receipt.text),o("receipt_held",{commit_n:l.receipt.event.commit_n}));else if(l.error&&e.mode!=="interactive"){t.out("error: saving the agent's work failed and can't be retried in this mode \u2014 session closed; re-run to retry"),t.emit?.({type:"warning",code:"SAVE_FAILED",message:"saving the agent's work failed and can't be retried in this mode \u2014 session closed; re-run to retry"}),o("headless_commit_error_terminal",{error:l.error}),h.kill();break}}else if(i.type==="error"){B=!0;let l=i;if(l.code==="PAIR_MISMATCH")throw new Ce(l.expected??"",l.actual??"");k=i.message,typeof l.code=="string"&&(y=l.code);let S=i.failed_proposal;S&&o("failed_proposal",S)}}}finally{h.kill(),dt?.()}let gt=e.chat===!0&&e.mode==="interactive",we=!!t.checkpoint&&!B&&!Y&&!D&&!te&&!F&&k===null&&(w===null||Q>0)&&!gt;return{proposal:w,error:k,...y!==void 0?{errorCode:y}:{},paused:D,highRisk:te,...F?{noDefault:F}:{},...H>0?{assumedDefaults:H}:{},...ne!==void 0?{creditsTotal:ne}:{},...we?{crashed:we}:{},...Y?{sentComplete:!0}:{},...J!==void 0?{verdict:J}:{}}}function it(e,t){let n=t.trim(),s=null;for(let r of e??[])if(r.ref===n){if(!r.consumed)return{kind:"unconsumed"};s={kind:"consumed",identity:r.consumed}}return s??{kind:"unauthorized"}}function In(e,t,n){let s=t.trim(),r=[...e??[]];return r.find(o=>o.ref===s&&!o.consumed)||r.push({ref:s,entered_at:n.toISOString()}),r}function ct(e,t,n){let s=t.trim(),r=[...e??[]],c=r.findIndex(u=>u.ref===s&&!u.consumed);if(c<0)return r;let{landing:o,...g}=r[c];return r[c]={...g,consumed:n},r}import{createHash as Vt}from"crypto";import{basename as q}from"path";function at(e,t,n,s,r){let c=t.mediaOf(s),o=0;if(c.format!=="image"){let g=U(e,t,s);g&&(o=g.toString("utf8").replace(/\n$/,"").split(`
|
|
8
|
-
`).length)}return{source_id:n,cid:s,total_lines:o,media_type:c.format,status:r}}var zt="new version of a known source \u2014 its changes await your review (reconcile), never a blind re-extraction";function ut(e,t,n){return n?{source_id:e,cid:t,status:"skipped",note:zt}:{source_id:e,cid:t,status:"pending"}}function Kt(e,t){return`${e}:ingest:${Vt("sha256").update(`${t.ref}\0${t.entered_at}`).digest("hex").slice(0,16)}`}function Wt(e,t){let n=0;return new Proxy(e,{get(s,r){if(r==="append")return(o,g)=>{let u=n===0?t:`${t}.${n}`;return n+=1,s.append({...o,event_ids:[...o.event_ids??[],u]},g)};let c=Reflect.get(s,r);return typeof c=="function"?c.bind(s):c}})}function Xt(e,t){let n=new Set;for(let s of e){let r=s.source_head_moves??{};if(s.event_ids?.includes(t)){let[c,o]=Object.entries(r)[0]??[];return c&&o?{source_id:c,cid:o,versioned:n.has(c)}:null}for(let c of Object.keys(r))n.add(c)}return null}function lt(e,t,n){let s=e.state.ingest_registry??[];if(!s.some(g=>g.landing))return;let r=t.recordsSince(null),c=[...e.state.ingest_schedule??[]],o=s.map(g=>{if(!g.landing)return g;let{landing:u,...f}=g,a=Xt(r,u.event_id);return a?(n&&!c.some(d=>d.source_id===a.source_id&&d.cid===a.cid)&&c.push(ut(a.source_id,a.cid,a.versioned)),{...f,consumed:{source_id:a.source_id,cid:a.cid}}):f});e.save({ingest_registry:o,...n?{ingest_schedule:c}:{}})}function Pn(e){return lt(e.handle,e.store,!!e.schedule),async t=>{lt(e.handle,e.store,!!e.schedule);let n=it(e.handle.state.ingest_registry,t.ref);if(n.kind==="unauthorized")return{ok:!1,error:{code:"INGEST_UNAUTHORIZED_REF",message:"that ref was not provided by the owner this session \u2014 only owner-provided refs may land"}};if(n.kind==="consumed"){let y=e.graphSlot?.current??L(e.store);return{ok:!0,result:at(e.store,y,n.identity.source_id,n.identity.cid,"unchanged")}}let s=[],r={out:y=>s.push(y),err:y=>s.push(y),confirm:async()=>!1,isTTY:!1},c=(e.handle.state.ingest_registry??[]).find(y=>y.ref===t.ref.trim()&&!y.consumed),o=c?Kt(e.handle.state.sid,c):null;c&&o&&e.handle.save({ingest_registry:(e.handle.state.ingest_registry??[]).map(y=>y===c?{...y,landing:{event_id:o}}:y)});let g=()=>{c&&e.handle.save({ingest_registry:(e.handle.state.ingest_registry??[]).map(y=>{if(y.ref!==c.ref||y.consumed)return y;let{landing:D,...v}=y;return v})})},u;try{u=await Te({store:o?Wt(e.store,o):e.store,refs:[t.ref],io:r,credentials:e.credentials,converters:e.converters??{pdf:Me,docx:De},remoteDeps:e.remoteDeps,onRefusal:e.onRefusal,...e.connections?{connections:e.connections}:{}})}catch(y){return g(),{ok:!1,error:{code:"INGEST_FAILED",message:y instanceof Error?y.message:String(y)}}}if(u.code!==0||u.results.length===0)return g(),{ok:!1,error:{code:"INGEST_FAILED",message:s.find(D=>D.startsWith("error:"))??s.at(-1)??"the landing failed"}};let f=u.results[0],a={source_id:f.source_id,cid:f.source_cid},d=ct(e.handle.state.ingest_registry,t.ref,a),m=f.status==="versioned"&&e.schedule,h=e.schedule?[...e.handle.state.ingest_schedule??[],ut(f.source_id,f.source_cid,!!m)]:void 0;e.handle.save({ingest_registry:d,...h!==void 0?{ingest_schedule:h}:{}}),e.graphSlot&&(e.graphSlot.current=L(e.store));let w=e.graphSlot?.current??L(e.store),k=at(e.store,w,f.source_id,f.source_cid,f.status==="unchanged"?"unchanged":"landed");return e.note(m?`landed ${f.source_id} (${q(t.ref)}) \u2014 ${k.total_lines} lines; a NEW VERSION of a known source \u2014 its changes await your review (the check-in offers it), not a blind re-extraction`:e.schedule?`landed ${f.source_id} (${q(t.ref)}) \u2014 ${k.total_lines} lines; scheduled for extraction in this run`:e.scheduleRefused?`landed ${f.source_id} (${q(t.ref)}) \u2014 ${k.total_lines} lines; ${e.scheduleRefused}`:`landed ${f.source_id} (${q(t.ref)}) \u2014 ${k.total_lines} lines; it guides this design only (not extracted \u2014 its own extraction pass adds its use-cases)`),{ok:!0,result:k}}}var Bn={ended:"failed",code:"AGENT_CRASHED"};function Fn(e){let t,n;return{emit:s=>{let r=s.code;s.type==="error"&&typeof r=="string"&&(t=r),e?.(s)},recorded(){n=t??n,t=void 0},failed:()=>({ended:"failed",code:t??"RUN_FAILED"}),failedRecorded:()=>({ended:"failed",code:n??t??"RUN_FAILED"})}}import{createHash as qt}from"crypto";function Vn(e){let t=n=>Array.isArray(n)?n.map(t):n!==null&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(s=>[s,t(n[s])])):n;return"sha256:"+qt("sha256").update(JSON.stringify(t(e))).digest("hex")}var Yt={kind:"system",id:"distiller"};function qn(e,t=Ee){try{let n=L(e),{watermark:s}=e.signals().snapshot(),r=Be({store:e,graph:n,watermark:s,by:Yt});if(r.errors){let c=r.errors.map(o=>`${o.code}: ${o.detail}`).join("; ");return t(`warning: style-note distill skipped \u2014 ${c}`),{minted:0,error:c}}return{minted:r.minted,error:null}}catch(n){let s=n instanceof Error?n.message:String(n);return t(`warning: style-note distill skipped \u2014 ${s}`),{minted:0,error:s}}}function Jn(e,t){let n={archived:[],replaced:[]};for(let s of t.nodes){let r=e.displayNameOf(s.cid)??s.cid;e.tipOf(s.cid)!==s.cid?n.replaced.push(r):e.trust.get(s.cid)==="archived"&&n.archived.push(r)}return n}var _e=e=>e.archived.length+e.replaced.length;function Zn(e,t){if(_e(t)===0)return`already saved \u2014 this ${e} is the one committed before`;let n=[...t.archived.length?[`${t.archived.join(", ")} ${t.archived.length===1?"was":"were"} archived`]:[],...t.replaced.length?[`${t.replaced.join(", ")} ${t.replaced.length===1?"was":"were"} replaced by an edit`]:[]],s=_e(t)===1?"it":"them";return`nothing saved again \u2014 this ${e} was saved earlier, and since then ${n.join(" and ")}; the agent is told how to restore ${s}`}function er(e){return`NOTHING COMMITTED: this content was committed before. ${[...e.archived.length?[`archived since: ${e.archived.join(", ")} \u2014 approve them to restore them`]:[],...e.replaced.length?[`replaced by an edit since: ${e.replaced.join(", ")} \u2014 edit them back to restore them`]:[]].join("; ")}. Sending the same content again commits nothing.`}function tr(e){return _e(e)>0}export{Zt as a,en as b,nn as c,Qe as d,rt as e,Bt as f,ot as g,An as h,Rn as i,In as j,Pn as k,Bn as l,Fn as m,Vn as n,qn as o,Jn as p,Zn as q,er as r,tr as s};
|
package/dist/chunk-6SD4XTYC.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{c as y,e as k}from"./chunk-CB344EDO.js";import{spawn as A}from"child_process";var S=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","impact","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint","turn_retry"]),M=5e3,E=new Set(["done","session_paused","error"]);function R(u,t={}){let a=t.spawnCmd!==void 0?t.spawnCmd:y();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 h=u.source.images?.length??0;a.tier==="dev-python"&&h>0&&t.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let n=A(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:k(u.session_id,t.auth)});if(n.stdin.on("error",e=>{e.code!=="EPIPE"&&t.onWarn?.(`agent stdin: ${e.message}`)}),n.stdin.write(JSON.stringify(u)+`
|
|
3
|
-
`),n.stdout.setEncoding("utf8"),n.stderr.setEncoding("utf8"),t.onStderr){let e="";n.stderr.on("data",r=>{e+=r;let i;for(;(i=e.indexOf(`
|
|
4
|
-
`))>=0;){let o=e.slice(0,i);e=e.slice(i+1),o.trim()&&t.onStderr(o)}})}let g=!1,d=new Promise(e=>{n.on("exit",(r,i)=>{g=!0,e({code:r,signal:i})})}),p=null,f=()=>(p??=(async()=>{if(g||n.pid===void 0)return;n.kill("SIGTERM");let e=setTimeout(()=>{g||n.kill("SIGKILL")},t.killGraceMs??M);e.unref?.(),await d,clearTimeout(e)})(),p),l,v=()=>{l===void 0&&(l=setTimeout(()=>{f()},t.killGraceMs??M),l.unref?.())};d.then(()=>clearTimeout(l));async function*w(){let e="",r=!1;for await(let i of n.stdout){e+=i;let o;for(;(o=e.indexOf(`
|
|
5
|
-
`))>=0;){let c=e.slice(0,o).trim();if(e=e.slice(o+1),!c)continue;let m;try{m=JSON.parse(c)}catch{t.onWarn?.(`agent: skipping malformed line: ${c.slice(0,120)}`);continue}let s=m;if(!s||typeof s!="object"||!S.has(s.type)){t.onWarn?.(`agent: skipping unknown event type "${s&&typeof s=="object"?String(s.type??"?"):"?"}"`);continue}if(E.has(s.type)&&v(),yield s,s.type==="done"){r=!0;break}}if(r)break}await d.catch(()=>{})}return{events:w(),send:e=>{n.stdin&&!n.stdin.destroyed&&n.stdin.write(JSON.stringify(e)+`
|
|
6
|
-
`)},kill:f,exited:d,...n.pid!==void 0?{pid:n.pid}:{}}}export{M as a,R as b};
|
package/dist/chunk-7YV2FCN4.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as O}from"./chunk-QSCXXNC2.js";import{a as k,b as P}from"./chunk-6PIIUAZF.js";import{b as A}from"./chunk-VO66KP2W.js";import{n as L}from"./chunk-G4K3TP2I.js";import{a as b,b as R,c as x,d as y,e as T,g as I,h as f}from"./chunk-UJLULWSR.js";import{d as w,g as p}from"./chunk-ZCRZFAOT.js";import{a as v}from"./chunk-RZ4F3BHX.js";import{a as m,i as S}from"./chunk-J4FIESTB.js";var h=class{config;buffer=[];stepBuffer=new Map;flushTimer=null;currentRunIndex=null;stopped=!1;_inFlightFlush=null;_stoppingFast=!1;_droppedBatches=0;_droppedEntries=0;constructor(e){this.config=e}start(){if(this.flushTimer)return;let e=this.config.flushIntervalMs??5e3;this.flushTimer=setInterval(()=>{this.flush().catch(()=>{})},e),this.flushTimer.unref&&this.flushTimer.unref()}setRunIndex(e){this.currentRunIndex=e}log(e,t,n,s={}){if(this.stopped)return;let o=this.buildEntry(e,t,n,s);this.buffer.push(o)}logStep(e,t,n,s={}){if(this.stopped)return;let o=this.buildEntry("debug",t,n,s);o.run_index=e,this.stepBuffer.has(e)||this.stepBuffer.set(e,[]),this.stepBuffer.get(e).push(o)}escalate(e){let t=this.stepBuffer.get(e);t&&t.length>0&&this.buffer.push(...t),this.stepBuffer.delete(e)}discardSteps(e){this.stepBuffer.delete(e)}async flush(){if(this.buffer.length===0)return;let e=this._flushBody();this._inFlightFlush=e;try{await e}finally{this._inFlightFlush===e&&(this._inFlightFlush=null)}}async _flushBody(){let e=this.buffer.splice(0),t=null;try{t=await this.config.getToken()}catch{this.buffer.unshift(...e);return}let n={"Content-Type":"application/json"};t&&(n.Authorization=`Bearer ${t}`);let s=JSON.stringify(e);for(let o=0;o<3;o++){try{let l=new AbortController,a=setTimeout(()=>l.abort(),1e4),c=await v(this.config.proxyUrl,{method:"POST",headers:n,body:s,signal:l.signal});if(clearTimeout(a),c.ok)return}catch{}if(this._stoppingFast){this.buffer.unshift(...e);return}o<2&&await new Promise(l=>setTimeout(l,1e3*Math.pow(2,o)))}this._droppedBatches++,this._droppedEntries+=e.length}async flushOnce(e){if(this.buffer.length===0)return"empty";let t=this.buffer.splice(0),n=Date.now()+e,s=!1,o,l=null;try{l=await Promise.race([this.config.getToken(),new Promise(d=>{o=setTimeout(()=>{s=!0,d(null)},e),o.unref&&o.unref()})])}catch{l=null}finally{o&&clearTimeout(o)}let a=n-Date.now();if(s||a<=0)return this.buffer.unshift(...t),"timeout";let c={"Content-Type":"application/json"};l&&(c.Authorization=`Bearer ${l}`);try{let d=new AbortController,u=setTimeout(()=>d.abort(),a);u.unref&&u.unref();let r=await v(this.config.proxyUrl,{method:"POST",headers:c,body:JSON.stringify(t),signal:d.signal});return clearTimeout(u),r.ok?"sent":(this.buffer.unshift(...t),"failed")}catch{return this.buffer.unshift(...t),Date.now()>=n?"timeout":"failed"}}async stopAndFlushOnce(e){let t=Date.now()+e;this._stoppingFast=!0,this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null);let n=this._inFlightFlush;if(n){let o;await Promise.race([n.catch(()=>{}),new Promise(l=>{o=setTimeout(l,e),o.unref&&o.unref()})]),o&&clearTimeout(o)}if(this.buffer.length===0)return"empty";let s=t-Date.now();if(s<=0)return"timeout";try{return await this.flushOnce(s)}catch{return"failed"}}drainBuffer(){return this.buffer.splice(0)}get droppedBatches(){return this._droppedBatches}get droppedEntries(){return this._droppedEntries}async shutdown(){this._droppedBatches>0&&this.log("warn","LOG_DROPS",`Dropped ${this._droppedEntries} entries in ${this._droppedBatches} batches`,{dropped_batches:this._droppedBatches,dropped_entries:this._droppedEntries}),this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush()}shutdownSync(){this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}get bufferSize(){return this.buffer.length}stepBufferSize(e){return this.stepBuffer.get(e)?.length??0}buildEntry(e,t,n,s){return{hostname:"kane-cli",service:"kane-cli",ddsource:"kane-cli",ddtags:`version:${this.config.device.cli_version}`,level:e,event:t,message:n,session_id:this.config.sessionId,run_index:t.startsWith("tcg_")?null:this.currentRunIndex,identity:this.config.identity,device:this.config.device,context:s,timestamp:new Date().toISOString()}}};import{platform as $,arch as V}from"os";import M from"fs";import B from"fs";import U from"path";var F=1e3,_=0,j=new Set([130,3]),g=class i{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,t={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=t}get enabled(){return this.logger!==null}event(e,t={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let n=y(this.ids,e,t);this.logger.log(x[e],e,e,C(n))}error(e,t={}){this.logger&&(this.logger.escalate(_),this.event("ASR_ERROR",{...t,error_code:e}))}child(e,t){return new i({...this.opts,envelope:{...this.ids,operation_id:t,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:t}=await import("./store-id-YZ5WKJ25.js"),{ids:n,cloned:s}=t(e,p());this.ids.context_lineage_id=n.context_lineage_id,this.ids.context_instance_id=n.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}spoolError(e,t={}){this.logger&&(this.event("ASR_ERROR",{...t,error_code:e}),T(this.logger.drainBuffer()))}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 t=typeof e.kind=="string"?e.kind.slice(0,64):"trace",n={...C(y(this.ids,"ASR_CMD_START",{})),trace_kind:t};typeof e.code=="string"&&(n.trace_code=e.code.slice(0,64)),delete n.event,this.logger.logStep(_,`trace_${t}`,t,n)}}wireTrace(e,t,n){if(!this.logger)return;n&&this.agentSession(n);let s=t&&typeof t=="object"?t:{};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;case"design_phase_committed":this.event("ASR_COMMIT",{phase:s.phase,duration_ms:s.ms});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(_):this.logger.escalate(_),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 t=await this.logger.flushOnce(F);(t==="failed"||t==="timeout")&&T(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),f(null)}}writeManifestLine(e){try{let t=w(this.ids.context_instance_id??null);B.mkdirSync(U.dirname(t),{recursive:!0});let n={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};B.appendFileSync(t,JSON.stringify(n)+`
|
|
3
|
-
`,{flag:"a",mode:384})}catch{}}};function C(i){let e={event:i.event,session_id:i.session_id,operation_id:i.operation_id,verb:i.verb,mode:i.mode,component:i.component,seq:i.seq,context_lineage_id:i.context_lineage_id,context_instance_id:i.context_instance_id};i.parent_operation_id&&(e.parent_operation_id=i.parent_operation_id),i.agent_session_id&&(e.agent_session_id=i.agent_session_id),i.lattice_session_id&&(e.lattice_session_id=i.lattice_session_id),i.project_id&&(e.project_id=i.project_id);for(let[t,n]of Object.entries(i.context))e[t]=n;return e}import{isMainThread as X}from"worker_threads";var E=()=>process.env.KANE_TELEMETRY_URL||S;function Y(){return process.env.TESTMUAI_BASE_URL?"custom":process.env.TESTMUAI_ENV==="stage"?"stage":"prod"}function z(){return process.env.KANE_TELEMETRY!=="0"&&(!process.env.VITEST||process.env.KANE_TELEMETRY==="1")}function me(i){let e=z(),t=i.env??Y(),n=i.sessionId??null;if(!n&&i.resumeSid&&i.contextRoot)try{let r=L(i.contextRoot,i.resumeSid);r?.user_session_id&&(n=r.user_session_id)}catch{}if(!n&&i.applyPlanPath)try{let r=JSON.parse(M.readFileSync(i.applyPlanPath,"utf8"));r.telemetry?.user_session_id&&(n=r.telemetry.user_session_id)}catch{}let s=i.sessionId===void 0?n!==null:i.resumeSid!==void 0;n||(n=b());let o=null,l=null,a=!1;if(i.contextRoot&&M.existsSync(i.contextRoot))if(i.write&&e){let r=P(i.contextRoot,p());o=r.ids.context_lineage_id,l=r.ids.context_instance_id,a=r.cloned}else{let r=k(i.contextRoot);o=r?.context_lineage_id??null,l=r?.context_instance_id??null}let c={session_id:n,operation_id:R(),context_lineage_id:o,context_instance_id:l,...i.remote?{lattice_session_id:i.remote.sessionId,project_id:i.remote.projectId}:{},verb:i.verb,mode:i.mode,component:"kane-cli"},d=null;if(e){let r=A(t),N={org_id:r.org_id??"",user_id:r.user_id??"",machine_id:r.machine_id,email:null,email_domain:"",user_type:r.user_type??"unknown",env:r.env,plan:r.plan??"unknown"},D=i.mode==="interactive"||i.mode==="cli"?"cli":"agent";d=new h({proxyUrl:E(),sessionId:n,identity:N,device:{cli_version:m,platform:$(),arch:V(),host_agent:O(),invocation_mode:D},getToken:async()=>null}),i.longSession&&d.start()}let u=new g({envelope:c,logger:d,longSession:!!i.longSession,proxyUrl:E(),clientVersion:`kane-cli/${m}`,telemetryEnabled:e});return e&&!i.errorsOnly&&(f(c),u.event("ASR_CMD_START",{resumed:s,applied_plan:!!i.applyPlanPath}),a&&u.event("ASR_CONTEXT_CLONED"),X&&I(E()).catch(()=>{})),u}export{h as a,F as b,E as c,Y as d,z as e,me as f};
|
package/dist/chunk-A2DODRHG.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{d as G,f as K,h as j}from"./chunk-2TK4MDF2.js";import{a as q,b as z,d as V,e as H}from"./chunk-KL7XFNSD.js";import{a as J,b as y,c as Q}from"./chunk-LPJKNX6D.js";import{a as N,b as L,c as O}from"./chunk-RNHSULQM.js";import{d as B,f as $}from"./chunk-C4KAPGBS.js";import{a as E}from"./chunk-MMBBQ4OZ.js";import{b as R,c as I,j as U}from"./chunk-NRAPCFI2.js";import{a as F}from"./chunk-TZXXJWHA.js";import{e as S}from"./chunk-Z7S3IWUX.js";import{n as h}from"./chunk-UJLULWSR.js";import{b as _,r as C,s as P}from"./chunk-A7RJQJNT.js";function W(e){return e.kind==="simulator"?e.id:e.virtualName??e.id}function X(e,r,o={}){let t={platform:e.platform,udid:e.id,target:e.kind};return r&&(t.app_package=r),o.noReset!==void 0&&(t.no_reset=o.noReset),o.appiumUrl&&(t.appium_url=o.appiumUrl),e.platform==="android"&&o.autoGrantPermissions!==void 0&&(t.auto_grant_permissions=o.autoGrantPermissions),e.platform==="ios"&&o.autoAcceptAlerts!==void 0&&(t.auto_accept_alerts=o.autoAcceptAlerts),t}function Y(e=process.env){let r=e.KANE_APPIUM_URL?.trim();return r||null}function m(e){return`${e.platform}|${W(e)}`}var g=new Map,Z=new Set;function ee(e){return Z.has(m(e))}function ye(e,r,o){r.state==="stopped"&&(g.has(m(r))||oe(e,r,o))}async function re(e,r,o){let t=g.get(m(r));return t?(o?.(`waiting for ${r.displayName} to finish booting\u2026`),t):oe(e,r,o)}function oe(e,r,o){let t=m(r),a=e.prepare(r,o);g.set(t,a),r.state==="stopped"&&a.then(()=>Z.add(t),()=>{});let n=()=>{g.get(t)===a&&g.delete(t)};return a.then(n,n),a.catch(()=>{}),a}import{basename as le}from"path";import{spawnSync as pe}from"child_process";async function de(e,r,o){if(!e.teardownPlan||!o.appPackage&&!o.shutdown)return;let t;try{t=await e.teardownPlan(r,o)}catch{return}t.length!==0&&h(`device:${r.id}`,()=>{G({udid:r.id,displayName:r.displayName});for(let a of t)try{pe(a.file,a.args,{timeout:3e4,stdio:"ignore"})}catch{}})}var te={emulator:[".apk"],simulator:[".zip"]};async function ce(e,r,o,t){if(e.kind==="package")return e;if(e.kind==="app_id"){let a=r.cloudUpload;if(!a)throw new Error(`${e.value} is an app id, which needs an account to download it. Log in, or pass a path to a local build instead.`);let n=await Q({appId:e.value,baseUrl:a.baseUrl,auth:a.auth,...te[o]?{accepts:te[o]}:{},...t?{onProgress:t}:{}}),s=x(n.path);if(!s||s.kind==="app_id")throw new Error(`${n.name} is not a build this CLI can install (from ${e.value}).`);return s}try{let a=new q,n=await V(e.value,a),s=new J;await s.find(n)||t?.(`copying ${le(e.value)} into the local app store\u2026`);let i=await s.put({key:n,sourcePath:e.value,source:"local"});return{...e,value:i.path}}catch{return e}}function ue(e){h(`appium:${e}`,()=>{j({deviceClass:e,owner:process.pid})})}var k=class extends Error{constructor(r){super(r),this.name="MobileHostUnsupportedError"}},v=class extends Error{constructor(o,t){super(o);this.doctorText=t;this.name="MobilePreflightError"}};async function ge(e,r,o){let t=o.cloudUpload,a=await H({path:e,type:r,env:t.env,orgId:t.orgId,userId:t.userId,auth:t.auth,baseUrl:t.baseUrl,...o.onProgress?{onProgress:o.onProgress}:{}});if(z(a)){o.onProgress?.(`app not uploaded \u2014 ${a.reason}`);return}return a.appId}var fe="app must be a build (.apk for an emulator, .zip of the .app bundle for a simulator) or an app id from your cloud uploads \u2014 a package id names something already installed on one device, so it cannot be uploaded, exported as code, or run anywhere else.",ae=C(_);function x(e){let r=e.trim();if(y(r))return{kind:"app_id",value:r};let o=P(r,ae);return o?{kind:o.slice(1),value:r}:null}function me(e){return!!e&&(P(e,ae)!==void 0||y(e.trim()))}function ve(e){return e.filter(r=>r.required&&r.status==="fail")}function be(e,r){return!!r&&S(e,r)}async function Ke(e){let r=F();if(!r.supported)throw new k(r.reason);let o=Y()??e.appiumUrl??e.defaults?.appium_url,t=!!(e.agent||!e.interactive),a=U(),n=!!E();t&&e.platform?.toLowerCase()!=="ios"&&!n&&((await a.status("emulator")).installed||await a.ensure("emulator",{automatic:!0,onProgress:e.onProgress}));let s=await N(e.platform,{appiumUrl:o});if(O(s)){let l=s.sections.flatMap(w=>ve(w.checks)).map(w=>w.label).join(", ");throw new v(`Mobile toolchain not ready (${l}). Run \`kane-cli doctor --target ${e.platform?.toLowerCase()==="ios"?"simulator":e.platform?.toLowerCase()==="android"?"emulator":"<emulator|simulator>"}\` for details.`,L(s))}let p=await $({device:e.device,platform:e.platform,defaultTarget:e.defaults?.default_target,interactive:e.interactive}),i;if(p.ok)i=p.target;else if(p.reason==="needs-picker"&&e.pickTarget){let l=await e.pickTarget(p.candidates);if(!l)throw new Error("Target selection cancelled");i=l}else throw new Error(p.message);let u=B(i.platform);if(!u)throw new Error(`No provider for platform "${i.platform}"`);let d=R(i);if(!d)throw new Error(`No managed dependencies serve ${i.platform} ${i.kind} targets yet.`);if(!(n&&i.platform.toLowerCase()==="android"))try{await a.ensure(d,{automatic:t,onProgress:e.onProgress})}catch(l){throw l instanceof I?new v(l.message,l.message):l}let ie=i.state!=="ready"||ee(i);i=await re(u,i,e.onProgress);let ne=await K(d,{...o?{appiumUrl:o}:{},device:{udid:i.id,displayName:i.displayName},onProgress:e.onProgress});ue(d);let D=be(i,e.defaults?.default_target)?e.defaults?.default_app:void 0,f=e.app??(me(D)?D:void 0);if(e.app&&!x(e.app))throw new Error(`${e.app}: ${fe}`);let c=f?x(f):null,M=c?await ce(c,e,d,e.onProgress):null,b=M?await u.ensureApp(i,M,e.onProgress):void 0,T=c?.kind==="app_id"?c.value:e.cloudUpload&&c&&f?await ge(c.value,d,e):void 0;await de(u,i,{shutdown:ie,...b?{appPackage:b}:{}});let se=X(i,b,{noReset:e.noReset??e.defaults?.no_reset,appiumUrl:ne.url,autoGrantPermissions:e.defaults?.auto_grant_permissions,autoAcceptAlerts:e.defaults?.auto_accept_alerts}),A=T??f;return{device:se,target:i,provider:u,...T?{appId:T}:{},...A?{appRef:A}:{}}}export{W as a,X as b,ye as c,re as d,k as e,v as f,fe as g,x as h,me as i,Ke as j};
|
package/dist/chunk-BJO6J5X2.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as h}from"./chunk-72KYMWQ5.js";import{a as m}from"./chunk-CCOD4GQJ.js";import{a as d}from"./chunk-JQ64X2TO.js";import{a as p}from"./chunk-3G2LSTK5.js";import{a as V}from"./chunk-4IEQNX7F.js";import{a as y}from"./chunk-ZCBOHWN3.js";import{a as g}from"./chunk-4QTH7VYE.js";import{a as c}from"./chunk-RZ4F3BHX.js";var u=class{constructor(e){this.baseUrl=e}async pushSecret(e){let s=g(e.username,e.accessKey),n=await c(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:e.secretKey,secretValue:e.secretValue,orgId:e.orgId,username:e.username,scope:"user",type:"user",accessKey:e.accessKey})});if(!n.ok)throw new Error(`Push secret failed: ${n.status} ${await n.text()}`)}static extractVariableKeys(e){let s=e.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),n=new Set;for(let t of s)n.add(t[1]);return[...n]}};var f=class extends p{constructor(e,s,n){super(e,{username:s,accessKey:n})}async upsertVariable(e){let s=e.environmentId??0,n=await c(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:e.name,value:String(e.value),type:"variable",value_type:"string",is_persist:e.isPersist??!1,environment_id:s})});if(n.ok){let o=await n.json().catch(()=>({}));if(o.type==="Success"&&o.id!=null)return{id:Number(o.id)||0}}let t=await c(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${s}`,{method:"GET",headers:this.headers()});if(!t.ok)return{id:0};let i=(await t.json().catch(()=>({}))).data?.id;return i==null?{id:0}:(await c(`${this.baseUrl}/v1/variables/${i}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(e.value),value_type:"string"})})).ok?{id:Number(i)||0}:{id:0}}};import{readdirSync as P,readFileSync as E,existsSync as S}from"fs";import{join as A}from"path";function b(r,e){let s=e.type==="parameter";return{value:typeof e.value=="number"?String(e.value):e.value,secret:e.secret??!1,syntax:e.syntax??(s?"${"+r+"}":`{{${r}}}`),...typeof e.type=="string"?{type:e.type}:{},...typeof e.description=="string"?{description:e.description}:{}}}function v(r,e){if(!S(r))return{};let s={},n;try{n=P(r).filter(t=>t.endsWith(".json")).sort()}catch{return{}}for(let t of n)try{let a=E(A(r,t),"utf-8"),i=JSON.parse(a);if(i&&typeof i=="object")for(let[l,o]of Object.entries(i))o&&typeof o=="object"&&"value"in o&&(s[l]=b(l,o))}catch{e?e("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:t}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${t}
|
|
3
|
-
`)}return s}function R(r){if(!S(r))throw new Error(`Variables file not found: ${r}`);let e=E(r,"utf-8"),s=V(e,r),n={};if(s&&typeof s=="object")for(let[t,a]of Object.entries(s))a&&typeof a=="object"&&"value"in a&&(n[t]=b(t,a));return n}function w(r){let e;try{e=JSON.parse(r)}catch{throw new Error("Invalid --variables JSON")}let s={};if(e&&typeof e=="object")for(let[n,t]of Object.entries(e))t&&typeof t=="object"&&"value"in t&&(s[n]=b(n,t));return s}function j(r,e,s){let n=v(r,s),t=v(e,s);return{...n,...t}}function G(r,e){if(Object.keys(r).length===0)return{};let s={};for(let[n,t]of Object.entries(r)){let a=t.syntax??`{{${n}}}`;k(e,a)&&(s[n]=t)}return s}function I(r){let e=r.trim();return e.startsWith("{{")&&e.endsWith("}}")?e.slice(2,-2).trim():e.startsWith("${")&&e.endsWith("}")?e.slice(2,-1).trim():e}function k(r,e){if(!e||!r)return!1;if(r.includes(e))return!0;let s=I(e);if(!s)return!1;let n=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:\\{\\{|\\$\\{)\\s*${n}(?=\\s*\\}|[.\\[])`).test(r)}function M(r){let e=j(r.globalDir,r.localDir,r.onLoadError),s=r.file?R(r.file):{},n=r.inline?w(r.inline):{},t={...e,...s,...n,...r.parameters??{}},a=Object.keys(t).length>0,{variables:i,objective:l}=a?h(t,r.objective):{variables:{},objective:r.objective},o=_(t);return m(o.secretEntries.map(([,x])=>x.value)),{raw:t,auteur:i,auteurObjective:l,...o}}function _(r){let e=Object.entries(r),s=e.filter(([,t])=>d(t)),n=e.filter(([,t])=>!d(t));return{secretEntries:n.filter(([,t])=>t.secret),nonSecretEntries:n.filter(([,t])=>!t.secret),parameterEntries:s}}async function Q(r){if(r.localMode)return{};let e=y(r.env);if(r.variables.secretEntries.length>0){let n=new u(e.secretsBaseUrl);for(let[t,a]of r.variables.secretEntries)n.pushSecret({secretKey:t,secretValue:a.value,username:r.auth.username,accessKey:r.auth.access_key,orgId:r.orgId}).then(()=>r.log("info","SECRET_PUSH_OK","Secret pushed",{key:t})).catch(i=>r.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:t,error:String(i)}))}let s={};if(r.variables.nonSecretEntries.length>0){let n=new f(e.tmsBaseUrl,r.auth.username,r.auth.access_key);for(let[t,a]of r.variables.nonSecretEntries)try{let i=await n.upsertVariable({name:t,value:a.value});s[t]=i.id,r.log("info","VAR_PUSH_OK","Variable pushed",{name:t,id:i.id})}catch(i){r.log("error","VAR_PUSH_FAILED","Variable push failed",{name:t,error:String(i)})}}return s}export{u as a,f as b,G as c,M as d,_ as e,Q as f};
|
package/dist/chunk-DIOK3SER.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{c as C,d as P}from"./chunk-OCVDMZWB.js";import{d as I}from"./chunk-F2F257PU.js";import{e as x}from"./chunk-5D7ENQTQ.js";import{b,e as R}from"./chunk-KL7XFNSD.js";import{f as D,h as S,l as E}from"./chunk-KQ4XKTIZ.js";import{b as _,c as N,g as k,h as A}from"./chunk-WLEWXE6L.js";import{b as h}from"./chunk-LPJKNX6D.js";import{a as v}from"./chunk-ZCBOHWN3.js";import{h as w}from"./chunk-A7RJQJNT.js";import{mkdirSync as q,writeFileSync as z}from"fs";import{join as J}from"path";function $(e,t=process.env){return t.KANE_MOBILE_APP_BASE_URL||v(e).mobileAppBaseUrl}var G="device-config.json",T=new WeakMap;function X(e,t){let r=T.get(e)??new Map;T.set(e,r);let n=JSON.stringify([t.path,t.type,t.env,t.orgId]),o=r.get(n);if(o)return o;let i=e(t).finally(()=>r.delete(n));return r.set(n,i),i}function U(e){return e.startsWith("lt://")?e:`lt://${e}`}async function Y(e,t){let r=await E(e.env,e.platform,{...e.selection.deviceName?{deviceName:e.selection.deviceName.value}:{},...e.selection.osVersion?{osVersion:e.selection.osVersion.value}:{}},t);if(r.kind==="unchecked"&&e.onWarning?.(`${r.reason} \u2014 the run continues, but the device and OS version are not checked before the session is requested.`),r.kind==="refused")throw new Error(r.detail)}async function Q(e,t){let r=e.selection.app.value.trim();if(h(r))return U(r);let n=e.credentials;if(!n?.orgId)throw new Error(`${r} has to be uploaded before it can run on a real device, but your account's org id was not found. Run kane-cli login, or set app: to an app ID from \`kane-cli apps list --target ${e.platform}\`.`);let o=await X(t,{path:r,type:e.platform,env:e.env,orgId:n.orgId,userId:n.userId??"",auth:{username:n.username,accessKey:n.accessKey,orgId:n.orgId},baseUrl:$(e.env),...e.onProgress?{onProgress:e.onProgress}:{}});if(b(o))throw new Error(`could not upload ${r} for this real-device run: ${o.reason}`);return U(o.appUrl??o.appId)}async function V(e,t={}){if(!e.credentials)throw new Error("a real-device run needs your TestMu AI username and access key, and none were found. Run kane-cli login, or pass --username and --access-key.");await Y(e,t.fetchCatalog??S);let r=await Q(e,t.upload??R),{deviceName:n,osVersion:o}=e.selection,i={platform_name:e.platform,device_name:n?.value??D,...o?{platform_version:o.value}:{},app:r,...e.testName?{test_name:e.testName}:{},...e.tcId?{"tms.tc_id":e.tcId}:{},...e.capabilities},a=J(e.outDir,G);return q(e.outDir,{recursive:!0}),z(a,`${JSON.stringify(i,null,2)}
|
|
3
|
-
`),{device:{platform:e.platform,target:e.platform,device_config_path:a},...n?{deviceName:n.value}:{},...o?{osVersion:o.value}:{},app:r}}import{createServer as Z}from"http";import{randomBytes as ee}from"crypto";import{spawn as re}from"child_process";import{mkdtempSync as te,readdirSync as ne,readFileSync as oe,rmSync as ie,writeFileSync as se}from"fs";import{tmpdir as M}from"os";import{join as y}from"path";function O(e,t,r,n){let o=Buffer.from(`${n.username}:${n.accessKey}`).toString("base64"),i=new URLSearchParams({session:r,auth:o});return t==="ios"&&i.set("mode","webrtc"),`${e.replace(/\/+$/,"")}/?${i.toString()}`}function W(e){return e.replace(/[&<>"']/g,t=>`&#${t.charCodeAt(0)};`)}function ae(e){return`<!doctype html>
|
|
4
|
-
<html lang="en">
|
|
5
|
-
<head>
|
|
6
|
-
<meta charset="utf-8">
|
|
7
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
8
|
-
<title>${W(e.title)}</title>
|
|
9
|
-
<style>
|
|
10
|
-
html, body { margin: 0; height: 100%; background: #111; font-family: system-ui, sans-serif; }
|
|
11
|
-
iframe { position: fixed; inset: 0; width: 100%; height: 100%; border: 0; }
|
|
12
|
-
#guard { position: fixed; inset: 0; cursor: not-allowed; background: transparent; }
|
|
13
|
-
#badge, #ended { position: fixed; left: 50%; transform: translateX(-50%); padding: 6px 12px;
|
|
14
|
-
border-radius: 999px; font-size: 13px; color: #fff; background: rgba(0, 0, 0, 0.7); }
|
|
15
|
-
#badge { bottom: 16px; }
|
|
16
|
-
#ended { top: 16px; display: none; background: #b42318; }
|
|
17
|
-
</style>
|
|
18
|
-
</head>
|
|
19
|
-
<body>
|
|
20
|
-
<iframe src="${W(e.streamUrl)}" allow="autoplay; fullscreen"></iframe>
|
|
21
|
-
${e.viewOnly?'<div id="guard"></div>':""}
|
|
22
|
-
<div id="badge">View only \u2014 the test is driving this device</div>
|
|
23
|
-
<div id="ended">The session ended</div>
|
|
24
|
-
<script>
|
|
25
|
-
// kane-cli answers while the run lives; once it stops, say so.
|
|
26
|
-
setInterval(() => {
|
|
27
|
-
fetch(location.pathname + "/alive", { cache: "no-store" })
|
|
28
|
-
.then((r) => { if (!r.ok) throw new Error(); })
|
|
29
|
-
.catch(() => { document.getElementById("ended").style.display = "block"; });
|
|
30
|
-
}, 3000);
|
|
31
|
-
</script>
|
|
32
|
-
</body>
|
|
33
|
-
</html>
|
|
34
|
-
`}async function B(e){let t=`/${ee(16).toString("hex")}`,r=ae(e),n=Z((a,s)=>{if(a.url===t){s.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),s.end(r);return}if(a.url===`${t}/alive`){s.writeHead(204),s.end();return}s.writeHead(404),s.end()});await new Promise((a,s)=>{n.once("error",s),n.listen(0,"127.0.0.1",()=>a())}),n.unref();let o=n.address();return{url:`http://127.0.0.1:${typeof o=="object"&&o?o.port:0}${t}`,close:()=>n.close()}}function j(e){let r=e?.width,n=e?.height;return!r||!n?{width:400,height:820}:{width:Math.min(1200,Math.max(320,Math.round(820*r/n))),height:820}}function ce(e,t,r){return[`--app=${e}`,`--user-data-dir=${t}`,`--window-size=${r.width},${r.height}`,"--no-first-run","--no-default-browser-check","--autoplay-policy=no-user-gesture-required"]}var le=3e3;async function L(e,t,r=le){if(!P())throw new Error("Google Chrome is not installed (or set KANE_CLI_CHROME_PATH).");me();let n=te(y(M(),K));se(y(n,F),String(process.pid));let o=re(C(),ce(e,n,t),{stdio:"ignore",detached:process.platform!=="win32"});o.unref();let i=()=>H(n);await new Promise((u,g)=>{let c=setTimeout(()=>{o.off("error",l),o.off("exit",p),u()},r);c.unref();function l(d){clearTimeout(c),i(),g(new Error(`Chrome did not start: ${d.message}`))}function p(d,m){clearTimeout(c),i(),g(new Error(`Chrome quit as it opened (${m??`exit code ${d}`}).`))}o.once("error",l),o.once("exit",p)}),o.on("error",()=>{}),o.once("exit",i);let a=()=>f();process.once("exit",a);let s=!1;function f(){if(!s){s=!0,process.off("exit",a);try{o.pid&&process.platform!=="win32"?process.kill(-o.pid):o.kill()}catch{}i()}}return f}var K="kane-device-view-",F="kane-cli.pid";function H(e){try{ie(e,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}catch{}}function de(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function me(e=M()){let t;try{t=ne(e).filter(r=>r.startsWith(K))}catch{return}for(let r of t){let n=y(e,r),o=NaN;try{o=Number(oe(y(n,F),"utf8"))}catch{}Number.isInteger(o)&&o>0&&de(o)||H(n)}}function Oe(e){return e.flag===!1||e.mobile?.device_stream===!1?"off":e.interactive?"open":"off"}function fe(e){let t=e.basicAuth;if(!t)return;let r=e.resolvedCreds;return{username:t.username,accessKey:t.access_key,...r?.org_id?{orgId:String(r.org_id)}:{},...r?.user_id?{userId:String(r.user_id)}:{}}}async function Be(e){let t=fe(e.auth),r=e.selection?await V({platform:e.target,selection:e.selection,env:e.env,outDir:e.sessionDir,...t?{credentials:t}:{},testName:e.testName,...e.tcId?{tcId:e.tcId}:{},capabilities:{...x(e.mobile,e.target),...I(e.tunnel)},onProgress:e.write,onWarning:c=>e.write(`warning: ${c}`)}):_({platform:e.target,hasCredentials:!!t});!e.selection&&e.tunnel&&e.write("warning: --tunnel is ignored: this run's device config names its own tunnel"),e.write(N(e.target,e.selection?e.tunnel:null));let n=r.app?.replace(/^lt:\/\//,""),o=A(e.target,r.app,e.write),i,a,s=!1,f=!1,u=()=>{f=!0,a?.(),i?.close()},g=c=>{let l=c.type==="run_start"&&!c.child_id?c.environment?.device:void 0,p=l?.session_id;if(s||!p||!t||(e.stream??"off")==="off")return;s=!0;let d=k(l);B({streamUrl:O(v(e.env).deviceStreamUrl,w(e.target),p,t),title:d?`${d} \u2014 live`:"Real device \u2014 live",viewOnly:e.target==="android"}).then(async m=>{i=m,a=await(e.openWindow??L)(m.url,j(l)),f?u():e.write("Showing the device in its own window.")}).catch(m=>{i?.close(),e.write(`note: no live view of the device \u2014 ${m.message}`)})};return{device:r.device,...r.deviceName?{deviceName:r.deviceName}:{},...r.osVersion?{osVersion:r.osVersion}:{},...r.app?{app:r.app}:{},...h(n)?{appId:n}:{},announce:c=>{o(c),g(c)},stopStream:u}}var pe="infra_error.device_lost";function je(e){return e?.reason_code===pe}export{$ as a,Oe as b,fe as c,Be as d,je as e};
|
package/dist/chunk-DREQ3RAA.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
function e(t){let n=t?.trim();return n||void 0}function o(t=process.env){let n=e(t.TEST_INSTANCE_ID),r=e(t.JOB_ID),s=e(t.TASK_ID);return{...n?{testInstanceId:n}:{},...r?{jobId:r}:{},...s?{taskId:s}:{}}}export{o as a};
|
package/dist/chunk-HC6VLPUB.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{b as rt,c as st}from"./chunk-W3USRQX6.js";import{R as nt}from"./chunk-CB2BWDHG.js";import{a as tt}from"./chunk-JQ64X2TO.js";import{a as Ct}from"./chunk-JIRNI5TB.js";import{a as k}from"./chunk-UTM7D4PI.js";import{b as et}from"./chunk-Z36KVIRR.js";import{b as Z,e as Q}from"./chunk-SB26HQO7.js";import{a as X}from"./chunk-FCD3NYOM.js";import{a as W}from"./chunk-4QTH7VYE.js";import{a as R}from"./chunk-RZ4F3BHX.js";import{e as jt}from"./chunk-UR6MHSHU.js";import{readFileSync as L,existsSync as H,readdirSync as Ae,mkdirSync as J,writeFileSync as S}from"fs";import{readFile as Lt,unlink as ke}from"fs/promises";import{join as y}from"path";import{existsSync as le,mkdirSync as de,readdirSync as kt,writeFileSync as _e}from"fs";import{join as w}from"path";import{randomUUID as A}from"crypto";var ot=["children","instructions","branches","module_content","true_branch","false_branch"];function D(e){let t=new Map,n=r=>{if(!r||typeof r!="object")return;let i=r;if(Array.isArray(i.operations))for(let s of i.operations){let o=s.operation_id;if(typeof o!="string"||!o)continue;let a=t.get(o)??[];a.includes(i)||a.push(i),t.set(o,a)}for(let s of ot){let o=i[s];Array.isArray(o)?o.forEach(n):o&&typeof o=="object"&&n(o)}};return e.forEach(n),t}function Dt(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];let n=e.action_params?.script;if(typeof n=="string"&&n.trim()){let r=n.trim(),i=t.find(s=>Ft(s)?.trim()===r);if(i)return i}return t[0]}function Ft(e){let t=e,n=t.script_content??t.js_snippet;return typeof n=="string"?n:void 0}function F(e,t){let n=new Map;for(let r of e){let i=Dt(r,r.action_id?t.get(r.action_id):void 0);if(!i)continue;let s=n.get(i)??[];s.push(r),n.set(i,s)}return n.size===0?null:[...n].map(([r,i])=>$t(r,i))}function at(e,t){let n=D(t.authoredInstructions),r=[];for(let i of e){if(i.flatIndex===void 0||!t.replayOnlyFlatIndices.has(i.flatIndex))continue;let s=F(i.records,n);s&&r.push(...s)}return r}function ct(e,t){let n=new Map(t.map(a=>[a.instruction_id,a])),r=[],i=a=>{if(!a||typeof a!="object")return;let c=a.instruction_id,u=typeof c=="string"?n.get(c):void 0;return u&&r.push(c),u},s=a=>{if(!a||typeof a!="object")return;let c=a;for(let u of ot){let l=c[u];if(Array.isArray(l))o(l);else if(l&&typeof l=="object"){let _=i(l);_&&(c[u]=_),s(_??l)}}},o=a=>{for(let c=0;c<a.length;c++){let u=i(a[c]);u&&(a[c]=u),s(u??a[c])}};return o(e),r}function Bt(e){if(!e.timestamp||e.duration_ms==null)return"";let t=new Date(e.timestamp);return isNaN(t.getTime())?"":new Date(t.getTime()+e.duration_ms).toISOString()}function j(e){if(e!=null)try{return JSON.parse(e)}catch{return e}}function Ut(e){return typeof e=="string"?"string":typeof e=="boolean"?"bool":typeof e=="number"?Number.isInteger(e)?"int":"float":Array.isArray(e)?"list":e==null?"NoneType":"JSON"}function C(e,t,n){let r=e.user_variables,i=typeof r=="string",s;try{s=i?JSON.parse(r):r??[]}catch{return}if(!Array.isArray(s)||s.length===0)return;let o=s.find(a=>t&&a.name===t)??(s.length===1?s[0]:void 0);o&&(o.value=n,o.value_type=Ut(n),e.user_variables=i?JSON.stringify(s):s)}function it(e){e.user_variables!==void 0&&(e.user_variables=typeof e.user_variables=="string"?"[]":[])}function Mt(e,t){let n=e.operations??[],r=new Set(t.map(s=>s.action_id).filter(Boolean)),i=n.filter(s=>r.has(s.operation_id));return i.length>0?i:n.length===1?n:[]}function zt(e){let t=e.error??"Script execution failed";return{error:t,error_code:"SCRIPT_EXECUTION_ERROR",error_message:t,reason:t}}function $t(e,t){let n=structuredClone(e),r=t[0],i=t[t.length-1];n.status=t.find(o=>o.status!=="success")?.status??r.status,n.start_timestamp=r.timestamp??n.start_timestamp,n.end_timestamp=Bt(i)||n.end_timestamp;let s=Mt(n,t);for(let o of s)o.status=n.status,o.operation_start=n.start_timestamp,o.operation_end=n.end_timestamp;switch(n.content_type){case"api":{let o=i.action_params?.api_data?.response;if(o&&typeof o=="object")for(let a of[n,...s])a.api_data={...a.api_data??{},response:o},C(a,i.output_variable,o);break}case"script":{let o=i.output_variable??n.output_variable_name;if(n.status!=="success"){let a=zt(i);n.code_error=a,it(n);for(let c of s)c.execution_result=a,c.code_error=a,it(c)}else if(i.output_value!=null){let a=j(i.output_value);C(n,o,a);for(let c of s)c.execution_result={value:a},C(c,o,a)}break}case"db_query":{i.output_value!=null&&(n.db_details={...n.db_details??{},carried_out_query:j(i.output_value)});break}case"screenshot_command":{let o=j(i.output_value);o&&typeof o=="object"&&(n.smartui_results=o);break}case"network_assertion":case"network_query":break;default:break}return n}var Vt="/home/kaneai/Downloads";function O(e){return`${Vt}/${e}`}function dt(e){return"FILE__"+e.replace(/[^A-Za-z0-9]/g,"_")}function z(e){return"file."+e}function N(e){let t=e?.media;return!t||!t.name||!t.media_url?null:{media_id:t.media_id??"",name:t.name,media_url:t.media_url,type:t.type??"doc",...t.alias?{alias:t.alias}:{}}}function _t(e){return e?e.includes(`
|
|
3
|
-
`)?e.split(`
|
|
4
|
-
`).map(t=>t.trim()).filter(Boolean):e.split(". ").map(t=>t.trim()).filter(Boolean).map(t=>t.endsWith(".")?t:t+"."):[]}function B(e){return typeof e=="string"&&e.includes("{{secrets.")}var qt={click:"CLICK",double_click:"CLICK",type:"TYPE",fill:"TYPE",clear:"CLEAR",select:"SELECT",hover:"HOVER",drag:"DRAG_DROP",upload_files:"UPLOAD_FILE",navigate:"OPEN",go_back:"NAVIGATE",go_forward:"NAVIGATE",refresh:"REFRESH",press_key:"SENDKEYS",scroll:"SCROLL_PIXELS",scroll_into_view:"SCROLL_UNTIL_ELEMENT",js_dialog:"JS_DIALOG",wait:"WAIT",wait_until:"WAIT_UNTIL",wait_for_load:"WAIT_FOR_LOAD",switch_tab:"SWITCH_TAB",new_tab:"NEW_TAB",close_tab:"CLOSE_TAB",api:"API",evaluate_js:"EVALUATE_JS",vision_query:"VISION_QUERY",textual_query:"TEXTUAL_QUERY",get_url:"GET_URL",get_title:"GET_TITLE",assert:"ASSERTION",math:"MATHEMATICAL_OPERATION",set_cookies:"SET_COOKIES",delete_cookies:"DELETE_COOKIES",clear_cookies:"CLEAR_COOKIES",set_local_storage:"SET_LOCAL_STORAGE",delete_local_storage:"DELETE_LOCAL_STORAGE",clear_local_storage:"CLEAR_LOCAL_STORAGE",set_clipboard:"SET_CLIPBOARD",paste_clipboard:"PASTE_CLIPBOARD",clear_clipboard:"CLEAR_CLIPBOARD",device_control:"DEVICE_CONTROL",device_control_query:"DEVICE_CONTROL_QUERY"},pt={literal:"SET_VARIABLE",condition:"SET_VARIABLE",visual:"VISION_QUERY",dom:"TEXTUAL_QUERY",url:"GET_URL",title:"GET_TITLE",devtool_network:"DEVTOOLS_NETWORK_QUERY",devtool_console:"DEVTOOLS_CONSOLE_QUERY",devtool_cookies:"DEVTOOLS_COOKIES_QUERY",devtool_storage:"DEVTOOLS_STORAGE_QUERY",devtool_performance:"DEVTOOLS_PERFORMANCE",api_response:"API_CALLS_QUERY",textual_visual:"TEXTUAL_ANALYZER"},Gt=new Set(["CLICK","TYPE","FILL","HOVER","SCROLL_UNTIL_ELEMENT","UPLOAD_FILE","VISION_QUERY","DRAG_DROP","SELECT"]);function U(e,t){return e!=="fill"&&!(e==="type"&&t.delay_requested===!0)?0:typeof t.delay_ms=="number"&&t.delay_ms>0?t.delay_ms:0}function gt(e,t){if(U(e,t?.action_params??{})&&(e==="fill"||(t?.selectors?.length??0)>0))return"FILL";if(e==="analyze"){let r=t?.action_params?.analyzer_type??"";return pt[r]}if(e==="scroll"&&t?.action_params?.into_view===!0)return"SCROLL_UNTIL_ELEMENT";let n=qt[e];return n||console.warn(`[migrator] UNKNOWN action_type "${e}" \u2014 falling back to "${e.toUpperCase()}"; explicit mapping required`),n??e.toUpperCase()}function ft(e,t){if(!e||!t)return"";try{let n=new Date(e);return isNaN(n.getTime())?"":new Date(n.getTime()+t).toISOString()}catch{return""}}function mt(e){try{return JSON.parse(e.output_value??"{}")}catch{return{}}}function Kt(e){let t=e.output_variable??"";if(!t)return"[]";let r={...mt(e)};return delete r.body,JSON.stringify([{name:t,unique_key:(e.action_id??"").replace(/-/g,"").slice(0,8)||A().replace(/-/g,"").slice(0,8),value:r,variable_description:"API Response"}])}function Ht(e,t,n){let r=e.action_params??{},i=Gt.has(t)?"Vision Agent":"Operation Agent",s={operation_type:t};t==="OPEN"&&(s.url=r.url??""),t==="SET_VARIABLE"&&(s.variable_name=e.output_variable??r.key??"",s.variable_value=e.output_value??"");let o=t==="UPLOAD_FILE"?N(r):null;o&&(s.value=O(o.name));let a={},c={},u=e.action_instruction??"",l=r.text??"",_=r.url??"",p=[["intent",u],["value",l],["url",_]];for(let[h,v]of Object.entries(n)){let I=String(v);if(h.startsWith("secrets."))for(let[b,E]of p)E.includes(I)&&(c[b]=h);for(let[b,E]of p)E.includes(I)&&!(b in a)&&(a[b]=E)}o?.alias&&(a.value=`{{${z(o.alias)}}}`);let d=e.action_type,g={operation:e.action_instruction??"",agent:i,operation_dict:s,reasoning:d==="analyze"?r.query??"":e.intent??e.action_instruction??"",variable:a,secrets:c,params:{}};d==="analyze"&&typeof r.code=="string"&&r.code&&(g.code=r.code),d==="analyze"&&typeof r.code_js=="string"&&r.code_js&&(g.code_js=r.code_js),d==="analyze"&&typeof r.condition_expression=="string"&&r.condition_expression&&(g.condition_expression=r.condition_expression),r.uses_websocket===!0&&(g.uses_websocket=!0),r.uses_sse===!0&&(g.uses_sse=!0),d==="analyze"&&r.analyzer_type==="textual_visual"&&(typeof r.wrapped_js=="string"&&(g.wrapped_js=r.wrapped_js),Array.isArray(r.locators)&&(g.locators=r.locators),typeof r.operator=="string"&&(g.operator=r.operator),Array.isArray(r.transforms)&&(g.transforms=r.transforms),typeof r.query=="string"&&(g.query=r.query),typeof r.expected_value=="string"&&(g.expected_value=r.expected_value),typeof r.needs_unit_conversion=="boolean"&&(g.needs_unit_conversion=r.needs_unit_conversion),typeof r.condition=="string"&&(g.condition=r.condition));let m={set_cookies:"cookies",set_clipboard:"text",delete_cookies:"names",set_local_storage:"items",delete_local_storage:"keys"}[d];return m&&r[m]!==void 0&&(g[m]=r[m]),d==="set_clipboard"&&typeof r.html=="string"&&r.html&&(g.html=r.html),g}function T(e){let t=e.assertion_tree;return t&&typeof t=="object"&&Object.keys(t).length>0?t:Array.isArray(e.sub_results)?e:{}}function Jt(e){let t=T(e);if(typeof t.passed=="boolean")return t.passed;let n=t.sub_results??[];return n.length===0?t.status==="passed":(t.composite_operator??"and")==="or"?n.some(i=>i.passed===!0):n.every(i=>i.passed===!0)}function ht(e){return e.map(t=>({description:t.description??"",store_key:t.store_key??"",expected_value:t.expected??"",extracted_value:t.extracted_value??"",operator:t.operator??"equals",transforms:t.transforms??[]}))}function Yt(e){let t=T(e),n=t.sub_results??[],r=ht(n);return{operator:[],assertion_operands:[],left_operand:null,right_operand:null,operands:[],sub_results:n,sub_checks:r,composite_operator:t.composite_operator??"and",verification:t.verification??"",claim:t.description??""}}function Wt(e){let t=e.action_params??{},n=T(t),r=n.sub_results??[],i=ht(r);return[{operation:e.action_instruction??"",agent:"Operation Agent",operation_dict:{operation_type:"ASSERTION",assertion_tree:{sub_results:r,sub_checks:i,composite_operator:n.composite_operator??"and",verification:"",claim:n.description??e.action_instruction??"",operator:[],assertion_operands:[],left_operand:null,right_operand:null,operands:[]}},variable:{},secrets:{},params:{}}]}function Xt(e,t,n,r){let i=e.visual_data;if(!i||i.x==null||i.y==null)return null;let s=t?`${t}/test_screenshots`:"";return{x:i.x,y:i.y,confidence:0,bbox:i.bbox??null,bbox_source:i.bbox?"accessibility_tree":"fallback",viewport_width:i.viewport_width??1280,viewport_height:i.viewport_height??800,scale_factor:null,raw_image_url:s?`${s}/untagged_screenshot/${n}.${r?.get(n)??"png"}`:"",raw_image_sas_url:"",annotated_image_url:"",annotated_image_sas_url:""}}function Zt(e){if(!e)return"";let t=e;return typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.frameInfo)&&(t=e.frameInfo),!Array.isArray(t)||t.length===0?"":JSON.stringify(t)}function Qt(e){return/^(android|ios)_native$/i.test(e.platform??"")}function bt(e,t){return e.map(n=>({...n,type:t?n.strategy??n.type??"native":n.isXPath?"xpath":"css"}))}function te(e,t,n){let r={selector_target:"",drag_displacement:{},hold_duration_ms:null,move_duration_ms:null,hold_at_destination_ms:null};if(e!=="drag")return r;let i=t.target_selectors,s={};typeof t.direction=="string"&&t.direction&&(s.direction=t.direction,typeof t.fraction=="number"&&(s.fraction=t.fraction));let o=a=>typeof t[a]=="number"?Math.trunc(t[a]):null;return{selector_target:Array.isArray(i)&&i.length>0?bt(i,n):"",drag_displacement:s,hold_duration_ms:o("hold_duration_ms"),move_duration_ms:o("move_duration_ms"),hold_at_destination_ms:o("hold_at_destination_ms")}}function ut(e,t="",n){let r=e.action_type,i=gt(r,e),s=e.action_params??{},o=e.coordinates??null,a=e.selectors??null,c=!!(a&&a.length>0),u=Qt(e),l=te(r,s,u),_=e.timestamp??"",p=e.duration_ms??0,d=e.variables_used??{},g=e.action_id??A(),f=A(),m=ft(_,p),h="",v="";if(r==="navigate")v=s.url??"",h=v;else if(r==="type"||r==="fill")h=s.text??"";else if(r==="press_key")h=s.key??"";else if(r==="wait")h=String(s.ms??s.timeout_ms??"");else if(r==="evaluate_js")h=s.script??"";else if(r==="js_dialog")h=s.prompt_text??"";else if(r==="upload_files"){let Y=N(s);Y&&(h=O(Y.name))}else r==="analyze"&&i==="SET_VARIABLE"&&(h=e.output_value??"");let I="";r==="go_back"?I="back":r==="go_forward"&&(I="forward");let b=e.action_instruction??"",E=B(h)||B(v)||B(b),x=Ht(e,i,d);return{operation_id:g,instruction_id:f,instruction:b,intent:b,operation_start:_,operation_end:m,status:e.status??"",command:i,name:"",target:"",value:h,message:"",operation_dict:"",frame:Zt(e.frame_info),surface:typeof s.surface=="string"?s.surface:"",...U(r,s)?{delay_ms:U(r,s)}:{},frame_path:typeof s.frame_path=="string"?s.frame_path:"",grounded_by:typeof s.grounded_by=="string"?s.grounded_by:"",error_message:e.error??"",code_snippet:"",sub_instruction_obj:JSON.stringify(x),test_id:"",test_version:"",action:"",string_to_float:!1,feedback_msg:"",time_taken:"",create_time_stamp:"",update_time_stamp:"",locator_variable:"",locator_variable_name:"",image_url:t&&r!=="js_dialog"?`${t}/test_screenshots/untagged_screenshot/${g}.${n?.get(g)??"png"}`:"",alternative_xpaths:[],attribute:"",value_description:"",url:v,navigation_direction:I,tagified_image_url:"",query_variable_name:e.output_variable??"",query_variable_value:e.output_value??"",query_variable_type:"",expected_value:"",queried_value:"",operator:"",assertion_status:i==="ASSERTION"?Jt(s):"",query_info_dict:{},query_content_confidence:"none",debugging_logs:[],locator_index:0,query_html:"",user_variables:"[]",optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,tab_index:String(s.tab_index??""),tab_identifier:String(s.tab_identifier??""),scroll_value:s.amount??1,scroll_direction:s.direction??"",mi_scroll_payload:{},sleep_duration:0,app_id:"",manual_interaction_tag:"",string_to_float_list:[],js_snippet:r==="evaluate_js"?s.script??"":"",code_error:"",hide:E,dismiss_dialog:!1,use_v2_mobile_tagging:u,multiple_inputs:!1,dialog_action:r==="js_dialog"?s.action??"":"",dialog_type:r==="js_dialog"?s.dialog_type??"":"",is_coordinates_used_for_interaction:o!==null&&!c,element_coordinates_ratio:[],element_bounds_ratio:[],x_coord:c?null:o?.x??null,y_coord:c?null:o?.y??null,target_x_coord:s.target_x??null,target_y_coord:s.target_y??null,source_description:s.source_description??null,target_description:s.target_description??null,use_coordinates:o!==null&&!c,kaneaiMobileTaggingImageLimit:1,clicks_order_code:"se_js_ac",selector:c?bt(a,u):"",selector_target:l.selector_target,math_result_variable_name:"",math_result_variable_value:"",expression_tree:i==="ASSERTION"?Yt(s):s.expression_tree??{},assertion_tree:i==="ASSERTION"?T(s):s.assertion_tree??{},assertion_tree_simplified:{},network_throttle:{},is_mobile_offline:!1,autoheal:!1,reprobe:e.reprobe??!1,click_modifier:(s.click_count??1)>=2?{kind:"multi_click",frequency:s.click_count}:null,db_query:"",db_details:{},db_query_decoded:"",is_global_variable:!1,is_global_variable_persist:!1,global_variable_id:"",wait_for_element_timeout:0,failure_condition:i==="ASSERTION"?"Fail test immediately":"",screenshot_command:"",smartui_contents:{},smartui_results:{},result_type:"",result_hint:"",drag_offset:{},drag_displacement:l.drag_displacement,hold_duration_ms:l.hold_duration_ms,move_duration_ms:l.move_duration_ms,hold_at_destination_ms:l.hold_at_destination_ms,start_coordinates:s.source_coordinates?{x:s.source_coordinates[0],y:s.source_coordinates[1]}:{},end_coordinates:s.target_coordinates?{x:s.target_coordinates[0],y:s.target_coordinates[1]}:{},element_rect:null,is_canvas:!1,until_condition:"",until_max_retries:0,until_settle_ms:0,api_data:r==="api"?{request:e.action_params?.api_data?.request??{}}:{},output_variables:r==="api"?e.output_variable?{[e.output_variable]:null}:{}:e.output_variable?{[e.output_variable]:e.output_value??""}:{},visual_context:Xt(e,t,g,n),reasoning:r==="analyze"?s.query??"":e.intent??e.action_instruction??""}}function lt(e,t){let n=e.action_type,r=gt(n,e),i=e.timestamp??"",s=e.duration_ms??0,o=ft(i,s),a=r==="ASSERTION"||r==="MATHEMATICAL_OPERATION";return{instruction_id:t.instruction_id,instruction_class:a?"non_driver_action":"driver_action",module_id:"",instruction:e.action_instruction??"",command:r,error:null,parent_instruction_id:"",classification_layer_resp:r==="ASSERTION"?Wt(e):[],classification_error:{},operations:[t],status:e.status??"",start_timestamp:i,end_timestamp:o,type:"agent_generated",tags:[],html_paths:[],optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,content_type:n==="api"?"api":n==="analyze"&&e.action_params?.analyzer_type==="api_response"?"api_calls_query":n==="analyze"&&e.action_params?.analyzer_type?.startsWith("devtool_")?e.action_params.analyzer_type.replace("devtool_","devtools_"):"instruction",js_snippet:n==="evaluate_js"?e.action_params?.script??"":"",user_variables:n==="api"?Kt(e):"[]",api_data:n==="api"?{request:e.action_params?.api_data?.request??{},response:mt(e)}:{},params_used:!1,hard_assertion:r==="ASSERTION"?e.action_params?.failure_condition==="hard":!1,expected_outcome:"",module_execution_index:0,module_version:null,network_throttle:{},isEdited:!1,use_query_assertion_v2:!1,db_query:"",db_details:{},network_assertion_content:{},screenshot_command:"",smartui_contents:{},generative_id:"",plan_id:"",generative_objective:"",error_message:"",error_code:"",reason:"",title:"",used_variables:[],reasoning:n==="analyze"?e.action_params?.query??"":e.intent??e.action_instruction??""}}function ee(e,t=[]){let n=e.action_params??{},r=n.branches??[],i=n.winning_index??-1,s=n.sub_results??[],o={};for(let c of s){let u=c.sub_results;if(u)for(let l of u){let _=l.store_key;_&&(o[_]=l)}}let a=r.map((c,u)=>{let l=u===i,_=(c.sub_checks??[]).map(p=>{let d=o[p.store_key];return{description:p.description,store_key:p.store_key,expected_value:p.expected_value,stored_value:d?.extracted_value??p.stored_value,operator:p.operator??d?.operator??"equals",transforms:p.transforms??d?.transforms??[]}});if(_.length===0&&c.condition&&s.length>0){let d=s.find(g=>g.branch_index===u)?.sub_results??[];d.length>0&&(_=d.map(g=>({description:g.description??c.condition,store_key:g.store_key??"",expected_value:g.expected??"true",stored_value:g.extracted_value??void 0,operator:g.operator??"equals",transforms:g.transforms??[]})))}return{branch_index:u,condition:c.condition??null,branch_type:c.branch_type??"sub_objective",passed:l,sub_objective:null,custom_event:c.custom_event??null,children:l?t:[],sub_checks:c.condition?_:[],composite_operator:c.composite_operator??"and"}});return{content_type:"conditional_block",instruction_id:`if_else_${A().slice(0,8)}`,instruction:e.action_instruction??"",instruction_class:"driver_action",command:"",status:e.status??"success",resolved_branch_index:i,branches:a,generative_id:"",generative_objective:"",variables_used:{},classification_layer_resp:[],classification_error:{},used_variables:[],user_variables:"[]",module_id:"",module_execution_index:0,module_version:"",plan_id:"",optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,error:null,error_message:"",error_code:"",reason:"",start_timestamp:e.timestamp??"",end_timestamp:"",type:"agent_generated",hook:null,hook_type:null,evaluation_context:{},query_variables:{}}}function yt(e,t,n){for(let r of e)r.content_type==="instruction"&&"generative_id"in r&&(r.generative_id=t,r.generative_objective=n)}function M(e,t="",n,r){let i=[],s=0;for(;s<e.length;){let o=e[s],a=o.action_type;if(!r?.keepFailedActions&&o.status==="error"&&a!=="assert"&&a!=="if_else"&&a!=="child_agent_start"&&a!=="child_agent_end"&&a!=="js_dialog"&&!(o.until_condition&&!o.error)){s+=1;continue}if(a==="analyze"&&(!pt[o.action_params?.analyzer_type??""]||o.action_params?.analyzer_type==="textual_visual"&&o.action_params?.code)){s+=1;continue}if(a==="child_agent_start"){let c=o.action_params?.child_id??"",u=o.action_params?.objective??"",l=[];s+=1;let _=1,p="error",d;for(;s<e.length&&_>0;){let E=e[s],x=E.action_type;if(x==="child_agent_start")_+=1;else if(x==="child_agent_end"&&(_-=1,_===0)){p=E.status??"success",d=E,s+=1;break}_>0&&l.push(E),s+=1}let g=M(l,t,n);yt(g,c,u);let f=d?.action_params?.result_code??null,m=d?.action_params?.reason_code??null,h=d?.action_params?.error_message??null,v=d?.action_params?.summary??null,I=d?.action_params?.one_liner??null,b=p==="error";i.push({content_type:"generative_block",instruction_id:`generative_block_${c}`,generative_id:c,objective:u,status:p,children:g,error_message:b?h??null:null,error_code:b?m??null:null,result_code:f??null,bifurcation_context:[],approach_reason:_t(v),one_liner:I??null});continue}else if(a==="child_agent_end"){s+=1;continue}else if(a==="if_else"){s+=1;let c=[];for(;s<e.length&&e[s].action_type==="child_agent_start";){let u=e[s],l=u.action_params?.child_id??"",_=u.action_params?.objective??"",p=[];s+=1;let d=1,g="error";for(;s<e.length&&d>0;){let m=e[s];if(m.action_type==="child_agent_start")d+=1;else if(m.action_type==="child_agent_end"&&(d-=1,d===0)){g=m.status??"success",s+=1;break}d>0&&p.push(m),s+=1}let f=M(p,t,n);c.push(...f)}i.push(ee(o,c));continue}else if(a==="query_tool"){s+=1;continue}else if(o.until_condition){let c=ut(o,t,n),u=lt(o,c),l=typeof o.until_condition_met=="boolean"?o.until_condition_met:o.status==="success";i.push({content_type:"until_block",instruction_id:`until_${A().slice(0,8)}`,condition:o.until_condition,max_retries:o.until_max_retries??10,settle_ms:o.until_settle_ms??500,current_count:0,condition_met:l,children:[u],generative_id:"",generative_objective:"",variables_used:{},status:o.status??"success"})}else{let c=ut(o,t,n),u=lt(o,c);i.push(u)}s+=1}return i}function P(e,t="",n,r){let i=[],s=[],o=r?.passthrough,a=o?D(o.authoredInstructions):null;for(let d of e){if(o&&a&&d.flatIndex!==void 0&&o.replayOnlyFlatIndices.has(d.flatIndex)){let b=F(d.records,a);if(b){for(let E of b)i.push(E),s.push(d.flatIndex);continue}console.warn(`[migrator] replay-only passthrough: no authored operation matched step ${d.flatIndex} (action_id \u2260 any operation_id in the authored blob) \u2014 falling back to this run's records`)}let g=M(d.records,t,n,r);if(g.length===0)continue;let f=A().replace(/-/g,"");yt(g,f,d.objective);let m=g.some(b=>"status"in b&&typeof b.status=="string"?b.status==="error"||b.status==="failed":!1),h=d.resultCode?parseInt(d.resultCode,10):null,v=h!==null&&!isNaN(h)&&h>=200,I=m||v?"error":"success";i.push({content_type:"generative_block",instruction_id:`generative_block_${f}`,generative_id:f,objective:d.objective,status:I,children:g,error_message:I==="error"?d.errorMessage??null:null,error_code:I==="error"?d.reasonCode??null:null,result_code:d.resultCode??null,bifurcation_context:[],approach_reason:_t(d.summary),one_liner:d.oneLiner??null}),s.push(d.flatIndex)}let c=i.map((d,g)=>({block:d,flat:s[g]})),u=r?.moduleSpans??[],l=r?.blockSpans??[],_=r?.authoredBlocks??[];u.length>0&&(c=Et(c,u,l,_));let p=At(l,u);return p.length>0&&(c=$(c,p,_)),{instructions:c.map(d=>d.block)}}function Et(e,t,n,r){let i=[],s=a=>a===void 0?void 0:t.find(c=>a>=c.flatFrom&&a<=c.flatTo),o=0;for(;o<e.length;){let a=s(e[o].flat);if(!a){i.push(e[o]),o++;continue}let c=[];for(;o<e.length&&s(e[o].flat)===a;)c.push(e[o++]);let u=Et(c,a.children,n,r),l=At(vt(n,a),a.children);l.length>0&&(u=$(u,l,r)),i.push({block:ue(a,u.map(_=>_.block)),flat:c[0].flat})}return i}function It(e,t){return e.flatFrom>=t.flatFrom&&e.flatTo<=t.flatTo}function vt(e,t){let n=[];for(let r of e)It(r,t)?n.push(r):n.push(...vt(r.children,t));return n}function At(e,t){let n=[],r=s=>{for(let o of s)n.push(o),r(o.children)};r(t);let i=s=>s.filter(o=>!n.some(a=>It(o,a))).map(o=>({...o,children:i(o.children)}));return n.length>0?i(e):e}function $(e,t,n){let r=[...t].sort((u,l)=>u.flatFrom-l.flatFrom),i=[],s=(u,l)=>{i.push({block:oe(u,l,n),flat:u.flatFrom})},o=(u,l)=>u!==void 0&&u>=l.flatFrom&&u<=l.flatTo,a=0,c=0;for(;c<e.length;){let u=e[c].flat;for(;a<r.length&&u!==void 0&&r[a].flatTo<u;)s(r[a++],[]);let l=a<r.length&&o(u,r[a])?r[a]:void 0;if(!l){i.push(e[c]),c++;continue}let _=[];for(;c<e.length&&o(e[c].flat,l);)_.push(e[c++]);s(l,_),a++}for(;a<r.length;)s(r[a++],[]);return i}function ne(e){let t=new Map;for(let n of e)t.set(n.flat,n);return e.filter(n=>t.get(n.flat)===n)}var re=["children","instructions","branches","module_content","true_branch","false_branch"];function se(e,t){if(!t)return;let n=[...e];for(;n.length>0;){let r=n.pop();if(!r||typeof r!="object")continue;let i=r;if(i.instruction_id===t&&(i.content_type==="conditional_block"||i.content_type==="until_block"))return i;for(let s of re){let o=i[s];Array.isArray(o)?n.push(...o):o&&typeof o=="object"&&n.push(o)}}}function ie(e,t,n){if(!e)return[];if(t==="while")return Array.isArray(e.children)?e.children:[];let i=(Array.isArray(e.branches)?e.branches:[])[n];return i&&Array.isArray(i.children)?i.children:[]}function oe(e,t,n){let r=se(n,e.blockId),i=e.branches.map((s,o)=>{let a=t.filter(l=>l.flat!==void 0&&l.flat>=s.flatFrom&&l.flat<=s.flatTo);e.kind==="while"&&(a=ne(a));let c=$(a,e.children,n).map(l=>l.block);if(c.length>0)return c;let u=ie(r,e.kind,o);return u.length===0&&!s.taken&&console.warn(`[migrator] control-flow: branch ${o} of block ${e.blockId||e.instruction} did not run and no authored block matched \u2014 emitted empty`),u});return e.kind==="if"?ae(e,i,r):ce(e,i[0]??[],r)}function ae(e,t,n){let r=Array.isArray(n?.branches)?n.branches:[],i=V(t.flat()),s=e.branches.map((o,a)=>{let c=r[a];return{branch_index:a,condition:o.branch_type==="else"?null:o.condition,branch_type:o.branch_type,passed:o.taken,sub_objective:null,custom_event:c?.custom_event??null,children:t[a],sub_checks:Array.isArray(c?.sub_checks)?c.sub_checks:[],composite_operator:c?.composite_operator??"and"}});return{content_type:"conditional_block",instruction_id:e.blockId||`if_else_${A().slice(0,8)}`,instruction:e.instruction,instruction_class:"driver_action",command:"",status:i?"error":"success",resolved_branch_index:e.branches.findIndex(o=>o.taken),branches:s,generative_id:"",generative_objective:"",variables_used:{},classification_layer_resp:[],classification_error:{},used_variables:[],user_variables:"[]",module_id:"",module_execution_index:0,module_version:"",plan_id:"",optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,error:null,error_message:i?.message??"",error_code:i?.code??"",reason:"",start_timestamp:"",end_timestamp:"",type:"agent_generated",hook:null,hook_type:null,evaluation_context:{},query_variables:{}}}function ce(e,t,n){let r=e.whileCfg??{max_retries:5,settle_ms:500,on_exhaust:"fail",iterations:0,condition_met:!1},i=V(t),s=(o,a)=>n&&n[o]!==void 0?n[o]:a;return{content_type:"until_block",instruction_id:e.blockId||`until_${A().slice(0,8)}`,condition:e.instruction,max_retries:r.max_retries,settle_ms:r.settle_ms,current_count:r.iterations,condition_met:r.condition_met,children:t,generative_id:"",generative_objective:"",variables_used:{},status:i?"error":"success",on_exhaust:s("on_exhaust",r.on_exhaust),mode:s("mode",""),check:s("check",""),conditions:s("conditions",[]),connectors:s("connectors",[]),sub_checks:s("sub_checks",[]),composite_operator:s("composite_operator","and")}}function V(e){for(let t of e){let n="status"in t&&typeof t.status=="string"?t.status:"";if(n==="error"||n==="failed"){let r="error_message"in t?t.error_message:void 0,i="error_code"in t?t.error_code:void 0;return{message:r??null,code:i??null}}}return null}function ue(e,t){let n=e.meta,r=(u,l="")=>typeof n[u]=="string"?n[u]:l,i=(u,l=!1)=>typeof n[u]=="boolean"?n[u]:l,s=u=>Array.isArray(n[u])?n[u]:[],o=typeof n.module_version=="number"||typeof n.module_version=="string"?n.module_version:null,a=r("module_id"),c=V(t);return{content_type:nt,instruction_id:`module_block_${a}`,module_id:a,module_version:o,module_instance_id:A(),module_name:r("module_name"),module_description:r("module_description"),module_platform:r("module_platform"),creation_mode:r("creation_mode","Agent"),tms_status:r("tms_status","active"),is_validated:i("is_validated"),is_dirty:e.dirty,enrichment_id:r("enrichment_id"),tags:s("tags"),project_ids:s("project_ids"),link_to_all:i("link_to_all"),status:c?"error":"success",children:t,error_message:c?.message??null,error_code:c?.code??null,update_available:!1,update_info:{}}}function Rt(e,t){let n;try{n=kt(e)}catch{return 0}let r=0,i=n.filter(s=>/^\d+$/.test(s)).sort((s,o)=>Number(s)-Number(o));for(let s of i){let o=w(e,s),a=w(o,"logs");if(!le(a))continue;let c;try{c=kt(a)}catch{continue}let u=c.filter(p=>p.endsWith("-actions.ndjson")).sort((p,d)=>(parseInt(p,10)||0)-(parseInt(d,10)||0)),l=[];for(let p of u){let d=t.readActions(w(a,p));d.length&&l.push({objective:t.objective??"",records:d})}if(l.length===0)continue;let{instructions:_}=P(l,t.screenshotBaseUrl??"",t.extMap,{keepFailedActions:!0});if(_.length!==0)try{let p=w(o,"auteur");de(p,{recursive:!0}),_e(w(p,"execution.json"),JSON.stringify(t.buildBlob(_),null,2)),r++,t.log?.("info","EVIDENCE_ARCHIVED_ATTEMPT_BLOB","Derived nested attempt blob",{attempt:s,instructions:_.length})}catch(p){t.log?.("debug","EVIDENCE_ARCHIVED_ATTEMPT_BLOB_FAILED","Nested attempt blob derivation failed",{attempt:s,error:p instanceof Error?p.message:String(p)})}}return r}import{existsSync as pe,readFileSync as ge}from"fs";function Pt(e){try{return pe(e)?JSON.parse(ge(e,"utf-8")):void 0}catch{return}}function q(e,t){if(!e||typeof e!="object")return;let n=e,r=n.project_token;if(typeof r!="string"||!r)return;let i={project_token:r},s=n[t];typeof s=="string"&&s&&(i.project_name=s);let o=n.project_id;return typeof o=="string"&&o&&(i.project_id=o),i}function G(e){if(Array.isArray(e)){for(let r of e){let i=G(r);if(i)return i}return}if(!e||typeof e!="object")return;let t=e,n=t.smartui_results;if(n&&typeof n=="object"){let r=q(n.project,"name");if(r)return r}for(let r of Object.values(t)){let i=G(r);if(i)return i}}function wt(e){for(let t of e.runMetaPaths){let n=Pt(t),r=q(n?.smartui,"project_name");if(r)return r}if(e.authoredBlobPath){let t=Pt(e.authoredBlobPath),n=q(t?.smartui,"project_name");if(n)return n}return G(e.instructions)??{}}var St=jt(Ct(),1);import{createWriteStream as fe}from"fs";import{readFile as me}from"fs/promises";import{join as he,basename as be}from"path";import{tmpdir as ye}from"os";var Ee=["**/screenshots/**","**/annotated/**","**/tcg/**","**/bifurcation/**"];async function xt(e){let t=he(ye(),`${be(e)}_artifacts.zip`);return new Promise((n,r)=>{let i=fe(t),s=(0,St.default)("zip",{zlib:{level:6}});i.on("close",()=>n(t)),s.on("error",r),s.pipe(i),s.glob("**/*",{cwd:e,ignore:Ee}),s.finalize()})}async function Ot(e){return me(e)}function Ie(e){if(!e||typeof e!="object")return;let t=e,n=typeof t.message=="string"?t.message:t.error?.message;return typeof n=="string"&&n.trim()?n.trim():void 0}function ve(e){if(!(e instanceof Error)||e.name!=="TmsHttpError")return null;let t=e.status;return typeof t=="number"?{status:t,body:e.body}:null}function qe(e){let t=ve(e);return t?{kind:"tms_refused",status:t.status,message:Ie(t.body)}:{kind:"tms_unreachable",detail:e instanceof Error?e.message:String(e)}}function K(e){if(!e)return"no Test Manager test was created for this session";switch(e.kind){case"tms_refused":return e.message?`${e.message} (HTTP ${e.status})`:e.status===401?"Test Manager didn't accept your login (HTTP 401) \u2014 run `kane-cli login` and try again":e.status>=500?`Test Manager had an error (HTTP ${e.status}) \u2014 try again later`:`Test Manager refused to create the test (HTTP ${e.status})`;case"tms_unreachable":return`Test Manager couldn't be reached${e.detail?` (${e.detail})`:""} \u2014 try again later`;case"no_cloud_app":return"the app under test wasn't uploaded to LambdaTest, so Test Manager has no build to file this test under";case"signed_out":return"you're not signed in \u2014 run `kane-cli login` to save runs to Test Manager"}}function Ge(e){return`This run won't be saved to Test Manager: ${K(e)}.`}function Nt(e,t){let n=t?.trim()?` (${t.trim()})`:"";switch(e){case"expired":return`Not saved to Test Manager: this test's edit session expired before the save${n}. Run it again to save.`;case"base_mismatch":return`Not saved to Test Manager: someone saved a newer version of this test while this run was going${n}. Pull the latest version and run it again.`;case"lock_mismatch":return`Not saved to Test Manager: another session holds this test for editing${n}.`;case"not_found":return`Not saved to Test Manager: the version this run was saving was not found${n}. Run it again to save.`;case"auth":return`Not saved to Test Manager: your account isn't allowed to save this test${n}. Check your login and your KaneAI access in this organization.`;case"network":return`Not saved to Test Manager: Test Manager couldn't be reached${n}. Try again later.`;case"bundle_sync_failed":return`Not saved to Test Manager: the test files couldn't be uploaded before saving${n}, so no new version was committed. The local recording is kept \u2014 run again with --push once fixed.`;default:return`Not saved to Test Manager: committing the new version failed (${e??"unknown"}${t?.trim()?`: ${t.trim()}`:""}).`}}async function Re(e,t){return Lt(et(e,t))}function Pe(e){return{key:"artifacts",content_type:"application/zip",filename:`${e}.evidence`}}var we=[1e3,2e3,4e3],Tt=class{config;controller;testId;constructor(t){this.config=t,this.controller=new X(t.controllerBaseUrl,t.auth),this.testId=t.testId}log(t,n,r,i){this.config.log?.(t,n,r,i)}async execute(){let{onProgress:t}=this.config;try{if(!this.testId)return this.log("error","PIPELINE_ABORT","No test_id available",{save_blocker:this.config.saveBlocker?.kind??null}),{success:!1,testId:null,error:`Not saved to Test Manager: ${K(this.config.saveBlocker)}.`};let n=this.config.evidence,r=null;if(this.config.shouldUploadArtifacts!==!1){t("convert","running");let a=this.collectNdjsonPerRun(),c=a.reduce((f,m)=>f+m.records.length,0);this.log("info","PIPELINE_CONVERT","Collected NDJSON records",{total_records:c,run_groups:a.length});let u=this.loadReplayOnlyPassthrough(),{instructions:l}=a.length>0?P(a,this.config.screenshotBaseUrl??"",this.config.screenshotExtMap,{moduleSpans:this.config.moduleSpans,...u?{passthrough:u}:{},...this.config.blockSpans?.length?{blockSpans:this.config.blockSpans,authoredBlocks:this.loadAuthoredBlocks()}:{}}):{instructions:[]};this.log("info","PIPELINE_CONVERT_INSTRUCTIONS","Auteur instructions produced",{count:l.length});let _=this.buildExecutionEnvelope(l),p=Buffer.from(JSON.stringify(_));this.log("info","PIPELINE_CONVERT_BLOB","Blob created",{size_kb:+(p.length/1024).toFixed(1)});let d=y(this.config.sessionDir,"execution.json");S(d,JSON.stringify(_,null,2)),this.log("info","PIPELINE_CONVERT_LOCAL_SAVE","Execution blob saved locally",{path:d});let g=n?.packTestDir??this.config.evidenceRead?.packTestDir;if(g){let f=y(g,"auteur");J(f,{recursive:!0}),S(y(f,"execution.json"),JSON.stringify(_,null,2)),this.log("info","PIPELINE_CONVERT_PACK_COPY","Execution blob copied into pack",{path:y(f,"execution.json")}),this.deriveArchivedAttemptBlobs(g)}if(t("convert","done"),n)r=p;else{t("zip","running"),this.log("info","PIPELINE_ZIP_START","Zipping session",{session_dir:this.config.sessionDir});let f=null,m;try{f=await xt(this.config.sessionDir),m=await Ot(f),this.log("info","PIPELINE_ZIP_DONE","Zip complete",{size_mb:+(m.length/1024/1024).toFixed(1),path:f}),t("zip","done",`${(m.length/1024/1024).toFixed(1)}MB`)}finally{f&&await ke(f).catch(()=>{})}t("presign","running"),this.log("info","PIPELINE_PRESIGN_START","Requesting presigned URLs",{url:`${this.config.controllerBaseUrl}/upload/presign`,test_id:this.testId,session_id:this.config.sessionId});let h=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[{key:"artifacts",content_type:"application/zip",filename:`${this.config.sessionId}_artifacts.zip`},{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);this.log("info","PIPELINE_PRESIGN_OK","Presigned URLs received",{artifacts_url:h.urls.artifacts?.blob_url,blob_url:h.urls.blob?.blob_url}),t("presign","done"),t("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading artifacts and blob",{artifact_size_mb:+(m.length/1024/1024).toFixed(1),blob_size_kb:+(p.length/1024).toFixed(1)}),await Promise.all([k(h.urls.artifacts.upload_url,m,"application/zip"),k(h.urls.blob.upload_url,p,"application/json")]),this.log("info","PIPELINE_UPLOAD_OK","Upload complete"),t("upload","done")}}else{let a=this.collectNdjsonPerRun(),c=this.loadReplayOnlyPassthrough(),{instructions:u}=a.length>0?P(a,this.config.screenshotBaseUrl??"",this.config.screenshotExtMap,{keepFailedActions:!0,moduleSpans:this.config.moduleSpans,...c?{passthrough:c}:{},...this.config.blockSpans?.length?{blockSpans:this.config.blockSpans,authoredBlocks:this.loadAuthoredBlocks()}:{}}):{instructions:[]},l=this.buildExecutionEnvelope(u),_=y(this.config.sessionDir,"execution.json");S(_,JSON.stringify(l,null,2)),this.log("info","PIPELINE_LOCAL_SAVE","Execution blob saved locally (no upload)",{path:_});let p=this.config.evidence?.packTestDir??this.config.evidenceRead?.packTestDir;if(p){let d=y(p,"auteur");J(d,{recursive:!0});let g=this.readAuthoredExecution(),f=g?this.refreshReplayOnlyInPack(g,a,c):null;S(y(d,"execution.json"),f?.raw??JSON.stringify(l,null,2)),this.log("info","PIPELINE_CONVERT_PACK_COPY","Execution blob copied into pack (gated)",{path:y(d,"execution.json"),source:f?f.refreshed.length>0?"authored+replay_results":"authored":"run_envelope",...f&&f.refreshed.length>0?{refreshed_instruction_ids:f.refreshed}:{}}),this.deriveArchivedAttemptBlobs(p)}t("convert","skipped"),t("zip","skipped"),t("presign","skipped"),t("upload","skipped"),this.log("info","PIPELINE_UPLOAD_SKIPPED","Upload steps skipped (gate disabled)")}if(this.config.shouldReplaceLocalOutput&&this.config.onAtomicReplace){t("atomic_replace","running");try{await this.config.onAtomicReplace(),this.log("info","PIPELINE_ATOMIC_REPLACE_OK","Local output replaced"),t("atomic_replace","done")}catch(a){let c=a instanceof Error?a.message:String(a);throw this.log("error","PIPELINE_ATOMIC_REPLACE_FAILED","Atomic-replace failed",{error:c}),t("atomic_replace","failed",c),a}}else t("atomic_replace","skipped");let i,s;if(this.config.shouldCommit&&!this.config.isFirstRun&&this.config.onCommitLock){t("commit_lock","running");let a=await this.config.onCommitLock();if(a.ok)i=a.testcaseId||void 0,this.log("info","PIPELINE_COMMIT_LOCK_OK","Commit lock acquired",{testcase_id:i??"none",trigger:a.trigger??null,test_instance_id:a.testInstanceId??null}),t("commit_lock","done");else return this.log("error","PIPELINE_COMMIT_LOCK_FAILED","Commit lock failed",{reason:a.reason,message:a.message}),t("commit_lock","failed",`${a.reason??"unknown"}: ${a.message??""}`),{success:!1,testId:this.testId,error:Nt(a.reason,a.message)}}else t("commit_lock","skipped");if(this.config.isFirstRun&&!this.config.skipTmsFinalize){t("finalize","running"),this.log("info","PIPELINE_FINALIZE_START","Finalizing test (first-run)",{test_id:this.testId,commit_id:this.config.commitId});let a=new Q(this.config.tmsBaseUrl,this.config.tmsUsername,this.config.tmsAccessKey),c=this.config.runObjectives&&this.config.runObjectives.length>0?this.config.runObjectives:[this.config.firstObjective],u={commit_id:this.config.commitId,time_taken:Math.round(this.config.totalDuration),steps_count:this.config.totalSteps,commit_message:this.config.firstObjective.slice(0,255),objectives:c,...this.config.assuranceStamp?{assurance:this.config.assuranceStamp}:{}},l;try{l=await this.stop(a,u)}catch(_){if(!this.config.attachedStop)throw _;let p=_ instanceof Error?_.message:String(_);this.log("error","PIPELINE_FINALIZE_NOT_SAVED","Attached test's stop did not finalize after its retries",{test_id:this.testId,error:p}),t("finalize","failed",p);try{await this.config.onFinalizeGaveUp?.()}catch(d){this.log("warn","PIPELINE_FINALIZE_META_FAILED","Meta-rewrite after a stop that did not finalize failed",{error:String(d)})}return{success:!1,testId:this.testId,error:`finalize failed: ${p}`,notSaved:!0}}if(i=l.testcase_id||void 0,this.log("info","PIPELINE_FINALIZE_OK","Test finalized",{testcase_id:i??"none",commit_id:l.commit_id??null}),this.config.onFinalizeSuccess)try{await this.config.onFinalizeSuccess(i,l.commit_id)}catch(_){this.log("warn","PIPELINE_FINALIZE_META_FAILED","Meta-rewrite after endTest failed",{error:String(_)})}t("finalize","done")}else t("finalize","skipped"),this.log("info","PIPELINE_FINALIZE_SKIPPED","Finalize skipped (evolve flow or first-run disabled)");if(i&&this.config.shareApiBaseUrl)try{s=await this.generateShareLink(i),this.log("info","PIPELINE_SHARE_OK","Share link generated",{share_id:s})}catch(a){this.log("warn","PIPELINE_SHARE_FAILED","Share link failed",{error:String(a)})}if(n&&r){let a=null;t("zip","running");try{await n.sealFn({testcaseId:i,shareId:s}),a=n.sealedPackPath?await Lt(n.sealedPackPath):await Re(n.executionId,n.cwd),this.log("info","PIPELINE_EVIDENCE_SEALED","Evidence pack sealed",{execution_id:n.executionId}),this.log("info","PIPELINE_PACK_READ","Sealed pack read",{size_mb:+(a.length/1024/1024).toFixed(1)})}catch(c){let u=c instanceof Error?c.message:String(c);this.log("warn","PIPELINE_EVIDENCE_UPLOAD_SKIPPED","Evidence seal/read failed \u2014 uploading blob only",{execution_id:n.executionId,error:u})}if(a){t("zip","done",`${(a.length/1024/1024).toFixed(1)}MB`),t("presign","running");let c=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[Pe(n.executionId),{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);this.log("info","PIPELINE_PRESIGN_OK","Presigned URLs received",{artifacts_url:c.urls.artifacts?.blob_url,blob_url:c.urls.blob?.blob_url}),t("presign","done"),t("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading pack and blob",{artifact_size_mb:+(a.length/1024/1024).toFixed(1),blob_size_kb:+(r.length/1024).toFixed(1)}),await Promise.all([k(c.urls.artifacts.upload_url,a,"application/zip"),k(c.urls.blob.upload_url,r,"application/json")]),this.log("info","PIPELINE_UPLOAD_OK","Upload complete"),t("upload","done")}else{t("zip","skipped"),t("presign","running");let c=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);t("presign","done"),t("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading blob only (evidence skipped)",{blob_size_kb:+(r.length/1024).toFixed(1)}),await k(c.urls.blob.upload_url,r,"application/json"),this.log("info","PIPELINE_UPLOAD_OK","Blob upload complete (pack skipped)"),t("upload","done")}}let o;if(this.config.codeExport?.enabled&&i){let a=!1;try{await this.triggerCodeExport(i),this.log("info","PIPELINE_CODE_EXPORT_START","Code export triggered"),a=!0}catch(c){let u=c instanceof Error?c.message:String(c);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export trigger failed; skipping poll",{error:u}),t("code_export","failed",`trigger failed: ${u}`)}if(a){t("code_export","running","Waiting for code generation\u2026");try{o=await this.pollAndDownloadCode(i,t),this.log("info","PIPELINE_CODE_EXPORT_OK","Code export complete",{dir:o}),t("code_export","done",o)}catch(c){let u=c instanceof Error?c.message:String(c);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export failed",{error:u}),t("code_export","failed",u)}}}else t("code_export","skipped");return this.log("info","PIPELINE_COMPLETE","Pipeline complete"),{success:!0,testId:this.testId,testcaseId:i,shareId:s,codeExportDir:o}}catch(n){return{success:!1,testId:this.testId,error:n instanceof Error?n.message:String(n)}}}async stop(t,n){let r=this.config.attachedStop?this.config.stopRetryDelaysMs??we:[];for(let i=0;;i++)try{return await t.endTest(this.testId,n)}catch(s){if(!(s instanceof Z&&(s.status===null||s.status>=500)&&i<r.length))throw s;this.log("warn","PIPELINE_FINALIZE_RETRY","Attached test's stop sent again",{attempt:i+1,status:s.status}),await new Promise(a=>setTimeout(a,r[i]))}}async runCodeExport(t,n){let r=n??this.config.onProgress,i=!1;try{await this.triggerCodeExport(t),this.log("info","PIPELINE_CODE_EXPORT_TRIGGER","Code export triggered",{testcase_id:t}),i=!0}catch(s){let o=s instanceof Error?s.message:String(s);this.log("error","PIPELINE_CODE_EXPORT_TRIGGER_FAILED","Code export trigger failed; skipping poll",{error:o}),r("code_export","failed",`trigger failed: ${o}`)}if(i){r("code_export","running","Waiting for code generation\u2026");try{let s=await this.pollAndDownloadCode(t,r);return this.log("info","PIPELINE_CODE_EXPORT_OK","Code export complete",{dir:s}),r("code_export","done",s),s}catch(s){let o=s instanceof Error?s.message:String(s);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export failed",{error:o}),r("code_export","failed",o);return}}}deriveArchivedAttemptBlobs(t){try{let n=Rt(t,{readActions:r=>this.readNdjsonFromFile(r),buildBlob:r=>this.buildExecutionEnvelope(r),objective:this.config.firstObjective,screenshotBaseUrl:this.config.screenshotBaseUrl??"",extMap:this.config.screenshotExtMap,log:(r,i,s,o)=>this.log(r,i,s,o)});n>0&&this.log("info","PIPELINE_ARCHIVED_ATTEMPTS","Nested retry-attempt blobs derived",{count:n})}catch(n){this.log("debug","PIPELINE_ARCHIVED_ATTEMPTS_FAILED","Nested attempt blob pass failed",{error:n instanceof Error?n.message:String(n)})}}collectNdjsonPerRun(){let t=[],n=this.config.runObjectives??[],r=this.config.runMetadata??[],i=this.config.evidence??this.config.evidenceRead;for(let s=0;s<this.config.runDirs.length;s++){let o=this.config.runDirs[s],a=n[s]||this.config.firstObjective,c=r[s],u=i?this.readNdjsonFromFile(y(i.packTestDir,"logs",`${i.runIndices?.[s]??s}-actions.ndjson`)):this.readNdjsonFromDir(o);if(u.length>0){let l=i?.runIndices?.[s]??s,_=this.config.runFlatIndex?.[l];t.push({objective:a,records:u,..._!==void 0?{flatIndex:_}:{},resultCode:c?.resultCode,reasonCode:c?.reasonCode,errorMessage:c?.errorMessage,summary:c?.summary,oneLiner:c?.oneLiner})}}if(t.length===0){let s=y(this.config.sessionDir,"runs");if(H(s))try{let a=Ae(s,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name).sort();for(let c of a){let u=y(s,c),l=this.readNdjsonFromDir(u);l.length>0&&t.push({objective:this.config.firstObjective,records:l})}}catch{}}return t}readNdjsonFromDir(t){let n=[y(t,"run-test","actions.ndjson"),y(t,"actions.ndjson")];for(let r of n)if(H(r))return this.readNdjsonFromFile(r);return[]}readNdjsonFromFile(t){let n=[];if(!H(t))return n;this.log("debug","PIPELINE_COLLECT_READ","Reading NDJSON file",{path:t});let r=L(t,"utf-8");for(let i of r.split(`
|
|
5
|
-
`)){let s=i.trim();if(s)try{n.push(JSON.parse(s))}catch{}}return n}async generateShareLink(t){let n=`${this.config.shareApiBaseUrl}/lshs/api/v1.0/share-item/generate-sharable-link`;this.log("info","PIPELINE_SHARE_START","Requesting share link",{url:n,testcase_id:t});let r={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({entityIds:[t],entityType:"Test Case Details",expiresAt:7})},i=!!this.config.authResolver;this.log("debug","PIPELINE_SHARE_AUTH","Share link auth config",{resolver:i,fallback_auth_type:typeof this.config.auth=="string"?"bearer":"basic",tms_user:this.config.tmsUsername});let s=i?await this.config.authResolver.fetch(n,r):await R(n,{...r,headers:{...r.headers,Authorization:this.buildAuthHeader()}});if(!s.ok)throw new Error(`Share link API failed: ${s.status} ${await s.text()}`);let o=await s.json();if(!o.shareId)throw new Error("Share link API returned no shareId");return o.shareId}async triggerCodeExport(t){if(!this.config.codeExport)throw new Error("triggerCodeExport called without resolved codeExport config");let{url:n,body:r}=rt({tmsBaseUrl:this.config.tmsBaseUrl,testcaseId:t,codeExport:this.config.codeExport,mobile:this.config.mobile});this.log("info","PIPELINE_CODE_EXPORT_POST","Triggering code export",{url:n});let i={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)},s=this.config.authResolver?await this.config.authResolver.fetch(n,i):await R(n,{...i,headers:{...i.headers,Authorization:this.buildAuthHeader()}});if(!s.ok)throw new Error(`Code export failed: ${s.status} ${await s.text()}`)}async pollAndDownloadCode(t,n){let r=st({tmsBaseUrl:this.config.tmsBaseUrl,testcaseId:t}),i=this.config.exitTimeoutMs??3e5,s=5e3,o=Date.now()+i;this.log("info","PIPELINE_CODE_EXPORT_POLL","Polling for code export",{url:r,timeout_ms:i});let a=(c,u)=>this.config.authResolver?this.config.authResolver.fetch(c,u):R(c,{...u,headers:{...u?.headers,Authorization:this.buildAuthHeader()}});for(;Date.now()<o;){let c=await a(r,{method:"GET",headers:{Accept:"application/json"}});if(!c.ok){let d=await c.text().catch(()=>"");throw this.log("warn","PIPELINE_CODE_EXPORT_POLL_FAILED","Code export poll non-200; skipping",{status:c.status,body:d.slice(0,200)}),new Error(`code export poll skipped: HTTP ${c.status}`)}let l=(await c.json()).data?.find(d=>d.code_name==="kane-cli-trigger");if(!l){this.log("debug","PIPELINE_CODE_EXPORT_WAITING","No kane-cli-trigger entry yet"),n("code_export","running","Waiting for code generation\u2026"),await this.sleep(s);continue}let _=l.status.toLowerCase();if(_==="in progress"||_==="in_progress"||_==="pending"){this.log("debug","PIPELINE_CODE_EXPORT_IN_PROGRESS","Code export in progress",{status:l.status}),n("code_export","running","Generating code\u2026"),await this.sleep(s);continue}if(!l.url||l.url.length===0)throw new Error(`Code export status=${l.status} but no files returned`);let p=this.config.codeExportDir??y(this.config.sessionDir,"code-export");J(p,{recursive:!0}),this.log("info","PIPELINE_CODE_EXPORT_DOWNLOAD","Downloading code files",{file_count:l.url.length,dir:p}),n("code_export","running",`Downloading ${l.url.length} files\u2026`);for(let d of l.url){let g=y(p,d.file_name),f=await R(d.file_url);if(!f.ok){this.log("warn","PIPELINE_CODE_EXPORT_FILE_FAILED","Failed to download file",{file_name:d.file_name,status:f.status});continue}let m=await f.text();S(g,m,"utf-8"),this.log("info","PIPELINE_CODE_EXPORT_FILE_SAVED","File saved",{file_name:d.file_name,size_bytes:m.length})}return p}throw new Error("Code export timed out")}sleep(t){return new Promise(n=>setTimeout(n,t))}buildAuthHeader(){return typeof this.config.auth=="string"?`Bearer ${this.config.auth}`:W(this.config.auth.username,this.config.auth.accessKey)}readAuthoredExecution(){let t=this.config.authoredExecutionPath;if(!t)return null;try{let n=L(t,"utf8");return JSON.parse(n),n}catch{return this.log("warn","PIPELINE_AUTHORED_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 pack gets this run's envelope",{path:t}),null}}refreshReplayOnlyInPack(t,n,r){if(!r)return{raw:t,refreshed:[]};let i=at(n,r);if(i.length===0)return{raw:t,refreshed:[]};let s=JSON.parse(t);if(!Array.isArray(s.instructions))return{raw:t,refreshed:[]};let o=ct(s.instructions,i);return o.length===0?{raw:t,refreshed:o}:{raw:JSON.stringify(s,null,2),refreshed:o}}loadAuthoredBlocks(){let t=this.config.blockAuthoredExecutionPath;if(!t)return[];try{let n=JSON.parse(L(t,"utf8"));return Array.isArray(n.instructions)?n.instructions:[]}catch(n){return this.log("warn","PIPELINE_AUTHORED_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 branches that did not run this time upload empty",{path:t,error:n instanceof Error?n.message:String(n)}),[]}}loadReplayOnlyPassthrough(){let t=this.config.replayOnlyPassthrough;if(!(!t||t.flatIndices.length===0))try{let n=JSON.parse(L(t.authoredExecutionPath,"utf8"));if(!Array.isArray(n.instructions))throw new Error("no instructions array");return{authoredInstructions:n.instructions,replayOnlyFlatIndices:new Set(t.flatIndices)}}catch(n){this.log("warn","PIPELINE_PASSTHROUGH_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 replay-only steps convert from this run's records",{path:t.authoredExecutionPath,flat_indices:t.flatIndices,error:n instanceof Error?n.message:String(n)});return}}smartuiProject(t){let n=this.config.evidence??this.config.evidenceRead,r=this.config.runDirs.map((s,o)=>n?y(n.packTestDir,"logs",`${n.runIndices?.[o]??o}-run_meta.json`):y(s,"run_meta.json"));return{...wt({runMetaPaths:r,authoredBlobPath:this.config.replayOnlyPassthrough?.authoredExecutionPath??this.config.authoredExecutionPath,instructions:t})}}buildExecutionEnvelope(t){let n=this.config.runStatuses.every(u=>u==="passed")?"success":"error",r=this.config.variableIds??{},i=[];if(this.config.variables)for(let[u,l]of Object.entries(this.config.variables)){if(l.secret||tt(l))continue;let _=u.startsWith("global.")?u.slice(7):u;i.push({id:r[_]??0,name:_,value:l.value,session_value:l.value,is_persist:!1,environment_id:0,environment_name:"No Env"})}let s=[],o=u=>{let l=s.find(_=>_.name===u.name);l?l.value=u.value:s.push(u)},a=[],c=new Set;for(let u of this.collectNdjsonPerRun())for(let l of u.records)if(l.output_variable&&l.output_value!=null&&o({name:l.output_variable,value:String(l.output_value),value_type:"test_level",variable_description:"ANALYZE result"}),l.action_type==="upload_files"){let _=N(l.action_params);if(_){let p=_.media_id||_.media_url;if(!c.has(p)){c.add(p),a.push({media_url:_.media_url,media_id:_.media_id,name:_.name,type:_.type,..._.alias?{alias:_.alias}:{}});let d=O(_.name);_.alias?o({name:z(_.alias),type:"file",value:d,value_type:"string",scope:_.alias.startsWith("local.")?"local":"global",media_id:_.media_id}):o({name:dt(_.name),value:d,value_type:"string",variable_description:`variable for ${d}`})}}}return{test_id:this.testId,version:"v4",auto_heal_version:this.config.apMode==="v2"?"AH2":"",session_id:this.config.sessionId,org_id:String(this.config.orgId),user_id:String(this.config.userId),url:this.config.firstUrl??"",start_timestamp:this.config.startedAt,end_timestamp:this.config.endedAt,status:n,commit_id:this.config.commitId,instructions:t,modules:[],uploaded_files:a,test_params:this.config.testParams??[],test_level_variables:JSON.stringify(s),test_global_variables:i,max_network_wait:0,wait_buffer:0,network_throttle:{},secrets:this.config.secrets??[],totp:[],environment_id:this.config.environmentId??0,environment:"",mobile_browser:!1,native_popups:[],smartui:this.smartuiProject(t),module_index:0}}};export{qe as a,Ge as b,Re as c,Pe as d,we as e,Tt as f};
|
package/dist/chunk-NZJSGINB.js
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{c as Nt}from"./chunk-N7IWR45S.js";import{a as ut,b as ct}from"./chunk-VCVEZEVS.js";import{b as bt,c as yt,d as vt,e as _t,f as kt}from"./chunk-ERRIDBE7.js";import{a as xt,b as Rt,c as Et,d as St,e as It}from"./chunk-3ZC7GSMM.js";import{c as q,d as Ie,f as Lt,g as jt,k as Ot,l as ce,m as pe,q as J,v as Ut}from"./chunk-OTMHCHH6.js";import{b as Ee,d as se}from"./chunk-ZUZ6QJRA.js";import{b as Se,c as pt,d as dt,e as mt,f as ie,g as ae,h as ft,i as gt,j as ht,k as wt,m as h,n as X,o as At,p as je,q as Te,r as Ce,s as Pe}from"./chunk-ZMIKNNO6.js";import{a as le,b as S}from"./chunk-KGNE5CIM.js";import{e as W,l as ue,n as Le,q as Tt,r as Ct,s as Pt,t as $t}from"./chunk-NPAUSUNM.js";import{a as it,b as at}from"./chunk-BJO6J5X2.js";import{d as Re,f as H}from"./chunk-OOGKX4Y6.js";import{a as ot}from"./chunk-Q4SMITTV.js";import{l as lt}from"./chunk-4CJQ7XZP.js";import{a as rt}from"./chunk-DREQ3RAA.js";import{a as st}from"./chunk-UTM7D4PI.js";import{a as et,b as ke,d as tt}from"./chunk-ULIIYKZB.js";import{b as Ze}from"./chunk-LV7224DG.js";import{e as Qe}from"./chunk-OCVDMZWB.js";import{b as ze}from"./chunk-F2F257PU.js";import{e as Ye}from"./chunk-SB26HQO7.js";import{a as qe}from"./chunk-FCD3NYOM.js";import{a as nt}from"./chunk-PVN64537.js";import{n as Xe,o as Je}from"./chunk-UJLULWSR.js";import{a as oe}from"./chunk-ZCBOHWN3.js";import{a as K}from"./chunk-4QTH7VYE.js";import{a as F}from"./chunk-RZ4F3BHX.js";import{a as ne}from"./chunk-TM45NPWL.js";import{a as We}from"./chunk-FOJHSG5M.js";import{a as M,b as re,z as Ke}from"./chunk-J4FIESTB.js";import{join as Ne}from"path";import{appendFileSync as sr,mkdirSync as ir}from"fs";import{dirname as ar}from"path";function Bt(e,t,n){if(t)try{ir(ar(t),{recursive:!0})}catch{}let r="",o=c=>{if(!(!t||!c))try{sr(t,n(c))}catch{}};e.child.stderr?.on("data",c=>{r+=c.toString();let g=r.lastIndexOf(`
|
|
3
|
-
`);g<0||(o(r.slice(0,g+1)),r=r.slice(g+1))}),e.child.stderr?.on("end",()=>{o(r),r=""});let i=e.getStderr.bind(e);return Object.assign(e,{getStderr:()=>n(i())})}var lr={seeding:"seeding",replay:"replaying",walking:"walking",settling:"settling",verifying:"verifying"},ur=8,cr=6,k=e=>typeof e=="string"&&e?e:null,V=e=>typeof e=="number"&&Number.isFinite(e)?e:null,de=class{s={run_id:null,exploration_id:null,status:"running",stop_reason:null,progress:null,browsers:[],version:0,updated_at:0};subs=new Set;now;constructor(t={}){this.now=t.now??Date.now}snapshot(){return structuredClone(this.s)}subscribe(t){return this.subs.add(t),()=>{this.subs.delete(t)}}end(t){this.s.status!=="ended"&&(this.s.status="ended",this.s.stop_reason=t,this.s.browsers=[],this.changed())}apply(t){this.reduce(t)&&this.changed()}changed(){if(this.s.version+=1,this.s.updated_at=this.now(),!this.subs.size)return;let t=this.snapshot();for(let n of this.subs)try{n(t)}catch{}}browser(t,n){let r=this.s.browsers.find(o=>o.worker===t)??null;return!r&&n&&(r={worker:t,state:"opening",since:this.now(),lease:null,step:null,steps:[],trail:[],held:null},this.s.browsers.push(r),this.s.browsers.sort((o,i)=>o.worker-i.worker)),r}setState(t,n){t.state!==n&&(t.state=n,t.since=this.now())}reduce(t){let n=V(t.worker_index);switch(t.type){case"explore_start":return this.s.run_id=k(t.run_id),this.s.exploration_id=k(t.exploration_id),this.s.status="running",!0;case"browser_request":return n===null?!1:(this.browser(n,!0),!0);case"browser_release":{if(n===null)return!1;let r=this.s.browsers.length;return this.s.browsers=this.s.browsers.filter(o=>o.worker!==n),this.s.browsers.length!==r}case"lease_start":{if(n===null||!k(t.lease_id))return!1;let r=this.browser(n,!0),o=t.reach&&typeof t.reach=="object"&&!Array.isArray(t.reach)?t.reach:null;return r.lease={id:String(t.lease_id),kind:String(t.kind??""),target:k(t.target),reach:o,started_at:this.now()},r.step=null,r.steps=[],this.setState(r,"starting"),!0}case"lease_step":{if(n===null)return!1;let r=this.browser(n,!1);if(!r||!r.lease||r.lease.id!==t.lease_id)return!1;let o={ordinal:V(t.ordinal)??r.steps.length,phase:String(t.phase??""),intent:k(t.intent),junction_id:k(t.junction_id),known:t.known===!0,url_pattern:k(t.url_pattern),flow_id:k(t.flow_id),navigated:t.navigated===!0,at:this.now()};return r.step=o,r.steps=[...r.steps,o].slice(-ur),o.junction_id&&r.trail[r.trail.length-1]!==o.junction_id&&(r.trail=[...r.trail,o.junction_id].slice(-cr)),this.setState(r,lr[o.phase]??"walking"),!0}case"lease_end":{let r=this.s.browsers.find(o=>o.lease?.id===t.lease_id);return r?(r.lease=null,r.step=null,r.steps=[],this.setState(r,r.held?"holding":"idle"),!0):!1}case"session_held":{if(n===null)return!1;let r=this.browser(n,!0);return r.held={kind:String(t.kind??""),start_flow:k(t.start_flow),junction_id:k(t.junction_id),url_pattern:k(t.url_pattern)},r.lease||this.setState(r,"holding"),!0}case"session_released":{if(n===null)return!1;let r=this.browser(n,!1);return!r||!r.held?!1:(r.held=null,r.lease||this.setState(r,"idle"),!0)}case"progress":return this.s.progress={frontier:V(t.frontier)??0,visited:V(t.visited)??0,active_workers:V(t.active_workers)??0,elapsed_s:V(t.elapsed_s)??0},!0;case"explore_control":return t.control!=="stop"||this.s.status!=="running"?!1:(this.s.status="paused",!0);case"explore_end":return this.s.status="ended",this.s.stop_reason=k(t.stop_reason),this.s.browsers=[],!0;default:return!1}}};var me=class{link=null;wanted=new Map;source=async(t,n)=>(this.wanted.set(t,n),this.link?.start(t),{stop:async()=>{this.wanted.get(t)===n&&(this.wanted.delete(t),this.link?.stop(t))}});attach(t){if(this.link=t,t)for(let n of this.wanted.keys())t.start(n)}frame(t,n){this.wanted.get(t)?.(n)}};var pr=500,dr=1e4,Mt=5e3,mr=async(e,t)=>{let n=new AbortController,r=()=>n.abort(),o=setTimeout(r,t.timeoutMs);t.signal.addEventListener("abort",r,{once:!0});try{let i=await F(e,{method:"POST",headers:t.headers,body:t.body,signal:n.signal}),c=null;try{c=await i.json()}catch{}return{status:i.status,body:c}}finally{clearTimeout(o),t.signal.removeEventListener("abort",r)}},fe=class{constructor(t){this.opts=t;this.post=t.post??mr,this.unsubscribeModel=t.model.subscribe(()=>this.stateChanged())}post;target=null;off=!1;framesOff=!1;abort=new AbortController;unsubscribeModel;stateInFlight=!1;stateDirty=!1;lastStateAt=0;stateTimer=null;heartbeat=null;watched=new Map;stopAsked=!1;waiting=new Map;sending=new Set;arm(t){this.off||(this.letAllGo(),this.abort.abort(),this.abort=new AbortController,this.stateInFlight=!1,this.target=t,this.framesOff=!1,this.stateDirty=!0,this.sendState())}async close(){this.off=!0,this.unsubscribeModel(),this.clearTimers(),this.letAllGo(),this.abort.abort()}url(t,n=""){let r=this.target;return`${r.baseUrl.replace(/\/+$/,"")}${n}/exploration/${encodeURIComponent(r.explorationId)}/runs/${encodeURIComponent(r.runId)}/live/${t}`}stateChanged(){if(this.off||!this.target||(this.stateDirty=!0,this.stateInFlight||this.stateTimer))return;let t=pr-(Date.now()-this.lastStateAt);t<=0?this.sendState():this.stateTimer=setTimeout(()=>{this.stateTimer=null,this.sendState()},t)}sendState(){if(this.off||!this.target||this.stateInFlight)return;let t=this.target;this.stateDirty=!1,this.stateInFlight=!0,this.lastStateAt=Date.now(),this.heartbeat&&clearTimeout(this.heartbeat),this.heartbeat=null;let n;try{n=JSON.stringify(this.opts.model.snapshot())}catch{this.stateInFlight=!1;return}this.post(this.url("state"),{headers:{Authorization:t.authHeader,"Content-Type":"application/json"},body:n,timeoutMs:Mt,signal:this.abort.signal}).then(r=>{if(this.target===t){if(r.status===404||r.status===403||r.status===401)return this.turnOff(r.status);r.status>=200&&r.status<300&&(this.stopIfAsked(r.body),this.follow(r.body))}},()=>{}).finally(()=>{this.target!==t||this.off||(this.stateInFlight=!1,this.heartbeat=setTimeout(()=>{this.heartbeat=null,this.stateDirty=!0,this.sendState()},dr),this.stateDirty&&this.stateChanged())})}turnOff(t){this.off||(this.off=!0,this.clearTimers(),this.letAllGo(),this.abort.abort(),this.opts.onWarn?.(`live view is off for this run: the controller has no live routes (HTTP ${t})`))}stopIfAsked(t){this.stopAsked||!t||typeof t!="object"||t.stop!==!0||(this.stopAsked=!0,this.opts.onStop?.())}follow(t){let n=t&&typeof t=="object"?t.watched:void 0;if(!Array.isArray(n)||this.framesOff)return;let r=new Set(n.filter(o=>Number.isInteger(o)&&o>=0));for(let o of[...this.watched.keys()])r.has(o)||this.letGo(o);for(let o of r)this.watched.has(o)||this.watched.set(o,this.opts.frames.subscribe(new Map([[o,Et]]),i=>this.frame(i)))}frame(t){t.kind!=="frame"||this.off||!this.watched.has(t.worker)||(this.waiting.set(t.worker,{data:t.data,at:t.at}),this.sendFrame(t.worker))}sendFrame(t){if(this.sending.has(t)||!this.target)return;let n=this.waiting.get(t);if(n===void 0)return;this.waiting.delete(t);let r=this.target;this.sending.add(t);let o=Number.isFinite(n.at)?`&at=${Math.round(n.at)}`:"";this.post(`${this.url("frames","/public")}?worker=${t}${o}`,{headers:{"X-Live-Token":r.liveToken,"Content-Type":"image/jpeg"},body:Buffer.from(n.data,"base64"),timeoutMs:Mt,signal:this.abort.signal}).then(i=>{this.target===r&&(i.status===410?this.letGo(t):i.status===401&&!this.framesOff&&(this.framesOff=!0,this.letAllGo(),this.opts.onWarn?.("live frames are off for this run: the controller refused its live token (HTTP 401)")))},()=>{}).finally(()=>{this.target===r&&(this.sending.delete(t),!this.off&&this.watched.has(t)&&this.sendFrame(t))})}letGo(t){let n=this.watched.get(t);this.watched.delete(t),this.waiting.delete(t),n?.()}letAllGo(){for(let t of[...this.watched.keys()])this.letGo(t);this.sending.clear()}clearTimers(){this.stateTimer&&clearTimeout(this.stateTimer),this.heartbeat&&clearTimeout(this.heartbeat),this.stateTimer=this.heartbeat=null}};function ge(e,t){return`watch live: kane-cli explore view --exploration-id ${e}${t?` --env ${t}`:""}`}async function Ht(e){let t=new de,n=new me,r=new Rt({start:e.startSource??n.source}),o=new fe({model:t,frames:r,post:e.post,onWarn:e.onWarn,onStop:e.onStop}),i=!1,c=!1,g=!1;return{model:t,frames:r,onBrowser(a){c||r.addBrowser(a)},offBrowser(a){r.removeBrowser(a)},attachRunner(a){n.attach(c?null:a)},runnerFrame(a,u){c||n.frame(a,u)},onEvent(a){t.apply(a),a.type==="explore_start"&&!i&&typeof a.exploration_id=="string"&&a.exploration_id&&(i=!0,e.onExploration?.(a.exploration_id))},armRun(a){if(!c){if(!a.liveToken){g||e.onWarn?.("live view is off for this run: the controller handed out no live token"),g=!0;return}o.arm({...e.controller,explorationId:a.explorationId,runId:a.runId,liveToken:a.liveToken})}},async close(a){c||(c=!0,await o.close(),n.attach(null),t.end(a),await r.close())}}}import{readFileSync as gr}from"fs";import{basename as hr}from"path";import{randomUUID as Wt}from"crypto";function $e(e){let t=[];for(let[n,r]of Object.entries(e)){if(r.type==="parameter")continue;let o=n.replace(/^(secrets\.user\.|global\.|environment\.)/,"");t.push({name:o,secret:!!r.secret,value:String(r.value??"")})}return t}async function Vt(e,t){if(t.activeRun){let u=null;try{u=await t.activeRun()}catch{u=null}if(u)return{ok:!1,error:`RUN_ACTIVE: run ${u.runId} is ${u.state} on exploration ${u.explorationId}; stop it or wait for it to end`}}let n=e.variables.filter(u=>u.secret),r=e.variables.filter(u=>!u.secret),o=[["LT_USERNAME",e.login.username],["LT_ACCESS_KEY",e.login.accessKey],...n.map(u=>[u.name,u.value])];for(let[u,l]of o){if(e.dev?.skipPush===u){e.onNote?.(`dev: not pushing secret ${u} (KANE_EXPLORE_DEV_SKIP_SECRET_PUSH)`);continue}try{await t.pushSecret(u,l)}catch(f){return{ok:!1,error:`could not push secret ${u} to HyperExecute Secrets: ${z(f)}`}}}for(let u of r)try{await t.upsertGlobal(u.name,u.value)}catch(l){return{ok:!1,error:`could not push variable ${u.name} to Test Manager: ${z(l)}`}}let i=o.map(([u])=>u);if(e.dev?.skipCheck)return e.onNote?.("dev: not checking the HyperExecute secrets list (KANE_EXPLORE_DEV_SKIP_SECRET_CHECK); the VM's check must refuse a missing secret"),a();let c;try{c=await t.hxSecretNames(i)}catch(u){return{ok:!1,error:`could not read your HyperExecute secrets to check them: ${z(u)}`}}let g=i.filter(u=>!c.includes(u));if(g.length)return{ok:!1,error:`HyperExecute Secrets does not list ${g.join(", ")} after the push; the VM would run without ${g.length===1?"it":"them"}`};return a();async function a(){let u=e.body;if(e.devBundle)try{let{kane_version:l,...f}=e.body;u={...f,dev:await e.devBundle()}}catch(l){return{ok:!1,error:`--dev-bundle: could not upload the bundle: ${z(l)}`}}try{return{ok:!0,reply:await t.remoteRun({...u,variables:e.variables.map(f=>({name:f.name,secret:f.secret}))})}}catch(l){if(l instanceof le&&l.code==="SECRETS_MISSING"){let f=l.body??{};return{ok:!1,secretsMissing:!0,error:typeof f.error=="string"&&f.error?f.error:"HyperExecute refused the job: a secret it names is missing",explorationId:typeof f.exploration_id=="string"?f.exploration_id:null,runId:typeof f.run_id=="string"?f.run_id:null}}return{ok:!1,error:`could not launch the remote run: ${z(l)}`}}}}async function Dt(e,t,n){let r={Authorization:K(t.username,t.accessKey),Accept:"application/json"},o=new URLSearchParams({username:t.username});for(let a of n)o.append("secretKey",a);let i=await F(`${e}/logistics/v1.0/all-secrets/list?${o}`,{method:"GET",headers:r});if(i.status===404&&(i=await F(`${e}/logistics/v1.0/secrets/list/${encodeURIComponent(t.username)}`,{method:"GET",headers:r})),!i.ok)throw new Error(`HTTP ${i.status}`);let c=null;try{c=await i.json()}catch{c=null}let g=fr(c);return n.filter(a=>g.has(a))}function fr(e){let t=new Set,n=e&&typeof e=="object"?e:{},r=Array.isArray(n.Data)?n.Data:Array.isArray(n.data)?n.data:Array.isArray(e)?e:[];for(let o of r)if(typeof o=="string")t.add(o);else if(o&&typeof o=="object"){let i=o,c=i.key??i.secretKey??i.Key??i.name;typeof c=="string"&&t.add(c)}return t}var Gt=["allowDomain","deny","allowPost","depthCaps","slowBudget","recheck","focus","hpsRegion","tunnel","tunnelName"];function Ae(e,t){let n={};t&&(n.deps=t);for(let r of Gt){let o=e[r];o===void 0||Array.isArray(o)&&!o.length||(n[r]=o)}return n}function Ft(e){let t=e.args&&typeof e.args=="object"?e.args:{},n={url:e.url,prompt:e.prompt,browser:"remote",headless:!0};typeof e.max_parallel=="number"&&e.max_parallel>0&&(n.maxParallel=e.max_parallel),typeof e.max_leases=="number"&&e.max_leases>0&&(n.maxLeases=e.max_leases),Array.isArray(e.allowed_domains)&&(n.allowDomain=e.allowed_domains),typeof e.policy=="string"&&e.policy&&(n.policy=e.policy);for(let r of Gt)t[r]!==void 0&&(n[r]=t[r]);return typeof t.deps=="string"&&t.deps&&(n.depsText=t.deps),n}function Kt(e,t){let n={},r=[];for(let o of e){if(!o.secret){n[o.name]={value:"",secret:!1};continue}let i=t[o.name];if(!i||i.includes("${{.secrets.")){r.push(o.name);continue}n[o.name]={value:i,secret:!0}}return r.length?{ok:!1,missing:r}:{ok:!0,variables:n}}function z(e){return e instanceof Error?e.message:String(e)}function qt(e){let t=$e(e.variables).map(n=>({name:n.name,secret:n.secret}));return{url:e.url,prompt:e.prompt,policy:e.policy??ue,...t.length?{variables:t}:{},...e.maxParallel?{max_parallel:e.maxParallel}:{},...e.maxLeases?{max_leases:e.maxLeases}:{},args:Ae({...e.opts,allowDomain:e.allowedDomains},e.depsText)}}function wr(e){let t={},n=(e.KANE_EXPLORE_DEV_SKIP_SECRET_PUSH??"").trim();return n&&(t.skipPush=n),(e.KANE_EXPLORE_DEV_SKIP_SECRET_CHECK??"").trim()==="1"&&(t.skipCheck=!0),t}async function xr(e,t){let n=gr(t),r=new qe(e.controllerBaseUrl,{username:e.basic.username,accessKey:e.basic.access_key}),o=`${Wt()}-${hr(t)}`,c=(await r.getPresignedUrls("explore-dev",Wt(),[{key:"bundle",content_type:"application/gzip",filename:o}])).urls.bundle;if(!c)throw new Error("the presign reply named no URL for the bundle");return await st(c.upload_url,n,"application/gzip"),c.blob_url}function br(e){return{project_id:e.projectId,url:e.url,prompt:e.prompt,policy:e.policy??ue,...e.allowedDomains.length?{allowed_domains:e.allowedDomains}:{},...e.contextEnabled===!1?{context_enabled:!1}:{},...e.maxParallel?{max_parallel:e.maxParallel}:{},...e.maxLeases?{max_leases:e.maxLeases}:{},args:Ae(e.opts,e.depsText),kane_version:e.kaneVersion}}async function Xt(e,t){let n=new S({baseUrl:e.controllerBaseUrl,auth:e.basic}),r=new it(e.secretsBaseUrl),o=new at(e.tmsBaseUrl,e.basic.username,e.basic.access_key),i={username:e.basic.username,accessKey:e.basic.access_key},c=br(t),g=t.dev,a=await Vt({variables:$e(t.variables),login:i,body:c,...g?{dev:wr(process.env),onNote:u=>e.emit({type:"warning",message:u}),devBundle:async()=>({bundle_url:await xr(e,g.bundlePath),controller_url:g.controllerUrl})}:{}},{pushSecret:(u,l)=>r.pushSecret({secretKey:u,secretValue:l,username:i.username,accessKey:i.accessKey,orgId:e.orgId}),upsertGlobal:async(u,l)=>{await o.upsertVariable({name:u,value:l})},hxSecretNames:u=>Dt(e.secretsBaseUrl,i,u),remoteRun:u=>n.remoteRun(u),activeRun:async()=>{if(!t.projectId)return null;let l=(await n.listExplorations({state:"running",project:t.projectId,limit:1})).explorations.find(f=>f.project_id===t.projectId&&f.current_session);return l&&l.current_session?{explorationId:l.exploration_id,runId:l.current_session.run_id,state:l.current_session.state}:null}});if(!a.ok&&a.secretsMissing)return{ok:!1,error:a.error,exitCode:2,stopped:{explorationId:a.explorationId,runId:a.runId}};if(!a.ok){if(t.contextEnabled===!1&&_t(a.error))return{ok:!1,error:vt,exitCode:2};let u=/could not launch/.test(a.error)||a.error.startsWith("RUN_ACTIVE:");return{ok:!1,error:a.error,exitCode:u?1:2}}return e.emit({type:"explore_remote_started",exploration_id:a.reply.exploration_id,run_id:a.reply.run_id,state:a.reply.state,hx_job_id:a.reply.hx_job_id,job_link:a.reply.job_link,created:a.reply.created,policy:c.policy??ue}),t.contextEnabled===!1&&!a.reply.created&&e.emit({type:"warning",message:`exploration ${a.reply.exploration_id} already exists; its assurance context is unchanged \u2014 use \`kane-cli explore context off ${a.reply.exploration_id}\``}),e.terminal||(process.stderr.write(`exploration ${a.reply.exploration_id}, run ${a.reply.run_id}: queued on HyperExecute
|
|
4
|
-
`),a.reply.job_link&&process.stderr.write(`job: ${a.reply.job_link}
|
|
5
|
-
`),process.stderr.write(ge(a.reply.exploration_id,e.env)+`
|
|
6
|
-
`)),{ok:!0,explorationId:a.reply.exploration_id,runId:a.reply.run_id}}async function Jt(e,t,n,r){let o=new S({baseUrl:e.controllerBaseUrl,auth:e.basic}),i;try{i=await o.runRequest(t,n)}catch(l){let f=l instanceof le?l.code:"";return{ok:!1,error:`could not read run ${n}'s request${f?` (${f})`:""}: ${l.message}`,exitCode:2,stopped:!1}}let c=i.requested&&typeof i.requested=="object"?i.requested:{},g=Array.isArray(c.variables)?c.variables:[],a=Kt(g,r);if(!a.ok){let l=`secret${a.missing.length===1?"":"s"} ${a.missing.join(", ")} not set on this machine (HyperExecute Secrets has no value for ${a.missing.length===1?"it":"them"})`,f=W("secrets_missing",l);try{let y=await o.startRun(t,{run_id:n,sessions:1,client_release:M});await o.endRun(t,n,{remark:f,stop_reason:"secrets_missing",last_seq:y.next_seq-1,complete:!1,totals:{},unacked:0})}catch(y){return{ok:!1,error:`${l}; stopping the run also failed: ${y.message}`,exitCode:1,stopped:!1}}return{ok:!1,error:l,exitCode:1,stopped:!0}}return{ok:!0,opts:{...Ft({...c,url:c.url??i.target_url,prompt:c.prompt??i.prompt}),explorationId:t,claimRunId:n,variables:JSON.stringify(a.variables)}}}import{existsSync as Rr}from"fs";function he(e,t,n){let r=typeof e.explorationId=="string"?e.explorationId.trim():"";return r&&t?{explorationId:r}:n?{projectId:n}:null}function zt(e){let t=e.trim();try{let n=new URL(t);return`${n.protocol}//${n.host}${n.pathname.replace(/\/+$/,"")}${n.search}${n.hash}`}catch{return t.replace(/\/+$/,"").toLowerCase()}}function yr(e,t){return zt(e)===zt(t)}var vr=10;async function Oe(e,t){let n;for(let r=0;r<vr;r++){let o=await e.listExplorations({state:"all",limit:100,...n?{cursor:n}:{},..."projectId"in t?{project:t.projectId}:{}}),i=o.explorations.find(c=>"projectId"in t?c.project_id===t.projectId:c.exploration_id===t.explorationId);if(i)return i;if(!o.next_cursor)return null;n=o.next_cursor}return null}function _r(e){return`use a new --project for another site, or kane-cli explore delete ${e} first`}function Ue(e,t){let n=e.target_url??"";return!n||!t.trim()||yr(n,t)?null:{error:`--url ${t.trim()} is not exploration ${e.exploration_id}'s URL (${n}): one exploration per project explores one URL`,next:_r(e.exploration_id)}}var kr=e=>We.hex(Ke.dim)(e),Er=`error: --setup and --setup-check were replaced by --deps <plain language> (repeatable, or @file), which the recon runs once as its setup walk; see kane-cli explore run --help
|
|
7
|
-
`,Sr=`
|
|
8
|
-
One project has one exploration, of one URL: a re-run takes the exploration's
|
|
9
|
-
URL, and a different --url is refused (use a new --project for another site,
|
|
10
|
-
or kane-cli explore delete <id> first).
|
|
11
|
-
|
|
12
|
-
Examples:
|
|
13
|
-
# a project's first run, on HyperExecute (exits once the run is queued)
|
|
14
|
-
$ kane-cli explore run --project <id> --url https://example.com \\
|
|
15
|
-
--prompt "Explore checkout"
|
|
16
|
-
# run again: the URL is the project's exploration's
|
|
17
|
-
$ kane-cli explore run --project <id> --max-leases 40
|
|
18
|
-
# a read-only run on this machine
|
|
19
|
-
$ kane-cli explore run --project <id> --policy read_only --local-orchestration
|
|
20
|
-
# a local app, through your LT tunnel (start LT first)
|
|
21
|
-
$ kane-cli explore run --project <id> --url http://localhost:3000 \\
|
|
22
|
-
--tunnel-name dev
|
|
23
|
-
`;function Qt(e){let t=Number(e);if(!Number.isInteger(t)||t<1)throw new Ee("must be a positive integer");return t}function co(e){let t=e.command("explore").description("Explore an app into a map of its screens and flows").enablePositionalOptions().option("--exploration-id <id>",X({purpose:"On a terminal: open this exploration's card",values:"an id from kane-cli explore list --all",dflt:"pick a project first"})).option("--env <name>",Te).option("--username <user>",Ce).option("--access-key <key>",Pe).option("--agent",je).configureHelp({sortSubcommands:!0,...pe([{title:"Target",flags:["--exploration-id"]},{title:"Output",flags:["--agent","--help"]},{title:"Account",flags:["--env","--username","--access-key"]}])}).addHelpText("after",`
|
|
24
|
-
On a terminal, plain \`kane-cli explore\` opens the project picker, then the
|
|
25
|
-
exploration's card (run again, watch, stop, map, sessions, context, delete);
|
|
26
|
-
with --agent or a pipe it prints this help. Each command's --help lists its
|
|
27
|
-
options, grouped, with their values, defaults and examples.
|
|
28
|
-
`).action(async(n,r)=>{if(r.args.length>0&&r.error(`error: unknown command '${r.args[0]}'`,{exitCode:2}),ce(n,Ot()))return r.help();let{runExploreEntryAction:o}=await import("./explore-entry-E6EY3VV3.js");process.exitCode=await o(n)});t.command("run").description("Run one exploration of an app into its project's map: on HyperExecute by default (exits once the run is queued; stop it with explore stop), or on this machine with --local-orchestration. A terminal opens a setup form and a review first; --agent or a pipe gets NDJSON on stdout, done last").option("--url <url>",h("url")).option("--project <id>",h("project")).option("--exploration-id <id>",h("explorationId")).option("--prompt <text>",h("prompt"),"Explore the app").option("--max-leases <n>",h("maxLeases"),Qt).option("--max-parallel <n>",h("maxParallel"),Qt).option("--depth-caps <depth:cap,\u2026>",h("depthCaps")).option("--slow-budget <spec>",h("slowBudget")).option("--no-recheck",h("recheck")).option("--policy <policy>",h("policy")).option("--allow-domain <host>",h("allowDomain"),we,[]).option("--deny <name>",h("deny"),we,[]).option("--allow-post <host/path>",h("allowPost"),we,[]).option("--focus <screen>",h("focus")).option("--local-orchestration",h("localOrchestration")).option("--browser <where>",h("browser"),"local").option("--headless",h("headless")).option("--tunnel",h("tunnel")).option("--tunnel-name <name>",h("tunnelName")).option("--deps <text>",h("deps"),we,[]).option("--variables <json>",h("variables")).option("--variables-file <path>",h("variablesFile")).option("--no-context",h("context")).option("--agent",h("agent")).option("--env <name>",h("env")).option("--username <user>",h("username")).option("--access-key <key>",h("accessKey")).addOption(new se("--claim-run <run-id>","On a HyperExecute VM: take over this queued run (the job's own command; needs --exploration-id)").hideHelp()).addOption(new se("--dev-bundle <tgz>","Dev only: the VM installs this kane-cli bundle and talks to EXPLORE_DEV_CONTROLLER_URL").hideHelp()).addOption(new se("--hps-region <region>",`With remote browsers on prod: the regional host (${ae.join(", ")})`).hideHelp()).configureHelp(pe(At())).addHelpText("after",Sr).configureOutput({outputError:(n,r)=>r(/\'--setup(?:-check)?(?:=|\')/.test(n)?Er:n)}).action(async n=>{process.exitCode=await Or(n)}),t.command("view").description("Serve a live graph of an exploration's map on 127.0.0.1 (polls the service; Ctrl-C to stop)").option("--exploration-id <id>",X({purpose:"The exploration to view",values:"an id from kane-cli explore list --all"})).option("--project <id>",X({purpose:"View this project's exploration instead (a project has one)",values:"a project id"})).option("--port <n>",X({purpose:"The port on 127.0.0.1",values:"1-65535",dflt:"the first free of 7420-7429"}),Ir).option("--agent",je).option("--env <name>",Te).option("--username <user>",Ce).option("--access-key <key>",Pe).configureHelp(pe([{title:"Target",flags:["--exploration-id","--project"]},{title:"Server",flags:["--port"]},{title:"Output",flags:["--agent","--help"]},{title:"Account",flags:["--env","--username","--access-key"]}])).addHelpText("after",`
|
|
29
|
-
Name the exploration with --exploration-id or --project, not both.
|
|
30
|
-
|
|
31
|
-
Examples:
|
|
32
|
-
$ kane-cli explore view --project <id>
|
|
33
|
-
$ kane-cli explore view --exploration-id <id> --port 7430
|
|
34
|
-
`).action(async n=>{process.exitCode=await Nr(n)}),Ut(t),Nt(t),t.command("assurance-job",{hidden:!0}).description("One cut of an exploration into its project's assurance (the controller's job; input from the environment)").action(async()=>{let{runAssuranceJob:n}=await import("./assurance-job-F4L3T4VJ.js");process.exitCode=await n()})}function Ir(e){let t=Number(e);if(!Number.isInteger(t)||t<1||t>65535)throw new Ee("must be an integer 1-65535");return t}function we(e,t){return[...t,e]}function Yt(e){let t=new Set;for(let n of e){let r=n.trim().toLowerCase();if(r){try{r.includes("://")&&(r=new URL(r).hostname)}catch{}r=r.replace(/\/.*$/,"").replace(/^www\./,"").replace(/\.$/,""),r&&t.add(r)}}return[...t]}function Lr(e,t){if(e.some(r=>r.trim()==="*"))return{posts:["*"]};let n=new Set;for(let r of e){let o=r.trim();if(!o)continue;let i=y=>({error:`--allow-post ${JSON.stringify(o)}: ${y}; write it as host/path, e.g. api.example.com/v1/flags`});if(o.includes("://"))return i("no scheme");if(/[?#]/.test(o))return i("no query or fragment (the match is on host and path only)");if(o.includes("*"))return i("no partial wildcards (name the endpoint exactly, or pass a bare * for every POST)");if(/\s/.test(o))return i("no whitespace");let c=o.indexOf("/");if(c<=0)return i("a host followed by a path starting with /");let g=o.slice(0,c).toLowerCase(),a=o.slice(c),u=/^([^:]+?)\.?(?::(\d+))?$/.exec(g);if(!u)return i("an invalid host");let l=u[1],f=u[2]&&u[2]!=="80"&&u[2]!=="443"?`:${u[2]}`:"";if(g=l+f,!t.some(y=>l===y||l.endsWith(`.${y}`)))return i(`host ${l} is outside the run's domains (${t.join(", ")||"none"}); add it with --allow-domain first`);n.add(g+a)}return{posts:[...n]}}function jr(e){if(e===void 0)return{caps:{}};let t={};for(let n of e.split(",").map(r=>r.trim()).filter(Boolean)){let r=/^(\d+):(\d+)$/.exec(n);if(!r)return{error:`--depth-caps "${e}": each entry is depth:cap with whole numbers, e.g. 0:0,1:3,2:1`};t[String(Number(r[1]))]=Number(r[2])}return Object.keys(t).length?{caps:t}:{error:`--depth-caps "${e}": give at least one depth:cap pair`}}var Tr={response:"response_ms",page:"page_ready_ms",step:"step_ms"};function Cr(e){if(e===void 0)return{budgets:{}};let t={};for(let n of e.split(",").map(r=>r.trim()).filter(Boolean)){let r=/^(response|page|step)=(\d+(?:\.\d+)?)(s|ms)$/.exec(n);if(!r)return{error:`--slow-budget "${e}": each entry is response|page|step=<number>s or ms, e.g. response=3s,page=4s,step=2.5s`};let o=Math.round(Number(r[2])*(r[3]==="s"?1e3:1));if(o<1)return{error:`--slow-budget "${e}": a budget is more than 0`};t[Tr[r[1]]]=o}return Object.keys(t).length?{budgets:t}:{error:`--slow-budget "${e}": give at least one budget`}}function Zt(e){return e.context===!1?{contextEnabled:!1}:{}}var Pr="--tunnel on a remote run: the remote browsers reach your apps through the LT tunnel on this machine; keep it (and this machine) up until the run ends, or its pages fail to load";function Be(e){return async t=>{let n=await J(e,"explore run");return n.ok?Oe(new S({baseUrl:n.controllerBaseUrl,auth:n.basic,timeoutMs:5e3}),t):null}}async function rr(e){let t=typeof e.project=="string"?e.project:"";if(!t)return null;try{let n=await J(e,"explore run");if(!n.ok)return null;let r=oe(e.env??new ne().getDefaultEnv()??"prod"),o=new Ye(r.tmsBaseUrl,n.basic.username,n.basic.access_key);return await xt((async()=>{try{let c=await o.getProject(t);if(c?.name)return c.name}catch{}return(await o.listProjects()).find(c=>String(c.project_id)===t)?.name??null})(),4e3,()=>null)}catch{return null}}var $r=async(e,t=Be(e))=>{let n=null,r=typeof e.project=="string"?e.project:"",o=he(e,!!e.localOrchestration,r||null),i=null;if(o)try{i=await t(o)}catch{i=null}if(i){let g=Ue(i,typeof e.url=="string"?e.url:"");if(g){for(let a of Ie(g.error,g.next))process.stderr.write(a+`
|
|
35
|
-
`);return 2}n=i.target_url??null}let c=await(await import("./explore-run-tty-M56I23IF.js")).setupRunOpts(e,n,await rr(e));return"opts"in c?c.opts:c.code};function Ar(e){if(e.startsWith("RUN_ACTIVE:"))return"watch it (kane-cli explore view) or stop it (kane-cli explore stop) first \u2014 one run per exploration";if(/HyperExecute Secrets does not list/.test(e))return"check the secret's name in HyperExecute Secrets and your variables files, then launch again; or run it here with --local-orchestration";if(/a secret it names is missing|SECRETS_MISSING/.test(e))return"add the missing secret to your variables files (secret: true) and launch again";if(/REMOTE_UNAVAILABLE|503|could not launch the remote run|could not read your HyperExecute secrets|could not push/.test(e))return"try again in a minute, or run it on this machine with --local-orchestration"}async function Or(e,t,n={}){let r=ce(e,t),o=r?Re("explore"):null,i=s=>s,c=null,g=s=>{o?o.emit(i(s)):c?.(i(s))},a=s=>{o?H(i(s)):process.stderr.write(`${s.type}: ${i(s).message}
|
|
36
|
-
`)},u=s=>(g({...yt({state:s.state??null,remark:s.remark??null,exitCode:s.exitCode,explorationId:s.explorationId??null,runId:s.runId??null,committed:s.committed??0,pending:s.pending??0,lastSeq:s.lastSeq??0,stopReason:s.stopReason??null,complete:s.complete??!1,runDir:s.runDir??null,error:s.error}),...s.teardown?{teardown:s.teardown}:{},...s.credits?{credits:s.credits}:{},...typeof s.creditsConsumed=="number"?{credits_consumed:s.creditsConsumed}:{},...s.focus?{focus:s.focus}:{},...s.refused?{refused:s.refused}:{},...s.parallelism?{parallelism:s.parallelism}:typeof s.peakParallel=="number"?{peak_parallel:s.peakParallel}:{}}),s.exitCode),l=(s,p)=>(a({type:"error",message:s}),p&&!o&&process.stderr.write(`next: ${p}
|
|
37
|
-
`),u({exitCode:2,error:s})),f=typeof e.claimRun=="string"&&e.claimRun?e.claimRun:null;if(f&&!r)return l("--claim-run is the HyperExecute VM's own mode; it never runs on a terminal");let y=Le(e);if("error"in y)return l(y.error,y.next);if(!r){let s=await(n.setup??(p=>$r(p,n.lookupExploration??Be(p))))(e);if(s===null)return 0;if(typeof s=="number")return s;e=s}if(!f&&!(typeof e.url=="string"&&e.url.trim())){let s=he(e,!!e.localOrchestration,typeof e.project=="string"&&e.project?e.project:null),p=null;if(s)try{p=await(n.lookupExploration??Be(e))(s)}catch{p=null}p?.target_url&&(e={...e,url:p.target_url})}if(!f&&!(typeof e.url=="string"&&e.url.trim()))return l("required option '--url <url>' not specified");let I=!!e.localOrchestration||!!f;if(f&&e.localOrchestration)return l("--claim-run is the VM's own mode; it takes no --local-orchestration");if(e.devBundle&&I)return l("--dev-bundle is for a remote run (the default), not --local-orchestration or --claim-run");if(f){let s=String(e.explorationId??"").trim();if(!s)return l("--claim-run needs --exploration-id");let p=await J(e,"explore run --claim-run");if(!p.ok)return l(p.error);let m=String(e.env??new ne().getDefaultEnv()??"prod"),d=await Jt(tr(m,p.basic,"",A=>g(A)),s,f,process.env);if(!d.ok)return H(i({type:"error",message:d.error})),d.stopped?u({exitCode:d.exitCode,error:d.error,state:"stopped",remark:W("secrets_missing",d.error),explorationId:s,runId:f}):u({exitCode:d.exitCode,error:d.error,explorationId:s,runId:f});e={...e,...d.opts,env:e.env,username:e.username,accessKey:e.accessKey}}let _=Le(e);if("error"in _)return l(_.error,_.next);let x=_.policy,U={prompt:"",deps:""},R={},N="";try{let s=typeof e.depsText=="string"?e.depsText:ut(e.deps??[]);N=s;let p=ct({prompt:e.prompt??"Explore the app",deps:s},{globalDir:Ne(re,"variables"),localDir:Ne(process.cwd(),".testmuai","variables"),file:e.variablesFile,inline:e.variables,onLoadError:m=>a({type:"warning",message:m})});if("error"in p)return l(p.error);U={prompt:p.prompt,deps:p.deps},R=p.variables}catch(s){return l(`variables: ${s.message}`)}let w=Yt(e.allowDomain??[]);if(U.deps&&w.length===0)return l("--deps needs --allow-domain for every host the app signs in or writes on (e.g. --allow-domain testmuai.com --allow-domain lambdatest.com)");let L=[...new Set([...w,...Yt([String(e.url??"")])])],b=I?String(e.browser??"local"):"remote";if(!I&&e.browser!==void 0&&e.browser!=="local")return l("--browser applies to --local-orchestration; a remote run always uses remote browsers");if(b!=="local"&&b!=="remote")return l(`--browser ${b}: local or remote`);let j=e.hpsRegion;if(j!==void 0&&b!=="remote")return l("--hps-region needs --browser remote");if(j!==void 0&&!ae.includes(j))return l(`--hps-region ${j}: one of ${ae.join(", ")}`);let T=ze(e);if("error"in T)return l(T.error);if(T.tunnel&&b!=="remote")return l("--tunnel needs remote browsers (a remote run, or --browser remote): a local Chrome already reaches this machine");let D=e.maxParallel??1;if(b==="local"&&D>Se)return l(`--max-parallel ${D}: at most ${Se} browsers run on this machine at once (--browser remote runs up to ${ie})`);if(b==="remote"&&D>ie)return l(`--max-parallel ${D}: at most ${ie} remote browsers at once`);let xe=jr(e.depthCaps);if("error"in xe)return l(xe.error);let be=Cr(e.slowBudget);if("error"in be)return l(be.error);let Q=Lr(e.allowPost??[],L);if("error"in Q)return l(Q.error);x==="mutating"&&Q.posts.length&&a({type:"warning",code:"allow_post_ignored",message:Tt});let Y=new ne,E=e.env??Y.getDefaultEnv()??"prod",O=oe(E),G=new Ze().load(),nr=Y.loadProfileConfig(Y.getActiveProfile()??"default",E)?.project_id??null,C=e.project??G.project_id??nr??null;if(x==="mutating"){let s=Ct(String(e.url??"")),p=Pt(String(e.url??""));o?H(i({type:"warning",code:"policy_mutating",policy:x,host:s,message:p})):process.stderr.write((process.stderr.columns?lt(p,process.stderr.columns):p)+`
|
|
38
|
-
`);let m=n.mutatingMemory??$t();if(!r&&!(C&&m.confirmed(C))){let A=await(n.confirmMutating??(async B=>(await import("./explore-run-tty-M56I23IF.js")).confirmMutatingRun({...B,projectName:B.projectName??(B.projectId?await rr({...e,project:B.projectId}):null)})))({host:s,projectId:C,projectName:C===G.project_id?G.project_name??null:null});if(A!==!0)return process.stderr.write(`setup discarded; nothing launched
|
|
39
|
-
`),A===null?130:0;C&&m.remember(C)}}if(!r&&n.afterChecks)return n.afterChecks();let Me=new Set;r||(c=s=>{s.type==="explore_remote_started"?process.stderr.write(q("queued on HyperExecute",` \xB7 run ${String(s.run_id).slice(0,8)}${s.job_link?` \xB7 ${String(s.job_link)}`:""}`,"done")+`
|
|
40
|
-
`):(s.type==="warning"||s.type==="error")&&process.stderr.write(`${String(s.type)}: ${String(s.message)}
|
|
41
|
-
`);for(let p of Me)p(s)});let He=(s,p)=>{if(o)H(i({type:"error",message:s}));else for(let m of Ie(i({message:s}).message,p??Ar(s)))process.stderr.write(m+`
|
|
42
|
-
`)},v,Ve="";try{let s=await ot({creds:Y,env:E,usernameFlag:e.username,accessKeyFlag:e.accessKey,log:()=>{}});v=s.basicAuth,Ve=String(s.resolvedCreds?.org_id??"")}catch(s){return s instanceof nt&&s.code==="not_authenticated"?l("not authenticated: pass --username/--access-key or run 'kane-cli login'"):l(`auth resolution failed: ${s.message}`)}if(!v)return l("explore needs Basic credentials (username + access key); none resolved");if(!f){let s=he(e,I,C),p=null,m=v;if(s)try{p=await(n.lookupExploration??(A=>Oe(new S({baseUrl:O.controllerBaseUrl,auth:m,timeoutMs:5e3}),A)))(s)}catch{p=null}let d=p?Ue(p,String(e.url??"")):null;if(d)return He(d.error,d.next),u({exitCode:2,error:d.error})}if(n.afterUrlCheck)return n.afterUrlCheck();if(!I){T.tunnel&&g({type:"warning",message:Pr});let s={...tr(E,v,Ve,te=>g(te)),terminal:!r},p;if(typeof e.devBundle=="string"&&e.devBundle){let te=(process.env.EXPLORE_DEV_CONTROLLER_URL??"").trim();if(!te)return l("--dev-bundle needs EXPLORE_DEV_CONTROLLER_URL (the controller the VM talks to: the tunnel URL)");if(!Rr(e.devBundle))return l(`--dev-bundle ${e.devBundle}: no such file`);p={bundlePath:e.devBundle,controllerUrl:te}}let m=C;if(!m)return l("a remote run needs a project: pass --project <id> or set one (kane-cli config set-project); one project has one exploration");r||process.stderr.write(q("launching on HyperExecute")+`
|
|
43
|
-
`);let d=await Xt(s,{opts:e,variables:R,depsText:N,prompt:e.prompt??"Explore the app",url:String(e.url),projectId:m,allowedDomains:w,policy:x,...Zt(e),maxParallel:e.maxParallel,maxLeases:e.maxLeases,kaneVersion:M,...p?{dev:p}:{}});if(!d.ok)return He(d.error,d.stopped?"add the missing secret to your variables files (secret: true) or HyperExecute Secrets, then launch again":void 0),d.stopped?u({exitCode:d.exitCode,error:d.error,state:"stopped",remark:W("secrets_missing",d.error),explorationId:d.stopped.explorationId,runId:d.stopped.runId}):u({exitCode:d.exitCode,error:d.error});let A=u({exitCode:0,state:"queued",explorationId:d.explorationId,runId:d.runId});if(r)return A;let{runLiveView:B}=await import("./explore-live-XIWWUV52.js");return(await B({client:new S({baseUrl:O.controllerBaseUrl,auth:v}),explorationId:d.explorationId,runId:d.runId,mode:"remote",env:E,policy:x})).exitCode}let ye=et();if(!ye)return l("v16-runner not found");let De=G.window_size?.width??1280,Ge=G.window_size?.height??800,Fe=C,$,Z={explorationId:null,runId:null};if(b==="remote"){if(E!=="stage"&&E!=="prod")return l(`--browser remote: no remote browsers for env ${E}`);let s;try{s=ft(E,j??null)}catch(m){return l(m.message)}let p=v;i=mt([p.access_key]),$=wt({hpsBase:s,auth:p,forge:gt(O.tmsBaseUrl,p,()=>({exploration_id:Z.explorationId,run_id:Z.runId,project_id:Fe,hx_job_id:rt().jobId??null,kane_version:M,region:j??null,tunnel:!!T.tunnel,tunnel_name:T.tunnel?.name??null})),tunnel:T.tunnel,releaseSync:m=>ht(O.tmsBaseUrl,p,m),onEvent:m=>g({type:"remote_browser",...m})})}else $=pt({launch:Qe,width:De,height:Ge,headless:!!e.headless});Xe("explore-browsers",()=>$.releaseAllSync());let P=null,ve=null;try{P=await Ht({controller:{baseUrl:O.controllerBaseUrl,authHeader:K(v.username,v.access_key)},onWarn:s=>g({type:"warning",message:s}),onExploration:s=>{process.stderr.write(ge(s,e.env)+`
|
|
44
|
-
`)},onStop:()=>{g({type:"warning",message:"explore stop: the run is stopping cleanly"}),ve?.()}})}catch(s){g({type:"warning",message:`live mode is off for this run: ${s.message}`})}let _e=()=>{},or=new Promise(s=>{_e=s}),ee=null;r||Me.add(s=>{s.type!=="explore_run_started"||ee||(ee=import("./explore-live-XIWWUV52.js").then(({runLiveView:p})=>p({client:new S({baseUrl:O.controllerBaseUrl,auth:v}),explorationId:String(s.exploration_id),runId:String(s.run_id),mode:"local",env:E,policy:x,ended:or})))});try{let s=await kt({url:e.url,prompt:U.prompt,maxLeases:e.maxLeases,explorationId:e.explorationId,...typeof e.claimRunId=="string"?{claimRunId:e.claimRunId}:{requested:qt({opts:e,url:String(e.url),prompt:e.prompt??"Explore the app",depsText:N,variables:R,allowedDomains:w,policy:x,maxParallel:e.maxParallel,maxLeases:e.maxLeases})},projectId:Fe,policy:x,context:U,variables:R,allowedDomains:w,...Zt(e),allowPosts:x==="read_only"?Q.posts:[],depthCaps:xe.caps,slowBudgets:be.budgets,recheck:e.recheck!==!1,maxParallel:D,...typeof e.focus=="string"?{focus:e.focus}:{},denyNames:(e.deny??[]).map(m=>m.trim()).filter(Boolean),headless:!!e.headless,width:De,height:Ge,auth:v,clientRelease:M},{client:new S({baseUrl:O.controllerBaseUrl,auth:v}),spawnRunner:m=>{let d=tt({environment:E,username:v.username,accessKey:v.access_key,sessionId:m});return $.kind==="local"?ke({env:d,runner:ye,sessionId:m}):Bt(ke({env:d,runner:ye}),Ne(re,"sessions",m,"runner-stderr.log"),dt([v.access_key]))},acquireBrowser:async m=>{let d=await $.acquire(m);return P?.onBrowser(m),{cdpEndpoint:d.cdpEndpoint,release:()=>{P?.offBrowser(m),d.release()}}},releaseBrowsersOnInterrupt:$.kind==="remote",frameLink:m=>P?.attachRunner(m),onFrame:(m,d)=>P?.runnerFrame(m,d),onLiveRun:m=>{Z.explorationId=m.explorationId,Z.runId=m.runId,P?.armRun(m)},emit:m=>{let d=i(m);o?o.emit(d):c?.(d),P?.onEvent(d)},baseDir:re,onInterrupt:m=>{ve=m;let d=Mr(m);return()=>{ve=null,d()}}});await $.releaseAll(),await P?.close(s.stopReason??s.remark?.code??"stopped");let p=u(f?{...s,exitCode:bt(s)}:s);return _e(p),ee&&await ee,p}finally{_e(1),await P?.close("stopped"),await $.releaseAll(),Je("explore-browsers")}}var Ur=3e3;async function Nr(e,t={}){let n=t.tty??!ce(e),r=t.out??(w=>{process.stdout.write(w+`
|
|
45
|
-
`)}),o=n?null:Re("explore"),i=String(e.explorationId??"").trim(),c=String(e.project??"").trim(),g=(w,L,b)=>(o?.emit({type:"done",status:L,exit_code:w,exploration_id:i||null,...b?{error:b}:{}}),w),a=(w,L)=>{if(o)H({type:"error",message:w});else{let b=t.err??(j=>{process.stderr.write(j+`
|
|
46
|
-
`)});b(`error: ${w}`),L&&b(`next: ${L}`)}return g(2,"error",w)};if(i&&c)return a("--exploration-id or --project, not both","kane-cli explore view --exploration-id <id>");if(!i&&!c)return a("name the exploration: --exploration-id or --project","kane-cli explore list --all names them (or plain kane-cli explore to pick one)");let u=await J(e,"explore view");if(!u.ok)return a(u.error,"kane-cli login");let l=u.basic,f={controllerBaseUrl:u.controllerBaseUrl};if(c){try{i=(await new S({baseUrl:f.controllerBaseUrl,auth:l}).listExplorations({state:"all",project:c})).explorations.find(L=>L.project_id===c)?.exploration_id??""}catch(w){return a(`could not find project ${c}'s exploration: ${w.message}`)}if(!i)return a(`project ${c} has no exploration`,`start one: kane-cli explore run --project ${c} --url <app>`)}let y=K(l.username,l.access_key),I={controllerBaseUrl:f.controllerBaseUrl,authHeader:y,explorationId:i,port:e.port,live:{controller:{baseUrl:f.controllerBaseUrl,authHeader:y}}},_=await St(I);if(_.kind==="not_found")return a(`exploration ${i} not found`,"kane-cli explore list --all");if(_.kind==="error")return a(`could not read the map: ${_.message}`);let x;try{x=await It(I)}catch(w){return a(`could not bind 127.0.0.1${I.port?`:${I.port}`:""}: ${w.message}`,"pass another --port, or leave it out for the first free one")}let U=t.hold?null:Hr(),R=null;try{R=await new S({baseUrl:f.controllerBaseUrl,auth:l,timeoutMs:Ur}).getContext(i)}catch{}o&&o.emit({type:"explore_view_started",url:x.url,exploration_id:i,context:R});let N=null;if(!o){let w=!t.out&&!!process.stdin.isTTY&&!!process.stdout.isTTY;w&&er(x.url),r(q("map viewer ready",` \xB7 ${x.url}`)),r(kr(` ${w?"opened in your browser \xB7 ":""}live when a run is going`)),r("");let L=_.kind==="ok"&&_.body.counts&&typeof _.body.counts=="object"?_.body.counts:null,b=R?`context ${R.enabled?"on":"off"}${R.last_job?` \xB7 ${R.last_job.status}`:""}`:"";for(let j of Lt({status:q("serving"),meta:["explore",i.slice(0,8),u.environment??""],tallies:[...jt(L).filter(T=>!T.endsWith("findings")&&!T.endsWith("finding")),...b?[b]:[]],keys:[...w?["o open again"]:[],"ctrl+c stop serving"]}))r(j);w&&!t.hold&&(N=Br(()=>{er(x.url)}))}t.onStarted?.(x);try{await(U??t.hold())}finally{N?.()}return await x.close(),g(0,"stopped")}async function er(e){try{let{default:t}=await import("./open-MQLQKFAW.js");await t(e)}catch{process.stderr.write(`could not open a browser: open ${e}
|
|
47
|
-
`)}}function Br(e){let t=process.stdin;if(!t.isTTY)return()=>{};let n=r=>{let o=r.toString("utf8");o===""?process.kill(process.pid,"SIGINT"):(o==="o"||o==="O")&&e()};return t.setRawMode(!0),t.resume(),t.on("data",n),()=>{t.off("data",n);try{t.setRawMode(!1)}catch{}t.pause()}}function Mr(e){let t=process.listeners("SIGINT");for(let n of t)process.removeListener("SIGINT",n);return process.on("SIGINT",e),()=>{process.removeListener("SIGINT",e);for(let n of t)process.on("SIGINT",n)}}function Hr(){return new Promise(e=>{let t=process.listeners("SIGINT"),n=process.listeners("SIGTERM");process.removeAllListeners("SIGINT"),process.removeAllListeners("SIGTERM");let r=()=>{process.removeListener("SIGINT",r),process.removeListener("SIGTERM",r);for(let o of t)process.on("SIGINT",o);for(let o of n)process.on("SIGTERM",o);e()};process.once("SIGINT",r),process.once("SIGTERM",r)})}function tr(e,t,n,r){let o=oe(e);return{env:e,controllerBaseUrl:o.controllerBaseUrl,secretsBaseUrl:o.secretsBaseUrl,tmsBaseUrl:o.tmsBaseUrl,basic:t,orgId:n,emit:r}}export{Er as a,Sr as b,co as c,Yt as d,Lr as e,jr as f,Cr as g,Zt as h,Pr as i,Or as j,Ur as k,Nr as l,Mr as m};
|
package/dist/chunk-SXRHKXSE.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{a as f}from"./chunk-RZ4F3BHX.js";import{f as g}from"./chunk-A7RJQJNT.js";import{openAsBlob as A}from"fs";import{basename as b}from"path";var c={emulator:{product:"app-testing",type:"emulator",source:"web-client"},simulator:{product:"app-testing",type:"simulator",source:"web-client"},android:{product:"app-testing",type:"android",source:"web-client"},ios:{product:"app-testing",type:"ios",source:"web-client"}},m={emulator:"application/vnd.android.package-archive",simulator:"application/zip",android:"application/vnd.android.package-archive",ios:"application/zip"},k=30*6e4,u=3e4;function _(n){let t=n??{},e=Array.isArray(t.data)?t.data:[],r=[];for(let a of e){let i=a??{},d=typeof i.app_id=="string"?i.app_id:void 0;d&&r.push({appId:d,name:typeof i.name=="string"&&i.name.trim()!==""?i.name:d,...typeof i.package=="string"?{packageName:i.package}:{},...typeof i.updated_at=="string"?{updatedAt:i.updated_at}:{}})}let s=t.metaData??{},o=typeof s.total=="number"?s.total:typeof s.total=="string"&&Number.isFinite(Number(s.total))?Number(s.total):r.length;return{apps:r,total:o}}function $(){return{fileBody:n=>A(n),request:f}}function R(n){if(!n||typeof n!="object")return null;let t=n,e=typeof t.app_id=="string"?t.app_id:void 0;return e?{appId:e,...typeof t.app_url=="string"?{appUrl:t.app_url}:{},...typeof t.url=="string"?{url:t.url}:{},cached:t.cached===!0,...typeof t.name=="string"?{name:t.name}:{}}:null}function T(n){if(!n||typeof n!="object")return null;let t=n,e=typeof t.app_id=="string"?t.app_id:void 0,r=typeof t.download_url=="string"&&t.download_url!==""?t.download_url:void 0;if(!e||!r)return null;let s=typeof t.app_name=="string"&&t.app_name.trim()!==""?t.app_name:`${e}.bin`;return{appId:e,name:s,url:r,...typeof t.package=="string"?{packageName:t.package}:{},...typeof t.type=="string"?{type:t.type}:{}}}function U(n){if(!n||typeof n!="object")return null;let t=n,e=typeof t.app_id=="string"?t.app_id:void 0,r=a=>typeof t[a]=="string"&&t[a]!==""?t[a]:void 0,s=r("cf_url")??r("cf_ap_url")??r("url");if(!e||!s)return null;let o=typeof t.name=="string"&&t.name.trim()!==""?t.name:`${e}.bin`;return{appId:e,name:o,url:s,...typeof t.package=="string"?{packageName:t.package}:{},...typeof t.type=="string"?{type:t.type}:{}}}function S(n){let t=n?.cause,e=t instanceof Error?t.message:typeof t=="string"?t:void 0,r=n instanceof Error?n.message:String(n);return e&&e!==r?`${r} (${e})`:r}var p=class extends Error{constructor(e,r){super(e);this.status=r;this.name="AppUploadError"}};async function l(n){let t=await n.text();try{let e=JSON.parse(t);return e.message??e.error??t}catch{return t||`app service returned ${n.status}`}}var h=20,y=100,w=class{constructor(t,e,r={}){this.baseUrl=t;this.auth=e;this.deps={...$(),...r}}deps;headers(){return{Authorization:`Basic ${Buffer.from(`${this.auth.username}:${this.auth.accessKey}`).toString("base64")}`,Accept:"application/json"}}async upload(t,e,r={}){let s=b(t);if(!this.auth.orgId||!Number.isFinite(Number(this.auth.orgId)))throw new p(`Could not register ${s}: this account's org id is required to record an upload.`);let o=await this.uploadTarget(s,e);r.onProgress?.(`uploading ${s}\u2026`);let a=await this.deps.request(o.uploadUrl,{method:"PUT",headers:{"Content-Type":m[e]},body:await this.deps.fileBody(t),signal:r.signal??AbortSignal.timeout(k)});if(!a.ok)throw new p(`Uploading ${s} failed: ${a.status} ${await a.text()}`,a.status);let i=o.uploadUrl.split("?")[0];return this.register(s,e,i)}async uploadTarget(t,e){let r=c[e],s=new URLSearchParams({key:t,contentType:m[e],product:r.product}),o=await this.deps.request(`${this.baseUrl}/app/get-upload-url?${s.toString()}`,{method:"GET",headers:this.headers(),signal:AbortSignal.timeout(u)});if(!o.ok)throw new p(`Could not start the upload of ${t}: ${await l(o)}`,o.status);let a=await o.json();if(!a.uploadURL)throw new p(`Could not start the upload of ${t}: no upload url.`);return{key:a.Key??"",uploadUrl:a.uploadURL}}async register(t,e,r){let s=Number(this.auth.orgId),o=c[e],a=await this.deps.request(`${this.baseUrl}/app/url`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({name:t,source:o.source,type:o.type,org_id:s,url:r,product:o.product}),signal:AbortSignal.timeout(u)});if(!a.ok)throw new p(`Could not register ${t}: ${await l(a)}`,a.status);let i=R(await a.json());if(!i)throw new p(`Registering ${t} returned no app id.`);return i}async list(t){let e=t.limit??h;e<=0&&(e=h),e>y&&(e=y);let r=t.offset!==void 0&&t.offset>0?t.offset:0,s=new URLSearchParams({limit:String(e),offset:String(r),type:c[t.type].type,level:g(t.type)?"org":"user",searchtxt:t.search??""}),o=`${this.baseUrl}/app/list?${s.toString()}`,a;try{a=await this.deps.request(o,{method:"GET",headers:this.headers(),signal:AbortSignal.timeout(u)})}catch(i){throw new p(S(i))}if(!a.ok)throw new p(`Could not list your uploads: ${await l(a)}`,a.status);return _(await a.json())}async details(t){let e=await this.deps.request(`${this.baseUrl}/app/${encodeURIComponent(t)}/download?format=url`,{method:"GET",headers:this.headers(),signal:AbortSignal.timeout(u)});if(e.ok){let o=T(await e.json());if(o)return o}else if(e.status!==404)throw new p(`${t}: ${await l(e)}`,e.status);let r=await this.deps.request(`${this.baseUrl}/app/${encodeURIComponent(t)}/url`,{method:"GET",headers:this.headers(),signal:AbortSignal.timeout(u)});if(!r.ok)throw new p(`${t}: ${await l(r)}`,r.status);let s=U(await r.json());if(!s)throw new p(`${t} returned no download url.`);return s}async liveness(t){try{return await this.details(t),"alive"}catch(e){let r=e instanceof p?e.status:void 0;return r!==void 0&&r>=400&&r<500?"gone":"unknown"}}};export{m as a,_ as b,R as c,T as d,U as e,S as f,p as g,w as h};
|