@testmuai/kane-cli 0.6.10 → 0.7.0

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 (157) hide show
  1. package/dist/ChatSurface-PMEOJBZG.js +8 -0
  2. package/dist/{ChromeProfilePicker-IDKFTIHW.js → ChromeProfilePicker-DK2A3NYY.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-SZOU5FGZ.js → CliFeedbackPrompt-D5QDOBE2.js} +1 -1
  4. package/dist/{CliUploadProgress-W2FC33Q4.js → CliUploadProgress-AIZL7N6Z.js} +1 -1
  5. package/dist/{ConfigView-JB2NSZ2N.js → ConfigView-SDBCTYUU.js} +1 -1
  6. package/dist/{EvidenceViewOffer-5YST67KY.js → EvidenceViewOffer-EOKJE2B6.js} +1 -1
  7. package/dist/{FolderPicker-SPNZESAR.js → FolderPicker-IVBHPPMW.js} +1 -1
  8. package/dist/{HelpView-XBDXXHFB.js → HelpView-YYYX4RKI.js} +1 -1
  9. package/dist/{InfoBox-2T7GYSFT.js → InfoBox-MQV3XBT4.js} +1 -1
  10. package/dist/{LinksBox-2NNZZDQT.js → LinksBox-NCFNBUMW.js} +1 -1
  11. package/dist/{ProfilesView-KJZVGU5B.js → ProfilesView-6GXF6CP2.js} +1 -1
  12. package/dist/{ProjectPicker-AUTZNEPE.js → ProjectPicker-W6XDGNDJ.js} +1 -1
  13. package/dist/{SaveSessionPrompt-LHLSJQSQ.js → SaveSessionPrompt-QF3P7ERS.js} +1 -1
  14. package/dist/SingleShotApp-T673X7BS.js +2 -0
  15. package/dist/{SummaryBox-5G7WULUN.js → SummaryBox-4SZI4XSO.js} +1 -1
  16. package/dist/TestMdRunView-SNYEO6CS.js +2 -0
  17. package/dist/{WhoamiView-XNWBDMQR.js → WhoamiView-N3HAJ3TN.js} +1 -1
  18. package/dist/auth-RXNBQZI2.js +2 -0
  19. package/dist/{bind-FEOGBJ2O.js → bind-NSGW5BBZ.js} +2 -2
  20. package/dist/{bootstrap-T6DSUI34.js → bootstrap-RPT3JOGD.js} +1 -1
  21. package/dist/{bridge-WMGH3O3B.js → bridge-BTSWCJ3B.js} +1 -1
  22. package/dist/{changelog-AGFDNTTW.js → changelog-MI3IPBJS.js} +1 -1
  23. package/dist/{chat-committer-4ENYH3RC.js → chat-committer-OS7ULZMH.js} +1 -1
  24. package/dist/chat-controller-QLORQWJZ.js +2 -0
  25. package/dist/{chunk-JHPZXF77.js → chunk-3CJIMPQK.js} +2 -2
  26. package/dist/{chunk-SKRZN25J.js → chunk-3RZ63RBO.js} +1 -1
  27. package/dist/{chunk-YOFKDRY4.js → chunk-44IWSV6L.js} +1 -1
  28. package/dist/{chunk-7LWXIRI3.js → chunk-4BAMZSFU.js} +1 -1
  29. package/dist/{chunk-TW3K2DKB.js → chunk-4GLYNAK7.js} +1 -1
  30. package/dist/{chunk-7APDXIKI.js → chunk-4SJC64KQ.js} +9 -9
  31. package/dist/{chunk-5Z7GAIPP.js → chunk-4XSW6WZD.js} +2 -2
  32. package/dist/{chunk-6NWPK2MS.js → chunk-5WE4DHXL.js} +1 -1
  33. package/dist/chunk-5YHVK2EO.js +6 -0
  34. package/dist/{chunk-TLL7KFLY.js → chunk-67SSEGDO.js} +1 -1
  35. package/dist/{chunk-L4JIMNKW.js → chunk-6HYW5RFX.js} +1 -1
  36. package/dist/{chunk-A46NBRAP.js → chunk-6W6AIDLJ.js} +1 -1
  37. package/dist/{chunk-VYQMCLKG.js → chunk-77WMTCUQ.js} +1 -1
  38. package/dist/{chunk-SDRFTIRU.js → chunk-7E24OCGX.js} +1 -1
  39. package/dist/chunk-7YPK6EDR.js +4 -0
  40. package/dist/{chunk-RH4GCEFX.js → chunk-A2IQRVPR.js} +1 -1
  41. package/dist/{chunk-YVXC46DY.js → chunk-AIMINJVP.js} +1 -1
  42. package/dist/{chunk-C3OGWCII.js → chunk-AV6E6WLY.js} +2 -2
  43. package/dist/{chunk-5LTUYXMP.js → chunk-AYY7RYMK.js} +1 -1
  44. package/dist/chunk-B4LLKQTK.js +2 -0
  45. package/dist/{chunk-FYDBD7Q4.js → chunk-BCH3JCND.js} +1 -1
  46. package/dist/{chunk-SACSQY3Q.js → chunk-CH3VWCRZ.js} +1 -1
  47. package/dist/{chunk-WSZ7IENQ.js → chunk-CSGQIY7X.js} +3 -3
  48. package/dist/{chunk-QGBLC4ZJ.js → chunk-DFDDUMG5.js} +1 -1
  49. package/dist/{chunk-JTCW76YG.js → chunk-DGIPQINV.js} +1 -1
  50. package/dist/chunk-E5PWL3BG.js +7 -0
  51. package/dist/{chunk-6MTVGARW.js → chunk-EN7NW7DU.js} +1 -1
  52. package/dist/{chunk-QPT4ERGK.js → chunk-F7WKDMX7.js} +1 -1
  53. package/dist/{chunk-7Z64BL5D.js → chunk-FCHTL74E.js} +1 -1
  54. package/dist/{chunk-OSALXGD4.js → chunk-FMR2KPSK.js} +1 -1
  55. package/dist/{chunk-RGDQMKNJ.js → chunk-FRBYGSGJ.js} +1 -1
  56. package/dist/{chunk-KA7Q5IIC.js → chunk-GQ3NCBYR.js} +1 -1
  57. package/dist/{chunk-XZW3TBOV.js → chunk-HOOXUO3X.js} +1 -1
  58. package/dist/{chunk-7C6G4V43.js → chunk-IQODWB32.js} +1 -1
  59. package/dist/{chunk-MBXWXBDM.js → chunk-J2KSZUOO.js} +1 -1
  60. package/dist/{chunk-W54W762O.js → chunk-J3EMJ7US.js} +1 -1
  61. package/dist/{chunk-ZFFRHV5U.js → chunk-JSF5JYZC.js} +1 -1
  62. package/dist/{chunk-MSK7AC4E.js → chunk-K4VIM4RM.js} +2 -2
  63. package/dist/{chunk-2H3XNXL3.js → chunk-KCBS57IF.js} +1 -1
  64. package/dist/chunk-KHQHVSZ6.js +5 -0
  65. package/dist/{chunk-DHF3VO2R.js → chunk-LGVHW4ZA.js} +1 -1
  66. package/dist/{chunk-KK7DYHK6.js → chunk-MAO5BAQI.js} +1 -1
  67. package/dist/{chunk-6CGNLFSN.js → chunk-MTHCUBDF.js} +1 -1
  68. package/dist/{chunk-3KN2UW37.js → chunk-MV4UYTZT.js} +1 -1
  69. package/dist/{chunk-Z25FKS3Y.js → chunk-N4LMQR7C.js} +1 -1
  70. package/dist/{chunk-5F7PU5AJ.js → chunk-NR23HZU4.js} +1 -1
  71. package/dist/chunk-QBCS57EO.js +62 -0
  72. package/dist/{chunk-J4WS2SXT.js → chunk-QQUZF2DZ.js} +1 -1
  73. package/dist/{chunk-WV42KKEU.js → chunk-RCTM7NGT.js} +1 -1
  74. package/dist/{chunk-76I6NJBX.js → chunk-RODHDQU3.js} +1 -1
  75. package/dist/{chunk-AYDUHTPA.js → chunk-RQYS3KGU.js} +1 -1
  76. package/dist/{chunk-MJF3USZF.js → chunk-SBZWFULF.js} +2 -2
  77. package/dist/{chunk-6JTEWZ75.js → chunk-T7ZPMTGS.js} +1 -1
  78. package/dist/chunk-TDPWFYTJ.js +2 -0
  79. package/dist/{chunk-OESHJ4J2.js → chunk-UXPQRALY.js} +2 -2
  80. package/dist/chunk-V3UE6RJP.js +2 -0
  81. package/dist/chunk-VJFFMOUA.js +2 -0
  82. package/dist/{chunk-GWJ76BLF.js → chunk-VYMCE7UR.js} +2 -2
  83. package/dist/{chunk-YJIESLN6.js → chunk-WREVEATJ.js} +1 -1
  84. package/dist/{chunk-XY5KWIRF.js → chunk-WTXHOWUP.js} +1 -1
  85. package/dist/{chunk-LPBAQQ7E.js → chunk-X5P2T7MA.js} +1 -1
  86. package/dist/{chunk-6ZJ7ZFEX.js → chunk-XIXR63FI.js} +1 -1
  87. package/dist/{chunk-ECFOND7B.js → chunk-XLKRV2JH.js} +1 -1
  88. package/dist/{chunk-FEF75YKV.js → chunk-YHQFYZJ5.js} +1 -1
  89. package/dist/chunk-Z2JSEL3I.js +4 -0
  90. package/dist/{config-7WI6TBDV.js → config-5GOFF5F4.js} +1 -1
  91. package/dist/{cover-cmd-J2ZJUL6P.js → cover-cmd-SV3I23UM.js} +1 -1
  92. package/dist/{credentials-MX5ABDPF.js → credentials-GXDXVMXW.js} +1 -1
  93. package/dist/docx-convert-ZBVQO2LG.js +2 -0
  94. package/dist/{dossier-UVTGCL7T.js → dossier-KJSJPWOW.js} +1 -1
  95. package/dist/{evidence-TZYIOSPG.js → evidence-VDNZ3K23.js} +1 -1
  96. package/dist/{evolve-cmd-IDS5ZIUY.js → evolve-cmd-BLSVVW4I.js} +1 -1
  97. package/dist/{explain-VTRHEVUQ.js → explain-EBVIUS2X.js} +1 -1
  98. package/dist/{explain-cmd-NPKN63XL.js → explain-cmd-DBUTPZHA.js} +1 -1
  99. package/dist/{explain-cmd-R3WCNR2A.js → explain-cmd-NWIYH5MI.js} +1 -1
  100. package/dist/{extract-bind-CISTQFI3.js → extract-bind-3SWPBZX6.js} +3 -3
  101. package/dist/{extract-cmd-HG3DHHSL.js → extract-cmd-HEX7F4IS.js} +1 -1
  102. package/dist/{gaps-cmd-XLVUFSTY.js → gaps-cmd-CKCHH3HQ.js} +1 -1
  103. package/dist/{generate-headless-4VJMAHCU.js → generate-headless-LZ4HRSQ4.js} +2 -2
  104. package/dist/index.js +52 -52
  105. package/dist/ingest-FIIO67ZN.js +2 -0
  106. package/dist/ingest-cmd-KRPZVB7W.js +7 -0
  107. package/dist/{interactive-bind-IXFRXBBL.js → interactive-bind-PTAZVCE7.js} +3 -3
  108. package/dist/{lifecycle-cmd-VTFZ3TF2.js → lifecycle-cmd-32LG364Q.js} +1 -1
  109. package/dist/{list-cmd-KXL4WQII.js → list-cmd-UTZ2PQUK.js} +1 -1
  110. package/dist/{list-commands-BJYJ34HT.js → list-commands-WIVODSEL.js} +1 -1
  111. package/dist/{logical-ids-LMBNMENR.js → logical-ids-I7B3VJEH.js} +1 -1
  112. package/dist/login-flow-GX7CTVWN.js +2 -0
  113. package/dist/{maintenance-cmd-UJG4LPWD.js → maintenance-cmd-BZAGSYGI.js} +1 -1
  114. package/dist/{persist-recorded-session-QR7RVAXR.js → persist-recorded-session-J6Z2SCTT.js} +1 -1
  115. package/dist/pipeline-HT7FCEXA.js +2 -0
  116. package/dist/readmodel-S5RAQH3F.js +2 -0
  117. package/dist/{reconcile-cmd-E2MMQM7Z.js → reconcile-cmd-2VHBKFA5.js} +1 -1
  118. package/dist/{recording-banner-QAIKLV6E.js → recording-banner-IRFMIZSJ.js} +1 -1
  119. package/dist/{require-project-folder-OANMHOVE.js → require-project-folder-XSBJGIVF.js} +1 -1
  120. package/dist/{revert-FRXNIP5R.js → revert-RQJE56HF.js} +1 -1
  121. package/dist/{review-cmd-2FCGP55U.js → review-cmd-7LXGYHHQ.js} +1 -1
  122. package/dist/run-4LTYFTF2.js +2 -0
  123. package/dist/run-YGJZ2SXX.js +2 -0
  124. package/dist/{run-test-md-5E53A5DT.js → run-test-md-QCERS7FQ.js} +2 -2
  125. package/dist/{skill-installer-LGEIIQ4Q.js → skill-installer-WAVEVCSG.js} +1 -1
  126. package/dist/{spawner-6FHAXNOA.js → spawner-YNYB4Z7K.js} +1 -1
  127. package/dist/tcg-generate-D35EMRMQ.js +2 -0
  128. package/dist/{testmd-actions-2OFH5GRJ.js → testmd-actions-NB5Z6QJ3.js} +1 -1
  129. package/dist/token-refresh-OY3WLAKD.js +2 -0
  130. package/dist/{validate-basic-Z46MAH2G.js → validate-basic-IJKKRQRU.js} +1 -1
  131. package/dist/{version-check-64M5JQQ7.js → version-check-O5GYZYTP.js} +1 -1
  132. package/dist/{view-cmd-PG66UQK7.js → view-cmd-GQBFCPDL.js} +1 -1
  133. package/dist/{walk-session-7PM2RXEF.js → walk-session-OPAEV4WR.js} +1 -1
  134. package/package.json +6 -6
  135. package/dist/ChatSurface-PLXUGRBV.js +0 -8
  136. package/dist/SingleShotApp-Z2HGSZXG.js +0 -2
  137. package/dist/TestMdRunView-B4IZHRDT.js +0 -2
  138. package/dist/chat-controller-M4QYRH7Y.js +0 -2
  139. package/dist/chunk-26H3PDVN.js +0 -4
  140. package/dist/chunk-2KS2YRIS.js +0 -2
  141. package/dist/chunk-2OQLMW3F.js +0 -7
  142. package/dist/chunk-4OSW2WEN.js +0 -61
  143. package/dist/chunk-GLS46X7N.js +0 -5
  144. package/dist/chunk-JHHMXU76.js +0 -2
  145. package/dist/chunk-KFUZYEHX.js +0 -2
  146. package/dist/chunk-RLZA4VJT.js +0 -4
  147. package/dist/chunk-ZPENY2Q3.js +0 -4
  148. package/dist/docx-convert-IAX54REO.js +0 -2
  149. package/dist/ingest-UAIKHOB4.js +0 -2
  150. package/dist/ingest-cmd-7HJLRLMG.js +0 -4
  151. package/dist/login-flow-KW5T7WRJ.js +0 -2
  152. package/dist/pipeline-L6V24KGN.js +0 -2
  153. package/dist/readmodel-AGAPK2AI.js +0 -2
  154. package/dist/run-FYJZCWYS.js +0 -2
  155. package/dist/run-IOBBB7GN.js +0 -2
  156. package/dist/tcg-generate-CEDA6DZJ.js +0 -2
  157. package/dist/token-refresh-R75DGT4X.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as l}from"./chunk-RZ4F3BHX.js";import{a,c,f as o}from"./chunk-2KS2YRIS.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
