@testmuai/kane-cli 0.8.17 → 0.8.18

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 (176) hide show
  1. package/dist/{ChatSurface-X2HLVN2I.js → ChatSurface-SY7HJD46.js} +1 -1
  2. package/dist/{ChromeProfilePicker-YU7HL6Z5.js → ChromeProfilePicker-NCIURJK6.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-7FEEVGCU.js → CliFeedbackPrompt-TTVW5COG.js} +1 -1
  4. package/dist/{CliUploadProgress-OTVPBGW4.js → CliUploadProgress-E3WEIF36.js} +1 -1
  5. package/dist/{ConfigView-UKHUASHL.js → ConfigView-ZY37EGAO.js} +1 -1
  6. package/dist/{EvidenceViewOffer-LIPGXO23.js → EvidenceViewOffer-6KT64W7L.js} +1 -1
  7. package/dist/FolderPicker-MPLLN4VP.js +2 -0
  8. package/dist/{InfoBox-2TYT2ROK.js → InfoBox-JP3TTPIO.js} +1 -1
  9. package/dist/{LinksBox-7AS6D7MX.js → LinksBox-4ZB7G5ET.js} +1 -1
  10. package/dist/{ProfilesView-F4MFHZ7Y.js → ProfilesView-25AXMCKS.js} +1 -1
  11. package/dist/{ProjectPicker-QLGZM35L.js → ProjectPicker-RL3LXLTV.js} +1 -1
  12. package/dist/{SaveSessionPrompt-T4MS76FY.js → SaveSessionPrompt-5W4ATISN.js} +1 -1
  13. package/dist/SingleShotApp-JV64B4XL.js +2 -0
  14. package/dist/{SummaryBox-IX32QPWM.js → SummaryBox-GW4XAX5T.js} +1 -1
  15. package/dist/TestMdRunView-7N6QXMNR.js +2 -0
  16. package/dist/{TestrunEvidenceTable-OK2HAENB.js → TestrunEvidenceTable-SYCFAGM4.js} +1 -1
  17. package/dist/WhoamiView-H2DRYRRA.js +2 -0
  18. package/dist/{app-download-CF4JLXWV.js → app-download-2IZ4GPTA.js} +1 -1
  19. package/dist/{auth-D4BDPJPR.js → auth-6PKLNV6Z.js} +1 -1
  20. package/dist/{binary-NWVJK542.js → binary-OMBH4UTI.js} +1 -1
  21. package/dist/{bind-LWN72YES.js → bind-IHLHM5UM.js} +2 -2
  22. package/dist/{bootstrap-63FBDEEU.js → bootstrap-UKZX3LRC.js} +1 -1
  23. package/dist/bridge-KJNDGKPU.js +2 -0
  24. package/dist/{changelog-GIZLIFMN.js → changelog-ZWOIODQ4.js} +1 -1
  25. package/dist/{chunk-BNZQKQOE.js → chunk-2KYJOBNI.js} +1 -1
  26. package/dist/{chunk-5UHM7CKR.js → chunk-2LKSDGWA.js} +1 -1
  27. package/dist/{chunk-JWOPRJIO.js → chunk-47FQ7ZUQ.js} +1 -1
  28. package/dist/{chunk-ZQ6KWTJ2.js → chunk-4ANRRDC7.js} +1 -1
  29. package/dist/{chunk-UQNRUAES.js → chunk-4B3EHSTD.js} +1 -1
  30. package/dist/{chunk-AH4QWIYU.js → chunk-4BKSQFEP.js} +1 -1
  31. package/dist/{chunk-3YBT4UGQ.js → chunk-4JRCAHHB.js} +1 -1
  32. package/dist/{chunk-5X7JIGG7.js → chunk-4R5U7CHE.js} +1 -1
  33. package/dist/{chunk-CCNPXTC6.js → chunk-5B2NEYHF.js} +2 -2
  34. package/dist/{chunk-5ZU7S4E7.js → chunk-5NZUMWUD.js} +2 -2
  35. package/dist/{chunk-UUYYTJG2.js → chunk-5RJ2J5QU.js} +1 -1
  36. package/dist/{chunk-DFK5QYB5.js → chunk-5WUDW6BG.js} +1 -1
  37. package/dist/{chunk-WKIYI6MB.js → chunk-6FEEYKSE.js} +1 -1
  38. package/dist/{chunk-KQCGBDPM.js → chunk-6OIC4S3C.js} +1 -1
  39. package/dist/{chunk-4OQ7GEIA.js → chunk-6VB4FGBZ.js} +1 -1
  40. package/dist/{chunk-4ASBXR6Q.js → chunk-7BMM5DFP.js} +1 -1
  41. package/dist/{chunk-637S3COE.js → chunk-7DSZ2YSD.js} +1 -1
  42. package/dist/{chunk-RGJIGNB3.js → chunk-7PLIZBXB.js} +1 -1
  43. package/dist/{chunk-D2F5T3NX.js → chunk-7ZKVI4US.js} +1 -1
  44. package/dist/{chunk-7U7HOEZO.js → chunk-7ZSHB3AN.js} +1 -1
  45. package/dist/{chunk-I6RTGDZ7.js → chunk-AK7BMF5T.js} +1 -1
  46. package/dist/{chunk-KWANVHJX.js → chunk-ALHCB3LL.js} +1 -1
  47. package/dist/{chunk-NFLQWKFR.js → chunk-BXM5GDIO.js} +2 -2
  48. package/dist/{chunk-5LSPHA3P.js → chunk-C3GDK2OS.js} +1 -1
  49. package/dist/{chunk-IGI4T3VC.js → chunk-CHA75LBJ.js} +1 -1
  50. package/dist/{chunk-5MKY3WMF.js → chunk-DDLEZGZB.js} +1 -1
  51. package/dist/{chunk-JPOYZCTX.js → chunk-DH3H6GWD.js} +1 -1
  52. package/dist/{chunk-GT6Y2SEY.js → chunk-DKPRWI7U.js} +2 -2
  53. package/dist/{chunk-DT2LIX5S.js → chunk-EA2LT5OJ.js} +1 -1
  54. package/dist/{chunk-47QKRIPY.js → chunk-EHOYD6VL.js} +3 -3
  55. package/dist/{chunk-UXJZUGKL.js → chunk-EJBJ7MYC.js} +1 -1
  56. package/dist/{chunk-CCW3VQIY.js → chunk-EKZI5HZV.js} +1 -1
  57. package/dist/{chunk-IZ3PYWUL.js → chunk-EW3KRQGF.js} +1 -1
  58. package/dist/{chunk-AG2MVCNK.js → chunk-EYVHPJLK.js} +1 -1
  59. package/dist/{chunk-HLUOLWEJ.js → chunk-F3IWJ73B.js} +1 -1
  60. package/dist/{chunk-2STKZSVF.js → chunk-G76O7C56.js} +1 -1
  61. package/dist/{chunk-5HDM7GDO.js → chunk-GESZSIB6.js} +1 -1
  62. package/dist/{chunk-L2SJRAK4.js → chunk-GUFIE3Z2.js} +1 -1
  63. package/dist/{chunk-AW34ZNNO.js → chunk-H5N25XIT.js} +1 -1
  64. package/dist/{chunk-IKB2JKMA.js → chunk-H7A4R7WY.js} +1 -1
  65. package/dist/{chunk-DQRVB5EU.js → chunk-IFQD53QB.js} +1 -1
  66. package/dist/{chunk-4PWAODKJ.js → chunk-IGLCR4J2.js} +1 -1
  67. package/dist/{chunk-IHUF6UP4.js → chunk-IQCW5SV5.js} +1 -1
  68. package/dist/{chunk-YOVKKZVZ.js → chunk-J3OGBEEP.js} +1 -1
  69. package/dist/{chunk-3UIZVDOF.js → chunk-JMWRMDSI.js} +1 -1
  70. package/dist/{chunk-UTIP6SMW.js → chunk-L4U7NP5Q.js} +1 -1
  71. package/dist/{chunk-MDM2LJFN.js → chunk-LHU6TEKD.js} +1 -1
  72. package/dist/{chunk-JGCB4OUP.js → chunk-LQMA6N5S.js} +1 -1
  73. package/dist/{chunk-SDJNWR4D.js → chunk-MMLYJDXO.js} +1 -1
  74. package/dist/{chunk-RSXCS474.js → chunk-MSLYSXGM.js} +1 -1
  75. package/dist/{chunk-MTCLFYNH.js → chunk-MVOO7RPO.js} +1 -1
  76. package/dist/{chunk-64TO3MD7.js → chunk-N4HKQTD5.js} +2 -2
  77. package/dist/{chunk-233MYVFS.js → chunk-NXZPWMK5.js} +1 -1
  78. package/dist/{chunk-ZRRBZUDJ.js → chunk-NYP7QV54.js} +1 -1
  79. package/dist/{chunk-KRI5NSGQ.js → chunk-OVL4WXGF.js} +1 -1
  80. package/dist/{chunk-N55U4S4W.js → chunk-PMBQU63H.js} +1 -1
  81. package/dist/{chunk-6OKOMKYR.js → chunk-PVJB7CVS.js} +1 -1
  82. package/dist/{chunk-6CYF7Q5W.js → chunk-QX5LJVTD.js} +2 -2
  83. package/dist/{chunk-VIYV6NIW.js → chunk-RBVLIMOV.js} +1 -1
  84. package/dist/{chunk-GBXF4JE6.js → chunk-SBQUEGTP.js} +1 -1
  85. package/dist/{chunk-EIMHIZKF.js → chunk-SYKS57PK.js} +1 -1
  86. package/dist/{chunk-OCWS5YVO.js → chunk-TG4GGP3H.js} +3 -3
  87. package/dist/{chunk-WDK5ETMA.js → chunk-TSNQLZE3.js} +1 -1
  88. package/dist/{chunk-KX5IV5FL.js → chunk-UAEU5IPH.js} +2 -2
  89. package/dist/{chunk-AIR2WVXM.js → chunk-UE5EYEFI.js} +1 -1
  90. package/dist/{chunk-PHR2OSWD.js → chunk-UQ6A52ML.js} +1 -1
  91. package/dist/{chunk-TMOSERKN.js → chunk-UUS5AK6L.js} +2 -2
  92. package/dist/{chunk-TISVRTL7.js → chunk-VH73F65W.js} +2 -2
  93. package/dist/{chunk-IHD2WXKT.js → chunk-WAZUOA3Y.js} +1 -1
  94. package/dist/{chunk-2LKNUXRN.js → chunk-WQV5SM5P.js} +1 -1
  95. package/dist/{chunk-75SSVUGS.js → chunk-WTAJTPI5.js} +1 -1
  96. package/dist/{chunk-ICFJVEEA.js → chunk-WWVHK7OA.js} +1 -1
  97. package/dist/{chunk-IDLJHKJX.js → chunk-XYMUKOKK.js} +1 -1
  98. package/dist/{chunk-JWPBLVPW.js → chunk-YAUR5CBH.js} +1 -1
  99. package/dist/{chunk-E6X5BVXC.js → chunk-YNOADDF7.js} +1 -1
  100. package/dist/{chunk-GIC56KI3.js → chunk-YPEIPCQY.js} +1 -1
  101. package/dist/{chunk-WC54SZUO.js → chunk-YVKNKK22.js} +1 -1
  102. package/dist/{chunk-B6NU3SNG.js → chunk-ZARM7ESN.js} +1 -1
  103. package/dist/{chunk-2LCWGWYC.js → chunk-ZMM3Y6U7.js} +1 -1
  104. package/dist/{chunk-KMF2PPJ5.js → chunk-ZO75BQ3Z.js} +1 -1
  105. package/dist/{chunk-RBFCGUR3.js → chunk-ZV5KM7LI.js} +1 -1
  106. package/dist/{chunk-LO47W2DO.js → chunk-ZW3JBY5E.js} +4 -4
  107. package/dist/{config-WKLEWUPU.js → config-ODCFEOAN.js} +1 -1
  108. package/dist/{cover-cmd-7TSQJFGM.js → cover-cmd-AQ7PWJRH.js} +1 -1
  109. package/dist/{credentials-FLY3ZXVX.js → credentials-MUZUCSJJ.js} +1 -1
  110. package/dist/{deps-bundle-CAKK3EO5.js → deps-bundle-7COKI7UV.js} +1 -1
  111. package/dist/{deps-resolve-MSLEFPVD.js → deps-resolve-ADN7P5L7.js} +1 -1
  112. package/dist/{dispatch-SXS276ZT.js → dispatch-V24LFEAO.js} +1 -1
  113. package/dist/{doctor-EZPQTFJM.js → doctor-3BRZM4EW.js} +1 -1
  114. package/dist/{evidence-GUOURW6F.js → evidence-EBD3FIXA.js} +1 -1
  115. package/dist/{evolve-cmd-LJJFOXXP.js → evolve-cmd-IR7UGOD2.js} +1 -1
  116. package/dist/{explain-cmd-5LLIJKM2.js → explain-cmd-NNYKSAQK.js} +1 -1
  117. package/dist/{extract-bind-CGU6WVS7.js → extract-bind-2GGLO5KU.js} +2 -2
  118. package/dist/{extract-cmd-7N7CCGN6.js → extract-cmd-2BQJ2HNT.js} +1 -1
  119. package/dist/{gaps-cmd-BNUGDF5N.js → gaps-cmd-Y6CZUCIX.js} +1 -1
  120. package/dist/{generate-headless-7TJYESUU.js → generate-headless-SPGLBRH5.js} +2 -2
  121. package/dist/index.js +44 -44
  122. package/dist/{ingest-cmd-B4T5CW5R.js → ingest-cmd-N37FGNP5.js} +1 -1
  123. package/dist/install-2PUHCC2Y.js +2 -0
  124. package/dist/{interactive-bind-HUZDSGFX.js → interactive-bind-ZLO6S2SG.js} +3 -3
  125. package/dist/{lifecycle-cmd-GIVLSUPE.js → lifecycle-cmd-6TWIQCKR.js} +1 -1
  126. package/dist/{list-cmd-KEKKQDUF.js → list-cmd-NDD2OSP5.js} +1 -1
  127. package/dist/{list-commands-SMBBT5CY.js → list-commands-AARQ2RZG.js} +1 -1
  128. package/dist/login-flow-V4US6VQP.js +2 -0
  129. package/dist/{maintenance-cmd-MLQ3IRFV.js → maintenance-cmd-4QUVSGUY.js} +1 -1
  130. package/dist/{mobile-prompts-EEPPPA6S.js → mobile-prompts-GYJS5BYX.js} +1 -1
  131. package/dist/{objective-variable-gate-AEBWIGH7.js → objective-variable-gate-FUVNHKRA.js} +1 -1
  132. package/dist/{open-provider-OTZ37JB6.js → open-provider-QTPN6XOL.js} +1 -1
  133. package/dist/{persist-recorded-session-IRWGMXGI.js → persist-recorded-session-UFK5VC7S.js} +1 -1
  134. package/dist/{pipeline-OV3TWKSZ.js → pipeline-Z477UOXV.js} +1 -1
  135. package/dist/prepare-target-IES7FXJG.js +2 -0
  136. package/dist/{reconcile-cmd-NBBDE7DJ.js → reconcile-cmd-NDLEM54D.js} +1 -1
  137. package/dist/{reconcile-deps-DJNIY7TP.js → reconcile-deps-APR2LE3C.js} +2 -2
  138. package/dist/{reconcile-engine-Z2XKUCQ7.js → reconcile-engine-C72AP4WS.js} +1 -1
  139. package/dist/{recording-banner-GCR6A46M.js → recording-banner-AZOKNSU3.js} +1 -1
  140. package/dist/registry-W3BMHQDQ.js +2 -0
  141. package/dist/{require-project-folder-YBB5T3OE.js → require-project-folder-LTVPPY3Q.js} +1 -1
  142. package/dist/{resolve-run-intent-XGZN6OQ6.js → resolve-run-intent-XX6O3RYT.js} +1 -1
  143. package/dist/{resolver-WNV53IOL.js → resolver-XMASFMID.js} +1 -1
  144. package/dist/{review-cmd-ZXTLZ4GE.js → review-cmd-4TNBQDJU.js} +1 -1
  145. package/dist/{run-YZP2PTNW.js → run-EOIV3OQE.js} +1 -1
  146. package/dist/{run-YWKZGZVL.js → run-XXA7ILIM.js} +1 -1
  147. package/dist/{run-test-md-N43FRXB6.js → run-test-md-GVRVMPRZ.js} +2 -2
  148. package/dist/{skill-installer-G7Z5ZDAQ.js → skill-installer-AWQT3LM2.js} +1 -1
  149. package/dist/{spawner-ABB7B5CQ.js → spawner-O3VKHYUY.js} +1 -1
  150. package/dist/{store-guard-YIQQF4LC.js → store-guard-MHWBXA4C.js} +1 -1
  151. package/dist/{sync-cmd-4AKHO5EG.js → sync-cmd-P2CL6YA6.js} +1 -1
  152. package/dist/{sync-setup-E7UV25KK.js → sync-setup-JY4T2X3M.js} +1 -1
  153. package/dist/tcg-generate-GWLHZYLF.js +2 -0
  154. package/dist/testmd-actions-SYMNRTK4.js +2 -0
  155. package/dist/{testmd-sync-I2E6W6JL.js → testmd-sync-IRV44CGT.js} +1 -1
  156. package/dist/token-refresh-IM6ELK6S.js +2 -0
  157. package/dist/{validate-basic-WZY6A3KD.js → validate-basic-A5TEMJNT.js} +1 -1
  158. package/dist/{variable-receipt-JONRYHCY.js → variable-receipt-QDP2S5CQ.js} +1 -1
  159. package/dist/{verdicts-JMVS6HNJ.js → verdicts-H755EUQL.js} +1 -1
  160. package/dist/{version-check-CD7DHZI2.js → version-check-26W5GVBQ.js} +1 -1
  161. package/dist/{view-cmd-ASH2UFUW.js → view-cmd-D3BYBDZE.js} +1 -1
  162. package/dist/{walk-session-ZPXR7ASG.js → walk-session-ZZ26LEQE.js} +1 -1
  163. package/dist/{with-telemetry-QXCHDKPW.js → with-telemetry-UE6SYQWL.js} +1 -1
  164. package/package.json +11 -11
  165. package/dist/FolderPicker-OTQYRAYC.js +0 -2
  166. package/dist/SingleShotApp-4CDTAF3H.js +0 -2
  167. package/dist/TestMdRunView-MRMY3RW5.js +0 -2
  168. package/dist/WhoamiView-AHMNIIXZ.js +0 -2
  169. package/dist/bridge-UMXGHAJF.js +0 -2
  170. package/dist/install-6KJ2MZX3.js +0 -2
  171. package/dist/login-flow-5ZIG7JXT.js +0 -2
  172. package/dist/prepare-target-35OI7XBL.js +0 -2
  173. package/dist/registry-V3ULHPLM.js +0 -2
  174. package/dist/tcg-generate-XJN5OMIJ.js +0 -2
  175. package/dist/testmd-actions-WFDWYEAU.js +0 -2
  176. package/dist/token-refresh-NADDXLYM.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as Y,c as W}from"./chunk-PDXZROJM.js";import{S as X}from"./chunk-TISVRTL7.js";import{b as J}from"./chunk-5GUD3CIH.js";import{a as H}from"./chunk-JQ64X2TO.js";import{a as Rt,b as k}from"./chunk-NBXYL2JT.js";import{a as K}from"./chunk-BPMSNGXQ.js";import{a as G}from"./chunk-DHJSM5DT.js";import{a as $}from"./chunk-NLCCBXXV.js";import{a as R}from"./chunk-RZ4F3BHX.js";import{e as kt}from"./chunk-UR6MHSHU.js";import{readFileSync as L,existsSync as z,readdirSync as ue,mkdirSync as V,writeFileSync as w}from"fs";import{readFile as vt,unlink as le}from"fs/promises";import{join as y}from"path";import{existsSync as te,mkdirSync as ee,readdirSync as ht,writeFileSync as ne}from"fs";import{join as S}from"path";import{randomUUID as A}from"crypto";var Q=["children","instructions","branches","module_content","true_branch","false_branch"];function j(e){let t=new Map,n=r=>{if(!r||typeof r!="object")return;let o=r;if(Array.isArray(o.operations))for(let i of o.operations){let s=i.operation_id;if(typeof s!="string"||!s)continue;let a=t.get(s)??[];a.includes(o)||a.push(o),t.set(s,a)}for(let i of Q){let s=o[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return e.forEach(n),t}function Pt(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];let n=e.action_params?.script;if(typeof n=="string"&&n.trim()){let r=n.trim(),o=t.find(i=>St(i)?.trim()===r);if(o)return o}return t[0]}function St(e){let t=e,n=t.script_content??t.js_snippet;return typeof n=="string"?n:void 0}function D(e,t){let n=new Map;for(let r of e){let o=Pt(r,r.action_id?t.get(r.action_id):void 0);if(!o)continue;let i=n.get(o)??[];i.push(r),n.set(o,i)}return n.size===0?null:[...n].map(([r,o])=>Lt(r,o))}function tt(e,t){let n=j(t.authoredInstructions),r=[];for(let o of e){if(o.flatIndex===void 0||!t.replayOnlyFlatIndices.has(o.flatIndex))continue;let i=D(o.records,n);i&&r.push(...i)}return r}function et(e,t){let n=new Map(t.map(a=>[a.instruction_id,a])),r=[],o=a=>{if(!a||typeof a!="object")return;let c=a.instruction_id,u=typeof c=="string"?n.get(c):void 0;return u&&r.push(c),u},i=a=>{if(!a||typeof a!="object")return;let c=a;for(let u of Q){let l=c[u];if(Array.isArray(l))s(l);else if(l&&typeof l=="object"){let _=o(l);_&&(c[u]=_),i(_??l)}}},s=a=>{for(let c=0;c<a.length;c++){let u=o(a[c]);u&&(a[c]=u),i(u??a[c])}};return s(e),r}function wt(e){if(!e.timestamp||e.duration_ms==null)return"";let t=new Date(e.timestamp);return isNaN(t.getTime())?"":new Date(t.getTime()+e.duration_ms).toISOString()}function T(e){if(e!=null)try{return JSON.parse(e)}catch{return e}}function xt(e){return typeof e=="string"?"string":typeof e=="boolean"?"bool":typeof e=="number"?Number.isInteger(e)?"int":"float":Array.isArray(e)?"list":e==null?"NoneType":"JSON"}function C(e,t,n){let r=e.user_variables,o=typeof r=="string",i;try{i=o?JSON.parse(r):r??[]}catch{return}if(!Array.isArray(i)||i.length===0)return;let s=i.find(a=>t&&a.name===t)??(i.length===1?i[0]:void 0);s&&(s.value=n,s.value_type=xt(n),e.user_variables=o?JSON.stringify(i):i)}function Z(e){e.user_variables!==void 0&&(e.user_variables=typeof e.user_variables=="string"?"[]":[])}function Ot(e,t){let n=e.operations??[],r=new Set(t.map(i=>i.action_id).filter(Boolean)),o=n.filter(i=>r.has(i.operation_id));return o.length>0?o:n.length===1?n:[]}function Nt(e){let t=e.error??"Script execution failed";return{error:t,error_code:"SCRIPT_EXECUTION_ERROR",error_message:t,reason:t}}function Lt(e,t){let n=structuredClone(e),r=t[0],o=t[t.length-1];n.status=t.find(s=>s.status!=="success")?.status??r.status,n.start_timestamp=r.timestamp??n.start_timestamp,n.end_timestamp=wt(o)||n.end_timestamp;let i=Ot(n,t);for(let s of i)s.status=n.status,s.operation_start=n.start_timestamp,s.operation_end=n.end_timestamp;switch(n.content_type){case"api":{let s=o.action_params?.api_data?.response;if(s&&typeof s=="object")for(let a of[n,...i])a.api_data={...a.api_data??{},response:s},C(a,o.output_variable,s);break}case"script":{let s=o.output_variable??n.output_variable_name;if(n.status!=="success"){let a=Nt(o);n.code_error=a,Z(n);for(let c of i)c.execution_result=a,c.code_error=a,Z(c)}else if(o.output_value!=null){let a=T(o.output_value);C(n,s,a);for(let c of i)c.execution_result={value:a},C(c,s,a)}break}case"db_query":{o.output_value!=null&&(n.db_details={...n.db_details??{},carried_out_query:T(o.output_value)});break}case"screenshot_command":{let s=T(o.output_value);s&&typeof s=="object"&&(n.smartui_results=s);break}case"network_assertion":case"network_query":break;default:break}return n}var Tt="/home/kaneai/Downloads";function O(e){return`${Tt}/${e}`}function it(e){return"FILE__"+e.replace(/[^A-Za-z0-9]/g,"_")}function N(e){let t=e?.media;return!t||!t.name||!t.media_url?null:{media_id:t.media_id??"",name:t.name,media_url:t.media_url,type:t.type??"doc"}}function ot(e){return e?e.includes(`
2
+ import{b as Y,c as W}from"./chunk-PDXZROJM.js";import{S as X}from"./chunk-VH73F65W.js";import{b as J}from"./chunk-5GUD3CIH.js";import{a as H}from"./chunk-JQ64X2TO.js";import{a as Rt,b as k}from"./chunk-NBXYL2JT.js";import{a as K}from"./chunk-BPMSNGXQ.js";import{a as G}from"./chunk-DHJSM5DT.js";import{a as $}from"./chunk-NLCCBXXV.js";import{a as R}from"./chunk-RZ4F3BHX.js";import{e as kt}from"./chunk-UR6MHSHU.js";import{readFileSync as L,existsSync as z,readdirSync as ue,mkdirSync as V,writeFileSync as w}from"fs";import{readFile as vt,unlink as le}from"fs/promises";import{join as y}from"path";import{existsSync as te,mkdirSync as ee,readdirSync as ht,writeFileSync as ne}from"fs";import{join as S}from"path";import{randomUUID as A}from"crypto";var Q=["children","instructions","branches","module_content","true_branch","false_branch"];function j(e){let t=new Map,n=r=>{if(!r||typeof r!="object")return;let o=r;if(Array.isArray(o.operations))for(let i of o.operations){let s=i.operation_id;if(typeof s!="string"||!s)continue;let a=t.get(s)??[];a.includes(o)||a.push(o),t.set(s,a)}for(let i of Q){let s=o[i];Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};return e.forEach(n),t}function Pt(e,t){if(!t||t.length===0)return;if(t.length===1)return t[0];let n=e.action_params?.script;if(typeof n=="string"&&n.trim()){let r=n.trim(),o=t.find(i=>St(i)?.trim()===r);if(o)return o}return t[0]}function St(e){let t=e,n=t.script_content??t.js_snippet;return typeof n=="string"?n:void 0}function D(e,t){let n=new Map;for(let r of e){let o=Pt(r,r.action_id?t.get(r.action_id):void 0);if(!o)continue;let i=n.get(o)??[];i.push(r),n.set(o,i)}return n.size===0?null:[...n].map(([r,o])=>Lt(r,o))}function tt(e,t){let n=j(t.authoredInstructions),r=[];for(let o of e){if(o.flatIndex===void 0||!t.replayOnlyFlatIndices.has(o.flatIndex))continue;let i=D(o.records,n);i&&r.push(...i)}return r}function et(e,t){let n=new Map(t.map(a=>[a.instruction_id,a])),r=[],o=a=>{if(!a||typeof a!="object")return;let c=a.instruction_id,u=typeof c=="string"?n.get(c):void 0;return u&&r.push(c),u},i=a=>{if(!a||typeof a!="object")return;let c=a;for(let u of Q){let l=c[u];if(Array.isArray(l))s(l);else if(l&&typeof l=="object"){let _=o(l);_&&(c[u]=_),i(_??l)}}},s=a=>{for(let c=0;c<a.length;c++){let u=o(a[c]);u&&(a[c]=u),i(u??a[c])}};return s(e),r}function wt(e){if(!e.timestamp||e.duration_ms==null)return"";let t=new Date(e.timestamp);return isNaN(t.getTime())?"":new Date(t.getTime()+e.duration_ms).toISOString()}function T(e){if(e!=null)try{return JSON.parse(e)}catch{return e}}function xt(e){return typeof e=="string"?"string":typeof e=="boolean"?"bool":typeof e=="number"?Number.isInteger(e)?"int":"float":Array.isArray(e)?"list":e==null?"NoneType":"JSON"}function C(e,t,n){let r=e.user_variables,o=typeof r=="string",i;try{i=o?JSON.parse(r):r??[]}catch{return}if(!Array.isArray(i)||i.length===0)return;let s=i.find(a=>t&&a.name===t)??(i.length===1?i[0]:void 0);s&&(s.value=n,s.value_type=xt(n),e.user_variables=o?JSON.stringify(i):i)}function Z(e){e.user_variables!==void 0&&(e.user_variables=typeof e.user_variables=="string"?"[]":[])}function Ot(e,t){let n=e.operations??[],r=new Set(t.map(i=>i.action_id).filter(Boolean)),o=n.filter(i=>r.has(i.operation_id));return o.length>0?o:n.length===1?n:[]}function Nt(e){let t=e.error??"Script execution failed";return{error:t,error_code:"SCRIPT_EXECUTION_ERROR",error_message:t,reason:t}}function Lt(e,t){let n=structuredClone(e),r=t[0],o=t[t.length-1];n.status=t.find(s=>s.status!=="success")?.status??r.status,n.start_timestamp=r.timestamp??n.start_timestamp,n.end_timestamp=wt(o)||n.end_timestamp;let i=Ot(n,t);for(let s of i)s.status=n.status,s.operation_start=n.start_timestamp,s.operation_end=n.end_timestamp;switch(n.content_type){case"api":{let s=o.action_params?.api_data?.response;if(s&&typeof s=="object")for(let a of[n,...i])a.api_data={...a.api_data??{},response:s},C(a,o.output_variable,s);break}case"script":{let s=o.output_variable??n.output_variable_name;if(n.status!=="success"){let a=Nt(o);n.code_error=a,Z(n);for(let c of i)c.execution_result=a,c.code_error=a,Z(c)}else if(o.output_value!=null){let a=T(o.output_value);C(n,s,a);for(let c of i)c.execution_result={value:a},C(c,s,a)}break}case"db_query":{o.output_value!=null&&(n.db_details={...n.db_details??{},carried_out_query:T(o.output_value)});break}case"screenshot_command":{let s=T(o.output_value);s&&typeof s=="object"&&(n.smartui_results=s);break}case"network_assertion":case"network_query":break;default:break}return n}var Tt="/home/kaneai/Downloads";function O(e){return`${Tt}/${e}`}function it(e){return"FILE__"+e.replace(/[^A-Za-z0-9]/g,"_")}function N(e){let t=e?.media;return!t||!t.name||!t.media_url?null:{media_id:t.media_id??"",name:t.name,media_url:t.media_url,type:t.type??"doc"}}function ot(e){return e?e.includes(`
3
3
  `)?e.split(`
4
4
  `).map(t=>t.trim()).filter(Boolean):e.split(". ").map(t=>t.trim()).filter(Boolean).map(t=>t.endsWith(".")?t:t+"."):[]}function U(e){return typeof e=="string"&&e.includes("{{secrets.")}var Ct={click:"CLICK",double_click:"CLICK",type:"TYPE",fill:"TYPE",clear:"CLEAR",select:"SELECT",hover:"HOVER",drag:"DRAG_DROP",upload_files:"UPLOAD_FILE",navigate:"OPEN",go_back:"NAVIGATE",go_forward:"NAVIGATE",refresh:"REFRESH",press_key:"SENDKEYS",scroll:"SCROLL_PIXELS",scroll_into_view:"SCROLL_UNTIL_ELEMENT",wait:"WAIT",wait_until:"WAIT_UNTIL",wait_for_load:"WAIT_FOR_LOAD",switch_tab:"SWITCH_TAB",new_tab:"NEW_TAB",close_tab:"CLOSE_TAB",api:"API",evaluate_js:"EVALUATE_JS",vision_query:"VISION_QUERY",textual_query:"TEXTUAL_QUERY",get_url:"GET_URL",get_title:"GET_TITLE",assert:"ASSERTION",math:"MATHEMATICAL_OPERATION",set_cookies:"SET_COOKIES",delete_cookies:"DELETE_COOKIES",clear_cookies:"CLEAR_COOKIES",set_local_storage:"SET_LOCAL_STORAGE",delete_local_storage:"DELETE_LOCAL_STORAGE",clear_local_storage:"CLEAR_LOCAL_STORAGE",set_clipboard:"SET_CLIPBOARD",paste_clipboard:"PASTE_CLIPBOARD",clear_clipboard:"CLEAR_CLIPBOARD",device_control:"DEVICE_CONTROL",device_control_query:"DEVICE_CONTROL_QUERY"},st={literal:"SET_VARIABLE",condition:"SET_VARIABLE",visual:"VISION_QUERY",dom:"TEXTUAL_QUERY",url:"GET_URL",title:"GET_TITLE",devtool_network:"DEVTOOLS_NETWORK_QUERY",devtool_console:"DEVTOOLS_CONSOLE_QUERY",devtool_cookies:"DEVTOOLS_COOKIES_QUERY",devtool_storage:"DEVTOOLS_STORAGE_QUERY",devtool_performance:"DEVTOOLS_PERFORMANCE",api_response:"API_CALLS_QUERY",textual_visual:"TEXTUAL_ANALYZER"},jt=new Set(["CLICK","TYPE","FILL","HOVER","SCROLL_UNTIL_ELEMENT","UPLOAD_FILE","VISION_QUERY","DRAG_DROP","SELECT"]);function at(e,t){if(e==="analyze"){let r=t?.action_params?.analyzer_type??"";return st[r]}if(e==="scroll"&&t?.action_params?.into_view===!0)return"SCROLL_UNTIL_ELEMENT";let n=Ct[e];return n||console.warn(`[migrator] UNKNOWN action_type "${e}" \u2014 falling back to "${e.toUpperCase()}"; explicit mapping required`),n??e.toUpperCase()}function ct(e,t){if(!e||!t)return"";try{let n=new Date(e);return isNaN(n.getTime())?"":new Date(n.getTime()+t).toISOString()}catch{return""}}function ut(e){try{return JSON.parse(e.output_value??"{}")}catch{return{}}}function Dt(e){let t=e.output_variable??"";if(!t)return"[]";let r={...ut(e)};return delete r.body,JSON.stringify([{name:t,unique_key:(e.action_id??"").replace(/-/g,"").slice(0,8)||A().replace(/-/g,"").slice(0,8),value:r,variable_description:"API Response"}])}function Ut(e,t,n){let r=e.action_params??{},o=jt.has(t)?"Vision Agent":"Operation Agent",i={operation_type:t};if(t==="OPEN"&&(i.url=r.url??""),t==="SET_VARIABLE"&&(i.variable_name=e.output_variable??r.key??"",i.variable_value=e.output_value??""),t==="UPLOAD_FILE"){let m=N(r);m&&(i.value=O(m.name))}let s={},a={},c=e.action_instruction??"",u=r.text??"",l=r.url??"",_=[["intent",c],["value",u],["url",l]];for(let[m,h]of Object.entries(n)){let I=String(h);if(m.startsWith("secrets."))for(let[E,b]of _)b.includes(I)&&(a[E]=m);for(let[E,b]of _)b.includes(I)&&!(E in s)&&(s[E]=b)}let p=e.action_type,d={operation:e.action_instruction??"",agent:o,operation_dict:i,reasoning:p==="analyze"?r.query??"":e.intent??e.action_instruction??"",variable:s,secrets:a,params:{}};p==="analyze"&&typeof r.code=="string"&&r.code&&(d.code=r.code),p==="analyze"&&typeof r.code_js=="string"&&r.code_js&&(d.code_js=r.code_js),p==="analyze"&&typeof r.condition_expression=="string"&&r.condition_expression&&(d.condition_expression=r.condition_expression),r.uses_websocket===!0&&(d.uses_websocket=!0),r.uses_sse===!0&&(d.uses_sse=!0),p==="analyze"&&r.analyzer_type==="textual_visual"&&(typeof r.wrapped_js=="string"&&(d.wrapped_js=r.wrapped_js),Array.isArray(r.locators)&&(d.locators=r.locators),typeof r.operator=="string"&&(d.operator=r.operator),Array.isArray(r.transforms)&&(d.transforms=r.transforms),typeof r.query=="string"&&(d.query=r.query),typeof r.expected_value=="string"&&(d.expected_value=r.expected_value),typeof r.needs_unit_conversion=="boolean"&&(d.needs_unit_conversion=r.needs_unit_conversion),typeof r.condition=="string"&&(d.condition=r.condition));let g={set_cookies:"cookies",set_clipboard:"text",delete_cookies:"names",set_local_storage:"items",delete_local_storage:"keys"}[p];return g&&r[g]!==void 0&&(d[g]=r[g]),p==="set_clipboard"&&typeof r.html=="string"&&r.html&&(d.html=r.html),d}function Ft(e){let t=e.assertion_tree??{};if(typeof t.passed=="boolean")return t.passed;let n=t.sub_results??[];return n.length===0?t.status==="passed":(t.composite_operator??"and")==="or"?n.some(o=>o.passed===!0):n.every(o=>o.passed===!0)}function lt(e){return e.map(t=>({description:t.description??"",store_key:t.store_key??"",expected_value:t.expected??"",extracted_value:t.extracted_value??"",operator:t.operator??"equals",transforms:t.transforms??[]}))}function Bt(e){let t=e.assertion_tree??{},n=t.sub_results??[],r=lt(n);return{operator:[],assertion_operands:[],left_operand:null,right_operand:null,operands:[],sub_results:n,sub_checks:r,composite_operator:t.composite_operator??"and",verification:t.verification??"",claim:t.description??""}}function Mt(e){let n=(e.action_params??{}).assertion_tree??{},r=n.sub_results??[],o=lt(r);return[{operation:e.action_instruction??"",agent:"Operation Agent",operation_dict:{operation_type:"ASSERTION",assertion_tree:{sub_results:r,sub_checks:o,composite_operator:n.composite_operator??"and",verification:"",claim:n.description??e.action_instruction??"",operator:[],assertion_operands:[],left_operand:null,right_operand:null,operands:[]}},variable:{},secrets:{},params:{}}]}function zt(e,t,n,r){let o=e.visual_data;if(!o||o.x==null||o.y==null)return null;let i=t?`${t}/test_screenshots`:"";return{x:o.x,y:o.y,confidence:0,bbox:o.bbox??null,bbox_source:o.bbox?"accessibility_tree":"fallback",viewport_width:o.viewport_width??1280,viewport_height:o.viewport_height??800,scale_factor:null,raw_image_url:i?`${i}/untagged_screenshot/${n}.${r?.get(n)??"png"}`:"",raw_image_sas_url:"",annotated_image_url:"",annotated_image_sas_url:""}}function Vt(e){if(!e)return"";let t=e;return typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.frameInfo)&&(t=e.frameInfo),!Array.isArray(t)||t.length===0?"":JSON.stringify(t)}function qt(e){return/^(android|ios)_native$/i.test(e.platform??"")}function dt(e,t){return e.map(n=>({...n,type:t?n.strategy??n.type??"native":n.isXPath?"xpath":"css"}))}function $t(e,t,n){let r={selector_target:"",drag_displacement:{},hold_duration_ms:null,move_duration_ms:null,hold_at_destination_ms:null};if(e!=="drag")return r;let o=t.target_selectors,i={};typeof t.direction=="string"&&t.direction&&(i.direction=t.direction,typeof t.fraction=="number"&&(i.fraction=t.fraction));let s=a=>typeof t[a]=="number"?Math.trunc(t[a]):null;return{selector_target:Array.isArray(o)&&o.length>0?dt(o,n):"",drag_displacement:i,hold_duration_ms:s("hold_duration_ms"),move_duration_ms:s("move_duration_ms"),hold_at_destination_ms:s("hold_at_destination_ms")}}function nt(e,t="",n){let r=e.action_type,o=at(r,e),i=e.action_params??{},s=e.coordinates??null,a=e.selectors??null,c=!!(a&&a.length>0),u=qt(e),l=$t(r,i,u),_=e.timestamp??"",p=e.duration_ms??0,d=e.variables_used??{},f=e.action_id??A(),g=A(),m=ct(_,p),h="",I="";if(r==="navigate")I=i.url??"",h=I;else if(r==="type"||r==="fill")h=i.text??"";else if(r==="press_key")h=i.key??"";else if(r==="wait")h=String(i.ms??i.timeout_ms??"");else if(r==="evaluate_js")h=i.script??"";else if(r==="upload_files"){let q=N(i);q&&(h=O(q.name))}else r==="analyze"&&o==="SET_VARIABLE"&&(h=e.output_value??"");let E="";r==="go_back"?E="back":r==="go_forward"&&(E="forward");let b=e.action_instruction??"",v=U(h)||U(I)||U(b),x=Ut(e,o,d);return{operation_id:f,instruction_id:g,instruction:b,intent:b,operation_start:_,operation_end:m,status:e.status??"",command:o,name:"",target:"",value:h,message:"",operation_dict:"",frame:Vt(e.frame_info),error_message:e.error??"",code_snippet:"",sub_instruction_obj:JSON.stringify(x),test_id:"",test_version:"",action:"",string_to_float:!1,feedback_msg:"",time_taken:"",create_time_stamp:"",update_time_stamp:"",locator_variable:"",locator_variable_name:"",image_url:t?`${t}/test_screenshots/untagged_screenshot/${f}.${n?.get(f)??"png"}`:"",alternative_xpaths:[],attribute:"",value_description:"",url:I,navigation_direction:E,tagified_image_url:"",query_variable_name:e.output_variable??"",query_variable_value:e.output_value??"",query_variable_type:"",expected_value:"",queried_value:"",operator:"",assertion_status:o==="ASSERTION"?Ft(i):"",query_info_dict:{},query_content_confidence:"none",debugging_logs:[],locator_index:0,query_html:"",user_variables:"[]",optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,tab_index:String(i.tab_index??""),tab_identifier:String(i.tab_identifier??""),scroll_value:i.amount??1,scroll_direction:i.direction??"",mi_scroll_payload:{},sleep_duration:0,app_id:"",manual_interaction_tag:"",string_to_float_list:[],js_snippet:r==="evaluate_js"?i.script??"":"",code_error:"",hide:v,dismiss_dialog:!1,use_v2_mobile_tagging:u,multiple_inputs:!1,dialog_action:"",dialog_type:"",is_coordinates_used_for_interaction:s!==null&&!c,element_coordinates_ratio:[],element_bounds_ratio:[],x_coord:c?null:s?.x??null,y_coord:c?null:s?.y??null,target_x_coord:i.target_x??null,target_y_coord:i.target_y??null,source_description:i.source_description??null,target_description:i.target_description??null,use_coordinates:s!==null&&!c,kaneaiMobileTaggingImageLimit:1,clicks_order_code:"se_js_ac",selector:c?dt(a,u):"",selector_target:l.selector_target,math_result_variable_name:"",math_result_variable_value:"",expression_tree:o==="ASSERTION"?Bt(i):i.expression_tree??{},assertion_tree:i.assertion_tree??{},assertion_tree_simplified:{},network_throttle:{},is_mobile_offline:!1,autoheal:!1,reprobe:e.reprobe??!1,click_modifier:(i.click_count??1)>=2?{kind:"multi_click",frequency:i.click_count}:null,db_query:"",db_details:{},db_query_decoded:"",is_global_variable:!1,is_global_variable_persist:!1,global_variable_id:"",wait_for_element_timeout:0,failure_condition:o==="ASSERTION"?"Fail test immediately":"",screenshot_command:"",smartui_contents:{},smartui_results:{},result_type:"",result_hint:"",drag_offset:{},drag_displacement:l.drag_displacement,hold_duration_ms:l.hold_duration_ms,move_duration_ms:l.move_duration_ms,hold_at_destination_ms:l.hold_at_destination_ms,start_coordinates:i.source_coordinates?{x:i.source_coordinates[0],y:i.source_coordinates[1]}:{},end_coordinates:i.target_coordinates?{x:i.target_coordinates[0],y:i.target_coordinates[1]}:{},element_rect:null,is_canvas:!1,until_condition:"",until_max_retries:0,until_settle_ms:0,api_data:r==="api"?{request:e.action_params?.api_data?.request??{}}:{},output_variables:r==="api"?e.output_variable?{[e.output_variable]:null}:{}:e.output_variable?{[e.output_variable]:e.output_value??""}:{},visual_context:zt(e,t,f,n),reasoning:r==="analyze"?i.query??"":e.intent??e.action_instruction??""}}function rt(e,t){let n=e.action_type,r=at(n,e),o=e.timestamp??"",i=e.duration_ms??0,s=ct(o,i),a=r==="ASSERTION"||r==="MATHEMATICAL_OPERATION";return{instruction_id:t.instruction_id,instruction_class:a?"non_driver_action":"driver_action",module_id:"",instruction:e.action_instruction??"",command:r,error:null,parent_instruction_id:"",classification_layer_resp:r==="ASSERTION"?Mt(e):[],classification_error:{},operations:[t],status:e.status??"",start_timestamp:o,end_timestamp:s,type:"agent_generated",tags:[],html_paths:[],optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,content_type:n==="api"?"api":n==="analyze"&&e.action_params?.analyzer_type==="api_response"?"api_calls_query":n==="analyze"&&e.action_params?.analyzer_type?.startsWith("devtool_")?e.action_params.analyzer_type.replace("devtool_","devtools_"):"instruction",js_snippet:n==="evaluate_js"?e.action_params?.script??"":"",user_variables:n==="api"?Dt(e):"[]",api_data:n==="api"?{request:e.action_params?.api_data?.request??{},response:ut(e)}:{},params_used:!1,hard_assertion:r==="ASSERTION"?e.action_params?.failure_condition==="hard":!1,expected_outcome:"",module_execution_index:0,module_version:null,network_throttle:{},isEdited:!1,use_query_assertion_v2:!1,db_query:"",db_details:{},network_assertion_content:{},screenshot_command:"",smartui_contents:{},generative_id:"",plan_id:"",generative_objective:"",error_message:"",error_code:"",reason:"",title:"",used_variables:[],reasoning:n==="analyze"?e.action_params?.query??"":e.intent??e.action_instruction??""}}function Gt(e,t=[]){let n=e.action_params??{},r=n.branches??[],o=n.winning_index??-1,i=n.sub_results??[],s={};for(let c of i){let u=c.sub_results;if(u)for(let l of u){let _=l.store_key;_&&(s[_]=l)}}let a=r.map((c,u)=>{let l=u===o,_=(c.sub_checks??[]).map(p=>{let d=s[p.store_key];return{description:p.description,store_key:p.store_key,expected_value:p.expected_value,stored_value:d?.extracted_value??p.stored_value,operator:p.operator??d?.operator??"equals",transforms:p.transforms??d?.transforms??[]}});if(_.length===0&&c.condition&&i.length>0){let d=i.find(f=>f.branch_index===u)?.sub_results??[];d.length>0&&(_=d.map(f=>({description:f.description??c.condition,store_key:f.store_key??"",expected_value:f.expected??"true",stored_value:f.extracted_value??void 0,operator:f.operator??"equals",transforms:f.transforms??[]})))}return{branch_index:u,condition:c.condition??null,branch_type:c.branch_type??"sub_objective",passed:l,sub_objective:null,custom_event:c.custom_event??null,children:l?t:[],sub_checks:c.condition?_:[],composite_operator:c.composite_operator??"and"}});return{content_type:"conditional_block",instruction_id:`if_else_${A().slice(0,8)}`,instruction:e.action_instruction??"",instruction_class:"driver_action",command:"",status:e.status??"success",resolved_branch_index:o,branches:a,generative_id:"",generative_objective:"",variables_used:{},classification_layer_resp:[],classification_error:{},used_variables:[],user_variables:"[]",module_id:"",module_execution_index:0,module_version:"",plan_id:"",optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,error:null,error_message:"",error_code:"",reason:"",start_timestamp:e.timestamp??"",end_timestamp:"",type:"agent_generated",hook:null,hook_type:null,evaluation_context:{},query_variables:{}}}function _t(e,t,n){for(let r of e)r.content_type==="instruction"&&"generative_id"in r&&(r.generative_id=t,r.generative_objective=n)}function F(e,t="",n,r){let o=[],i=0;for(;i<e.length;){let s=e[i],a=s.action_type;if(!r?.keepFailedActions&&s.status==="error"&&a!=="assert"&&a!=="if_else"&&a!=="child_agent_start"&&a!=="child_agent_end"&&!(s.until_condition&&!s.error)){i+=1;continue}if(a==="analyze"&&(!st[s.action_params?.analyzer_type??""]||s.action_params?.analyzer_type==="textual_visual"&&s.action_params?.code)){i+=1;continue}if(a==="child_agent_start"){let c=s.action_params?.child_id??"",u=s.action_params?.objective??"",l=[];i+=1;let _=1,p="error",d;for(;i<e.length&&_>0;){let v=e[i],x=v.action_type;if(x==="child_agent_start")_+=1;else if(x==="child_agent_end"&&(_-=1,_===0)){p=v.status??"success",d=v,i+=1;break}_>0&&l.push(v),i+=1}let f=F(l,t,n);_t(f,c,u);let g=d?.action_params?.result_code??null,m=d?.action_params?.reason_code??null,h=d?.action_params?.error_message??null,I=d?.action_params?.summary??null,E=d?.action_params?.one_liner??null,b=p==="error";o.push({content_type:"generative_block",instruction_id:`generative_block_${c}`,generative_id:c,objective:u,status:p,children:f,error_message:b?h??null:null,error_code:b?m??null:null,result_code:g??null,bifurcation_context:[],approach_reason:ot(I),one_liner:E??null});continue}else if(a==="child_agent_end"){i+=1;continue}else if(a==="if_else"){i+=1;let c=[];for(;i<e.length&&e[i].action_type==="child_agent_start";){let u=e[i],l=u.action_params?.child_id??"",_=u.action_params?.objective??"",p=[];i+=1;let d=1,f="error";for(;i<e.length&&d>0;){let m=e[i];if(m.action_type==="child_agent_start")d+=1;else if(m.action_type==="child_agent_end"&&(d-=1,d===0)){f=m.status??"success",i+=1;break}d>0&&p.push(m),i+=1}let g=F(p,t,n);c.push(...g)}o.push(Gt(s,c));continue}else if(a==="query_tool"){i+=1;continue}else if(s.until_condition){let c=nt(s,t,n),u=rt(s,c),l=typeof s.until_condition_met=="boolean"?s.until_condition_met:s.status==="success";o.push({content_type:"until_block",instruction_id:`until_${A().slice(0,8)}`,condition:s.until_condition,max_retries:s.until_max_retries??10,settle_ms:s.until_settle_ms??500,current_count:0,condition_met:l,children:[u],generative_id:"",generative_objective:"",variables_used:{},status:s.status??"success"})}else{let c=nt(s,t,n),u=rt(s,c);o.push(u)}i+=1}return o}function P(e,t="",n,r){let o=[],i=[],s=r?.passthrough,a=s?j(s.authoredInstructions):null;for(let d of e){if(s&&a&&d.flatIndex!==void 0&&s.replayOnlyFlatIndices.has(d.flatIndex)){let b=D(d.records,a);if(b){for(let v of b)o.push(v),i.push(d.flatIndex);continue}console.warn(`[migrator] replay-only passthrough: no authored operation matched step ${d.flatIndex} (action_id \u2260 any operation_id in the authored blob) \u2014 falling back to this run's records`)}let f=F(d.records,t,n,r);if(f.length===0)continue;let g=A().replace(/-/g,"");_t(f,g,d.objective);let m=f.some(b=>"status"in b&&typeof b.status=="string"?b.status==="error"||b.status==="failed":!1),h=d.resultCode?parseInt(d.resultCode,10):null,I=h!==null&&!isNaN(h)&&h>=200,E=m||I?"error":"success";o.push({content_type:"generative_block",instruction_id:`generative_block_${g}`,generative_id:g,objective:d.objective,status:E,children:f,error_message:E==="error"?d.errorMessage??null:null,error_code:E==="error"?d.reasonCode??null:null,result_code:d.resultCode??null,bifurcation_context:[],approach_reason:ot(d.summary),one_liner:d.oneLiner??null}),i.push(d.flatIndex)}let c=o.map((d,f)=>({block:d,flat:i[f]})),u=r?.moduleSpans??[],l=r?.blockSpans??[],_=r?.authoredBlocks??[];u.length>0&&(c=pt(c,u,l,_));let p=mt(l,u);return p.length>0&&(c=B(c,p,_)),{instructions:c.map(d=>d.block)}}function pt(e,t,n,r){let o=[],i=a=>a===void 0?void 0:t.find(c=>a>=c.flatFrom&&a<=c.flatTo),s=0;for(;s<e.length;){let a=i(e[s].flat);if(!a){o.push(e[s]),s++;continue}let c=[];for(;s<e.length&&i(e[s].flat)===a;)c.push(e[s++]);let u=pt(c,a.children,n,r),l=mt(ft(n,a),a.children);l.length>0&&(u=B(u,l,r)),o.push({block:Qt(a,u.map(_=>_.block)),flat:c[0].flat})}return o}function gt(e,t){return e.flatFrom>=t.flatFrom&&e.flatTo<=t.flatTo}function ft(e,t){let n=[];for(let r of e)gt(r,t)?n.push(r):n.push(...ft(r.children,t));return n}function mt(e,t){let n=[],r=i=>{for(let s of i)n.push(s),r(s.children)};r(t);let o=i=>i.filter(s=>!n.some(a=>gt(s,a))).map(s=>({...s,children:o(s.children)}));return n.length>0?o(e):e}function B(e,t,n){let r=[...t].sort((u,l)=>u.flatFrom-l.flatFrom),o=[],i=(u,l)=>{o.push({block:Yt(u,l,n),flat:u.flatFrom})},s=(u,l)=>u!==void 0&&u>=l.flatFrom&&u<=l.flatTo,a=0,c=0;for(;c<e.length;){let u=e[c].flat;for(;a<r.length&&u!==void 0&&r[a].flatTo<u;)i(r[a++],[]);let l=a<r.length&&s(u,r[a])?r[a]:void 0;if(!l){o.push(e[c]),c++;continue}let _=[];for(;c<e.length&&s(e[c].flat,l);)_.push(e[c++]);i(l,_),a++}for(;a<r.length;)i(r[a++],[]);return o}function Kt(e){let t=new Map;for(let n of e)t.set(n.flat,n);return e.filter(n=>t.get(n.flat)===n)}var Ht=["children","instructions","branches","module_content","true_branch","false_branch"];function Jt(e,t){if(!t)return;let n=[...e];for(;n.length>0;){let r=n.pop();if(!r||typeof r!="object")continue;let o=r;if(o.instruction_id===t&&(o.content_type==="conditional_block"||o.content_type==="until_block"))return o;for(let i of Ht){let s=o[i];Array.isArray(s)?n.push(...s):s&&typeof s=="object"&&n.push(s)}}}function Xt(e,t,n){if(!e)return[];if(t==="while")return Array.isArray(e.children)?e.children:[];let o=(Array.isArray(e.branches)?e.branches:[])[n];return o&&Array.isArray(o.children)?o.children:[]}function Yt(e,t,n){let r=Jt(n,e.blockId),o=e.branches.map((i,s)=>{let a=t.filter(l=>l.flat!==void 0&&l.flat>=i.flatFrom&&l.flat<=i.flatTo);e.kind==="while"&&(a=Kt(a));let c=B(a,e.children,n).map(l=>l.block);if(c.length>0)return c;let u=Xt(r,e.kind,s);return u.length===0&&!i.taken&&console.warn(`[migrator] control-flow: branch ${s} of block ${e.blockId||e.instruction} did not run and no authored block matched \u2014 emitted empty`),u});return e.kind==="if"?Wt(e,o,r):Zt(e,o[0]??[],r)}function Wt(e,t,n){let r=Array.isArray(n?.branches)?n.branches:[],o=M(t.flat()),i=e.branches.map((s,a)=>{let c=r[a];return{branch_index:a,condition:s.branch_type==="else"?null:s.condition,branch_type:s.branch_type,passed:s.taken,sub_objective:null,custom_event:c?.custom_event??null,children:t[a],sub_checks:Array.isArray(c?.sub_checks)?c.sub_checks:[],composite_operator:c?.composite_operator??"and"}});return{content_type:"conditional_block",instruction_id:e.blockId||`if_else_${A().slice(0,8)}`,instruction:e.instruction,instruction_class:"driver_action",command:"",status:o?"error":"success",resolved_branch_index:e.branches.findIndex(s=>s.taken),branches:i,generative_id:"",generative_objective:"",variables_used:{},classification_layer_resp:[],classification_error:{},used_variables:[],user_variables:"[]",module_id:"",module_execution_index:0,module_version:"",plan_id:"",optional_flag:!1,max_retries:0,retries_delay:0,explicit_wait:0,implicit_wait:0,error:null,error_message:o?.message??"",error_code:o?.code??"",reason:"",start_timestamp:"",end_timestamp:"",type:"agent_generated",hook:null,hook_type:null,evaluation_context:{},query_variables:{}}}function Zt(e,t,n){let r=e.whileCfg??{max_retries:5,settle_ms:500,on_exhaust:"fail",iterations:0,condition_met:!1},o=M(t),i=(s,a)=>n&&n[s]!==void 0?n[s]:a;return{content_type:"until_block",instruction_id:e.blockId||`until_${A().slice(0,8)}`,condition:e.instruction,max_retries:r.max_retries,settle_ms:r.settle_ms,current_count:r.iterations,condition_met:r.condition_met,children:t,generative_id:"",generative_objective:"",variables_used:{},status:o?"error":"success",on_exhaust:i("on_exhaust",r.on_exhaust),mode:i("mode",""),check:i("check",""),conditions:i("conditions",[]),connectors:i("connectors",[]),sub_checks:i("sub_checks",[]),composite_operator:i("composite_operator","and")}}function M(e){for(let t of e){let n="status"in t&&typeof t.status=="string"?t.status:"";if(n==="error"||n==="failed"){let r="error_message"in t?t.error_message:void 0,o="error_code"in t?t.error_code:void 0;return{message:r??null,code:o??null}}}return null}function Qt(e,t){let n=e.meta,r=(u,l="")=>typeof n[u]=="string"?n[u]:l,o=(u,l=!1)=>typeof n[u]=="boolean"?n[u]:l,i=u=>Array.isArray(n[u])?n[u]:[],s=typeof n.module_version=="number"||typeof n.module_version=="string"?n.module_version:null,a=r("module_id"),c=M(t);return{content_type:X,instruction_id:`module_block_${a}`,module_id:a,module_version:s,module_instance_id:A(),module_name:r("module_name"),module_description:r("module_description"),module_platform:r("module_platform"),creation_mode:r("creation_mode","Agent"),tms_status:r("tms_status","active"),is_validated:o("is_validated"),is_dirty:e.dirty,enrichment_id:r("enrichment_id"),tags:i("tags"),project_ids:i("project_ids"),link_to_all:o("link_to_all"),status:c?"error":"success",children:t,error_message:c?.message??null,error_code:c?.code??null,update_available:!1,update_info:{}}}function bt(e,t){let n;try{n=ht(e)}catch{return 0}let r=0,o=n.filter(i=>/^\d+$/.test(i)).sort((i,s)=>Number(i)-Number(s));for(let i of o){let s=S(e,i),a=S(s,"logs");if(!te(a))continue;let c;try{c=ht(a)}catch{continue}let u=c.filter(p=>p.endsWith("-actions.ndjson")).sort((p,d)=>(parseInt(p,10)||0)-(parseInt(d,10)||0)),l=[];for(let p of u){let d=t.readActions(S(a,p));d.length&&l.push({objective:t.objective??"",records:d})}if(l.length===0)continue;let{instructions:_}=P(l,t.screenshotBaseUrl??"",t.extMap,{keepFailedActions:!0});if(_.length!==0)try{let p=S(s,"auteur");ee(p,{recursive:!0}),ne(S(p,"execution.json"),JSON.stringify(t.buildBlob(_),null,2)),r++,t.log?.("info","EVIDENCE_ARCHIVED_ATTEMPT_BLOB","Derived nested attempt blob",{attempt:i,instructions:_.length})}catch(p){t.log?.("debug","EVIDENCE_ARCHIVED_ATTEMPT_BLOB_FAILED","Nested attempt blob derivation failed",{attempt:i,error:p instanceof Error?p.message:String(p)})}}return r}var yt=kt(Rt(),1);import{createWriteStream as re}from"fs";import{readFile as ie}from"fs/promises";import{join as oe,basename as se}from"path";import{tmpdir as ae}from"os";var ce=["**/screenshots/**","**/annotated/**","**/tcg/**","**/bifurcation/**"];async function Et(e){let t=oe(ae(),`${se(e)}_artifacts.zip`);return new Promise((n,r)=>{let o=re(t),i=(0,yt.default)("zip",{zlib:{level:6}});o.on("close",()=>n(t)),i.on("error",r),i.pipe(o),i.glob("**/*",{cwd:e,ignore:ce}),i.finalize()})}async function It(e){return ie(e)}async function de(e,t){return vt(J(e,t))}function _e(e){return{key:"artifacts",content_type:"application/zip",filename:`${e}.evidence`}}var At=class{config;controller;testId;constructor(t){this.config=t,this.controller=new G(t.controllerBaseUrl,t.auth),this.testId=t.testId}log(t,n,r,o){this.config.log?.(t,n,r,o)}async execute(){let{onProgress:t}=this.config;try{if(!this.testId)return this.log("error","PIPELINE_ABORT","No test_id available"),{success:!1,testId:null,error:"No test_id available"};let n=this.config.evidence,r=null;if(this.config.shouldUploadArtifacts!==!1){t("convert","running");let a=this.collectNdjsonPerRun(),c=a.reduce((g,m)=>g+m.records.length,0);this.log("info","PIPELINE_CONVERT","Collected NDJSON records",{total_records:c,run_groups:a.length});let u=this.loadReplayOnlyPassthrough(),{instructions:l}=a.length>0?P(a,this.config.screenshotBaseUrl??"",this.config.screenshotExtMap,{moduleSpans:this.config.moduleSpans,...u?{passthrough:u}:{},...this.config.blockSpans?.length?{blockSpans:this.config.blockSpans,authoredBlocks:this.loadAuthoredBlocks()}:{}}):{instructions:[]};this.log("info","PIPELINE_CONVERT_INSTRUCTIONS","Auteur instructions produced",{count:l.length});let _=this.buildExecutionEnvelope(l),p=Buffer.from(JSON.stringify(_));this.log("info","PIPELINE_CONVERT_BLOB","Blob created",{size_kb:+(p.length/1024).toFixed(1)});let d=y(this.config.sessionDir,"execution.json");w(d,JSON.stringify(_,null,2)),this.log("info","PIPELINE_CONVERT_LOCAL_SAVE","Execution blob saved locally",{path:d});let f=n?.packTestDir??this.config.evidenceRead?.packTestDir;if(f){let g=y(f,"auteur");V(g,{recursive:!0}),w(y(g,"execution.json"),JSON.stringify(_,null,2)),this.log("info","PIPELINE_CONVERT_PACK_COPY","Execution blob copied into pack",{path:y(g,"execution.json")}),this.deriveArchivedAttemptBlobs(f)}if(t("convert","done"),n)r=p;else{t("zip","running"),this.log("info","PIPELINE_ZIP_START","Zipping session",{session_dir:this.config.sessionDir});let g=null,m;try{g=await Et(this.config.sessionDir),m=await It(g),this.log("info","PIPELINE_ZIP_DONE","Zip complete",{size_mb:+(m.length/1024/1024).toFixed(1),path:g}),t("zip","done",`${(m.length/1024/1024).toFixed(1)}MB`)}finally{g&&await le(g).catch(()=>{})}t("presign","running"),this.log("info","PIPELINE_PRESIGN_START","Requesting presigned URLs",{url:`${this.config.controllerBaseUrl}/upload/presign`,test_id:this.testId,session_id:this.config.sessionId});let h=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[{key:"artifacts",content_type:"application/zip",filename:`${this.config.sessionId}_artifacts.zip`},{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);this.log("info","PIPELINE_PRESIGN_OK","Presigned URLs received",{artifacts_url:h.urls.artifacts?.blob_url,blob_url:h.urls.blob?.blob_url}),t("presign","done"),t("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading artifacts and blob",{artifact_size_mb:+(m.length/1024/1024).toFixed(1),blob_size_kb:+(p.length/1024).toFixed(1)}),await Promise.all([k(h.urls.artifacts.upload_url,m,"application/zip"),k(h.urls.blob.upload_url,p,"application/json")]),this.log("info","PIPELINE_UPLOAD_OK","Upload complete"),t("upload","done")}}else{let a=this.collectNdjsonPerRun(),c=this.loadReplayOnlyPassthrough(),{instructions:u}=a.length>0?P(a,this.config.screenshotBaseUrl??"",this.config.screenshotExtMap,{keepFailedActions:!0,moduleSpans:this.config.moduleSpans,...c?{passthrough:c}:{},...this.config.blockSpans?.length?{blockSpans:this.config.blockSpans,authoredBlocks:this.loadAuthoredBlocks()}:{}}):{instructions:[]},l=this.buildExecutionEnvelope(u),_=y(this.config.sessionDir,"execution.json");w(_,JSON.stringify(l,null,2)),this.log("info","PIPELINE_LOCAL_SAVE","Execution blob saved locally (no upload)",{path:_});let p=this.config.evidence?.packTestDir??this.config.evidenceRead?.packTestDir;if(p){let d=y(p,"auteur");V(d,{recursive:!0});let f=this.readAuthoredExecution(),g=f?this.refreshReplayOnlyInPack(f,a,c):null;w(y(d,"execution.json"),g?.raw??JSON.stringify(l,null,2)),this.log("info","PIPELINE_CONVERT_PACK_COPY","Execution blob copied into pack (gated)",{path:y(d,"execution.json"),source:g?g.refreshed.length>0?"authored+replay_results":"authored":"run_envelope",...g&&g.refreshed.length>0?{refreshed_instruction_ids:g.refreshed}:{}}),this.deriveArchivedAttemptBlobs(p)}t("convert","skipped"),t("zip","skipped"),t("presign","skipped"),t("upload","skipped"),this.log("info","PIPELINE_UPLOAD_SKIPPED","Upload steps skipped (gate disabled)")}if(this.config.shouldReplaceLocalOutput&&this.config.onAtomicReplace){t("atomic_replace","running");try{await this.config.onAtomicReplace(),this.log("info","PIPELINE_ATOMIC_REPLACE_OK","Local output replaced"),t("atomic_replace","done")}catch(a){let c=a instanceof Error?a.message:String(a);throw this.log("error","PIPELINE_ATOMIC_REPLACE_FAILED","Atomic-replace failed",{error:c}),t("atomic_replace","failed",c),a}}else t("atomic_replace","skipped");let o,i;if(this.config.shouldCommit&&!this.config.isFirstRun&&this.config.onCommitLock){t("commit_lock","running");let a=await this.config.onCommitLock();if(a.ok)o=a.testcaseId||void 0,this.log("info","PIPELINE_COMMIT_LOCK_OK","Commit lock acquired",{testcase_id:o??"none",trigger:a.trigger??null,test_instance_id:a.testInstanceId??null}),t("commit_lock","done");else return this.log("error","PIPELINE_COMMIT_LOCK_FAILED","Commit lock failed",{reason:a.reason,message:a.message}),t("commit_lock","failed",`${a.reason??"unknown"}: ${a.message??""}`),{success:!1,testId:this.testId,error:`commit-lock failed: ${a.reason??"unknown"}`}}else t("commit_lock","skipped");if(this.config.isFirstRun&&!this.config.skipTmsFinalize){t("finalize","running"),this.log("info","PIPELINE_FINALIZE_START","Finalizing test (first-run)",{test_id:this.testId,commit_id:this.config.commitId});let a=new K(this.config.tmsBaseUrl,this.config.tmsUsername,this.config.tmsAccessKey),c=this.config.runObjectives&&this.config.runObjectives.length>0?this.config.runObjectives:[this.config.firstObjective];if(o=(await a.endTest(this.testId,{commit_id:this.config.commitId,time_taken:Math.round(this.config.totalDuration),steps_count:this.config.totalSteps,commit_message:this.config.firstObjective.slice(0,255),objectives:c})).testcase_id||void 0,this.log("info","PIPELINE_FINALIZE_OK","Test finalized",{testcase_id:o??"none"}),this.config.onFinalizeSuccess)try{await this.config.onFinalizeSuccess(o)}catch(l){this.log("warn","PIPELINE_FINALIZE_META_FAILED","Meta-rewrite after endTest failed",{error:String(l)})}t("finalize","done")}else t("finalize","skipped"),this.log("info","PIPELINE_FINALIZE_SKIPPED","Finalize skipped (evolve flow or first-run disabled)");if(o&&this.config.shareApiBaseUrl)try{i=await this.generateShareLink(o),this.log("info","PIPELINE_SHARE_OK","Share link generated",{share_id:i})}catch(a){this.log("warn","PIPELINE_SHARE_FAILED","Share link failed",{error:String(a)})}if(n&&r){let a=null;t("zip","running");try{await n.sealFn({testcaseId:o,shareId:i}),a=n.sealedPackPath?await vt(n.sealedPackPath):await de(n.executionId,n.cwd),this.log("info","PIPELINE_EVIDENCE_SEALED","Evidence pack sealed",{execution_id:n.executionId}),this.log("info","PIPELINE_PACK_READ","Sealed pack read",{size_mb:+(a.length/1024/1024).toFixed(1)})}catch(c){let u=c instanceof Error?c.message:String(c);this.log("warn","PIPELINE_EVIDENCE_UPLOAD_SKIPPED","Evidence seal/read failed \u2014 uploading blob only",{execution_id:n.executionId,error:u})}if(a){t("zip","done",`${(a.length/1024/1024).toFixed(1)}MB`),t("presign","running");let c=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[_e(n.executionId),{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);this.log("info","PIPELINE_PRESIGN_OK","Presigned URLs received",{artifacts_url:c.urls.artifacts?.blob_url,blob_url:c.urls.blob?.blob_url}),t("presign","done"),t("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading pack and blob",{artifact_size_mb:+(a.length/1024/1024).toFixed(1),blob_size_kb:+(r.length/1024).toFixed(1)}),await Promise.all([k(c.urls.artifacts.upload_url,a,"application/zip"),k(c.urls.blob.upload_url,r,"application/json")]),this.log("info","PIPELINE_UPLOAD_OK","Upload complete"),t("upload","done")}else{t("zip","skipped"),t("presign","running");let c=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);t("presign","done"),t("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading blob only (evidence skipped)",{blob_size_kb:+(r.length/1024).toFixed(1)}),await k(c.urls.blob.upload_url,r,"application/json"),this.log("info","PIPELINE_UPLOAD_OK","Blob upload complete (pack skipped)"),t("upload","done")}}let s;if(this.config.codeExport?.enabled&&o){let a=!1;try{await this.triggerCodeExport(o),this.log("info","PIPELINE_CODE_EXPORT_START","Code export triggered"),a=!0}catch(c){let u=c instanceof Error?c.message:String(c);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export trigger failed; skipping poll",{error:u}),t("code_export","failed",`trigger failed: ${u}`)}if(a){t("code_export","running","Waiting for code generation\u2026");try{s=await this.pollAndDownloadCode(o,t),this.log("info","PIPELINE_CODE_EXPORT_OK","Code export complete",{dir:s}),t("code_export","done",s)}catch(c){let u=c instanceof Error?c.message:String(c);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export failed",{error:u}),t("code_export","failed",u)}}}else t("code_export","skipped");return this.log("info","PIPELINE_COMPLETE","Pipeline complete"),{success:!0,testId:this.testId,testcaseId:o,shareId:i,codeExportDir:s}}catch(n){return{success:!1,testId:this.testId,error:n instanceof Error?n.message:String(n)}}}async runCodeExport(t,n){let r=n??this.config.onProgress,o=!1;try{await this.triggerCodeExport(t),this.log("info","PIPELINE_CODE_EXPORT_TRIGGER","Code export triggered",{testcase_id:t}),o=!0}catch(i){let s=i instanceof Error?i.message:String(i);this.log("error","PIPELINE_CODE_EXPORT_TRIGGER_FAILED","Code export trigger failed; skipping poll",{error:s}),r("code_export","failed",`trigger failed: ${s}`)}if(o){r("code_export","running","Waiting for code generation\u2026");try{let i=await this.pollAndDownloadCode(t,r);return this.log("info","PIPELINE_CODE_EXPORT_OK","Code export complete",{dir:i}),r("code_export","done",i),i}catch(i){let s=i instanceof Error?i.message:String(i);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export failed",{error:s}),r("code_export","failed",s);return}}}deriveArchivedAttemptBlobs(t){try{let n=bt(t,{readActions:r=>this.readNdjsonFromFile(r),buildBlob:r=>this.buildExecutionEnvelope(r),objective:this.config.firstObjective,screenshotBaseUrl:this.config.screenshotBaseUrl??"",extMap:this.config.screenshotExtMap,log:(r,o,i,s)=>this.log(r,o,i,s)});n>0&&this.log("info","PIPELINE_ARCHIVED_ATTEMPTS","Nested retry-attempt blobs derived",{count:n})}catch(n){this.log("debug","PIPELINE_ARCHIVED_ATTEMPTS_FAILED","Nested attempt blob pass failed",{error:n instanceof Error?n.message:String(n)})}}collectNdjsonPerRun(){let t=[],n=this.config.runObjectives??[],r=this.config.runMetadata??[],o=this.config.evidence??this.config.evidenceRead;for(let i=0;i<this.config.runDirs.length;i++){let s=this.config.runDirs[i],a=n[i]||this.config.firstObjective,c=r[i],u=o?this.readNdjsonFromFile(y(o.packTestDir,"logs",`${o.runIndices?.[i]??i}-actions.ndjson`)):this.readNdjsonFromDir(s);if(u.length>0){let l=o?.runIndices?.[i]??i,_=this.config.runFlatIndex?.[l];t.push({objective:a,records:u,..._!==void 0?{flatIndex:_}:{},resultCode:c?.resultCode,reasonCode:c?.reasonCode,errorMessage:c?.errorMessage,summary:c?.summary,oneLiner:c?.oneLiner})}}if(t.length===0){let i=y(this.config.sessionDir,"runs");if(z(i))try{let a=ue(i,{withFileTypes:!0}).filter(c=>c.isDirectory()).map(c=>c.name).sort();for(let c of a){let u=y(i,c),l=this.readNdjsonFromDir(u);l.length>0&&t.push({objective:this.config.firstObjective,records:l})}}catch{}}return t}readNdjsonFromDir(t){let n=[y(t,"run-test","actions.ndjson"),y(t,"actions.ndjson")];for(let r of n)if(z(r))return this.readNdjsonFromFile(r);return[]}readNdjsonFromFile(t){let n=[];if(!z(t))return n;this.log("debug","PIPELINE_COLLECT_READ","Reading NDJSON file",{path:t});let r=L(t,"utf-8");for(let o of r.split(`
5
5
  `)){let i=o.trim();if(i)try{n.push(JSON.parse(i))}catch{}}return n}async generateShareLink(t){let n=`${this.config.shareApiBaseUrl}/lshs/api/v1.0/share-item/generate-sharable-link`;this.log("info","PIPELINE_SHARE_START","Requesting share link",{url:n,testcase_id:t});let r={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({entityIds:[t],entityType:"Test Case Details",expiresAt:7})},o=!!this.config.authResolver;this.log("debug","PIPELINE_SHARE_AUTH","Share link auth config",{resolver:o,fallback_auth_type:typeof this.config.auth=="string"?"bearer":"basic",tms_user:this.config.tmsUsername});let i=o?await this.config.authResolver.fetch(n,r):await R(n,{...r,headers:{...r.headers,Authorization:this.buildAuthHeader()}});if(!i.ok)throw new Error(`Share link API failed: ${i.status} ${await i.text()}`);let s=await i.json();if(!s.shareId)throw new Error("Share link API returned no shareId");return s.shareId}async triggerCodeExport(t){if(!this.config.codeExport)throw new Error("triggerCodeExport called without resolved codeExport config");let{url:n,body:r}=Y({tmsBaseUrl:this.config.tmsBaseUrl,testcaseId:t,codeExport:this.config.codeExport,mobile:this.config.mobile});this.log("info","PIPELINE_CODE_EXPORT_POST","Triggering code export",{url:n});let o={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)},i=this.config.authResolver?await this.config.authResolver.fetch(n,o):await R(n,{...o,headers:{...o.headers,Authorization:this.buildAuthHeader()}});if(!i.ok)throw new Error(`Code export failed: ${i.status} ${await i.text()}`)}async pollAndDownloadCode(t,n){let r=W({tmsBaseUrl:this.config.tmsBaseUrl,testcaseId:t}),o=this.config.exitTimeoutMs??3e5,i=5e3,s=Date.now()+o;this.log("info","PIPELINE_CODE_EXPORT_POLL","Polling for code export",{url:r,timeout_ms:o});let a=(c,u)=>this.config.authResolver?this.config.authResolver.fetch(c,u):R(c,{...u,headers:{...u?.headers,Authorization:this.buildAuthHeader()}});for(;Date.now()<s;){let c=await a(r,{method:"GET",headers:{Accept:"application/json"}});if(!c.ok){let d=await c.text().catch(()=>"");throw this.log("warn","PIPELINE_CODE_EXPORT_POLL_FAILED","Code export poll non-200; skipping",{status:c.status,body:d.slice(0,200)}),new Error(`code export poll skipped: HTTP ${c.status}`)}let l=(await c.json()).data?.find(d=>d.code_name==="kane-cli-trigger");if(!l){this.log("debug","PIPELINE_CODE_EXPORT_WAITING","No kane-cli-trigger entry yet"),n("code_export","running","Waiting for code generation\u2026"),await this.sleep(i);continue}let _=l.status.toLowerCase();if(_==="in progress"||_==="in_progress"||_==="pending"){this.log("debug","PIPELINE_CODE_EXPORT_IN_PROGRESS","Code export in progress",{status:l.status}),n("code_export","running","Generating code\u2026"),await this.sleep(i);continue}if(!l.url||l.url.length===0)throw new Error(`Code export status=${l.status} but no files returned`);let p=this.config.codeExportDir??y(this.config.sessionDir,"code-export");V(p,{recursive:!0}),this.log("info","PIPELINE_CODE_EXPORT_DOWNLOAD","Downloading code files",{file_count:l.url.length,dir:p}),n("code_export","running",`Downloading ${l.url.length} files\u2026`);for(let d of l.url){let f=y(p,d.file_name),g=await R(d.file_url);if(!g.ok){this.log("warn","PIPELINE_CODE_EXPORT_FILE_FAILED","Failed to download file",{file_name:d.file_name,status:g.status});continue}let m=await g.text();w(f,m,"utf-8"),this.log("info","PIPELINE_CODE_EXPORT_FILE_SAVED","File saved",{file_name:d.file_name,size_bytes:m.length})}return p}throw new Error("Code export timed out")}sleep(t){return new Promise(n=>setTimeout(n,t))}buildAuthHeader(){return typeof this.config.auth=="string"?`Bearer ${this.config.auth}`:$(this.config.auth.username,this.config.auth.accessKey)}readAuthoredExecution(){let t=this.config.authoredExecutionPath;if(!t)return null;try{let n=L(t,"utf8");return JSON.parse(n),n}catch{return this.log("warn","PIPELINE_AUTHORED_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 pack gets this run's envelope",{path:t}),null}}refreshReplayOnlyInPack(t,n,r){if(!r)return{raw:t,refreshed:[]};let o=tt(n,r);if(o.length===0)return{raw:t,refreshed:[]};let i=JSON.parse(t);if(!Array.isArray(i.instructions))return{raw:t,refreshed:[]};let s=et(i.instructions,o);return s.length===0?{raw:t,refreshed:s}:{raw:JSON.stringify(i,null,2),refreshed:s}}loadAuthoredBlocks(){let t=this.config.blockAuthoredExecutionPath;if(!t)return[];try{let n=JSON.parse(L(t,"utf8"));return Array.isArray(n.instructions)?n.instructions:[]}catch(n){return this.log("warn","PIPELINE_AUTHORED_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 branches that did not run this time upload empty",{path:t,error:n instanceof Error?n.message:String(n)}),[]}}loadReplayOnlyPassthrough(){let t=this.config.replayOnlyPassthrough;if(!(!t||t.flatIndices.length===0))try{let n=JSON.parse(L(t.authoredExecutionPath,"utf8"));if(!Array.isArray(n.instructions))throw new Error("no instructions array");return{authoredInstructions:n.instructions,replayOnlyFlatIndices:new Set(t.flatIndices)}}catch(n){this.log("warn","PIPELINE_PASSTHROUGH_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 replay-only steps convert from this run's records",{path:t.authoredExecutionPath,flat_indices:t.flatIndices,error:n instanceof Error?n.message:String(n)});return}}buildExecutionEnvelope(t){let n=this.config.runStatuses.every(u=>u==="passed")?"success":"error",r=this.config.variableIds??{},o=[];if(this.config.variables)for(let[u,l]of Object.entries(this.config.variables)){if(l.secret||H(l))continue;let _=u.startsWith("global.")?u.slice(7):u;o.push({id:r[_]??0,name:_,value:l.value,session_value:l.value,is_persist:!1,environment_id:0,environment_name:"No Env"})}let i=[],s=u=>{let l=i.find(_=>_.name===u.name);l?l.value=u.value:i.push(u)},a=[],c=new Set;for(let u of this.collectNdjsonPerRun())for(let l of u.records)if(l.output_variable&&l.output_value!=null&&s({name:l.output_variable,value:String(l.output_value),value_type:"test_level",variable_description:"ANALYZE result"}),l.action_type==="upload_files"){let _=N(l.action_params);if(_){let p=_.media_id||_.media_url;if(!c.has(p)){c.add(p),a.push({media_url:_.media_url,media_id:_.media_id,name:_.name,type:_.type});let d=O(_.name);s({name:it(_.name),value:d,value_type:"string",variable_description:`variable for ${d}`})}}}return{test_id:this.testId,version:"v4",auto_heal_version:this.config.apMode==="v2"?"AH2":"",session_id:this.config.sessionId,org_id:String(this.config.orgId),user_id:String(this.config.userId),url:this.config.firstUrl??"",start_timestamp:this.config.startedAt,end_timestamp:this.config.endedAt,status:n,commit_id:this.config.commitId,instructions:t,modules:[],uploaded_files:a,test_params:this.config.testParams??[],test_level_variables:JSON.stringify(i),test_global_variables:o,max_network_wait:0,wait_buffer:0,network_throttle:{},secrets:this.config.secrets??[],totp:[],environment_id:0,environment:"",mobile_browser:!1,native_popups:[],smartui:{},module_index:0}}};export{de as a,_e as b,At as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as at}from"./chunk-ZKSN2SJ7.js";import{a as rt,b as _e}from"./chunk-EVFFDODK.js";import{a as X,b as Ye,e as fe,f as he,g as Je,h as st}from"./chunk-KMF2PPJ5.js";import{a as Qe,c as Ze,d as et,e as be,f as tt}from"./chunk-D7WG7SRA.js";import{a as He,b as ze,c as We}from"./chunk-SDJNWR4D.js";import{a as ge}from"./chunk-U6OTFMIT.js";import{c as Ke}from"./chunk-V4B5QA3U.js";import{a as Fe,b as Ve,c as Ue}from"./chunk-BB2W35TW.js";import{a as Me,e as Ge}from"./chunk-FY7TCYPK.js";import{a as Xe}from"./chunk-63DYVWNX.js";import{a as nt,b as it}from"./chunk-LSDWPG6C.js";import{q as Be}from"./chunk-6CYF7Q5W.js";import{b as je,c as qe,d as oe,f as Le}from"./chunk-IDLJHKJX.js";import{b as $e,c as Ee,e as Re,f as Ce,g as Ae,h as me,k as ue,l as pe}from"./chunk-IPQAKIJO.js";import{d as De}from"./chunk-CAOZKSQ3.js";import{b as le}from"./chunk-VZ7KXRXB.js";import{a as xe,c as de}from"./chunk-5LJRZI7S.js";import{z as V}from"./chunk-IICT4VOU.js";import{H as Ne}from"./chunk-RDHWNSDP.js";import{a as Ie,f as Oe,g as Pe}from"./chunk-FQNQVC5O.js";import{d as ae,e as Te,f as U,g as W}from"./chunk-XLSOQLVT.js";import{a as Se}from"./chunk-5EOX4MEY.js";import{mkdirSync as Ht,appendFileSync as zt,rmdirSync as $t}from"fs";import{randomBytes as Wt}from"crypto";import{dirname as ce,join as ke,relative as Kt}from"path";function ot(t,e){let i=[];for(let n of e??[]){let c=t.resolve(n.ref)?.tip??null;c!==n.cid&&i.push({ref:n.ref,pinned:n.cid,now:c})}return i}import{existsSync as ye,readFileSync as ve,readdirSync as Ct}from"fs";import{join as se}from"path";var ct=`
2
+ import{a as at}from"./chunk-ZKSN2SJ7.js";import{a as rt,b as _e}from"./chunk-EVFFDODK.js";import{a as X,b as Ye,e as fe,f as he,g as Je,h as st}from"./chunk-ZO75BQ3Z.js";import{a as Qe,c as Ze,d as et,e as be,f as tt}from"./chunk-D7WG7SRA.js";import{a as He,b as ze,c as We}from"./chunk-MMLYJDXO.js";import{a as ge}from"./chunk-U6OTFMIT.js";import{c as Ke}from"./chunk-V4B5QA3U.js";import{a as Fe,b as Ve,c as Ue}from"./chunk-BB2W35TW.js";import{a as Me,e as Ge}from"./chunk-FY7TCYPK.js";import{a as Xe}from"./chunk-63DYVWNX.js";import{a as nt,b as it}from"./chunk-LSDWPG6C.js";import{q as Be}from"./chunk-QX5LJVTD.js";import{b as je,c as qe,d as oe,f as Le}from"./chunk-XYMUKOKK.js";import{b as $e,c as Ee,e as Re,f as Ce,g as Ae,h as me,k as ue,l as pe}from"./chunk-IPQAKIJO.js";import{d as De}from"./chunk-CAOZKSQ3.js";import{b as le}from"./chunk-VZ7KXRXB.js";import{a as xe,c as de}from"./chunk-5LJRZI7S.js";import{z as V}from"./chunk-IICT4VOU.js";import{H as Ne}from"./chunk-RDHWNSDP.js";import{a as Ie,f as Oe,g as Pe}from"./chunk-FQNQVC5O.js";import{d as ae,e as Te,f as U,g as W}from"./chunk-XLSOQLVT.js";import{a as Se}from"./chunk-5EOX4MEY.js";import{mkdirSync as Ht,appendFileSync as zt,rmdirSync as $t}from"fs";import{randomBytes as Wt}from"crypto";import{dirname as ce,join as ke,relative as Kt}from"path";function ot(t,e){let i=[];for(let n of e??[]){let c=t.resolve(n.ref)?.tip??null;c!==n.cid&&i.push({ref:n.ref,pinned:n.cid,now:c})}return i}import{existsSync as ye,readFileSync as ve,readdirSync as Ct}from"fs";import{join as se}from"path";var ct=`
3
3
  version: 1
4
4
  techniques:
5
5
  - id: eqp
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as V,c as H,d as W,e as ie,f as se}from"./chunk-E6X5BVXC.js";import{a as le}from"./chunk-CCW3VQIY.js";import{e as te}from"./chunk-ZRRBZUDJ.js";import{a as oe}from"./chunk-5HDM7GDO.js";import{a as re}from"./chunk-EIMHIZKF.js";import{b as Z}from"./chunk-DT2LIX5S.js";import{b as ee}from"./chunk-4PWAODKJ.js";import{a as I}from"./chunk-BPMSNGXQ.js";import{a as T,b as j,d as ne}from"./chunk-VE3SUJMA.js";import{b as Q}from"./chunk-TZXXJWHA.js";import{r as C}from"./chunk-RSSOJ3L2.js";import{b as Y}from"./chunk-5UHM7CKR.js";import{i as J}from"./chunk-Z7S3IWUX.js";import{a as D}from"./chunk-VIYV6NIW.js";import{a as B,e as K}from"./chunk-EYOCNMUM.js";import{a as z}from"./chunk-JWOPRJIO.js";import{a as q}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as L,j as G}from"./chunk-C44QQJR4.js";import{a as ve}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var s=F(ve(),1);import{basename as he}from"path";var n=F(q(),1);function Ge({resultRef:x,mode:g="singleshot",loginCompleteRef:d}){let{exit:m}=G(),A=(0,s.useRef)(new z),E=(0,s.useRef)(new oe),v=(0,s.useRef)(new te),o=A.current,l=E.current,O=v.current,ae=V(),[h,f]=(0,s.useState)(g==="login"?"login":"gate"),[M,ce]=(0,s.useState)(null),[Pe,R]=(0,s.useState)(null),[we,$]=(0,s.useState)(null),[X,ue]=(0,s.useState)(null),[N,_]=(0,s.useState)([]),P=(0,s.useCallback)((e,t,i,r)=>O.log(e,t,i,r),[O]),be=(0,s.useCallback)((e,t)=>{e?T(o,l,e,t):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[o,l]),y=(0,s.useCallback)(()=>{if(g==="login")d&&(d.current=!0),m();else{let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(t.kind==="unset"||t.kind==="choose-mobile")&&Q();f(i?"target":"input")}},[g,m,d,l]),S=(0,s.useCallback)((e,t)=>{let i=T(o,l,e,t);if(g==="login"){f("ensure-project");return}ne(i)?y():i.projectId?f("ensure-folder"):f("ensure-project")},[o,l,y,g]);L((e,t)=>{t.ctrl&&e==="c"&&C(0,"Ctrl+C exit")});let U=(0,s.useRef)(!1);s.default.useEffect(()=>{U.current||(U.current=!0,g!=="login"&&se(o,P).then(e=>{ce(e),e.status==="authenticated"?S(e.result.profile,e.result.env):e.status==="needs_pick"?f("pick"):(R(e.profile??null),$(e.env??null),f("login"))}).catch(e=>{ue(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[o,P]);let fe=(0,s.useCallback)(e=>{x.current={objective:e},m()},[x,m]),de=(0,s.useCallback)(async(e,t)=>{o.setActiveProfile(e),o.setDefaultEnv(t),(await ie(o,e,t,P)).status==="authenticated"?S(e,t):(R(e),$(t),f("login"))},[o,P,S]),w=(0,s.useCallback)(()=>{let e=o.getActiveProfile(),t=o.getDefaultEnv();if(!e)return null;let i=D(t),r=o.loadBasicAuth(e,t);return new re(i.controllerBaseUrl,async()=>o.loadCredentials(e,t)?.access_token??null,r,P)},[o,P]),ge=(0,s.useCallback)(async()=>{let e=w();if(!e)return null;let t=e.cached??await e.resolve();if(!t)return null;let i=D(o.getDefaultEnv()),r=new I(i.tmsBaseUrl,t.username,t.access_key);try{let p=(await r.listProjects()).find(k=>k.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let b=await r.createProject("KaneAI Generated");return{id:b.id,name:b.name}}catch{return null}},[w,o]),pe=(0,s.useCallback)(async e=>{let t=w();if(!t)return null;let i=t.cached??await t.resolve();if(!i)return null;let r=D(o.getDefaultEnv()),a=new I(r.tmsBaseUrl,i.username,i.access_key);try{let b=(await a.listFolders(e)).find(me=>me.name==="Untitled");if(b)return{id:b.id,name:b.name};let k=await a.createFolder(e,"Untitled");return{id:k.id,name:k.name}}catch{return null}},[w,o]);if(h==="gate")return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(X)return(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"red",children:X}),(0,n.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(h==="pick"&&M?.status==="needs_pick")return(0,n.jsx)(xe,{profiles:M.profiles,onSelect:de});if(h==="login")return(0,n.jsx)(W,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:async(e,t,i,r)=>{let{validateBasicAuth:a}=await import("./validate-basic-WZY6A3KD.js");await a(t,i,r),o.saveBasicAuth(e,t,{username:i,access_key:r}),o.setActiveProfile(e),o.setDefaultEnv(t)},onOAuthLogin:async(e,t)=>{let{LoginFlow:i}=await import("./login-flow-5ZIG7JXT.js");o.setDefaultEnv(t),o.setActiveProfile(e),await new i(e,t,o).login()},onComplete:(e,t)=>{R(e),$(t),o.setActiveProfile(e),o.setDefaultEnv(t),S(e,t)},onCancel:()=>{C(0,"Login cancelled")}});if(h==="ensure-project"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=()=>{if(g==="login"){f("ensure-folder");return}T(o,l,e,t).folderId?y():f("ensure-folder")};return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(Z,{resolver:w(),currentProjectId:l.load().project_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{projectId:r,projectName:a}),_(p=>[...p,`\u2713 Project: ${a} (${r})`]),i()},onCancel:async()=>{let r=await ge();r&&(j(o,l,e,t,{projectId:r.id,projectName:r.name}),_(a=>[...a,`\u2713 Default project: ${r.name} (${r.id})`]),i())}})]})}if(h==="ensure-folder"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=o.loadProfileConfig(e,t);return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(ee,{resolver:w(),projectId:i?.project_id??"",currentFolderId:l.load().folder_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{folderId:r,folderName:a}),_(p=>[...p,`\u2713 Folder: ${a} (${r})`]),y()},onCancel:async()=>{if(!i?.project_id)return;let r=await pe(i.project_id);r&&(j(o,l,e,t,{folderId:r.id,folderName:r.name}),_(a=>[...a,`\u2713 Default folder: ${r.name} (${r.id})`]),y())}})]})}if(h==="target"){let e=B(l.load().mobile?.tui_target,l.load().mobile?.default_target?.kind).kind==="choose-mobile";return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(le,{mode:e?"mobile-only":"all",onSelect:t=>{l.setMobile({tui_target:t}),f("input")},onCancel:()=>f("input")})})}if(h==="input"){let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(()=>{if(t.kind==="emulator"||t.kind==="simulator"){let r=J(e?.default_target)??"(no device)",a=e?.default_app?Y(e.default_app)?e.default_app:he(e.default_app):"(no app)";return`Config: ${K(t.kind)} \xB7 ${r} \xB7 ${a}`}return"Config: Desktop \xB7 Chrome"})();return(0,n.jsxs)(c,{flexDirection:"column",children:[N.length>0&&(0,n.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:N.map((r,a)=>(0,n.jsx)(u,{color:"green",children:r},a))}),(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"gray",children:i})}),(0,n.jsx)(H,{onSubmit:fe,onEscape:()=>C(0,"User pressed Escape"),history:ae,placeholder:"Type an objective..."})]})}return(0,n.jsx)(n.Fragment,{})}function xe({profiles:x,onSelect:g}){let[d,m]=(0,s.useState)(0),[A,E]=(0,s.useState)(!1);return L((v,o)=>{if(!A){if(o.escape){C(0,"Profile picker cancelled");return}if(o.upArrow&&d>0&&m(l=>l-1),o.downArrow&&d<x.length-1&&m(l=>l+1),o.return){E(!0);let l=x[d];g(l.profile,l.env).catch(()=>E(!1))}}}),(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,n.jsx)(c,{marginTop:1,flexDirection:"column",children:x.map((v,o)=>(0,n.jsxs)(u,{children:[o===d?"\u276F ":" ",(0,n.jsx)(u,{color:o===d?"#ff9500":"white",bold:o===d,children:v.profile}),(0,n.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),A&&(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{Ge as a};
2
+ import{b as V,c as H,d as W,e as ie,f as se}from"./chunk-YNOADDF7.js";import{a as le}from"./chunk-EKZI5HZV.js";import{e as te}from"./chunk-NYP7QV54.js";import{a as oe}from"./chunk-GESZSIB6.js";import{a as re}from"./chunk-SYKS57PK.js";import{b as Z}from"./chunk-EA2LT5OJ.js";import{b as ee}from"./chunk-IGLCR4J2.js";import{a as I}from"./chunk-BPMSNGXQ.js";import{a as T,b as j,d as ne}from"./chunk-VE3SUJMA.js";import{b as Q}from"./chunk-TZXXJWHA.js";import{r as C}from"./chunk-RSSOJ3L2.js";import{b as Y}from"./chunk-2LKSDGWA.js";import{i as J}from"./chunk-Z7S3IWUX.js";import{a as D}from"./chunk-RBVLIMOV.js";import{a as B,e as K}from"./chunk-EYOCNMUM.js";import{a as z}from"./chunk-47FQ7ZUQ.js";import{a as q}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as L,j as G}from"./chunk-C44QQJR4.js";import{a as ve}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var s=F(ve(),1);import{basename as he}from"path";var n=F(q(),1);function Ge({resultRef:x,mode:g="singleshot",loginCompleteRef:d}){let{exit:m}=G(),A=(0,s.useRef)(new z),E=(0,s.useRef)(new oe),v=(0,s.useRef)(new te),o=A.current,l=E.current,O=v.current,ae=V(),[h,f]=(0,s.useState)(g==="login"?"login":"gate"),[M,ce]=(0,s.useState)(null),[Pe,R]=(0,s.useState)(null),[we,$]=(0,s.useState)(null),[X,ue]=(0,s.useState)(null),[N,_]=(0,s.useState)([]),P=(0,s.useCallback)((e,t,i,r)=>O.log(e,t,i,r),[O]),be=(0,s.useCallback)((e,t)=>{e?T(o,l,e,t):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[o,l]),y=(0,s.useCallback)(()=>{if(g==="login")d&&(d.current=!0),m();else{let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(t.kind==="unset"||t.kind==="choose-mobile")&&Q();f(i?"target":"input")}},[g,m,d,l]),S=(0,s.useCallback)((e,t)=>{let i=T(o,l,e,t);if(g==="login"){f("ensure-project");return}ne(i)?y():i.projectId?f("ensure-folder"):f("ensure-project")},[o,l,y,g]);L((e,t)=>{t.ctrl&&e==="c"&&C(0,"Ctrl+C exit")});let U=(0,s.useRef)(!1);s.default.useEffect(()=>{U.current||(U.current=!0,g!=="login"&&se(o,P).then(e=>{ce(e),e.status==="authenticated"?S(e.result.profile,e.result.env):e.status==="needs_pick"?f("pick"):(R(e.profile??null),$(e.env??null),f("login"))}).catch(e=>{ue(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[o,P]);let fe=(0,s.useCallback)(e=>{x.current={objective:e},m()},[x,m]),de=(0,s.useCallback)(async(e,t)=>{o.setActiveProfile(e),o.setDefaultEnv(t),(await ie(o,e,t,P)).status==="authenticated"?S(e,t):(R(e),$(t),f("login"))},[o,P,S]),w=(0,s.useCallback)(()=>{let e=o.getActiveProfile(),t=o.getDefaultEnv();if(!e)return null;let i=D(t),r=o.loadBasicAuth(e,t);return new re(i.controllerBaseUrl,async()=>o.loadCredentials(e,t)?.access_token??null,r,P)},[o,P]),ge=(0,s.useCallback)(async()=>{let e=w();if(!e)return null;let t=e.cached??await e.resolve();if(!t)return null;let i=D(o.getDefaultEnv()),r=new I(i.tmsBaseUrl,t.username,t.access_key);try{let p=(await r.listProjects()).find(k=>k.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let b=await r.createProject("KaneAI Generated");return{id:b.id,name:b.name}}catch{return null}},[w,o]),pe=(0,s.useCallback)(async e=>{let t=w();if(!t)return null;let i=t.cached??await t.resolve();if(!i)return null;let r=D(o.getDefaultEnv()),a=new I(r.tmsBaseUrl,i.username,i.access_key);try{let b=(await a.listFolders(e)).find(me=>me.name==="Untitled");if(b)return{id:b.id,name:b.name};let k=await a.createFolder(e,"Untitled");return{id:k.id,name:k.name}}catch{return null}},[w,o]);if(h==="gate")return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(X)return(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"red",children:X}),(0,n.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(h==="pick"&&M?.status==="needs_pick")return(0,n.jsx)(xe,{profiles:M.profiles,onSelect:de});if(h==="login")return(0,n.jsx)(W,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:async(e,t,i,r)=>{let{validateBasicAuth:a}=await import("./validate-basic-A5TEMJNT.js");await a(t,i,r),o.saveBasicAuth(e,t,{username:i,access_key:r}),o.setActiveProfile(e),o.setDefaultEnv(t)},onOAuthLogin:async(e,t)=>{let{LoginFlow:i}=await import("./login-flow-V4US6VQP.js");o.setDefaultEnv(t),o.setActiveProfile(e),await new i(e,t,o).login()},onComplete:(e,t)=>{R(e),$(t),o.setActiveProfile(e),o.setDefaultEnv(t),S(e,t)},onCancel:()=>{C(0,"Login cancelled")}});if(h==="ensure-project"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=()=>{if(g==="login"){f("ensure-folder");return}T(o,l,e,t).folderId?y():f("ensure-folder")};return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(Z,{resolver:w(),currentProjectId:l.load().project_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{projectId:r,projectName:a}),_(p=>[...p,`\u2713 Project: ${a} (${r})`]),i()},onCancel:async()=>{let r=await ge();r&&(j(o,l,e,t,{projectId:r.id,projectName:r.name}),_(a=>[...a,`\u2713 Default project: ${r.name} (${r.id})`]),i())}})]})}if(h==="ensure-folder"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=o.loadProfileConfig(e,t);return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(ee,{resolver:w(),projectId:i?.project_id??"",currentFolderId:l.load().folder_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{folderId:r,folderName:a}),_(p=>[...p,`\u2713 Folder: ${a} (${r})`]),y()},onCancel:async()=>{if(!i?.project_id)return;let r=await pe(i.project_id);r&&(j(o,l,e,t,{folderId:r.id,folderName:r.name}),_(a=>[...a,`\u2713 Default folder: ${r.name} (${r.id})`]),y())}})]})}if(h==="target"){let e=B(l.load().mobile?.tui_target,l.load().mobile?.default_target?.kind).kind==="choose-mobile";return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(le,{mode:e?"mobile-only":"all",onSelect:t=>{l.setMobile({tui_target:t}),f("input")},onCancel:()=>f("input")})})}if(h==="input"){let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(()=>{if(t.kind==="emulator"||t.kind==="simulator"){let r=J(e?.default_target)??"(no device)",a=e?.default_app?Y(e.default_app)?e.default_app:he(e.default_app):"(no app)";return`Config: ${K(t.kind)} \xB7 ${r} \xB7 ${a}`}return"Config: Desktop \xB7 Chrome"})();return(0,n.jsxs)(c,{flexDirection:"column",children:[N.length>0&&(0,n.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:N.map((r,a)=>(0,n.jsx)(u,{color:"green",children:r},a))}),(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"gray",children:i})}),(0,n.jsx)(H,{onSubmit:fe,onEscape:()=>C(0,"User pressed Escape"),history:ae,placeholder:"Type an objective..."})]})}return(0,n.jsx)(n.Fragment,{})}function xe({profiles:x,onSelect:g}){let[d,m]=(0,s.useState)(0),[A,E]=(0,s.useState)(!1);return L((v,o)=>{if(!A){if(o.escape){C(0,"Profile picker cancelled");return}if(o.upArrow&&d>0&&m(l=>l-1),o.downArrow&&d<x.length-1&&m(l=>l+1),o.return){E(!0);let l=x[d];g(l.profile,l.env).catch(()=>E(!1))}}}),(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,n.jsx)(c,{marginTop:1,flexDirection:"column",children:x.map((v,o)=>(0,n.jsxs)(u,{children:[o===d?"\u276F ":" ",(0,n.jsx)(u,{color:o===d?"#ff9500":"white",bold:o===d,children:v.profile}),(0,n.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),A&&(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{Ge as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as he}from"./chunk-WVHMPIDQ.js";import{a as pe}from"./chunk-CCNPXTC6.js";import{b as ue,c as de,d as q,e as Y}from"./chunk-SDJNWR4D.js";import{d as ge,e as me}from"./chunk-AXTPNZPX.js";import{d as fe}from"./chunk-BZAGVBCX.js";import{a as L}from"./chunk-KDNNMU7Q.js";import{a as le}from"./chunk-AG2MVCNK.js";import{z as I}from"./chunk-IICT4VOU.js";import{F as ce,X as ae}from"./chunk-RDHWNSDP.js";function mt(t){let e=process.env.HOME??"";return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}import{randomBytes as lt}from"crypto";function J(t,e){let r=Math.min(t.length,e.length),o=0,n=0,c=0;for(let s=0;s<r;s++)o+=t[s]*e[s],n+=t[s]*t[s],c+=e[s]*e[s];return n===0||c===0?0:o/(Math.sqrt(n)*Math.sqrt(c))}function Z(t,e,r){return r*t+(1-r)*e}var ee=.7;var je=["get_node","get_edges","find_by_provenance","match_by_type","stale_nodes","search_similar","search_similar_batch","history"],Pe=["source_read","source_grep","source_list"],Ue=[...je,...Pe],ke=50,be=200,te=10,xe=50,_e=20,Ve=200,He=50;function P(t,e,r){let o=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):e;return Math.max(1,Math.min(o,r))}function M(t,e){let r=t[e];if(typeof r!="string"||r.length===0)throw new k(`param "${e}" must be a non-empty string`);return r}function $(t,e){let r=t[e];if(r==null)return null;if(typeof r!="string")throw new k(`param "${e}" must be a string when present`);return r}var k=class extends Error{},ye=24,Qe=10,ze=10;function Ke(t){let e=t.cursor;if(e==null)return 0;if(typeof e=="string"&&/^\d+$/.test(e))return Number.parseInt(e,10);throw new k(`BAD_CURSOR: cursor ${JSON.stringify(e)} is not a cursor this store minted`)}function ve(t,e){let r=e.fields;if(!Array.isArray(r)||r.length===0)return t;let o=new Set(r.filter(n=>typeof n=="string"));return t.map(n=>Object.fromEntries(Object.entries(n).filter(([c])=>o.has(c))))}function ne(t,e,r=ke,o=be){let n=Ke(e),c=P(e.limit,r,o),s=t.slice(n,n+c),u=n+s.length<t.length;return{rows:ve(s,e),truncated:u,next_cursor:u?String(n+s.length):null}}var We=t=>t.cursor!=null||t.fields!=null;function U(t,e,r=ke){let o=ne(t,e,r);return We(e)||o.truncated?{rows:o.rows,truncated:o.truncated,next_cursor:o.next_cursor}:o.rows}function re(t,e){let r=t.getNode(e);return r?{cid:e,label:r.label,content:r.content,trust:t.trust.get(e)??null,freshness:t.stale(e)}:null}function we(t){return new Set(t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").split(" ").filter(Boolean))}function V(t,...e){let r=we(t);if(r.size===0)return 0;let o=t.trim().toLowerCase(),n=0;for(let c of e){let s=we(c);if(s.size===0)continue;let u=0;for(let l of r)s.has(l)&&u++;let f=r.size+s.size-u,d=f===0?0:u/f;o&&c.toLowerCase().includes(o)&&(d=Math.max(d,.9)),n=Math.max(n,d)}return n}function Xe(t,e){let r=M(e,"cid"),o=$(e,"type"),n=$(e,"direction")??"both";if(!["out","in","both"].includes(n))throw new k('param "direction" must be out|in|both');let c=[];(n==="out"||n==="both")&&c.push(...t.edgesFrom(r)),(n==="in"||n==="both")&&c.push(...t.edgesInto(r));let s=c.filter(u=>o==null||u.type===o);return U(s,e)}function qe(t,e){let r=M(e,"source_id"),o=t.heads.get(r)??null,n=[];for(let c of t.nodeLabel.keys()){let s=t.derivesInto(c).filter(f=>f.props.source_id===r).map(f=>({source_cid:f.props.source_cid,anchor:f.props.anchor??null}));if(s.length===0)continue;let u=re(t,c);u&&n.push({...u,pins:s,pinned_to_head:o!=null&&s.some(f=>f.source_cid===o)})}return U(n,e,be)}function Ye(t,e){let r=M(e,"label"),o=$(e,"trust"),n=$(e,"freshness"),c=[];for(let{cid:s}of t.byLabel(r)){let u=re(t,s);u&&(o!=null&&u.trust!==o||n!=null&&u.freshness!==n||c.push(u))}return U(c,e)}function Je(t,e={}){let r=$(e,"label"),o=t.staleList().map(({cid:n,state:c})=>{let s=t.getNode(n);return{cid:n,state:c,label:s?.label??null,title:s?.content.title??null}}).filter(n=>r==null||n.label===r);return U(o,e)}function Ze(t,e,r){let o=e.extracted,n=$(e,"kind"),c=[];for(let d of[...t.heads.keys()].sort()){let l=t.heads.get(d);if(typeof l!="string")continue;let h=t.mediaOf(l).format;if(n!=null&&h!==n)continue;let p=t.extractedSourceCids.has(l);if(typeof o=="boolean"&&p!==o)continue;let S=0;if(h!=="image"){let b=L(r,t,l);b&&(S=b.toString("utf8").replace(/\n$/,"").split(`
2
+ import{a as he}from"./chunk-WVHMPIDQ.js";import{a as pe}from"./chunk-5B2NEYHF.js";import{b as ue,c as de,d as q,e as Y}from"./chunk-MMLYJDXO.js";import{d as ge,e as me}from"./chunk-AXTPNZPX.js";import{d as fe}from"./chunk-BZAGVBCX.js";import{a as L}from"./chunk-KDNNMU7Q.js";import{a as le}from"./chunk-EYVHPJLK.js";import{z as I}from"./chunk-IICT4VOU.js";import{F as ce,X as ae}from"./chunk-RDHWNSDP.js";function mt(t){let e=process.env.HOME??"";return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}import{randomBytes as lt}from"crypto";function J(t,e){let r=Math.min(t.length,e.length),o=0,n=0,c=0;for(let s=0;s<r;s++)o+=t[s]*e[s],n+=t[s]*t[s],c+=e[s]*e[s];return n===0||c===0?0:o/(Math.sqrt(n)*Math.sqrt(c))}function Z(t,e,r){return r*t+(1-r)*e}var ee=.7;var je=["get_node","get_edges","find_by_provenance","match_by_type","stale_nodes","search_similar","search_similar_batch","history"],Pe=["source_read","source_grep","source_list"],Ue=[...je,...Pe],ke=50,be=200,te=10,xe=50,_e=20,Ve=200,He=50;function P(t,e,r){let o=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):e;return Math.max(1,Math.min(o,r))}function M(t,e){let r=t[e];if(typeof r!="string"||r.length===0)throw new k(`param "${e}" must be a non-empty string`);return r}function $(t,e){let r=t[e];if(r==null)return null;if(typeof r!="string")throw new k(`param "${e}" must be a string when present`);return r}var k=class extends Error{},ye=24,Qe=10,ze=10;function Ke(t){let e=t.cursor;if(e==null)return 0;if(typeof e=="string"&&/^\d+$/.test(e))return Number.parseInt(e,10);throw new k(`BAD_CURSOR: cursor ${JSON.stringify(e)} is not a cursor this store minted`)}function ve(t,e){let r=e.fields;if(!Array.isArray(r)||r.length===0)return t;let o=new Set(r.filter(n=>typeof n=="string"));return t.map(n=>Object.fromEntries(Object.entries(n).filter(([c])=>o.has(c))))}function ne(t,e,r=ke,o=be){let n=Ke(e),c=P(e.limit,r,o),s=t.slice(n,n+c),u=n+s.length<t.length;return{rows:ve(s,e),truncated:u,next_cursor:u?String(n+s.length):null}}var We=t=>t.cursor!=null||t.fields!=null;function U(t,e,r=ke){let o=ne(t,e,r);return We(e)||o.truncated?{rows:o.rows,truncated:o.truncated,next_cursor:o.next_cursor}:o.rows}function re(t,e){let r=t.getNode(e);return r?{cid:e,label:r.label,content:r.content,trust:t.trust.get(e)??null,freshness:t.stale(e)}:null}function we(t){return new Set(t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").split(" ").filter(Boolean))}function V(t,...e){let r=we(t);if(r.size===0)return 0;let o=t.trim().toLowerCase(),n=0;for(let c of e){let s=we(c);if(s.size===0)continue;let u=0;for(let l of r)s.has(l)&&u++;let f=r.size+s.size-u,d=f===0?0:u/f;o&&c.toLowerCase().includes(o)&&(d=Math.max(d,.9)),n=Math.max(n,d)}return n}function Xe(t,e){let r=M(e,"cid"),o=$(e,"type"),n=$(e,"direction")??"both";if(!["out","in","both"].includes(n))throw new k('param "direction" must be out|in|both');let c=[];(n==="out"||n==="both")&&c.push(...t.edgesFrom(r)),(n==="in"||n==="both")&&c.push(...t.edgesInto(r));let s=c.filter(u=>o==null||u.type===o);return U(s,e)}function qe(t,e){let r=M(e,"source_id"),o=t.heads.get(r)??null,n=[];for(let c of t.nodeLabel.keys()){let s=t.derivesInto(c).filter(f=>f.props.source_id===r).map(f=>({source_cid:f.props.source_cid,anchor:f.props.anchor??null}));if(s.length===0)continue;let u=re(t,c);u&&n.push({...u,pins:s,pinned_to_head:o!=null&&s.some(f=>f.source_cid===o)})}return U(n,e,be)}function Ye(t,e){let r=M(e,"label"),o=$(e,"trust"),n=$(e,"freshness"),c=[];for(let{cid:s}of t.byLabel(r)){let u=re(t,s);u&&(o!=null&&u.trust!==o||n!=null&&u.freshness!==n||c.push(u))}return U(c,e)}function Je(t,e={}){let r=$(e,"label"),o=t.staleList().map(({cid:n,state:c})=>{let s=t.getNode(n);return{cid:n,state:c,label:s?.label??null,title:s?.content.title??null}}).filter(n=>r==null||n.label===r);return U(o,e)}function Ze(t,e,r){let o=e.extracted,n=$(e,"kind"),c=[];for(let d of[...t.heads.keys()].sort()){let l=t.heads.get(d);if(typeof l!="string")continue;let h=t.mediaOf(l).format;if(n!=null&&h!==n)continue;let p=t.extractedSourceCids.has(l);if(typeof o=="boolean"&&p!==o)continue;let S=0;if(h!=="image"){let b=L(r,t,l);b&&(S=b.toString("utf8").replace(/\n$/,"").split(`
3
3
  `).length)}let _=t.extractionCompleteness.get(d);c.push({source_id:d,kind:h,lines:S,head_cid:l,extracted:p,last_extract_at:_?.at??null,extractor_version:_?.extractor_version??null})}let{rows:s,truncated:u,next_cursor:f}=ne(c,e);return{sources:s,truncated:u,next_cursor:f}}function et(t,e,r){let o=M(e,"ref"),n=t.resolve(o);if(!n)throw new k(`UNKNOWN_REF: ${o} names nothing in the graph`);let c=n.tip,s=new Map;for(let[m,w]of t.superseded)typeof w=="string"&&w!==m&&s.set(w,[...s.get(w)??[],m]);let u=[],f=[c],d=new Set;for(;f.length>0;){let m=f.pop();d.has(m)||(d.add(m),u.push(m),f.push(...s.get(m)??[]))}let{records:l}=ce(r),g=new Map,h=new Map;for(let m of l){for(let w of m.nodes)g.has(w.cid)||g.set(w.cid,m.ts);for(let w of m.supersessions)w.kind==="node"&&h.set(w.old,{by_cid:w.new,reason:w.reason})}let p=u.map(m=>({cid:m,minted_at:g.get(m)??null,superseded_by:h.get(m)?.by_cid??null,reason:h.get(m)?.reason??null,change_note:null})),{rows:S,truncated:_,next_cursor:b}=ne(p,e,ze);return{root_logical_id:t.displayNameOf(c),live_tip:t.superseded.has(c)?null:c,truncated:_,next_cursor:b,chain:S}}function Se(t){let e=t.queries;if(!Array.isArray(e)||e.length<1||e.length>ye)throw new k(`param "queries" must be 1..${ye} entries`);return e.map((r,o)=>{if(typeof r!="object"||r===null)throw new k(`queries[${o}] must be an object`);let n=r;if(typeof n.qid!="string"||n.qid.length===0)throw new k(`queries[${o}].qid must be a non-empty string`);if(typeof n.text!="string"||n.text.length===0)throw new k(`queries[${o}].text must be a non-empty string`);return{qid:n.qid,text:n.text,topK:P(n.top_k,te,Qe)}})}function Ae(t){let e=[];for(let{cid:r,content:o}of t.byLabel("usecase"))t.superseded.has(r)||e.push({cid:r,title:String(o.title??""),summary:String(o.summary??""),description:String(o.description??"")});return e}function Re(t,e,r){let o=Ae(t);return e.map(n=>{let c=[];for(let s of o){let u=r(n,s);u<=0||c.push({cid:s.cid,logical_id:t.displayNameOf(s.cid),title:s.title,score:Math.round(u*1e3)/1e3,trust:t.trust.get(s.cid)??null,superseded:!1})}return c.sort((s,u)=>u.score-s.score||s.cid.localeCompare(u.cid)),{qid:n.qid,truncated:c.length>n.topK,matches:c.slice(0,n.topK)}})}function Ee(t,e){let r=Se(e);return{results:Re(t,r,(o,n)=>V(o.text,n.title,n.summary,n.description)),scorer:"lexical_fallback"}}function tt(t,e){let r=M(e,"text"),o=$(e,"label")??"usecase",n=P(e.k,te,xe),c=[];for(let{cid:s,content:u}of t.byLabel(o)){let f=String(u.title??""),d=String(u.summary??""),l=V(r,f,d);l<=0||c.push({cid:s,title:f,summary:d,score:Math.round(l*1e3)/1e3,trust:t.trust.get(s)??null,freshness:t.stale(s)})}return c.sort((s,u)=>u.score-s.score||s.cid.localeCompare(u.cid)),c.slice(0,n)}function De(t,e,r){let o=t.heads.get(r);if(typeof o!="string"){let c=[...t.heads.keys()].sort().join(", ");throw new k(`unknown source_id "${r}" \u2014 known: ${c||"(none)"}`)}if(t.mediaOf(o).format==="image")throw new k(`source "${r}" is an image \u2014 no line window (cite img#whole)`);let n=L(e,t,o);if(n==null)throw new k(`source "${r}" blob is missing from the store`);return{head:o,lines:n.toString("utf8").replace(/\n$/,"").split(`
4
4
  `)}}function nt(t,e,r){return t.slice(e-1,r).map((o,n)=>`${String(e+n).padStart(4,"0")}| ${o}`).join(`
5
5
  `)}function rt(t,e,r){let o=M(e,"source_id"),n=$(e,"anchor"),c=e.line_range;if(n!=null&&c!=null)throw new k("give anchor OR line_range, not both");let{head:s,lines:u}=De(t,r,o),f=u.length,d,l;if(n!=null){let g=/^L(\d+)-L(\d+)$/.exec(n);if(!g)throw new k(`anchor "${n}" is not L<a>-L<b>`);let h=Number(g[1]),p=Number(g[2]);if(h<1||p<h||p>f)throw new k(`anchor "${n}" does not resolve (source has ${f} lines)`);d=Math.max(1,h-_e),l=Math.min(f,p+_e)}else if(c!=null){if(!Array.isArray(c)||c.length!==2||!c.every(p=>Number.isInteger(p)))throw new k('param "line_range" must be [from_line, to_line]');let[g,h]=c;if(g<1||h<g)throw new k('param "line_range" must be 1-based with from \u2264 to');if(g>f)throw new k(`line_range starts past the end (source has ${f} lines)`);d=g,l=Math.min(h,f)}else d=1,l=f;return l=Math.min(l,d+Ve-1),{window:nt(u,d,l),from_line:d,to_line:l,source_cid:s,total_lines:f}}function st(t,e,r){let o=M(e,"pattern"),n=$(e,"source_id"),c;try{c=new RegExp(o,"u")}catch(d){throw new k(`invalid pattern: ${d instanceof Error?d.message:String(d)}`)}let s=n!=null?[n]:[...t.heads.keys()].sort(),u=[],f=!1;e:for(let d of s){if(n==null){let g=t.heads.get(d);if(typeof g!="string"||t.mediaOf(g).format==="image")continue}let{lines:l}=De(t,r,d);for(let g=0;g<l.length;g++)if(c.test(l[g])){if(u.length>=He){f=!0;break e}u.push({source_id:d,line:g+1,text:l[g]})}}return{matches:u,truncated:f}}function ot(t,e,r,o){try{switch(e){case"get_node":{let n=re(t,M(r,"cid"));return n==null?{ok:!0,result:null}:{ok:!0,result:ve([n],r)[0]}}case"get_edges":return{ok:!0,result:Xe(t,r)};case"find_by_provenance":return{ok:!0,result:qe(t,r)};case"match_by_type":return{ok:!0,result:Ye(t,r)};case"stale_nodes":return{ok:!0,result:Je(t,r)};case"search_similar":return{ok:!0,result:tt(t,r)};case"search_similar_batch":return{ok:!0,result:Ee(t,r)};case"history":{if(o==null)throw new k("history unavailable (no context store)");return{ok:!0,result:et(t,r,o)}}case"source_list":{if(o==null)throw new k("source roster unavailable (no context store)");return{ok:!0,result:Ze(t,r,o)}}case"source_read":case"source_grep":{if(o==null)throw new k("source text unavailable (no context store)");return{ok:!0,result:(e==="source_read"?rt:st)(t,r,o)}}default:return{ok:!1,error:`unknown method: ${e} \u2014 available: ${Ue.join(", ")}`}}}catch(n){return n instanceof k?{ok:!1,error:`${e}: ${n.message}`}:{ok:!1,error:`${e}: graph read failed: ${n instanceof Error?n.message:String(n)}`}}}var j="assurance.sim";function it(t){return[t.title,t.summary,t.description].filter(Boolean).join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as u,b as x}from"./chunk-5X7JIGG7.js";import{y as m}from"./chunk-PHR2OSWD.js";import{a as f}from"./chunk-HCBYKLMW.js";import{a as r,b as i}from"./chunk-C44QQJR4.js";import{e as n}from"./chunk-UR6MHSHU.js";var e=n(f(),1);function C({title:B,titleColor:c,borderColor:d,variant:p,rows:s,footer:t,labelWidth:l=14,marginBottom:b=1}){return(0,e.jsxs)(u,{title:B,titleColor:c,borderColor:d,variant:p,marginBottom:b,children:[s.map((o,a)=>typeof o.value=="string"?(0,e.jsx)(x,{label:o.label,value:o.value,valueColor:o.valueColor,labelWidth:l},`${o.label}-${a}`):(0,e.jsxs)(r,{children:[(0,e.jsx)(r,{width:l,children:(0,e.jsx)(i,{color:m.dim,children:o.label})}),o.value]},`${o.label}-${a}`)),t&&(0,e.jsx)(r,{marginTop:1,children:t})]})}export{C as a};
2
+ import{a as u,b as x}from"./chunk-4R5U7CHE.js";import{y as m}from"./chunk-UQ6A52ML.js";import{a as f}from"./chunk-HCBYKLMW.js";import{a as r,b as i}from"./chunk-C44QQJR4.js";import{e as n}from"./chunk-UR6MHSHU.js";var e=n(f(),1);function C({title:B,titleColor:c,borderColor:d,variant:p,rows:s,footer:t,labelWidth:l=14,marginBottom:b=1}){return(0,e.jsxs)(u,{title:B,titleColor:c,borderColor:d,variant:p,marginBottom:b,children:[s.map((o,a)=>typeof o.value=="string"?(0,e.jsx)(x,{label:o.label,value:o.value,valueColor:o.valueColor,labelWidth:l},`${o.label}-${a}`):(0,e.jsxs)(r,{children:[(0,e.jsx)(r,{width:l,children:(0,e.jsx)(i,{color:m.dim,children:o.label})}),o.value]},`${o.label}-${a}`)),t&&(0,e.jsx)(r,{marginTop:1,children:t})]})}export{C as a};
@@ -1,17 +1,17 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as we}from"./chunk-YKTYVJBN.js";import{b as he,c as ye,d as be,e as Ee,f as _e,p as T}from"./chunk-7N6OCHPC.js";import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-VVOKM2VO.js";import{z as j}from"./chunk-IICT4VOU.js";import{g as N}from"./chunk-RDHWNSDP.js";import{x as ge}from"./chunk-PHR2OSWD.js";var A="https://integrations.lambdatest.com",E=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function ft(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${ge[n].shareApiBaseUrl}/lis/api/v1`}function gt(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 k(t){let n=t.split(`
2
+ import{a as we}from"./chunk-YKTYVJBN.js";import{b as he,c as ye,d as be,e as Ee,f as _e,p as T}from"./chunk-7N6OCHPC.js";import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-VVOKM2VO.js";import{z as j}from"./chunk-IICT4VOU.js";import{g as N}from"./chunk-RDHWNSDP.js";import{x as ge}from"./chunk-UQ6A52ML.js";var A="https://integrations.lambdatest.com",E=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function ft(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${ge[n].shareApiBaseUrl}/lis/api/v1`}function gt(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 k(t){let n=t.split(`
3
3
  `,1)[0].replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return n.length>200?`${n.slice(0,200)}\u2026`:n}function ht(t,n,e="the issue"){return t===401||t===403?new E("LIS_AUTH","credentials rejected \u2014 run `kane-cli login` and retry"):t>=500?new E("LIS_UNAVAILABLE",`the integrations service returned an error (HTTP ${t}) \u2014 retry later`):new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${e}: ${k(n)||`HTTP ${t}`}`)}function C(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{throw new E("LIS_UNAVAILABLE","the integrations service returned a malformed response \u2014 retry later")}}function ce(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{return{}}}function Le(t){return ce(t).code}function S(t,n="the issue",e="Atlassian"){let r=ce(t),s=e==="Atlassian"?"Confluence":e;switch(r.code){case"TOKEN_EXPIRED":return new E("LIS_SETUP",`your ${e} connection needs a resync \u2014 reconnect at ${A} and retry`);case"NOT_INSTALLED":return new E("LIS_SETUP",`no ${e} connection for this account \u2014 create one at ${A} and retry`);case"SCOPE_MISSING":return new E("LIS_SETUP",`the connection has no ${s} access \u2014 reconnect with ${s} at ${A} and retry`);case"FORBIDDEN":return new E("LIS_FORBIDDEN",`you don't have access to ${n}`);case"NOT_FOUND":return new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${n}: ${k(r.message??"")||"not found"}`);case"PAYLOAD_TOO_LARGE":return new E("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");case"INVALID_PAYLOAD":return new E("LIS_UNAVAILABLE",`the integrations service rejected the request (${k(r.message??"")||"invalid payload"}) \u2014 retry later`);case"NOT_SUPPORTED":return new E("LIS_UNAVAILABLE","the integrations service does not support this operation yet");case"UPSTREAM_ERROR":case"UPSTREAM_TIMEOUT":return new E("LIS_UNAVAILABLE",`${e} is not responding through the integrations service \u2014 retry later`);default:return ht(t.status,r.message??"",n)}}var yt=3e4,bt=5;async function $(t,n,e){let r=e.env??process.env,s=e.fetchImpl??fetch;for(let o=0;;o++){let l=new AbortController,u=setTimeout(()=>l.abort(),yt);try{let i=await s(`${ft(r)}${t}`,{...n,headers:{"content-type":"application/json",...gt(e),...n.headers??{}},signal:l.signal}),c=await Promise.race([i.arrayBuffer(),new Promise((d,p)=>{l.signal.addEventListener("abort",()=>p(new DOMException("aborted","AbortError")),{once:!0})})]),a={status:i.status,ok:i.ok,headers:i.headers,bytes:Buffer.from(c)};if(a.status===429){if(o>0)throw new E("LIS_RATE_LIMITED","the integrations service is busy \u2014 try again in a moment");let d=ce(a).data?.retry_after_sec,p=Math.min(Math.max(typeof d=="number"&&Number.isFinite(d)?d:1,0),bt);clearTimeout(u),await new Promise(b=>setTimeout(b,p*1e3));continue}return a}catch(i){throw i instanceof E?i:l.signal.aborted?new E("LIS_UNAVAILABLE","the integrations service did not respond within 30 seconds \u2014 retry later"):new E("LIS_UNAVAILABLE",`could not reach the integrations service (${k(i instanceof Error?i.message:String(i))}) \u2014 check your connection and retry`)}finally{clearTimeout(u)}}}function V(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 H(t={}){let n=await $("/jira/info",{method:"GET"},t);if(!n.ok)throw S(n);let e=C(n),r=(e.data?.SELECTED_PROJECTS??[]).map(s=>s?.key).filter(s=>typeof s=="string"&&s.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 z(t,n={}){let e=await $("/jira/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"jira",issueKey:t})},n);if(!e.ok)throw S(e);let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Ie=100,Et=5e3,_t=60;async function X(t,n={}){let e=[],r=new Set,s=null,o=0;for(let l=0;;l++){if(l>=_t)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let u=await $("/jira/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Ie,cursor:s,start_at:o,order_by:"created",fetch_all:!1})},n);if(!u.ok)throw S(u,"the issue's comments");let i=C(u);if(i.type==="error"||!i.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(i.message??"")||"unavailable"}`);for(let w of i.data.comments??[]){let g=String(w.id);r.has(g)||(r.add(g),e.push(w))}let c=i.data.pagination;if(!c?.has_more)return e;if(e.length>=Et)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let a=c.next_cursor??null,d=c.next_start_at!=null,p=d?c.next_start_at:o+Ie;if(!(a!=null&&a!==s||a==null&&d&&p!==o))throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=a,o=p}}async function Z(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok){if(Le(e)===void 0){if(e.status===413)throw new E("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");if(e.status===404)throw new E("JIRA_NOT_CONNECTED",`Jira is not connected for this account \u2014 connect it at ${A} and retry`)}throw S(e,`attachment ${t}`)}return V(e)}var q="kane.source.jira/2";function Ae(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(Ae).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 ve(t,n,e){let r=[],s={},o=t.additional_fields??{};for(let a of Object.keys(o).sort()){let d=Ae(o[a]);if(d===null){r.push(`field "${a}" has no stable text form \u2014 dropped from the envelope`);continue}s[a]=d}let l=[...t.attachments??[]].map(a=>({id:String(a.id),filename:a.filename??"",media_type:a.mime_type??"application/octet-stream",size:a.size??0})).sort((a,d)=>{let p=Number(a.id),b=Number(d.id);return Number.isFinite(p)&&Number.isFinite(b)?p-b:a.id<d.id?-1:a.id>d.id?1:0}),u=e.map(a=>({id:String(a.id),author:a.author?.display_name??"",body:a.body??"",created:a.created??""})).sort((a,d)=>{if(a.created!==d.created)return a.created<d.created?-1:1;let p=Number(a.id),b=Number(d.id);return Number.isFinite(p)&&Number.isFinite(b)&&p!==b?p-b:a.id<d.id?-1:a.id>d.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:q,site:n,project:i.slice(0,i.lastIndexOf("-")),issue:{id:t.id,key:i},content:{summary:t.summary??"",description:t.description??"",fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(c),"utf8"),envelope:c,warnings:r}}var Se=64,wt=16,Lt=6e6,It=5e7,At=12e6,vt={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"},St=new Set(["png","jpeg","webp"]);function $e(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!==q)throw new Error(`JIRA_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${q}`);let r=[],s=new Map,o=[],l=0,u=new Map,i=[];for(let d=0;d<e.attachments.length;d++){let p=e.attachments[d],b=`i${d+1}`,w=`attachment:${p.filename}`,g=v=>`[img#${b}] ${p.filename} (${p.media_type}, ${p.size} bytes${v?"":" \u2014 not delivered"})`,h=(v,R,x)=>{r.push({ref:b,loc:w,media_type:v,...x?.blob?{blob:x.blob}:{},...x?.appearance?{appearance:x.appearance}:{},delivery:R,...x?.duplicate_of?{duplicate_of:x.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),i.push(g(!1));continue}let _;try{_=await t.fetchAttachment(p.id)}catch{h(p.media_type,"external-image-not-fetched"),i.push(g(!1));continue}let y=_.bytes,m=J(y),f=vt[m.format],I=B(y);if(s.set(I,y),!St.has(m.format)){let v=m.format==="gif"||m.format==="bmp"||m.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(f,v,{blob:I}),i.push(g(!1));continue}if(m.width===void 0||m.height===void 0||m.width*m.height>It){h(f,"undecodable",{blob:I}),i.push(g(!1));continue}let L;if(m.format==="png"||m.format==="jpeg"){let v=F(y,m.format);if(v===null){h(f,"undecodable",{blob:I}),i.push(g(!1));continue}L=M(v.data,{width:v.width,height:v.height,channels:v.channels})}if(m.width<Se||m.height<Se){h(f,"below-dimension-floor",{blob:I,appearance:L}),i.push(g(!1));continue}let O=u.get(I);if(O!==void 0){h(f,"duplicate",{blob:I,appearance:L,duplicate_of:O}),i.push(g(!1));continue}if(y.byteLength>Lt){h(f,"image-too-large",{blob:I,appearance:L}),i.push(g(!1));continue}if(l+y.byteLength>At){h(f,"vision-byte-budget-reached",{blob:I,appearance:L}),i.push(g(!1));continue}if(o.length>=wt){h(f,"image-cap-reached",{blob:I,appearance:L}),i.push(g(!1));continue}u.set(I,b),l+=y.byteLength,o.push(b),h(f,"selected",{blob:I,appearance:L}),i.push(g(!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 a=Object.keys(e.content.fields);return a.length>0&&c.push("","--- fields ---",...a.map(d=>`${d}: ${e.content.fields[d]}`)),i.length>0&&c.push("","--- attachments ---",...i),e.comments.length>0&&(c.push("","--- comments ---"),e.comments.forEach((d,p)=>{p>0&&c.push(""),c.push(`[${p+1}] ${d.author} \xB7 ${d.created}`,...d.body.split(`
5
5
  `))})),{projection:c.join(`
6
6
  `)+`
7
- `,inventory:r,blobs:s,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var $t=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function Q(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 s=e[r+1];return $t.test(s)?{site:n.hostname,issueKey:s.toUpperCase()}:null}function ee(t,n){let e=j(t),r=e.heads.get(n);return r==null?null:Ce(t,e,r)}function te(t,n){let r=ee(t,n)?.site;return typeof r=="string"&&r.length>0?r:null}function ke(t,n,e,r){let s=j(t);for(let[o,l]of s.heads){if(l==null||s.mediaOf(l).format!==n)continue;let u=Ce(t,s,l);if(u===null)continue;let i=u;for(let c of e){if(i===null||typeof i!="object"){i=void 0;break}i=i[c]}if(i===r)return o}return null}function Ce(t,n,e){let r=n.getNode(e)?.content?.blob;if(typeof r!="string")return null;let s=W(t,r);if(s===null)return null;try{let o=JSON.parse(s.toString("utf8"));return o!==null&&typeof o=="object"?o:null}catch{return null}}var Re={jira:"a jira issue source",confluence:"a confluence page source",linear:"a linear issue source","linear-doc":"a linear document source",web:"a web page source"};function P(t,n,e){let r=j(t),s=r.heads.get(n);if(s==null)return null;let o=r.mediaOf(s).format;if(o===e)return null;let l=Re[o]??`${o} content`;return`source '${n}' is already backed by ${l}, not ${Re[e]??e} \u2014 retire it first (kane-cli context retire ${n}) or ingest under a different id with --as`}async function Rt(t,n,e,r,s){let o=Q(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 l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X};try{let i={auth:await(s?.authEnv??(await import("./auth-D4BDPJPR.js")).resolveLisAuthEnv)(),env:process.env},c=await l.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} 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 ${A} and retry`),{code:1};let a=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(a))return(e.err??e.out)(`error: ${t}: project ${a} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${A}`),{code:1};let d=await l.jiraIssue(o.issueKey,i),p=await l.jiraComments(o.issueKey,i),b=o.site;if(d.host)try{b=new URL(d.host).hostname}catch{b=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:g}=ve(d,b,p),h=n??o.issueKey.toLowerCase();N(h);let _=P(r,h,"jira");if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let y=te(r,h);if(y!==null&&y!==b)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${y}, but this read serves ${b} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let m=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:f=>l.jiraAttachment(f,i)})}});e.out(U(e.isTTY,m,o.issueKey));for(let f of g)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: jira, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${kt(u instanceof Error?u.message:String(u))}`),{code:1})}}function kt(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 Oe={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>Q(t)!==null,ingest:Rt,sourceIdFor:t=>{let n=Q(t);return n?n.issueKey.toLowerCase():null}};async function Ne(t,n={}){let e=await $("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the page");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${k(r.message??"")||"page not found or not accessible"}`);return r.data}async function Te(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw S(e,"the page's attachment");return{bytes:V(e).bytes}}var ne="kane.source.confluence/1";function Pe(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,l)=>o.id<l.id?-1:o.id>l.id?1:0),s={schema:ne,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(s),"utf8"),envelope:s,warnings:[]}}var Ue=64,Ct=16,Ot=6e6,Nt=5e7,Tt=12e6,Pt={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"},Ut=new Set(["png","jpeg","webp"]);function xe(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!==ne)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${ne}`);let s=[],o=new Map,l=[],u=0,i=new Map,c=[];for(let d=0;d<r.attachments.length;d++){let p=r.attachments[d],b=`i${d+1}`,w=`attachment:${p.filename}`,g=R=>`[img#${b}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:b,loc:w,media_type:R,...D?.blob?{blob:D.blob}:{},...D?.appearance?{appearance:D.appearance}:{},delivery:x,...D?.duplicate_of?{duplicate_of:D.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),c.push(g(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let y;try{y=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let m=y.bytes,f=J(m),I=Pt[f.format],L=B(m);if(o.set(L,m),!Ut.has(f.format)){let R=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(g(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Nt){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}let O;if(f.format==="png"||f.format==="jpeg"){let R=F(m,f.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(f.width<Ue||f.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(g(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(g(!1));continue}if(m.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(g(!1));continue}if(u+m.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(g(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(g(!1));continue}i.set(L,b),u+=m.byteLength,l.push(b),h(I,"selected",{blob:L,appearance:O}),c.push(g(!0))}let a=[];return a.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&a.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&a.push("",...r.content.body.split(`
7
+ `,inventory:r,blobs:s,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var $t=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function Q(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 s=e[r+1];return $t.test(s)?{site:n.hostname,issueKey:s.toUpperCase()}:null}function ee(t,n){let e=j(t),r=e.heads.get(n);return r==null?null:Ce(t,e,r)}function te(t,n){let r=ee(t,n)?.site;return typeof r=="string"&&r.length>0?r:null}function ke(t,n,e,r){let s=j(t);for(let[o,l]of s.heads){if(l==null||s.mediaOf(l).format!==n)continue;let u=Ce(t,s,l);if(u===null)continue;let i=u;for(let c of e){if(i===null||typeof i!="object"){i=void 0;break}i=i[c]}if(i===r)return o}return null}function Ce(t,n,e){let r=n.getNode(e)?.content?.blob;if(typeof r!="string")return null;let s=W(t,r);if(s===null)return null;try{let o=JSON.parse(s.toString("utf8"));return o!==null&&typeof o=="object"?o:null}catch{return null}}var Re={jira:"a jira issue source",confluence:"a confluence page source",linear:"a linear issue source","linear-doc":"a linear document source",web:"a web page source"};function P(t,n,e){let r=j(t),s=r.heads.get(n);if(s==null)return null;let o=r.mediaOf(s).format;if(o===e)return null;let l=Re[o]??`${o} content`;return`source '${n}' is already backed by ${l}, not ${Re[e]??e} \u2014 retire it first (kane-cli context retire ${n}) or ingest under a different id with --as`}async function Rt(t,n,e,r,s){let o=Q(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 l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X};try{let i={auth:await(s?.authEnv??(await import("./auth-6PKLNV6Z.js")).resolveLisAuthEnv)(),env:process.env},c=await l.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} 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 ${A} and retry`),{code:1};let a=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(a))return(e.err??e.out)(`error: ${t}: project ${a} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${A}`),{code:1};let d=await l.jiraIssue(o.issueKey,i),p=await l.jiraComments(o.issueKey,i),b=o.site;if(d.host)try{b=new URL(d.host).hostname}catch{b=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:g}=ve(d,b,p),h=n??o.issueKey.toLowerCase();N(h);let _=P(r,h,"jira");if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let y=te(r,h);if(y!==null&&y!==b)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${y}, but this read serves ${b} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let m=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:f=>l.jiraAttachment(f,i)})}});e.out(U(e.isTTY,m,o.issueKey));for(let f of g)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: jira, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${kt(u instanceof Error?u.message:String(u))}`),{code:1})}}function kt(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 Oe={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>Q(t)!==null,ingest:Rt,sourceIdFor:t=>{let n=Q(t);return n?n.issueKey.toLowerCase():null}};async function Ne(t,n={}){let e=await $("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the page");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${k(r.message??"")||"page not found or not accessible"}`);return r.data}async function Te(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw S(e,"the page's attachment");return{bytes:V(e).bytes}}var ne="kane.source.confluence/1";function Pe(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,l)=>o.id<l.id?-1:o.id>l.id?1:0),s={schema:ne,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(s),"utf8"),envelope:s,warnings:[]}}var Ue=64,Ct=16,Ot=6e6,Nt=5e7,Tt=12e6,Pt={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"},Ut=new Set(["png","jpeg","webp"]);function xe(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!==ne)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${ne}`);let s=[],o=new Map,l=[],u=0,i=new Map,c=[];for(let d=0;d<r.attachments.length;d++){let p=r.attachments[d],b=`i${d+1}`,w=`attachment:${p.filename}`,g=R=>`[img#${b}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:b,loc:w,media_type:R,...D?.blob?{blob:D.blob}:{},...D?.appearance?{appearance:D.appearance}:{},delivery:x,...D?.duplicate_of?{duplicate_of:D.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),c.push(g(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let y;try{y=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let m=y.bytes,f=J(m),I=Pt[f.format],L=B(m);if(o.set(L,m),!Ut.has(f.format)){let R=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(g(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Nt){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}let O;if(f.format==="png"||f.format==="jpeg"){let R=F(m,f.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(f.width<Ue||f.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(g(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(g(!1));continue}if(m.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(g(!1));continue}if(u+m.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(g(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(g(!1));continue}i.set(L,b),u+=m.byteLength,l.push(b),h(I,"selected",{blob:L,appearance:O}),c.push(g(!0))}let a=[];return a.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&a.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&a.push("",...r.content.body.split(`
8
8
  `)),c.length>0&&a.push("","--- attachments ---",...c),{projection:a.join(`
9
9
  `)+`
10
- `,inventory:s,blobs:o,delivered:l,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var xt=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function re(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 s=e[r+2],o=e[r+4];return s===void 0||o===void 0||!xt.test(s)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:s,pageId:o}}async function Dt(t,n,e,r,s){let o=re(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 l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X},u=s?.confluence??{confluenceDocument:Ne,confluenceAttachment:Te};try{let c={auth:await(s?.authEnv??(await import("./auth-D4BDPJPR.js")).resolveLisAuthEnv)(),env:process.env},a=await l.jiraInfo(c);if(!a.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(a.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${A} and retry`),{code:1};let d=await u.confluenceDocument(o.pageId,c),p=o.site;if(d.url)try{p=new URL(d.url).hostname}catch{}let{bytes:b,warnings:w}=Pe(d,p),g=n??`page-${o.pageId}`;N(g);let h=P(r,g,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,g);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let y=Object.fromEntries((d.attachments??[]).filter(f=>typeof f.download=="string"&&f.download.length>0).map(f=>[String(f.id),f.download])),m=await T({contextDir:r,bytes:b,media:ye,sourceId:g,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:y,fetchAttachment:f=>u.confluenceAttachment(f.download,c)})}});e.out(U(e.isTTY,m,`${o.spaceKey}/${o.pageId}`));for(let f of w)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: confluence, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}catch(i){return i instanceof E?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${jt(i instanceof Error?i.message:String(i))}`),{code:1})}}function jt(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 De={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>re(t)!==null,ingest:Dt,sourceIdFor:t=>{let n=re(t);return n?`page-${n.pageId}`:null}};async function je(t={}){let n=await $("/linear-app/info",{method:"GET"},t);if(!n.ok)throw S(n,"the connection","Linear");let e=C(n);return{installed:e.data?.INSTALLED==="YES",capabilities:{issue:e.data?.capabilities?.issue===!0,comments:e.data?.capabilities?.comments===!0,document:e.data?.capabilities?.document===!0}}}async function Be(t,n={}){let e=await $("/linear-app/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"linear-app",issueKey:t})},n);if(!e.ok)throw S(e,"the issue","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Bt=100,Mt=5e3,Jt=60;async function Me(t,n={}){let e=[],r=new Set,s=null;for(let o=0;;o++){if(o>=Jt)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let l=await $("/linear-app/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Bt,...s===null?{}:{cursor:s},fetch_all:!1})},n);if(!l.ok)throw S(l,"the issue's comments","Linear");let u=C(l);if(u.type==="error"||!u.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(u.message??"")||"unavailable"}`);if(u.data.partial)throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 retry later");for(let a of u.data.comments??[]){if(typeof a.id!="string"||a.id==="")throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 a comment row has no comment id");r.has(a.id)||(r.add(a.id),e.push(a))}let i=u.data.pagination;if(!i?.has_more)return e;if(e.length>=Mt)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let c=i.next_cursor??null;if(c==null||c===s)throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=c}}async function Je(t,n={}){let e=await $("/linear-app/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the document","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the document: ${k(r.message??"")||"document not found or not accessible"}`);return r.data}async function Fe(t,n={}){let e=await $("/linear-app/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok)throw S(e,"the attachment","Linear");return{bytes:V(e).bytes}}var oe="kane.source.linear/1",ie="kane.source.linear-doc/1",Ft=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g;function G(t){return t.replace(Ft,n=>{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)})}function Ve(t,n){return t.id<n.id?-1:t.id>n.id?1:0}function Vt(t,n){return Ve(t,n)||(t.filename<n.filename?-1:t.filename>n.filename?1:0)||(t.url<n.url?-1:t.url>n.url?1:0)}function Ge(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this issue \u2014 the integrations service returned no issue id");let r=t.key;if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(r)){let c=String(r).replace(/[\u0000-\u001f\u007f-\u009f]/g,"").slice(0,80);throw new Error(`cannot build a stable identity for issue key "${c}" \u2014 expected a TEAM-NUMBER key`)}let s={},o=[...t.labels??[]].filter(c=>typeof c=="string").sort();o.length>0&&(s.labels=o.join(", ")),typeof t.priority=="string"&&t.priority!==""&&(s.priority=t.priority),typeof t.project=="string"&&t.project!==""&&(s.project=t.project),typeof t.status=="string"&&t.status!==""&&(s.status=t.status);let l=(t.attachments??[]).map(c=>({id:c.id!=null&&String(c.id)!==""?String(c.id):G(c.download??""),filename:c.filename??"",url:G(c.download??"")})).sort(Vt),u=n.map(c=>({id:String(c.id),author:c.author?.display_name??"",body:G(c.body??""),created:c.created??""})).sort((c,a)=>c.created!==a.created?c.created<a.created?-1:1:Ve(c,a)),i={schema:oe,site:e,team:r.slice(0,r.lastIndexOf("-")),issue:{uuid:t.id,key:r},content:{title:t.summary??"",description:G(t.description??""),fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(i),"utf8"),envelope:i,warnings:[]}}function Ye(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this document \u2014 the integrations service returned no document id");let r=(t.attachments??[]).map(o=>({url:G(o.download??String(o.id??"")),filename:o.filename??""})).sort((o,l)=>o.url<l.url?-1:o.url>l.url?1:0),s={schema:ie,site:n,document:{uuid:t.id,slug_id:e},project:{id:t.space?.key??""},title:t.title??"",content:{body:G(t.body??"")},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ke=64,Gt=16,Yt=6e6,Kt=5e7,Wt=12e6,se=64,We="https://uploads.linear.app/",Ht=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g,zt={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"},Xt=new Set(["png","jpeg","webp"]);async function He(t,n){let e=[],r=new Map,s=[],o=0,l=new Map,u=[];for(let i=0;i<t.length;i++){let c=t[i],a=`i${i+1}`,d=f=>`[img#${a}] ${c.label}${f?"":" \u2014 not delivered"}`,p=(f,I,L)=>{e.push({ref:a,loc:c.loc,media_type:f,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},b;try{b=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=b.bytes,g=J(w),h=zt[g.format],_=B(w);if(r.set(_,w),!Xt.has(g.format)){let f=g.format==="gif"||g.format==="bmp"||g.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,f,{blob:_}),u.push(d(!1));continue}if(g.width===void 0||g.height===void 0||g.width*g.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let y;if(g.format==="png"||g.format==="jpeg"){let f=F(w,g.format);if(f===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}y=M(f.data,{width:f.width,height:f.height,channels:f.channels})}if(g.width<Ke||g.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:y}),u.push(d(!1));continue}let m=l.get(_);if(m!==void 0){p(h,"duplicate",{blob:_,appearance:y,duplicate_of:m}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:y}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:y}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:y}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:y}),u.push(d(!0))}return{inventory:e,blobs:r,delivered:s,lines:u}}function Zt(t){let n=new Set,e=[];for(let r of t.match(Ht)??[])n.has(r)||(n.add(r),e.push(r));return e}function ze(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_ENVELOPE_SCHEMA: source bytes are not a kane linear envelope")}if(e.schema!==oe)throw new Error(`LINEAR_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${oe}`);let r=[],s=new Set;for(let a of Zt(e.content.description))s.add(a),r.push({url:a,label:a,loc:`body:${a}`});let o=[];for(let a of e.attachments)if(a.url.startsWith(We)){if(s.has(a.url)){if(a.filename!==""){let d=r.find(p=>p.url===a.url);d!==void 0&&d.label===d.url&&(d.label=a.filename)}continue}s.add(a.url),r.push({url:a.url,label:a.filename||a.url,loc:`attachment:${a.filename||a.url}`})}else a.url!==""&&o.push(`[${o.length+1}] ${a.filename||a.url} \u2014 ${a.url}`);let l=Math.max(0,r.length-se),u=await He(r.slice(0,se),t.fetchAttachment);l>0&&u.lines.push(`${l} more upload links not examined`);let i=[];i.push(`${e.issue.key} \xB7 ${e.site}`,`Title: ${e.content.title}`),e.content.description!==""&&i.push("",...e.content.description.split(`
10
+ `,inventory:s,blobs:o,delivered:l,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var xt=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function re(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 s=e[r+2],o=e[r+4];return s===void 0||o===void 0||!xt.test(s)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:s,pageId:o}}async function Dt(t,n,e,r,s){let o=re(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 l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X},u=s?.confluence??{confluenceDocument:Ne,confluenceAttachment:Te};try{let c={auth:await(s?.authEnv??(await import("./auth-6PKLNV6Z.js")).resolveLisAuthEnv)(),env:process.env},a=await l.jiraInfo(c);if(!a.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(a.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${A} and retry`),{code:1};let d=await u.confluenceDocument(o.pageId,c),p=o.site;if(d.url)try{p=new URL(d.url).hostname}catch{}let{bytes:b,warnings:w}=Pe(d,p),g=n??`page-${o.pageId}`;N(g);let h=P(r,g,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,g);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let y=Object.fromEntries((d.attachments??[]).filter(f=>typeof f.download=="string"&&f.download.length>0).map(f=>[String(f.id),f.download])),m=await T({contextDir:r,bytes:b,media:ye,sourceId:g,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:y,fetchAttachment:f=>u.confluenceAttachment(f.download,c)})}});e.out(U(e.isTTY,m,`${o.spaceKey}/${o.pageId}`));for(let f of w)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: confluence, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}catch(i){return i instanceof E?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${jt(i instanceof Error?i.message:String(i))}`),{code:1})}}function jt(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 De={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>re(t)!==null,ingest:Dt,sourceIdFor:t=>{let n=re(t);return n?`page-${n.pageId}`:null}};async function je(t={}){let n=await $("/linear-app/info",{method:"GET"},t);if(!n.ok)throw S(n,"the connection","Linear");let e=C(n);return{installed:e.data?.INSTALLED==="YES",capabilities:{issue:e.data?.capabilities?.issue===!0,comments:e.data?.capabilities?.comments===!0,document:e.data?.capabilities?.document===!0}}}async function Be(t,n={}){let e=await $("/linear-app/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"linear-app",issueKey:t})},n);if(!e.ok)throw S(e,"the issue","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Bt=100,Mt=5e3,Jt=60;async function Me(t,n={}){let e=[],r=new Set,s=null;for(let o=0;;o++){if(o>=Jt)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let l=await $("/linear-app/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Bt,...s===null?{}:{cursor:s},fetch_all:!1})},n);if(!l.ok)throw S(l,"the issue's comments","Linear");let u=C(l);if(u.type==="error"||!u.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(u.message??"")||"unavailable"}`);if(u.data.partial)throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 retry later");for(let a of u.data.comments??[]){if(typeof a.id!="string"||a.id==="")throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 a comment row has no comment id");r.has(a.id)||(r.add(a.id),e.push(a))}let i=u.data.pagination;if(!i?.has_more)return e;if(e.length>=Mt)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let c=i.next_cursor??null;if(c==null||c===s)throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=c}}async function Je(t,n={}){let e=await $("/linear-app/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the document","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the document: ${k(r.message??"")||"document not found or not accessible"}`);return r.data}async function Fe(t,n={}){let e=await $("/linear-app/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok)throw S(e,"the attachment","Linear");return{bytes:V(e).bytes}}var oe="kane.source.linear/1",ie="kane.source.linear-doc/1",Ft=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g;function G(t){return t.replace(Ft,n=>{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)})}function Ve(t,n){return t.id<n.id?-1:t.id>n.id?1:0}function Vt(t,n){return Ve(t,n)||(t.filename<n.filename?-1:t.filename>n.filename?1:0)||(t.url<n.url?-1:t.url>n.url?1:0)}function Ge(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this issue \u2014 the integrations service returned no issue id");let r=t.key;if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(r)){let c=String(r).replace(/[\u0000-\u001f\u007f-\u009f]/g,"").slice(0,80);throw new Error(`cannot build a stable identity for issue key "${c}" \u2014 expected a TEAM-NUMBER key`)}let s={},o=[...t.labels??[]].filter(c=>typeof c=="string").sort();o.length>0&&(s.labels=o.join(", ")),typeof t.priority=="string"&&t.priority!==""&&(s.priority=t.priority),typeof t.project=="string"&&t.project!==""&&(s.project=t.project),typeof t.status=="string"&&t.status!==""&&(s.status=t.status);let l=(t.attachments??[]).map(c=>({id:c.id!=null&&String(c.id)!==""?String(c.id):G(c.download??""),filename:c.filename??"",url:G(c.download??"")})).sort(Vt),u=n.map(c=>({id:String(c.id),author:c.author?.display_name??"",body:G(c.body??""),created:c.created??""})).sort((c,a)=>c.created!==a.created?c.created<a.created?-1:1:Ve(c,a)),i={schema:oe,site:e,team:r.slice(0,r.lastIndexOf("-")),issue:{uuid:t.id,key:r},content:{title:t.summary??"",description:G(t.description??""),fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(i),"utf8"),envelope:i,warnings:[]}}function Ye(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this document \u2014 the integrations service returned no document id");let r=(t.attachments??[]).map(o=>({url:G(o.download??String(o.id??"")),filename:o.filename??""})).sort((o,l)=>o.url<l.url?-1:o.url>l.url?1:0),s={schema:ie,site:n,document:{uuid:t.id,slug_id:e},project:{id:t.space?.key??""},title:t.title??"",content:{body:G(t.body??"")},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ke=64,Gt=16,Yt=6e6,Kt=5e7,Wt=12e6,se=64,We="https://uploads.linear.app/",Ht=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g,zt={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"},Xt=new Set(["png","jpeg","webp"]);async function He(t,n){let e=[],r=new Map,s=[],o=0,l=new Map,u=[];for(let i=0;i<t.length;i++){let c=t[i],a=`i${i+1}`,d=f=>`[img#${a}] ${c.label}${f?"":" \u2014 not delivered"}`,p=(f,I,L)=>{e.push({ref:a,loc:c.loc,media_type:f,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},b;try{b=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=b.bytes,g=J(w),h=zt[g.format],_=B(w);if(r.set(_,w),!Xt.has(g.format)){let f=g.format==="gif"||g.format==="bmp"||g.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,f,{blob:_}),u.push(d(!1));continue}if(g.width===void 0||g.height===void 0||g.width*g.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let y;if(g.format==="png"||g.format==="jpeg"){let f=F(w,g.format);if(f===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}y=M(f.data,{width:f.width,height:f.height,channels:f.channels})}if(g.width<Ke||g.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:y}),u.push(d(!1));continue}let m=l.get(_);if(m!==void 0){p(h,"duplicate",{blob:_,appearance:y,duplicate_of:m}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:y}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:y}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:y}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:y}),u.push(d(!0))}return{inventory:e,blobs:r,delivered:s,lines:u}}function Zt(t){let n=new Set,e=[];for(let r of t.match(Ht)??[])n.has(r)||(n.add(r),e.push(r));return e}function ze(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_ENVELOPE_SCHEMA: source bytes are not a kane linear envelope")}if(e.schema!==oe)throw new Error(`LINEAR_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${oe}`);let r=[],s=new Set;for(let a of Zt(e.content.description))s.add(a),r.push({url:a,label:a,loc:`body:${a}`});let o=[];for(let a of e.attachments)if(a.url.startsWith(We)){if(s.has(a.url)){if(a.filename!==""){let d=r.find(p=>p.url===a.url);d!==void 0&&d.label===d.url&&(d.label=a.filename)}continue}s.add(a.url),r.push({url:a.url,label:a.filename||a.url,loc:`attachment:${a.filename||a.url}`})}else a.url!==""&&o.push(`[${o.length+1}] ${a.filename||a.url} \u2014 ${a.url}`);let l=Math.max(0,r.length-se),u=await He(r.slice(0,se),t.fetchAttachment);l>0&&u.lines.push(`${l} more upload links not examined`);let i=[];i.push(`${e.issue.key} \xB7 ${e.site}`,`Title: ${e.content.title}`),e.content.description!==""&&i.push("",...e.content.description.split(`
11
11
  `));let c=Object.keys(e.content.fields);return c.length>0&&i.push("","--- fields ---",...c.map(a=>`${a}: ${e.content.fields[a]}`)),u.lines.length>0&&i.push("","--- images ---",...u.lines),o.length>0&&i.push("","--- links ---",...o),e.comments.length>0&&(i.push("","--- comments ---"),e.comments.forEach((a,d)=>{d>0&&i.push(""),i.push(`[${d+1}] ${a.author} \xB7 ${a.created}`,...a.body.split(`
12
12
  `))})),{projection:i.join(`
13
13
  `)+`
14
14
  `,inventory:u.inventory,blobs:u.blobs,delivered:u.delivered,converter:{name:"linear-convert",version:"1",policy:"v1"}}}}function Xe(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_DOC_ENVELOPE_SCHEMA: source bytes are not a kane linear document envelope")}if(e.schema!==ie)throw new Error(`LINEAR_DOC_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${ie}`);let r=new Set,s=[];for(let i of e.attachments)!i.url.startsWith(We)||r.has(i.url)||(r.add(i.url),s.push({url:i.url,label:i.filename||i.url,loc:`body:${i.url}`}));let o=Math.max(0,s.length-se),l=await He(s.slice(0,se),t.fetchAttachment);o>0&&l.lines.push(`${o} more upload links not examined`);let u=[];return u.push(`${e.title} \xB7 ${e.site}`),e.content.body!==""&&u.push("",...e.content.body.split(`
15
15
  `)),l.lines.length>0&&u.push("","--- images ---",...l.lines),{projection:u.join(`
16
16
  `)+`
17
- `,inventory:l.inventory,blobs:l.blobs,delivered:l.delivered,converter:{name:"linear-doc-convert",version:"1",policy:"v1"}}}}var qt=/^[A-Za-z][A-Za-z0-9]*-\d+$/,Qt=/-([0-9a-f]{12})$/;function ue(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname.toLowerCase()!=="linear.app"?null:n.pathname.split("/").filter(Boolean)}function Ze(t){let n=ue(t);return n===null||n.length<3?null:{workspace:n[0],segs:n}}function Y(t){let n=Ze(t);if(n===null||n.segs[1]!=="issue")return null;let e=n.segs[2];return qt.test(e)?{workspace:n.workspace,key:e}:null}function K(t){let n=Ze(t);if(n===null||n.segs[1]!=="document")return null;let e=n.segs[2].match(Qt);return e===null?null:{workspace:n.workspace,slugId:e[1]}}var en=new Set(["project","team","view","initiative","cycle","roadmap","inbox","triage","my-issues"]),qe=new Set(["docs","features","method","blog","customers","pricing","integrations","developers","changelog","about","careers","security","download","contact","now","switch","homepage"]);function le(t){let n=ue(t);return n===null||n.length<2||!en.has(n[1])||qe.has(n[0].toLowerCase())?null:{workspace:n[0],section:n[1]}}function de(t){let n=ue(t);return n===null||n.length<2||n[1]!=="issue"&&n[1]!=="document"||qe.has(n[0].toLowerCase())||Y(t)!==null||K(t)!==null?null:{workspace:n[0],section:n[1]}}function Qe(t){let n=Y(t);return n?n.key.toLowerCase():null}function et(t){let n=K(t);return n?`doc-${n.slugId}`:null}var tt={linearInfo:je,linearIssue:Be,linearComments:Me,linearDocument:Je,linearAttachment:Fe};function nt(t,n){if(t)try{let e=new URL(t).pathname.split("/").filter(Boolean)[0];if(e)return`linear.app/${e.toLowerCase()}`}catch{}return`linear.app/${n.toLowerCase()}`}function rt(t,n,e,r,s,o){let l=ee(t,r);if(l!==null&&typeof l.schema=="string"&&l.schema.startsWith(`kane.source.${n}/`)){let i=l;for(let c of e)i=i!==null&&typeof i=="object"?i[c]:void 0;if(typeof i=="string"&&i!==""&&i!==s)return`source '${r}' was ingested from a different ${o} that used this key \u2014 the key was recycled; retire it first (kane-cli context retire ${r}) or ingest under a different id with --as`}let u=ke(t,n,e,s);return u!==null&&u!==r?`this ${o} is already ingested as '${u}' (its key changed) \u2014 reconcile that source, or retire it to re-ingest under the new key`:null}function ot(t,n,e,r){let s=ee(t,e);if(s===null||typeof s.schema!="string"||!s.schema.startsWith(`kane.source.${n}/`))return null;let o=s.site;return typeof o!="string"||o.length===0||o===r?null:`source '${e}' was ingested from ${o}, but this read serves ${r} \u2014 retire it first (kane-cli context retire ${e}) or ingest under a different id with --as`}async function tn(t,n,e,r,s){let o=Y(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear issue URL (https://linear.app/<workspace>/issue/KEY-123)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-D4BDPJPR.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.issue===!1||c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issues or their comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearIssue(o.key,i),d=await l.linearComments(o.key,i),p=nt(a.host,o.workspace),{bytes:b,envelope:w,warnings:g}=Ge(a,d,p),h=n??o.key.toLowerCase();N(h);let _=rt(r,"linear",["issue","uuid"],h,w.issue.uuid,"issue")??P(r,h,"linear")??ot(r,"linear",h,p);if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let y=await T({contextDir:r,bytes:b,media:Ee,sourceId:h,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{linear:ze({fetchAttachment:m=>l.linearAttachment(m,i)})}});e.out(U(e.isTTY,y,w.issue.key));for(let m of g)e.out(`warning: ${m}`);for(let m of y.warnings??[])e.out(`warning: ${m}`);if(y.composite){let m=y.composite.delivered+y.composite.omitted;e.out(`${y.source_id}: linear, ${m} images, ${y.composite.delivered} delivered (${y.composite.omitted} omitted)`)}return{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid,...y.gitignore?{gitignore:y.gitignore}:{}}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"issue","Linear")}`),{code:1})}}async function nn(t,n,e,r,s){let o=K(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear document URL (https://linear.app/<workspace>/document/<slug>)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-D4BDPJPR.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read documents yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearDocument(o.slugId,i),d=nt(a.url,o.workspace),{bytes:p,envelope:b,warnings:w}=Ye(a,d,o.slugId),g=n??`doc-${o.slugId}`;N(g);let h=rt(r,"linear-doc",["document","uuid"],g,b.document.uuid,"document")??P(r,g,"linear-doc")??ot(r,"linear-doc",g,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:g,label:t,confirmSameSource:e.isTTY?y=>e.confirm(`identical content already ingested as ${y} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:y=>l.linearAttachment(y,i)})}});e.out(U(e.isTTY,_,b.title||`document ${o.slugId}`));for(let y of w)e.out(`warning: ${y}`);for(let y of _.warnings??[])e.out(`warning: ${y}`);if(_.composite){let y=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${y} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid,..._.gitignore?{gitignore:_.gitignore}:{}}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"document","Linear")}`),{code:1})}}function it(t,n,e){let r=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return r?`the ${n}'s content is too large to ingest (${r[1]}; the limit is ${r[2]}) \u2014 trim the ${n} in ${e} and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?`the ${n}'s text is too large to ingest \u2014 trim the ${n} in ${e} and retry`:t}var st={name:"linear",hint:"Linear issue URLs (https://linear.app/<workspace>/issue/KEY-123)",match:t=>Y(t)!==null,ingest:tn,sourceIdFor:Qe},at={name:"linear-doc",hint:"Linear document URLs (https://linear.app/<workspace>/document/<slug>)",match:t=>K(t)!==null,ingest:nn,sourceIdFor:et},ct={name:"linear-page",hint:"Linear issue or document URLs (other linear.app pages are not ingestable)",match:t=>le(t)!==null||de(t)!==null,ingest:async(t,n,e)=>{let r=le(t);if(r===null){let s=de(t);return s!==null?((e.err??e.out)(`error: ${t}: this Linear ${s.section} link is incomplete or malformed \u2014 use the full form (https://linear.app/${s.workspace}/issue/KEY-123 or https://linear.app/${s.workspace}/document/<slug>-<id>)`),{code:1}):((e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear workspace page`),{code:1})}return(e.err??e.out)(`error: ${t}: this Linear page can't be ingested \u2014 only issue and document URLs are supported; ingest the project's issues or documents individually (https://linear.app/${r.workspace}/issue/KEY-123)`),{code:1}},sourceIdFor:()=>null};var rn=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 ut(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,s=we(e),o={"Content-Type":"application/json"},l=await n.authEnv(),u=l.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=l.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;u?o.Authorization=`Basic ${u}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${s}/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 a;try{a=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let p=a.page;return p===void 0||typeof p.markdown!="string"||p.markdown===""||typeof p.final_url!="string"||p.final_url===""||typeof p.projection?.kind!="string"||typeof p.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:p}}let d=a.code;return typeof d=="string"&&rn.has(d)?{ok:!1,kind:d}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var pe="kane.source.web/1";function lt(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:pe,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var on=new Set(["markdown"]);function dt(){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!==pe)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!on.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 sn}from"crypto";function pt(t){return ae(t)!==null}function ae(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 me(t){let n=ae(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(/-+$/,""),s=sn("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${s}`}function an(t,n){let e=j(t),r=e.heads.get(n);if(r==null)return null;let s=e.getNode(r)?.content?.blob;if(typeof s!="string")return null;let o=W(t,s);if(o===null)return null;try{let l=JSON.parse(o.toString("utf8"));return l.schema!=="kane.source.web/1"?null:typeof l.url=="string"&&l.url.length>0?l.url:null}catch{return null}}function fe(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 cn(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 un(t,n,e,r,s){let o=ae(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};let l=me(t),u=n??l;if(u===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};try{N(u)}catch(b){return(e.err??e.out)(`error: ${t}: ${b instanceof Error?b.message:String(b)}`),{code:1}}let i=P(r,u,"web");if(i!==null)return(e.err??e.out)(`error: ${t}: ${i}`),{code:1};let c=an(r,u);if(c!==null&&c!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${u}' was ingested from ${c} \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 '${u}' was ingested from ${c} \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 a=s?.web?.scrape??ut,d=s?.authEnv??(async()=>(await import("./spawner-ABB7B5CQ.js")).resolveAgentAuthEnv()),p=await a(o,{authEnv:d});if(!p.ok)return(e.err??e.out)(`error: ${t}: ${fe(p.kind)}`),{code:1};try{let{bytes:b}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:b,media:be,sourceId:u,label:o,confirmSameSource:e.isTTY?h=>e.confirm(`identical content already ingested as ${h} \u2014 treat as the same source?`):void 0,converters:{web:dt()}}),g=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,g));for(let h of w.warnings??[])e.out(`warning: ${h}`);return e.isTTY&&p.page.title&&e.out(` title: ${p.page.title}`),{code:0,result:{status:w.status,source_id:w.source_id,source_cid:w.cid,...w.gitignore?{gitignore:w.gitignore}:{}}}}catch(b){return(e.err??e.out)(`error: ${t}: ${cn(b instanceof Error?b.message:String(b))}`),{code:1}}}var mt={name:"web",hint:"any public web page URL (https://\u2026)",match:pt,ingest:un,sourceIdFor:me};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 ln=[Oe,De,st,at,ct,mt];function Kr(t){return/^https?:\/\/.+/i.test(t)}function Wr(t){return ln.find(n=>n.match(t))??null}export{U as a,ln as b,Kr as c,Wr as d};
17
+ `,inventory:l.inventory,blobs:l.blobs,delivered:l.delivered,converter:{name:"linear-doc-convert",version:"1",policy:"v1"}}}}var qt=/^[A-Za-z][A-Za-z0-9]*-\d+$/,Qt=/-([0-9a-f]{12})$/;function ue(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname.toLowerCase()!=="linear.app"?null:n.pathname.split("/").filter(Boolean)}function Ze(t){let n=ue(t);return n===null||n.length<3?null:{workspace:n[0],segs:n}}function Y(t){let n=Ze(t);if(n===null||n.segs[1]!=="issue")return null;let e=n.segs[2];return qt.test(e)?{workspace:n.workspace,key:e}:null}function K(t){let n=Ze(t);if(n===null||n.segs[1]!=="document")return null;let e=n.segs[2].match(Qt);return e===null?null:{workspace:n.workspace,slugId:e[1]}}var en=new Set(["project","team","view","initiative","cycle","roadmap","inbox","triage","my-issues"]),qe=new Set(["docs","features","method","blog","customers","pricing","integrations","developers","changelog","about","careers","security","download","contact","now","switch","homepage"]);function le(t){let n=ue(t);return n===null||n.length<2||!en.has(n[1])||qe.has(n[0].toLowerCase())?null:{workspace:n[0],section:n[1]}}function de(t){let n=ue(t);return n===null||n.length<2||n[1]!=="issue"&&n[1]!=="document"||qe.has(n[0].toLowerCase())||Y(t)!==null||K(t)!==null?null:{workspace:n[0],section:n[1]}}function Qe(t){let n=Y(t);return n?n.key.toLowerCase():null}function et(t){let n=K(t);return n?`doc-${n.slugId}`:null}var tt={linearInfo:je,linearIssue:Be,linearComments:Me,linearDocument:Je,linearAttachment:Fe};function nt(t,n){if(t)try{let e=new URL(t).pathname.split("/").filter(Boolean)[0];if(e)return`linear.app/${e.toLowerCase()}`}catch{}return`linear.app/${n.toLowerCase()}`}function rt(t,n,e,r,s,o){let l=ee(t,r);if(l!==null&&typeof l.schema=="string"&&l.schema.startsWith(`kane.source.${n}/`)){let i=l;for(let c of e)i=i!==null&&typeof i=="object"?i[c]:void 0;if(typeof i=="string"&&i!==""&&i!==s)return`source '${r}' was ingested from a different ${o} that used this key \u2014 the key was recycled; retire it first (kane-cli context retire ${r}) or ingest under a different id with --as`}let u=ke(t,n,e,s);return u!==null&&u!==r?`this ${o} is already ingested as '${u}' (its key changed) \u2014 reconcile that source, or retire it to re-ingest under the new key`:null}function ot(t,n,e,r){let s=ee(t,e);if(s===null||typeof s.schema!="string"||!s.schema.startsWith(`kane.source.${n}/`))return null;let o=s.site;return typeof o!="string"||o.length===0||o===r?null:`source '${e}' was ingested from ${o}, but this read serves ${r} \u2014 retire it first (kane-cli context retire ${e}) or ingest under a different id with --as`}async function tn(t,n,e,r,s){let o=Y(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear issue URL (https://linear.app/<workspace>/issue/KEY-123)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-6PKLNV6Z.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.issue===!1||c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issues or their comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearIssue(o.key,i),d=await l.linearComments(o.key,i),p=nt(a.host,o.workspace),{bytes:b,envelope:w,warnings:g}=Ge(a,d,p),h=n??o.key.toLowerCase();N(h);let _=rt(r,"linear",["issue","uuid"],h,w.issue.uuid,"issue")??P(r,h,"linear")??ot(r,"linear",h,p);if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let y=await T({contextDir:r,bytes:b,media:Ee,sourceId:h,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{linear:ze({fetchAttachment:m=>l.linearAttachment(m,i)})}});e.out(U(e.isTTY,y,w.issue.key));for(let m of g)e.out(`warning: ${m}`);for(let m of y.warnings??[])e.out(`warning: ${m}`);if(y.composite){let m=y.composite.delivered+y.composite.omitted;e.out(`${y.source_id}: linear, ${m} images, ${y.composite.delivered} delivered (${y.composite.omitted} omitted)`)}return{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid,...y.gitignore?{gitignore:y.gitignore}:{}}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"issue","Linear")}`),{code:1})}}async function nn(t,n,e,r,s){let o=K(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear document URL (https://linear.app/<workspace>/document/<slug>)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-6PKLNV6Z.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read documents yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearDocument(o.slugId,i),d=nt(a.url,o.workspace),{bytes:p,envelope:b,warnings:w}=Ye(a,d,o.slugId),g=n??`doc-${o.slugId}`;N(g);let h=rt(r,"linear-doc",["document","uuid"],g,b.document.uuid,"document")??P(r,g,"linear-doc")??ot(r,"linear-doc",g,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:g,label:t,confirmSameSource:e.isTTY?y=>e.confirm(`identical content already ingested as ${y} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:y=>l.linearAttachment(y,i)})}});e.out(U(e.isTTY,_,b.title||`document ${o.slugId}`));for(let y of w)e.out(`warning: ${y}`);for(let y of _.warnings??[])e.out(`warning: ${y}`);if(_.composite){let y=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${y} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid,..._.gitignore?{gitignore:_.gitignore}:{}}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"document","Linear")}`),{code:1})}}function it(t,n,e){let r=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return r?`the ${n}'s content is too large to ingest (${r[1]}; the limit is ${r[2]}) \u2014 trim the ${n} in ${e} and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?`the ${n}'s text is too large to ingest \u2014 trim the ${n} in ${e} and retry`:t}var st={name:"linear",hint:"Linear issue URLs (https://linear.app/<workspace>/issue/KEY-123)",match:t=>Y(t)!==null,ingest:tn,sourceIdFor:Qe},at={name:"linear-doc",hint:"Linear document URLs (https://linear.app/<workspace>/document/<slug>)",match:t=>K(t)!==null,ingest:nn,sourceIdFor:et},ct={name:"linear-page",hint:"Linear issue or document URLs (other linear.app pages are not ingestable)",match:t=>le(t)!==null||de(t)!==null,ingest:async(t,n,e)=>{let r=le(t);if(r===null){let s=de(t);return s!==null?((e.err??e.out)(`error: ${t}: this Linear ${s.section} link is incomplete or malformed \u2014 use the full form (https://linear.app/${s.workspace}/issue/KEY-123 or https://linear.app/${s.workspace}/document/<slug>-<id>)`),{code:1}):((e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear workspace page`),{code:1})}return(e.err??e.out)(`error: ${t}: this Linear page can't be ingested \u2014 only issue and document URLs are supported; ingest the project's issues or documents individually (https://linear.app/${r.workspace}/issue/KEY-123)`),{code:1}},sourceIdFor:()=>null};var rn=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 ut(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,s=we(e),o={"Content-Type":"application/json"},l=await n.authEnv(),u=l.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=l.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;u?o.Authorization=`Basic ${u}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${s}/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 a;try{a=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let p=a.page;return p===void 0||typeof p.markdown!="string"||p.markdown===""||typeof p.final_url!="string"||p.final_url===""||typeof p.projection?.kind!="string"||typeof p.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:p}}let d=a.code;return typeof d=="string"&&rn.has(d)?{ok:!1,kind:d}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var pe="kane.source.web/1";function lt(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:pe,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var on=new Set(["markdown"]);function dt(){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!==pe)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!on.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 sn}from"crypto";function pt(t){return ae(t)!==null}function ae(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 me(t){let n=ae(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(/-+$/,""),s=sn("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${s}`}function an(t,n){let e=j(t),r=e.heads.get(n);if(r==null)return null;let s=e.getNode(r)?.content?.blob;if(typeof s!="string")return null;let o=W(t,s);if(o===null)return null;try{let l=JSON.parse(o.toString("utf8"));return l.schema!=="kane.source.web/1"?null:typeof l.url=="string"&&l.url.length>0?l.url:null}catch{return null}}function fe(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 cn(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 un(t,n,e,r,s){let o=ae(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};let l=me(t),u=n??l;if(u===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};try{N(u)}catch(b){return(e.err??e.out)(`error: ${t}: ${b instanceof Error?b.message:String(b)}`),{code:1}}let i=P(r,u,"web");if(i!==null)return(e.err??e.out)(`error: ${t}: ${i}`),{code:1};let c=an(r,u);if(c!==null&&c!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${u}' was ingested from ${c} \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 '${u}' was ingested from ${c} \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 a=s?.web?.scrape??ut,d=s?.authEnv??(async()=>(await import("./spawner-O3VKHYUY.js")).resolveAgentAuthEnv()),p=await a(o,{authEnv:d});if(!p.ok)return(e.err??e.out)(`error: ${t}: ${fe(p.kind)}`),{code:1};try{let{bytes:b}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:b,media:be,sourceId:u,label:o,confirmSameSource:e.isTTY?h=>e.confirm(`identical content already ingested as ${h} \u2014 treat as the same source?`):void 0,converters:{web:dt()}}),g=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,g));for(let h of w.warnings??[])e.out(`warning: ${h}`);return e.isTTY&&p.page.title&&e.out(` title: ${p.page.title}`),{code:0,result:{status:w.status,source_id:w.source_id,source_cid:w.cid,...w.gitignore?{gitignore:w.gitignore}:{}}}}catch(b){return(e.err??e.out)(`error: ${t}: ${cn(b instanceof Error?b.message:String(b))}`),{code:1}}}var mt={name:"web",hint:"any public web page URL (https://\u2026)",match:pt,ingest:un,sourceIdFor:me};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 ln=[Oe,De,st,at,ct,mt];function Kr(t){return/^https?:\/\/.+/i.test(t)}function Wr(t){return ln.find(n=>n.match(t))??null}export{U as a,ln as b,Kr as c,Wr as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-VIYV6NIW.js";import"./chunk-PHR2OSWD.js";import"./chunk-UR6MHSHU.js";export{a as getEnvironment};
2
+ import{a}from"./chunk-RBVLIMOV.js";import"./chunk-UQ6A52ML.js";import"./chunk-UR6MHSHU.js";export{a as getEnvironment};
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as O}from"./chunk-DYW5C6II.js";import{P as g,Q as S,S as G}from"./chunk-6CYF7Q5W.js";import"./chunk-ICFJVEEA.js";import"./chunk-H6TNBKGR.js";import"./chunk-66MOZKD2.js";import"./chunk-YLQHY4A7.js";import{e as w,f as $}from"./chunk-5GUD3CIH.js";import{d as x}from"./chunk-WESMQEPO.js";import{e as k}from"./chunk-EHN5HTUD.js";import"./chunk-IPQAKIJO.js";import"./chunk-VVOKM2VO.js";import"./chunk-CH273NAE.js";import"./chunk-CAOZKSQ3.js";import{b}from"./chunk-VZ7KXRXB.js";import"./chunk-5LJRZI7S.js";import"./chunk-BKM2LWU2.js";import{z as R}from"./chunk-IICT4VOU.js";import"./chunk-D6E6KRVX.js";import"./chunk-3UI5VTQS.js";import"./chunk-RDHWNSDP.js";import"./chunk-FQNQVC5O.js";import"./chunk-XLSOQLVT.js";import"./chunk-UD7KKHPW.js";import"./chunk-YCCUBQY4.js";import"./chunk-RSSOJ3L2.js";import"./chunk-5EOX4MEY.js";import"./chunk-RZ4F3BHX.js";import"./chunk-EYOCNMUM.js";import"./chunk-PHR2OSWD.js";import"./chunk-DFS4RMVP.js";import"./chunk-HCBYKLMW.js";import"./chunk-C44QQJR4.js";import"./chunk-6YGTRKDT.js";import"./chunk-UR6MHSHU.js";import{basename as h}from"path";import{statSync as A}from"fs";function C(t,e){if(!t)return 1;let o=t.resolve(e);return!o||o.superseded?1:t.getNode(o.tip)?.content.risk==="high"?3:1}function D(t,e){return t.usecases.map(o=>{let s=o.acceptance_criteria??[],a=s.filter(n=>(n.covered_by??[]).length>0),l=s.filter(n=>n.execution==="passed"),i=s.filter(n=>n.execution==="failed"),u=s.filter(n=>n.execution==="blocked"),d=0,m=0;for(let n of s){let f=C(e,n.id);d+=f,n.execution==="passed"&&(m+=f)}let r=d===0?0:Math.round(100*m/d),p=a.length===0?"uncovered":s.length===l.length?"covered":u.length>0&&i.length===0?"blocked":"partial";return{id:o.id,title:o.title,status:p,pct:r,acs:{total:s.length,covered:a.length,passed:l.length,failed:i.length,blocked:u.length},stale:s.filter(n=>n.fresh==="stale").map(n=>n.id)}})}async function P(t){let e=await w(t);return e.length===0?null:e.map(o=>({p:o,m:A(o).mtimeMs})).sort((o,s)=>s.m-o.m)[0].p}var N={covered:"\u2714",partial:"\u25D0",uncovered:"\u2716",blocked:"\u23F8"};function _(t){let e=Math.round(t/10);return"\u2588".repeat(e)+"\u2591".repeat(10-e)}async function I(t,e=G(),o=process.cwd()){if(t.mode!==void 0&&t.mode!=="agent"&&t.mode!=="ci"&&t.mode!=="interactive")return g(e,`--mode must be interactive | agent | ci, got '${t.mode}'`),2;if(t.mode==="agent"||t.mode==="ci"){let{makeHeadlessIO:r,agentRefusal:p}=await import("./headless-io-3A3BZVQ5.js"),n=r("ndjson","cover",{stdout:c=>e.out(c.replace(/\n$/,"")),stderr:c=>(e.err??e.out)(c.replace(/\n$/,""))}),f=[],v=[],j={out:c=>f.push(c),err:c=>v.push(c),confirm:async()=>!1,isTTY:!1};if(await I({...t,json:!0,mode:void 0},j,o)!==0)return p(n,v.join("; ")||"cover refused");let y=JSON.parse(f.join(`
2
+ import{b as O}from"./chunk-DYW5C6II.js";import{P as g,Q as S,S as G}from"./chunk-QX5LJVTD.js";import"./chunk-WWVHK7OA.js";import"./chunk-H6TNBKGR.js";import"./chunk-66MOZKD2.js";import"./chunk-YLQHY4A7.js";import{e as w,f as $}from"./chunk-5GUD3CIH.js";import{d as x}from"./chunk-WESMQEPO.js";import{e as k}from"./chunk-EHN5HTUD.js";import"./chunk-IPQAKIJO.js";import"./chunk-VVOKM2VO.js";import"./chunk-CH273NAE.js";import"./chunk-CAOZKSQ3.js";import{b}from"./chunk-VZ7KXRXB.js";import"./chunk-5LJRZI7S.js";import"./chunk-BKM2LWU2.js";import{z as R}from"./chunk-IICT4VOU.js";import"./chunk-D6E6KRVX.js";import"./chunk-3UI5VTQS.js";import"./chunk-RDHWNSDP.js";import"./chunk-FQNQVC5O.js";import"./chunk-XLSOQLVT.js";import"./chunk-UD7KKHPW.js";import"./chunk-YCCUBQY4.js";import"./chunk-RSSOJ3L2.js";import"./chunk-5EOX4MEY.js";import"./chunk-RZ4F3BHX.js";import"./chunk-EYOCNMUM.js";import"./chunk-UQ6A52ML.js";import"./chunk-DFS4RMVP.js";import"./chunk-HCBYKLMW.js";import"./chunk-C44QQJR4.js";import"./chunk-6YGTRKDT.js";import"./chunk-UR6MHSHU.js";import{basename as h}from"path";import{statSync as A}from"fs";function C(t,e){if(!t)return 1;let o=t.resolve(e);return!o||o.superseded?1:t.getNode(o.tip)?.content.risk==="high"?3:1}function D(t,e){return t.usecases.map(o=>{let s=o.acceptance_criteria??[],a=s.filter(n=>(n.covered_by??[]).length>0),l=s.filter(n=>n.execution==="passed"),i=s.filter(n=>n.execution==="failed"),u=s.filter(n=>n.execution==="blocked"),d=0,m=0;for(let n of s){let f=C(e,n.id);d+=f,n.execution==="passed"&&(m+=f)}let r=d===0?0:Math.round(100*m/d),p=a.length===0?"uncovered":s.length===l.length?"covered":u.length>0&&i.length===0?"blocked":"partial";return{id:o.id,title:o.title,status:p,pct:r,acs:{total:s.length,covered:a.length,passed:l.length,failed:i.length,blocked:u.length},stale:s.filter(n=>n.fresh==="stale").map(n=>n.id)}})}async function P(t){let e=await w(t);return e.length===0?null:e.map(o=>({p:o,m:A(o).mtimeMs})).sort((o,s)=>s.m-o.m)[0].p}var N={covered:"\u2714",partial:"\u25D0",uncovered:"\u2716",blocked:"\u23F8"};function _(t){let e=Math.round(t/10);return"\u2588".repeat(e)+"\u2591".repeat(10-e)}async function I(t,e=G(),o=process.cwd()){if(t.mode!==void 0&&t.mode!=="agent"&&t.mode!=="ci"&&t.mode!=="interactive")return g(e,`--mode must be interactive | agent | ci, got '${t.mode}'`),2;if(t.mode==="agent"||t.mode==="ci"){let{makeHeadlessIO:r,agentRefusal:p}=await import("./headless-io-3A3BZVQ5.js"),n=r("ndjson","cover",{stdout:c=>e.out(c.replace(/\n$/,"")),stderr:c=>(e.err??e.out)(c.replace(/\n$/,""))}),f=[],v=[],j={out:c=>f.push(c),err:c=>v.push(c),confirm:async()=>!1,isTTY:!1};if(await I({...t,json:!0,mode:void 0},j,o)!==0)return p(n,v.join("; ")||"cover refused");let y=JSON.parse(f.join(`
3
3
  `));return n.event({type:"coverage",...y}),n.done(0,void 0,M(y.completeness??[]))}let s=S(o,e);if(!s)return 2;let a=t.from?await $(t.from,o):await P(o);if(!a)return g(e,t.from?`no evidence pack at '${t.from}'`:"no evidence pack in .testmuai/evidence \u2014 run a test first, or pass --from <pack>"),2;let l=await k(a,"coverage/usecases.yaml");if(l==null)return g(e,`${h(a)} carries no coverage/usecases.yaml \u2014 the pack predates coverage or its project had no .context at seal time`),2;let i=b(l);if(!i||!Array.isArray(i.usecases))return g(e,`${h(a)}: coverage/usecases.yaml is not a usecases document`),2;let u=R(s),d=D(i,u),m=await x(u,"design");if(t.json)return e.out(JSON.stringify({pack:a,depth:d,completeness:m},null,2)),0;e.out(`coverage \u2014 ${h(a)}`),e.out(""),e.out("depth (proven by the pack):");for(let r of d){let p=r.stale.length?` \xB7 ${r.stale.length} stale`:"";e.out(` ${N[r.status]} ${_(r.pct)} ${String(r.pct).padStart(3)}% ${r.id} \u2014 ${r.status} (${r.acs.passed}/${r.acs.total} ACs proven${r.acs.failed?`, ${r.acs.failed} failed`:""}${r.acs.blocked?`, ${r.acs.blocked} blocked`:""})${p}`)}e.out(""),e.out("completeness (live graph):"),m.length===0&&e.out(" no design gaps \u2014 every AC verified, every use-case scenarioed");for(let r of m)e.out(` [${r.risk}] ${r.tag} ${r.ref} \u2014 ${r.why}`),e.out(` \u2192 ${r.ready_command}`);return 0}function M(t){return t.filter(e=>e.ready_command.startsWith("kane-cli ")&&O(e.ready_command)).slice(0,4).map(e=>({cmd:e.ready_command,why:e.why}))}export{I as coverCommand,M as coverNext,D as depthRows};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-JWOPRJIO.js";import"./chunk-PHR2OSWD.js";import"./chunk-UR6MHSHU.js";export{a as CredentialsManager};
2
+ import{a}from"./chunk-47FQ7ZUQ.js";import"./chunk-UQ6A52ML.js";import"./chunk-UR6MHSHU.js";export{a as CredentialsManager};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-TMOSERKN.js";import"./chunk-MSGW4JDG.js";import"./chunk-4JOD47QI.js";import"./chunk-PHR2OSWD.js";import"./chunk-UR6MHSHU.js";export{a as DEPS_INSTALL_SCHEMA_VERSION,i as DepsBundleResolver,c as DepsInstallRequiredError,h as NoPublishedBundleError,b as classOfTarget,g as downloadPayload,e as formatEta,d as formatRate,j as managedDeps,f as planRangeParts};
2
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-UUS5AK6L.js";import"./chunk-MSGW4JDG.js";import"./chunk-4JOD47QI.js";import"./chunk-UQ6A52ML.js";import"./chunk-UR6MHSHU.js";export{a as DEPS_INSTALL_SCHEMA_VERSION,i as DepsBundleResolver,c as DepsInstallRequiredError,h as NoPublishedBundleError,b as classOfTarget,g as downloadPayload,e as formatEta,d as formatRate,j as managedDeps,f as planRangeParts};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import"./chunk-UR6MHSHU.js";var c="Mobile dependencies are resolved through your KaneAI account. Run `kane-cli login` first.";function d(l,o,e=process.env){return e.KANE_MOBILE_DEPS_BASE_URL||o(l)}async function u(){let[{CredentialsManager:l},{refreshOAuthToken:o},{getEnvironment:e},{ControllerClient:n}]=await Promise.all([import("./credentials-FLY3ZXVX.js"),import("./token-refresh-NADDXLYM.js"),import("./config-WKLEWUPU.js"),import("./controller-client-ZF5IXRUV.js")]),s=new l;return{creds:s,refresh:r=>o({creds:s,profile:r.profile,env:r.env,credentials:r.credentials}),controllerBaseUrlFor:r=>d(r,t=>e(t).controllerBaseUrl),makeClient:(r,t)=>new n(r,t)}}function p(l){return async o=>{let e=l??await u(),n=e.creds.getActiveProfile();if(!n)throw new Error(c);let s=e.creds.getDefaultEnv(),r=e.controllerBaseUrlFor(s),t=e.creds.loadBasicAuth(n,s);if(t)return e.makeClient(r,{username:t.username,accessKey:t.access_key}).resolveMobileDepsBundle(o);let i=e.creds.loadCredentials(n,s);if(!i)throw new Error(c);try{await e.refresh({creds:e.creds,profile:n,env:s,credentials:i})}catch{}let a=(e.creds.loadCredentials(n,s)??i).access_token;if(typeof a!="string"||!a)throw new Error(c);return e.makeClient(r,a).resolveMobileDepsBundle(o)}}export{p as controllerResolveBundle,d as depsControllerBaseUrl};
2
+ import"./chunk-UR6MHSHU.js";var c="Mobile dependencies are resolved through your KaneAI account. Run `kane-cli login` first.";function d(l,o,e=process.env){return e.KANE_MOBILE_DEPS_BASE_URL||o(l)}async function u(){let[{CredentialsManager:l},{refreshOAuthToken:o},{getEnvironment:e},{ControllerClient:n}]=await Promise.all([import("./credentials-MUZUCSJJ.js"),import("./token-refresh-IM6ELK6S.js"),import("./config-ODCFEOAN.js"),import("./controller-client-ZF5IXRUV.js")]),s=new l;return{creds:s,refresh:r=>o({creds:s,profile:r.profile,env:r.env,credentials:r.credentials}),controllerBaseUrlFor:r=>d(r,t=>e(t).controllerBaseUrl),makeClient:(r,t)=>new n(r,t)}}function p(l){return async o=>{let e=l??await u(),n=e.creds.getActiveProfile();if(!n)throw new Error(c);let s=e.creds.getDefaultEnv(),r=e.controllerBaseUrlFor(s),t=e.creds.loadBasicAuth(n,s);if(t)return e.makeClient(r,{username:t.username,accessKey:t.access_key}).resolveMobileDepsBundle(o);let i=e.creds.loadCredentials(n,s);if(!i)throw new Error(c);try{await e.refresh({creds:e.creds,profile:n,env:s,credentials:i})}catch{}let a=(e.creds.loadCredentials(n,s)??i).access_token;if(typeof a!="string"||!a)throw new Error(c);return e.makeClient(r,a).resolveMobileDepsBundle(o)}}export{p as controllerResolveBundle,d as depsControllerBaseUrl};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d}from"./chunk-LO47W2DO.js";import"./chunk-YKTYVJBN.js";import"./chunk-7N6OCHPC.js";import"./chunk-KDNNMU7Q.js";import"./chunk-2UIHS2FH.js";import"./chunk-Q2F5QB2W.js";import"./chunk-N2P4MI32.js";import"./chunk-VVOKM2VO.js";import"./chunk-IICT4VOU.js";import"./chunk-D6E6KRVX.js";import"./chunk-3UI5VTQS.js";import"./chunk-RDHWNSDP.js";import"./chunk-FQNQVC5O.js";import"./chunk-XLSOQLVT.js";import"./chunk-UD7KKHPW.js";import"./chunk-PHR2OSWD.js";import"./chunk-UR6MHSHU.js";export{b as REMOTE_PROVIDERS,d as findProvider,a as landingReceipt,c as looksLikeUrl};
2
+ import{a,b,c,d}from"./chunk-ZW3JBY5E.js";import"./chunk-YKTYVJBN.js";import"./chunk-7N6OCHPC.js";import"./chunk-KDNNMU7Q.js";import"./chunk-2UIHS2FH.js";import"./chunk-Q2F5QB2W.js";import"./chunk-N2P4MI32.js";import"./chunk-VVOKM2VO.js";import"./chunk-IICT4VOU.js";import"./chunk-D6E6KRVX.js";import"./chunk-3UI5VTQS.js";import"./chunk-RDHWNSDP.js";import"./chunk-FQNQVC5O.js";import"./chunk-XLSOQLVT.js";import"./chunk-UD7KKHPW.js";import"./chunk-UQ6A52ML.js";import"./chunk-UR6MHSHU.js";export{b as REMOTE_PROVIDERS,d as findProvider,a as landingReceipt,c as looksLikeUrl};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d}from"./chunk-MTCLFYNH.js";import"./chunk-3YBT4UGQ.js";import"./chunk-MMBBQ4OZ.js";import"./chunk-TMOSERKN.js";import"./chunk-MSGW4JDG.js";import"./chunk-TZXXJWHA.js";import"./chunk-Z7S3IWUX.js";import"./chunk-4JOD47QI.js";import"./chunk-RZ4F3BHX.js";import"./chunk-PHR2OSWD.js";import"./chunk-UR6MHSHU.js";export{d as doctorExitCode,c as doctorPreflightBlocked,b as renderDoctorText,a as runDoctor};
2
+ import{a,b,c,d}from"./chunk-MVOO7RPO.js";import"./chunk-4JRCAHHB.js";import"./chunk-MMBBQ4OZ.js";import"./chunk-UUS5AK6L.js";import"./chunk-MSGW4JDG.js";import"./chunk-TZXXJWHA.js";import"./chunk-Z7S3IWUX.js";import"./chunk-4JOD47QI.js";import"./chunk-RZ4F3BHX.js";import"./chunk-UQ6A52ML.js";import"./chunk-UR6MHSHU.js";export{d as doctorExitCode,c as doctorPreflightBlocked,b as renderDoctorText,a as runDoctor};