@testmuai/kane-cli 0.8.3 → 0.8.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.
Files changed (178) hide show
  1. package/dist/{ChatSurface-FJSO3IKR.js → ChatSurface-H26E7DM6.js} +1 -1
  2. package/dist/{ChromeProfilePicker-NTZ2RN3L.js → ChromeProfilePicker-USUPENU2.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-BCHUH24C.js → CliFeedbackPrompt-ZIAZ2M2U.js} +1 -1
  4. package/dist/{CliUploadProgress-QVAJJRUW.js → CliUploadProgress-LEOJTXHT.js} +1 -1
  5. package/dist/{ConfigView-LAKAQN7O.js → ConfigView-JBIQPG7O.js} +1 -1
  6. package/dist/EvidenceViewOffer-IWQ6Q2CI.js +2 -0
  7. package/dist/FolderPicker-G4DT3OEZ.js +2 -0
  8. package/dist/{HelpView-JFFVHQAW.js → HelpView-I27LWSL5.js} +1 -1
  9. package/dist/{InfoBox-46C7AHDE.js → InfoBox-ORHNXPET.js} +1 -1
  10. package/dist/{LinksBox-KFJXZDUJ.js → LinksBox-6SKDUB5T.js} +1 -1
  11. package/dist/{ProfilesView-FV3KFVBX.js → ProfilesView-Y5GTLDJY.js} +1 -1
  12. package/dist/{ProjectPicker-MCH35VEF.js → ProjectPicker-WDCMKWNQ.js} +1 -1
  13. package/dist/{SaveSessionPrompt-RXHP3YW6.js → SaveSessionPrompt-I4KLFESC.js} +1 -1
  14. package/dist/SingleShotApp-Y77CNTSO.js +2 -0
  15. package/dist/{SummaryBox-33K2MMUW.js → SummaryBox-QWKW5FHK.js} +1 -1
  16. package/dist/TestMdRunView-PPM6LD3I.js +2 -0
  17. package/dist/TestrunEvidenceTable-ENJJ2GIW.js +2 -0
  18. package/dist/{WhoamiView-HUPBB5AQ.js → WhoamiView-H6M536AY.js} +1 -1
  19. package/dist/{app-download-3O7NJNGG.js → app-download-PSRQWDVW.js} +1 -1
  20. package/dist/{auth-OMWFVDL2.js → auth-JVH2EHK2.js} +1 -1
  21. package/dist/binary-YTQJP2FG.js +2 -0
  22. package/dist/{bind-NXXKFJMA.js → bind-OUXCFLSE.js} +2 -2
  23. package/dist/{bootstrap-MMRPAHWE.js → bootstrap-3NEI7O6I.js} +1 -1
  24. package/dist/bridge-AFQTFWCU.js +2 -0
  25. package/dist/{changelog-VZ5HFHYM.js → changelog-WDKG4WCV.js} +1 -1
  26. package/dist/chunk-2HT3RYKJ.js +2 -0
  27. package/dist/chunk-2PH43Z3P.js +69 -0
  28. package/dist/{chunk-NWJOPZ7P.js → chunk-35L2QXWP.js} +2 -2
  29. package/dist/{chunk-IFIXY3YG.js → chunk-3JLWPEQW.js} +1 -1
  30. package/dist/{chunk-IWWQTXGK.js → chunk-4CHO7SAT.js} +1 -1
  31. package/dist/{chunk-YJNGBZ42.js → chunk-52GWEKFD.js} +1 -1
  32. package/dist/chunk-55NSNWM5.js +26 -0
  33. package/dist/{chunk-CJJXT5DO.js → chunk-5GUD3CIH.js} +1 -1
  34. package/dist/{chunk-KZVEFBH5.js → chunk-5HYXTFGB.js} +1 -1
  35. package/dist/{chunk-IEOHAHZO.js → chunk-62WYSEAT.js} +1 -1
  36. package/dist/{chunk-AVH3BEEU.js → chunk-66RJPH73.js} +1 -1
  37. package/dist/chunk-6CR2HTIM.js +7 -0
  38. package/dist/{chunk-QJTXNQV5.js → chunk-7HPEHQHH.js} +1 -1
  39. package/dist/chunk-7HXZZ3VA.js +19 -0
  40. package/dist/{chunk-LP3BSP74.js → chunk-7LP4X25A.js} +1 -1
  41. package/dist/{chunk-SA2LQSYP.js → chunk-7VTYRTEJ.js} +1 -1
  42. package/dist/{chunk-UBTNWAKK.js → chunk-A3PGLDQY.js} +1 -1
  43. package/dist/{chunk-5CKQTZMG.js → chunk-A4XJUWAQ.js} +1 -1
  44. package/dist/{chunk-EBJD2V4Z.js → chunk-A6TJUSOS.js} +1 -1
  45. package/dist/{chunk-KOMKHFC4.js → chunk-BCCWICSS.js} +1 -1
  46. package/dist/{chunk-CJP7RX3E.js → chunk-BDUCWZYO.js} +1 -1
  47. package/dist/{chunk-2ZDXNTZT.js → chunk-BGMI5PH4.js} +1 -1
  48. package/dist/{chunk-DSXSU5MH.js → chunk-BSCMUMSV.js} +4 -4
  49. package/dist/{chunk-DVYO4CR2.js → chunk-BWSL2KQQ.js} +1 -1
  50. package/dist/{chunk-4G4RWARU.js → chunk-BXRZGISN.js} +1 -1
  51. package/dist/{chunk-VK3NU742.js → chunk-DEZ7CXGM.js} +1 -1
  52. package/dist/{chunk-GR35ZFM2.js → chunk-DWWAIXVZ.js} +2 -2
  53. package/dist/{chunk-NNCMMV6P.js → chunk-DXJKMZEC.js} +29 -23
  54. package/dist/{chunk-5BVOF4UW.js → chunk-DYGUHGZ6.js} +1 -1
  55. package/dist/{chunk-TUTDSX7T.js → chunk-DZJQNL66.js} +1 -1
  56. package/dist/{chunk-RUCSRS4C.js → chunk-EQSE6NIB.js} +1 -1
  57. package/dist/{chunk-7YZMUTJA.js → chunk-GJED4QGF.js} +1 -1
  58. package/dist/chunk-GSYJUHRK.js +2 -0
  59. package/dist/{chunk-LNQCZ5DS.js → chunk-HHHNQW5Z.js} +1 -1
  60. package/dist/{chunk-ZNNRCUHH.js → chunk-HXSEA7JS.js} +1 -1
  61. package/dist/chunk-IXTFWIQ6.js +2 -0
  62. package/dist/{chunk-4FQI643D.js → chunk-J27JJWMT.js} +1 -1
  63. package/dist/{chunk-SPQPOUUR.js → chunk-JCILRPOM.js} +2 -2
  64. package/dist/chunk-JR46A564.js +2 -0
  65. package/dist/{chunk-IHAHCFFG.js → chunk-JRADU3PO.js} +1 -1
  66. package/dist/{chunk-CVCVBQP6.js → chunk-JT7I6OST.js} +1 -1
  67. package/dist/{chunk-DJR3M7XO.js → chunk-KAMJ7U4M.js} +1 -1
  68. package/dist/{chunk-3MFTTLOF.js → chunk-KUYJ6FEN.js} +1 -1
  69. package/dist/{chunk-AF572MQG.js → chunk-L4EDLDLZ.js} +3 -3
  70. package/dist/{chunk-KGSVOTLG.js → chunk-L77ZOU4N.js} +1 -1
  71. package/dist/{chunk-ZH64GOBG.js → chunk-N5JHMCRU.js} +1 -1
  72. package/dist/{chunk-LSZVSYAP.js → chunk-N7N222VC.js} +2 -2
  73. package/dist/{chunk-XO45NGSN.js → chunk-NDAAY2RL.js} +1 -1
  74. package/dist/{chunk-NVGM5ISX.js → chunk-NEAMQMYH.js} +1 -1
  75. package/dist/chunk-NEHX45NQ.js +15 -0
  76. package/dist/{chunk-IVYXXZEE.js → chunk-OSB32HJE.js} +1 -1
  77. package/dist/chunk-OVLCJ2VX.js +37 -0
  78. package/dist/{chunk-6IA6QMPH.js → chunk-P7YZ3PU3.js} +1 -1
  79. package/dist/{chunk-D6FYCAIA.js → chunk-PH22FRN5.js} +1 -1
  80. package/dist/{chunk-JANVTG62.js → chunk-PQWSHTSH.js} +1 -1
  81. package/dist/{chunk-TRVB7RSW.js → chunk-PRLTUEKP.js} +1 -1
  82. package/dist/{chunk-LCU2P3CH.js → chunk-PSWB3BWQ.js} +1 -1
  83. package/dist/{chunk-CDB3SYZG.js → chunk-PWFZZWYU.js} +1 -1
  84. package/dist/{chunk-3S5DDQLP.js → chunk-QBF5FJVL.js} +1 -1
  85. package/dist/{chunk-DOG7S7R6.js → chunk-QDIZQ3ZF.js} +1 -1
  86. package/dist/{chunk-FPAJURPL.js → chunk-QWDFFEEJ.js} +1 -1
  87. package/dist/{chunk-WMMJXI5O.js → chunk-RN3YHD4S.js} +1 -1
  88. package/dist/{chunk-WCF2Z4SE.js → chunk-SFXQFUM6.js} +1 -1
  89. package/dist/{chunk-XMYCRE5K.js → chunk-SIH6JG7S.js} +3 -3
  90. package/dist/{chunk-ITTZYA2G.js → chunk-TXH2KG7U.js} +1 -1
  91. package/dist/{chunk-NXXJ56QA.js → chunk-TYI4MLFJ.js} +1 -1
  92. package/dist/{chunk-DN42IM2Z.js → chunk-U55NUF4E.js} +2 -2
  93. package/dist/chunk-ULGZPRKU.js +2 -0
  94. package/dist/{chunk-BRIEBB2U.js → chunk-UOMRMCMI.js} +1 -1
  95. package/dist/{chunk-2ERQYYSJ.js → chunk-UONRTWLU.js} +1 -1
  96. package/dist/{chunk-2N4SZOWN.js → chunk-UTIGOLON.js} +1 -1
  97. package/dist/chunk-V444REBC.js +11 -0
  98. package/dist/chunk-VBCIDWSK.js +2 -0
  99. package/dist/{chunk-37ZWKLEN.js → chunk-VYYTENPY.js} +1 -1
  100. package/dist/{chunk-L5LI2JF4.js → chunk-VZ7KXRXB.js} +11 -11
  101. package/dist/{chunk-SQDKYSWT.js → chunk-W75AVBFG.js} +1 -1
  102. package/dist/{chunk-5OVEBP4D.js → chunk-XHNPNYJP.js} +1 -1
  103. package/dist/{chunk-6G5YKTVN.js → chunk-YB73T7QH.js} +1 -1
  104. package/dist/{chunk-APETOVZK.js → chunk-YBX2SQ5R.js} +1 -1
  105. package/dist/{chunk-HJ6AXOCR.js → chunk-ZI6W65E3.js} +1 -1
  106. package/dist/{chunk-GIQURCTO.js → chunk-ZK57J37M.js} +1 -1
  107. package/dist/{chunk-KHU7C6EE.js → chunk-ZKSN2SJ7.js} +1 -1
  108. package/dist/{chunk-ZPDM6FO7.js → chunk-ZSXDZI56.js} +2 -2
  109. package/dist/{config-OTUKOTHM.js → config-SFM45WCV.js} +1 -1
  110. package/dist/cover-cmd-7JILZJUK.js +3 -0
  111. package/dist/{credentials-A3RU25MJ.js → credentials-3CENDBPH.js} +1 -1
  112. package/dist/{deps-bundle-RIBEQC2R.js → deps-bundle-P37ZJDXC.js} +1 -1
  113. package/dist/{deps-resolve-7SWSUDRX.js → deps-resolve-VSICFRWU.js} +1 -1
  114. package/dist/{dispatch-RHSWJJLC.js → dispatch-HDGQAEWN.js} +1 -1
  115. package/dist/doctor-CPMWU5TL.js +2 -0
  116. package/dist/evidence-ABYJOIV2.js +2 -0
  117. package/dist/evidence-presentation-XF23B7F2.js +2 -0
  118. package/dist/{evolve-cmd-FFF3F3HO.js → evolve-cmd-MROTNJIV.js} +1 -1
  119. package/dist/{explain-cmd-3GEKR7O5.js → explain-cmd-2TKO7GRW.js} +1 -1
  120. package/dist/{extract-bind-VIPNGK2H.js → extract-bind-LBZMEDUK.js} +2 -2
  121. package/dist/{extract-cmd-5J47Q4XU.js → extract-cmd-K4KBPMB7.js} +1 -1
  122. package/dist/{gaps-cmd-WPCJPLGB.js → gaps-cmd-3ZX3PZF4.js} +1 -1
  123. package/dist/{generate-headless-AJI2OVRG.js → generate-headless-EBMWSLTR.js} +2 -2
  124. package/dist/index.js +147 -85
  125. package/dist/{ingest-cmd-2LK7DWDW.js → ingest-cmd-ULEWNGCI.js} +1 -1
  126. package/dist/install-YDH2CORO.js +2 -0
  127. package/dist/{interactive-bind-PI3HY623.js → interactive-bind-IYAJN45L.js} +3 -3
  128. package/dist/{list-commands-7Y5XV5FK.js → list-commands-YPBJNGCE.js} +1 -1
  129. package/dist/login-flow-W5SAB7NN.js +2 -0
  130. package/dist/{mobile-prompts-O5ALU3QU.js → mobile-prompts-LHUYRSV7.js} +1 -1
  131. package/dist/{persist-recorded-session-TKSU4HOA.js → persist-recorded-session-KCXYXSQG.js} +1 -1
  132. package/dist/pipeline-ELIXCTFZ.js +2 -0
  133. package/dist/prepare-target-OU2DQXSW.js +2 -0
  134. package/dist/{reconcile-cmd-VHEW2DY5.js → reconcile-cmd-TSQDYEUT.js} +1 -1
  135. package/dist/{reconcile-deps-UJ6KVUIS.js → reconcile-deps-ETMGIQNM.js} +2 -2
  136. package/dist/{reconcile-engine-NUQJSIFX.js → reconcile-engine-TLFTAOTZ.js} +1 -1
  137. package/dist/{recording-banner-GO2PP53Y.js → recording-banner-ACOLKL4K.js} +1 -1
  138. package/dist/{registry-KYPVINS2.js → registry-3Q6PNWCK.js} +1 -1
  139. package/dist/{require-project-folder-NUQMH224.js → require-project-folder-5KWTJAXN.js} +1 -1
  140. package/dist/resolve-run-intent-L2I7G55O.js +2 -0
  141. package/dist/{resolver-HHLYRR5W.js → resolver-NRU6HGTL.js} +1 -1
  142. package/dist/run-RHLRZCV5.js +2 -0
  143. package/dist/{run-OPLOL3PZ.js → run-T53Z5TCY.js} +1 -1
  144. package/dist/{run-test-md-3BA56ZYF.js → run-test-md-JYDYT3XF.js} +2 -2
  145. package/dist/{skill-installer-O7JYVZXD.js → skill-installer-NWF53JAB.js} +1 -1
  146. package/dist/{spawner-OZ4OE44T.js → spawner-LKYUMXSO.js} +1 -1
  147. package/dist/tcg-generate-2PHA7VNL.js +2 -0
  148. package/dist/{testmd-actions-YJ7O43Z6.js → testmd-actions-CRRUXYOP.js} +1 -1
  149. package/dist/token-refresh-XKXPM6H3.js +2 -0
  150. package/dist/{types-6E2HTDKJ.js → types-VYEOJ6U2.js} +1 -1
  151. package/dist/{validate-basic-HWYK3CU6.js → validate-basic-X2XPEBFD.js} +1 -1
  152. package/dist/{verdicts-KFPMRADV.js → verdicts-J2SDU4MW.js} +1 -1
  153. package/dist/{version-check-3ECNG5V2.js → version-check-DAWGRSJ5.js} +1 -1
  154. package/dist/{walk-session-MZCMXVZB.js → walk-session-D6TCM33V.js} +1 -1
  155. package/dist/{with-telemetry-Q6V6THIF.js → with-telemetry-RXLIXUMR.js} +1 -1
  156. package/package.json +11 -11
  157. package/dist/EvidenceViewOffer-POKUWAPS.js +0 -2
  158. package/dist/FolderPicker-GR6FZMUJ.js +0 -2
  159. package/dist/SingleShotApp-BK5QNXGG.js +0 -2
  160. package/dist/TestMdRunView-AT26LOSG.js +0 -2
  161. package/dist/bridge-UH32UGR5.js +0 -2
  162. package/dist/chunk-5NQ3TI4S.js +0 -13
  163. package/dist/chunk-A5FFLJVL.js +0 -26
  164. package/dist/chunk-D5VYMHSO.js +0 -2
  165. package/dist/chunk-DXI5TXNL.js +0 -19
  166. package/dist/chunk-IOD3HQVW.js +0 -11
  167. package/dist/chunk-ZUYPPPC5.js +0 -66
  168. package/dist/cover-cmd-HDZZWJXG.js +0 -3
  169. package/dist/doctor-XP7YDE3J.js +0 -2
  170. package/dist/evidence-K7R7OG2K.js +0 -2
  171. package/dist/login-flow-Z45G34DM.js +0 -2
  172. package/dist/pipeline-HZUV7IMT.js +0 -2
  173. package/dist/prepare-target-DBYKQ7HW.js +0 -2
  174. package/dist/resolve-run-intent-H3HX5KUC.js +0 -7
  175. package/dist/run-67ONKMGR.js +0 -2
  176. package/dist/tcg-generate-EG2MXRJ7.js +0 -2
  177. package/dist/token-refresh-K7CANKFQ.js +0 -2
  178. /package/dist/{lifecycle-cmd-HO5VL7AM.js → lifecycle-cmd-O2324GN6.js} +0 -0
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as h}from"./chunk-EHN5HTUD.js";import{a as y,b as v}from"./chunk-L5LI2JF4.js";import{randomUUID as k,randomBytes as D}from"crypto";import{promises as i}from"fs";import{join as c}from"path";function p(t=process.cwd()){return c(t,".testmuai","evidence")}function b(t,e=process.cwd()){return c(p(e),`${t}.evidence`)}function W(){return k()}var S=/\.evidence\.tmp-(\d+)-[0-9a-f]+$/;async function _(t,e,r=process.cwd()){let n=p(r);await i.mkdir(n,{recursive:!0});let o=b(e,r),a=c(n,`${e}.evidence.tmp-${process.pid}-${D(6).toString("hex")}`);return await i.copyFile(t,a),await i.rename(a,o),o}async function I(t=process.cwd()){let e=p(t),r;try{r=await i.readdir(e)}catch{return[]}return r.filter(n=>n.endsWith(".evidence")).sort().map(n=>c(e,n))}async function L(t,e=process.cwd()){if(await P(t))return t;let r=b(t,e);return await P(r)?r:null}async function P(t){try{return await i.stat(t),!0}catch{return!1}}function E(t){try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}async function M(t=process.cwd(),e=E){let r=p(t);await h(r).catch(()=>({restored:[],removed:[]}));let n=[],o=[],a;try{a=await i.readdir(r,{withFileTypes:!0})}catch{return{aborted:n,removed:o}}for(let u of a){let d=u.name.match(S);if(d){let g=Number(d[1]);if(Number.isFinite(g)&&e(g))continue;let w=c(r,u.name);await i.rm(w,{force:!0}),o.push(w);continue}if(!u.isDirectory()||!u.name.endsWith(".evidence"))continue;let m=c(r,u.name),f=c(m,"run.yaml"),s;try{s=y(await i.readFile(f,"utf8"))}catch{continue}if(s?.status!=="running")continue;let l=s?.environment?.pid;if(typeof l=="number"&&e(l))continue;let x=s?.environment?.saved===!0;s?.environment?.origin==="inline"&&!x?(await i.rm(m,{recursive:!0,force:!0}),o.push(m)):(s.status="aborted",await i.writeFile(f,v(s,{lineWidth:-1})),n.push(m))}return{aborted:n,removed:o}}export{p as a,b,W as c,_ as d,I as e,L as f,M as g};
2
+ import{c as h}from"./chunk-EHN5HTUD.js";import{b as y,c as v}from"./chunk-VZ7KXRXB.js";import{randomUUID as k,randomBytes as D}from"crypto";import{promises as i}from"fs";import{join as c}from"path";function p(t=process.cwd()){return c(t,".testmuai","evidence")}function b(t,e=process.cwd()){return c(p(e),`${t}.evidence`)}function W(){return k()}var S=/\.evidence\.tmp-(\d+)-[0-9a-f]+$/;async function _(t,e,r=process.cwd()){let n=p(r);await i.mkdir(n,{recursive:!0});let o=b(e,r),a=c(n,`${e}.evidence.tmp-${process.pid}-${D(6).toString("hex")}`);return await i.copyFile(t,a),await i.rename(a,o),o}async function I(t=process.cwd()){let e=p(t),r;try{r=await i.readdir(e)}catch{return[]}return r.filter(n=>n.endsWith(".evidence")).sort().map(n=>c(e,n))}async function L(t,e=process.cwd()){if(await P(t))return t;let r=b(t,e);return await P(r)?r:null}async function P(t){try{return await i.stat(t),!0}catch{return!1}}function E(t){try{return process.kill(t,0),!0}catch(e){return e?.code==="EPERM"}}async function M(t=process.cwd(),e=E){let r=p(t);await h(r).catch(()=>({restored:[],removed:[]}));let n=[],o=[],a;try{a=await i.readdir(r,{withFileTypes:!0})}catch{return{aborted:n,removed:o}}for(let u of a){let d=u.name.match(S);if(d){let g=Number(d[1]);if(Number.isFinite(g)&&e(g))continue;let w=c(r,u.name);await i.rm(w,{force:!0}),o.push(w);continue}if(!u.isDirectory()||!u.name.endsWith(".evidence"))continue;let m=c(r,u.name),f=c(m,"run.yaml"),s;try{s=y(await i.readFile(f,"utf8"))}catch{continue}if(s?.status!=="running")continue;let l=s?.environment?.pid;if(typeof l=="number"&&e(l))continue;let x=s?.environment?.saved===!0;s?.environment?.origin==="inline"&&!x?(await i.rm(m,{recursive:!0,force:!0}),o.push(m)):(s.status="aborted",await i.writeFile(f,v(s,{lineWidth:-1})),n.push(m))}return{aborted:n,removed:o}}export{p as a,b,W as c,_ as d,I as e,L as f,M as g};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-5Y2G4NC7.js";import{y as o}from"./chunk-D6FYCAIA.js";import{a as n}from"./chunk-HCBYKLMW.js";import{b as t}from"./chunk-C44QQJR4.js";import{a as s}from"./chunk-6YGTRKDT.js";import{e as r}from"./chunk-UR6MHSHU.js";var l=r(s(),1);var m=r(n(),1),i=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function b({active:e=!0}){let[p,c]=(0,l.useState)(0);return a(()=>{c(f=>(f+1)%i.length)},e?80:null),(0,m.jsx)(t,{color:o.orange,children:e?i[p]:"\u25CF"})}export{b as a};
2
+ import{a}from"./chunk-5Y2G4NC7.js";import{y as o}from"./chunk-PH22FRN5.js";import{a as n}from"./chunk-HCBYKLMW.js";import{b as t}from"./chunk-C44QQJR4.js";import{a as s}from"./chunk-6YGTRKDT.js";import{e as r}from"./chunk-UR6MHSHU.js";var l=r(s(),1);var m=r(n(),1),i=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function b({active:e=!0}){let[p,c]=(0,l.useState)(0);return a(()=>{c(f=>(f+1)%i.length)},e?80:null),(0,m.jsx)(t,{color:o.orange,children:e?i[p]:"\u25CF"})}export{b as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as C}from"./chunk-KZVEFBH5.js";import{f as Z}from"./chunk-4G4RWARU.js";import{a as D}from"./chunk-YCCUBQY4.js";import{a as O}from"./chunk-KOMKHFC4.js";import{a as M}from"./chunk-DXI5TXNL.js";import{b as W}from"./chunk-AVH3BEEU.js";import{a as B}from"./chunk-SA2LQSYP.js";import{y as o}from"./chunk-D6FYCAIA.js";import{a as v}from"./chunk-HCBYKLMW.js";import{a as n,b as t,i as N}from"./chunk-C44QQJR4.js";import{a as L}from"./chunk-6YGTRKDT.js";import{e as g}from"./chunk-UR6MHSHU.js";var h=g(v(),1);function oe(e){let i=e.kind==="simulator";switch(e.state){case"ready":return i?"Booted":"Running";case"stopped":return i?"Shutdown":"Stopped";case"unauthorized":return"UNAUTHORIZED";case"offline":return"Offline"}}function te(e){switch(e.state){case"unauthorized":return"accept the authorisation prompt on the device, then reopen this list";case"offline":return e.kind==="simulator"?"not responding \u2014 open Simulator.app to inspect it":"not responding \u2014 reconnect it, or restart the emulator";default:return}}function re(e,i){let c=M(i.id);return e.platform===i.platform&&e.kind===i.kind&&(M(e.id)===c||e.virtualName!==void 0&&M(e.virtualName)===c)}function ne(e,i){let c=e.state==="ready"||e.state==="stopped",m=te(e);return{id:e.id,label:`${e.displayName} \xB7 ${oe(e)}`,...i&&re(e,i)?{isActive:!0}:{},...c?{}:{disabled:!0},...!c&&m?{disabledHint:m}:{}}}function ie(e){return e==="emulator"?"No Android emulator found. Make sure an emulator exists on this machine (Android Studio \u2192 Device Manager), then reopen this list.":e==="simulator"?"No iOS simulator found. Make sure a simulator exists on this machine (Xcode \u2192 Windows \u2192 Devices and Simulators), then reopen this list.":"No emulator or simulator found. Make sure one exists on this machine, then reopen this list."}function ge({targets:e,preselectedTarget:i,preselectedId:c,busyMessage:m,onSelect:S,onCancel:f,kind:l}){if(m)return(0,h.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,h.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,h.jsxs)(n,{marginTop:1,children:[(0,h.jsx)(C,{}),(0,h.jsxs)(t,{color:o.secondary,children:[" ",m]})]})]});if(e.length===0)return(0,h.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,h.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,h.jsx)(n,{marginTop:1,children:(0,h.jsx)(t,{color:o.dim,children:ie(l)})})]});let d=e.map(r=>ne(r,i)),p=i?d.find(r=>r.isActive)?.id??null:c?e.find(r=>r.id===c||r.virtualName===c)?.id??null:null,a=new Map(e.map(r=>[r.id,r]));return(0,h.jsx)(O,{title:"Device",items:d,itemNoun:"devices",defaultActiveId:p,preserveSelectionById:!0,onSelect:r=>{let y=a.get(r.id);y&&S(y)},onCancel:f})}var b=g(L(),1);var u=g(v(),1),q=50,G=500;function ae(e){return`${e.name} (${e.appId})`}function ve({kind:e,listApps:i,onSelect:c,onManualEntry:m,onCancel:S,busyMessage:f}){let[l,d]=(0,b.useState)([]),[p,a]=(0,b.useState)(!0),[r,y]=(0,b.useState)(!1),[Q,E]=(0,b.useState)(!1),[w,H]=(0,b.useState)(null),[$,V]=(0,b.useState)(""),[J,U]=(0,b.useState)(!1),X=(0,b.useRef)(!0),R=(0,b.useRef)(0);if((0,b.useEffect)(()=>{let x=++R.current,k=$.trim();X.current?a(!0):k&&E(!0),y(!0),H(null),U(!1),(async()=>{let I=[];try{for(let P=0;;P+=q){let z=await i({limit:q,offset:P,search:k});if(x!==R.current)return;if(I.push(...z.apps),d([...I]),X.current&&(a(!1),X.current=!1),E(!1),z.apps.length===0||I.length>=z.total)break;if(I.length>=G){U(!0);break}}}catch(P){if(x!==R.current)return;H(P instanceof Error?P.message:String(P)),a(!1),E(!1)}finally{x===R.current&&y(!1)}})()},[$,i]),N((x,k)=>{if(k.tab){m();return}k.escape&&S()},{isActive:!!w&&!f}),f)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,u.jsxs)(n,{marginTop:1,children:[(0,u.jsx)(C,{}),(0,u.jsxs)(t,{color:o.secondary,children:[" ",f]})]})]});if(w)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.red,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.red,bold:!0,children:"App under test"}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.red,children:"Could not load your uploads."})}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.dim,children:w})}),(0,u.jsx)(B,{bindings:[{keys:"tab",label:"tab to enter an app id"}],escBackLabel:"back to chat"})]});let j=new Map(l.map(x=>[x.appId,x])),ee=l.map(x=>({id:x.appId,label:ae(x)})),_=!p&&!r&&l.length===0&&!$.trim()?e==="simulator"?"No simulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":"No emulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":null;return(0,u.jsx)(O,{title:"App under test",items:ee,loading:p,loadingText:"Loading your uploads\u2026",loadingMore:r,searching:Q,itemNoun:"uploads",preserveSelectionById:!0,onSearch:V,onTab:m,extraHint:"tab to enter an id",footer:_?(0,u.jsx)(t,{color:o.dim,children:_}):J?(0,u.jsx)(t,{color:o.dim,children:`Showing the first ${G} \u2014 type to search the rest.`}):void 0,onSelect:x=>{let k=j.get(x.id);k&&c({appId:k.appId,name:k.name})},onCancel:S})}var Y=g(L(),1);var T=g(v(),1),le={emulator:["apk"],simulator:["zip"]};function pe(e){return Z(e.trim())}function Ne({kind:e,onBack:i,onSelect:c,onCancel:m}){let[S,f]=(0,Y.useState)(""),[l,d]=(0,Y.useState)(null),p=e==="emulator"?".apk":".zip";return(0,T.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,T.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,T.jsx)(n,{marginTop:1,children:(0,T.jsx)(t,{color:o.dim,children:`Path to a build (${p}): `})}),(0,T.jsxs)(n,{marginTop:1,children:[(0,T.jsx)(t,{color:o.dim,children:" "}),(0,T.jsx)(D,{value:S,onChange:a=>{f(a),l&&d(null)},onSubmit:a=>{let r=pe(a);if(!r){d(a.trim()?`Not a build \u2014 expected ${p}.`:"Enter the path to a build.");return}if(!le[e].includes(r.kind)){d(`${r.kind} builds don't run on a ${e} \u2014 expected ${p}.`);return}d(null),c(r).then(y=>{!y.ok&&y.error&&d(y.error)})},onCancel:i,placeholder:e==="emulator"?"/path/to/app-debug.apk":"/path/to/MyApp.zip"})]}),l&&(0,T.jsx)(n,{marginTop:1,children:(0,T.jsx)(t,{color:o.red,children:l})}),(0,T.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this build"}],escBackLabel:"back"})]})}var F=g(L(),1);var A=g(v(),1);function se(e){return[{value:"local",label:"Local build",hint:e==="emulator"?".apk":".zip",available:!0},{value:"uploaded",label:"Uploaded app",hint:"an app id from your cloud uploads",available:!0}]}function $e({kind:e,onSelect:i,onCancel:c}){let m=se(e),[S,f]=(0,F.useState)(0),[l,d]=(0,F.useState)(null);return N((p,a)=>{if(a.escape){c();return}if(a.upArrow&&f(r=>Math.max(0,r-1)),a.downArrow&&f(r=>Math.min(m.length-1,r+1)),a.return){let r=m[S];if(!r.available){d("That source isn't available \u2014 choose a local build for now.");return}d(null),i(r.value)}}),(0,A.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,A.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,A.jsx)(n,{marginTop:1,flexDirection:"column",children:m.map((p,a)=>{let r=a===S,y=p.available?r?o.orange:void 0:o.muted;return(0,A.jsxs)(n,{children:[(0,A.jsxs)(t,{color:y,children:[r?"\u276F ":" ",p.label]}),(0,A.jsxs)(t,{color:o.dim,children:[" ",p.hint]})]},p.value)})}),l&&(0,A.jsx)(n,{marginTop:1,children:(0,A.jsx)(t,{color:o.red,children:l})}),(0,A.jsx)(B,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}var K=g(L(),1);var s=g(v(),1);function We({busyMessage:e,onSubmit:i,onBack:c}){let[m,S]=(0,K.useState)(""),[f,l]=(0,K.useState)(null);return e?(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(C,{}),(0,s.jsxs)(t,{color:o.secondary,children:[" ",e]})]})]}):(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsx)(n,{marginTop:1,children:(0,s.jsx)(t,{color:o.dim,children:"App id from your cloud uploads:"})}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(t,{color:o.dim,children:" "}),(0,s.jsx)(D,{value:m,onChange:d=>{S(d),f&&l(null)},onSubmit:d=>{let p=d.trim();if(!p){l("Enter an app id.");return}if(!W(p)){l("That doesn't look like an app id \u2014 they start with APP.");return}l(null),i(p).then(a=>{!a.ok&&a.error&&l(a.error)})},onCancel:c,placeholder:"APP1016032231178585590501450"})]}),f&&(0,s.jsxs)(n,{marginTop:1,flexDirection:"column",children:[(0,s.jsx)(t,{color:o.red,children:f}),(0,s.jsx)(t,{color:o.dim,children:"Enter a valid app id \u2014 copy it from your cloud uploads."})]}),(0,s.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this app"}],escBackLabel:"back"})]})}export{ge as a,ve as b,Ne as c,$e as d,We as e};
2
+ import{a as C}from"./chunk-5HYXTFGB.js";import{f as Z}from"./chunk-BXRZGISN.js";import{a as D}from"./chunk-YCCUBQY4.js";import{a as O}from"./chunk-BCCWICSS.js";import{a as M}from"./chunk-7HXZZ3VA.js";import{b as W}from"./chunk-66RJPH73.js";import{a as B}from"./chunk-7VTYRTEJ.js";import{y as o}from"./chunk-PH22FRN5.js";import{a as v}from"./chunk-HCBYKLMW.js";import{a as n,b as t,i as N}from"./chunk-C44QQJR4.js";import{a as L}from"./chunk-6YGTRKDT.js";import{e as g}from"./chunk-UR6MHSHU.js";var h=g(v(),1);function oe(e){let i=e.kind==="simulator";switch(e.state){case"ready":return i?"Booted":"Running";case"stopped":return i?"Shutdown":"Stopped";case"unauthorized":return"UNAUTHORIZED";case"offline":return"Offline"}}function te(e){switch(e.state){case"unauthorized":return"accept the authorisation prompt on the device, then reopen this list";case"offline":return e.kind==="simulator"?"not responding \u2014 open Simulator.app to inspect it":"not responding \u2014 reconnect it, or restart the emulator";default:return}}function re(e,i){let c=M(i.id);return e.platform===i.platform&&e.kind===i.kind&&(M(e.id)===c||e.virtualName!==void 0&&M(e.virtualName)===c)}function ne(e,i){let c=e.state==="ready"||e.state==="stopped",m=te(e);return{id:e.id,label:`${e.displayName} \xB7 ${oe(e)}`,...i&&re(e,i)?{isActive:!0}:{},...c?{}:{disabled:!0},...!c&&m?{disabledHint:m}:{}}}function ie(e){return e==="emulator"?"No Android emulator found. Make sure an emulator exists on this machine (Android Studio \u2192 Device Manager), then reopen this list.":e==="simulator"?"No iOS simulator found. Make sure a simulator exists on this machine (Xcode \u2192 Windows \u2192 Devices and Simulators), then reopen this list.":"No emulator or simulator found. Make sure one exists on this machine, then reopen this list."}function ge({targets:e,preselectedTarget:i,preselectedId:c,busyMessage:m,onSelect:S,onCancel:f,kind:l}){if(m)return(0,h.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,h.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,h.jsxs)(n,{marginTop:1,children:[(0,h.jsx)(C,{}),(0,h.jsxs)(t,{color:o.secondary,children:[" ",m]})]})]});if(e.length===0)return(0,h.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,h.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,h.jsx)(n,{marginTop:1,children:(0,h.jsx)(t,{color:o.dim,children:ie(l)})})]});let d=e.map(r=>ne(r,i)),p=i?d.find(r=>r.isActive)?.id??null:c?e.find(r=>r.id===c||r.virtualName===c)?.id??null:null,a=new Map(e.map(r=>[r.id,r]));return(0,h.jsx)(O,{title:"Device",items:d,itemNoun:"devices",defaultActiveId:p,preserveSelectionById:!0,onSelect:r=>{let y=a.get(r.id);y&&S(y)},onCancel:f})}var b=g(L(),1);var u=g(v(),1),q=50,G=500;function ae(e){return`${e.name} (${e.appId})`}function ve({kind:e,listApps:i,onSelect:c,onManualEntry:m,onCancel:S,busyMessage:f}){let[l,d]=(0,b.useState)([]),[p,a]=(0,b.useState)(!0),[r,y]=(0,b.useState)(!1),[Q,E]=(0,b.useState)(!1),[w,H]=(0,b.useState)(null),[$,V]=(0,b.useState)(""),[J,U]=(0,b.useState)(!1),X=(0,b.useRef)(!0),R=(0,b.useRef)(0);if((0,b.useEffect)(()=>{let x=++R.current,k=$.trim();X.current?a(!0):k&&E(!0),y(!0),H(null),U(!1),(async()=>{let I=[];try{for(let P=0;;P+=q){let z=await i({limit:q,offset:P,search:k});if(x!==R.current)return;if(I.push(...z.apps),d([...I]),X.current&&(a(!1),X.current=!1),E(!1),z.apps.length===0||I.length>=z.total)break;if(I.length>=G){U(!0);break}}}catch(P){if(x!==R.current)return;H(P instanceof Error?P.message:String(P)),a(!1),E(!1)}finally{x===R.current&&y(!1)}})()},[$,i]),N((x,k)=>{if(k.tab){m();return}k.escape&&S()},{isActive:!!w&&!f}),f)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,u.jsxs)(n,{marginTop:1,children:[(0,u.jsx)(C,{}),(0,u.jsxs)(t,{color:o.secondary,children:[" ",f]})]})]});if(w)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.red,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.red,bold:!0,children:"App under test"}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.red,children:"Could not load your uploads."})}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.dim,children:w})}),(0,u.jsx)(B,{bindings:[{keys:"tab",label:"tab to enter an app id"}],escBackLabel:"back to chat"})]});let j=new Map(l.map(x=>[x.appId,x])),ee=l.map(x=>({id:x.appId,label:ae(x)})),_=!p&&!r&&l.length===0&&!$.trim()?e==="simulator"?"No simulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":"No emulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":null;return(0,u.jsx)(O,{title:"App under test",items:ee,loading:p,loadingText:"Loading your uploads\u2026",loadingMore:r,searching:Q,itemNoun:"uploads",preserveSelectionById:!0,onSearch:V,onTab:m,extraHint:"tab to enter an id",footer:_?(0,u.jsx)(t,{color:o.dim,children:_}):J?(0,u.jsx)(t,{color:o.dim,children:`Showing the first ${G} \u2014 type to search the rest.`}):void 0,onSelect:x=>{let k=j.get(x.id);k&&c({appId:k.appId,name:k.name})},onCancel:S})}var Y=g(L(),1);var T=g(v(),1),le={emulator:["apk"],simulator:["zip"]};function pe(e){return Z(e.trim())}function Ne({kind:e,onBack:i,onSelect:c,onCancel:m}){let[S,f]=(0,Y.useState)(""),[l,d]=(0,Y.useState)(null),p=e==="emulator"?".apk":".zip";return(0,T.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,T.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,T.jsx)(n,{marginTop:1,children:(0,T.jsx)(t,{color:o.dim,children:`Path to a build (${p}): `})}),(0,T.jsxs)(n,{marginTop:1,children:[(0,T.jsx)(t,{color:o.dim,children:" "}),(0,T.jsx)(D,{value:S,onChange:a=>{f(a),l&&d(null)},onSubmit:a=>{let r=pe(a);if(!r){d(a.trim()?`Not a build \u2014 expected ${p}.`:"Enter the path to a build.");return}if(!le[e].includes(r.kind)){d(`${r.kind} builds don't run on a ${e} \u2014 expected ${p}.`);return}d(null),c(r).then(y=>{!y.ok&&y.error&&d(y.error)})},onCancel:i,placeholder:e==="emulator"?"/path/to/app-debug.apk":"/path/to/MyApp.zip"})]}),l&&(0,T.jsx)(n,{marginTop:1,children:(0,T.jsx)(t,{color:o.red,children:l})}),(0,T.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this build"}],escBackLabel:"back"})]})}var F=g(L(),1);var A=g(v(),1);function se(e){return[{value:"local",label:"Local build",hint:e==="emulator"?".apk":".zip",available:!0},{value:"uploaded",label:"Uploaded app",hint:"an app id from your cloud uploads",available:!0}]}function $e({kind:e,onSelect:i,onCancel:c}){let m=se(e),[S,f]=(0,F.useState)(0),[l,d]=(0,F.useState)(null);return N((p,a)=>{if(a.escape){c();return}if(a.upArrow&&f(r=>Math.max(0,r-1)),a.downArrow&&f(r=>Math.min(m.length-1,r+1)),a.return){let r=m[S];if(!r.available){d("That source isn't available \u2014 choose a local build for now.");return}d(null),i(r.value)}}),(0,A.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,A.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,A.jsx)(n,{marginTop:1,flexDirection:"column",children:m.map((p,a)=>{let r=a===S,y=p.available?r?o.orange:void 0:o.muted;return(0,A.jsxs)(n,{children:[(0,A.jsxs)(t,{color:y,children:[r?"\u276F ":" ",p.label]}),(0,A.jsxs)(t,{color:o.dim,children:[" ",p.hint]})]},p.value)})}),l&&(0,A.jsx)(n,{marginTop:1,children:(0,A.jsx)(t,{color:o.red,children:l})}),(0,A.jsx)(B,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}var K=g(L(),1);var s=g(v(),1);function We({busyMessage:e,onSubmit:i,onBack:c}){let[m,S]=(0,K.useState)(""),[f,l]=(0,K.useState)(null);return e?(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(C,{}),(0,s.jsxs)(t,{color:o.secondary,children:[" ",e]})]})]}):(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsx)(n,{marginTop:1,children:(0,s.jsx)(t,{color:o.dim,children:"App id from your cloud uploads:"})}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(t,{color:o.dim,children:" "}),(0,s.jsx)(D,{value:m,onChange:d=>{S(d),f&&l(null)},onSubmit:d=>{let p=d.trim();if(!p){l("Enter an app id.");return}if(!W(p)){l("That doesn't look like an app id \u2014 they start with APP.");return}l(null),i(p).then(a=>{!a.ok&&a.error&&l(a.error)})},onCancel:c,placeholder:"APP1016032231178585590501450"})]}),f&&(0,s.jsxs)(n,{marginTop:1,flexDirection:"column",children:[(0,s.jsx)(t,{color:o.red,children:f}),(0,s.jsx)(t,{color:o.dim,children:"Enter a valid app id \u2014 copy it from your cloud uploads."})]}),(0,s.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this app"}],escBackLabel:"back"})]})}export{ge as a,ve as b,Ne as c,$e as d,We as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{h as w}from"./chunk-TAOHYWEO.js";import{a as h}from"./chunk-RZ4F3BHX.js";import{c as f}from"./chunk-D6FYCAIA.js";import{mkdtemp as O,rm as $}from"fs/promises";import{createWriteStream as R}from"fs";import{Readable as U}from"stream";import{pipeline as F}from"stream/promises";import{tmpdir as T}from"os";import{basename as z,join as A}from"path";import{access as x,cp as P,mkdir as g,readdir as y,readFile as S,rename as I,rm as k,stat as b,writeFile as v}from"fs/promises";import{basename as D,join as d}from"path";function u(){return d(f,"mobile","apps")}function m(){return d(u(),"index.json")}function C(){return{readIndex:async()=>{try{let e=JSON.parse(await S(m(),"utf8"));return{apps:Array.isArray(e.apps)?e.apps:[]}}catch{return{apps:[]}}},writeIndex:async r=>{await g(u(),{recursive:!0});let e=`${m()}.tmp`;await v(e,JSON.stringify(r,null,2)),await I(e,m())},exists:async r=>{try{return await x(r),!0}catch{return!1}},copy:(r,e)=>P(r,e,{recursive:!0,force:!0}),remove:r=>k(r,{recursive:!0,force:!0}),sizeOf:async r=>{try{return(await b(r)).size}catch{return}},now:()=>new Date}}var c=class{deps;constructor(e={}){this.deps={...C(),...e}}async list(){let{apps:e}=await this.deps.readIndex();return[...e].sort((t,s)=>s.lastUsedAt.localeCompare(t.lastUsedAt))}async find(e){return(await this.deps.readIndex()).apps.find(t=>t.key===e)}async put(e){let t=await this.deps.readIndex(),s=t.apps.find(n=>n.key===e.key),a=this.deps.now().toISOString();if(s&&await this.deps.exists(s.path))return s.lastUsedAt=a,await this.deps.writeIndex(t),s;s&&(t.apps=t.apps.filter(n=>n.key!==e.key));let l=D(e.name??e.sourcePath),o=d(u(),e.key),p=d(o,l);await g(o,{recursive:!0}),await this.deps.copy(e.sourcePath,p);let i={key:e.key,path:p,name:l,source:e.source,...e.source==="local"?{originPath:e.sourcePath}:{},addedAt:a,lastUsedAt:a,...await this.deps.sizeOf(p).then(n=>n?{bytes:n}:{})};return t.apps=[...t.apps.filter(n=>n.key!==e.key),i],await this.deps.writeIndex(t),i}async exists(e){if(await this.deps.sizeOf(e.path)!==void 0)return!0;try{return await y(e.path),!0}catch{return!1}}async forget(e){let t=await this.deps.readIndex(),s=t.apps.find(a=>a.key===e);s&&(await this.deps.remove(s.path),t.apps=t.apps.filter(a=>a.key!==e),await this.deps.writeIndex(t))}async prune(){let e=await this.deps.readIndex(),t=[];for(let s of e.apps)if(await this.deps.sizeOf(s.path)!==void 0)t.push(s);else try{await y(s.path),t.push(s)}catch{}return t.length!==e.apps.length&&await this.deps.writeIndex({apps:t}),t}};var E=30*6e4,j=/^APP\d{6,}$/;function Y(r){return!!r&&j.test(r.trim())}function _(){return{store:new c,client:(r,e)=>new w(r,e),fetchToFile:async(r,e)=>{let t=await h(r,{method:"GET",signal:AbortSignal.timeout(E)});if(!t.ok)throw new Error(`Downloading the app failed: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("Downloading the app failed: empty response body");await F(U.fromWeb(t.body),R(e))}}}async function Z(r,e={}){let t={..._(),...e},s=r.appId.trim(),a=await t.store.find(s);if(a&&await t.store.exists(a))return r.onProgress?.(`using the copy of ${a.name} already on this machine`),await t.store.put({key:s,sourcePath:a.path,source:"cloud",name:a.name}),{path:a.path,name:a.name,fromStore:!0};r.onProgress?.(`looking up ${s}\u2026`);let o=await t.client(r.baseUrl,r.auth).details(s);if(r.accepts&&!r.accepts.some(i=>o.name.toLowerCase().endsWith(i)))throw new Error(`${o.name} cannot run on this device \u2014 expected ${r.accepts.join(" or ")}.`);r.onProgress?.(`downloading ${o.name} \u2014 this can take a while, please wait\u2026`);let p=await O(A(T(),"kane-app-dl-"));try{let i=A(p,z(o.name));await t.fetchToFile(o.url,i);let n=await t.store.put({key:s,sourcePath:i,source:"cloud",name:o.name});return r.onProgress?.(`${o.name} is ready`),{path:n.path,name:n.name,fromStore:!1,details:o}}finally{await $(p,{recursive:!0,force:!0})}}export{c as a,Y as b,Z as c};
2
+ import{h as w}from"./chunk-TAOHYWEO.js";import{a as h}from"./chunk-RZ4F3BHX.js";import{c as f}from"./chunk-PH22FRN5.js";import{mkdtemp as O,rm as $}from"fs/promises";import{createWriteStream as R}from"fs";import{Readable as U}from"stream";import{pipeline as F}from"stream/promises";import{tmpdir as T}from"os";import{basename as z,join as A}from"path";import{access as x,cp as P,mkdir as g,readdir as y,readFile as S,rename as I,rm as k,stat as b,writeFile as v}from"fs/promises";import{basename as D,join as d}from"path";function u(){return d(f,"mobile","apps")}function m(){return d(u(),"index.json")}function C(){return{readIndex:async()=>{try{let e=JSON.parse(await S(m(),"utf8"));return{apps:Array.isArray(e.apps)?e.apps:[]}}catch{return{apps:[]}}},writeIndex:async r=>{await g(u(),{recursive:!0});let e=`${m()}.tmp`;await v(e,JSON.stringify(r,null,2)),await I(e,m())},exists:async r=>{try{return await x(r),!0}catch{return!1}},copy:(r,e)=>P(r,e,{recursive:!0,force:!0}),remove:r=>k(r,{recursive:!0,force:!0}),sizeOf:async r=>{try{return(await b(r)).size}catch{return}},now:()=>new Date}}var c=class{deps;constructor(e={}){this.deps={...C(),...e}}async list(){let{apps:e}=await this.deps.readIndex();return[...e].sort((t,s)=>s.lastUsedAt.localeCompare(t.lastUsedAt))}async find(e){return(await this.deps.readIndex()).apps.find(t=>t.key===e)}async put(e){let t=await this.deps.readIndex(),s=t.apps.find(n=>n.key===e.key),a=this.deps.now().toISOString();if(s&&await this.deps.exists(s.path))return s.lastUsedAt=a,await this.deps.writeIndex(t),s;s&&(t.apps=t.apps.filter(n=>n.key!==e.key));let l=D(e.name??e.sourcePath),o=d(u(),e.key),p=d(o,l);await g(o,{recursive:!0}),await this.deps.copy(e.sourcePath,p);let i={key:e.key,path:p,name:l,source:e.source,...e.source==="local"?{originPath:e.sourcePath}:{},addedAt:a,lastUsedAt:a,...await this.deps.sizeOf(p).then(n=>n?{bytes:n}:{})};return t.apps=[...t.apps.filter(n=>n.key!==e.key),i],await this.deps.writeIndex(t),i}async exists(e){if(await this.deps.sizeOf(e.path)!==void 0)return!0;try{return await y(e.path),!0}catch{return!1}}async forget(e){let t=await this.deps.readIndex(),s=t.apps.find(a=>a.key===e);s&&(await this.deps.remove(s.path),t.apps=t.apps.filter(a=>a.key!==e),await this.deps.writeIndex(t))}async prune(){let e=await this.deps.readIndex(),t=[];for(let s of e.apps)if(await this.deps.sizeOf(s.path)!==void 0)t.push(s);else try{await y(s.path),t.push(s)}catch{}return t.length!==e.apps.length&&await this.deps.writeIndex({apps:t}),t}};var E=30*6e4,j=/^APP\d{6,}$/;function Y(r){return!!r&&j.test(r.trim())}function _(){return{store:new c,client:(r,e)=>new w(r,e),fetchToFile:async(r,e)=>{let t=await h(r,{method:"GET",signal:AbortSignal.timeout(E)});if(!t.ok)throw new Error(`Downloading the app failed: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("Downloading the app failed: empty response body");await F(U.fromWeb(t.body),R(e))}}}async function Z(r,e={}){let t={..._(),...e},s=r.appId.trim(),a=await t.store.find(s);if(a&&await t.store.exists(a))return r.onProgress?.(`using the copy of ${a.name} already on this machine`),await t.store.put({key:s,sourcePath:a.path,source:"cloud",name:a.name}),{path:a.path,name:a.name,fromStore:!0};r.onProgress?.(`looking up ${s}\u2026`);let o=await t.client(r.baseUrl,r.auth).details(s);if(r.accepts&&!r.accepts.some(i=>o.name.toLowerCase().endsWith(i)))throw new Error(`${o.name} cannot run on this device \u2014 expected ${r.accepts.join(" or ")}.`);r.onProgress?.(`downloading ${o.name} \u2014 this can take a while, please wait\u2026`);let p=await O(A(T(),"kane-app-dl-"));try{let i=A(p,z(o.name));await t.fetchToFile(o.url,i);let n=await t.store.put({key:s,sourcePath:i,source:"cloud",name:o.name});return r.onProgress?.(`${o.name} is ready`),{path:n.path,name:n.name,fromStore:!1,details:o}}finally{await $(p,{recursive:!0,force:!0})}}export{c as a,Y as b,Z as c};
@@ -0,0 +1,7 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{e as v,f as l}from"./chunk-BXRZGISN.js";import{a as f,c as m,e as p}from"./chunk-EYOCNMUM.js";var R=["desktop","emulator","simulator"];function k(e,n){return e.kind==="app_id"?!0:n==="emulator"?e.kind==="apk":e.kind==="zip"}function g(e,n,t){let s=l(e);return s?k(s,n)?null:n==="emulator"?`${t} cannot run on an emulator (needs an .apk, or an APP\u2026 id).`:`${t} cannot run on a simulator (needs a .zip of the .app bundle, or an APP\u2026 id).`:`${e}: ${v}`}function b(e){return R.includes(e)?e:null}function T(e){return`--target must be one of desktop, emulator, simulator (got "${e}")`}function h(e){let n=[];for(let[t,s]of[["--device",e.device],["--app",e.app]])s!==void 0&&n.push(`ignored ${t} ${s}: session target is desktop \u2014 set --target emulator|simulator to run on a device`);return n}function I(e){let{flags:n,saved:t}=e,s=[],r;if(n.target!==void 0){let i=b(n.target);if(!i)return{kind:"invalid",message:T(n.target)};r=i}else{let i=f(t?.tui_target,t?.default_target?.kind);if(i.kind==="choose-mobile")return{kind:"choose-mobile-kind"};r=i.kind==="unset"?"desktop":i.kind}if(r==="desktop")return s.push(...h(n)),{kind:"web",warnings:s};if(!e.host.supported)return{kind:"invalid",message:e.host.reason??"this machine cannot run mobile targets."};let a=[],o;n.device!==void 0?o={value:n.device,source:"flag"}:t?.default_target&&t.default_target.kind===r?o={value:t.default_target.id,source:"saved"}:a.push("device");let d;if(n.app!==void 0){let i=g(n.app,r,`--app ${n.app}`);if(i)return{kind:"invalid",message:i};d={value:n.app,source:"flag"}}else{let i=t?.default_app,c=i?l(i):null;c&&k(c,r)&&t?.default_target?.kind===r?d={value:i,source:"saved"}:a.push("app")}return{kind:"mobile",target:r,...o?{device:o}:{},...d?{app:d}:{},missing:a,warnings:s}}function P(e){let{flags:n,file:t}=e,s=[],r=t.target==="emulator"||t.target==="simulator"?t.target:void 0,a;if(n.target!==void 0){let i=b(n.target);if(!i)return{kind:"invalid",message:T(n.target)};a=i,r&&r!==a&&s.push(`--target ${a} overrides the file's \`target: ${r}\` \u2014 steps recorded on ${r==="emulator"?"an emulator":"a simulator"} may not replay here`)}else a=r??"desktop";if(a==="desktop")return s.push(...h(n)),{kind:"web",warnings:s};if(n.app!==void 0){let i=g(n.app,a,`--app ${n.app}`);if(i)return{kind:"invalid",message:i}}else if(t.app){let i=g(t.app,a,`the file's app: ${t.app}`);if(i)return{kind:"invalid",message:i}}let o=n.app??(t.app||void 0),d=n.device?.trim();return{kind:"mobile",target:a,platform:m(a)??"",...d?{device:d}:{},...o?{app:o}:{},...t.no_reset!==void 0?{noReset:t.no_reset}:{},warnings:s}}function _(e){return e.target==="desktop"?"Running on: Desktop \xB7 Chrome":`Running on: ${p(e.target)} \xB7 ${e.deviceLabel} \xB7 ${e.appLabel}`}var u={emulator:"</path/to/app.apk | APPid>",simulator:"</path/to/app.zip | APPid>"};function x(e,n){let t=p(e).toLowerCase();return n==="device"?[`session target is "${t}" but no device is set.`,` See devices: kane-cli devices list --target ${e}`,' Set one: kane-cli config set-device "<name>"',' Or per-run: --device "<name>"'].join(`
3
+ `):[`session target is "${t}" but no app is set.`,` Set one: kane-cli config set-app ${u[e]}`,` Or per-run: --app ${u[e]}`].join(`
4
+ `)}function A(e){return[`saved device "${e}" was not found on this machine.`," See devices: kane-cli devices list",' Set one: kane-cli config set-device "<name>"'].join(`
5
+ `)}function w(e,n){return[`saved app ${e} no longer exists on disk.`," The build may have been moved or cleaned. Set a new one:",` kane-cli config set-app ${u[n]}`].join(`
6
+ `)}var y=['session target is "mobile" from an older version \u2014 say which kind:'," kane-cli config set-target emulator|simulator"].join(`
7
+ `);export{k as a,I as b,P as c,_ as d,x as e,A as f,w as g,y as h};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as h}from"./chunk-SA2LQSYP.js";import{y as l}from"./chunk-D6FYCAIA.js";import{a as A}from"./chunk-HCBYKLMW.js";import{a as c,b as f,i as P}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as x}from"./chunk-UR6MHSHU.js";var L=x(B(),1);var n=x(A(),1);function S(r,d,s,u,m){let p=s==="basic"&&u?`basic (${u})`:s,i=20,a=`${r} [${d}]`,g="\xB7".repeat(Math.max(2,i-a.length+3));return{label:`${a} ${g} ${p}`,profile:r,env:d,isActive:m}}function M({creds:r,onSwitch:d,onCancel:s}){let u=r.listProfiles(),m=r.getActiveProfile(),p=r.getDefaultEnv(),i=u.map(e=>{let o=r.loadBasicAuth(e.profile,e.env),t=r.loadCredentials(e.profile,e.env)!==null,v=o?"basic":t?"oauth":"none",b=o?o.username:null,w=e.profile===m&&e.env===p;return S(e.profile,e.env,v,b,w)}),[a,g]=(0,L.useState)(()=>{let e=i.findIndex(o=>o.isActive);return e>=0?e:0});return P((e,o)=>{if(o.escape){s();return}if(o.upArrow){g(t=>Math.max(0,t-1));return}if(o.downArrow){g(t=>Math.min(i.length-1,t+1));return}if(o.return&&i[a]){let t=i[a];t.isActive||d(t.profile,t.env),s();return}}),i.length===0?(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(f,{color:l.dim,children:"No profiles \u2014 use Login to create one"})}),(0,n.jsx)(h,{bindings:[],escBackLabel:"back"})]}):(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{flexDirection:"column",marginTop:1,children:i.map((e,o)=>{let t=o===a,v=t?"\u276F ":" ",b=e.isActive?l.green:t?l.orange:void 0;return(0,n.jsxs)(f,{color:b,children:[v,e.label,e.isActive?" \u25CF active":""]},`${e.profile}-${e.env}`)})}),(0,n.jsx)(h,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"switch"}],escBackLabel:"back"})]})}export{S as a,M as b};
2
+ import{a as h}from"./chunk-7VTYRTEJ.js";import{y as l}from"./chunk-PH22FRN5.js";import{a as A}from"./chunk-HCBYKLMW.js";import{a as c,b as f,i as P}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as x}from"./chunk-UR6MHSHU.js";var L=x(B(),1);var n=x(A(),1);function S(r,d,s,u,m){let p=s==="basic"&&u?`basic (${u})`:s,i=20,a=`${r} [${d}]`,g="\xB7".repeat(Math.max(2,i-a.length+3));return{label:`${a} ${g} ${p}`,profile:r,env:d,isActive:m}}function M({creds:r,onSwitch:d,onCancel:s}){let u=r.listProfiles(),m=r.getActiveProfile(),p=r.getDefaultEnv(),i=u.map(e=>{let o=r.loadBasicAuth(e.profile,e.env),t=r.loadCredentials(e.profile,e.env)!==null,v=o?"basic":t?"oauth":"none",b=o?o.username:null,w=e.profile===m&&e.env===p;return S(e.profile,e.env,v,b,w)}),[a,g]=(0,L.useState)(()=>{let e=i.findIndex(o=>o.isActive);return e>=0?e:0});return P((e,o)=>{if(o.escape){s();return}if(o.upArrow){g(t=>Math.max(0,t-1));return}if(o.downArrow){g(t=>Math.min(i.length-1,t+1));return}if(o.return&&i[a]){let t=i[a];t.isActive||d(t.profile,t.env),s();return}}),i.length===0?(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(f,{color:l.dim,children:"No profiles \u2014 use Login to create one"})}),(0,n.jsx)(h,{bindings:[],escBackLabel:"back"})]}):(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{flexDirection:"column",marginTop:1,children:i.map((e,o)=>{let t=o===a,v=t?"\u276F ":" ",b=e.isActive?l.green:t?l.orange:void 0;return(0,n.jsxs)(f,{color:b,children:[v,e.label,e.isActive?" \u25CF active":""]},`${e.profile}-${e.env}`)})}),(0,n.jsx)(h,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"switch"}],escBackLabel:"back"})]})}export{S as a,M as b};
@@ -0,0 +1,19 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as G}from"./chunk-MMBBQ4OZ.js";import{j as O}from"./chunk-JCILRPOM.js";import{d as E,e as z}from"./chunk-4JOD47QI.js";import{a as X}from"./chunk-RZ4F3BHX.js";import{spawn as _e}from"child_process";import{existsSync as Ie,readFileSync as $e}from"fs";import{homedir as Ne}from"os";import{dirname as Q,join as k}from"path";import{access as ve,mkdir as W,readFile as we}from"fs/promises";import{homedir as be}from"os";import{arch as ye,platform as Ae}from"process";import{join as M}from"path";var xe=35,Se="google_apis",ke="KaneCLI_Pixel_API35",Te="KaneAI_Pixel_API35";function bt(t){return t===Te?ke:t}var De=1;function Pe(t,e){return t==="darwin"&&e==="arm64"?"arm64-v8a":"x86_64"}function Me(){return{home:be(),os:Ae,arch:ye}}async function Y(t){try{return await ve(t),!0}catch{return!1}}var H=class{deps;constructor(e={}){this.deps={...Me(),...e}}paths(){let e=M(this.deps.home,".testmuai","kaneai","mobile"),r=M(e,"android-sdk");return{root:r,emulatorDir:M(r,"emulator"),systemImageDir:M(r,"system-images",`android-${xe}`,Se,Pe(this.deps.os,this.deps.arch)),avdHome:M(e,"avd"),manifest:M(r,"sdk-manifest.json")}}environment(){let e=this.paths();return{ANDROID_HOME:e.root,ANDROID_SDK_ROOT:e.root,ANDROID_AVD_HOME:e.avdHome}}async ensureSdkRootMarkers(){let e=this.paths().root;await W(M(e,"platforms"),{recursive:!0}),await W(M(e,"platform-tools"),{recursive:!0})}async status(){let e=this.paths(),r=null;try{r=JSON.parse(await we(e.manifest,"utf8"))}catch{}if(!r||r.schemaVersion!==De)return{emulator:!1,systemImage:!1};let o=this.deps.os==="win32"?"emulator.exe":"emulator";return{emulator:!!r.components.emulator&&await Y(M(e.emulatorDir,o)),systemImage:!!r.components.systemImage&&await Y(M(e.systemImageDir,"system.img"))}}},Z;function L(){return Z??=new H,Z}var V="android",Ee="http://127.0.0.1:4723/status",Oe=2e3,ee=12e4,Re=1e3,Ce=3e5;var Le=5,te="Run `kane-cli doctor --target emulator --install` to install the managed Appium tree.",Fe={device:"ready",unauthorized:"unauthorized",offline:"offline"};function Be(t){let e={};for(let r of t){let o=r.indexOf(":");o<=0||(e[r.slice(0,o)]=r.slice(o+1))}return e}function Ue(t){let e=[];for(let r of t.split(`
3
+ `)){let o=r.trim();if(!o||o.startsWith("*"))continue;let m=o.toLowerCase();if(m.startsWith("list of devices")||m.startsWith("adb server"))continue;let f=o.split(/\s+/),p=f[0],v=f[1];if(!p||!v||!p.startsWith("emulator-"))continue;let h=Be(f.slice(2)),b=h.model?h.model.replace(/_/g," "):void 0;e.push({platform:V,kind:"emulator",id:p,displayName:b??p,state:Fe[v]??"offline"})}return e}function ie(t){let e=[];for(let r of t.split(`
4
+ `)){let o=r.trim();o&&/^[A-Za-z0-9._-]+$/.test(o)&&(e.includes(o)||e.push(o))}return e}function qe(t){for(let e of t.split(`
5
+ `)){let r=e.trim();if(!(!r||r==="OK"))return r}}function He(t){let e=/^Version\s+(\S+)/m.exec(t);return e?.[1]?e[1].split("-")[0]:/Android Debug Bridge version\s+(\S+)/.exec(t)?.[1]}function Ve(t){let e=[];for(let r of t.split(`
6
+ `)){let o=r.trim();if(!o.startsWith("package:"))continue;let m=o.slice(8).trim();m&&!e.includes(m)&&e.push(m)}return e.sort()}function je(t){let e=Number(t.trim());return Number.isInteger(e)&&e>0?e:void 0}function Je(t){return[...new Set(t.split(",").map(e=>e.trim()).filter(Boolean))]}var Ke=[{match:/INSTALL_FAILED_VERIFICATION|verif(?:ier|ication)/i,hint:`Package verification blocked the install. Disable it for adb installs:
7
+ adb -s <device> shell settings put global verifier_verify_adb_installs 0`},{match:/INSTALL_FAILED_UPDATE_INCOMPATIBLE|INSTALL_FAILED_VERSION_DOWNGRADE|signatures do not match/i,hint:`A different build of this package is already installed. Uninstall it first:
8
+ adb -s <device> uninstall <package>`},{match:/INSUFFICIENT_STORAGE/i,hint:"The device is out of storage. Free space on the device and retry."}];function Xe(t){for(let{match:e,hint:r}of Ke)if(e.test(t))return r}function j(t,e,r=Le){let o=t.toLowerCase(),m=e.filter(v=>v.toLowerCase().includes(o)),f=Math.max(6,Math.floor(o.length/2)),p=e.filter(v=>!m.includes(v)&&ze(v.toLowerCase(),o)>=f);return[...m,...p].slice(0,r)}function ze(t,e){let r=Math.min(t.length,e.length),o=0;for(;o<r&&t[o]===e[o];)o++;return o}function ne(t){return t&&/^hw\.device\.name\s*=\s*(.+)\s*$/m.exec(t)?.[1]?.trim()||void 0}function Ge(){return X(Ee,{signal:AbortSignal.timeout(Oe)}).then(t=>t.ok,()=>!1)}function We(t,e,r){_e(t,e,{stdio:"ignore",detached:!0,...r?{env:{...process.env,...r}}:{}}).unref()}function Ye(){return{exec:E,spawnDetached:We,fileExists:Ie,env:process.env,home:Ne(),os:process.platform,probeAppiumServer:Ge,now:()=>Date.now(),sleep:z,mobileDeps:{status:t=>O().status(t),environment:t=>O().environment(t)},sdkSuite:{status:()=>L().status(),environment:()=>L().environment(),emulatorPath:()=>{let t=L().paths().emulatorDir;return k(t,process.platform==="win32"?"emulator.exe":"emulator")},ensureSdkRootMarkers:()=>L().ensureSdkRootMarkers()}}}function re(t={}){let e={...Ye(),...t},r={},o=new Set;function m(i){return e.os==="win32"?`${i}.exe`:i}function f(i){if(e.readAvdConfig)return e.readAvdConfig(i);let n=[e.env.ANDROID_AVD_HOME,k(e.home,".android","avd"),e.sdkSuite.environment().ANDROID_AVD_HOME];for(let s of n){if(!s)continue;let a=k(s,`${i}.avd`,"config.ini");try{if(e.fileExists(a))return $e(a,"utf8")}catch{}}}function p(){return e.os==="win32"?"appium.cmd":"appium"}function v(){let i=[];for(let n of["ANDROID_HOME","ANDROID_SDK_ROOT"]){let s=e.env[n];s&&s.trim()!==""&&i.push(s.trim())}return e.os==="darwin"?i.push(k(e.home,"Library","Android","sdk")):e.os==="win32"?i.push(k(e.home,"AppData","Local","Android","Sdk")):i.push(k(e.home,"Android","Sdk")),i}function h(i){let n=i==="adb"?"platform-tools":"emulator";return v().map(s=>k(s,n,m(i)))}async function b(i){let n=e.os==="win32"?"where":"which",s=await e.exec(n,[m(i)],{timeoutMs:5e3});if(s.code!==0)return null;let a=s.stdout.split(`
9
+ `)[0]?.trim();return a&&a!==""?a:null}async function S(i){if(i==="adb"){let s=G(e.env);if(s){let u=k(s.platformToolsDir,m("adb"));if(e.fileExists(u)){let c={path:u,source:"sdk"};return r[i]=c,c}return delete r[i],null}if((await e.mobileDeps.status("emulator")).installed){let u=await e.mobileDeps.environment("emulator");if(u.platformToolsDir){let c={path:k(u.platformToolsDir,m("adb")),source:"local"};return r[i]=c,c}}return delete r[i],null}if(i==="emulator"&&(await e.sdkSuite.status()).emulator){let a={path:e.sdkSuite.emulatorPath(),source:"local"};return r[i]=a,a}let n=await b(i);if(n){let s={path:n,source:"sdk"};return r[i]=s,s}for(let s of h(i))if(e.fileExists(s)){let a={path:s,source:"sdk"};return r[i]=a,a}return delete r[i],null}async function $(){let i=await S("adb");if(!i)throw new Error("Managed adb is not installed.\nRun `kane-cli doctor --target emulator --install` to install the pinned Android platform-tools.");return i.path}async function d(i){let n=await e.exec(i,["devices","-l"],{timeoutMs:2e4});return Ue(n.stdout)}async function l(i,n){let s=await e.exec(i,["-s",n,"shell","getprop","ro.boot.qemu.avd_name"],{timeoutMs:1e4});if(s.code===0){let u=s.stdout.split(`
10
+ `)[0]?.trim();if(u)return u}let a=await e.exec(i,["-s",n,"emu","avd","name"],{timeoutMs:1e4});if(a.code===0)return qe(a.stdout)}async function g(i){let n=await S("emulator");if(!n)return[];let s=await e.exec(n.path,["-list-avds"],{timeoutMs:2e4}),a=s.code===0?ie(s.stdout):[];if(o.clear(),(await e.sdkSuite.status()).emulator){let c=await e.exec(n.path,["-list-avds"],{timeoutMs:2e4,env:{...e.env,...e.sdkSuite.environment()}});if(c.code===0)for(let w of ie(c.stdout))o.add(w),a.includes(w)||a.push(w)}return a.filter(c=>!i.has(c)).map(c=>{let w=ne(f(c));return{platform:V,kind:"emulator",id:c,displayName:c,state:"stopped",virtualName:c,...w?{modelIdentifier:w}:{}}})}async function y(){let i=await S("adb");if(!i)return[];let n=await d(i.path),s=new Set;for(let u of n){if(u.kind!=="emulator"||u.state!=="ready")continue;let c=await l(i.path,u.id);if(!c)continue;u.virtualName=c,u.displayName=c;let w=ne(f(c));w&&(u.modelIdentifier=w),s.add(c)}let a=await g(s);return[...n,...a]}function T(i,n){return[`${i} did not finish booting within ${ee/1e3}s.`,n?`It attached as ${n} but never reported sys.boot_completed=1.`:"It never attached to adb.","The emulator process is still running \u2014 check its window for errors.","Common causes: no hardware acceleration (install the Android Emulator","hypervisor driver / enable KVM), or a corrupt AVD (recreate it in","Android Studio's Device Manager)."].join(`
11
+ `)}async function A(i,n,s){let a=await S("emulator");if(!a)throw new Error("The Android `emulator` binary was not found, so AVDs cannot be booted.\nInstall it via Android Studio's SDK Manager (Android Emulator) and set ANDROID_HOME.");let u=new Set((await d(i)).map(F=>F.id)),c=o.has(n);c&&await e.sdkSuite.ensureSdkRootMarkers();let w=c?{...e.env,...e.sdkSuite.environment()}:void 0;e.spawnDetached(a.path,["-avd",n],w),s?.(`booting ${n}\u2026`);let P=e.now()+ee,x;for(;e.now()<P;){if(await e.sleep(Re),!x){let I=(await d(i)).find(C=>C.kind==="emulator"&&!u.has(C.id));I&&(x=I.id,s?.(`${n} attached as ${x}, waiting for boot\u2026`));continue}if((await e.exec(i,["-s",x,"shell","getprop","sys.boot_completed"],{timeoutMs:1e4})).stdout.trim()==="1")return x}throw new Error(T(n,x))}async function _(i,n){let s=await $();if(i.state==="ready")return D(i,s);if(i.state==="unauthorized")throw new Error(`${i.displayName} (${i.id}) is UNAUTHORIZED. Accept the USB-debugging prompt on the device, then retry.`);if(i.state==="offline")throw new Error(`${i.displayName} (${i.id}) is offline. Reconnect it (USB) or re-run \`adb connect ${i.id}\` (wireless), then retry.`);let a=i.virtualName??i.id,u=await A(s,a,n);return D({...i,kind:"emulator",id:u,displayName:a,state:"ready",virtualName:a},s)}async function D(i,n){let[s,a,u,c]=await Promise.all([e.exec(n,["-s",i.id,"shell","getprop","ro.build.version.sdk"],{timeoutMs:1e4}),e.exec(n,["-s",i.id,"shell","getprop","ro.build.version.release"],{timeoutMs:1e4}),e.exec(n,["-s",i.id,"shell","getprop","ro.product.cpu.abilist"],{timeoutMs:1e4}),e.exec(n,["-s",i.id,"shell","getprop","ro.product.cpu.abi"],{timeoutMs:1e4})]),w=s.code===0?je(s.stdout):void 0,P=a.code===0?a.stdout.trim():"",x=Je(u.code===0&&u.stdout.trim()!==""?u.stdout:c.stdout);return{...i,...w!==void 0?{androidApiLevel:w}:{},...P!==""?{osVersion:P}:{},...x.length>0?{androidAbis:x}:{}}}async function N(i){let n=await $(),s=await e.exec(n,["-s",i.id,"shell","pm","list","packages","-3"],{timeoutMs:3e4});if(s.code!==0)throw new Error(`Could not list installed packages on ${i.id}: ${s.stderr.trim()||`adb exited ${s.code}`}`);return Ve(s.stdout)}async function U(i){let n;try{let{default:s}=await import("./adbkit-apkreader-ORZBGCJQ.js");n=(await(await s.open(i)).readManifest())?.package}catch(s){let a=s instanceof Error?s.message:String(s);throw new Error(`Could not read the package name from ${i} (${a}).
12
+ Pass the package name explicitly with --app <package>.`)}if(typeof n!="string"||n.trim()==="")throw new Error(`${i} has no package name in its manifest.
13
+ Pass the package name explicitly with --app <package>.`);return n.trim()}async function ce(i,n,s){let a=await $();s?.(`installing ${n} on ${i.id}\u2026`);let u=await e.exec(a,["-s",i.id,"install","-r",n],{timeoutMs:Ce}),c=`${u.stdout}
14
+ ${u.stderr}`;if(u.code===0&&!/\bFailure\b/i.test(c))return;let w=Xe(c),P=[`Installing ${n} on ${i.id} failed (adb exited ${u.code}).`,c.trim()];throw w&&P.push("",w),new Error(P.filter(x=>x!=="").join(`
15
+ `))}async function me(i,n,s){if(n.kind==="package"){let a=await N(i);if(a.includes(n.value))return n.value;let u=j(n.value,a),c=[`${n.value} is not installed on ${i.displayName} (${i.id}).`];throw u.length>0?c.push("Close matches:",...u.map(w=>` ${w}`)):c.push("Pass a local .apk path to --app to install it instead."),new Error(c.join(`
16
+ `))}if(n.kind!=="apk"){let a=n.kind==="aab"?"Android app bundles are not directly installable; build an APK first.":n.kind==="apks"?"Split bundles are not supported yet.":`${n.kind} artifacts are not installable on Android.`;throw new Error(a)}return await ce(i,n.value,s),U(n.value)}async function pe(){let i=await e.mobileDeps.status("emulator");return i.installed?{status:i,env:await e.mobileDeps.environment("emulator")}:null}async function fe(i={}){let n=[],s=await pe(),a=await e.mobileDeps.status("emulator"),u=await S("adb");if(u){let I=await e.exec(u.path,["version"],{timeoutMs:1e4}),C=He(I.stdout);n.push({id:"android.adb",fixedByBundle:!0,label:"adb",required:!0,status:"pass",detail:C?`platform-tools ${C} \xB7 ${u.path}`:u.path})}else n.push({id:"android.adb",fixedByBundle:!0,label:"adb",required:!0,status:"fail",detail:a.corrupt??"managed mobile dependencies are not installed",fixText:"Run `kane-cli doctor --target emulator --install` to download the managed mobile deps bundle under ~/.testmuai/kaneai/mobile."});let c=!i.appiumUrl;s?.env.appiumHome?n.push({id:"android.appium",fixedByBundle:!0,label:"Appium",required:c,status:"pass",detail:k(Q(s.env.appiumHome),"appium","node_modules",".bin",p())}):n.push({id:"android.appium",fixedByBundle:!0,label:"Appium",required:c,status:c?"fail":"info",detail:i.appiumUrl?`managed Appium not required because --appium-url is set (${i.appiumUrl})`:a.corrupt??"managed Appium is not installed",...c?{fixText:te}:{}}),n.push({id:"android.uiautomator2",fixedByBundle:!0,label:"uiautomator2 driver",required:c,status:s?"pass":c?"fail":"info",detail:s?"bundled in the managed mobile deps":i.appiumUrl?"managed driver not required because --appium-url is set":"not installed in the managed deps tree",...s||!c?{}:{fixText:te}});let w=k(e.home,".testmuai","kaneai","mobile","trees");e.fileExists(w)&&n.push({id:"android.legacy-trees",label:"legacy toolchain trees",required:!1,status:"info",detail:`${w} predates the deps bundle \u2014 removed automatically by the next bundle install`});let P=await b("adb");P&&n.push({id:"android.system-adb",label:"system adb",required:!1,status:"info",detail:`${P} (ignored; managed adb always wins and may restart its server)`});let x=await b("appium");x&&n.push({id:"android.system-appium",label:"system Appium",required:!1,status:"info",detail:`${x} (ignored; managed Appium always wins)`});let F=await e.sdkSuite.status(),q=await S("emulator");if(F.emulator?n.push({id:"android.emulator",label:"emulator",required:!1,status:"pass",detail:`managed emulator \xB7 ${e.sdkSuite.emulatorPath()}`}):q?n.push({id:"android.emulator",label:"emulator",required:!1,status:"info",detail:`${q.path} (system install)`}):n.push({id:"android.emulator",label:"emulator",required:!1,status:"info",detail:"not installed, so stopped AVDs are not listed. Install it with the Android SDK (Android Studio \u2192 SDK Manager \u2192 Android Emulator)."}),e.os==="darwin"){let I=await e.exec("sysctl",["-n","kern.hv_support"],{timeoutMs:5e3});n.push({id:"android.virtualization",label:"virtualization",required:!1,status:"info",detail:I.code===0&&I.stdout.trim()==="1"?"Hypervisor.framework available":"Hypervisor.framework not reported \u2014 emulator boots may hang"})}else e.os==="linux"?n.push({id:"android.virtualization",label:"virtualization",required:!1,status:"info",detail:e.fileExists("/dev/kvm")?"/dev/kvm present":"/dev/kvm missing \u2014 enable KVM or emulator boots will hang"}):n.push({id:"android.virtualization",label:"virtualization",required:!1,status:"info",detail:"not checked on this host"});return n}async function ge(i){let n=await e.mobileDeps.environment("emulator"),s=[...n.dirs],a=r.emulator,u=a?.source==="sdk"?Q(a.path):void 0;return u&&!s.includes(u)&&s.push(u),{...n,dirs:s}}async function he(i,n){let s=await $(),a=[];return n.appPackage&&a.push({label:`closing ${n.appPackage}`,file:s,args:["-s",i.id,"shell","am","force-stop",n.appPackage]}),n.shutdown&&a.push({label:`shutting down ${i.displayName}`,file:s,args:["-s",i.id,"emu","kill"]}),a}return{platform:V,available:()=>!0,checks:fe,discover:y,prepare:_,listApps:N,ensureApp:me,teardownPlan:he,toolEnv:ge}}import{mkdtemp as se,readdir as Ze,rm as oe,writeFile as Qe}from"fs/promises";import{tmpdir as ae}from"os";import{join as R}from"path";var de="ios",et=12e4,tt=3e5,it="an .ipa cannot be installed on a simulator \u2014 use a .zip of the .app build";function nt(t){let e=/\.iOS-(\d+)-(\d+)$/.exec(t);return e?`${e[1]}.${e[2]}`:void 0}function rt(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=[];for(let[o,m]of Object.entries(e.devices??{})){let f=nt(o);for(let p of m??[]){let v=typeof p.udid=="string"?p.udid:void 0,h=typeof p.name=="string"?p.name:void 0;if(!v||!h)continue;let b=p.state==="Booted"?"ready":p.state==="Shutdown"?"stopped":"offline",S=typeof p.deviceTypeIdentifier=="string"?p.deviceTypeIdentifier.replace(/^com\.apple\.CoreSimulator\.SimDeviceType\./,""):void 0;r.push({platform:de,kind:"simulator",id:v,displayName:f?`${h} (iOS ${f})`:h,state:b,virtualName:h,...f?{osVersion:f}:{},...S?{modelIdentifier:S}:{}})}}return r}function st(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=[];for(let[o,m]of Object.entries(e)){if(m?.ApplicationType!=="User")continue;let f=m.CFBundleIdentifier??o;r.includes(f)||r.push(f)}return r.sort()}function ot(t){let e;try{e=JSON.parse(t)}catch{return[]}let r=[];for(let[o,m]of Object.entries(e)){let f=m?.CFBundleIdentifier??o;f&&!r.includes(f)&&r.push(f)}return r.sort()}var J=16;function at(t){return/^Xcode (\d+(?:\.\d+)*)/m.exec(t)?.[1]}async function dt(t){let e=await se(R(ae(),"kane-app-unzip-")),r=()=>oe(e,{recursive:!0,force:!0}),o=await E("unzip",["-q",t,"-d",e],{timeoutMs:10*6e4});if(o.code!==0)throw await r(),new Error(`Could not unpack ${t}: ${o.stderr.trim()||`unzip exited ${o.code}`}`);for(let m of[e,R(e,"Payload")]){let f;try{f=await Ze(m)}catch{continue}let p=f.find(v=>v.toLowerCase().endsWith(".app"));if(p)return{appPath:R(m,p),cleanup:r}}throw await r(),new Error(`${t} does not contain a .app bundle.`)}async function lt(t){let e=await se(R(ae(),"kane-plist-"));try{let r=R(e,"input.plist");await Qe(r,t);let o=await E("plutil",["-convert","json","-o","-",r],{timeoutMs:15e3});if(o.code!==0)throw new Error(`plutil could not convert simctl output: ${o.stderr.trim()}`);return o.stdout}finally{await oe(e,{recursive:!0,force:!0})}}function ut(){return{exec:E,os:process.platform,convertPlistToJson:lt,mobileDeps:{status:()=>O().status("simulator"),environment:()=>O().environment("simulator")}}}function le(t={}){let e={...ut(),...t};async function r(d,l=3e4){return e.exec("xcrun",["simctl",...d],{timeoutMs:l})}async function o(){let d=await r(["list","devices","available","--json"]);return d.code!==0?[]:rt(d.stdout)}async function m(){return o()}async function f(d,l){let g=await e.exec("open",["-a","Simulator","--args","-CurrentDeviceUDID",d],{timeoutMs:15e3});g.code!==0&&l?.(`could not open Simulator.app (${g.stderr.trim()||`exit ${g.code}`}); the device is booted and the run continues headless`)}async function p(d,l){if(d.state!=="ready"&&d.state!=="stopped")throw new Error(`${d.displayName} (${d.id}) is ${d.state}; open Simulator.app to inspect it, then retry.`);d.kind==="simulator"&&await f(d.id,l),d.state==="stopped"&&l?.(`booting ${d.displayName}\u2026`);let g=await r(["bootstatus",d.id,"-b"],et);if(g.code!==0)throw new Error(`Could not boot ${d.displayName}: ${g.stderr.trim()||g.stdout.trim()||`simctl bootstatus exited ${g.code}`}`);let y=(await o()).find(T=>T.id===d.id);if(y?.state==="ready")return y;throw new Error(`${d.displayName} finished booting but simctl still reports it as ${y?.state??"missing"}.`)}async function v(d){let l=await r(["listapps",d.id]);if(l.code!==0)throw new Error(`Could not list apps on ${d.displayName}: ${l.stderr.trim()||`simctl exited ${l.code}`}`);return st(await e.convertPlistToJson(l.stdout))}async function h(d){let l=R(d,"Info.plist"),g=await e.exec("plutil",["-convert","json","-o","-",l],{timeoutMs:15e3});if(g.code!==0)throw new Error(`${d} Info.plist could not be read: ${g.stderr.trim()||`plutil exited ${g.code}`}`);let y;try{y=JSON.parse(g.stdout)}catch{throw new Error(`${d} Info.plist did not contain valid JSON from plutil.`)}if(!y.CFBundleIdentifier)throw new Error(`${d} has no CFBundleIdentifier in its Info.plist.`);return y.CFBundleIdentifier}async function b(d,l,g){if(l.kind==="package"){let A=await r(["listapps",d.id]);if(A.code!==0)throw new Error(`Could not list apps on ${d.displayName}: ${A.stderr.trim()||`simctl exited ${A.code}`}`);let _=ot(await e.convertPlistToJson(A.stdout));if(_.includes(l.value))return l.value;let D=j(l.value,_),N=[`${l.value} is not installed on ${d.displayName} (${d.id}).`];throw D.length>0?N.push("Close matches:",...D.map(U=>` ${U}`)):N.push("Pass a .zip of the .app bundle to install it instead."),new Error(N.join(`
17
+ `))}if(l.kind==="ipa")throw new Error(`${it}.`);if(l.kind!=="app"&&l.kind!=="zip")throw new Error(`${l.kind} artifacts are Android-only and not installable on iOS.`);let y=l.value,T;if(l.kind==="zip"){g?.(`unpacking ${l.value}\u2026`);let A=await dt(l.value);y=A.appPath,T=A.cleanup}g?.(`installing ${y} on ${d.displayName}\u2026`);try{let A=await r(["install",d.id,y],tt);if(A.code!==0)throw new Error(`Installing ${l.value} on ${d.displayName} failed: ${A.stderr.trim()||A.stdout.trim()}`);return await h(y)}finally{await T?.()}}async function S(d={}){let l=[],g=await e.exec("xcode-select",["-p"],{timeoutMs:1e4});if(g.code===0&&g.stdout.trim()!==""){let _=await e.exec("xcodebuild",["-version"],{timeoutMs:3e4}),D=_.code===0?at(_.stdout):void 0;D?Number(D.split(".")[0])<J?l.push({id:"ios.xcode",label:"Xcode",required:!0,status:"fail",detail:`Xcode ${D} is older than the required Xcode ${J}`,fixText:`Update Xcode to ${J} or newer from the App Store.`}):l.push({id:"ios.xcode",label:"Xcode",required:!0,status:"pass",detail:`Xcode ${D} \xB7 ${g.stdout.trim()}`}):l.push({id:"ios.xcode",label:"Xcode",required:!0,status:"fail",detail:`${g.stdout.trim()} has no usable xcodebuild (Command Line Tools only?)`,fixText:"Install full Xcode from the App Store, then run `sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`."})}else l.push({id:"ios.xcode",label:"Xcode",required:!0,status:"fail",detail:"xcode-select reports no developer directory",fixText:"Install Xcode from the App Store, then run `xcode-select --install`."});let y=await e.exec("xcrun",["simctl","help"],{timeoutMs:15e3});l.push(y.code===0?{id:"ios.xcrun",label:"xcrun",required:!0,status:"pass",detail:"simctl reachable"}:{id:"ios.xcrun",label:"xcrun",required:!0,status:"fail",detail:`xcrun cannot run simctl: ${y.stderr.trim()||y.stdout.trim()||`exit ${y.code}`}`,fixText:"Run `xcode-select --install`, then confirm with `xcrun simctl list devices`. If Xcode is installed, `sudo xcode-select -s /Applications/Xcode.app/Contents/Developer` repoints it."});let T=!d.appiumUrl,A=await e.mobileDeps.status();return l.push({id:"ios.xcuitest",fixedByBundle:!0,label:"xcuitest driver",required:T,status:A.installed?"pass":T?"fail":"info",detail:A.installed?"bundled in the managed mobile deps (with prebuilt WDA)":d.appiumUrl?"managed driver not required because --appium-url is set":A.corrupt??"the simulator deps bundle is not installed",...A.installed||!T?{}:{fixText:"Run `kane-cli doctor --target simulator --install` to download the simulator deps bundle."}}),l}async function $(d,l){let g=[];return l.appPackage&&g.push({label:`closing ${l.appPackage}`,file:"xcrun",args:["simctl","terminate",d.id,l.appPackage]}),l.shutdown&&g.push({label:`shutting down ${d.displayName}`,file:"xcrun",args:["simctl","shutdown",d.id]}),g}return{platform:de,available:()=>e.os==="darwin",checks:S,discover:m,prepare:p,listApps:v,ensureApp:b,teardownPlan:$,toolEnv:()=>e.mobileDeps.environment()}}var ue=[re(),le()];function B(){return ue.filter(t=>t.available())}function qt(){return B().map(t=>t.platform)}function Ht(){return ue.map(t=>t.platform)}function ct(t){let e=t.toLowerCase();return B().find(r=>r.platform.toLowerCase()===e)}async function mt(t){let e=t?B().filter(o=>o.platform.toLowerCase()===t.toLowerCase()):B(),r=[];for(let o of e)try{r.push(...await o.discover())}catch{}return r}function pt(t,e){let r=e.toLowerCase();return t.id.toLowerCase()===r||t.virtualName?.toLowerCase()===r}function ft(t){let e=t.virtualName&&t.virtualName!==t.id?`${t.displayName} (${t.virtualName})`:t.displayName;return`${t.id} \u2014 ${e} [${t.platform} \xB7 ${t.kind} \xB7 ${t.state}]`}function K(t){return t.length===0?"":`
18
+ ${t.map(e=>` ${ft(e)}`).join(`
19
+ `)}`}async function Vt(t,e={}){let r=e.discover??mt,o=e.providerFor??ct,m=await r(t.platform),f=h=>{let b=o(h.platform);return b?{ok:!0,target:h,provider:b}:{ok:!1,reason:"not-found",candidates:m,message:`No provider is registered for platform '${h.platform}'.`}};if(t.device){let h=m.filter(b=>pt(b,t.device));return h.length===0?{ok:!1,reason:"not-found",candidates:m,message:`No target matches --device '${t.device}'.`+(m.length>0?` Available:${K(m)}`:" No targets were found \u2014 run `kane-cli doctor --target <emulator|simulator>`.")}:f(h.find(b=>b.state==="ready")??h[0])}let p=t.defaultTarget;if(p&&(!t.platform||t.platform.toLowerCase()===p.platform.toLowerCase())){let h=m.find(b=>b.platform===p.platform&&b.kind===p.kind&&(b.id===p.id||b.virtualName===p.id));return h?f(h):{ok:!1,reason:t.interactive?"needs-picker":"not-found",candidates:m,message:`The saved default target '${p.id}' (${p.platform} \xB7 ${p.kind}) is not connected. `+(t.interactive?"Pick a target to bind this run.":"Pass --device <id> explicitly \u2014 kane-cli never binds a different device on its own.")+(m.length>0?` Available:${K(m)}`:"")}}if(m.length===0)return{ok:!1,reason:"none-found",candidates:[],message:"No emulator or simulator found. Start an Android emulator or boot an iOS simulator, then run `kane-cli devices list --target <emulator|simulator>`."};let v=m.filter(h=>h.state==="ready");return v.length===1?f(v[0]):t.interactive?{ok:!1,reason:"needs-picker",candidates:m,message:v.length===0?"No target is ready \u2014 pick one to prepare it.":"More than one target is ready \u2014 pick one."}:{ok:!1,reason:"ambiguous",candidates:m,message:(v.length===0?"No target is ready.":`${v.length} targets are ready.`)+` Pass --device <id>:${K(m)}`}}export{bt as a,qt as b,Ht as c,ct as d,mt as e,Vt as f};
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as w,b as O}from"./chunk-R5T4RLF5.js";import{a as I}from"./chunk-KBM3XHAM.js";import{e as L}from"./chunk-IDX3TOPY.js";import{a as N,b as k}from"./chunk-BKM2LWU2.js";import{a as R,b as y,c as T,d as m,e as A,f as b,g as r}from"./chunk-56PAQAX5.js";import{b as x}from"./chunk-5EOX4MEY.js";import{a as E}from"./chunk-RZ4F3BHX.js";import{a as g,j as v}from"./chunk-D6FYCAIA.js";import{platform as X,arch as Y}from"os";import P from"fs";import M from"fs";import D from"path";var V=1e3,d=0,j=new Set([130,3]),a=class t{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,n={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=n}get enabled(){return this.logger!==null}event(e,n={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let i=m(this.ids,e,n);this.logger.log(R[e],e,e,C(i))}error(e,n={}){this.logger&&(this.logger.escalate(d),this.event("ASR_ERROR",{...n,error_code:e}))}child(e,n){return new t({...this.opts,envelope:{...this.ids,operation_id:n,parent_operation_id:this.ids.operation_id,verb:"design"}},this.errorState)}async lateBindContext(e){if(!(!this.logger||this.ids.context_instance_id))try{let{ensureStoreIds:n}=await import("./store-id-EOSGEKVK.js"),{ids:i,cloned:s}=n(e);this.ids.context_lineage_id=i.context_lineage_id,this.ids.context_instance_id=i.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}agentSession(e){this.ids.agent_session_id=e}spawnEnv(){if(!this.opts.telemetryEnabled)return{};let e={TESTMUAI_USER_SESSION_ID:this.ids.session_id,TESTMUAI_OPERATION_ID:this.ids.operation_id,TESTMUAI_CLIENT_VERSION:this.opts.clientVersion,TESTMUAI_TELEMETRY_PROXY_URL:this.opts.proxyUrl};return this.ids.context_instance_id&&(e.TESTMUAI_CONTEXT_INSTANCE_ID=this.ids.context_instance_id),e}traceTee(){return e=>{if(!this.logger)return;let n=typeof e.kind=="string"?e.kind.slice(0,64):"trace",i={...C(m(this.ids,"ASR_CMD_START",{})),trace_kind:n};typeof e.code=="string"&&(i.trace_code=e.code.slice(0,64)),delete i.event,this.logger.logStep(d,`trace_${n}`,n,i)}}wireTrace(e,n,i){if(!this.logger)return;i&&this.agentSession(i);let s=n&&typeof n=="object"?n:{};switch(e){case"spawn":this.event("ASR_AGENT_SPAWN",{tier:s.tier});break;case"session_paused":this.event("ASR_SESSION_PAUSED",s);break;case"commit":this.event("ASR_COMMIT",s);break;default:this.traceTee()({kind:e,code:typeof s.code=="string"?s.code:void 0})}}banner(){return`session: ${this.ids.session_id}`}supportFooter(){return`if this keeps failing, share this id with support: ${this.ids.session_id}`}async end(e){if(!this.ended){if(this.ended=!0,e.duration_ms===void 0&&(e={...e,duration_ms:Date.now()-this.createdAt}),this.logger)if(e.exit_code===0?this.logger.discardSteps(d):this.logger.escalate(d),e.exit_code>0&&!j.has(e.exit_code)&&!this.errorState.emitted&&this.event("ASR_ERROR",{error_code:e.exit_code===2?"usage_exit_unattributed":`exit_${e.exit_code}_unattributed`,exit_code:e.exit_code}),this.event("ASR_CMD_END",e),this.opts.longSession)await this.logger.shutdown();else{let n=await this.logger.flushOnce(V);(n==="failed"||n==="timeout")&&A(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),r(null)}}writeManifestLine(e){try{let n=x(this.ids.context_instance_id??null);M.mkdirSync(D.dirname(n),{recursive:!0});let i={ts:new Date().toISOString(),session_id:this.ids.session_id,operation_id:this.ids.operation_id,agent_session_id:this.ids.agent_session_id,verb:this.ids.verb,mode:this.ids.mode,exit_code:e};M.appendFileSync(n,JSON.stringify(i)+`
2
+ import{a as w,b as O}from"./chunk-R5T4RLF5.js";import{a as I}from"./chunk-KBM3XHAM.js";import{e as L}from"./chunk-IDX3TOPY.js";import{a as N,b as k}from"./chunk-BKM2LWU2.js";import{a as R,b as y,c as T,d as m,e as A,f as b,g as r}from"./chunk-56PAQAX5.js";import{b as x}from"./chunk-5EOX4MEY.js";import{a as E}from"./chunk-RZ4F3BHX.js";import{a as g,j as v}from"./chunk-PH22FRN5.js";import{platform as X,arch as Y}from"os";import P from"fs";import M from"fs";import D from"path";var V=1e3,d=0,j=new Set([130,3]),a=class t{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,n={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=n}get enabled(){return this.logger!==null}event(e,n={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let i=m(this.ids,e,n);this.logger.log(R[e],e,e,C(i))}error(e,n={}){this.logger&&(this.logger.escalate(d),this.event("ASR_ERROR",{...n,error_code:e}))}child(e,n){return new t({...this.opts,envelope:{...this.ids,operation_id:n,parent_operation_id:this.ids.operation_id,verb:"design"}},this.errorState)}async lateBindContext(e){if(!(!this.logger||this.ids.context_instance_id))try{let{ensureStoreIds:n}=await import("./store-id-EOSGEKVK.js"),{ids:i,cloned:s}=n(e);this.ids.context_lineage_id=i.context_lineage_id,this.ids.context_instance_id=i.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}agentSession(e){this.ids.agent_session_id=e}spawnEnv(){if(!this.opts.telemetryEnabled)return{};let e={TESTMUAI_USER_SESSION_ID:this.ids.session_id,TESTMUAI_OPERATION_ID:this.ids.operation_id,TESTMUAI_CLIENT_VERSION:this.opts.clientVersion,TESTMUAI_TELEMETRY_PROXY_URL:this.opts.proxyUrl};return this.ids.context_instance_id&&(e.TESTMUAI_CONTEXT_INSTANCE_ID=this.ids.context_instance_id),e}traceTee(){return e=>{if(!this.logger)return;let n=typeof e.kind=="string"?e.kind.slice(0,64):"trace",i={...C(m(this.ids,"ASR_CMD_START",{})),trace_kind:n};typeof e.code=="string"&&(i.trace_code=e.code.slice(0,64)),delete i.event,this.logger.logStep(d,`trace_${n}`,n,i)}}wireTrace(e,n,i){if(!this.logger)return;i&&this.agentSession(i);let s=n&&typeof n=="object"?n:{};switch(e){case"spawn":this.event("ASR_AGENT_SPAWN",{tier:s.tier});break;case"session_paused":this.event("ASR_SESSION_PAUSED",s);break;case"commit":this.event("ASR_COMMIT",s);break;default:this.traceTee()({kind:e,code:typeof s.code=="string"?s.code:void 0})}}banner(){return`session: ${this.ids.session_id}`}supportFooter(){return`if this keeps failing, share this id with support: ${this.ids.session_id}`}async end(e){if(!this.ended){if(this.ended=!0,e.duration_ms===void 0&&(e={...e,duration_ms:Date.now()-this.createdAt}),this.logger)if(e.exit_code===0?this.logger.discardSteps(d):this.logger.escalate(d),e.exit_code>0&&!j.has(e.exit_code)&&!this.errorState.emitted&&this.event("ASR_ERROR",{error_code:e.exit_code===2?"usage_exit_unattributed":`exit_${e.exit_code}_unattributed`,exit_code:e.exit_code}),this.event("ASR_CMD_END",e),this.opts.longSession)await this.logger.shutdown();else{let n=await this.logger.flushOnce(V);(n==="failed"||n==="timeout")&&A(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),r(null)}}writeManifestLine(e){try{let n=x(this.ids.context_instance_id??null);M.mkdirSync(D.dirname(n),{recursive:!0});let i={ts:new Date().toISOString(),session_id:this.ids.session_id,operation_id:this.ids.operation_id,agent_session_id:this.ids.agent_session_id,verb:this.ids.verb,mode:this.ids.mode,exit_code:e};M.appendFileSync(n,JSON.stringify(i)+`
3
3
  `,{flag:"a",mode:384})}catch{}}};function C(t){let e={event:t.event,session_id:t.session_id,operation_id:t.operation_id,verb:t.verb,mode:t.mode,component:t.component,seq:t.seq,context_lineage_id:t.context_lineage_id,context_instance_id:t.context_instance_id};t.parent_operation_id&&(e.parent_operation_id=t.parent_operation_id),t.agent_session_id&&(e.agent_session_id=t.agent_session_id);for(let[n,i]of Object.entries(t.context))e[n]=i;return e}var u=process.env.KANE_TELEMETRY_URL||v;function B(){return process.env.TESTMUAI_BASE_URL?"custom":process.env.TESTMUAI_ENV==="stage"?"stage":"prod"}function _e(t){let e=process.env.KANE_TELEMETRY!=="0"&&(!process.env.VITEST||process.env.KANE_TELEMETRY==="1"),n=t.env??B(),i=null;if(t.resumeSid&&t.contextRoot)try{let o=L(t.contextRoot,t.resumeSid);o?.user_session_id&&(i=o.user_session_id)}catch{}if(!i&&t.applyPlanPath)try{let o=JSON.parse(P.readFileSync(t.applyPlanPath,"utf8"));o.telemetry?.user_session_id&&(i=o.telemetry.user_session_id)}catch{}let s=i!==null;i||(i=y());let l=null,c=null,f=!1;if(t.contextRoot&&P.existsSync(t.contextRoot))if(t.write&&e){let o=k(t.contextRoot);l=o.ids.context_lineage_id,c=o.ids.context_instance_id,f=o.cloned}else{let o=N(t.contextRoot);l=o?.context_lineage_id??null,c=o?.context_instance_id??null}let h={session_id:i,operation_id:T(),context_lineage_id:l,context_instance_id:c,verb:t.verb,mode:t.mode,component:"kane-cli"},_=null;if(e){let o=I(n),S={org_id:o.org_id??"",user_id:o.user_id??"",machine_id:o.machine_id,email:null,email_domain:"",user_type:o.user_type??"unknown",env:o.env,plan:o.plan??"unknown"},U=t.mode==="interactive"||t.mode==="cli"?"cli":"agent";_=new w({proxyUrl:u,sessionId:i,identity:S,device:{cli_version:g,platform:X(),arch:Y(),host_agent:O(),invocation_mode:U},getToken:async()=>null}),t.longSession&&_.start()}let p=new a({envelope:h,logger:_,longSession:!!t.longSession,proxyUrl:u,clientVersion:`kane-cli/${g}`,telemetryEnabled:e});return e&&(r(h),p.event("ASR_CMD_START",{resumed:s,applied_plan:!!t.applyPlanPath}),f&&p.event("ASR_CONTEXT_CLONED"),b(async o=>{try{return(await E(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok}catch{return!1}}).catch(()=>{})),p}export{B as a,_e as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{y as n}from"./chunk-D6FYCAIA.js";import{a as s}from"./chunk-HCBYKLMW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
2
+ import{y as n}from"./chunk-PH22FRN5.js";import{a as s}from"./chunk-HCBYKLMW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as c}from"./chunk-CVCVBQP6.js";import{a as n}from"./chunk-RZ4F3BHX.js";import{v as s,w as a}from"./chunk-D6FYCAIA.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
2
+ import{a as c}from"./chunk-JT7I6OST.js";import{a as n}from"./chunk-RZ4F3BHX.js";import{v as s,w as a}from"./chunk-PH22FRN5.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as B}from"./chunk-S3DAAAE5.js";import{a as g}from"./chunk-ZNNRCUHH.js";import{y as s}from"./chunk-D6FYCAIA.js";import{a as w}from"./chunk-HCBYKLMW.js";import{a as x,b as t,c as h,i as P,j as S}from"./chunk-C44QQJR4.js";import{a as C}from"./chunk-6YGTRKDT.js";import{e as T}from"./chunk-UR6MHSHU.js";var o=T(C(),1);var e=T(w(),1);function D({defaultName:i,onSubmit:c}){let[d,p]=(0,o.useState)("confirm"),[f,a]=(0,o.useState)(""),[m,u]=(0,o.useState)(null),l=(0,o.useMemo)(()=>f.trim()||i,[f,i]);return P((n,r)=>{if(d==="confirm"){if(n==="y"||n==="Y"){a(i),p("name");return}if(n==="n"||n==="N"||r.escape||r.ctrl&&n==="c"){c(null);return}if(r.return){c(i);return}return}if(r.return){if(!B(l)){u(`name "${l}" is invalid; allowed: letters, digits, underscore, hyphen`);return}c(l);return}if(r.escape||r.ctrl&&n==="c"){c(null);return}if(r.backspace||r.delete){a(v=>v.slice(0,-1)),u(null);return}n&&!r.ctrl&&!r.meta&&(a(v=>v+n),u(null))}),d==="confirm"?(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsx)(t,{color:s.orange,children:i})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save with this name"}),(0,e.jsx)(t,{color:s.dim,children:"Y \u2014 edit name"}),(0,e.jsx)(t,{color:s.dim,children:"N/esc \u2014 discard session"})]})}):(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsxs)(x,{children:[(0,e.jsx)(t,{color:s.orange,children:f}),(0,e.jsx)(t,{inverse:!0,children:" "})]})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[m&&(0,e.jsx)(t,{color:s.red,children:m}),(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save \xB7 esc \u2014 discard"})]})})}function V(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}async function Y(i){return new Promise(c=>{function d(){let{exit:a}=S(),[m,u]=(0,o.useState)(!1);return(0,o.useEffect)(()=>{if(m){let l=setTimeout(()=>a(),50);return()=>clearTimeout(l)}},[m,a]),(0,e.jsx)(D,{defaultName:i,onSubmit:l=>{c(l),u(!0)}})}let{waitUntilExit:p,unmount:f}=h((0,e.jsx)(d,{}),{stdout:process.stderr,exitOnCtrlC:!1});p().then(()=>{try{f()}catch{}})})}export{D as a,V as b,Y as c};
2
+ import{b as B}from"./chunk-S3DAAAE5.js";import{a as g}from"./chunk-HXSEA7JS.js";import{y as s}from"./chunk-PH22FRN5.js";import{a as w}from"./chunk-HCBYKLMW.js";import{a as x,b as t,c as h,i as P,j as S}from"./chunk-C44QQJR4.js";import{a as C}from"./chunk-6YGTRKDT.js";import{e as T}from"./chunk-UR6MHSHU.js";var o=T(C(),1);var e=T(w(),1);function D({defaultName:i,onSubmit:c}){let[d,p]=(0,o.useState)("confirm"),[f,a]=(0,o.useState)(""),[m,u]=(0,o.useState)(null),l=(0,o.useMemo)(()=>f.trim()||i,[f,i]);return P((n,r)=>{if(d==="confirm"){if(n==="y"||n==="Y"){a(i),p("name");return}if(n==="n"||n==="N"||r.escape||r.ctrl&&n==="c"){c(null);return}if(r.return){c(i);return}return}if(r.return){if(!B(l)){u(`name "${l}" is invalid; allowed: letters, digits, underscore, hyphen`);return}c(l);return}if(r.escape||r.ctrl&&n==="c"){c(null);return}if(r.backspace||r.delete){a(v=>v.slice(0,-1)),u(null);return}n&&!r.ctrl&&!r.meta&&(a(v=>v+n),u(null))}),d==="confirm"?(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsx)(t,{color:s.orange,children:i})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save with this name"}),(0,e.jsx)(t,{color:s.dim,children:"Y \u2014 edit name"}),(0,e.jsx)(t,{color:s.dim,children:"N/esc \u2014 discard session"})]})}):(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsxs)(x,{children:[(0,e.jsx)(t,{color:s.orange,children:f}),(0,e.jsx)(t,{inverse:!0,children:" "})]})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[m&&(0,e.jsx)(t,{color:s.red,children:m}),(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save \xB7 esc \u2014 discard"})]})})}function V(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}async function Y(i){return new Promise(c=>{function d(){let{exit:a}=S(),[m,u]=(0,o.useState)(!1);return(0,o.useEffect)(()=>{if(m){let l=setTimeout(()=>a(),50);return()=>clearTimeout(l)}},[m,a]),(0,e.jsx)(D,{defaultName:i,onSubmit:l=>{c(l),u(!0)}})}let{waitUntilExit:p,unmount:f}=h((0,e.jsx)(d,{}),{stdout:process.stderr,exitOnCtrlC:!1});p().then(()=>{try{f()}catch{}})})}export{D as a,V as b,Y as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{y as m}from"./chunk-D6FYCAIA.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a as u,b as a,j as g}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as f}from"./chunk-UR6MHSHU.js";var T=f(b(),1);function k(i,n){if(!n)return i;let l=i.trim()||n;return`\x1B]8;;${n}\x07${l}\x1B]8;;\x07`}var r=f(x(),1);function $({shareableLink:i,testCaseLink:n,codeExportDir:l,recordedTestPath:s,outputDir:o,autoExit:p=!0}){let{exit:c}=g();(0,T.useEffect)(()=>{if(!p)return;let t=setTimeout(()=>c(),100);return()=>clearTimeout(t)},[c,p]);let e=[];return s&&e.push({label:"Test",url:s,linkUrl:`file://${s}`}),o&&e.push({label:"Output",url:o,linkUrl:`file://${o}`}),i&&e.push({label:"ShareLink",url:i}),n&&e.push({label:"TestCase",url:n}),l&&!o&&e.push({label:"CodeExport",url:l,linkUrl:`file://${l}`}),e.length===0?(0,r.jsx)(r.Fragment,{}):(0,r.jsx)(u,{flexDirection:"column",marginTop:1,marginLeft:1,children:e.map(t=>(0,r.jsxs)(u,{flexDirection:"column",marginBottom:1,children:[(0,r.jsxs)(a,{color:m.orange,children:[t.label,":"]}),(0,r.jsx)(a,{color:m.dim,children:k(t.url,t.linkUrl??t.url)})]},t.label))})}export{$ as a};
2
+ import{y as m}from"./chunk-PH22FRN5.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a as u,b as a,j as g}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as f}from"./chunk-UR6MHSHU.js";var T=f(b(),1);function k(i,n){if(!n)return i;let l=i.trim()||n;return`\x1B]8;;${n}\x07${l}\x1B]8;;\x07`}var r=f(x(),1);function $({shareableLink:i,testCaseLink:n,codeExportDir:l,recordedTestPath:s,outputDir:o,autoExit:p=!0}){let{exit:c}=g();(0,T.useEffect)(()=>{if(!p)return;let t=setTimeout(()=>c(),100);return()=>clearTimeout(t)},[c,p]);let e=[];return s&&e.push({label:"Test",url:s,linkUrl:`file://${s}`}),o&&e.push({label:"Output",url:o,linkUrl:`file://${o}`}),i&&e.push({label:"ShareLink",url:i}),n&&e.push({label:"TestCase",url:n}),l&&!o&&e.push({label:"CodeExport",url:l,linkUrl:`file://${l}`}),e.length===0?(0,r.jsx)(r.Fragment,{}):(0,r.jsx)(u,{flexDirection:"column",marginTop:1,marginLeft:1,children:e.map(t=>(0,r.jsxs)(u,{flexDirection:"column",marginBottom:1,children:[(0,r.jsxs)(a,{color:m.orange,children:[t.label,":"]}),(0,r.jsx)(a,{color:m.dim,children:k(t.url,t.linkUrl??t.url)})]},t.label))})}export{$ as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as R}from"./chunk-SA2LQSYP.js";import{y as i}from"./chunk-D6FYCAIA.js";import{a as X}from"./chunk-HCBYKLMW.js";import{a,b as l,i as p}from"./chunk-C44QQJR4.js";import{a as G}from"./chunk-6YGTRKDT.js";import{e as P}from"./chunk-UR6MHSHU.js";var x=P(G(),1);var e=P(X(),1),f=5;function K(t,I){if(!I)return t;let c=I.toLowerCase();return t.filter(B=>B.label.toLowerCase().includes(c))}function J(t){let{title:I,items:c,loading:B=!1,loadingText:Y,error:L=null,itemNoun:v="items",onSelect:F,onCancel:E,defaultActiveId:w,onTab:y,extraHint:H}=t,[g,d]=(0,x.useState)(0),[S,u]=(0,x.useState)(0),[s,A]=(0,x.useState)(""),[C,h]=(0,x.useState)(null);(0,x.useEffect)(()=>{if(c.length===0)return;if(t.preserveSelectionById&&C!==null){let o=c.findIndex(n=>n.id===C);if(o>=0){u(Math.floor(o/f)),d(o%f);return}}let r=w?c.findIndex(o=>o.id===w):c.findIndex(o=>o.isActive);r>=0?(u(Math.floor(r/f)),d(r%f),t.preserveSelectionById&&h(c[r].id)):t.preserveSelectionById&&(u(0),d(0),h(c[0]?.id??null))},[c,w,t.preserveSelectionById,C]),(0,x.useEffect)(()=>{if(!t.onSearch)return;let r=setTimeout(()=>t.onSearch(s),t.searchDebounceMs??250);return()=>clearTimeout(r)},[s,t.onSearch,t.searchDebounceMs]);let b=t.onSearch?c:K(c,s),D=S*f,N=Math.min(D+f,b.length),M=Math.ceil(b.length/f),O=N-D,T=b.slice(D,N);return p((r,o)=>{if(L){o.escape&&E();return}if(o.escape){s?(A(""),d(0),u(0)):E();return}if(o.tab&&y){y();return}if(o.upArrow){if(g>0){let n=g-1;d(n),t.preserveSelectionById&&h(T[n]?.id??null)}else if(S>0){let n=S-1,m=f-1;u(n),d(m),t.preserveSelectionById&&h(b[n*f+m]?.id??null)}return}if(o.downArrow){if(g<O-1){let n=g+1;d(n),t.preserveSelectionById&&h(T[n]?.id??null)}else if(S<M-1){let n=S+1,m=0;u(n),d(m),t.preserveSelectionById&&h(b[n*f+m]?.id??null)}return}if(o.return&&T[g]){if(T[g].disabled)return;F(T[g]);return}if(o.backspace||o.delete){A(n=>n.slice(0,-1)),d(0),u(0);return}r&&!o.ctrl&&!o.meta&&(A(n=>n+r),d(0),u(0))},{isActive:!B}),B?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.secondary,children:Y??`Loading ${v}\u2026`})})]}):L?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.red,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.red,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.red,children:L})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:I}),(0,e.jsxs)(l,{color:i.dim,children:[" (",b.length,!t.onSearch&&s?`/${c.length}`:""," ",v,t.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(a,{marginTop:1,children:[(0,e.jsx)(l,{color:i.secondary,children:s?"filter: ":""}),s?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(l,{children:s}),(0,e.jsx)(l,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(l,{color:i.dim,children:["Search ",v,"\u2026"]}),(0,e.jsx)(l,{inverse:!0,children:" "})]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:t.searching?(0,e.jsxs)(l,{color:i.secondary,children:["Searching ",v,"\u2026"]}):b.length===0?(0,e.jsxs)(l,{color:i.dim,children:["No ",v,' match "',s,'"']}):T.map((r,o)=>{let n=o===g,m=n?"\u276F ":" ",$=r.disabled?i.muted:r.isActive?i.green:n?i.orange:void 0;return(0,e.jsxs)(a,{flexDirection:"column",children:[(0,e.jsxs)(l,{color:$,children:[m,r.label,r.isActive&&!r.disabled?" \u25CF selected":""]}),n&&r.disabled&&r.disabledHint&&(0,e.jsxs)(l,{color:i.red,children:[" ",r.disabledHint]})]},r.id)})}),!t.searching&&M>1&&(0,e.jsx)(a,{marginTop:1,children:(0,e.jsxs)(l,{color:i.dim,children:["Page ",S+1,"/",M]})}),t.footer&&(0,e.jsx)(a,{marginTop:1,flexDirection:"column",children:t.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...y&&H?[{keys:"tab",label:H}]:[]],escBackLabel:s?"clear":"back to chat"})]})}export{J as a};
2
+ import{a as R}from"./chunk-7VTYRTEJ.js";import{y as i}from"./chunk-PH22FRN5.js";import{a as X}from"./chunk-HCBYKLMW.js";import{a,b as l,i as p}from"./chunk-C44QQJR4.js";import{a as G}from"./chunk-6YGTRKDT.js";import{e as P}from"./chunk-UR6MHSHU.js";var x=P(G(),1);var e=P(X(),1),f=5;function K(t,I){if(!I)return t;let c=I.toLowerCase();return t.filter(B=>B.label.toLowerCase().includes(c))}function J(t){let{title:I,items:c,loading:B=!1,loadingText:Y,error:L=null,itemNoun:v="items",onSelect:F,onCancel:E,defaultActiveId:w,onTab:y,extraHint:H}=t,[g,d]=(0,x.useState)(0),[S,u]=(0,x.useState)(0),[s,A]=(0,x.useState)(""),[C,h]=(0,x.useState)(null);(0,x.useEffect)(()=>{if(c.length===0)return;if(t.preserveSelectionById&&C!==null){let o=c.findIndex(n=>n.id===C);if(o>=0){u(Math.floor(o/f)),d(o%f);return}}let r=w?c.findIndex(o=>o.id===w):c.findIndex(o=>o.isActive);r>=0?(u(Math.floor(r/f)),d(r%f),t.preserveSelectionById&&h(c[r].id)):t.preserveSelectionById&&(u(0),d(0),h(c[0]?.id??null))},[c,w,t.preserveSelectionById,C]),(0,x.useEffect)(()=>{if(!t.onSearch)return;let r=setTimeout(()=>t.onSearch(s),t.searchDebounceMs??250);return()=>clearTimeout(r)},[s,t.onSearch,t.searchDebounceMs]);let b=t.onSearch?c:K(c,s),D=S*f,N=Math.min(D+f,b.length),M=Math.ceil(b.length/f),O=N-D,T=b.slice(D,N);return p((r,o)=>{if(L){o.escape&&E();return}if(o.escape){s?(A(""),d(0),u(0)):E();return}if(o.tab&&y){y();return}if(o.upArrow){if(g>0){let n=g-1;d(n),t.preserveSelectionById&&h(T[n]?.id??null)}else if(S>0){let n=S-1,m=f-1;u(n),d(m),t.preserveSelectionById&&h(b[n*f+m]?.id??null)}return}if(o.downArrow){if(g<O-1){let n=g+1;d(n),t.preserveSelectionById&&h(T[n]?.id??null)}else if(S<M-1){let n=S+1,m=0;u(n),d(m),t.preserveSelectionById&&h(b[n*f+m]?.id??null)}return}if(o.return&&T[g]){if(T[g].disabled)return;F(T[g]);return}if(o.backspace||o.delete){A(n=>n.slice(0,-1)),d(0),u(0);return}r&&!o.ctrl&&!o.meta&&(A(n=>n+r),d(0),u(0))},{isActive:!B}),B?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.secondary,children:Y??`Loading ${v}\u2026`})})]}):L?(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.red,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:i.red,bold:!0,children:I}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(l,{color:i.red,children:L})}),(0,e.jsx)(R,{bindings:[]})]}):(0,e.jsxs)(a,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(l,{color:i.orange,bold:!0,children:I}),(0,e.jsxs)(l,{color:i.dim,children:[" (",b.length,!t.onSearch&&s?`/${c.length}`:""," ",v,t.loadingMore?" \xB7 loading more":"",")"]})]}),(0,e.jsxs)(a,{marginTop:1,children:[(0,e.jsx)(l,{color:i.secondary,children:s?"filter: ":""}),s?(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)(l,{children:s}),(0,e.jsx)(l,{inverse:!0,children:" "})]}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)(l,{color:i.dim,children:["Search ",v,"\u2026"]}),(0,e.jsx)(l,{inverse:!0,children:" "})]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:t.searching?(0,e.jsxs)(l,{color:i.secondary,children:["Searching ",v,"\u2026"]}):b.length===0?(0,e.jsxs)(l,{color:i.dim,children:["No ",v,' match "',s,'"']}):T.map((r,o)=>{let n=o===g,m=n?"\u276F ":" ",$=r.disabled?i.muted:r.isActive?i.green:n?i.orange:void 0;return(0,e.jsxs)(a,{flexDirection:"column",children:[(0,e.jsxs)(l,{color:$,children:[m,r.label,r.isActive&&!r.disabled?" \u25CF selected":""]}),n&&r.disabled&&r.disabledHint&&(0,e.jsxs)(l,{color:i.red,children:[" ",r.disabledHint]})]},r.id)})}),!t.searching&&M>1&&(0,e.jsx)(a,{marginTop:1,children:(0,e.jsxs)(l,{color:i.dim,children:["Page ",S+1,"/",M]})}),t.footer&&(0,e.jsx)(a,{marginTop:1,flexDirection:"column",children:t.footer}),(0,e.jsx)(R,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"type",label:"to search"},{keys:"\u21B5",label:"select"},...y&&H?[{keys:"tab",label:H}]:[]],escBackLabel:s?"clear":"back to chat"})]})}export{J as a};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f,c as u}from"./chunk-EYOCNMUM.js";import{d as g,k as p}from"./chunk-D6FYCAIA.js";import{readFileSync as _,writeFileSync as m,mkdirSync as b,existsSync as h}from"fs";import{dirname as v}from"path";var s={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:p,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",assertion_mode:"dom",network_ws:!1,network_sse:!1,bug_detection:"off",final_validation:!1,code_export:{enabled:!0,language:"python",skip_validation:!0},generate:{scenario_limit:2,per_scenario_limit:3,memory_enabled:!1},last_seen_version:"",hints_enabled:!0};function w(o){let{mobile:e,...i}=o,t={...i};delete t.target,delete t.device,delete t.app;let n=e??{};n.tui_target&&(t.target=n.tui_target);let r=n.default_target?.id?.trim();r&&(t.device=r),n.default_app&&(t.app=n.default_app);let a={};return n.no_reset!==void 0&&(a.no_reset=n.no_reset),n.appium_url!==void 0&&(a.appium_url=n.appium_url),Object.keys(a).length>0&&(t.mobile=a),t}function C(o){let e=o.mobile??{},i=typeof o.target=="string"?o.target:void 0,t=typeof o.device=="string"&&o.device.trim()!==""?o.device.trim():void 0,n=typeof o.app=="string"&&o.app!==""?o.app:void 0,r={},a=i??e.tui_target;if(a&&(r.tui_target=a),t){let d=f(a,void 0);(d.kind==="emulator"||d.kind==="simulator")&&(r.default_target={platform:u(d.kind),kind:d.kind,id:t})}else e.default_target?.id?.trim()&&(r.default_target=e.default_target);let l=n??e.default_app;return l&&(r.default_app=l),e.no_reset!==void 0&&(r.no_reset=e.no_reset),e.appium_url!==void 0&&(r.appium_url=e.appium_url),Object.keys(r).length>0?r:void 0}var c=class{constructor(e=g){this.path=e}exists(){return h(this.path)}load(){try{let e=_(this.path,"utf-8"),i=JSON.parse(e),t=C(i),{target:n,device:r,app:a,...l}=i;return{...s,...l,...t?{mobile:t}:{},code_export:{...s.code_export,...i.code_export??{}},generate:{...s.generate,...i.generate??{}}}}catch{return{...s,code_export:{...s.code_export},generate:{...s.generate}}}}write(e){try{b(v(this.path),{recursive:!0}),m(this.path,JSON.stringify(w(e),null,2)+`
2
+ import{a as f,c as u}from"./chunk-EYOCNMUM.js";import{d as g,k as p}from"./chunk-PH22FRN5.js";import{readFileSync as _,writeFileSync as m,mkdirSync as b,existsSync as h}from"fs";import{dirname as v}from"path";var s={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:p,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",assertion_mode:"dom",network_ws:!1,network_sse:!1,bug_detection:"off",final_validation:!1,code_export:{enabled:!0,language:"python",skip_validation:!0},generate:{scenario_limit:2,per_scenario_limit:3,memory_enabled:!1},last_seen_version:"",hints_enabled:!0};function w(o){let{mobile:e,...i}=o,t={...i};delete t.target,delete t.device,delete t.app;let n=e??{};n.tui_target&&(t.target=n.tui_target);let r=n.default_target?.id?.trim();r&&(t.device=r),n.default_app&&(t.app=n.default_app);let a={};return n.no_reset!==void 0&&(a.no_reset=n.no_reset),n.appium_url!==void 0&&(a.appium_url=n.appium_url),Object.keys(a).length>0&&(t.mobile=a),t}function C(o){let e=o.mobile??{},i=typeof o.target=="string"?o.target:void 0,t=typeof o.device=="string"&&o.device.trim()!==""?o.device.trim():void 0,n=typeof o.app=="string"&&o.app!==""?o.app:void 0,r={},a=i??e.tui_target;if(a&&(r.tui_target=a),t){let d=f(a,void 0);(d.kind==="emulator"||d.kind==="simulator")&&(r.default_target={platform:u(d.kind),kind:d.kind,id:t})}else e.default_target?.id?.trim()&&(r.default_target=e.default_target);let l=n??e.default_app;return l&&(r.default_app=l),e.no_reset!==void 0&&(r.no_reset=e.no_reset),e.appium_url!==void 0&&(r.appium_url=e.appium_url),Object.keys(r).length>0?r:void 0}var c=class{constructor(e=g){this.path=e}exists(){return h(this.path)}load(){try{let e=_(this.path,"utf-8"),i=JSON.parse(e),t=C(i),{target:n,device:r,app:a,...l}=i;return{...s,...l,...t?{mobile:t}:{},code_export:{...s.code_export,...i.code_export??{}},generate:{...s.generate,...i.generate??{}}}}catch{return{...s,code_export:{...s.code_export},generate:{...s.generate}}}}write(e){try{b(v(this.path),{recursive:!0}),m(this.path,JSON.stringify(w(e),null,2)+`
3
3
  `)}catch(i){let t=i instanceof Error?i.message:String(i);process.stderr.write(`[config] Failed to save config: ${t}
4
4
  `)}}set(e,i){let t=this.load();t[e]=i,this.write(t)}save(e){this.write({...this.load(),...e})}getMobile(){return this.load().mobile??{}}setMobile(e){let i={...this.getMobile()};for(let t of Object.keys(e)){let n=e[t];n===void 0?delete i[t]:i[t]=n}this.set("mobile",Object.keys(i).length>0?i:void 0)}writeRaw(e){this.write(e)}};export{c as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as k}from"./chunk-RFHMDQXZ.js";import{a as b}from"./chunk-UBTNWAKK.js";import{a as C}from"./chunk-5OVEBP4D.js";import{q as m,r as u,s as f,t as x,u as y}from"./chunk-D6FYCAIA.js";import{createServer as S}from"http";import{randomBytes as A}from"crypto";import{URL as L}from"url";var P=class{profile;environment;creds;oauth;constructor(r="default",o="prod",e){this.profile=r,this.environment=o,this.creds=e??new C,this.oauth=new b(o)}async login(){let{server:r,port:o}=await this.startCallbackServer(),e=y(o);try{let t=this.creds.loadClient(this.profile,this.environment),i=t?.redirect_uris;(!t||!i?.includes(e))&&(t=await this.oauth.registerClient(e),this.creds.saveClient(this.profile,this.environment,t));let c=t.client_id,[h,d]=b.generatePkce(),a=A(32).toString("hex"),n=this.oauth.buildAuthorizationUrl(c,d,a,e),l=await this.waitForCallback(r,o,n,a);if(!l)throw new Error("Login cancelled or timed out");let p=await this.oauth.exchangeCode(l,c,h,e),g={access_token:p.access_token,refresh_token:p.refresh_token,expires_at:Math.floor(Date.now()/1e3)+p.expires_in,scope:p.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,g),this.creds.setActiveProfile(this.profile),g}catch(t){throw r.close(),t}}startCallbackServer(){return new Promise((r,o)=>{let e=u,t=()=>{let i=S();i.on("error",c=>{c.code==="EADDRINUSE"&&e<f?(e++,t()):o(new Error(`Failed to start callback server: ${c.message}. Ports ${u}-${f} are all in use.`))}),i.listen(e,m,()=>{r({server:i,port:e})})};t()})}waitForCallback(r,o,e,t){return new Promise(i=>{let c=!1,h=setTimeout(()=>d(null),12e4),d=a=>{c||(c=!0,clearTimeout(h),r.close(),i(a))};r.on("request",(a,n)=>{let l=new L(a.url??"/",`http://${m}:${o}`);if(l.pathname!==x){n.writeHead(404),n.end();return}let p=l.searchParams.get("state"),g=l.searchParams.get("code");if(l.searchParams.get("error")){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),d(null);return}if(p!==t){n.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),d(null);return}n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),d(g)}),k(e).catch(a=>{let n=a instanceof Error?a.message:String(a);process.stderr.write(`[auth] Could not open browser: ${n}
2
+ import{c as k}from"./chunk-RFHMDQXZ.js";import{a as b}from"./chunk-A3PGLDQY.js";import{a as C}from"./chunk-XHNPNYJP.js";import{q as m,r as u,s as f,t as x,u as y}from"./chunk-PH22FRN5.js";import{createServer as S}from"http";import{randomBytes as A}from"crypto";import{URL as L}from"url";var P=class{profile;environment;creds;oauth;constructor(r="default",o="prod",e){this.profile=r,this.environment=o,this.creds=e??new C,this.oauth=new b(o)}async login(){let{server:r,port:o}=await this.startCallbackServer(),e=y(o);try{let t=this.creds.loadClient(this.profile,this.environment),i=t?.redirect_uris;(!t||!i?.includes(e))&&(t=await this.oauth.registerClient(e),this.creds.saveClient(this.profile,this.environment,t));let c=t.client_id,[h,d]=b.generatePkce(),a=A(32).toString("hex"),n=this.oauth.buildAuthorizationUrl(c,d,a,e),l=await this.waitForCallback(r,o,n,a);if(!l)throw new Error("Login cancelled or timed out");let p=await this.oauth.exchangeCode(l,c,h,e),g={access_token:p.access_token,refresh_token:p.refresh_token,expires_at:Math.floor(Date.now()/1e3)+p.expires_in,scope:p.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,g),this.creds.setActiveProfile(this.profile),g}catch(t){throw r.close(),t}}startCallbackServer(){return new Promise((r,o)=>{let e=u,t=()=>{let i=S();i.on("error",c=>{c.code==="EADDRINUSE"&&e<f?(e++,t()):o(new Error(`Failed to start callback server: ${c.message}. Ports ${u}-${f} are all in use.`))}),i.listen(e,m,()=>{r({server:i,port:e})})};t()})}waitForCallback(r,o,e,t){return new Promise(i=>{let c=!1,h=setTimeout(()=>d(null),12e4),d=a=>{c||(c=!0,clearTimeout(h),r.close(),i(a))};r.on("request",(a,n)=>{let l=new L(a.url??"/",`http://${m}:${o}`);if(l.pathname!==x){n.writeHead(404),n.end();return}let p=l.searchParams.get("state"),g=l.searchParams.get("code");if(l.searchParams.get("error")){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),d(null);return}if(p!==t){n.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),d(null);return}n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(v({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),d(g)}),k(e).catch(a=>{let n=a instanceof Error?a.message:String(a);process.stderr.write(`[auth] Could not open browser: ${n}
3
3
  Please open this URL manually: ${e}
4
4
  `)})})}};function v(s){let r=s.state==="success",o=r?"#22c55e":"#ef4444",e=r?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)",t=r?'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg>':'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',i=s.autoClose?"<script>setTimeout(function(){try{window.close();}catch(e){}}, 1500);</script>":"";return`<!doctype html>
5
5
  <html lang="en">
@@ -1,10 +1,10 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as ce}from"./chunk-YKTYVJBN.js";import{a as k,b as se,c as ie,d as ae,k as P}from"./chunk-X2FM67OM.js";import{a as D,b as F}from"./chunk-2UIHS2FH.js";import{a as J}from"./chunk-N2P4MI32.js";import{b as B,d as M}from"./chunk-NVGBE2DR.js";import{A as x}from"./chunk-TH47OOBV.js";import{x as oe}from"./chunk-D6FYCAIA.js";var L="https://integrations.lambdatest.com",b=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function Re(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${oe[n].shareApiBaseUrl}/lis/api/v1`}function $e(t){let n=t.env??process.env,e=t.auth?.TESTMUAI_BASIC_AUTH||n.TESTMUAI_BASIC_AUTH;if(e)return{authorization:`Basic ${e}`};let r=t.auth?.TESTMUAI_API_KEY||n.TESTMUAI_API_KEY;return r?{authorization:`Bearer ${r}`}:{}}function $(t){let n=t.split(`
3
- `,1)[0].replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return n.length>200?`${n.slice(0,200)}\u2026`:n}function Te(t,n,e="the issue"){return t===401||t===403?new b("LIS_AUTH","credentials rejected \u2014 run `kane-cli login` and retry"):t>=500?new b("LIS_UNAVAILABLE",`the integrations service returned an error (HTTP ${t}) \u2014 retry later`):new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${e}: ${$(n)||`HTTP ${t}`}`)}function j(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{throw new b("LIS_UNAVAILABLE","the integrations service returned a malformed response \u2014 retry later")}}function ee(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{return{}}}function ue(t){return ee(t).code}function C(t,n="the issue"){let e=ee(t);switch(e.code){case"TOKEN_EXPIRED":return new b("LIS_SETUP",`your Atlassian connection needs a resync \u2014 reconnect at ${L} and retry`);case"NOT_INSTALLED":return new b("LIS_SETUP",`no Atlassian connection for this account \u2014 create one at ${L} and retry`);case"SCOPE_MISSING":return new b("LIS_SETUP",`the connection has no Confluence access \u2014 reconnect with Confluence at ${L} and retry`);case"FORBIDDEN":return new b("LIS_FORBIDDEN",`you don't have access to ${n}`);case"NOT_FOUND":return new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${n}: ${$(e.message??"")||"not found"}`);case"PAYLOAD_TOO_LARGE":return new b("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");case"INVALID_PAYLOAD":return new b("LIS_UNAVAILABLE",`the integrations service rejected the request (${$(e.message??"")||"invalid payload"}) \u2014 retry later`);case"NOT_SUPPORTED":return new b("LIS_UNAVAILABLE","the integrations service does not support this operation yet");case"UPSTREAM_ERROR":case"UPSTREAM_TIMEOUT":return new b("LIS_UNAVAILABLE","Atlassian is not responding through the integrations service \u2014 retry later");default:return Te(t.status,e.message??"",n)}}var Ce=3e4,Oe=5;async function O(t,n,e){let r=e.env??process.env,l=e.fetchImpl??fetch;for(let o=0;;o++){let d=new AbortController,f=setTimeout(()=>d.abort(),Ce);try{let i=await l(`${Re(r)}${t}`,{...n,headers:{"content-type":"application/json",...$e(e),...n.headers??{}},signal:d.signal}),c=await Promise.race([i.arrayBuffer(),new Promise((a,s)=>{d.signal.addEventListener("abort",()=>s(new DOMException("aborted","AbortError")),{once:!0})})]),u={status:i.status,ok:i.ok,headers:i.headers,bytes:Buffer.from(c)};if(u.status===429){if(o>0)throw new b("LIS_RATE_LIMITED","the integrations service is busy \u2014 try again in a moment");let a=ee(u).data?.retry_after_sec,s=Math.min(Math.max(typeof a=="number"&&Number.isFinite(a)?a:1,0),Oe);clearTimeout(f),await new Promise(y=>setTimeout(y,s*1e3));continue}return u}catch(i){throw i instanceof b?i:d.signal.aborted?new b("LIS_UNAVAILABLE","the integrations service did not respond within 30 seconds \u2014 retry later"):new b("LIS_UNAVAILABLE",`could not reach the integrations service (${$(i instanceof Error?i.message:String(i))}) \u2014 check your connection and retry`)}finally{clearTimeout(f)}}}function K(t){let n=t.headers.get("content-type")??"application/octet-stream";if(n.includes("json"))try{let e=JSON.parse(t.bytes.toString("utf8")),r=e.content??e.data?.content;if(typeof r=="string")return{bytes:Buffer.from(r,"base64"),mediaType:e.mime_type??e.data?.mime_type??"application/octet-stream"}}catch{}return{bytes:t.bytes,mediaType:n}}async function V(t={}){let n=await O("/jira/info",{method:"GET"},t);if(!n.ok)throw C(n);let e=j(n),r=(e.data?.SELECTED_PROJECTS??[]).map(l=>l?.key).filter(l=>typeof l=="string"&&l.length>0);return{installed:e.data?.INSTALLED==="YES",selectAll:e.data?.SELECT_ALL===!0,selectedProjects:r,capabilities:{document:e.data?.capabilities?.document===!0,comments:e.data?.capabilities?.comments===!0}}}async function W(t,n={}){let e=await O("/jira/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"jira",issueKey:t})},n);if(!e.ok)throw C(e);let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${$(r.message??"")||"issue not found or not accessible"}`);return r.data}var le=100,Ne=5e3,ke=60;async function G(t,n={}){let e=[],r=new Set,l=null,o=0;for(let d=0;;d++){if(d>=ke)throw new b("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let f=await O("/jira/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:le,cursor:l,start_at:o,order_by:"created",fetch_all:!1})},n);if(!f.ok)throw C(f,"the issue's comments");let i=j(f);if(i.type==="error"||!i.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${$(i.message??"")||"unavailable"}`);for(let v of i.data.comments??[]){let m=String(v.id);r.has(m)||(r.add(m),e.push(v))}let c=i.data.pagination;if(!c?.has_more)return e;if(e.length>=Ne)throw new b("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let u=c.next_cursor??null,a=c.next_start_at!=null,s=a?c.next_start_at:o+le;if(!(u!=null&&u!==l||u==null&&a&&s!==o))throw new b("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");l=u,o=s}}async function Y(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok){if(ue(e)===void 0){if(e.status===413)throw new b("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");if(e.status===404)throw new b("JIRA_NOT_CONNECTED",`Jira is not connected for this account \u2014 connect it at ${L} and retry`)}throw C(e,`attachment ${t}`)}return K(e)}var H="kane.source.jira/2";function pe(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t)){let n=t.map(pe).filter(e=>e!==null);return n.length===0?null:n.join(", ")}if(t!==null&&typeof t=="object"){let n=t;for(let e of["name","value","displayName"])if(typeof n[e]=="string")return n[e];return null}return null}function de(t,n,e){let r=[],l={},o=t.additional_fields??{};for(let u of Object.keys(o).sort()){let a=pe(o[u]);if(a===null){r.push(`field "${u}" has no stable text form \u2014 dropped from the envelope`);continue}l[u]=a}let d=[...t.attachments??[]].map(u=>({id:String(u.id),filename:u.filename??"",media_type:u.mime_type??"application/octet-stream",size:u.size??0})).sort((u,a)=>{let s=Number(u.id),y=Number(a.id);return Number.isFinite(s)&&Number.isFinite(y)?s-y:u.id<a.id?-1:u.id>a.id?1:0}),f=e.map(u=>({id:String(u.id),author:u.author?.display_name??"",body:u.body??"",created:u.created??""})).sort((u,a)=>{if(u.created!==a.created)return u.created<a.created?-1:1;let s=Number(u.id),y=Number(a.id);return Number.isFinite(s)&&Number.isFinite(y)&&s!==y?s-y:u.id<a.id?-1:u.id>a.id?1:0}),i=t.key;if(!/^[A-Za-z][A-Za-z0-9_]*-\d+$/.test(i))throw new Error(`cannot build a stable identity for issue key "${i}" \u2014 expected a PROJECT-NUMBER key`);let c={schema:H,site:n,project:i.slice(0,i.lastIndexOf("-")),issue:{id:t.id,key:i},content:{summary:t.summary??"",description:t.description??"",fields:l},attachments:d,comments:f};return{bytes:Buffer.from(JSON.stringify(c),"utf8"),envelope:c,warnings:r}}var me=64,Pe=16,je=6e6,Ue=5e7,xe=12e6,Be={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Me=new Set(["png","jpeg","webp"]);function fe(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("JIRA_ENVELOPE_SCHEMA: source bytes are not a kane jira envelope")}if(e.schema!==H)throw new Error(`JIRA_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${H}`);let r=[],l=new Map,o=[],d=0,f=new Map,i=[];for(let a=0;a<e.attachments.length;a++){let s=e.attachments[a],y=`i${a+1}`,v=`attachment:${s.filename}`,m=I=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${I?"":" \u2014 not delivered"})`,g=(I,A,T)=>{r.push({ref:y,loc:v,media_type:I,...T?.blob?{blob:T.blob}:{},...T?.appearance?{appearance:T.appearance}:{},delivery:A,...T?.duplicate_of?{duplicate_of:T.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),i.push(m(!1));continue}let S;try{S=await t.fetchAttachment(s.id)}catch{g(s.media_type,"external-image-not-fetched"),i.push(m(!1));continue}let h=S.bytes,p=D(h),_=Be[p.format],E=B(h);if(l.set(E,h),!Me.has(p.format)){let I=p.format==="gif"||p.format==="bmp"||p.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(_,I,{blob:E}),i.push(m(!1));continue}if(p.width===void 0||p.height===void 0||p.width*p.height>Ue){g(_,"undecodable",{blob:E}),i.push(m(!1));continue}let w;if(p.format==="png"||p.format==="jpeg"){let I=F(h,p.format);if(I===null){g(_,"undecodable",{blob:E}),i.push(m(!1));continue}w=J(I.data,{width:I.width,height:I.height,channels:I.channels})}if(p.width<me||p.height<me){g(_,"below-dimension-floor",{blob:E,appearance:w}),i.push(m(!1));continue}let R=f.get(E);if(R!==void 0){g(_,"duplicate",{blob:E,appearance:w,duplicate_of:R}),i.push(m(!1));continue}if(h.byteLength>je){g(_,"image-too-large",{blob:E,appearance:w}),i.push(m(!1));continue}if(d+h.byteLength>xe){g(_,"vision-byte-budget-reached",{blob:E,appearance:w}),i.push(m(!1));continue}if(o.length>=Pe){g(_,"image-cap-reached",{blob:E,appearance:w}),i.push(m(!1));continue}f.set(E,y),d+=h.byteLength,o.push(y),g(_,"selected",{blob:E,appearance:w}),i.push(m(!0))}let c=[];c.push(`${e.issue.key} \xB7 ${e.site}/${e.project}`,`Summary: ${e.content.summary}`),e.content.description!==""&&c.push("",...e.content.description.split(`
2
+ import{a as D,b as F}from"./chunk-2UIHS2FH.js";import{a as ce}from"./chunk-YKTYVJBN.js";import{a as k,b as se,c as ie,d as ae,k as P}from"./chunk-X2FM67OM.js";import{a as J}from"./chunk-N2P4MI32.js";import{b as B,d as M}from"./chunk-NVGBE2DR.js";import{A as x}from"./chunk-TH47OOBV.js";import{x as oe}from"./chunk-PH22FRN5.js";var v="https://integrations.lambdatest.com",b=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function Re(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${oe[n].shareApiBaseUrl}/lis/api/v1`}function $e(t){let n=t.env??process.env,e=t.auth?.TESTMUAI_BASIC_AUTH||n.TESTMUAI_BASIC_AUTH;if(e)return{authorization:`Basic ${e}`};let r=t.auth?.TESTMUAI_API_KEY||n.TESTMUAI_API_KEY;return r?{authorization:`Bearer ${r}`}:{}}function $(t){let n=t.split(`
3
+ `,1)[0].replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return n.length>200?`${n.slice(0,200)}\u2026`:n}function Te(t,n,e="the issue"){return t===401||t===403?new b("LIS_AUTH","credentials rejected \u2014 run `kane-cli login` and retry"):t>=500?new b("LIS_UNAVAILABLE",`the integrations service returned an error (HTTP ${t}) \u2014 retry later`):new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${e}: ${$(n)||`HTTP ${t}`}`)}function j(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{throw new b("LIS_UNAVAILABLE","the integrations service returned a malformed response \u2014 retry later")}}function ee(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{return{}}}function ue(t){return ee(t).code}function C(t,n="the issue"){let e=ee(t);switch(e.code){case"TOKEN_EXPIRED":return new b("LIS_SETUP",`your Atlassian connection needs a resync \u2014 reconnect at ${v} and retry`);case"NOT_INSTALLED":return new b("LIS_SETUP",`no Atlassian connection for this account \u2014 create one at ${v} and retry`);case"SCOPE_MISSING":return new b("LIS_SETUP",`the connection has no Confluence access \u2014 reconnect with Confluence at ${v} and retry`);case"FORBIDDEN":return new b("LIS_FORBIDDEN",`you don't have access to ${n}`);case"NOT_FOUND":return new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${n}: ${$(e.message??"")||"not found"}`);case"PAYLOAD_TOO_LARGE":return new b("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");case"INVALID_PAYLOAD":return new b("LIS_UNAVAILABLE",`the integrations service rejected the request (${$(e.message??"")||"invalid payload"}) \u2014 retry later`);case"NOT_SUPPORTED":return new b("LIS_UNAVAILABLE","the integrations service does not support this operation yet");case"UPSTREAM_ERROR":case"UPSTREAM_TIMEOUT":return new b("LIS_UNAVAILABLE","Atlassian is not responding through the integrations service \u2014 retry later");default:return Te(t.status,e.message??"",n)}}var Ce=3e4,Oe=5;async function O(t,n,e){let r=e.env??process.env,l=e.fetchImpl??fetch;for(let o=0;;o++){let d=new AbortController,f=setTimeout(()=>d.abort(),Ce);try{let i=await l(`${Re(r)}${t}`,{...n,headers:{"content-type":"application/json",...$e(e),...n.headers??{}},signal:d.signal}),c=await Promise.race([i.arrayBuffer(),new Promise((a,s)=>{d.signal.addEventListener("abort",()=>s(new DOMException("aborted","AbortError")),{once:!0})})]),u={status:i.status,ok:i.ok,headers:i.headers,bytes:Buffer.from(c)};if(u.status===429){if(o>0)throw new b("LIS_RATE_LIMITED","the integrations service is busy \u2014 try again in a moment");let a=ee(u).data?.retry_after_sec,s=Math.min(Math.max(typeof a=="number"&&Number.isFinite(a)?a:1,0),Oe);clearTimeout(f),await new Promise(y=>setTimeout(y,s*1e3));continue}return u}catch(i){throw i instanceof b?i:d.signal.aborted?new b("LIS_UNAVAILABLE","the integrations service did not respond within 30 seconds \u2014 retry later"):new b("LIS_UNAVAILABLE",`could not reach the integrations service (${$(i instanceof Error?i.message:String(i))}) \u2014 check your connection and retry`)}finally{clearTimeout(f)}}}function K(t){let n=t.headers.get("content-type")??"application/octet-stream";if(n.includes("json"))try{let e=JSON.parse(t.bytes.toString("utf8")),r=e.content??e.data?.content;if(typeof r=="string")return{bytes:Buffer.from(r,"base64"),mediaType:e.mime_type??e.data?.mime_type??"application/octet-stream"}}catch{}return{bytes:t.bytes,mediaType:n}}async function V(t={}){let n=await O("/jira/info",{method:"GET"},t);if(!n.ok)throw C(n);let e=j(n),r=(e.data?.SELECTED_PROJECTS??[]).map(l=>l?.key).filter(l=>typeof l=="string"&&l.length>0);return{installed:e.data?.INSTALLED==="YES",selectAll:e.data?.SELECT_ALL===!0,selectedProjects:r,capabilities:{document:e.data?.capabilities?.document===!0,comments:e.data?.capabilities?.comments===!0}}}async function W(t,n={}){let e=await O("/jira/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"jira",issueKey:t})},n);if(!e.ok)throw C(e);let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${$(r.message??"")||"issue not found or not accessible"}`);return r.data}var le=100,Ne=5e3,ke=60;async function G(t,n={}){let e=[],r=new Set,l=null,o=0;for(let d=0;;d++){if(d>=ke)throw new b("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let f=await O("/jira/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:le,cursor:l,start_at:o,order_by:"created",fetch_all:!1})},n);if(!f.ok)throw C(f,"the issue's comments");let i=j(f);if(i.type==="error"||!i.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${$(i.message??"")||"unavailable"}`);for(let L of i.data.comments??[]){let m=String(L.id);r.has(m)||(r.add(m),e.push(L))}let c=i.data.pagination;if(!c?.has_more)return e;if(e.length>=Ne)throw new b("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let u=c.next_cursor??null,a=c.next_start_at!=null,s=a?c.next_start_at:o+le;if(!(u!=null&&u!==l||u==null&&a&&s!==o))throw new b("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");l=u,o=s}}async function Y(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok){if(ue(e)===void 0){if(e.status===413)throw new b("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");if(e.status===404)throw new b("JIRA_NOT_CONNECTED",`Jira is not connected for this account \u2014 connect it at ${v} and retry`)}throw C(e,`attachment ${t}`)}return K(e)}var H="kane.source.jira/2";function pe(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t)){let n=t.map(pe).filter(e=>e!==null);return n.length===0?null:n.join(", ")}if(t!==null&&typeof t=="object"){let n=t;for(let e of["name","value","displayName"])if(typeof n[e]=="string")return n[e];return null}return null}function de(t,n,e){let r=[],l={},o=t.additional_fields??{};for(let u of Object.keys(o).sort()){let a=pe(o[u]);if(a===null){r.push(`field "${u}" has no stable text form \u2014 dropped from the envelope`);continue}l[u]=a}let d=[...t.attachments??[]].map(u=>({id:String(u.id),filename:u.filename??"",media_type:u.mime_type??"application/octet-stream",size:u.size??0})).sort((u,a)=>{let s=Number(u.id),y=Number(a.id);return Number.isFinite(s)&&Number.isFinite(y)?s-y:u.id<a.id?-1:u.id>a.id?1:0}),f=e.map(u=>({id:String(u.id),author:u.author?.display_name??"",body:u.body??"",created:u.created??""})).sort((u,a)=>{if(u.created!==a.created)return u.created<a.created?-1:1;let s=Number(u.id),y=Number(a.id);return Number.isFinite(s)&&Number.isFinite(y)&&s!==y?s-y:u.id<a.id?-1:u.id>a.id?1:0}),i=t.key;if(!/^[A-Za-z][A-Za-z0-9_]*-\d+$/.test(i))throw new Error(`cannot build a stable identity for issue key "${i}" \u2014 expected a PROJECT-NUMBER key`);let c={schema:H,site:n,project:i.slice(0,i.lastIndexOf("-")),issue:{id:t.id,key:i},content:{summary:t.summary??"",description:t.description??"",fields:l},attachments:d,comments:f};return{bytes:Buffer.from(JSON.stringify(c),"utf8"),envelope:c,warnings:r}}var me=64,Pe=16,je=6e6,Ue=5e7,xe=12e6,Be={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Me=new Set(["png","jpeg","webp"]);function fe(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("JIRA_ENVELOPE_SCHEMA: source bytes are not a kane jira envelope")}if(e.schema!==H)throw new Error(`JIRA_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${H}`);let r=[],l=new Map,o=[],d=0,f=new Map,i=[];for(let a=0;a<e.attachments.length;a++){let s=e.attachments[a],y=`i${a+1}`,L=`attachment:${s.filename}`,m=I=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${I?"":" \u2014 not delivered"})`,g=(I,A,T)=>{r.push({ref:y,loc:L,media_type:I,...T?.blob?{blob:T.blob}:{},...T?.appearance?{appearance:T.appearance}:{},delivery:A,...T?.duplicate_of?{duplicate_of:T.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),i.push(m(!1));continue}let S;try{S=await t.fetchAttachment(s.id)}catch{g(s.media_type,"external-image-not-fetched"),i.push(m(!1));continue}let h=S.bytes,p=D(h),_=Be[p.format],E=B(h);if(l.set(E,h),!Me.has(p.format)){let I=p.format==="gif"||p.format==="bmp"||p.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(_,I,{blob:E}),i.push(m(!1));continue}if(p.width===void 0||p.height===void 0||p.width*p.height>Ue){g(_,"undecodable",{blob:E}),i.push(m(!1));continue}let w;if(p.format==="png"||p.format==="jpeg"){let I=F(h,p.format);if(I===null){g(_,"undecodable",{blob:E}),i.push(m(!1));continue}w=J(I.data,{width:I.width,height:I.height,channels:I.channels})}if(p.width<me||p.height<me){g(_,"below-dimension-floor",{blob:E,appearance:w}),i.push(m(!1));continue}let R=f.get(E);if(R!==void 0){g(_,"duplicate",{blob:E,appearance:w,duplicate_of:R}),i.push(m(!1));continue}if(h.byteLength>je){g(_,"image-too-large",{blob:E,appearance:w}),i.push(m(!1));continue}if(d+h.byteLength>xe){g(_,"vision-byte-budget-reached",{blob:E,appearance:w}),i.push(m(!1));continue}if(o.length>=Pe){g(_,"image-cap-reached",{blob:E,appearance:w}),i.push(m(!1));continue}f.set(E,y),d+=h.byteLength,o.push(y),g(_,"selected",{blob:E,appearance:w}),i.push(m(!0))}let c=[];c.push(`${e.issue.key} \xB7 ${e.site}/${e.project}`,`Summary: ${e.content.summary}`),e.content.description!==""&&c.push("",...e.content.description.split(`
4
4
  `));let u=Object.keys(e.content.fields);return u.length>0&&c.push("","--- fields ---",...u.map(a=>`${a}: ${e.content.fields[a]}`)),i.length>0&&c.push("","--- attachments ---",...i),e.comments.length>0&&(c.push("","--- comments ---"),e.comments.forEach((a,s)=>{s>0&&c.push(""),c.push(`[${s+1}] ${a.author} \xB7 ${a.created}`,...a.body.split(`
5
5
  `))})),{projection:c.join(`
6
6
  `)+`
7
- `,inventory:r,blobs:l,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var Je=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function z(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.lastIndexOf("browse");if(r===-1||r+1>=e.length)return null;let l=e[r+1];return Je.test(l)?{site:n.hostname,issueKey:l.toUpperCase()}:null}function X(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return typeof d.site=="string"&&d.site.length>0?d.site:null}catch{return null}}async function De(t,n,e,r,l){let o=z(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Jira issue URL (https://<site>/browse/KEY-123)`),{code:1};let d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G};try{let i={auth:await(l?.authEnv??(await import("./auth-OMWFVDL2.js")).resolveLisAuthEnv)(),env:process.env},c=await d.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${L} and retry`),{code:1};if(c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issue comments yet \u2014 resync it at ${L} and retry`),{code:1};let u=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(u))return(e.err??e.out)(`error: ${t}: project ${u} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${L}`),{code:1};let a=await d.jiraIssue(o.issueKey,i),s=await d.jiraComments(o.issueKey,i),y=o.site;if(a.host)try{y=new URL(a.host).hostname}catch{y=a.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:v,warnings:m}=de(a,y,s),g=n??o.issueKey.toLowerCase();k(g);let S=X(r,g);if(S!==null&&S!==y)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${S}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let h=await P({contextDir:r,bytes:v,media:se,sourceId:g,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{jira:fe({fetchAttachment:p=>d.jiraAttachment(p,i)})}});e.out(U(e.isTTY,h,o.issueKey));for(let p of m)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: jira, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(f){return f instanceof b?((e.err??e.out)(`error: ${t}: ${f.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${Fe(f instanceof Error?f.message:String(f))}`),{code:1})}}function Fe(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the issue's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the description or attachments in Jira and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the issue's text is too large to ingest \u2014 trim the description in Jira and retry":t}var ge={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>z(t)!==null,ingest:De,sourceIdFor:t=>{let n=z(t);return n?n.issueKey.toLowerCase():null}};async function he(t,n={}){let e=await O("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw C(e,"the page");let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${$(r.message??"")||"page not found or not accessible"}`);return r.data}async function ye(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw C(e,"the page's attachment");return{bytes:K(e).bytes}}var q="kane.source.confluence/1";function be(t,n){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this page \u2014 the integrations service returned no page id");let e=[...t.labels??[]].filter(o=>typeof o=="string").sort(),r=[...t.attachments??[]].map(o=>({id:String(o.id),filename:o.filename??"",media_type:o.mime_type??"application/octet-stream",size:o.size??0})).sort((o,d)=>o.id<d.id?-1:o.id>d.id?1:0),l={schema:q,site:n,page:{id:t.id},space:{key:t.space?.key??""},title:t.title??"",labels:e,content:{body:t.body??""},attachments:r};return{bytes:Buffer.from(JSON.stringify(l),"utf8"),envelope:l,warnings:[]}}var _e=64,Ke=16,Ve=6e6,We=5e7,Ge=12e6,Ye={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},He=new Set(["png","jpeg","webp"]);function Ee(t){let n=new Map(Object.entries(t.downloads));return async e=>{let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw new Error("CONFLUENCE_ENVELOPE_SCHEMA: source bytes are not a kane confluence envelope")}if(r.schema!==q)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${q}`);let l=[],o=new Map,d=[],f=0,i=new Map,c=[];for(let a=0;a<r.attachments.length;a++){let s=r.attachments[a],y=`i${a+1}`,v=`attachment:${s.filename}`,m=A=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${A?"":" \u2014 not delivered"})`,g=(A,T,N)=>{l.push({ref:y,loc:v,media_type:A,...N?.blob?{blob:N.blob}:{},...N?.appearance?{appearance:N.appearance}:{},delivery:T,...N?.duplicate_of?{duplicate_of:N.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),c.push(m(!1));continue}let S=n.get(s.id);if(!S){g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let h;try{h=await t.fetchAttachment({id:s.id,download:S})}catch{g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let p=h.bytes,_=D(p),E=Ye[_.format],w=B(p);if(o.set(w,p),!He.has(_.format)){let A=_.format==="gif"||_.format==="bmp"||_.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(E,A,{blob:w}),c.push(m(!1));continue}if(_.width===void 0||_.height===void 0||_.width*_.height>We){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}let R;if(_.format==="png"||_.format==="jpeg"){let A=F(p,_.format);if(A===null){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}R=J(A.data,{width:A.width,height:A.height,channels:A.channels})}if(_.width<_e||_.height<_e){g(E,"below-dimension-floor",{blob:w,appearance:R}),c.push(m(!1));continue}let I=i.get(w);if(I!==void 0){g(E,"duplicate",{blob:w,appearance:R,duplicate_of:I}),c.push(m(!1));continue}if(p.byteLength>Ve){g(E,"image-too-large",{blob:w,appearance:R}),c.push(m(!1));continue}if(f+p.byteLength>Ge){g(E,"vision-byte-budget-reached",{blob:w,appearance:R}),c.push(m(!1));continue}if(d.length>=Ke){g(E,"image-cap-reached",{blob:w,appearance:R}),c.push(m(!1));continue}i.set(w,y),f+=p.byteLength,d.push(y),g(E,"selected",{blob:w,appearance:R}),c.push(m(!0))}let u=[];return u.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&u.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&u.push("",...r.content.body.split(`
7
+ `,inventory:r,blobs:l,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var Je=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function z(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.lastIndexOf("browse");if(r===-1||r+1>=e.length)return null;let l=e[r+1];return Je.test(l)?{site:n.hostname,issueKey:l.toUpperCase()}:null}function X(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return typeof d.site=="string"&&d.site.length>0?d.site:null}catch{return null}}async function De(t,n,e,r,l){let o=z(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Jira issue URL (https://<site>/browse/KEY-123)`),{code:1};let d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G};try{let i={auth:await(l?.authEnv??(await import("./auth-JVH2EHK2.js")).resolveLisAuthEnv)(),env:process.env},c=await d.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${v} and retry`),{code:1};if(c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issue comments yet \u2014 resync it at ${v} and retry`),{code:1};let u=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(u))return(e.err??e.out)(`error: ${t}: project ${u} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${v}`),{code:1};let a=await d.jiraIssue(o.issueKey,i),s=await d.jiraComments(o.issueKey,i),y=o.site;if(a.host)try{y=new URL(a.host).hostname}catch{y=a.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:L,warnings:m}=de(a,y,s),g=n??o.issueKey.toLowerCase();k(g);let S=X(r,g);if(S!==null&&S!==y)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${S}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let h=await P({contextDir:r,bytes:L,media:se,sourceId:g,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{jira:fe({fetchAttachment:p=>d.jiraAttachment(p,i)})}});e.out(U(e.isTTY,h,o.issueKey));for(let p of m)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: jira, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(f){return f instanceof b?((e.err??e.out)(`error: ${t}: ${f.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${Fe(f instanceof Error?f.message:String(f))}`),{code:1})}}function Fe(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the issue's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the description or attachments in Jira and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the issue's text is too large to ingest \u2014 trim the description in Jira and retry":t}var ge={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>z(t)!==null,ingest:De,sourceIdFor:t=>{let n=z(t);return n?n.issueKey.toLowerCase():null}};async function he(t,n={}){let e=await O("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw C(e,"the page");let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${$(r.message??"")||"page not found or not accessible"}`);return r.data}async function ye(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw C(e,"the page's attachment");return{bytes:K(e).bytes}}var q="kane.source.confluence/1";function be(t,n){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this page \u2014 the integrations service returned no page id");let e=[...t.labels??[]].filter(o=>typeof o=="string").sort(),r=[...t.attachments??[]].map(o=>({id:String(o.id),filename:o.filename??"",media_type:o.mime_type??"application/octet-stream",size:o.size??0})).sort((o,d)=>o.id<d.id?-1:o.id>d.id?1:0),l={schema:q,site:n,page:{id:t.id},space:{key:t.space?.key??""},title:t.title??"",labels:e,content:{body:t.body??""},attachments:r};return{bytes:Buffer.from(JSON.stringify(l),"utf8"),envelope:l,warnings:[]}}var _e=64,Ke=16,Ve=6e6,We=5e7,Ge=12e6,Ye={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},He=new Set(["png","jpeg","webp"]);function Ee(t){let n=new Map(Object.entries(t.downloads));return async e=>{let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw new Error("CONFLUENCE_ENVELOPE_SCHEMA: source bytes are not a kane confluence envelope")}if(r.schema!==q)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${q}`);let l=[],o=new Map,d=[],f=0,i=new Map,c=[];for(let a=0;a<r.attachments.length;a++){let s=r.attachments[a],y=`i${a+1}`,L=`attachment:${s.filename}`,m=A=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${A?"":" \u2014 not delivered"})`,g=(A,T,N)=>{l.push({ref:y,loc:L,media_type:A,...N?.blob?{blob:N.blob}:{},...N?.appearance?{appearance:N.appearance}:{},delivery:T,...N?.duplicate_of?{duplicate_of:N.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),c.push(m(!1));continue}let S=n.get(s.id);if(!S){g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let h;try{h=await t.fetchAttachment({id:s.id,download:S})}catch{g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let p=h.bytes,_=D(p),E=Ye[_.format],w=B(p);if(o.set(w,p),!He.has(_.format)){let A=_.format==="gif"||_.format==="bmp"||_.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(E,A,{blob:w}),c.push(m(!1));continue}if(_.width===void 0||_.height===void 0||_.width*_.height>We){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}let R;if(_.format==="png"||_.format==="jpeg"){let A=F(p,_.format);if(A===null){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}R=J(A.data,{width:A.width,height:A.height,channels:A.channels})}if(_.width<_e||_.height<_e){g(E,"below-dimension-floor",{blob:w,appearance:R}),c.push(m(!1));continue}let I=i.get(w);if(I!==void 0){g(E,"duplicate",{blob:w,appearance:R,duplicate_of:I}),c.push(m(!1));continue}if(p.byteLength>Ve){g(E,"image-too-large",{blob:w,appearance:R}),c.push(m(!1));continue}if(f+p.byteLength>Ge){g(E,"vision-byte-budget-reached",{blob:w,appearance:R}),c.push(m(!1));continue}if(d.length>=Ke){g(E,"image-cap-reached",{blob:w,appearance:R}),c.push(m(!1));continue}i.set(w,y),f+=p.byteLength,d.push(y),g(E,"selected",{blob:w,appearance:R}),c.push(m(!0))}let u=[];return u.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&u.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&u.push("",...r.content.body.split(`
8
8
  `)),c.length>0&&u.push("","--- attachments ---",...c),{projection:u.join(`