2
+ import{a as l}from"./chunk-RZ4F3BHX.js";import{a,c,f as o}from"./chunk-B4LLKQTK.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{f as He}from"./chunk-K7USHLVZ.js";import{a as he,e as Be,g as je,h as We}from"./chunk-ZFFRHV5U.js";import{a as Te,b as Ne}from"./chunk-JFAFKHDX.js";import{a as Ge,b as qe,c as Le}from"./chunk-J44RN3FB.js";import{a as Me}from"./chunk-GG43HSU2.js";import{c as Ie}from"./chunk-OSALXGD4.js";import{b as Pe}from"./chunk-JHHMXU76.js";import{a as se,b as Ae}from"./chunk-DNNZ353O.js";import{b as Fe}from"./chunk-YKTYVJBN.js";import{a as Ue}from"./chunk-CVOGP253.js";import{b as Oe}from"./chunk-FHKDTM5L.js";import{a as V}from"./chunk-NVGBE2DR.js";import{a as R}from"./chunk-SDRFTIRU.js";import{e as z,f as re}from"./chunk-A46NBRAP.js";import{b as Ee}from"./chunk-IAHKTEET.js";import{d as j}from"./chunk-5YPBPZUR.js";import{a as Re}from"./chunk-5EOX4MEY.js";import{appendFileSync as ot,mkdirSync as pe,writeFileSync as _e}from"fs";import{dirname as nt,extname as at,join as U}from"path";var E=class extends Error{code;constructor(e,c){super(`${e}: ${c}`),this.name="ProposalAdapterError",this.code=e}};function ze(s){return s.version===2}function Ve(s,e){if(s.read_basis.length!==1)throw new E("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${s.read_basis.length}`);let c=s.read_basis[0],u=s.use_cases.map(i=>{if(i.cite.length!==1)throw new E("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);let g=i.cite[0];if(g.source_id!==c.source_id)throw new E("SOURCE_MISMATCH",`${i.temp_ref}: cite source ${g.source_id} != read_basis source ${c.source_id} (single-source)`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:{anchor:g.anchor,quote:g.quote},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((d,_)=>{if(d.cite.source_id!==c.source_id)throw new E("SOURCE_MISMATCH",`${i.temp_ref}.criteria[${_}]: cite source ${d.cite.source_id} != read_basis source ${c.source_id} (single-source)`);return{text:d.text,cite:{anchor:d.cite.anchor,quote:d.cite.quote}}})}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:i.updated.criteria.map((d,_)=>{if(d.cite.source_id!==c.source_id)throw new E("SOURCE_MISMATCH",`${i.temp_ref}.updated.criteria[${_}]: cite source ${d.cite.source_id} != read_basis source ${c.source_id} (single-source)`);return{text:d.text,cite:{anchor:d.cite.anchor,quote:d.cite.quote}}})}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:c.source_id,source_cid:c.source_cid},use_cases:u}}function Je(s){let{contextDir:e,graph:c}=s,u=s.maxDigestBytes??4096,i={},g=[];for(let[l,f]of c.heads){if(i[l]=f,typeof f!="string")continue;let x=c.mediaOf(f),k=c.getNode(f)?.content?.blob;if(typeof k=="string")if(x.format==="image")g.push({source_id:l,cid:f,format:"image",blobRef:{path:V(e,k),cid:k}});else{let n=se(e,c,f)?.toString("utf8")??"";g.push({source_id:l,cid:f,format:x.format,text:n})}}g.sort((l,f)=>l.source_id<f.source_id?-1:1);let d=[];for(let l of c.byLabel(j.STYLENOTE).sort((f,x)=>f.cid<x.cid?-1:1))c.superseded.has(l.cid)||d.push(`\u2022 ${String(l.content.statement)} [${String(l.content.learned_from_kind)}]`);let _="";for(let l of d){if(Buffer.byteLength(_+l+`
2
+ import{f as He}from"./chunk-K7USHLVZ.js";import{a as he,e as Be,g as je,h as We}from"./chunk-JSF5JYZC.js";import{a as Ge,b as qe,c as Le}from"./chunk-J44RN3FB.js";import{a as Te,b as Ne}from"./chunk-JFAFKHDX.js";import{b as Fe}from"./chunk-YKTYVJBN.js";import{a as Ue}from"./chunk-CVOGP253.js";import{a as Me}from"./chunk-GG43HSU2.js";import{c as Ie}from"./chunk-FMR2KPSK.js";import{c as Pe}from"./chunk-V3UE6RJP.js";import{a as se,b as Ae}from"./chunk-DNNZ353O.js";import{b as Oe}from"./chunk-FHKDTM5L.js";import{a as V}from"./chunk-NVGBE2DR.js";import{a as R}from"./chunk-7E24OCGX.js";import{e as z,f as re}from"./chunk-6W6AIDLJ.js";import{d as j}from"./chunk-5YPBPZUR.js";import{b as Ee}from"./chunk-IAHKTEET.js";import{a as Re}from"./chunk-5EOX4MEY.js";import{appendFileSync as ot,mkdirSync as pe,writeFileSync as _e}from"fs";import{dirname as nt,extname as at,join as U}from"path";var E=class extends Error{code;constructor(e,c){super(`${e}: ${c}`),this.name="ProposalAdapterError",this.code=e}};function ze(s){return s.version===2}function Ve(s,e){if(s.read_basis.length!==1)throw new E("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${s.read_basis.length}`);let c=s.read_basis[0],u=s.use_cases.map(i=>{if(i.cite.length!==1)throw new E("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);let g=i.cite[0];if(g.source_id!==c.source_id)throw new E("SOURCE_MISMATCH",`${i.temp_ref}: cite source ${g.source_id} != read_basis source ${c.source_id} (single-source)`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:{anchor:g.anchor,quote:g.quote},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((d,_)=>{if(d.cite.source_id!==c.source_id)throw new E("SOURCE_MISMATCH",`${i.temp_ref}.criteria[${_}]: cite source ${d.cite.source_id} != read_basis source ${c.source_id} (single-source)`);return{text:d.text,cite:{anchor:d.cite.anchor,quote:d.cite.quote}}})}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:i.updated.criteria.map((d,_)=>{if(d.cite.source_id!==c.source_id)throw new E("SOURCE_MISMATCH",`${i.temp_ref}.updated.criteria[${_}]: cite source ${d.cite.source_id} != read_basis source ${c.source_id} (single-source)`);return{text:d.text,cite:{anchor:d.cite.anchor,quote:d.cite.quote}}})}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:c.source_id,source_cid:c.source_cid},use_cases:u}}function Je(s){let{contextDir:e,graph:c}=s,u=s.maxDigestBytes??4096,i={},g=[];for(let[l,f]of c.heads){if(i[l]=f,typeof f!="string")continue;let x=c.mediaOf(f),k=c.getNode(f)?.content?.blob;if(typeof k=="string")if(x.format==="image")g.push({source_id:l,cid:f,format:"image",blobRef:{path:V(e,k),cid:k}});else{let n=se(e,c,f)?.toString("utf8")??"";g.push({source_id:l,cid:f,format:x.format,text:n})}}g.sort((l,f)=>l.source_id<f.source_id?-1:1);let d=[];for(let l of c.byLabel(j.STYLENOTE).sort((f,x)=>f.cid<x.cid?-1:1))c.superseded.has(l.cid)||d.push(`\u2022 ${String(l.content.statement)} [${String(l.content.learned_from_kind)}]`);let _="";for(let l of d){if(Buffer.byteLength(_+l+`
3
3
  `,"utf8")>u)break;_+=l+`
4
4
  `}return{read_basis:i,sources:g,styleNoteDigest:_}}function Ke(s,e){let c=Je({contextDir:s,graph:e}).styleNoteDigest;return c.length>0?c:void 0}function ct(s,e){let c=(s.images??[]).filter(u=>u.delivery==="selected");if(c.length!==0)return c.map(u=>({ref:u.ref,...u.page!==void 0?{page:u.page}:{},...u.loc!==void 0?{loc:u.loc}:{},media_type:u.media_type,blob_ref:{path:V(e,u.blob),cid:u.blob}}))}function dt(s){return s.length>8&&s[0]===137&&s[1]===80&&s[2]===78&&s[3]===71?"image/png":s.length>3&&s[0]===255&&s[1]===216&&s[2]===255?"image/jpeg":s.length>12&&s.toString("ascii",0,4)==="RIFF"&&s.toString("ascii",8,12)==="WEBP"?"image/webp":null}function Xe(s){return s.toISOString().replace(/[-:]/g,"").slice(0,15)}function ut(s){return s.startsWith("su-conv-")?`conv-${Ee(Buffer.from(s,"utf8")).slice(0,8)}`:s}function et(s){return s.source_id.startsWith("su-conv-")?"the conversation":s.source_id}function lt(s,e,c){return`reading ${et(s)}${c>1?` (source ${e} of ${c})`:""}`}function J(s){return s.toLowerCase().trim().replace(/\s+/g," ")}function Ye(s,e){let c=new Map,u=new Map,i=new Map;for(let{cid:d,content:_}of e.byLabel(j.USECASE)){if(e.superseded.has(d))continue;(e.trust.get(d)==="archived"?i:u).set(J(String(_.title??"")),d)}let g=d=>e.trust.get(d)==="archived"?{cid:d,archived:!0,reason:e.archivedReason.get(d)}:{cid:d};for(let d of s.use_cases){if(d.matches_existing){let f=d.matches_existing.cid;if(e.superseded.has(f)){let x=e.tipOf(f);f=e.superseded.has(x)?null:x}if(f!==null){c.set(d.temp_ref,g(f));continue}}let _=u.get(J(d.title));if(_){c.set(d.temp_ref,{cid:_});continue}let l=i.get(J(d.title));l&&c.set(d.temp_ref,g(l))}return c}var Qe=/^(\S+)\.criteria\[(\d+)\]/;function mt(s,e,c){if(e.length===0||!e.every(i=>Qe.test(i.detail)))return!1;let u=new Map;for(let i of e){let g=Qe.exec(i.detail),d=u.get(g[1])??new Set;d.add(Number(g[2])),u.set(g[1],d)}for(let i of s.use_cases){let g=u.get(i.temp_ref);g?.size&&(i.criteria=(i.criteria??[]).filter((d,_)=>!g.has(_)),c(`${i.temp_ref}: dropped ${g.size} criteria with unverifiable cites \u2014 committed without them (criteria are hints, not oracles)`))}return!0}async function Ze(s,e,c,u,i=()=>{},g){let d=(_,l)=>i(_,l,s.session_id);return je(s,e,c,u,i,{async onProposalEvent(_){let l=_,f=null,x=null;if(ze(l))try{f=Ve(l,s.read_basis),d("adapter",{ok:!0,use_cases:f.use_cases.length})}catch(k){x=k instanceof E?k.message:String(k),d("adapter",{ok:!1,error:x})}else f=l;return f&&f.use_cases.length===0&&e.out("warning: the agent proposed ZERO use-cases for this source"),f&&g&&await g(f),{proposal:f,error:x}}})}var gt=new Set(["agent","ci","override"]);async function Jt(s,e){let c=s.mode??"interactive";if(c==="interactive"){if(!e.isTTY)return e.out("extract: --mode interactive needs a TTY (use --mode agent|ci|override headless)"),2}else if(!gt.has(c))return e.out(`extract: unknown mode "${c}" \u2014 interactive | agent | ci | override`),2;let u=e.telemetry?.enabled?e.telemetry:void 0,i=Xe(e.now?.()??new Date),g=u?Re(u.ids.context_instance_id??null,"extract",u.ids.session_id):U(e.contextDir,"logs",`extract-${i}.log`);pe(nt(g),{recursive:!0});let d=`run-${i}-${Math.random().toString(36).slice(2,8)}`,_=t=>t==="error"||t==="failed_proposal"?"error":t==="repair_respawn"?"warn":"info",l=(t,a,m)=>{try{ot(g,JSON.stringify({ts:new Date().toISOString(),level:_(t),run_id:d,...u?{user_session_id:u.ids.session_id}:{},...m?{session_id:m}:{},kind:t,data:a})+`
5
5
  `)}catch{}u?.wireTrace(t,a,m)};e.out(`trace: ${he(g)}`),u&&e.out(u.banner()),e.emit?.({type:"run_start",mode:c,trace:g});let f=Fe();if(f&&e.out(f),e.preflightTurn){let t=await e.preflightTurn();if(l("preflight",t),!t.ok)return e.out(t.message??"error: turn-endpoint preflight failed"),e.emit?.({type:"error",message:t.message??"error: turn-endpoint preflight failed",code:"PREFLIGHT"}),2}let x=R(e.contextDir),k=Ke(e.contextDir,x);if(s.source){if(s.resume){let a="error: --source cannot be combined with --resume (the resumed session already has its scope)";return e.out(a),e.emit?.({type:"error",message:a,code:"SOURCE_WITH_RESUME"}),2}let t=x.heads.get(s.source);if(typeof t!="string"){let a=t===null?`error: --source ${s.source} was ingested but is retired \u2014 re-ingest it to extract again`:`error: --source ${s.source} is not an ingested source (kane-cli context list shows them)`;return e.out(a),e.emit?.({type:"error",message:a,code:"SOURCE_UNKNOWN"}),2}}let n=null;if(s.resume){try{n=Le(e.contextDir,s.resume,x)}catch(m){return e.out(`error: ${m instanceof Error?m.message:String(m)}`),e.emit?.({type:"error",message:`error: ${m instanceof Error?m.message:String(m)}`}),1}let t=n.handle.state.change_basis;if(t&&(x.heads.get(t.source_id)??null)!==t.new_head){let m=`error: ${t.source_id} moved while this reconcile extraction was paused \u2014 its recorded change context no longer matches; re-run kane-cli maintain reconcile against the current file (session ${s.resume} is defunct and can be ignored)`;return e.out(m),e.emit?.({type:"error",message:m,code:"CHANGE_BASIS_MOVED"}),n.handle.release(),2}n.staleBasis.length>0&&e.out(`note: changed since the pause: ${n.staleBasis.join(", ")} \u2014 re-presented items may be stale`);let a=n.handle.state.held_receipts??[];if(a.length>0)if(e.chat?.holdReceipt)for(let m of a)e.chat.holdReceipt(m);else e={...e,initialMessage:[a.join(`
@@ -0,0 +1,7 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as E}from"./chunk-TDPWFYTJ.js";import{a as S}from"./chunk-T7ZPMTGS.js";import{a as v}from"./chunk-A2IQRVPR.js";import{e as _,j as y}from"./chunk-B4LLKQTK.js";import{spawn as T,execSync as h}from"child_process";import{appendFileSync as N,existsSync as m,mkdirSync as O}from"fs";import{homedir as M}from"os";import{join as I,resolve as i,dirname as p}from"path";import{fileURLToPath as L}from"url";import{createInterface as C}from"readline";async function*R(e){let n=C({input:e,crlfDelay:1/0});for await(let s of n){let a=s.trim();if(a)try{let t=JSON.parse(a);t&&typeof t.type=="string"&&(yield t)}catch{}}}function x(e){return e==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_BIFURCATION_PHASES:"1"},unset:["V16_NETWORK_WS","V16_NETWORK_SSE"]}:{set:{V16_BIFURCATION_PHASES:"1"},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_NETWORK_WS","V16_NETWORK_SSE"]}}function A(e){return e?{set:{},unset:["V16_AGENT_SKIP_CP_FINAL"]}:{set:{V16_AGENT_SKIP_CP_FINAL:"true"},unset:[]}}function w(e){return e==="dom"?{set:{V16_AGENT_ENABLE_TEXTUAL_VISUAL:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_TEXTUAL_VISUAL"]}}var c=p(L(import.meta.url));function P(){for(let e of["python3","python"])try{return h(`${e} --version`,{stdio:"ignore"}),e}catch{}return null}function V(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",s={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"linux-arm64":["@testmuai/kane-cli-linux-arm64","@lambdatestincprivate/kane-cli-linux-arm64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},a=`${process.platform}-${process.arch}`,t=s[a];if(t)for(let r of t){let o=[i(c,"..","node_modules",r,"bin",n),i(c,"..","..","node_modules",r,"bin",n),i(c,"..","..","..","node_modules",r,"bin",n),i(c,"..","..","..","..","node_modules",r,"bin",n)];for(let u of o)if(m(u))return{cmd:u,args:[]}}let d=[i(c,"bin",n),i(c,"..","bin",n),i(c,"..","..","..","..","v16-runner","dist",n),i(c,"..","..","..","v16-runner","dist",n),i(c,"..","..","v16-runner","dist",n),i(process.cwd(),"v16-runner","dist",n),i(process.cwd(),"..","v16-runner","dist",n)];for(let r of d)if(m(r))return{cmd:r,args:[]};let l=[i(c,"..","..","v16-runner"),i(c,"..","..","..","..","v16-runner"),i(c,"..","..","..","v16-runner"),i(process.cwd(),"v16-runner"),i(process.cwd(),"..","v16-runner")];for(let r of l)if(m(i(r,"main.py"))){for(let u of[i(r,".venv","bin","python"),i(r,"..",".venv","bin","python"),i(r,"..","browser-agent",".venv","bin","python")])if(m(u))return{cmd:u,args:["main.py"],cwd:r};let o=P();if(o)return{cmd:o,args:["main.py"],cwd:r}}return null}function b(e){return e?I(M(),".testmuai","kaneai","sessions",e,"runner-stderr.log"):null}function k(e){let n=T(e.runner.cmd,e.runner.args,{stdio:["pipe","pipe","pipe"],env:e.env,cwd:e.runner.cwd});n.stdin.on("error",()=>{});let s=b(e.sessionId);if(s)try{O(p(s),{recursive:!0})}catch{}let a=1e5,t="";n.stderr.on("data",u=>{if(t+=u.toString(),t.length>a&&(t=t.slice(-a)),s)try{N(s,u)}catch{}}),n.on("error",u=>{e.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:u.message})});let d=null,l=null,r=new Promise(u=>{n.on("close",(f,g)=>{d=f,l=g?String(g):null,e.log?.("info","RUNNER_EXIT","Runner exited",{code:f,signal:l??"none"}),u({code:f,signal:l})})}),o=R(n.stdout);return{child:n,events:o,getStderr:()=>t,getExitCode:()=>d,getExitSignal:()=>l,exited:r}}function U(e){let n={...process.env};e.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8");let s=v(e.environment);n.V16_SERVER_API_HOST=s.v16ServerHost,n.ATMS_URL=s.tmsBaseUrl.replace(/\/api\/?$/,""),e.username&&e.accessKey&&(n.LT_USERNAME=e.username,n.LT_ACCESS_KEY=e.accessKey),e.sessionId&&(n.TESTMUAI_SESSION_ID=e.sessionId);let a=x(e.mode??"testing");Object.assign(n,a.set);for(let o of a.unset)delete n[o];let t=new S().load(),d=w(e.assertionMode??(t.assertion_mode==="visual"?"visual":"dom"));Object.assign(n,d.set);for(let o of d.unset)delete n[o];let l=e.finalValidation??t.final_validation,r=A(l);Object.assign(n,r.set);for(let o of r.unset)delete n[o];return n}function K(e,n){let s=v(n?.environment),a=E();a!==void 0&&e.ap_mode===void 0&&(e.ap_mode=a),e.telemetry_proxy_url===void 0&&process.env.KANE_TELEMETRY!=="0"&&(e.telemetry_proxy_url=y),e.media_upload===void 0&&e.org_id&&e.username&&e.access_key&&(e.media_upload={url:s.shareApiBaseUrl.replace(/\/$/,"")+"/mfs/v1.0/media/upload",artefacts_host:s.mediaArtefactsHost,org_id:e.org_id,media_dir:_})}function Z(e,n){let s=V();if(!s)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");process.env.KANE_SPAWN_DEBUG&&process.stderr.write(`[spawn-debug] ${JSON.stringify(s)}
3
+ `);let a=U({environment:n?.environment,mode:n?.mode,assertionMode:n?.assertionMode,finalValidation:n?.finalValidation,username:e.username,accessKey:e.access_key,sessionId:e.session_id});K(e,{environment:n?.environment});let t=k({env:a,runner:s,log:n?.log,sessionId:e.session_id}),d=t.child;d.stdin.write(JSON.stringify(e)+`
4
+ `);let l=b(e.session_id);if(l)try{O(p(l),{recursive:!0}),N(l,`--- runner spawn ${new Date().toISOString()} run_index=${e.run_index} ---
5
+ `)}catch{}return{child:d,events:t.events,sendUserResponse(r){let o=JSON.stringify({type:"user_response",answer:r});try{d.stdin.write(o+`
6
+ `)}catch{}},sendCancel(r){let o=JSON.stringify({type:"cancel",reason:r});try{d.stdin.write(o+`
7
+ `)}catch{}},cancel(){d.kill("SIGTERM")},get stderr(){return t.getStderr()},get exitCode(){return t.getExitCode()},get exitSignal(){return t.getExitSignal()},exited:t.exited}}export{V as a,k as b,U as c,K as d,Z as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as t}from"./chunk-5F7PU5AJ.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
2
+ import{a as t}from"./chunk-NR23HZU4.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
@@ -15,7 +15,7 @@ import{a as ri,b as ii}from"./chunk-VOHQA2SP.js";import{b as ei}from"./chunk-NVG
15
15
  ${Ur(S.tokens,y=>o.occurrence(y,T,`${m}:${T}`))}`)}for(let[m,F]of[["footnote",rh],["endnote",ih]]){let w=[];for(let g of h.tokens)g.t==="note-ref"&&g.noteKind===m&&!w.includes(g.id)&&w.push(g.id);if(w.length===0)continue;let T=null;for(let g of f.values())if(F.has(g.type)&&g.targetMode==="Internal"){T=n.resolveTarget(n.mainPart,g.target);break}if(T===null||!n.parts.has(T))continue;let S=os(de(n.parts.get(T)),{partName:T,budget:s});i(T);for(let g of w){let y=S.get(g);if(!y)continue;l+=Hr(y);let x=T;p.push(`[${m} ${g}]
16
16
  ${Ur(y,z=>o.occurrence(z,x,`${m}:${g}`))}`)}}if(l===0&&o.count()===0)throw new et("DOCX_NO_TEXT","no extractable text or images \u2014 nothing citable in this document");let C=p.join("");return C.endsWith(`
17
17
  `)||(C+=`
18
- `),{projection:C,inventory:o.inventory,blobs:o.blobs,delivered:o.delivered,converter:{name:"ooxml-walk",version:Zo,policy:jo}}}export{jo as a,Zo as b,Qo as c,Ko as d,Jo as e,th as f,eh as g,Ur as h,Zh as i};
18
+ `),{projection:C,inventory:o.inventory,blobs:o.blobs,delivered:o.delivered,converter:{name:"ooxml-walk",version:Zo,policy:jo}}}export{rs as a,is as b,jo as c,Zo as d,Qo as e,Ko as f,Jo as g,th as h,eh as i,Ur as j,Zh as k};
19
19
  /*! Bundled license information:
20
20
 
21
21
  xmlchars/xml/1.0/ed5.js:
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as c}from"./chunk-MBXWXBDM.js";import{d as l}from"./chunk-5YPBPZUR.js";function h(f,o,u){let n=o.resolve(u);if(!n)return{target:null,entries:[]};let t=new Set([n.cid]),r=n.cid;for(;o.superseded.has(r);){let s=o.superseded.get(r);if(typeof s!="string"||t.has(s))break;t.add(s),r=s}let d=o.nodeLabel.get(n.cid)??"(unknown)",{records:p}=c(f),i=[];for(let s of p){for(let e of s.nodes)t.has(e.cid)&&i.push({seq:s.seq,ts:s.ts,kind:"minted",detail:`minted ${e.label} ${e.cid}`});for(let e of s.judgements??[])t.has(e.about)&&i.push({seq:s.seq,ts:s.ts,kind:"judgement",rationale:e.rationale,detail:`judgement on ${e.about}`,by:e.by});for(let e of s.review)t.has(e.id)&&i.push({seq:s.seq,ts:s.ts,kind:"review",detail:`${e.resolution}${e.reason?` \u2014 ${e.reason}`:""}`,by:e.by});for(let e of s.supersessions)e.kind==="node"&&(t.has(e.old)||e.new!==null&&t.has(e.new))&&i.push({seq:s.seq,ts:s.ts,kind:"supersession",detail:`${e.old} \u2192 ${String(e.new)} \u2014 ${e.reason}`,by:e.by});for(let e of s.names??[])t.has(e.cid)&&i.push({seq:s.seq,ts:s.ts,kind:"name",detail:`named ${e.slug}`,by:e.by});if(d===l.SOURCE)for(let[e,a]of Object.entries(s.source_head_moves))(t.has(a??"")||o.heads.get(e)!==void 0&&t.has(n.cid)&&e===o.getNode(n.cid)?.content?.source_id)&&i.push({seq:s.seq,ts:s.ts,kind:"head_move",detail:`${e} head \u2192 ${String(a)}`})}return i.sort((s,e)=>e.seq-s.seq),{target:{cid:n.cid,tip:n.tip,label:d,slug:o.nameOf.get(n.cid)},entries:i}}export{h as a};
2
+ import{b as c}from"./chunk-J2KSZUOO.js";import{d as l}from"./chunk-5YPBPZUR.js";function h(f,o,u){let n=o.resolve(u);if(!n)return{target:null,entries:[]};let t=new Set([n.cid]),r=n.cid;for(;o.superseded.has(r);){let s=o.superseded.get(r);if(typeof s!="string"||t.has(s))break;t.add(s),r=s}let d=o.nodeLabel.get(n.cid)??"(unknown)",{records:p}=c(f),i=[];for(let s of p){for(let e of s.nodes)t.has(e.cid)&&i.push({seq:s.seq,ts:s.ts,kind:"minted",detail:`minted ${e.label} ${e.cid}`});for(let e of s.judgements??[])t.has(e.about)&&i.push({seq:s.seq,ts:s.ts,kind:"judgement",rationale:e.rationale,detail:`judgement on ${e.about}`,by:e.by});for(let e of s.review)t.has(e.id)&&i.push({seq:s.seq,ts:s.ts,kind:"review",detail:`${e.resolution}${e.reason?` \u2014 ${e.reason}`:""}`,by:e.by});for(let e of s.supersessions)e.kind==="node"&&(t.has(e.old)||e.new!==null&&t.has(e.new))&&i.push({seq:s.seq,ts:s.ts,kind:"supersession",detail:`${e.old} \u2192 ${String(e.new)} \u2014 ${e.reason}`,by:e.by});for(let e of s.names??[])t.has(e.cid)&&i.push({seq:s.seq,ts:s.ts,kind:"name",detail:`named ${e.slug}`,by:e.by});if(d===l.SOURCE)for(let[e,a]of Object.entries(s.source_head_moves))(t.has(a??"")||o.heads.get(e)!==void 0&&t.has(n.cid)&&e===o.getNode(n.cid)?.content?.source_id)&&i.push({seq:s.seq,ts:s.ts,kind:"head_move",detail:`${e} head \u2192 ${String(a)}`})}return i.sort((s,e)=>e.seq-s.seq),{target:{cid:n.cid,tip:n.tip,label:d,slug:o.nameOf.get(n.cid)},entries:i}}export{h as a};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as b,d as _}from"./chunk-NVGBE2DR.js";import{a as g,c as h}from"./chunk-L4JIMNKW.js";import{e as S}from"./chunk-MBXWXBDM.js";import{d as f,f as v}from"./chunk-5YPBPZUR.js";var V=n=>`conv#turn=${n}`;function E(n,o){for(let t of n.split(`
2
+ import{c as b,d as _}from"./chunk-NVGBE2DR.js";import{a as g,c as h}from"./chunk-6HYW5RFX.js";import{e as S}from"./chunk-J2KSZUOO.js";import{d as f,f as v}from"./chunk-5YPBPZUR.js";var V=n=>`conv#turn=${n}`;function E(n,o){for(let t of n.split(`
3
3
  `))if(t.trim())try{let r=JSON.parse(t);if(r.turn===o)return r.text}catch{}return null}var y={format:"conversation",media_type:"text/x-conversation",anchors_supported:["#turn="]};function $(n){let{contextDir:o,graph:t,sessionStamp:r}=n,e=`su-conv-${r}`,u=t.heads.get(e);if(typeof u=="string")return{record:null,errors:[{code:"CONV_SOURCE_EXISTS",detail:`${e} already exists \u2014 resume it`}],sourceId:e,cid:u};let i=b(o,Buffer.from("","utf8")),c=h(e,i),a=v("source",c);if(a.length>0)return{record:null,errors:a.map(s=>({code:s.code,detail:s.detail})),sourceId:e,cid:""};let d=g("source",c);return{record:S(o,{ts:new Date().toISOString(),proposal_id:null,nodes:[{cid:d,label:f.SOURCE,content:c}],edges:[],review:[],supersessions:[],source_head_moves:{[e]:d},media:{[e]:y},conv:{source_id:e,turn:0,append_of:null}},{expectPrev:t.latestHash}).record,errors:null,sourceId:e,cid:d}}function G(n){let{contextDir:o,graph:t,sourceId:r,text:e,force:u}=n,i=t.heads.get(r),c=t.convChains.get(r);if(typeof i!="string"||!c)return{record:null,errors:[{code:"CONV_SOURCE_MISSING",detail:`${r} is not a live conversation source`}]};let d=t.getNode(i)?.content?.blob;if(typeof d!="string")return{record:null,errors:[{code:"CONV_SOURCE_MISSING",detail:`${r} head node unreadable`}]};let l=_(o,d)?.toString("utf8")??"",s=c.turns;if(!u&&s>0&&E(l,s)===e)return{record:null,errors:null,turn:s,cid:i,idempotent:!0};let p=s+1,C=`${l}${JSON.stringify({turn:p,text:e})}
4
4
  `,O=b(o,Buffer.from(C,"utf8")),x=h(r,O),m=g("source",x);return{record:S(o,{ts:new Date().toISOString(),proposal_id:null,nodes:[{cid:m,label:f.SOURCE,content:x}],edges:[],review:[],supersessions:[],source_head_moves:{[r]:m},media:{[r]:y},conv:{source_id:r,turn:p,append_of:i}},{expectPrev:t.latestHash}).record,errors:null,turn:p,cid:m,idempotent:!1}}export{V as a,E as b,$ as c,G as d};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as q}from"./chunk-L4JIMNKW.js";import{a as b,b as S,d as C}from"./chunk-MBXWXBDM.js";import{a as R,e as I,f as j,g as L,h as F}from"./chunk-5YPBPZUR.js";import{existsSync as E,mkdirSync as P,readFileSync as k,renameSync as J,rmSync as W,writeFileSync as K}from"fs";import{dirname as V,join as y}from"path";var O=o=>y(o,"derived"),D=o=>y(O(o),"index.json");function U(o,e){let r=e.startsWith("sha256:")?e.slice(7):e;return y(O(o),"nodes",r.slice(0,2),r.slice(2)+".json")}function $(){return{applied:{seq:0,hash:null},heads:{},trust:{},nodeLabel:{},forward:{},extracted:[],design_of:{},exec:{},superseded:{},names:{},archivedReason:{},appliedEvents:[],conv:{},media:{}}}function M(o){let e=D(o);if(!E(e))return null;try{let r=JSON.parse(k(e,"utf8"));return r.superseded===void 0||r.names===void 0||r.archivedReason===void 0||r.appliedEvents===void 0||r.conv===void 0||r.media===void 0||r.exec===void 0||r.reverse!==void 0?null:r}catch{return null}}function T(o,e){P(V(o),{recursive:!0});let r=`${o}.tmp-${process.pid}`;K(r,e),J(r,o)}function w(o,e,r,p,f={}){let u=f.writeNodeFiles!==!1,h=new Set(e.extracted),m=new Set(e.appliedEvents);r.forEach((i,v)=>{for(let n of i.nodes){let s=U(o,n.cid);u&&!E(s)&&T(s,JSON.stringify({label:n.label,content:n.content})+`
2
+ import{a as q}from"./chunk-6HYW5RFX.js";import{a as b,b as S,d as C}from"./chunk-J2KSZUOO.js";import{a as R,e as I,f as j,g as L,h as F}from"./chunk-5YPBPZUR.js";import{existsSync as E,mkdirSync as P,readFileSync as k,renameSync as J,rmSync as W,writeFileSync as K}from"fs";import{dirname as V,join as y}from"path";var O=o=>y(o,"derived"),D=o=>y(O(o),"index.json");function U(o,e){let r=e.startsWith("sha256:")?e.slice(7):e;return y(O(o),"nodes",r.slice(0,2),r.slice(2)+".json")}function $(){return{applied:{seq:0,hash:null},heads:{},trust:{},nodeLabel:{},forward:{},extracted:[],design_of:{},exec:{},superseded:{},names:{},archivedReason:{},appliedEvents:[],conv:{},media:{}}}function M(o){let e=D(o);if(!E(e))return null;try{let r=JSON.parse(k(e,"utf8"));return r.superseded===void 0||r.names===void 0||r.archivedReason===void 0||r.appliedEvents===void 0||r.conv===void 0||r.media===void 0||r.exec===void 0||r.reverse!==void 0?null:r}catch{return null}}function T(o,e){P(V(o),{recursive:!0});let r=`${o}.tmp-${process.pid}`;K(r,e),J(r,o)}function w(o,e,r,p,f={}){let u=f.writeNodeFiles!==!1,h=new Set(e.extracted),m=new Set(e.appliedEvents);r.forEach((i,v)=>{for(let n of i.nodes){let s=U(o,n.cid);u&&!E(s)&&T(s,JSON.stringify({label:n.label,content:n.content})+`
3
3
  `),!(n.cid in e.trust)&&n.content.derived===!0&&(e.trust[n.cid]="derived"),e.nodeLabel[n.cid]=n.label}i.proposal_id!=null&&typeof i.extraction_of=="string"&&h.add(i.extraction_of),i.design_of&&((e.design_of??={})[i.design_of.uc_cid]={engine:i.design_of.engine,seq:i.seq});for(let n of i.executions??[])((e.exec??={})[n.about]??=[]).push(n);for(let n of i.edges){let{quote:s,...t}=n.props,c=e.forward[n.src]??=[];c.some(a=>a.ecid===n.ecid)||c.push({...n,props:t}),i.proposal_id!=null&&n.type===I.DERIVES&&typeof n.props.source_cid=="string"&&h.add(n.props.source_cid)}for(let n of i.review)n.resolution==="approved"||n.resolution==="edited"?(e.trust[n.id]="trusted",delete e.archivedReason[n.id]):n.resolution==="rejected"?(e.trust[n.id]="archived",n.reason?e.archivedReason[n.id]=n.reason:delete e.archivedReason[n.id]):n.resolution==="reset"&&(e.trust[n.id]="derived",delete e.archivedReason[n.id]);for(let n of i.supersessions)n.kind==="node"?n.new===n.old?delete e.superseded[n.old]:e.superseded[n.old]=n.new:e.superseded[n.ecid]=null;for(let n of i.names??[])e.names[n.slug]=n.cid;for(let[n,s]of Object.entries(i.source_head_moves))e.heads[n]=s;for(let n of i.event_ids??[])m.add(n);if(i.media)for(let[n,s]of Object.entries(i.media)){let t=i.source_head_moves[n];typeof t=="string"&&(e.media[t]=s)}if(i.conv){let n=i.source_head_moves[i.conv.source_id];if(typeof n=="string"){let s=e.conv[i.conv.source_id],t=s&&s.chain.length>0?s.chain[s.chain.length-1]:null;i.conv.append_of===t?e.conv[i.conv.source_id]={turns:i.conv.turn,chain:[...s?.chain??[],n]}:e.conv[i.conv.source_id]={turns:i.conv.turn,chain:[n]}}}for(let[n,s]of Object.entries(i.source_head_moves))i.conv?.source_id!==n&&e.conv[n]!==void 0&&(e.conv[n]=typeof s=="string"?{turns:e.conv[n].turns,chain:[s]}:{turns:e.conv[n].turns,chain:[]});e.applied={seq:i.seq,hash:p[v]}}),e.extracted=[...h].sort(),e.appliedEvents=[...m].sort()}function x(o,e){T(D(o),JSON.stringify(e)+`
4
4
  `)}function Y(o){let e=y(o,"meta.json");if(E(e))try{let r=JSON.parse(k(e,"utf8"));if(r.schema!==R||r.canonicalizer!=="v1")throw new b(`schema fence: store is ${r.schema}/${r.canonicalizer}, this build is ${R}/${"v1"} \u2014 migrate explicitly (kane-cli context rebuild after upgrading)`)}catch(r){throw r instanceof b?r:new b(`corrupt meta.json in ${o} \u2014 fix or remove it`)}}function z(o){Y(o);let e=M(o);if(e===null){e=$();let{records:f,hashes:u}=S(o);return w(o,e,f,u),x(o,e),e}let{records:r,hashes:p}=C(o,e.applied.seq,e.applied.hash);return r.length>0&&(w(o,e,r,p),x(o,e)),e}function X(o){return W(O(o),{recursive:!0,force:!0}),z(o)}function ee(o){let e=[],r=[],p=[];try{({records:r,hashes:p}=S(o))}catch(s){return{ok:!1,issues:[s instanceof b?s.message:String(s)],records:0}}let f=$();w(o,f,r,p,{writeNodeFiles:!1});let u=M(o),h=0,m=f;if(u!==null&&u.applied.seq<r.length){let s=u.applied.seq;u.applied.hash===(s===0?null:p[s-1])&&(h=r.length-s,m=$(),w(o,m,r.slice(0,s),p.slice(0,s),{writeNodeFiles:!1}))}if(u===null)e.push("derived/index.json missing or corrupt (run kane-cli context rebuild)");else{let s=t=>JSON.stringify(N(t));for(let t of["applied","heads","trust","nodeLabel","forward","extracted","superseded","names","archivedReason","appliedEvents","conv","media","design_of","exec"])s(m[t])!==s(u[t])&&e.push(`derived drift in index.${t} (run kane-cli context rebuild)`)}let i=new Set;for(let s of Object.values(f.forward))for(let t of s)i.add(t.ecid);let v=new Set;for(let s of r)for(let t of s.supersessions)t.kind==="node"?(t.old in f.nodeLabel||e.push(`SUPERSEDE_UNKNOWN_OLD: ${t.old} (record ${s.seq})`),t.new!==null&&t.new!==t.old&&!(t.new in f.nodeLabel)&&e.push(`SUPERSEDE_UNKNOWN_NEW: ${String(t.new)} (record ${s.seq})`),t.new===t.old?v.delete(t.old):(v.has(t.old)&&e.push(`DOUBLE_SUPERSEDE: ${t.old} re-superseded while live (record ${s.seq})`),v.add(t.old))):i.has(t.ecid)||e.push(`SUPERSEDE_UNKNOWN_ECID: ${t.ecid} (record ${s.seq})`);for(let s of Object.keys(f.superseded)){let t=new Set,c=s;for(;c!==null&&c in f.superseded;){if(t.has(c)){e.push(`SUPERSEDE_CYCLE: chain from ${s} revisits ${c}`);break}t.add(c),c=f.superseded[c]}}for(let[s,t]of Object.entries(f.names))t in f.nodeLabel||e.push(`NAME_UNKNOWN_TARGET: slug ${s} \u2192 ${t} not in the graph`);for(let s of r)for(let t of s.edges){let c=f.nodeLabel[t.src]??"(unknown)",a=f.nodeLabel[t.dst]??"(unknown)";for(let d of F(t.type,c,a,t.props))e.push(`${d.code}: ${t.ecid} ${d.detail}`)}let n=new Map;for(let s of Object.values(f.forward))for(let t of s){if(t.ecid in f.superseded)continue;let c=n.get(t.type)??[];c.push(t),n.set(t.type,c)}for(let[s,t]of n){let c=L(s);if(c?.acyclic){let a=new Map;for(let l of t)a.set(l.src,[...a.get(l.src)??[],l.dst]);let d=new Map,g=l=>{d.set(l,1);for(let _ of a.get(l)??[])if(d.get(_)===1||d.get(_)===void 0&&g(_))return!0;return d.set(l,2),!1};for(let l of a.keys())if(d.get(l)===void 0&&g(l)){e.push(`EDGE_CYCLE: live ${s} edges form a cycle reachable from ${l}`);break}}if(c?.cardinality==="one-live-per-src"||c?.cardinality==="one-live-per-src-and-dst"){let a=new Map;for(let d of t)d.dst in f.superseded||a.set(d.src,(a.get(d.src)??0)+1);for(let[d,g]of a)g>1&&e.push(`CARDINALITY_VIOLATION: ${g} live ${s} edges from ${d} (one-live-per-src)`)}if(c?.cardinality==="one-live-per-src-and-dst"){let a=new Map;for(let d of t)d.src in f.superseded||d.dst in f.superseded||a.set(d.dst,(a.get(d.dst)??0)+1);for(let[d,g]of a)g>1&&e.push(`CARDINALITY_VIOLATION: ${g} live ${s} edges onto ${d} (one-live-per-dst)`)}}for(let[s,t]of Object.entries(m.nodeLabel)){let c=U(o,s);if(!E(c)){e.push(`missing node file for ${s} (run kane-cli context rebuild)`);continue}try{let a=JSON.parse(k(c,"utf8"));(a.label!==t||q(a.label,a.content)!==s)&&e.push(`node file content mismatch for ${s} (run kane-cli context rebuild)`);for(let d of j(a.label,a.content))e.push(`${d.code}: ${s} ${d.detail}`)}catch{e.push(`corrupt node file for ${s} (run kane-cli context rebuild)`)}}return{ok:e.length===0,issues:e,records:r.length,...h>0?{pending:h}:{}}}function N(o){return Array.isArray(o)?o.map(N):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).sort(([e],[r])=>e<r?-1:1).map(([e,r])=>[e,N(r)])):o}export{U as a,z as b,X as c,ee as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as L}from"./chunk-RFHMDQXZ.js";import{Q as O,S}from"./chunk-OESHJ4J2.js";import{m as P,n as R}from"./chunk-Y5RNCJAN.js";import{y as s}from"./chunk-2KS2YRIS.js";import{a as y}from"./chunk-HCBYKLMW.js";import{a as E,b as o,i as h}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var n=d(B(),1);import{basename as D}from"path";var r=d(y(),1),U="evidence-view-server";function Q({packPath:m,viewerBase:w,onDone:V,openUrl:k}){let[t,a]=(0,n.useState)("ask"),[g,b]=(0,n.useState)(null),[l,p]=(0,n.useState)(null),f=(0,n.useRef)(null),u=(0,n.useRef)(!1),x=async()=>{let e=f.current;f.current=null,e&&(R(U),await e.close())},v=()=>{u.current||(u.current=!0,V())};return h((e,i)=>{u.current||(t==="ask"?e==="y"||e==="Y"?a("starting"):(e==="n"||e==="N"||i.return||i.escape)&&v():t==="serving"&&(e==="q"||e==="Q"||i.escape)&&x().then(v))}),(0,n.useEffect)(()=>{if(t!=="starting")return;let e=!1;return(async()=>{try{let i=D(m),c=await O({packs:new Map([[i,m]]),allowedOrigins:[new URL(w).origin]});if(e){await c.close();return}f.current=c,P(U,()=>{c.close()});let T=S(c.urlFor(i),w);b(T);try{await(k??(q=>L(q)))(T)}catch{p("could not open browser \u2014 open the URL manually")}a("serving")}catch(i){p(`evidence view failed \u2014 ${i.message}`),a("failed")}})(),()=>{e=!0}},[t]),(0,n.useEffect)(()=>{if(t!=="failed")return;let e=setTimeout(v,0);return()=>clearTimeout(e)},[t]),(0,n.useEffect)(()=>()=>{x()},[]),t==="ask"?(0,r.jsxs)(o,{children:["View evidence in browser? ",(0,r.jsx)(o,{color:s.dim,children:"(y/N)"})]}):t==="serving"||t==="starting"?(0,r.jsxs)(E,{flexDirection:"column",children:[g?(0,r.jsxs)(o,{children:["viewer ",(0,r.jsx)(o,{color:s.orange,children:g})]}):(0,r.jsx)(o,{color:s.dim,children:"starting\u2026"}),l?(0,r.jsx)(o,{color:"yellow",children:l}):null,t==="serving"?(0,r.jsx)(o,{color:s.dim,children:"Press q when done"}):null]}):l?(0,r.jsx)(o,{color:"yellow",children:l}):null}export{Q as a};
2
+ import{c as L}from"./chunk-RFHMDQXZ.js";import{Q as O,S}from"./chunk-UXPQRALY.js";import{m as P,n as R}from"./chunk-Y5RNCJAN.js";import{y as s}from"./chunk-B4LLKQTK.js";import{a as y}from"./chunk-HCBYKLMW.js";import{a as E,b as o,i as h}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var n=d(B(),1);import{basename as D}from"path";var r=d(y(),1),U="evidence-view-server";function Q({packPath:m,viewerBase:w,onDone:V,openUrl:k}){let[t,a]=(0,n.useState)("ask"),[g,b]=(0,n.useState)(null),[l,p]=(0,n.useState)(null),f=(0,n.useRef)(null),u=(0,n.useRef)(!1),x=async()=>{let e=f.current;f.current=null,e&&(R(U),await e.close())},v=()=>{u.current||(u.current=!0,V())};return h((e,i)=>{u.current||(t==="ask"?e==="y"||e==="Y"?a("starting"):(e==="n"||e==="N"||i.return||i.escape)&&v():t==="serving"&&(e==="q"||e==="Q"||i.escape)&&x().then(v))}),(0,n.useEffect)(()=>{if(t!=="starting")return;let e=!1;return(async()=>{try{let i=D(m),c=await O({packs:new Map([[i,m]]),allowedOrigins:[new URL(w).origin]});if(e){await c.close();return}f.current=c,P(U,()=>{c.close()});let T=S(c.urlFor(i),w);b(T);try{await(k??(q=>L(q)))(T)}catch{p("could not open browser \u2014 open the URL manually")}a("serving")}catch(i){p(`evidence view failed \u2014 ${i.message}`),a("failed")}})(),()=>{e=!0}},[t]),(0,n.useEffect)(()=>{if(t!=="failed")return;let e=setTimeout(v,0);return()=>clearTimeout(e)},[t]),(0,n.useEffect)(()=>()=>{x()},[]),t==="ask"?(0,r.jsxs)(o,{children:["View evidence in browser? ",(0,r.jsx)(o,{color:s.dim,children:"(y/N)"})]}):t==="serving"||t==="starting"?(0,r.jsxs)(E,{flexDirection:"column",children:[g?(0,r.jsxs)(o,{children:["viewer ",(0,r.jsx)(o,{color:s.orange,children:g})]}):(0,r.jsx)(o,{color:s.dim,children:"starting\u2026"}),l?(0,r.jsx)(o,{color:"yellow",children:l}):null,t==="serving"?(0,r.jsx)(o,{color:s.dim,children:"Press q when done"}):null]}):l?(0,r.jsx)(o,{color:"yellow",children:l}):null}export{Q as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-6MTVGARW.js";import{a as h}from"./chunk-FPFOW6BS.js";import{a as m}from"./chunk-RH4GCEFX.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:p,log:t}=c,e=null,u=null;if(l&&p)e={username:l,access_key:p},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,g=new h(v.controllerBaseUrl,b,y,t),s=await g.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:g,resolvedCreds:s}}export{o as a,k as b};
2
+ import{a as f}from"./chunk-EN7NW7DU.js";import{a as h}from"./chunk-FPFOW6BS.js";import{a as m}from"./chunk-A2IQRVPR.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:p,log:t}=c,e=null,u=null;if(l&&p)e={username:l,access_key:p},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,g=new h(v.controllerBaseUrl,b,y,t),s=await g.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:g,resolvedCreds:s}}export{o as a,k as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{m as r}from"./chunk-A46NBRAP.js";function i(t){return r.test(t)?t.toUpperCase():t}export{i as a};
2
+ import{m as r}from"./chunk-6W6AIDLJ.js";function i(t){return r.test(t)?t.toUpperCase():t}export{i as a};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as C,b as _}from"./chunk-IAHKTEET.js";import{a as g}from"./chunk-5YPBPZUR.js";import{closeSync as $,existsSync as O,fsyncSync as x,mkdirSync as b,openSync as v,readFileSync as y,readdirSync as N,renameSync as P,rmSync as A,writeFileSync as k}from"fs";import{join as p}from"path";var i=class extends Error{};function S(e,r){if(e.schema_version!==void 0&&e.schema_version!==g)throw new i(`record ${r} is stamped ${e.schema_version}, this build reads ${g} \u2014 migrate explicitly`);if(e.parents!==void 0&&!(e.prev_hash===null?e.parents.length===0:e.parents.length===1&&e.parents[0]===e.prev_hash))throw new i(`record ${r}: parents does not mirror prev_hash \u2014 multi-parent records need a DAG-aware reader`)}function F(e){b(e,{recursive:!0});let r=p(e,".lock"),t=Date.now()+2e3;for(;;)try{let n=v(r,"wx");return k(n,`${process.pid}
2
+ import{a as g}from"./chunk-5YPBPZUR.js";import{a as C,b as _}from"./chunk-IAHKTEET.js";import{closeSync as $,existsSync as O,fsyncSync as x,mkdirSync as b,openSync as v,readFileSync as y,readdirSync as N,renameSync as P,rmSync as A,writeFileSync as k}from"fs";import{join as p}from"path";var i=class extends Error{};function S(e,r){if(e.schema_version!==void 0&&e.schema_version!==g)throw new i(`record ${r} is stamped ${e.schema_version}, this build reads ${g} \u2014 migrate explicitly`);if(e.parents!==void 0&&!(e.prev_hash===null?e.parents.length===0:e.parents.length===1&&e.parents[0]===e.prev_hash))throw new i(`record ${r}: parents does not mirror prev_hash \u2014 multi-parent records need a DAG-aware reader`)}function F(e){b(e,{recursive:!0});let r=p(e,".lock"),t=Date.now()+2e3;for(;;)try{let n=v(r,"wx");return k(n,`${process.pid}
3
3
  `),$(n),()=>{try{A(r)}catch{}}}catch(n){if(n.code!=="EEXIST")throw n;if(Date.now()>t)throw new i(`.context is locked by another process \u2014 remove ${r} if that process is gone`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25)}}var J=/^\d{6}-[0-9a-f]{12}\.json$/,f=e=>p(e,"commits");function w(e){return"sha256:"+_(Buffer.from(C(e),"utf8"))}function R(e){let r=f(e);return O(r)?N(r).filter(t=>J.test(t)).sort():[]}function B(e){let r=R(e),t=[],n=[],c=null;return r.forEach((s,h)=>{let d=y(p(f(e),s),"utf8"),o;try{o=JSON.parse(d)}catch(l){throw new i(`corrupt commit record ${s}: ${String(l)}`)}if(o.seq!==h+1)throw new i(`sequence gap: expected seq ${h+1}, ${s} has ${o.seq}`);if(o.prev_hash!==c)throw new i(`broken chain at ${s}: prev_hash ${String(o.prev_hash)} != ${String(c)}`);S(o,s);let m=w(o),a=s.slice(7,19);if(!m.slice(7).startsWith(a))throw new i(`tampered record ${s}: content hash ${m} does not match filename`);t.push(o),n.push(m),c=m}),{records:t,hashes:n}}function E(e){let r=R(e);if(r.length===0)return null;let t=r[r.length-1],n=y(p(f(e),t),"utf8"),c;try{c=JSON.parse(n)}catch(h){throw new i(`corrupt tail record ${t}: ${String(h)}`)}S(c,t);let s=w(c);if(!s.slice(7).startsWith(t.slice(7,19)))throw new i(`tampered tail record ${t}: content hash ${s} does not match filename`);if(c.seq!==r.length)throw new i(`sequence gap at tail: ${r.length} record files but tail seq is ${c.seq}`);return{seq:c.seq,hash:s}}function T(e){return E(e)?.hash??null}function z(e,r,t){let n=R(e);if(n.length<r)throw new i(`derived state is ahead of the record log (applied seq ${r}, ${n.length} records) \u2014 run kane-cli context rebuild`);let c=[],s=[],h=t;for(let d=r;d<n.length;d++){let o=n[d],m=y(p(f(e),o),"utf8"),a;try{a=JSON.parse(m)}catch(u){throw new i(`corrupt commit record ${o}: ${String(u)}`)}if(a.seq!==d+1)throw new i(`sequence gap: expected seq ${d+1}, ${o} has ${a.seq}`);if(a.prev_hash!==h)throw new i(`broken chain at ${o}: prev_hash ${String(a.prev_hash)} != ${String(h)}`);S(a,o);let l=w(a);if(!l.slice(7).startsWith(o.slice(7,19)))throw new i(`tampered record ${o}: content hash ${l} does not match filename`);c.push(a),s.push(l),h=l}return{records:c,hashes:s}}function G(e,r,t={}){let n=F(e);try{return j(e,r,t)}finally{n()}}function j(e,r,t){let n=E(e),c=(n?.seq??0)+1,s=n?.hash??null;if(t.expectPrev!==void 0&&t.expectPrev!==s)throw new i(`concurrent append detected: validated against ${String(t.expectPrev)} but the chain head is ${String(s)} \u2014 re-open and retry`);let h={seq:c,prev_hash:s,...r,schema_version:g,parents:s===null?[]:[s]},d=w(h),o=f(e);b(o,{recursive:!0});let m=`${String(c).padStart(6,"0")}-${d.slice(7,19)}.json`,a=p(o,m),l=a+".tmp",u=v(l,"w");try{k(u,JSON.stringify(h)+`
4
4
  `),x(u)}finally{$(u)}P(l,a);try{let q=v(o,"r");x(q),$(q)}catch{}return{seq:c,hash:d,file:a,record:h}}export{i as a,B as b,T as c,z as d,G as e};
@@ -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-6NWPK2MS.js";import{y as m}from"./chunk-2KS2YRIS.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-5WE4DHXL.js";import{y as m}from"./chunk-B4LLKQTK.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,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as F}from"./chunk-JFAFKHDX.js";import{d as Y,f as Z}from"./chunk-GG43HSU2.js";import{a as J}from"./chunk-DNNZ353O.js";import{a as I}from"./chunk-YKTYVJBN.js";import{a as W}from"./chunk-SDRFTIRU.js";import{b as X}from"./chunk-RGDQMKNJ.js";import{n as K}from"./chunk-A46NBRAP.js";import{a as z}from"./chunk-L4JIMNKW.js";import{e as Q}from"./chunk-MBXWXBDM.js";import{d as U,f as H}from"./chunk-5YPBPZUR.js";import{a as B,c as j}from"./chunk-2KS2YRIS.js";function mt(t){let e=process.env.HOME??"";return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}import{readFileSync as Re,writeFileSync as Ce,renameSync as Te,mkdirSync as Me}from"fs";import{dirname as De,join as Fe}from"path";var O=1,Ne=720*60*1e3;function N(t){return Fe(j,"embeddings",`alias-${t}.json`)}function q(t,e=Date.now()){return t!==null&&e-t.fetchedAt<Ne}function ee(t){try{let e=JSON.parse(Re(t,"utf-8"));return e.wrapperVersion!==O||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:O,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function te(t,e,n=N(t)){let r=ee(n)?.purposes?.[e];return!r||typeof r.alias!="string"||typeof r.dims!="number"||typeof r.fetchedAt!="number"?null:{alias:r.alias,dims:r.dims,fetchedAt:r.fetchedAt}}function ne(t,e,n,s=N(t)){try{Me(De(s),{recursive:!0});let a=ee(s)?.purposes??{};a[e]={alias:n.alias,dims:n.dims,fetchedAt:Date.now()};let o={wrapperVersion:O,writtenByVersion:B,purposes:a},u=`${s}.tmp`;Ce(u,JSON.stringify(o,null,2)+`
2
+ import{d as F}from"./chunk-JFAFKHDX.js";import{a as I}from"./chunk-YKTYVJBN.js";import{d as Y,f as Z}from"./chunk-GG43HSU2.js";import{a as J}from"./chunk-DNNZ353O.js";import{a as W}from"./chunk-7E24OCGX.js";import{b as X}from"./chunk-FRBYGSGJ.js";import{n as K}from"./chunk-6W6AIDLJ.js";import{a as z}from"./chunk-6HYW5RFX.js";import{e as Q}from"./chunk-J2KSZUOO.js";import{d as U,f as H}from"./chunk-5YPBPZUR.js";import{a as B,c as j}from"./chunk-B4LLKQTK.js";function mt(t){let e=process.env.HOME??"";return e&&t.startsWith(e)?`~${t.slice(e.length)}`:t}import{readFileSync as Re,writeFileSync as Ce,renameSync as Te,mkdirSync as Me}from"fs";import{dirname as De,join as Fe}from"path";var O=1,Ne=720*60*1e3;function N(t){return Fe(j,"embeddings",`alias-${t}.json`)}function q(t,e=Date.now()){return t!==null&&e-t.fetchedAt<Ne}function ee(t){try{let e=JSON.parse(Re(t,"utf-8"));return e.wrapperVersion!==O||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:O,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function te(t,e,n=N(t)){let r=ee(n)?.purposes?.[e];return!r||typeof r.alias!="string"||typeof r.dims!="number"||typeof r.fetchedAt!="number"?null:{alias:r.alias,dims:r.dims,fetchedAt:r.fetchedAt}}function ne(t,e,n,s=N(t)){try{Me(De(s),{recursive:!0});let a=ee(s)?.purposes??{};a[e]={alias:n.alias,dims:n.dims,fetchedAt:Date.now()};let o={wrapperVersion:O,writtenByVersion:B,purposes:a},u=`${s}.tmp`;Ce(u,JSON.stringify(o,null,2)+`
3
3
  `),Te(u,s)}catch(r){process.stderr.write(`[embed] Failed to save alias cache: ${r instanceof Error?r.message:String(r)}
4
4
  `)}}function Le(t){return t.TESTMUAI_ENV==="stage"?"stage":"prod"}function re(t){let e=t.env??process.env,n=t.auth?.TESTMUAI_BASIC_AUTH||e.TESTMUAI_BASIC_AUTH;if(n)return{authorization:`Basic ${n}`};let s=t.auth?.TESTMUAI_API_KEY||e.TESTMUAI_API_KEY;return s?{authorization:`Bearer ${s}`}:{}}async function se(t,e={}){let n=e.env??process.env,s=Le(n),r=e.aliasCacheFile??N(s),a=e.now??Date.now,o=te(s,t,r);if(q(o,a()))return{alias:o.alias,dims:o.dims};let d=`${I(n)}/assurance/embed/alias?purpose=${encodeURIComponent(t)}`,m=await(e.fetchImpl??fetch)(d,{method:"GET",headers:re(e)});if(!m.ok)throw new Error(`embed alias resolve failed: ${m.status}`);let c=await m.json();return ne(s,t,{alias:c.alias,dims:c.dims},r),{alias:c.alias,dims:c.dims}}async function ie(t,e,n={}){let s=n.env??process.env,r=I(s),a=await(n.fetchImpl??fetch)(`${r}/assurance/embed`,{method:"POST",headers:{...re(n),"content-type":"application/json"},body:JSON.stringify({purpose:t,input:e})});if(!a.ok)throw new Error(`embed failed: ${a.status}`);return await a.json()}import{randomBytes as it}from"crypto";function oe(t,e){let n=Math.min(t.length,e.length),s=0,r=0,a=0;for(let o=0;o<n;o++)s+=t[o]*e[o],r+=t[o]*t[o],a+=e[o]*e[o];return r===0||a===0?0:s/(Math.sqrt(r)*Math.sqrt(a))}function ae(t,e,n){return n*t+(1-n)*e}var ce=.7;import{readFileSync as Ge,writeFileSync as Ie,renameSync as Oe,mkdirSync as Pe}from"fs";import{dirname as Ve,join as le}from"path";function Be(t){return le(t,"embeddings")}function je(t){let e=t.indexOf(":");return e>=0?t.slice(e+1):t}function de(t,e,n){let s=je(n);return le(Be(t),e,s.slice(0,2),`${s.slice(2)}.f32`)}function ue(t,e,n){try{let s=Ge(de(t,e,n)),r=new Float32Array(Math.floor(s.length/4));for(let a=0;a<r.length;a++)r[a]=s.readFloatLE(a*4);return r}catch{return null}}function me(t,e,n,s){try{let r=de(t,e,n);Pe(Ve(r),{recursive:!0});let a=Buffer.alloc(s.length*4);for(let u=0;u<s.length;u++)a.writeFloatLE(s[u],u*4);let o=`${r}.tmp`;Ie(o,a),Oe(o,r)}catch(r){process.stderr.write(`[embed] Failed to cache vector: ${r instanceof Error?r.message:String(r)}
5
5
  `)}}var Ue=["get_node","get_edges","find_by_provenance","match_by_type","stale_nodes","search_similar"],He=["source_read","source_grep"],ze=[...Ue,...He],he=50,P=200,_e=10,ye=50,fe=20,Qe=200,Xe=50;function L(t,e,n){let s=typeof t=="number"&&Number.isFinite(t)?Math.floor(t):e;return Math.max(1,Math.min(s,n))}function R(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new b(`param "${e}" must be a non-empty string`);return n}function $(t,e){let n=t[e];if(n==null)return null;if(typeof n!="string")throw new b(`param "${e}" must be a string when present`);return n}var b=class extends Error{};function V(t,e){let n=t.getNode(e);return n?{cid:e,label:n.label,content:n.content,trust:t.trust.get(e)??null,freshness:t.stale(e)}:null}function pe(t){return new Set(t.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").split(" ").filter(Boolean))}function we(t,...e){let n=pe(t);if(n.size===0)return 0;let s=t.trim().toLowerCase(),r=0;for(let a of e){let o=pe(a);if(o.size===0)continue;let u=0;for(let c of n)o.has(c)&&u++;let d=n.size+o.size-u,m=d===0?0:u/d;s&&a.toLowerCase().includes(s)&&(m=Math.max(m,.9)),r=Math.max(r,m)}return r}function Ke(t,e){let n=R(e,"cid"),s=$(e,"type"),r=$(e,"direction")??"both";if(!["out","in","both"].includes(r))throw new b('param "direction" must be out|in|both');let a=L(e.limit,he,P),o=[];return(r==="out"||r==="both")&&o.push(...t.edgesFrom(n)),(r==="in"||r==="both")&&o.push(...t.edgesInto(n)),o.filter(u=>s==null||u.type===s).slice(0,a)}function We(t,e){let n=R(e,"source_id"),s=t.heads.get(n)??null,r=[];for(let a of t.nodeLabel.keys()){let o=t.derivesInto(a).filter(d=>d.props.source_id===n).map(d=>({source_cid:d.props.source_cid,anchor:d.props.anchor??null}));if(o.length===0)continue;let u=V(t,a);if(u&&(r.push({...u,pins:o,pinned_to_head:s!=null&&o.some(d=>d.source_cid===s)}),r.length>=P))break}return r}function Je(t,e){let n=R(e,"label"),s=$(e,"trust"),r=$(e,"freshness"),a=L(e.limit,he,P),o=[];for(let{cid:u}of t.byLabel(n)){let d=V(t,u);if(d&&!(s!=null&&d.trust!==s)&&!(r!=null&&d.freshness!==r)&&(o.push(d),o.length>=a))break}return o}function Ye(t){return t.staleList().map(({cid:e,state:n})=>{let s=t.getNode(e);return{cid:e,state:n,label:s?.label??null,title:s?.content.title??null}})}function Ze(t,e){let n=R(e,"text"),s=$(e,"label")??"usecase",r=L(e.k,_e,ye),a=[];for(let{cid:o,content:u}of t.byLabel(s)){let d=String(u.title??""),m=String(u.summary??""),c=we(n,d,m);c<=0||a.push({cid:o,title:d,summary:m,score:Math.round(c*1e3)/1e3,trust:t.trust.get(o)??null,freshness:t.stale(o)})}return a.sort((o,u)=>u.score-o.score||o.cid.localeCompare(u.cid)),a.slice(0,r)}function be(t,e,n){let s=t.heads.get(n);if(typeof s!="string"){let a=[...t.heads.keys()].sort().join(", ");throw new b(`unknown source_id "${n}" \u2014 known: ${a||"(none)"}`)}if(t.mediaOf(s).format==="image")throw new b(`source "${n}" is an image \u2014 no line window (cite img#whole)`);let r=J(e,t,s);if(r==null)throw new b(`source "${n}" blob is missing from the store`);return{head:s,lines:r.toString("utf8").replace(/\n$/,"").split(`
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as k}from"./chunk-FPFOW6BS.js";import{p as a}from"./chunk-Y5RNCJAN.js";import{a as m}from"./chunk-2WVKOZ6W.js";import{a as y}from"./chunk-RH4GCEFX.js";import{a as h}from"./chunk-YJIESLN6.js";var $=10,u=200,N=1e4,S=1e6;function T(t,e,r="streaming"){let n=r==="full-fetch"?S:N,o=$,i=0;if(t!==void 0){let s=Number(t);if(!Number.isInteger(s)||s<1||s>u)return{error:`--limit must be an integer in [1, ${u}] (got "${t}")`};o=s}if(e!==void 0){let s=Number(e);if(!Number.isInteger(s)||s<0||s>n)return{error:`--offset must be an integer in [0, ${n}] (got "${e}")`};i=s}return{limit:o,offset:i}}function C(t,e){if(!e)return t;let r=e.toLowerCase();return t.filter(n=>n.name.toLowerCase().includes(r))}function j(t,{limit:e,offset:r}){let n=t.slice(r,r+e),o=t.length>r+e;return{slice:n,hasMore:o}}function v(t,e,r=n=>process.stdout.write(`${n}
2
+ import{a as k}from"./chunk-FPFOW6BS.js";import{p as a}from"./chunk-Y5RNCJAN.js";import{a as m}from"./chunk-2WVKOZ6W.js";import{a as y}from"./chunk-A2IQRVPR.js";import{a as h}from"./chunk-WREVEATJ.js";var $=10,u=200,N=1e4,S=1e6;function T(t,e,r="streaming"){let n=r==="full-fetch"?S:N,o=$,i=0;if(t!==void 0){let s=Number(t);if(!Number.isInteger(s)||s<1||s>u)return{error:`--limit must be an integer in [1, ${u}] (got "${t}")`};o=s}if(e!==void 0){let s=Number(e);if(!Number.isInteger(s)||s<0||s>n)return{error:`--offset must be an integer in [0, ${n}] (got "${e}")`};i=s}return{limit:o,offset:i}}function C(t,e){if(!e)return t;let r=e.toLowerCase();return t.filter(n=>n.name.toLowerCase().includes(r))}function j(t,{limit:e,offset:r}){let n=t.slice(r,r+e),o=t.length>r+e;return{slice:n,hasMore:o}}function v(t,e,r=n=>process.stdout.write(`${n}
3
3
  `)){for(let n of t)r(JSON.stringify(n));r(JSON.stringify({_meta:"page",limit:e.limit,offset:e.offset,returned:t.length,has_more:e.has_more}))}function b(t,e,r=n=>process.stdout.write(`${n}
4
- `)){if(t.length===0){r("(no results)");return}let n=Math.max(2,...t.map(s=>s.id.length)),o=`${"ID".padEnd(n)} NAME`;r(o),r(`${"-".repeat(n)} ----`);for(let s of t)r(`${s.id.padEnd(n)} ${s.name}`);r("");let i=e.offset+t.length;if(e.hasMore){let s=e.totalIsLowerBound?`${e.total}+`:`${e.total}`;r(`${i} of ${s} \u2014 next: --offset ${e.offset+e.limit}`)}else r(`${t.length} shown (${e.total} total)`)}async function B(t,e,r){if(r.username&&r.accessKey)return{ok:!0,creds:{username:r.username,access_key:r.accessKey}};let n=new h,o=n.loadBasicAuth(t,e);if(o)return{ok:!0,creds:{username:o.username,access_key:o.access_key}};let i=n.loadCredentials(t,e);if(!i)return{ok:!1,reason:"no_credentials"};let s=i.access_token;try{let{refreshOAuthToken:d}=await import("./token-refresh-R75DGT4X.js"),w=await d({creds:n,profile:t,env:e,credentials:i});w&&(s=w.accessToken)}catch(d){return{ok:!1,reason:"refresh_failed",detail:d instanceof Error?d.message:String(d)}}let c=y(e),f=await new k(c.controllerBaseUrl,async()=>s,null).resolve();return f?{ok:!0,creds:{username:f.username,access_key:f.access_key}}:{ok:!1,reason:"exchange_failed"}}function E(t,e,r){switch(r.reason){case"no_credentials":return{message:`error: no credentials for profile "${t}" [${e}]. Run \`kane-cli login\` or pass --username/--access-key.
4
+ `)){if(t.length===0){r("(no results)");return}let n=Math.max(2,...t.map(s=>s.id.length)),o=`${"ID".padEnd(n)} NAME`;r(o),r(`${"-".repeat(n)} ----`);for(let s of t)r(`${s.id.padEnd(n)} ${s.name}`);r("");let i=e.offset+t.length;if(e.hasMore){let s=e.totalIsLowerBound?`${e.total}+`:`${e.total}`;r(`${i} of ${s} \u2014 next: --offset ${e.offset+e.limit}`)}else r(`${t.length} shown (${e.total} total)`)}async function B(t,e,r){if(r.username&&r.accessKey)return{ok:!0,creds:{username:r.username,access_key:r.accessKey}};let n=new h,o=n.loadBasicAuth(t,e);if(o)return{ok:!0,creds:{username:o.username,access_key:o.access_key}};let i=n.loadCredentials(t,e);if(!i)return{ok:!1,reason:"no_credentials"};let s=i.access_token;try{let{refreshOAuthToken:d}=await import("./token-refresh-OY3WLAKD.js"),w=await d({creds:n,profile:t,env:e,credentials:i});w&&(s=w.accessToken)}catch(d){return{ok:!1,reason:"refresh_failed",detail:d instanceof Error?d.message:String(d)}}let c=y(e),f=await new k(c.controllerBaseUrl,async()=>s,null).resolve();return f?{ok:!0,creds:{username:f.username,access_key:f.access_key}}:{ok:!1,reason:"exchange_failed"}}function E(t,e,r){switch(r.reason){case"no_credentials":return{message:`error: no credentials for profile "${t}" [${e}]. Run \`kane-cli login\` or pass --username/--access-key.
5
5
  `,exitCode:2};case"refresh_failed":return{message:`error: OAuth token refresh failed for profile "${t}" [${e}]${r.detail?`: ${r.detail}`:""}. Run \`kane-cli login\` to re-auth.
6
6
  `,exitCode:2};case"exchange_failed":return{message:`error: TMS credential exchange failed for profile "${t}" [${e}]. Token may be revoked \u2014 try \`kane-cli login\`; if the problem persists, TMS may be down.
7
7
  `,exitCode:2}}}function O(t){return{id:t.project_id,name:t.name}}function M(t){return{id:t.id,name:t.name}}async function P(t,e,r,n){let o=r+n+1,i=[],s=!0;for await(let c of t.listProjectsStream({name:e})){if(i.push(...c.projects),c.done){s=!0;break}if(i.length>=o){s=!1;break}}return{items:i,doneStreaming:s}}function g(t){return!!t.agent||!process.stdin.isTTY||!process.stdout.isTTY}function _(t,e=r=>process.stdout.write(`${r}
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as K,c as V,d as z,e as ee,f as te}from"./chunk-VYQMCLKG.js";import{c as J}from"./chunk-7APDXIKI.js";import{a as Q}from"./chunk-6JTEWZ75.js";import{a as Z}from"./chunk-FPFOW6BS.js";import{b as H}from"./chunk-SACSQY3Q.js";import{b as W}from"./chunk-7LWXIRI3.js";import{p as E}from"./chunk-Y5RNCJAN.js";import{a as O}from"./chunk-2WVKOZ6W.js";import{a as _}from"./chunk-RH4GCEFX.js";import{a as k,b as A,d as Y}from"./chunk-VE3SUJMA.js";import{a as q}from"./chunk-YJIESLN6.js";import{a as G}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as I,j as X}from"./chunk-C44QQJR4.js";import{a as ue}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var i=F(ue(),1);var r=F(G(),1);function _e({resultRef:h,mode:d="singleshot",loginCompleteRef:f}){let{exit:m}=X(),C=(0,i.useRef)(new q),S=(0,i.useRef)(new Q),v=(0,i.useRef)(new J),t=C.current,l=S.current,$=v.current,ne=K(),[P,g]=(0,i.useState)(d==="login"?"login":"gate"),[L,re]=(0,i.useState)(null),[de,R]=(0,i.useState)(null),[ge,T]=(0,i.useState)(null),[N,oe]=(0,i.useState)(null),[U,B]=(0,i.useState)([]),x=(0,i.useCallback)((e,n,s,o)=>$.log(e,n,s,o),[$]),pe=(0,i.useCallback)((e,n)=>{e?k(t,l,e,n):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[t,l]),y=(0,i.useCallback)(()=>{d==="login"?(f&&(f.current=!0),m()):g("input")},[d,m,f]),D=(0,i.useCallback)((e,n)=>{let s=k(t,l,e,n);if(d==="login"){g("ensure-project");return}Y(s)?y():s.projectId?g("ensure-folder"):g("ensure-project")},[t,l,y,d]);I((e,n)=>{n.ctrl&&e==="c"&&E(0,"Ctrl+C exit")});let M=(0,i.useRef)(!1);i.default.useEffect(()=>{M.current||(M.current=!0,d!=="login"&&te(t,x).then(e=>{re(e),e.status==="authenticated"?D(e.result.profile,e.result.env):e.status==="needs_pick"?g("pick"):(R(e.profile??null),T(e.env??null),g("login"))}).catch(e=>{oe(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[t,x]);let ie=(0,i.useCallback)(e=>{h.current={objective:e},m()},[h,m]),se=(0,i.useCallback)(async(e,n)=>{t.setActiveProfile(e),t.setDefaultEnv(n),(await ee(t,e,n,x)).status==="authenticated"?D(e,n):(R(e),T(n),g("login"))},[t,x,D]),w=(0,i.useCallback)(()=>{let e=t.getActiveProfile(),n=t.getDefaultEnv();if(!e)return null;let s=_(n),o=t.loadBasicAuth(e,n);return new Z(s.controllerBaseUrl,async()=>t.loadCredentials(e,n)?.access_token??null,o,x)},[t,x]),le=(0,i.useCallback)(async()=>{let e=w();if(!e)return null;let n=e.cached??await e.resolve();if(!n)return null;let s=_(t.getDefaultEnv()),o=new O(s.tmsBaseUrl,n.username,n.access_key);try{let p=(await o.listProjects()).find(b=>b.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let j=await o.createProject("KaneAI Generated");return{id:j.id,name:j.name}}catch{return null}},[w,t]),ae=(0,i.useCallback)(async e=>{let n=w();if(!n)return null;let s=n.cached??await n.resolve();if(!s)return null;let o=_(t.getDefaultEnv()),a=new O(o.tmsBaseUrl,s.username,s.access_key);try{let j=(await a.listFolders(e)).find(ce=>ce.name==="Untitled");if(j)return{id:j.id,name:j.name};let b=await a.createFolder(e,"Untitled");return{id:b.id,name:b.name}}catch{return null}},[w,t]);if(P==="gate")return(0,r.jsx)(c,{paddingX:1,children:(0,r.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(N)return(0,r.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,r.jsx)(u,{color:"red",children:N}),(0,r.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(P==="pick"&&L?.status==="needs_pick")return(0,r.jsx)(fe,{profiles:L.profiles,onSelect:se});if(P==="login")return(0,r.jsx)(z,{devMode:process.env.KANE_DEV_MODE==="1",profiles:t.listProfiles(),onBasicLogin:async(e,n,s,o)=>{let{validateBasicAuth:a}=await import("./validate-basic-Z46MAH2G.js");await a(n,s,o),t.saveBasicAuth(e,n,{username:s,access_key:o}),t.setActiveProfile(e),t.setDefaultEnv(n)},onOAuthLogin:async(e,n)=>{let{LoginFlow:s}=await import("./login-flow-KW5T7WRJ.js");t.setDefaultEnv(n),t.setActiveProfile(e),await new s(e,n,t).login()},onComplete:(e,n)=>{R(e),T(n),t.setActiveProfile(e),t.setDefaultEnv(n),D(e,n)},onCancel:()=>{E(0,"Login cancelled")}});if(P==="ensure-project"){let e=t.getActiveProfile()??"default",n=t.getDefaultEnv(),s=()=>{if(d==="login"){g("ensure-folder");return}k(t,l,e,n).folderId?y():g("ensure-folder")};return(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsx)(c,{paddingX:1,marginBottom:1,children:(0,r.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,r.jsx)(H,{resolver:w(),currentProjectId:l.load().project_id,env:n,onSelect:(o,a)=>{A(t,l,e,n,{projectId:o,projectName:a}),B(p=>[...p,`\u2713 Project: ${a} (${o})`]),s()},onCancel:async()=>{let o=await le();o&&(A(t,l,e,n,{projectId:o.id,projectName:o.name}),B(a=>[...a,`\u2713 Default project: ${o.name} (${o.id})`]),s())}})]})}if(P==="ensure-folder"){let e=t.getActiveProfile()??"default",n=t.getDefaultEnv(),s=t.loadProfileConfig(e,n);return(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsx)(c,{paddingX:1,marginBottom:1,children:(0,r.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,r.jsx)(W,{resolver:w(),projectId:s?.project_id??"",currentFolderId:l.load().folder_id,env:n,onSelect:(o,a)=>{A(t,l,e,n,{folderId:o,folderName:a}),B(p=>[...p,`\u2713 Folder: ${a} (${o})`]),y()},onCancel:async()=>{if(!s?.project_id)return;let o=await ae(s.project_id);o&&(A(t,l,e,n,{folderId:o.id,folderName:o.name}),B(a=>[...a,`\u2713 Default folder: ${o.name} (${o.id})`]),y())}})]})}return P==="input"?(0,r.jsxs)(c,{flexDirection:"column",children:[U.length>0&&(0,r.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:U.map((e,n)=>(0,r.jsx)(u,{color:"green",children:e},n))}),(0,r.jsx)(V,{onSubmit:ie,onEscape:()=>E(0,"User pressed Escape"),history:ne,placeholder:"Type an objective..."})]}):(0,r.jsx)(r.Fragment,{})}function fe({profiles:h,onSelect:d}){let[f,m]=(0,i.useState)(0),[C,S]=(0,i.useState)(!1);return I((v,t)=>{if(!C){if(t.escape){E(0,"Profile picker cancelled");return}if(t.upArrow&&f>0&&m(l=>l-1),t.downArrow&&f<h.length-1&&m(l=>l+1),t.return){S(!0);let l=h[f];d(l.profile,l.env).catch(()=>S(!1))}}}),(0,r.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,r.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,r.jsx)(c,{marginTop:1,flexDirection:"column",children:h.map((v,t)=>(0,r.jsxs)(u,{children:[t===f?"\u276F ":" ",(0,r.jsx)(u,{color:t===f?"#ff9500":"white",bold:t===f,children:v.profile}),(0,r.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),C&&(0,r.jsx)(c,{marginTop:1,children:(0,r.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{_e as a};
2
+ import{b as K,c as V,d as z,e as ee,f as te}from"./chunk-77WMTCUQ.js";import{c as J}from"./chunk-4SJC64KQ.js";import{a as Q}from"./chunk-T7ZPMTGS.js";import{a as Z}from"./chunk-FPFOW6BS.js";import{b as H}from"./chunk-CH3VWCRZ.js";import{b as W}from"./chunk-4BAMZSFU.js";import{p as E}from"./chunk-Y5RNCJAN.js";import{a as O}from"./chunk-2WVKOZ6W.js";import{a as _}from"./chunk-A2IQRVPR.js";import{a as k,b as A,d as Y}from"./chunk-VE3SUJMA.js";import{a as q}from"./chunk-WREVEATJ.js";import{a as G}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as I,j as X}from"./chunk-C44QQJR4.js";import{a as ue}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var i=F(ue(),1);var r=F(G(),1);function _e({resultRef:h,mode:d="singleshot",loginCompleteRef:f}){let{exit:m}=X(),C=(0,i.useRef)(new q),S=(0,i.useRef)(new Q),v=(0,i.useRef)(new J),t=C.current,l=S.current,$=v.current,ne=K(),[P,g]=(0,i.useState)(d==="login"?"login":"gate"),[L,re]=(0,i.useState)(null),[de,R]=(0,i.useState)(null),[ge,T]=(0,i.useState)(null),[N,oe]=(0,i.useState)(null),[U,B]=(0,i.useState)([]),x=(0,i.useCallback)((e,n,s,o)=>$.log(e,n,s,o),[$]),pe=(0,i.useCallback)((e,n)=>{e?k(t,l,e,n):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[t,l]),y=(0,i.useCallback)(()=>{d==="login"?(f&&(f.current=!0),m()):g("input")},[d,m,f]),D=(0,i.useCallback)((e,n)=>{let s=k(t,l,e,n);if(d==="login"){g("ensure-project");return}Y(s)?y():s.projectId?g("ensure-folder"):g("ensure-project")},[t,l,y,d]);I((e,n)=>{n.ctrl&&e==="c"&&E(0,"Ctrl+C exit")});let M=(0,i.useRef)(!1);i.default.useEffect(()=>{M.current||(M.current=!0,d!=="login"&&te(t,x).then(e=>{re(e),e.status==="authenticated"?D(e.result.profile,e.result.env):e.status==="needs_pick"?g("pick"):(R(e.profile??null),T(e.env??null),g("login"))}).catch(e=>{oe(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[t,x]);let ie=(0,i.useCallback)(e=>{h.current={objective:e},m()},[h,m]),se=(0,i.useCallback)(async(e,n)=>{t.setActiveProfile(e),t.setDefaultEnv(n),(await ee(t,e,n,x)).status==="authenticated"?D(e,n):(R(e),T(n),g("login"))},[t,x,D]),w=(0,i.useCallback)(()=>{let e=t.getActiveProfile(),n=t.getDefaultEnv();if(!e)return null;let s=_(n),o=t.loadBasicAuth(e,n);return new Z(s.controllerBaseUrl,async()=>t.loadCredentials(e,n)?.access_token??null,o,x)},[t,x]),le=(0,i.useCallback)(async()=>{let e=w();if(!e)return null;let n=e.cached??await e.resolve();if(!n)return null;let s=_(t.getDefaultEnv()),o=new O(s.tmsBaseUrl,n.username,n.access_key);try{let p=(await o.listProjects()).find(b=>b.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let j=await o.createProject("KaneAI Generated");return{id:j.id,name:j.name}}catch{return null}},[w,t]),ae=(0,i.useCallback)(async e=>{let n=w();if(!n)return null;let s=n.cached??await n.resolve();if(!s)return null;let o=_(t.getDefaultEnv()),a=new O(o.tmsBaseUrl,s.username,s.access_key);try{let j=(await a.listFolders(e)).find(ce=>ce.name==="Untitled");if(j)return{id:j.id,name:j.name};let b=await a.createFolder(e,"Untitled");return{id:b.id,name:b.name}}catch{return null}},[w,t]);if(P==="gate")return(0,r.jsx)(c,{paddingX:1,children:(0,r.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(N)return(0,r.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,r.jsx)(u,{color:"red",children:N}),(0,r.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(P==="pick"&&L?.status==="needs_pick")return(0,r.jsx)(fe,{profiles:L.profiles,onSelect:se});if(P==="login")return(0,r.jsx)(z,{devMode:process.env.KANE_DEV_MODE==="1",profiles:t.listProfiles(),onBasicLogin:async(e,n,s,o)=>{let{validateBasicAuth:a}=await import("./validate-basic-IJKKRQRU.js");await a(n,s,o),t.saveBasicAuth(e,n,{username:s,access_key:o}),t.setActiveProfile(e),t.setDefaultEnv(n)},onOAuthLogin:async(e,n)=>{let{LoginFlow:s}=await import("./login-flow-GX7CTVWN.js");t.setDefaultEnv(n),t.setActiveProfile(e),await new s(e,n,t).login()},onComplete:(e,n)=>{R(e),T(n),t.setActiveProfile(e),t.setDefaultEnv(n),D(e,n)},onCancel:()=>{E(0,"Login cancelled")}});if(P==="ensure-project"){let e=t.getActiveProfile()??"default",n=t.getDefaultEnv(),s=()=>{if(d==="login"){g("ensure-folder");return}k(t,l,e,n).folderId?y():g("ensure-folder")};return(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsx)(c,{paddingX:1,marginBottom:1,children:(0,r.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,r.jsx)(H,{resolver:w(),currentProjectId:l.load().project_id,env:n,onSelect:(o,a)=>{A(t,l,e,n,{projectId:o,projectName:a}),B(p=>[...p,`\u2713 Project: ${a} (${o})`]),s()},onCancel:async()=>{let o=await le();o&&(A(t,l,e,n,{projectId:o.id,projectName:o.name}),B(a=>[...a,`\u2713 Default project: ${o.name} (${o.id})`]),s())}})]})}if(P==="ensure-folder"){let e=t.getActiveProfile()??"default",n=t.getDefaultEnv(),s=t.loadProfileConfig(e,n);return(0,r.jsxs)(c,{flexDirection:"column",children:[(0,r.jsx)(c,{paddingX:1,marginBottom:1,children:(0,r.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,r.jsx)(W,{resolver:w(),projectId:s?.project_id??"",currentFolderId:l.load().folder_id,env:n,onSelect:(o,a)=>{A(t,l,e,n,{folderId:o,folderName:a}),B(p=>[...p,`\u2713 Folder: ${a} (${o})`]),y()},onCancel:async()=>{if(!s?.project_id)return;let o=await ae(s.project_id);o&&(A(t,l,e,n,{folderId:o.id,folderName:o.name}),B(a=>[...a,`\u2713 Default folder: ${o.name} (${o.id})`]),y())}})]})}return P==="input"?(0,r.jsxs)(c,{flexDirection:"column",children:[U.length>0&&(0,r.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:U.map((e,n)=>(0,r.jsx)(u,{color:"green",children:e},n))}),(0,r.jsx)(V,{onSubmit:ie,onEscape:()=>E(0,"User pressed Escape"),history:ne,placeholder:"Type an objective..."})]}):(0,r.jsx)(r.Fragment,{})}function fe({profiles:h,onSelect:d}){let[f,m]=(0,i.useState)(0),[C,S]=(0,i.useState)(!1);return I((v,t)=>{if(!C){if(t.escape){E(0,"Profile picker cancelled");return}if(t.upArrow&&f>0&&m(l=>l-1),t.downArrow&&f<h.length-1&&m(l=>l+1),t.return){S(!0);let l=h[f];d(l.profile,l.env).catch(()=>S(!1))}}}),(0,r.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,r.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,r.jsx)(c,{marginTop:1,flexDirection:"column",children:h.map((v,t)=>(0,r.jsxs)(u,{children:[t===f?"\u276F ":" ",(0,r.jsx)(u,{color:t===f?"#ff9500":"white",bold:t===f,children:v.profile}),(0,r.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),C&&(0,r.jsx)(c,{marginTop:1,children:(0,r.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{_e as a};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as M,b as B,c as oe,d as A}from"./chunk-2YQ6TW77.js";import{a as F}from"./chunk-WAOCHXJ5.js";import{b as z}from"./chunk-CJJXT5DO.js";import{a as U}from"./chunk-2WVKOZ6W.js";import{a as j}from"./chunk-NLCCBXXV.js";import{a as O}from"./chunk-RZ4F3BHX.js";import{e as se}from"./chunk-UR6MHSHU.js";import{readFileSync as te,existsSync as C,readdirSync as Re,mkdirSync as D,writeFileSync as x}from"fs";import{readFile as ie,unlink as Ae}from"fs/promises";import{join as E}from"path";import{randomUUID as P}from"crypto";var re="/home/kaneai/Downloads";function N(t){return`${re}/${t}`}function $(t){return"FILE__"+t.replace(/[^A-Za-z0-9]/g,"_")}function S(t){let e=t?.media;return!e||!e.name||!e.media_url?null:{media_id:e.media_id??"",name:e.name,media_url:e.media_url,type:e.type??"doc"}}function K(t){return t?t.includes(`
3
+ `)?t.split(`
4
+ `).map(e=>e.trim()).filter(Boolean):t.split(". ").map(e=>e.trim()).filter(Boolean).map(e=>e.endsWith(".")?e:e+"."):[]}function L(t,e){return!t||!e?t:t.replace(/\{\{(.+?)\}\}/g,(i,n)=>{let s=e[n];return s?s.value:i}).replace(/\$\{(.+?)\}/g,(i,n)=>{let s=e[n];return s?s.value:i})}var ae={click:"CLICK",double_click:"CLICK",type:"TYPE",fill:"TYPE",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"},G={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"},le=new Set(["CLICK","TYPE","FILL","HOVER","SCROLL_UNTIL_ELEMENT","UPLOAD_FILE","VISION_QUERY","DRAG_DROP","SELECT"]);function X(t,e){if(t==="analyze"){let n=e?.action_params?.analyzer_type??"";return G[n]}let i=ae[t];return i||console.warn(`[migrator] UNKNOWN action_type "${t}" \u2014 falling back to "${t.toUpperCase()}"; explicit mapping required`),i??t.toUpperCase()}function Y(t,e){if(!t||!e)return"";try{let i=new Date(t);return isNaN(i.getTime())?"":new Date(i.getTime()+e).toISOString()}catch{return""}}function H(t){try{return JSON.parse(t.output_value??"{}")}catch{return{}}}function ce(t){let e=t.output_variable??"";if(!e)return"[]";let n={...H(t)};return delete n.body,JSON.stringify([{name:e,unique_key:(t.action_id??"").replace(/-/g,"").slice(0,8)||P().replace(/-/g,"").slice(0,8),value:n,variable_description:"API Response"}])}function ue(t,e,i){let n=t.action_params??{},s=le.has(e)?"Vision Agent":"Operation Agent",a={operation_type:e};if(e==="OPEN"&&(a.url=n.url??""),e==="SET_VARIABLE"&&(a.variable_name=t.output_variable??n.key??"",a.variable_value=t.output_value??""),e==="UPLOAD_FILE"){let f=S(n);f&&(a.value=N(f.name))}let o={},l={},r=t.action_instruction??"",c=n.text??"",u=n.url??"",p=[["intent",r],["value",c],["url",u]];for(let[f,h]of Object.entries(i)){let b=String(h);if(f.startsWith("secrets."))for(let[I,v]of p)v.includes(b)&&(l[I]=f);for(let[I,v]of p)v.includes(b)&&!(I in o)&&(o[I]=v)}let _=t.action_type,d={operation:t.action_instruction??"",agent:s,operation_dict:a,reasoning:_==="analyze"?n.query??"":t.intent??t.action_instruction??"",variable:o,secrets:l,params:{}};_==="analyze"&&typeof n.code=="string"&&n.code&&(d.code=n.code),_==="analyze"&&typeof n.code_js=="string"&&n.code_js&&(d.code_js=n.code_js),_==="analyze"&&typeof n.condition_expression=="string"&&n.condition_expression&&(d.condition_expression=n.condition_expression),n.uses_websocket===!0&&(d.uses_websocket=!0),n.uses_sse===!0&&(d.uses_sse=!0),_==="analyze"&&n.analyzer_type==="textual_visual"&&(typeof n.wrapped_js=="string"&&(d.wrapped_js=n.wrapped_js),Array.isArray(n.locators)&&(d.locators=n.locators),typeof n.operator=="string"&&(d.operator=n.operator),Array.isArray(n.transforms)&&(d.transforms=n.transforms),typeof n.query=="string"&&(d.query=n.query),typeof n.expected_value=="string"&&(d.expected_value=n.expected_value),typeof n.needs_unit_conversion=="boolean"&&(d.needs_unit_conversion=n.needs_unit_conversion),typeof n.condition=="string"&&(d.condition=n.condition));let m={set_cookies:"cookies",set_clipboard:"text",delete_cookies:"names",set_local_storage:"items",delete_local_storage:"keys"}[_];return m&&n[m]!==void 0&&(d[m]=n[m]),_==="set_clipboard"&&typeof n.html=="string"&&n.html&&(d.html=n.html),d}function de(t){let e=t.assertion_tree??{};if(typeof e.passed=="boolean")return e.passed;let i=e.sub_results??[];return i.length===0?e.status==="passed":(e.composite_operator??"and")==="or"?i.some(s=>s.passed===!0):i.every(s=>s.passed===!0)}function W(t){return t.map(e=>({description:e.description??"",store_key:e.store_key??"",expected_value:e.expected??"",extracted_value:e.extracted_value??"",operator:e.operator??"equals",transforms:e.transforms??[]}))}function _e(t){let e=t.assertion_tree??{},i=e.sub_results??[],n=W(i);return{operator:[],assertion_operands:[],left_operand:null,right_operand:null,operands:[],sub_results:i,sub_checks:n,composite_operator:e.composite_operator??"and",verification:e.verification??"",claim:e.description??""}}function pe(t){let i=(t.action_params??{}).assertion_tree??{},n=i.sub_results??[],s=W(n);return[{operation:t.action_instruction??"",agent:"Operation Agent",operation_dict:{operation_type:"ASSERTION",assertion_tree:{sub_results:n,sub_checks:s,composite_operator:i.composite_operator??"and",verification:"",claim:i.description??t.action_instruction??"",operator:[],assertion_operands:[],left_operand:null,right_operand:null,operands:[]}},variable:{},secrets:{},params:{}}]}function ge(t,e,i,n){let s=t.visual_data;if(!s||s.x==null||s.y==null)return null;let a=e?`${e}/test_screenshots`:"";return{x:s.x,y:s.y,confidence:0,bbox:s.bbox??null,bbox_source:s.bbox?"accessibility_tree":"fallback",viewport_width:s.viewport_width??1280,viewport_height:s.viewport_height??800,scale_factor:null,raw_image_url:a?`${a}/untagged_screenshot/${i}.${n?.get(i)??"png"}`:"",raw_image_sas_url:"",annotated_image_url:"",annotated_image_sas_url:""}}function fe(t){if(!t)return"";let e=t;return typeof t=="object"&&!Array.isArray(t)&&Array.isArray(t.frameInfo)&&(e=t.frameInfo),!Array.isArray(e)||e.length===0?"":JSON.stringify(e)}function V(t,e={},i="",n){let s=t.action_type,a=X(s,t),o=t.action_params??{},l=t.coordinates??null,r=t.selectors??null,c=!!(r&&r.length>0),u=t.timestamp??"",p=t.duration_ms??0,_=t.variables_used??{},d=t.action_id??P(),g=P(),m=Y(u,p),f="",h="";if(s==="navigate")h=o.url??"",f=h;else if(s==="type"||s==="fill")f=o.text??"";else if(s==="press_key")f=o.key??"";else if(s==="wait")f=String(o.ms??o.timeout_ms??"");else if(s==="evaluate_js")f=o.script??"";else if(s==="upload_files"){let y=S(o);y&&(f=N(y.name))}else s==="analyze"&&a==="SET_VARIABLE"&&(f=t.output_value??"");let b="";s==="go_back"?b="back":s==="go_forward"&&(b="forward");let I=L(f,e),v=L(h,e),k=L(t.action_instruction??"",e),R=ue(t,a,_);return{operation_id:d,instruction_id:g,instruction:k,intent:k,operation_start:u,operation_end:m,status:t.status??"",command:a,name:"",target:"",value:I,message:"",operation_dict:"",frame:fe(t.frame_info),error_message:t.error??"",code_snippet:"",sub_instruction_obj:JSON.stringify(R),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:i?`${i}/test_screenshots/untagged_screenshot/${d}.${n?.get(d)??"png"}`:"",alternative_xpaths:[],attribute:"",value_description:"",url:v,navigation_direction:b,tagified_image_url:"",query_variable_name:t.output_variable??"",query_variable_value:t.output_value??"",query_variable_type:"",expected_value:"",queried_value:"",operator:"",assertion_status:a==="ASSERTION"?de(o):"",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(o.tab_index??""),tab_identifier:String(o.tab_identifier??""),scroll_value:o.amount??1,scroll_direction:o.direction??"",mi_scroll_payload:{},sleep_duration:0,app_id:"",manual_interaction_tag:"",string_to_float_list:[],js_snippet:s==="evaluate_js"?o.script??"":"",code_error:"",hide:!1,dismiss_dialog:!1,use_v2_mobile_tagging:!1,multiple_inputs:!1,dialog_action:"",dialog_type:"",is_coordinates_used_for_interaction:l!==null&&!c,element_coordinates_ratio:[],element_bounds_ratio:[],x_coord:c?null:l?.x??null,y_coord:c?null:l?.y??null,target_x_coord:o.target_x??null,target_y_coord:o.target_y??null,source_description:o.source_description??null,target_description:o.target_description??null,use_coordinates:l!==null&&!c,kaneaiMobileTaggingImageLimit:1,clicks_order_code:"se_js_ac",selector:c?r.map(y=>({type:y.isXPath?"xpath":"css",...y})):"",selector_target:"",math_result_variable_name:"",math_result_variable_value:"",expression_tree:a==="ASSERTION"?_e(o):o.expression_tree??{},assertion_tree:o.assertion_tree??{},assertion_tree_simplified:{},network_throttle:{},is_mobile_offline:!1,autoheal:!1,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:a==="ASSERTION"?"Fail test immediately":"",screenshot_command:"",smartui_contents:{},smartui_results:{},result_type:"",result_hint:"",drag_offset:{},start_coordinates:o.source_coordinates?{x:o.source_coordinates[0],y:o.source_coordinates[1]}:{},end_coordinates:o.target_coordinates?{x:o.target_coordinates[0],y:o.target_coordinates[1]}:{},element_rect:null,is_canvas:!1,until_condition:"",until_max_retries:0,until_settle_ms:0,api_data:s==="api"?{request:t.action_params?.api_data?.request??{}}:{},output_variables:s==="api"?t.output_variable?{[t.output_variable]:null}:{}:t.output_variable?{[t.output_variable]:t.output_value??""}:{},visual_context:ge(t,i,d,n),reasoning:s==="analyze"?o.query??"":t.intent??t.action_instruction??""}}function q(t,e,i={}){let n=t.action_type,s=X(n,t),a=t.timestamp??"",o=t.duration_ms??0,l=Y(a,o),r=s==="ASSERTION"||s==="MATHEMATICAL_OPERATION";return{instruction_id:e.instruction_id,instruction_class:r?"non_driver_action":"driver_action",module_id:"",instruction:L(t.action_instruction??"",i),command:s,error:null,parent_instruction_id:"",classification_layer_resp:s==="ASSERTION"?pe(t):[],classification_error:{},operations:[e],status:t.status??"",start_timestamp:a,end_timestamp:l,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"&&t.action_params?.analyzer_type==="api_response"?"api_calls_query":n==="analyze"&&t.action_params?.analyzer_type?.startsWith("devtool_")?t.action_params.analyzer_type.replace("devtool_","devtools_"):"instruction",js_snippet:n==="evaluate_js"?t.action_params?.script??"":"",user_variables:n==="api"?ce(t):"[]",api_data:n==="api"?{request:t.action_params?.api_data?.request??{},response:H(t)}:{},params_used:!1,hard_assertion:s==="ASSERTION"?t.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"?t.action_params?.query??"":t.intent??t.action_instruction??""}}function me(t,e=[]){let i=t.action_params??{},n=i.branches??[],s=i.winning_index??-1,a=i.sub_results??[],o={};for(let r of a){let c=r.sub_results;if(c)for(let u of c){let p=u.store_key;p&&(o[p]=u)}}let l=n.map((r,c)=>{let u=c===s,p=(r.sub_checks??[]).map(_=>{let d=o[_.store_key];return{description:_.description,store_key:_.store_key,expected_value:_.expected_value,stored_value:d?.extracted_value??_.stored_value,operator:_.operator??d?.operator??"equals",transforms:_.transforms??d?.transforms??[]}});if(p.length===0&&r.condition&&a.length>0){let d=a.find(g=>g.branch_index===c)?.sub_results??[];d.length>0&&(p=d.map(g=>({description:g.description??r.condition,store_key:g.store_key??"",expected_value:g.expected??"true",stored_value:g.extracted_value??void 0,operator:g.operator??"equals",transforms:g.transforms??[]})))}return{branch_index:c,condition:r.condition??null,branch_type:r.branch_type??"sub_objective",passed:u,sub_objective:null,custom_event:r.custom_event??null,children:u?e:[],sub_checks:r.condition?p:[],composite_operator:r.composite_operator??"and"}});return{content_type:"conditional_block",instruction_id:`if_else_${P().slice(0,8)}`,instruction:t.action_instruction??"",instruction_class:"driver_action",command:"",status:t.status??"success",resolved_branch_index:s,branches:l,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:t.timestamp??"",end_timestamp:"",type:"agent_generated",hook:null,hook_type:null,evaluation_context:{},query_variables:{}}}function J(t,e,i){for(let n of t)n.content_type==="instruction"&&"generative_id"in n&&(n.generative_id=e,n.generative_objective=i)}function w(t,e={},i="",n,s){let a=[],o=0;for(;o<t.length;){let l=t[o],r=l.action_type;if(!s?.keepFailedActions&&l.status==="error"&&r!=="assert"&&r!=="if_else"&&r!=="child_agent_start"&&r!=="child_agent_end"&&!(l.until_condition&&!l.error)){o+=1;continue}if(r==="analyze"&&!G[l.action_params?.analyzer_type??""]){o+=1;continue}if(r==="child_agent_start"){let c=l.action_params?.child_id??"",u=l.action_params?.objective??"",p=[];o+=1;let _=1,d="error",g;for(;o<t.length&&_>0;){let R=t[o],y=R.action_type;if(y==="child_agent_start")_+=1;else if(y==="child_agent_end"&&(_-=1,_===0)){d=R.status??"success",g=R,o+=1;break}_>0&&p.push(R),o+=1}let m=w(p,e,i,n);J(m,c,u);let f=g?.action_params?.result_code??null,h=g?.action_params?.reason_code??null,b=g?.action_params?.error_message??null,I=g?.action_params?.summary??null,v=g?.action_params?.one_liner??null,k=d==="error";a.push({content_type:"generative_block",instruction_id:`generative_block_${c}`,generative_id:c,objective:u,status:d,children:m,error_message:k?b??null:null,error_code:k?h??null:null,result_code:f??null,bifurcation_context:[],approach_reason:K(I),one_liner:v??null});continue}else if(r==="child_agent_end"){o+=1;continue}else if(r==="if_else"){o+=1;let c=[];for(;o<t.length&&t[o].action_type==="child_agent_start";){let u=t[o],p=u.action_params?.child_id??"",_=u.action_params?.objective??"",d=[];o+=1;let g=1,m="error";for(;o<t.length&&g>0;){let h=t[o];if(h.action_type==="child_agent_start")g+=1;else if(h.action_type==="child_agent_end"&&(g-=1,g===0)){m=h.status??"success",o+=1;break}g>0&&d.push(h),o+=1}let f=w(d,e,i,n);c.push(...f)}a.push(me(l,c));continue}else if(r==="query_tool"){o+=1;continue}else if(l.until_condition){let c=V(l,e,i,n),u=q(l,c,e),p=typeof l.until_condition_met=="boolean"?l.until_condition_met:l.status==="success";a.push({content_type:"until_block",instruction_id:`until_${P().slice(0,8)}`,condition:l.until_condition,max_retries:l.until_max_retries??10,settle_ms:l.until_settle_ms??500,current_count:0,condition_met:p,children:[u],generative_id:"",generative_objective:"",variables_used:{},status:l.status??"success"})}else{let c=V(l,e,i,n),u=q(l,c,e);a.push(u)}o+=1}return a}function T(t,e={},i="",n,s){let a=[];for(let o of t){let l=w(o.records,e,i,n,s);if(l.length===0)continue;let r=P().replace(/-/g,"");J(l,r,o.objective);let c=l.some(d=>"status"in d&&typeof d.status=="string"?d.status==="error"||d.status==="failed":!1),u=o.resultCode?parseInt(o.resultCode,10):null,p=u!==null&&!isNaN(u)&&u>=200,_=c||p?"error":"success";a.push({content_type:"generative_block",instruction_id:`generative_block_${r}`,generative_id:r,objective:o.objective,status:_,children:l,error_message:_==="error"?o.errorMessage??null:null,error_code:_==="error"?o.reasonCode??null:null,result_code:o.resultCode??null,bifurcation_context:[],approach_reason:K(o.summary),one_liner:o.oneLiner??null})}return{instructions:a}}var Z=se(oe(),1);import{createWriteStream as he}from"fs";import{readFile as Ee}from"fs/promises";import{join as be,basename as Ie}from"path";import{tmpdir as ve}from"os";var ye=["**/screenshots/**","**/annotated/**","**/tcg/**","**/bifurcation/**"];async function Q(t){let e=be(ve(),`${Ie(t)}_artifacts.zip`);return new Promise((i,n)=>{let s=he(e),a=(0,Z.default)("zip",{zlib:{level:6}});s.on("close",()=>i(e)),a.on("error",n),a.pipe(s),a.glob("**/*",{cwd:t,ignore:ye}),a.finalize()})}async function ee(t){return Ee(t)}async function Pe(t,e){return ie(z(t,e))}function ke(t){return{key:"artifacts",content_type:"application/zip",filename:`${t}.evidence`}}var ne=class{config;controller;testId;constructor(e){this.config=e,this.controller=new F(e.controllerBaseUrl,e.auth),this.testId=e.testId}log(e,i,n,s){this.config.log?.(e,i,n,s)}async execute(){let{onProgress:e}=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 i=this.config.evidence,n=null;if(this.config.shouldUploadArtifacts!==!1){e("convert","running");let l=this.collectNdjsonPerRun(),r=l.reduce((m,f)=>m+f.records.length,0);this.log("info","PIPELINE_CONVERT","Collected NDJSON records",{total_records:r,run_groups:l.length});let c=this.config.variables??{};this.log("info","PIPELINE_CONVERT_VARS","Variables for template resolution",{keys:Object.keys(c)});let{instructions:u}=l.length>0?T(l,c,this.config.screenshotBaseUrl??"",this.config.screenshotExtMap):{instructions:[]};this.log("info","PIPELINE_CONVERT_INSTRUCTIONS","Auteur instructions produced",{count:u.length});let p=this.buildExecutionEnvelope(u),_=Buffer.from(JSON.stringify(p));this.log("info","PIPELINE_CONVERT_BLOB","Blob created",{size_kb:+(_.length/1024).toFixed(1)});let d=E(this.config.sessionDir,"execution.json");x(d,JSON.stringify(p,null,2)),this.log("info","PIPELINE_CONVERT_LOCAL_SAVE","Execution blob saved locally",{path:d});let g=i?.packTestDir??this.config.evidenceRead?.packTestDir;if(g){let m=E(g,"auteur");D(m,{recursive:!0}),x(E(m,"execution.json"),JSON.stringify(p,null,2)),this.log("info","PIPELINE_CONVERT_PACK_COPY","Execution blob copied into pack",{path:E(m,"execution.json")})}if(e("convert","done"),i)n=_;else{e("zip","running"),this.log("info","PIPELINE_ZIP_START","Zipping session",{session_dir:this.config.sessionDir});let m=null,f;try{m=await Q(this.config.sessionDir),f=await ee(m),this.log("info","PIPELINE_ZIP_DONE","Zip complete",{size_mb:+(f.length/1024/1024).toFixed(1),path:m}),e("zip","done",`${(f.length/1024/1024).toFixed(1)}MB`)}finally{m&&await Ae(m).catch(()=>{})}e("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}),e("presign","done"),e("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading artifacts and blob",{artifact_size_mb:+(f.length/1024/1024).toFixed(1),blob_size_kb:+(_.length/1024).toFixed(1)}),await Promise.all([A(h.urls.artifacts.upload_url,f,"application/zip"),A(h.urls.blob.upload_url,_,"application/json")]),this.log("info","PIPELINE_UPLOAD_OK","Upload complete"),e("upload","done")}}else{let l=this.collectNdjsonPerRun(),r=this.config.variables??{},{instructions:c}=l.length>0?T(l,r,this.config.screenshotBaseUrl??"",this.config.screenshotExtMap,{keepFailedActions:!0}):{instructions:[]},u=this.buildExecutionEnvelope(c),p=E(this.config.sessionDir,"execution.json");x(p,JSON.stringify(u,null,2)),this.log("info","PIPELINE_LOCAL_SAVE","Execution blob saved locally (no upload)",{path:p});let _=this.config.evidence?.packTestDir??this.config.evidenceRead?.packTestDir;if(_){let d=E(_,"auteur");D(d,{recursive:!0});let g=this.readAuthoredExecution();x(E(d,"execution.json"),g??JSON.stringify(u,null,2)),this.log("info","PIPELINE_CONVERT_PACK_COPY","Execution blob copied into pack (gated)",{path:E(d,"execution.json"),source:g?"authored":"run_envelope"})}e("convert","skipped"),e("zip","skipped"),e("presign","skipped"),e("upload","skipped"),this.log("info","PIPELINE_UPLOAD_SKIPPED","Upload steps skipped (gate disabled)")}if(this.config.shouldReplaceLocalOutput&&this.config.onAtomicReplace){e("atomic_replace","running");try{await this.config.onAtomicReplace(),this.log("info","PIPELINE_ATOMIC_REPLACE_OK","Local output replaced"),e("atomic_replace","done")}catch(l){let r=l instanceof Error?l.message:String(l);throw this.log("error","PIPELINE_ATOMIC_REPLACE_FAILED","Atomic-replace failed",{error:r}),e("atomic_replace","failed",r),l}}else e("atomic_replace","skipped");let s,a;if(this.config.shouldCommit&&!this.config.isFirstRun&&this.config.onCommitLock){e("commit_lock","running");let l=await this.config.onCommitLock();if(l.ok)s=l.testcaseId,this.log("info","PIPELINE_COMMIT_LOCK_OK","Commit lock acquired",{testcase_id:s??"none"}),e("commit_lock","done");else return this.log("error","PIPELINE_COMMIT_LOCK_FAILED","Commit lock failed",{reason:l.reason,message:l.message}),e("commit_lock","failed",`${l.reason??"unknown"}: ${l.message??""}`),{success:!1,testId:this.testId,error:`commit-lock failed: ${l.reason??"unknown"}`}}else e("commit_lock","skipped");if(this.config.isFirstRun&&!this.config.skipTmsFinalize){e("finalize","running"),this.log("info","PIPELINE_FINALIZE_START","Finalizing test (first-run)",{test_id:this.testId,commit_id:this.config.commitId});let l=new U(this.config.tmsBaseUrl,this.config.tmsUsername,this.config.tmsAccessKey),r=this.config.runObjectives&&this.config.runObjectives.length>0?this.config.runObjectives:[this.config.firstObjective];if(s=(await l.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:r})).testcase_id||void 0,this.log("info","PIPELINE_FINALIZE_OK","Test finalized",{testcase_id:s??"none"}),this.config.onFinalizeSuccess)try{await this.config.onFinalizeSuccess(s)}catch(u){this.log("warn","PIPELINE_FINALIZE_META_FAILED","Meta-rewrite after endTest failed",{error:String(u)})}e("finalize","done")}else e("finalize","skipped"),this.log("info","PIPELINE_FINALIZE_SKIPPED","Finalize skipped (evolve flow or first-run disabled)");if(s&&this.config.shareApiBaseUrl)try{a=await this.generateShareLink(s),this.log("info","PIPELINE_SHARE_OK","Share link generated",{share_id:a})}catch(l){this.log("warn","PIPELINE_SHARE_FAILED","Share link failed",{error:String(l)})}if(i&&n){let l=null;e("zip","running");try{await i.sealFn({testcaseId:s,shareId:a}),l=i.sealedPackPath?await ie(i.sealedPackPath):await Pe(i.executionId,i.cwd),this.log("info","PIPELINE_EVIDENCE_SEALED","Evidence pack sealed",{execution_id:i.executionId}),this.log("info","PIPELINE_PACK_READ","Sealed pack read",{size_mb:+(l.length/1024/1024).toFixed(1)})}catch(r){let c=r instanceof Error?r.message:String(r);this.log("warn","PIPELINE_EVIDENCE_UPLOAD_SKIPPED","Evidence seal/read failed \u2014 uploading blob only",{execution_id:i.executionId,error:c})}if(l){e("zip","done",`${(l.length/1024/1024).toFixed(1)}MB`),e("presign","running");let r=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[ke(i.executionId),{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);this.log("info","PIPELINE_PRESIGN_OK","Presigned URLs received",{artifacts_url:r.urls.artifacts?.blob_url,blob_url:r.urls.blob?.blob_url}),e("presign","done"),e("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading pack and blob",{artifact_size_mb:+(l.length/1024/1024).toFixed(1),blob_size_kb:+(n.length/1024).toFixed(1)}),await Promise.all([A(r.urls.artifacts.upload_url,l,"application/zip"),A(r.urls.blob.upload_url,n,"application/json")]),this.log("info","PIPELINE_UPLOAD_OK","Upload complete"),e("upload","done")}else{e("zip","skipped"),e("presign","running");let r=await this.controller.getPresignedUrls(this.testId,this.config.sessionId,[{key:"blob",content_type:"application/json",filename:`${this.config.commitId}.json`}]);e("presign","done"),e("upload","running"),this.log("info","PIPELINE_UPLOAD_START","Uploading blob only (evidence skipped)",{blob_size_kb:+(n.length/1024).toFixed(1)}),await A(r.urls.blob.upload_url,n,"application/json"),this.log("info","PIPELINE_UPLOAD_OK","Blob upload complete (pack skipped)"),e("upload","done")}}let o;if(this.config.codeExport?.enabled&&s){let l=!1;try{await this.triggerCodeExport(s),this.log("info","PIPELINE_CODE_EXPORT_START","Code export triggered"),l=!0}catch(r){let c=r instanceof Error?r.message:String(r);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export trigger failed; skipping poll",{error:c}),e("code_export","failed",`trigger failed: ${c}`)}if(l){e("code_export","running","Waiting for code generation\u2026");try{o=await this.pollAndDownloadCode(s,e),this.log("info","PIPELINE_CODE_EXPORT_OK","Code export complete",{dir:o}),e("code_export","done",o)}catch(r){let c=r instanceof Error?r.message:String(r);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export failed",{error:c}),e("code_export","failed",c)}}}else e("code_export","skipped");return this.log("info","PIPELINE_COMPLETE","Pipeline complete"),{success:!0,testId:this.testId,testcaseId:s,shareId:a,codeExportDir:o}}catch(i){return{success:!1,testId:this.testId,error:i instanceof Error?i.message:String(i)}}}async runCodeExport(e,i){let n=i??this.config.onProgress,s=!1;try{await this.triggerCodeExport(e),this.log("info","PIPELINE_CODE_EXPORT_TRIGGER","Code export triggered",{testcase_id:e}),s=!0}catch(a){let o=a instanceof Error?a.message:String(a);this.log("error","PIPELINE_CODE_EXPORT_TRIGGER_FAILED","Code export trigger failed; skipping poll",{error:o}),n("code_export","failed",`trigger failed: ${o}`)}if(s){n("code_export","running","Waiting for code generation\u2026");try{let a=await this.pollAndDownloadCode(e,n);return this.log("info","PIPELINE_CODE_EXPORT_OK","Code export complete",{dir:a}),n("code_export","done",a),a}catch(a){let o=a instanceof Error?a.message:String(a);this.log("error","PIPELINE_CODE_EXPORT_FAILED","Code export failed",{error:o}),n("code_export","failed",o);return}}}collectNdjsonPerRun(){let e=[],i=this.config.runObjectives??[],n=this.config.runMetadata??[],s=this.config.evidence??this.config.evidenceRead;for(let a=0;a<this.config.runDirs.length;a++){let o=this.config.runDirs[a],l=i[a]||this.config.firstObjective,r=n[a],c=s?this.readNdjsonFromFile(E(s.packTestDir,"logs",`${s.runIndices?.[a]??a}-actions.ndjson`)):this.readNdjsonFromDir(o);c.length>0&&e.push({objective:l,records:c,resultCode:r?.resultCode,reasonCode:r?.reasonCode,errorMessage:r?.errorMessage,summary:r?.summary,oneLiner:r?.oneLiner})}if(e.length===0){let a=E(this.config.sessionDir,"runs");if(C(a))try{let l=Re(a,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort();for(let r of l){let c=E(a,r),u=this.readNdjsonFromDir(c);u.length>0&&e.push({objective:this.config.firstObjective,records:u})}}catch{}}return e}readNdjsonFromDir(e){let i=[E(e,"run-test","actions.ndjson"),E(e,"actions.ndjson")];for(let n of i)if(C(n))return this.readNdjsonFromFile(n);return[]}readNdjsonFromFile(e){let i=[];if(!C(e))return i;this.log("debug","PIPELINE_COLLECT_READ","Reading NDJSON file",{path:e});let n=te(e,"utf-8");for(let s of n.split(`
5
+ `)){let a=s.trim();if(a)try{i.push(JSON.parse(a))}catch{}}return i}async generateShareLink(e){let i=`${this.config.shareApiBaseUrl}/lshs/api/v1.0/share-item/generate-sharable-link`;this.log("info","PIPELINE_SHARE_START","Requesting share link",{url:i,testcase_id:e});let n={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({entityIds:[e],entityType:"Test Case Details",expiresAt:7})},s=!!this.config.authResolver;this.log("debug","PIPELINE_SHARE_AUTH","Share link auth config",{resolver:s,fallback_auth_type:typeof this.config.auth=="string"?"bearer":"basic",tms_user:this.config.tmsUsername});let a=s?await this.config.authResolver.fetch(i,n):await O(i,{...n,headers:{...n.headers,Authorization:this.buildAuthHeader()}});if(!a.ok)throw new Error(`Share link API failed: ${a.status} ${await a.text()}`);let o=await a.json();if(!o.shareId)throw new Error("Share link API returned no shareId");return o.shareId}async triggerCodeExport(e){if(!this.config.codeExport)throw new Error("triggerCodeExport called without resolved codeExport config");let{url:i,body:n}=M({tmsBaseUrl:this.config.tmsBaseUrl,testcaseId:e,codeExport:this.config.codeExport});this.log("info","PIPELINE_CODE_EXPORT_POST","Triggering code export",{url:i});let s={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)},a=this.config.authResolver?await this.config.authResolver.fetch(i,s):await O(i,{...s,headers:{...s.headers,Authorization:this.buildAuthHeader()}});if(!a.ok)throw new Error(`Code export failed: ${a.status} ${await a.text()}`)}async pollAndDownloadCode(e,i){let n=B({tmsBaseUrl:this.config.tmsBaseUrl,testcaseId:e}),s=this.config.exitTimeoutMs??3e5,a=5e3,o=Date.now()+s;this.log("info","PIPELINE_CODE_EXPORT_POLL","Polling for code export",{url:n,timeout_ms:s});let l=(r,c)=>this.config.authResolver?this.config.authResolver.fetch(r,c):O(r,{...c,headers:{...c?.headers,Authorization:this.buildAuthHeader()}});for(;Date.now()<o;){let r=await l(n,{method:"GET",headers:{Accept:"application/json"}});if(!r.ok){let d=await r.text().catch(()=>"");throw this.log("warn","PIPELINE_CODE_EXPORT_POLL_FAILED","Code export poll non-200; skipping",{status:r.status,body:d.slice(0,200)}),new Error(`code export poll skipped: HTTP ${r.status}`)}let u=(await r.json()).data?.find(d=>d.code_name==="kane-cli-trigger");if(!u){this.log("debug","PIPELINE_CODE_EXPORT_WAITING","No kane-cli-trigger entry yet"),i("code_export","running","Waiting for code generation\u2026"),await this.sleep(a);continue}let p=u.status.toLowerCase();if(p==="in progress"||p==="in_progress"||p==="pending"){this.log("debug","PIPELINE_CODE_EXPORT_IN_PROGRESS","Code export in progress",{status:u.status}),i("code_export","running","Generating code\u2026"),await this.sleep(a);continue}if(!u.url||u.url.length===0)throw new Error(`Code export status=${u.status} but no files returned`);let _=this.config.codeExportDir??E(this.config.sessionDir,"code-export");D(_,{recursive:!0}),this.log("info","PIPELINE_CODE_EXPORT_DOWNLOAD","Downloading code files",{file_count:u.url.length,dir:_}),i("code_export","running",`Downloading ${u.url.length} files\u2026`);for(let d of u.url){let g=E(_,d.file_name),m=await O(d.file_url);if(!m.ok){this.log("warn","PIPELINE_CODE_EXPORT_FILE_FAILED","Failed to download file",{file_name:d.file_name,status:m.status});continue}let f=await m.text();x(g,f,"utf-8"),this.log("info","PIPELINE_CODE_EXPORT_FILE_SAVED","File saved",{file_name:d.file_name,size_bytes:f.length})}return _}throw new Error("Code export timed out")}sleep(e){return new Promise(i=>setTimeout(i,e))}buildAuthHeader(){return typeof this.config.auth=="string"?`Bearer ${this.config.auth}`:j(this.config.auth.username,this.config.auth.accessKey)}readAuthoredExecution(){let e=this.config.authoredExecutionPath;if(!e)return null;try{let i=te(e,"utf8");return JSON.parse(i),i}catch{return this.log("warn","PIPELINE_AUTHORED_BLOB_UNREADABLE","Authored execution.json missing/unreadable \u2014 pack gets this run's envelope",{path:e}),null}}buildExecutionEnvelope(e){let i=this.config.runStatuses.every(r=>r==="passed")?"success":"error",n=this.config.variableIds??{},s=[];if(this.config.variables)for(let[r,c]of Object.entries(this.config.variables)){if(c.secret)continue;let u=r.startsWith("global.")?r.slice(7):r;s.push({id:n[u]??0,name:u,value:c.value,session_value:c.value,is_persist:!1,environment_id:0,environment_name:"No Env"})}let a=[],o=[],l=new Set;for(let r of this.collectNdjsonPerRun())for(let c of r.records)if(c.output_variable&&c.output_value!=null&&a.push({name:c.output_variable,value:String(c.output_value),value_type:"test_level",variable_description:"ANALYZE result"}),c.action_type==="upload_files"){let u=S(c.action_params);if(u){let p=u.media_id||u.media_url;if(!l.has(p)){l.add(p),o.push({media_url:u.media_url,media_id:u.media_id,name:u.name,type:u.type});let _=N(u.name);a.push({name:$(u.name),value:_,value_type:"string",variable_description:`variable for ${_}`})}}}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:i,commit_id:this.config.commitId,instructions:e,modules:[],uploaded_files:o,test_params:[],test_level_variables:JSON.stringify(a),test_global_variables:s,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{Pe as a,ke as b,ne as c};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as $e}from"./chunk-RLZA4VJT.js";import{a as te}from"./chunk-YVXC46DY.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-W54W762O.js";import{a as ve}from"./chunk-6NWPK2MS.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{y as i}from"./chunk-2KS2YRIS.js";import{a as k}from"./chunk-HCBYKLMW.js";import{a as s,b as o,i as Se,j as Te,k as ee}from"./chunk-C44QQJR4.js";import{a as V}from"./chunk-6YGTRKDT.js";import{e as R}from"./chunk-UR6MHSHU.js";var A=R(V(),1);var C=R(V(),1);function de(e){let t=e.flatMap(u=>[u,...u.children??[]]),n=t.filter(u=>u.status==="passed").length,l=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:n,failed:l,total:a}}function we(e){let t=$e(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[n,l]=(0,C.useState)(0),[a,u]=(0,C.useState)("idle"),c=(0,C.useRef)("idle"),v=(0,C.useRef)(0),S=(0,C.useRef)(!1),T=(0,C.useRef)(null),d=(0,C.useRef)(null),L=(0,C.useCallback)(h=>{c.current=h,u(h)},[]),O=(0,C.useCallback)(async h=>{let b=await e.getNextConfig(h);if(!b){L("done"),e.onAllComplete?.();return}let B=h?v.current+1:0;v.current=B,l(B),e.onStepStart?.(b,B),T.current=null,d.current=null,L("running"),await t.startRun(b,e.spawnOpts)},[t,e,L]);(0,C.useEffect)(()=>{S.current||(S.current=!0,O(null))},[]),(0,C.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===T.current||c.current!=="running")return;T.current=t.lastRunEnd,c.current="transitioning",u("transitioning");let h=t.lastRunEnd,b=de(t.steps),B=t.bifurcationInfo,F={status:h.status==="passed"?"passed":"failed",duration_s:h.duration??0,reason:h.reason,runEnd:h,hadError:!1,stepsPassed:b.passed,stepsFailed:b.failed,stepsTotal:b.total,bifurcationFlows:B&&!B.isSingleFlow?B.flows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(F,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(F)},[t.lastRunEnd]),(0,C.useEffect)(()=>{if(!t.runError||t.runError===d.current||t.lastRunEnd||c.current!=="running")return;d.current=t.runError,c.current="transitioning",u("transitioning");let h=de(t.steps),b={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:h.passed,stepsFailed:h.failed,stepsTotal:h.total,bifurcationFlows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(b,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(b)},[t.runError,t.lastRunEnd]);let y=(0,C.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:n,phase:a,cancel:y}}var pe=R(V(),1);var ne=R(k(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function ke({label:e,hasBifurcation:t=!1}){let[n,l]=(0,pe.useState)(0),[a,u]=(0,pe.useState)(0);K(()=>{l(v=>(v+1)%Ee.length)},80),K(()=>{u(v=>(v+1)%4)},400);let c=e??(t?"Planning approach":"Analyzing objective");return(0,ne.jsxs)(s,{marginLeft:1,children:[(0,ne.jsxs)(o,{color:i.orange,children:[Ee[n]," "]}),(0,ne.jsxs)(o,{color:i.dim,children:[c,".".repeat(a+1)]})]})}function Ie(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let n=e.steps.findIndex(a=>a.status==="running");return(n===-1?e.cmInitCounts.length===0:n>=e.cmInitCounts.length)?{label:n>0?`Planning flow ${n+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(n=>n.children?.length)?null:{hasBifurcation:!!t}}var I=R(V(),1);var Ce=R(V(),1);var re=R(k(),1),He="#ffc580",Ue="#ffd9a8",Le="#ffffff";function oe({text:e,active:t=!0}){let[n,l]=(0,Ce.useState)(0),a=4;if(K(()=>{l(c=>(c+1)%(e.length+a*2))},t?80:null),!t)return(0,re.jsx)(o,{color:Le,children:e});let u=e.split("").map((c,v)=>{let S=n-a,T=Math.abs(v-S-a/2),d;return T<=a/2?d=He:T<=a?d=Ue:d=Le,(0,re.jsx)(o,{color:d,children:c},v)});return(0,re.jsx)(o,{children:u})}var _=R(k(),1),We={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function ie({currentStep:e,maxSteps:t,elapsed:n,status:l}){let a=We[l]??i.orange,u=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`;return(0,_.jsxs)(s,{marginLeft:3,children:[(0,_.jsx)(o,{color:i.dim,children:"Steps "}),(0,_.jsx)(o,{bold:!0,children:e}),(0,_.jsxs)(o,{color:i.dim,children:["/",t]}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Elapsed "}),(0,_.jsx)(o,{bold:!0,children:u}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Status "}),(0,_.jsx)(o,{bold:!0,color:a,children:l})]})}var Ve={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function Oe(e){return Ve[e]??"\u25CF"}var q=R(k(),1);function fe({steps:e,flows:t,cmInitCounts:n,renderStep:l}){return(0,q.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,q.jsxs)(o,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((a,u)=>(0,q.jsxs)(s,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,q.jsxs)(o,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??a.objective]}),n&&n[u]!=null&&(0,q.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",n[u]," checkpoints"]}),a.children&&a.children.length>0?a.children.map(c=>{let v=!!c.branchObjective,S=`f${u}-${c.childId??"p"}-${c.index}`;return v?(0,q.jsxs)(s,{flexDirection:"column",children:[l({...c,children:void 0},S),(c.children??[]).map(T=>(0,q.jsx)(s,{marginLeft:2,children:l(T,`${S}-${T.childId??"p"}-${T.index}`)},`${S}-${T.childId??"p"}-${T.index}`))]},`${S}-host`):l(c,S)}):a.status==="pending"&&(0,q.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var H=R(k(),1);function Pe({label:e,shimmer:t=!1}){return(0,H.jsxs)(s,{marginLeft:6,children:[(0,H.jsx)(te,{}),(0,H.jsx)(o,{children:" "}),t?(0,H.jsx)(oe,{text:e,active:!0}):(0,H.jsx)(o,{color:i.dim,children:e})]})}var De=R(V(),1);var me=R(k(),1);function ze(e,t){let n=[];for(let l of e.split(`
2
+ import{d as $e}from"./chunk-5YHVK2EO.js";import{a as te}from"./chunk-AIMINJVP.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-J3EMJ7US.js";import{a as ve}from"./chunk-5WE4DHXL.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{y as i}from"./chunk-B4LLKQTK.js";import{a as k}from"./chunk-HCBYKLMW.js";import{a as s,b as o,i as Se,j as Te,k as ee}from"./chunk-C44QQJR4.js";import{a as V}from"./chunk-6YGTRKDT.js";import{e as R}from"./chunk-UR6MHSHU.js";var A=R(V(),1);var C=R(V(),1);function de(e){let t=e.flatMap(u=>[u,...u.children??[]]),n=t.filter(u=>u.status==="passed").length,l=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:n,failed:l,total:a}}function we(e){let t=$e(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[n,l]=(0,C.useState)(0),[a,u]=(0,C.useState)("idle"),c=(0,C.useRef)("idle"),v=(0,C.useRef)(0),S=(0,C.useRef)(!1),T=(0,C.useRef)(null),d=(0,C.useRef)(null),L=(0,C.useCallback)(h=>{c.current=h,u(h)},[]),O=(0,C.useCallback)(async h=>{let b=await e.getNextConfig(h);if(!b){L("done"),e.onAllComplete?.();return}let B=h?v.current+1:0;v.current=B,l(B),e.onStepStart?.(b,B),T.current=null,d.current=null,L("running"),await t.startRun(b,e.spawnOpts)},[t,e,L]);(0,C.useEffect)(()=>{S.current||(S.current=!0,O(null))},[]),(0,C.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===T.current||c.current!=="running")return;T.current=t.lastRunEnd,c.current="transitioning",u("transitioning");let h=t.lastRunEnd,b=de(t.steps),B=t.bifurcationInfo,F={status:h.status==="passed"?"passed":"failed",duration_s:h.duration??0,reason:h.reason,runEnd:h,hadError:!1,stepsPassed:b.passed,stepsFailed:b.failed,stepsTotal:b.total,bifurcationFlows:B&&!B.isSingleFlow?B.flows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(F,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(F)},[t.lastRunEnd]),(0,C.useEffect)(()=>{if(!t.runError||t.runError===d.current||t.lastRunEnd||c.current!=="running")return;d.current=t.runError,c.current="transitioning",u("transitioning");let h=de(t.steps),b={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:h.passed,stepsFailed:h.failed,stepsTotal:h.total,bifurcationFlows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(b,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(b)},[t.runError,t.lastRunEnd]);let y=(0,C.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:n,phase:a,cancel:y}}var pe=R(V(),1);var ne=R(k(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function ke({label:e,hasBifurcation:t=!1}){let[n,l]=(0,pe.useState)(0),[a,u]=(0,pe.useState)(0);K(()=>{l(v=>(v+1)%Ee.length)},80),K(()=>{u(v=>(v+1)%4)},400);let c=e??(t?"Planning approach":"Analyzing objective");return(0,ne.jsxs)(s,{marginLeft:1,children:[(0,ne.jsxs)(o,{color:i.orange,children:[Ee[n]," "]}),(0,ne.jsxs)(o,{color:i.dim,children:[c,".".repeat(a+1)]})]})}function Ie(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let n=e.steps.findIndex(a=>a.status==="running");return(n===-1?e.cmInitCounts.length===0:n>=e.cmInitCounts.length)?{label:n>0?`Planning flow ${n+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(n=>n.children?.length)?null:{hasBifurcation:!!t}}var I=R(V(),1);var Ce=R(V(),1);var re=R(k(),1),He="#ffc580",Ue="#ffd9a8",Le="#ffffff";function oe({text:e,active:t=!0}){let[n,l]=(0,Ce.useState)(0),a=4;if(K(()=>{l(c=>(c+1)%(e.length+a*2))},t?80:null),!t)return(0,re.jsx)(o,{color:Le,children:e});let u=e.split("").map((c,v)=>{let S=n-a,T=Math.abs(v-S-a/2),d;return T<=a/2?d=He:T<=a?d=Ue:d=Le,(0,re.jsx)(o,{color:d,children:c},v)});return(0,re.jsx)(o,{children:u})}var _=R(k(),1),We={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function ie({currentStep:e,maxSteps:t,elapsed:n,status:l}){let a=We[l]??i.orange,u=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`;return(0,_.jsxs)(s,{marginLeft:3,children:[(0,_.jsx)(o,{color:i.dim,children:"Steps "}),(0,_.jsx)(o,{bold:!0,children:e}),(0,_.jsxs)(o,{color:i.dim,children:["/",t]}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Elapsed "}),(0,_.jsx)(o,{bold:!0,children:u}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Status "}),(0,_.jsx)(o,{bold:!0,color:a,children:l})]})}var Ve={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function Oe(e){return Ve[e]??"\u25CF"}var q=R(k(),1);function fe({steps:e,flows:t,cmInitCounts:n,renderStep:l}){return(0,q.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,q.jsxs)(o,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((a,u)=>(0,q.jsxs)(s,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,q.jsxs)(o,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??a.objective]}),n&&n[u]!=null&&(0,q.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",n[u]," checkpoints"]}),a.children&&a.children.length>0?a.children.map(c=>{let v=!!c.branchObjective,S=`f${u}-${c.childId??"p"}-${c.index}`;return v?(0,q.jsxs)(s,{flexDirection:"column",children:[l({...c,children:void 0},S),(c.children??[]).map(T=>(0,q.jsx)(s,{marginLeft:2,children:l(T,`${S}-${T.childId??"p"}-${T.index}`)},`${S}-${T.childId??"p"}-${T.index}`))]},`${S}-host`):l(c,S)}):a.status==="pending"&&(0,q.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var H=R(k(),1);function Pe({label:e,shimmer:t=!1}){return(0,H.jsxs)(s,{marginLeft:6,children:[(0,H.jsx)(te,{}),(0,H.jsx)(o,{children:" "}),t?(0,H.jsx)(oe,{text:e,active:!0}):(0,H.jsx)(o,{color:i.dim,children:e})]})}var De=R(V(),1);var me=R(k(),1);function ze(e,t){let n=[];for(let l of e.split(`
3
3
  `)){if(l===""){n.push("");continue}let a="";for(let u of l.split(" ")){let c=u;for(;c.length>t;)a&&(n.push(a),a=""),n.push(c.slice(0,t)),c=c.slice(t);a===""?a=c:a.length+1+c.length<=t?a+=" "+c:(n.push(a),a=c)}n.push(a)}return n}function je({text:e,maxLines:t=3}){let{stdout:n}=ee(),l=Math.max(20,(n?.columns??80)-7),a=!e.trim(),[u,c]=(0,De.useState)(!0);K(()=>c(T=>!T),500);let v=(a?"Thinking\u2026":e)+(u?"\u258C":" "),S=ze(v,l).slice(-t);for(;S.length<t;)S.push("");return(0,me.jsx)(s,{borderStyle:"round",borderColor:i.muted,paddingX:1,marginLeft:3,flexDirection:"column",children:S.map((T,d)=>(0,me.jsx)(o,{color:a?i.dim:i.secondary,wrap:"truncate-end",children:T.length?T:" "},d))})}var U=R(k(),1);function se({activity:e,describe:t,describeVisible:n}){return(0,U.jsxs)(U.Fragment,{children:[e?(0,U.jsx)(Pe,{label:e.label,shimmer:e.shimmer}):null,n?(0,U.jsx)(je,{text:t??""}):null]})}var r=R(k(),1);function le(e){for(let t of e){if(t.children&&t.children.length>0){let n=le(t.children);if(n)return n}if(t.status==="running")return t}}function z(e){return e.status==="running"&&!e.branchObjective&&(!e.children||e.children.length===0)}function Fe(e){let t=[];for(let n of e)z(n)||(n.children&&n.children.length>0?t.push({...n,children:Fe(n.children)}):t.push(n));return t}function ge(e,t){if(!e)return null;let n=e.objective??"";return n.length>0&&!/^Step \d+$/.test(n)?{label:n+"\u2026",shimmer:!1}:{label:t?"Looking at the screen\u2026":"Deciding next action\u2026",shimmer:!0}}function P({step:e,indent:t=2}){let n=e.actionType?Oe(e.actionType):null,l=e.status==="running",a=e.status==="passed",u=e.status==="failed",c=e.status==="pending"||e.status==="stopped",{stdout:v}=ee(),S=v?.columns??80,T=Math.max(20,S-t-21),d=e.objective??"",L=d.length>T?d.slice(0,T-1)+"\u2026":d,O=(e.duration??0)*1e3,y=e.duration!=null?O<1e3?`${Math.round(O)}ms`:`${(O/1e3).toFixed(1)}s`:"";return(0,r.jsxs)(s,{flexDirection:"column",children:[(0,r.jsxs)(s,{marginLeft:t,children:[(0,r.jsx)(s,{width:4,children:(0,r.jsxs)(o,{color:i.muted,children:[String(e.index).padStart(2," ")," "]})}),(0,r.jsx)(s,{width:3,children:l?(0,r.jsx)(te,{}):a?(0,r.jsx)(o,{color:i.green,bold:!0,children:"\u2713"}):u?(0,r.jsx)(o,{color:i.red,bold:!0,children:"\u2717"}):(0,r.jsx)(o,{color:i.muted,children:"\u25CB"})}),(0,r.jsx)(s,{flexGrow:1,children:l?(0,r.jsx)(oe,{text:L,active:!0}):u?(0,r.jsx)(o,{color:i.red,children:L}):c?(0,r.jsx)(o,{color:i.dim,children:L}):(0,r.jsx)(o,{color:i.dim,children:L})}),(a||u)&&n?(0,r.jsx)(s,{width:3,marginLeft:1,children:(0,r.jsx)(o,{color:i.muted,children:n})}):(0,r.jsx)(s,{width:3,marginLeft:1}),(0,r.jsx)(s,{width:7,justifyContent:"flex-end",children:(0,r.jsx)(o,{color:i.dim,children:y})})]}),e.children&&e.children.length>0&&(0,r.jsx)(s,{flexDirection:"column",children:e.children.map((h,b)=>(0,r.jsx)(P,{step:h,indent:t+2},`child-${b}`))})]})}function Xe(e){return e.type==="cm_init"?(0,r.jsx)(s,{marginLeft:2,paddingLeft:1,children:(0,r.jsxs)(o,{color:i.dim,children:["\u25AA Generated task with ",e.count," checkpoints"]})}):(0,r.jsx)(s,{marginLeft:2,paddingLeft:1,children:(0,r.jsx)(P,{step:e.step})})}function _e({steps:e,bifurcated:t,flows:n,cmInitCounts:l,maxSteps:a=50,staticSteps:u=!1,onStepCommit:c,describe:v,describeVisible:S,describeRevealing:T}){let d=(0,I.useRef)(new Set),L=(0,I.useRef)(!1),O=(0,I.useRef)(new Set),y=(0,I.useRef)(!1),h=(0,I.useRef)(new Set),b=(0,I.useRef)(0);(0,I.useEffect)(()=>{e.length===0&&b.current>0&&(d.current.clear(),L.current=!1,O.current.clear(),y.current=!1,h.current.clear()),b.current=e.length},[e.length]);let B=e.flatMap(p=>[p,...p.children??[]]),F=B.some(p=>p.status==="running"),M=B.some(p=>p.status==="failed"),X=B.length===0||B.every(p=>p.status==="pending"),Y=B.filter(p=>p.status==="passed"||p.status==="failed").length,N;X?N="starting":F?N="running":M?N="failed":N="passed";let J=(0,I.useRef)(null),[ce,he]=(0,I.useState)(0);(0,I.useEffect)(()=>{B.length===0||X?(J.current=null,he(0)):F&&J.current==null&&(J.current=Date.now())},[F,X,B.length]),(0,I.useEffect)(()=>{if(!F)return;let p=setInterval(()=>{J.current!=null&&he((Date.now()-J.current)/1e3)},500);return()=>clearInterval(p)},[F]);let ae=(0,I.useRef)(new Set),[,xe]=(0,I.useState)(0),be=(0,I.useRef)(!1);(0,I.useEffect)(()=>{if(!c||!u||t)return;let p=[];!be.current&&l&&l[0]!=null&&(be.current=!0,l[0]>0&&p.push({key:"cm_init_0",type:"cm_init",count:l[0]}));for(let g of e)(g.status==="passed"||g.status==="failed")&&!ae.current.has(g.index)&&(ae.current.add(g.index),p.push({key:`step_${g.index}`,type:"step",step:{...g,children:g.children?[...g.children]:void 0}}));if(p.length>0){for(let g of p)c(Xe(g));xe(g=>g+1)}},[e,t,l,u,c]),(0,I.useEffect)(()=>{if(!c||u)return;let p=d.current.size;if(!t&&!y.current&&l&&l[0]!=null&&(y.current=!0,l[0]>0&&c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:["\u25A0 Generated task with ",l[0]," checkpoints"]})}))),t&&n&&!L.current&&(L.current=!0,c((0,r.jsx)(o,{color:i.purple,children:"\u2501\u2501 Bifurcated into "+n.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),t){let g=e.flatMap((x,f)=>{let m=x.children??[];return!O.current.has(f)&&m.length>0&&(O.current.add(f),c((0,r.jsx)(o,{color:i.purple,children:" Flow "+(f+1)+": "+(n?.[f]??"")})),l?.[f]!=null&&l[f]>0&&!h.current.has(f)&&(h.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",l[f]," checkpoints"]})})))),l?.[f]!=null&&l[f]>0&&O.current.has(f)&&!h.current.has(f)&&(h.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",l[f]," checkpoints"]})}))),m});for(let x of g){let f=`${x.childId??"p"}-${x.index}-${x.objective}`;if(!!x.branchObjective){d.current.has(f)||(d.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...x,children:void 0}})})));for(let $ of x.children??[]){let w=`child-${x.childId??"p"}-${x.index}-${$.childId??"p"}-${$.index}-${$.objective}`;d.current.has(w)||($.status==="passed"||$.status==="failed"||$.status==="stopped")&&(d.current.add(w),c((0,r.jsx)(s,{marginLeft:4,children:(0,r.jsx)(P,{step:$})})))}continue}d.current.has(f)||(x.status==="passed"||x.status==="failed"||x.status==="stopped")&&(d.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:x})})))}}else for(let g of e){let x=`${g.index}-${g.objective}`,f=!!g.branchObjective;f&&!d.current.has(x)&&(d.current.add(x),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...g,children:void 0}})})));for(let m of g.children??[]){let $=`child-${g.index}-${m.childId??"p"}-${m.index}-${m.objective}`;d.current.has($)||(m.status==="passed"||m.status==="failed"||m.status==="stopped")&&(d.current.add($),c((0,r.jsx)(s,{marginLeft:4,children:(0,r.jsx)(P,{step:m})})))}!f&&!d.current.has(x)&&(g.status==="passed"||g.status==="failed"||g.status==="stopped")&&(d.current.add(x),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...g,children:void 0}})})))}d.current.size>p&&xe(g=>g+1)},[e,c,t,n,l]);let G=[];if(u&&!t)for(let p of e)ae.current.has(p.index)||G.push(p);else if(c&&!u)if(t)for(let p of e){let g=p.children??[],x=[];for(let f of g){let m=`${f.childId??"p"}-${f.index}-${f.objective}`,$=d.current.has(m);if(f.branchObjective){let w=(f.children??[]).filter(Q=>{let ue=`child-${f.childId??"p"}-${f.index}-${Q.childId??"p"}-${Q.index}-${Q.objective}`;return!d.current.has(ue)});(!$||w.length>0)&&x.push({...f,children:w})}else $||x.push(f)}x.length>0&&G.push({...p,children:x})}else for(let p of e){let g=`${p.index}-${p.objective}`,x=d.current.has(g),f=(p.children??[]).filter(m=>{let $=`child-${p.index}-${m.childId??"p"}-${m.index}-${m.objective}`;return!d.current.has($)});x?f.length>0&&G.push({...p,children:f}):G.push({...p,children:f})}if(!u){let p=c?G:e,g=le(p),x=ge(g,T);return(0,r.jsxs)(s,{flexDirection:"column",children:[t?c?p.length>0?(0,r.jsx)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:p.map((m,$)=>(0,r.jsx)(s,{flexDirection:"column",marginTop:$>0?1:0,children:m.children&&m.children.length>0?m.children.map(w=>{if(z(w))return null;let Q=!!w.branchObjective,ue=`${w.childId??"p"}-${w.index}-${w.objective}`,Ke=d.current.has(ue);return Q?(0,r.jsxs)(s,{flexDirection:"column",children:[!Ke&&(0,r.jsx)(P,{step:{...w,children:void 0}}),(w.children??[]).filter(Z=>!z(Z)).map(Z=>(0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:Z})},`f${$}-${w.index}-${Z.childId??"p"}-${Z.index}`))]},`f${$}-host-${w.childId??"p"}-${w.index}`):(0,r.jsx)(P,{step:w},`f${$}-${w.childId??"p"}-${w.index}`)}):m.status==="pending"&&(0,r.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})},$))}):null:(0,r.jsx)(fe,{steps:e,flows:n,cmInitCounts:l,renderStep:(m,$)=>z(m)?null:(0,r.jsx)(P,{step:m},$)}):(0,r.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!c&&l&&l[0]!=null&&(0,r.jsxs)(o,{color:i.dim,children:["\u25AA Generated task with ",l[0]," checkpoints"]}),p.filter(m=>!(m.status==="running"&&(!m.children||m.children.length===0))).map(m=>{let $=`${m.index}-${m.objective}`;return c&&d.current.has($)?(0,r.jsx)(s,{flexDirection:"column",children:(m.children??[]).filter(w=>!z(w)).map(w=>(0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:w})},`${w.childId??"p"}-${w.index}`))},`branch-children-${m.index}`):(0,r.jsx)(P,{step:m},m.index)})]}),(0,r.jsx)(se,{activity:x,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}if(t){let p=le(e),g=ge(p,T);return(0,r.jsxs)(s,{flexDirection:"column",children:[(0,r.jsx)(fe,{steps:e,flows:n,cmInitCounts:l,renderStep:(x,f)=>z(x)?null:(0,r.jsx)(P,{step:x},f)}),(0,r.jsx)(se,{activity:g,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}let Ne=le(G),Ge=ge(Ne,T),Re=Fe(G);return(0,r.jsxs)(s,{flexDirection:"column",children:[Re.length>0&&(0,r.jsx)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:Re.map(p=>(0,r.jsx)(P,{step:p},p.index))}),(0,r.jsx)(se,{activity:Ge,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}var W=R(k(),1);function Ae({runner:e,runKey:t,onStepCommit:n}){let l=Ie({isRunning:e.isRunning,bifurcationInfo:e.bifurcationInfo,steps:e.steps,cmInitCounts:e.cmInitCounts,replayInfo:e.replayInfo});return(0,W.jsxs)(W.Fragment,{children:[l&&(0,W.jsx)(ke,{label:l.label,hasBifurcation:l.hasBifurcation}),e.isRunning&&e.steps.length>0&&(0,W.jsx)(_e,{steps:e.steps,bifurcated:!!e.bifurcationInfo&&!e.bifurcationInfo.isSingleFlow,flows:e.bifurcationInfo?.flows,cmInitCounts:e.cmInitCounts,maxSteps:e.maxSteps,onStepCommit:n},`run-${t}`)]})}var D=R(k(),1),Ye=64;function Je(e){return e.split(`
4
4
  `).map(t=>t.replace(/^[-–•]\s*/,"").trim()).filter(t=>t.length>0)}function qe({status:e,summary:t,duration:n,steps:l,stepsPassed:a,stepsFailed:u,reason:c,creditsConsumed:v}){let S=e==="passed",T=S?i.green:i.red,d=S?"\u2713":"\u2717",L=e.toUpperCase(),O=a??(S?l:Math.max(0,l-1)),y=u??(S?0:1),h=y>0?`${l} steps (${O} passed, ${y} failed)`:`${l} steps`,b=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`,B=Je(t);return(0,D.jsx)(s,{flexDirection:"column",marginTop:1,children:(0,D.jsxs)(s,{borderStyle:"round",borderColor:T,flexDirection:"column",paddingX:2,paddingY:1,width:Ye+6,children:[(0,D.jsxs)(s,{flexDirection:"column",children:[(0,D.jsxs)(o,{bold:!0,color:T,children:[d," ",L]}),(0,D.jsxs)(o,{color:i.dim,wrap:"wrap",children:[h," \xB7 ",b,typeof v=="number"&&v>0?` \xB7 ${parseFloat(v.toFixed(4))} credits`:""]})]}),B.length>0&&(0,D.jsx)(s,{flexDirection:"column",marginTop:1,marginLeft:1,children:B.map((F,M)=>(0,D.jsxs)(s,{marginBottom:M<B.length-1?1:0,children:[(0,D.jsx)(o,{color:i.orange,children:"\u25CF "}),(0,D.jsx)(s,{flexShrink:1,children:(0,D.jsx)(o,{wrap:"wrap",children:F})})]},M))}),c&&!S&&(0,D.jsx)(s,{marginTop:1,children:(0,D.jsxs)(o,{color:i.red,wrap:"wrap",children:["Reason: ",c]})})]})})}var j=R(k(),1);function Me({message:e,code:t,remediation:n,docsUrl:l}){return(0,j.jsx)(ve,{title:"Error",variant:"error",children:(0,j.jsxs)(s,{flexDirection:"column",paddingY:1,children:[(0,j.jsxs)(o,{color:i.red,bold:!0,children:[" \u2717 ",e]}),t&&(0,j.jsxs)(s,{marginTop:0,marginLeft:5,children:[(0,j.jsx)(o,{color:i.muted,children:"Code: "}),(0,j.jsx)(o,{color:i.dim,children:t})]}),n&&(0,j.jsxs)(s,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,j.jsx)(o,{color:i.green,bold:!0,children:"Fix:"}),(0,j.jsxs)(o,{color:i.orange,children:["$ ",n]})]}),l&&(0,j.jsxs)(s,{marginTop:1,marginLeft:5,children:[(0,j.jsx)(o,{color:i.muted,children:"Docs: "}),(0,j.jsx)(o,{color:i.orange,underline:!0,children:l})]})]})})}var E=R(k(),1);function un(e){let{exit:t}=Te(),{append:n}=ye(),l=(0,A.useRef)(!1);(0,A.useEffect)(()=>{l.current||(l.current=!0,n((0,E.jsx)(s,{flexDirection:"column",marginBottom:1,children:(0,E.jsxs)(s,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,E.jsx)(o,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,E.jsx)(o,{color:i.dim,children:" \u2502 "}),(0,E.jsx)(o,{color:i.orange,children:e.topBanner.model}),(0,E.jsx)(o,{color:i.dim,children:" \u2502 "}),(0,E.jsx)(o,{color:i.dim,children:e.topBanner.auth})]})})),n((0,E.jsx)(Qe,{data:e.globalConfig})),e.priorAttemptRollup&&n((0,E.jsx)(o,{color:i.dim,children:` \u21B3 replayed ${e.priorAttemptRollup.startIdx}..${e.priorAttemptRollup.endIdx-1} (${e.priorAttemptRollup.count} steps, from prior attempt)`})))},[]);let a=(0,A.useRef)(null),u=(0,A.useCallback)(async y=>{let h=await e.getNextStep(y);return h?(a.current=h,h.config):(a.current=null,null)},[e]),c=(0,A.useCallback)((y,h)=>{let b=a.current;if(!b)return;let B=b.mode==="replay"?"cyan":"#dc4e08",F=b.modeReason?` (${b.modeReason})`:"",M=b.perStepOverrides?Object.entries(b.perStepOverrides):[];n((0,E.jsxs)(s,{flexDirection:"column",marginBottom:0,children:[(0,E.jsxs)(o,{children:[(0,E.jsxs)(o,{color:i.dim,children:[b.banner.stepLabel," "]}),(0,E.jsxs)(o,{color:B,children:["[",b.mode,"]"]}),(0,E.jsx)(o,{color:i.dim,children:F})]}),(0,E.jsx)(o,{color:i.dim,children:b.banner.objective}),M.length>0&&(0,E.jsxs)(o,{color:i.dim,children:["overrides: ",M.map(([X,Y])=>`${X}=${Y}`).join(", ")]})]}))},[n]),v=(0,A.useRef)(0),S=(0,A.useRef)(!1),T=(0,A.useCallback)((y,h)=>(y.hadError?n((0,E.jsx)(Me,{message:y.reason??"Runner error",code:"RUNNER_ERROR"})):n((0,E.jsx)(s,{flexDirection:"column",marginBottom:1,children:(0,E.jsx)(qe,{status:y.status,summary:y.runEnd?.summary??"",duration:y.runEnd?.duration??0,steps:y.stepsTotal,stepsPassed:y.stepsPassed,stepsFailed:y.stepsFailed,reason:y.runEnd?.reason,creditsConsumed:y.runEnd?.credits_consumed})})),e.onStepEnd?.(y,h)??!0),[n,e]),d=we({getNextConfig:u,onStepStart:c,onStepEnd:T,onAllComplete:()=>{e.onAllComplete(),e.exitOnComplete!==!1&&setImmediate(()=>t())},screenshotDispatcher:e.screenshotDispatcher,stepLogger:e.stepLogger,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete,spawnOpts:e.spawnOpts}),L=250,O=5e3;return Se((y,h)=>{if(h.ctrl&&y==="c"){let b=Date.now(),B=b-v.current;if(B<L)return;S.current&&B<O?(d.cancel(),e.onCancel?.(),e.exitOnComplete!==!1&&setImmediate(()=>t())):(S.current=!0,n((0,E.jsx)(o,{color:"yellow",children:"press Ctrl+C again to cancel run"}))),v.current=b}}),(0,E.jsx)(s,{flexDirection:"column",children:d.phase!=="done"&&(0,E.jsx)(Ae,{runner:d.runner,runKey:d.currentStepIndex,onStepCommit:n})})}function Qe({data:e}){return(0,E.jsx)(Be,{title:"test.md run",titleColor:"#ff9500",borderColor:i.dim,rows:[{label:"source",value:e.source},{label:"steps",value:`${e.steps.total} (${e.steps.replay} replay, ${e.steps.author} author per walker)`},{label:"model",value:e.model},{label:"viewport",value:`${e.viewport.width} x ${e.viewport.height}`},{label:"chrome",value:e.chrome},{label:"session",value:e.session},{label:"variables",value:`${e.variables.count} (${e.variables.secrets} secret)`},{label:"flags",value:e.flags.length>0?e.flags.join(" "):"(none)"}]})}export{_e as a,ke as b,Ie as c,de as d,qe as e,Me as f,un as g};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as Me}from"./chunk-KHU7C6EE.js";import{c as je}from"./chunk-SKRZN25J.js";import{a as de,b as Ae,c as Te,d as Oe,g as Ie,h as Pe}from"./chunk-ZFFRHV5U.js";import{b as qe,c as Le}from"./chunk-J44RN3FB.js";import{a as Be,b as Fe}from"./chunk-3C5GMAM4.js";import{a as $e}from"./chunk-GG43HSU2.js";import{c as Ce}from"./chunk-OSALXGD4.js";import{a as Ne}from"./chunk-CVOGP253.js";import{a as De,b as Re}from"./chunk-FHKDTM5L.js";import{b as fe,c as he,d as _e,e as ae,f as ne,g as ie}from"./chunk-ZPDM6FO7.js";import{a as oe}from"./chunk-L5LI2JF4.js";import{a as Y}from"./chunk-SDRFTIRU.js";import{c as xe,n as Ee}from"./chunk-A46NBRAP.js";import{a as we,b as ce}from"./chunk-L4JIMNKW.js";import{c as Se,e as ke}from"./chunk-MBXWXBDM.js";import{d as v,e as D,f as be,g as ye,h as ve}from"./chunk-5YPBPZUR.js";import{a as pe}from"./chunk-5EOX4MEY.js";import{mkdirSync as mt,appendFileSync as gt}from"fs";import{randomBytes as pt}from"crypto";import{dirname as ft,join as ht}from"path";import{existsSync as le,readFileSync as ue,readdirSync as nt}from"fs";import{join as Z}from"path";var Ge=`
2
+ import{c as je}from"./chunk-3RZ63RBO.js";import{a as Me}from"./chunk-KHU7C6EE.js";import{a as de,b as Ae,c as Te,d as Oe,g as Ie,h as Pe}from"./chunk-JSF5JYZC.js";import{b as qe,c as Le}from"./chunk-J44RN3FB.js";import{a as Ne}from"./chunk-CVOGP253.js";import{a as Be,b as Fe}from"./chunk-3C5GMAM4.js";import{a as $e}from"./chunk-GG43HSU2.js";import{c as Ce}from"./chunk-FMR2KPSK.js";import{a as De,b as Re}from"./chunk-FHKDTM5L.js";import{b as fe,c as he,d as _e,e as ae,f as ne,g as ie}from"./chunk-ZPDM6FO7.js";import{a as oe}from"./chunk-L5LI2JF4.js";import{a as Y}from"./chunk-7E24OCGX.js";import{c as xe,n as Ee}from"./chunk-6W6AIDLJ.js";import{a as we,b as ce}from"./chunk-6HYW5RFX.js";import{c as Se,e as ke}from"./chunk-J2KSZUOO.js";import{d as v,e as D,f as be,g as ye,h as ve}from"./chunk-5YPBPZUR.js";import{a as pe}from"./chunk-5EOX4MEY.js";import{mkdirSync as mt,appendFileSync as gt}from"fs";import{randomBytes as pt}from"crypto";import{dirname as ft,join as ht}from"path";import{existsSync as le,readFileSync as ue,readdirSync as nt}from"fs";import{join as Z}from"path";var Ge=`
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{a as b}from"./chunk-TW3K2DKB.js";import{n as d,y as o}from"./chunk-2KS2YRIS.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
2
+ import{a as b}from"./chunk-4GLYNAK7.js";import{n as d,y as o}from"./chunk-B4LLKQTK.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as l}from"./chunk-QGBLC4ZJ.js";import{a as p}from"./chunk-RZ4F3BHX.js";import{a as m}from"./chunk-RH4GCEFX.js";import{a as f}from"./chunk-YJIESLN6.js";import{a as c,c as s,i as a,x as u}from"./chunk-2KS2YRIS.js";var v="/public/skills/kane-cli";function C(){try{let n=new f().getDefaultEnv();if(n in u)return n}catch{}return"prod"}function k(){return`${m(C()).controllerBaseUrl}${v}`}import{readFileSync as S,writeFileSync as E,mkdirSync as g}from"fs";import{join as d}from"path";var h=d(s,"skill-check.json"),y=3600*1e3;function V(){try{let n=JSON.parse(S(h,"utf-8"));if(Date.now()-n.checkedAt<y)return n}catch{}return null}function A(n){try{g(s,{recursive:!0}),E(h,JSON.stringify({map:n,checkedAt:Date.now()}))}catch{}}function I(){for(let{dir:n}of a)try{let t=S(d(n,"VERSION"),"utf-8").trim();if(t)return t}catch{}return null}function M(n,t){let i=Object.keys(n.versions??{});if(i.length===0)return null;let o=i.slice().sort((r,e)=>l(r,e));for(let r of o){let e=n.versions[r]?.kaneCliMinVersion;if(!e||l(t,e)<=0)return r}return null}async function U(){try{let n=V()?.map;if(!n){let o=new AbortController,r=setTimeout(()=>o.abort(),5e3),e=await p(k(),{headers:{Accept:"application/json"},signal:o.signal});if(clearTimeout(r),!e.ok)return null;n=await e.json(),A(n)}let t=M(n,c);if(!t)return null;let i=I();return i===null?{current:null,latestCompatible:t}:l(i,t)>0?{current:i,latestCompatible:t}:null}catch{return null}}export{k as a,M as b,U as c};
2
+ import{b as l}from"./chunk-DFDDUMG5.js";import{a as p}from"./chunk-RZ4F3BHX.js";import{a as m}from"./chunk-A2IQRVPR.js";import{a as f}from"./chunk-WREVEATJ.js";import{a as c,c as s,i as a,x as u}from"./chunk-B4LLKQTK.js";var v="/public/skills/kane-cli";function C(){try{let n=new f().getDefaultEnv();if(n in u)return n}catch{}return"prod"}function k(){return`${m(C()).controllerBaseUrl}${v}`}import{readFileSync as S,writeFileSync as E,mkdirSync as g}from"fs";import{join as d}from"path";var h=d(s,"skill-check.json"),y=3600*1e3;function V(){try{let n=JSON.parse(S(h,"utf-8"));if(Date.now()-n.checkedAt<y)return n}catch{}return null}function A(n){try{g(s,{recursive:!0}),E(h,JSON.stringify({map:n,checkedAt:Date.now()}))}catch{}}function I(){for(let{dir:n}of a)try{let t=S(d(n,"VERSION"),"utf-8").trim();if(t)return t}catch{}return null}function M(n,t){let i=Object.keys(n.versions??{});if(i.length===0)return null;let o=i.slice().sort((r,e)=>l(r,e));for(let r of o){let e=n.versions[r]?.kaneCliMinVersion;if(!e||l(t,e)<=0)return r}return null}async function U(){try{let n=V()?.map;if(!n){let o=new AbortController,r=setTimeout(()=>o.abort(),5e3),e=await p(k(),{headers:{Accept:"application/json"},signal:o.signal});if(clearTimeout(r),!e.ok)return null;n=await e.json(),A(n)}let t=M(n,c);if(!t)return null;let i=I();return i===null?{current:null,latestCompatible:t}:l(i,t)>0?{current:i,latestCompatible:t}:null}catch{return null}}export{k as a,M as b,U as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as c,c as p}from"./chunk-WV42KKEU.js";import{spawn as y}from"child_process";var h=new Set(["progress","ask_user","graph_query","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete"]);function w(l,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:c();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=l.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=y(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(l.session_id,n.auth)});if(t.stdin.write(JSON.stringify(l)+`
2
+ import{b as c,c as p}from"./chunk-RCTM7NGT.js";import{spawn as y}from"child_process";var h=new Set(["progress","ask_user","graph_query","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete"]);function w(l,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:c();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=l.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=y(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(l.session_id,n.auth)});if(t.stdin.write(JSON.stringify(l)+`
3
3
  `),n.onStderr){let e="";t.stderr.on("data",r=>{e+=r.toString("utf8");let i;for(;(i=e.indexOf(`
4
4
  `))>=0;){let o=e.slice(0,i);e=e.slice(i+1),o.trim()&&n.onStderr(o)}})}let d=new Promise(e=>{t.on("exit",(r,i)=>e({code:r,signal:i}))});async function*m(){let e="",r=!1;for await(let i of t.stdout){e+=i.toString("utf8");let o;for(;(o=e.indexOf(`
5
5
  `))>=0;){let g=e.slice(0,o).trim();if(e=e.slice(o+1),!g)continue;let u;try{u=JSON.parse(g)}catch{n.onWarn?.(`agent: skipping malformed line: ${g.slice(0,120)}`);continue}let s=u;if(!s||typeof s!="object"||!h.has(s.type)){n.onWarn?.(`agent: skipping unknown event type "${s&&typeof s=="object"?String(s.type??"?"):"?"}"`);continue}if(yield s,s.type==="done"){r=!0;break}}if(r)break}await d.catch(()=>{})}return{events:m(),send:e=>{t.stdin&&!t.stdin.destroyed&&t.stdin.write(JSON.stringify(e)+`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as n}from"./chunk-RZ4F3BHX.js";import{a as c}from"./chunk-RH4GCEFX.js";import{v as s,w as a}from"./chunk-2KS2YRIS.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
2
+ import{a as n}from"./chunk-RZ4F3BHX.js";import{a as c}from"./chunk-A2IQRVPR.js";import{v as s,w as a}from"./chunk-B4LLKQTK.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};