9
9
  `)+`
10
- `,inventory:l,blobs:o,delivered:d,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var ze=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function Z(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.indexOf("wiki");if(r===-1||e[r+1]!=="spaces"||e[r+3]!=="pages")return null;let l=e[r+2],o=e[r+4];return l===void 0||o===void 0||!ze.test(l)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:l,pageId:o}}async function Xe(t,n,e,r,l){let o=Z(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Confluence page URL (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)`),{code:1};let d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G},f=l?.confluence??{confluenceDocument:he,confluenceAttachment:ye};try{let c={auth:await(l?.authEnv??(await import("./auth-OMWFVDL2.js")).resolveLisAuthEnv)(),env:process.env},u=await d.jiraInfo(c);if(!u.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${L} and retry`),{code:1};if(u.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${L} and retry`),{code:1};let a=await f.confluenceDocument(o.pageId,c),s=o.site;if(a.url)try{s=new URL(a.url).hostname}catch{}let{bytes:y,warnings:v}=be(a,s),m=n??`page-${o.pageId}`;k(m);let g=X(r,m);if(g!==null&&g!==s)return(e.err??e.out)(`error: ${t}: source '${m}' was ingested from ${g}, but this read serves ${s} \u2014 retire it first (kane-cli context retire ${m}) or ingest under a different id with --as`),{code:1};let S=Object.fromEntries((a.attachments??[]).filter(p=>typeof p.download=="string"&&p.download.length>0).map(p=>[String(p.id),p.download])),h=await P({contextDir:r,bytes:y,media:ie,sourceId:m,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{confluence:Ee({downloads:S,fetchAttachment:p=>f.confluenceAttachment(p.download,c)})}});e.out(U(e.isTTY,h,`${o.spaceKey}/${o.pageId}`));for(let p of v)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: confluence, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(i){return i instanceof b?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${qe(i instanceof Error?i.message:String(i))}`),{code:1})}}function qe(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the page in Confluence and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page's text is too large to ingest \u2014 trim the page in Confluence and retry":t}var we={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>Z(t)!==null,ingest:Xe,sourceIdFor:t=>{let n=Z(t);return n?`page-${n.pageId}`:null}};var Ze=new Set(["invalid_url","target_disallowed","page_not_found","page_access_blocked","page_paywalled","unsupported_content_type","page_too_large","page_timeout","scrape_unavailable","scrape_rate_limited","internal_error","credit_denied"]);async function Ie(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,l=ce(e),o={"Content-Type":"application/json"},d=await n.authEnv(),f=d.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=d.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;f?o.Authorization=`Basic ${f}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${l}/assurance/web/scrape`,{method:"POST",headers:o,body:JSON.stringify({url:t}),signal:AbortSignal.timeout(n.timeoutMs??55e3)})}catch{return{ok:!1,kind:"transport_unreachable"}}if(c.status===401)return{ok:!1,kind:"auth_rejected"};let u;try{u=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let s=u.page;return s===void 0||typeof s.markdown!="string"||s.markdown===""||typeof s.final_url!="string"||s.final_url===""||typeof s.projection?.kind!="string"||typeof s.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:s}}let a=u.code;return typeof a=="string"&&Ze.has(a)?{ok:!1,kind:a}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var te="kane.source.web/1";function Ae(t,n,e){if(e==="")throw new Error("cannot build a web source from an empty page projection");if(n.kind===""||n.version==="")throw new Error("cannot build a stable identity without a server-reported projection kind/version");let r={schema:te,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var Qe=new Set(["markdown"]);function ve(){return async t=>{let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("this web source's stored envelope is not readable \u2014 re-ingest the page")}if(n.schema!==te)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!Qe.has(n.projection?.kind??""))throw new Error(`unknown web projection kind '${String(n.projection?.kind)}' \u2014 update kane-cli to read this source`);if(typeof n.content?.markdown!="string"||n.content.markdown==="")throw new Error("this web source's stored envelope carries no content \u2014 re-ingest the page");return{projection:n.content.markdown,inventory:[],blobs:new Map,delivered:[],converter:{name:"web-convert",version:"1",policy:"markdown-passthrough"}}}}import{createHash as et}from"crypto";function Le(t){return Q(t)!==null}function Q(t){if(!/^https?:\/\//i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname===""?null:(n.hash="",n.username="",n.password="",n.toString())}function ne(t){let n=Q(t);if(n===null)return null;let e=new URL(n),r=(e.hostname+e.pathname).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,""),l=et("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${l}`}function tt(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return d.schema!=="kane.source.web/1"?null:typeof d.url=="string"&&d.url.length>0?d.url:null}catch{return null}}function re(t){switch(t){case"invalid_url":return"this is not a valid public HTTP or HTTPS page URL \u2014 check the address and try again";case"target_disallowed":return"that address cannot be fetched because it does not point to an allowed public web page";case"page_not_found":return"the page could not be found \u2014 check that the URL is correct and that the page still exists";case"page_access_blocked":return"the page refused automated access, so its contents could not be ingested \u2014 use a publicly accessible version of the page";case"page_paywalled":return"the page is behind a paywall or sign-in screen, so its full contents could not be ingested \u2014 use a publicly accessible copy";case"unsupported_content_type":return"the URL does not point to an HTML web page \u2014 download the document and ingest the supported file instead";case"page_too_large":return"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first";case"page_timeout":return"the page took too long to load \u2014 try again later";case"scrape_unavailable":case"scrape_rate_limited":case"internal_error":return"the page ingest service is temporarily unavailable \u2014 try again later";case"credit_denied":return"the page could not be ingested \u2014 your organization is out of credits";case"auth_rejected":return"your credentials were rejected \u2014 run `kane-cli login` and retry";case"route_missing":return"the page ingest service could not be reached \u2014 your controller does not serve web ingest yet; retry after the next deploy";case"transport_unreachable":return"the page ingest service could not be reached \u2014 check your connection and try again";case"malformed_response":return"the page ingest service returned a response that could not be read safely \u2014 try again later"}}function nt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page contains too much text to ingest as a single source (${n[1]}; the limit is ${n[2]}) \u2014 use a narrower page or trim the content first`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first":t}async function rt(t,n,e,r,l){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};let d=ne(t),f=n??d;if(f===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};try{k(f)}catch(s){return(e.err??e.out)(`error: ${t}: ${s instanceof Error?s.message:String(s)}`),{code:1}}let i=tt(r,f);if(i!==null&&i!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${i} \u2014 re-run on a TTY to adopt the new URL as its next version, or ingest under a different id with --as`),{code:1};if(!await e.confirm(`source '${f}' was ingested from ${i} \u2014 treat ${o} as its new version (replaces the current version; items built on it go stale)?`))return e.out(`skipped ${t} \u2014 ingest under a different id with --as to keep both pages`),{code:1}}let c=l?.web?.scrape??Ie,u=l?.authEnv??(async()=>(await import("./spawner-OZ4OE44T.js")).resolveAgentAuthEnv()),a=await c(o,{authEnv:u});if(!a.ok)return(e.err??e.out)(`error: ${t}: ${re(a.kind)}`),{code:1};try{let{bytes:s}=Ae(o,a.page.projection,a.page.markdown),y=await P({contextDir:r,bytes:s,media:ae,sourceId:f,label:o,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{web:ve()}}),v=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,y,v));for(let m of y.warnings??[])e.out(`warning: ${m}`);return e.isTTY&&a.page.title&&e.out(` title: ${a.page.title}`),{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid}}}catch(s){return(e.err??e.out)(`error: ${t}: ${nt(s instanceof Error?s.message:String(s))}`),{code:1}}}var Se={name:"web",hint:"any public web page URL (https://\u2026)",match:Le,ingest:rt,sourceIdFor:ne};function U(t,n,e){return t?n.status==="created"?`landed ${n.source_id} (${e}) \u2014 new source`:n.status==="versioned"?`landed ${n.source_id} (${e}) \u2014 new version; dependents go stale`:`${n.source_id} unchanged \u2014 already landed`:`${n.status} ${n.source_id} source ${n.cid} blob ${n.blob}`}var ot=[ge,we,Se];function _n(t){return/^https?:\/\/.+/i.test(t)}function En(t){return ot.find(n=>n.match(t))??null}export{U as a,ot as b,_n as c,En as d};
10
+ `,inventory:l,blobs:o,delivered:d,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var ze=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function Z(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.indexOf("wiki");if(r===-1||e[r+1]!=="spaces"||e[r+3]!=="pages")return null;let l=e[r+2],o=e[r+4];return l===void 0||o===void 0||!ze.test(l)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:l,pageId:o}}async function Xe(t,n,e,r,l){let o=Z(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Confluence page URL (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)`),{code:1};let d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G},f=l?.confluence??{confluenceDocument:he,confluenceAttachment:ye};try{let c={auth:await(l?.authEnv??(await import("./auth-JVH2EHK2.js")).resolveLisAuthEnv)(),env:process.env},u=await d.jiraInfo(c);if(!u.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${v} and retry`),{code:1};if(u.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${v} and retry`),{code:1};let a=await f.confluenceDocument(o.pageId,c),s=o.site;if(a.url)try{s=new URL(a.url).hostname}catch{}let{bytes:y,warnings:L}=be(a,s),m=n??`page-${o.pageId}`;k(m);let g=X(r,m);if(g!==null&&g!==s)return(e.err??e.out)(`error: ${t}: source '${m}' was ingested from ${g}, but this read serves ${s} \u2014 retire it first (kane-cli context retire ${m}) or ingest under a different id with --as`),{code:1};let S=Object.fromEntries((a.attachments??[]).filter(p=>typeof p.download=="string"&&p.download.length>0).map(p=>[String(p.id),p.download])),h=await P({contextDir:r,bytes:y,media:ie,sourceId:m,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{confluence:Ee({downloads:S,fetchAttachment:p=>f.confluenceAttachment(p.download,c)})}});e.out(U(e.isTTY,h,`${o.spaceKey}/${o.pageId}`));for(let p of L)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: confluence, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(i){return i instanceof b?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${qe(i instanceof Error?i.message:String(i))}`),{code:1})}}function qe(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the page in Confluence and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page's text is too large to ingest \u2014 trim the page in Confluence and retry":t}var we={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>Z(t)!==null,ingest:Xe,sourceIdFor:t=>{let n=Z(t);return n?`page-${n.pageId}`:null}};var Ze=new Set(["invalid_url","target_disallowed","page_not_found","page_access_blocked","page_paywalled","unsupported_content_type","page_too_large","page_timeout","scrape_unavailable","scrape_rate_limited","internal_error","credit_denied"]);async function Ie(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,l=ce(e),o={"Content-Type":"application/json"},d=await n.authEnv(),f=d.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=d.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;f?o.Authorization=`Basic ${f}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${l}/assurance/web/scrape`,{method:"POST",headers:o,body:JSON.stringify({url:t}),signal:AbortSignal.timeout(n.timeoutMs??55e3)})}catch{return{ok:!1,kind:"transport_unreachable"}}if(c.status===401)return{ok:!1,kind:"auth_rejected"};let u;try{u=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let s=u.page;return s===void 0||typeof s.markdown!="string"||s.markdown===""||typeof s.final_url!="string"||s.final_url===""||typeof s.projection?.kind!="string"||typeof s.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:s}}let a=u.code;return typeof a=="string"&&Ze.has(a)?{ok:!1,kind:a}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var te="kane.source.web/1";function Ae(t,n,e){if(e==="")throw new Error("cannot build a web source from an empty page projection");if(n.kind===""||n.version==="")throw new Error("cannot build a stable identity without a server-reported projection kind/version");let r={schema:te,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var Qe=new Set(["markdown"]);function Le(){return async t=>{let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("this web source's stored envelope is not readable \u2014 re-ingest the page")}if(n.schema!==te)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!Qe.has(n.projection?.kind??""))throw new Error(`unknown web projection kind '${String(n.projection?.kind)}' \u2014 update kane-cli to read this source`);if(typeof n.content?.markdown!="string"||n.content.markdown==="")throw new Error("this web source's stored envelope carries no content \u2014 re-ingest the page");return{projection:n.content.markdown,inventory:[],blobs:new Map,delivered:[],converter:{name:"web-convert",version:"1",policy:"markdown-passthrough"}}}}import{createHash as et}from"crypto";function ve(t){return Q(t)!==null}function Q(t){if(!/^https?:\/\//i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname===""?null:(n.hash="",n.username="",n.password="",n.toString())}function ne(t){let n=Q(t);if(n===null)return null;let e=new URL(n),r=(e.hostname+e.pathname).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,""),l=et("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${l}`}function tt(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return d.schema!=="kane.source.web/1"?null:typeof d.url=="string"&&d.url.length>0?d.url:null}catch{return null}}function re(t){switch(t){case"invalid_url":return"this is not a valid public HTTP or HTTPS page URL \u2014 check the address and try again";case"target_disallowed":return"that address cannot be fetched because it does not point to an allowed public web page";case"page_not_found":return"the page could not be found \u2014 check that the URL is correct and that the page still exists";case"page_access_blocked":return"the page refused automated access, so its contents could not be ingested \u2014 use a publicly accessible version of the page";case"page_paywalled":return"the page is behind a paywall or sign-in screen, so its full contents could not be ingested \u2014 use a publicly accessible copy";case"unsupported_content_type":return"the URL does not point to an HTML web page \u2014 download the document and ingest the supported file instead";case"page_too_large":return"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first";case"page_timeout":return"the page took too long to load \u2014 try again later";case"scrape_unavailable":case"scrape_rate_limited":case"internal_error":return"the page ingest service is temporarily unavailable \u2014 try again later";case"credit_denied":return"the page could not be ingested \u2014 your organization is out of credits";case"auth_rejected":return"your credentials were rejected \u2014 run `kane-cli login` and retry";case"route_missing":return"ingesting web pages is not available in your environment yet \u2014 nothing is wrong with the URL; try again later";case"transport_unreachable":return"the page ingest service could not be reached \u2014 check your connection and try again";case"malformed_response":return"the page ingest service returned a response that could not be read safely \u2014 try again later"}}function nt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page contains too much text to ingest as a single source (${n[1]}; the limit is ${n[2]}) \u2014 use a narrower page or trim the content first`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first":t}async function rt(t,n,e,r,l){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};let d=ne(t),f=n??d;if(f===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};try{k(f)}catch(s){return(e.err??e.out)(`error: ${t}: ${s instanceof Error?s.message:String(s)}`),{code:1}}let i=tt(r,f);if(i!==null&&i!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${i} \u2014 re-run on a TTY to adopt the new URL as its next version, or ingest under a different id with --as`),{code:1};if(!await e.confirm(`source '${f}' was ingested from ${i} \u2014 treat ${o} as its new version (replaces the current version; items built on it go stale)?`))return e.out(`skipped ${t} \u2014 ingest under a different id with --as to keep both pages`),{code:1}}let c=l?.web?.scrape??Ie,u=l?.authEnv??(async()=>(await import("./spawner-LKYUMXSO.js")).resolveAgentAuthEnv()),a=await c(o,{authEnv:u});if(!a.ok)return(e.err??e.out)(`error: ${t}: ${re(a.kind)}`),{code:1};try{let{bytes:s}=Ae(o,a.page.projection,a.page.markdown),y=await P({contextDir:r,bytes:s,media:ae,sourceId:f,label:o,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{web:Le()}}),L=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,y,L));for(let m of y.warnings??[])e.out(`warning: ${m}`);return e.isTTY&&a.page.title&&e.out(` title: ${a.page.title}`),{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid}}}catch(s){return(e.err??e.out)(`error: ${t}: ${nt(s instanceof Error?s.message:String(s))}`),{code:1}}}var Se={name:"web",hint:"any public web page URL (https://\u2026)",match:ve,ingest:rt,sourceIdFor:ne};function U(t,n,e){return t?n.status==="created"?`landed ${n.source_id} (${e}) \u2014 new source`:n.status==="versioned"?`landed ${n.source_id} (${e}) \u2014 new version; dependents go stale`:`${n.source_id} unchanged \u2014 already landed`:`${n.status} ${n.source_id} source ${n.cid} blob ${n.blob}`}var ot=[ge,we,Se];function _n(t){return/^https?:\/\/.+/i.test(t)}function En(t){return ot.find(n=>n.match(t))??null}export{U as a,ot as b,_n as c,En as d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as u,d as p}from"./chunk-XO45NGSN.js";import{spawn as h}from"child_process";var k=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint"]);function v(g,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:u();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=g.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=h(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(g.session_id,n.auth)});if(t.stdin.write(JSON.stringify(g)+`
2
+ import{c as u,d as p}from"./chunk-NDAAY2RL.js";import{spawn as h}from"child_process";var k=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint"]);function v(g,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:u();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=g.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=h(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(g.session_id,n.auth)});if(t.stdin.write(JSON.stringify(g)+`
3
3
  `),n.onStderr){let e="";t.stderr.on("data",r=>{e+=r.toString("utf8");let i;for(;(i=e.indexOf(`
4
4
  `))>=0;){let o=e.slice(0,i);e=e.slice(i+1),o.trim()&&n.onStderr(o)}})}let d=new Promise(e=>{t.on("exit",(r,i)=>e({code:r,signal:i}))});async function*m(){let e="",r=!1;for await(let i of t.stdout){e+=i.toString("utf8");let o;for(;(o=e.indexOf(`
5
5
  `))>=0;){let l=e.slice(0,o).trim();if(e=e.slice(o+1),!l)continue;let c;try{c=JSON.parse(l)}catch{n.onWarn?.(`agent: skipping malformed line: ${l.slice(0,120)}`);continue}let s=c;if(!s||typeof s!="object"||!k.has(s.type)){n.onWarn?.(`agent: skipping unknown event type "${s&&typeof s=="object"?String(s.type??"?"):"?"}"`);continue}if(yield s,s.type==="done"){r=!0;break}}if(r)break}await d.catch(()=>{})}return{events:m(),send:e=>{t.stdin&&!t.stdin.destroyed&&t.stdin.write(JSON.stringify(e)+`