@testmuai/kane-cli 0.8.14 → 0.8.15

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 (189) hide show
  1. package/dist/{ChatSurface-AVL3TJA2.js → ChatSurface-2GPR4S7I.js} +1 -1
  2. package/dist/{ChromeProfilePicker-WJZJOZ6Z.js → ChromeProfilePicker-XAZGCJKR.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-65BQF5G5.js → CliFeedbackPrompt-4SILDU7S.js} +1 -1
  4. package/dist/{CliUploadProgress-HEBZYKGN.js → CliUploadProgress-OAQBY55Y.js} +1 -1
  5. package/dist/{ConfigView-JEVQ2SO4.js → ConfigView-FDBMJC26.js} +1 -1
  6. package/dist/EvidenceViewOffer-YSNRKKPC.js +2 -0
  7. package/dist/FolderPicker-XCTJ5447.js +2 -0
  8. package/dist/{InfoBox-KM5DLBCV.js → InfoBox-ZPUBB7J4.js} +1 -1
  9. package/dist/{LinksBox-FQA36GTV.js → LinksBox-MNNNOH23.js} +1 -1
  10. package/dist/{ProfilesView-76KGHTMK.js → ProfilesView-GY5QCIT3.js} +1 -1
  11. package/dist/{ProjectPicker-65YOU46H.js → ProjectPicker-UCHMCNFV.js} +1 -1
  12. package/dist/{SaveSessionPrompt-QD6BNTWO.js → SaveSessionPrompt-ATVHKAHN.js} +1 -1
  13. package/dist/SingleShotApp-IPNZBFXB.js +2 -0
  14. package/dist/{SummaryBox-N2B6DUDD.js → SummaryBox-2DTNE25L.js} +1 -1
  15. package/dist/TestMdRunView-2FQIEI5W.js +2 -0
  16. package/dist/{TestrunEvidenceTable-3WLQVTF4.js → TestrunEvidenceTable-6UE5EMON.js} +1 -1
  17. package/dist/{WhoamiView-T26HA4ZZ.js → WhoamiView-TFCHIOW5.js} +1 -1
  18. package/dist/{app-download-XKZWFMEK.js → app-download-N7MLJQ42.js} +1 -1
  19. package/dist/{auth-PPJANIMZ.js → auth-IQPCVCZK.js} +1 -1
  20. package/dist/{binary-DKWWODT2.js → binary-VML7EGV4.js} +1 -1
  21. package/dist/{bind-62AZYFAY.js → bind-YV6V5AI6.js} +2 -2
  22. package/dist/{bootstrap-6IJNZIPT.js → bootstrap-KCPWDBLX.js} +1 -1
  23. package/dist/bridge-5UKX7YIO.js +2 -0
  24. package/dist/{changelog-UTGJ7FSP.js → changelog-CJFWGRIL.js} +1 -1
  25. package/dist/chunk-27ERHOW3.js +2 -0
  26. package/dist/{chunk-WR42Q3HU.js → chunk-2WRBCTNM.js} +1 -1
  27. package/dist/{chunk-73ULUGBM.js → chunk-3D5MKSG3.js} +1 -1
  28. package/dist/{chunk-2BFXT7VQ.js → chunk-3GELV4IN.js} +3 -3
  29. package/dist/{chunk-O6U2HU5M.js → chunk-4TMQTSIO.js} +1 -1
  30. package/dist/{chunk-X74PP5NJ.js → chunk-5HTSKF5K.js} +1 -1
  31. package/dist/{chunk-MLRO7OH3.js → chunk-6DHEOPXX.js} +1 -1
  32. package/dist/{chunk-WBHSPN55.js → chunk-6GLFQHSW.js} +2 -2
  33. package/dist/chunk-6K4FDYMH.js +89 -0
  34. package/dist/{chunk-3BHRGHIZ.js → chunk-6L5RV62W.js} +1 -1
  35. package/dist/{chunk-N7ZRF5K3.js → chunk-74FHTDEE.js} +1 -1
  36. package/dist/{chunk-CGT4NFQN.js → chunk-7EGIX6Y4.js} +2 -2
  37. package/dist/{chunk-3YX3RQXO.js → chunk-7WDPU33M.js} +1 -1
  38. package/dist/{chunk-JKX57HA7.js → chunk-7X4R6464.js} +1 -1
  39. package/dist/{chunk-RQLU4NDG.js → chunk-A557OSRS.js} +1 -1
  40. package/dist/{chunk-3SPOJWRA.js → chunk-AYJ2YZP5.js} +1 -1
  41. package/dist/{chunk-YHVG7V3E.js → chunk-BMVE73M7.js} +1 -1
  42. package/dist/chunk-CAOZKSQ3.js +8 -0
  43. package/dist/{chunk-L6MOO4WT.js → chunk-CNPIJFZM.js} +1 -1
  44. package/dist/{chunk-EMSLJTYN.js → chunk-D6GBOFK5.js} +1 -1
  45. package/dist/{chunk-FFFB5BXL.js → chunk-DMCEGMGB.js} +1 -1
  46. package/dist/{chunk-J7NRD4Q7.js → chunk-DMT3W26F.js} +1 -1
  47. package/dist/{chunk-NOLYYHVG.js → chunk-EDQZIEPJ.js} +1 -1
  48. package/dist/{chunk-K7K23DIQ.js → chunk-EFTRH35G.js} +1 -1
  49. package/dist/{chunk-LL5DQO6V.js → chunk-EJXBKCNF.js} +1 -1
  50. package/dist/{chunk-OH2NSBO6.js → chunk-EPE2ELDH.js} +1 -1
  51. package/dist/{chunk-42FHKRPA.js → chunk-FXO7JKMZ.js} +3 -3
  52. package/dist/{chunk-VNFCX2SH.js → chunk-GSDXZS4U.js} +1 -1
  53. package/dist/{chunk-4K5XTIJ6.js → chunk-GZ65ZA4C.js} +1 -1
  54. package/dist/{chunk-Q7XBMBMR.js → chunk-HLCETZ73.js} +1 -1
  55. package/dist/{chunk-B2ZGG7WM.js → chunk-HYTBEPC2.js} +1 -1
  56. package/dist/{chunk-AC7BPO4X.js → chunk-IAHOLH5W.js} +1 -1
  57. package/dist/{chunk-GESG672R.js → chunk-JCMHB4KH.js} +1 -1
  58. package/dist/{chunk-XGHMZJGI.js → chunk-JFUFWICY.js} +2 -2
  59. package/dist/{chunk-JH6E632O.js → chunk-JGAMMOUC.js} +1 -1
  60. package/dist/{chunk-KOL6ZWOQ.js → chunk-JL3L6KOG.js} +1 -1
  61. package/dist/chunk-JQCOKL6U.js +15 -0
  62. package/dist/{chunk-M7DN6FO3.js → chunk-JSS22MFY.js} +9 -9
  63. package/dist/chunk-JVEZBJJ7.js +2 -0
  64. package/dist/{chunk-ZWHPIR2Z.js → chunk-KALEPJAV.js} +2 -2
  65. package/dist/{chunk-O2APH6TZ.js → chunk-KUS324VE.js} +1 -1
  66. package/dist/{chunk-NDCRJXYF.js → chunk-LJGAXIDU.js} +1 -1
  67. package/dist/{chunk-ZKEOPIQ3.js → chunk-M36MOFJW.js} +1 -1
  68. package/dist/{chunk-O5AS2ZIX.js → chunk-MLYNVJNH.js} +1 -1
  69. package/dist/{chunk-GKZ2KVE6.js → chunk-N3CVR4Z2.js} +1 -1
  70. package/dist/{chunk-6F6YI3ZG.js → chunk-NLEA6NPU.js} +1 -1
  71. package/dist/{chunk-SGHP44WS.js → chunk-NUJVYAI4.js} +1 -1
  72. package/dist/{chunk-IQ7NGOAT.js → chunk-NWNG5UWD.js} +1 -1
  73. package/dist/{chunk-IICQ5KRD.js → chunk-O66WXOOC.js} +3 -3
  74. package/dist/{chunk-ZA4M4O7E.js → chunk-OFWJBOGT.js} +2 -2
  75. package/dist/{chunk-MNE5VMHT.js → chunk-OGDAWNFY.js} +1 -1
  76. package/dist/{chunk-75I46VTM.js → chunk-ORQGQSWG.js} +2 -2
  77. package/dist/{chunk-YHR2YAN5.js → chunk-OWGFFJKK.js} +1 -1
  78. package/dist/{chunk-SQDQADWD.js → chunk-PGXJ275T.js} +1 -1
  79. package/dist/{chunk-P3JUE2RM.js → chunk-Q77QO3PC.js} +4 -4
  80. package/dist/{chunk-JJJSDDQ2.js → chunk-QVLYK5JL.js} +1 -1
  81. package/dist/{chunk-UXH3RMQ7.js → chunk-QXRT6HSV.js} +1 -1
  82. package/dist/{chunk-RH6KFHJB.js → chunk-R7QMZBBH.js} +1 -1
  83. package/dist/{chunk-BJYGWXVP.js → chunk-RI4ILZZC.js} +1 -1
  84. package/dist/{chunk-PGU64EWQ.js → chunk-RQILLYSP.js} +1 -1
  85. package/dist/chunk-S4JUCBCT.js +7 -0
  86. package/dist/{chunk-4BBDKWM3.js → chunk-SHSXOYKT.js} +1 -1
  87. package/dist/{chunk-7RAI77XD.js → chunk-SIYSKT6I.js} +1 -1
  88. package/dist/{chunk-22QIVSQR.js → chunk-SWTJMTBY.js} +1 -1
  89. package/dist/{chunk-X5276I5H.js → chunk-T4R26WER.js} +2 -2
  90. package/dist/{chunk-BAKJPQGU.js → chunk-TEHZUSUY.js} +1 -1
  91. package/dist/{chunk-RBHQXWR7.js → chunk-TVELOH5A.js} +1 -1
  92. package/dist/{chunk-6LGED4FC.js → chunk-UHSNUUX3.js} +2 -2
  93. package/dist/{chunk-QPUVOVD7.js → chunk-UZIMYV5U.js} +1 -1
  94. package/dist/{chunk-WILT62DP.js → chunk-VOTIGXQ4.js} +1 -1
  95. package/dist/{chunk-SFTFHFG3.js → chunk-VZDLRJ5N.js} +1 -1
  96. package/dist/{chunk-2RMHDOP4.js → chunk-W77SZLFC.js} +1 -1
  97. package/dist/{chunk-QJ5O27SJ.js → chunk-WFBJNVMQ.js} +1 -1
  98. package/dist/{chunk-SX56MVUO.js → chunk-WNB2IYHY.js} +1 -1
  99. package/dist/chunk-XSUJJB7Z.js +11 -0
  100. package/dist/{chunk-NBMLBCJ3.js → chunk-XUJXGE42.js} +1 -1
  101. package/dist/{chunk-ARG56PJG.js → chunk-XXE7W5AV.js} +1 -1
  102. package/dist/{chunk-DA57DXCF.js → chunk-YAAQER2L.js} +1 -1
  103. package/dist/{chunk-7L25ZNNP.js → chunk-YGMUNNKH.js} +1 -1
  104. package/dist/{chunk-OO5GMBVI.js → chunk-YKYKOV6U.js} +1 -1
  105. package/dist/{chunk-C74ABM24.js → chunk-YZVR7ESF.js} +1 -1
  106. package/dist/{chunk-GPIXV7AV.js → chunk-Z3YYMZHT.js} +1 -1
  107. package/dist/{chunk-WOA7VCGA.js → chunk-Z73ZYROU.js} +1 -1
  108. package/dist/{chunk-LR5DJ6EN.js → chunk-ZCSEBT2W.js} +1 -1
  109. package/dist/{chunk-KOPP4CJW.js → chunk-ZEVU2OT3.js} +1 -1
  110. package/dist/{chunk-IQ7GPETF.js → chunk-ZKCCG3GK.js} +1 -1
  111. package/dist/{config-3AKWRTFS.js → config-UGCWZGH5.js} +1 -1
  112. package/dist/{cover-cmd-ZLAWMEC2.js → cover-cmd-SWJ2NZUZ.js} +1 -1
  113. package/dist/{credentials-Q4WH5CBN.js → credentials-GWLYYRTL.js} +1 -1
  114. package/dist/{deps-bundle-RVZK6LZJ.js → deps-bundle-VNGC2UG6.js} +1 -1
  115. package/dist/{deps-resolve-6F2U4TJP.js → deps-resolve-YLCEU6I7.js} +1 -1
  116. package/dist/{dispatch-46BETGXY.js → dispatch-OMQCT7WO.js} +1 -1
  117. package/dist/{doctor-WRPG56HH.js → doctor-B4Z6RPKQ.js} +1 -1
  118. package/dist/{evidence-XWR32HWP.js → evidence-XJGXVLO5.js} +1 -1
  119. package/dist/{evolve-cmd-27ZQN6YB.js → evolve-cmd-QQQPPGL3.js} +1 -1
  120. package/dist/{explain-cmd-JCJTXVZY.js → explain-cmd-XVE6Z67Q.js} +1 -1
  121. package/dist/{extract-bind-D5BYYGYA.js → extract-bind-7IDQS4QP.js} +2 -2
  122. package/dist/{extract-cmd-CCYW7FIY.js → extract-cmd-KIEOBRIT.js} +1 -1
  123. package/dist/{gaps-cmd-3VJKQ25D.js → gaps-cmd-RGIPUSIR.js} +1 -1
  124. package/dist/{generate-headless-2M6UT3IK.js → generate-headless-XGRIDD6O.js} +2 -2
  125. package/dist/index.js +134 -136
  126. package/dist/{ingest-cmd-HVTUK264.js → ingest-cmd-R5H5SF5K.js} +1 -1
  127. package/dist/install-W3VPVPAQ.js +2 -0
  128. package/dist/{interactive-bind-OJCYNQPI.js → interactive-bind-X5DVLRRW.js} +3 -3
  129. package/dist/{lifecycle-cmd-GWFGUGTC.js → lifecycle-cmd-6R2PR2HM.js} +1 -1
  130. package/dist/{list-cmd-AXDW64OY.js → list-cmd-QCIYKWYQ.js} +1 -1
  131. package/dist/{list-commands-YNZ6EFIF.js → list-commands-VRRCVWKO.js} +1 -1
  132. package/dist/login-flow-5HL2QYEL.js +2 -0
  133. package/dist/{maintenance-cmd-QEMK6YNV.js → maintenance-cmd-GZ4EMT3V.js} +1 -1
  134. package/dist/{mobile-prompts-OXHA5GHJ.js → mobile-prompts-CMIVWDHQ.js} +1 -1
  135. package/dist/objective-variable-gate-EEYJ6B3X.js +2 -0
  136. package/dist/{open-provider-E5VUGFNE.js → open-provider-UFSCTIQQ.js} +1 -1
  137. package/dist/{persist-recorded-session-KWPH37HI.js → persist-recorded-session-JXL5E53A.js} +1 -1
  138. package/dist/pipeline-RSCRNNPW.js +2 -0
  139. package/dist/prepare-target-XZ3FTVBW.js +2 -0
  140. package/dist/{reconcile-cmd-V7TDYETT.js → reconcile-cmd-4VRTUM2D.js} +1 -1
  141. package/dist/{reconcile-deps-X6IGH4CA.js → reconcile-deps-ZCJ2QCK5.js} +2 -2
  142. package/dist/{reconcile-engine-OGXSIE7O.js → reconcile-engine-IVLZCYZB.js} +1 -1
  143. package/dist/{recording-banner-IZWN2XFY.js → recording-banner-SRLPSTFP.js} +1 -1
  144. package/dist/registry-CPQHW2L2.js +2 -0
  145. package/dist/{require-project-folder-PEEUITK6.js → require-project-folder-SKEZMSN7.js} +1 -1
  146. package/dist/{resolve-run-intent-JGXXE45Y.js → resolve-run-intent-THC3EPAX.js} +1 -1
  147. package/dist/{resolver-TY7XLJBN.js → resolver-2NUNLK7N.js} +1 -1
  148. package/dist/{review-cmd-74YTPT7E.js → review-cmd-BMJQZ6XJ.js} +1 -1
  149. package/dist/{run-GRYWYKIH.js → run-TURFDLC6.js} +1 -1
  150. package/dist/{run-DN4XARP2.js → run-UDP5VPYS.js} +1 -1
  151. package/dist/{run-test-md-DFCKCQ4T.js → run-test-md-MRYNFNPO.js} +2 -2
  152. package/dist/{skill-installer-GRU3HOYF.js → skill-installer-CVJ5VTEJ.js} +1 -1
  153. package/dist/{spawner-LNMD4NJF.js → spawner-7FUA3JXA.js} +1 -1
  154. package/dist/{store-guard-Q4MYZQHF.js → store-guard-XQ5MSUB2.js} +1 -1
  155. package/dist/{sync-cmd-H6Y5EB3L.js → sync-cmd-5INKTZN2.js} +1 -1
  156. package/dist/{sync-setup-THGRBKTA.js → sync-setup-4R54VRAO.js} +1 -1
  157. package/dist/tcg-generate-2BOPGRM6.js +2 -0
  158. package/dist/testmd-actions-2CPJZAC2.js +2 -0
  159. package/dist/testmd-sync-HYZI6NRM.js +2 -0
  160. package/dist/token-refresh-NTE4LQRN.js +2 -0
  161. package/dist/{validate-basic-RCBEELSB.js → validate-basic-OKLJLDML.js} +1 -1
  162. package/dist/{variable-receipt-JHRW73Z6.js → variable-receipt-CMCDUJI2.js} +1 -1
  163. package/dist/{verdicts-XFXDRND4.js → verdicts-EMCYGQWM.js} +1 -1
  164. package/dist/{version-check-Z774UWW3.js → version-check-4DQJBSXW.js} +1 -1
  165. package/dist/{view-cmd-I4LQGJ2X.js → view-cmd-P3XRFORJ.js} +1 -1
  166. package/dist/{walk-session-FP52IGLB.js → walk-session-MUGS6CZY.js} +1 -1
  167. package/dist/{with-telemetry-P6RUPWBH.js → with-telemetry-3T53GIQC.js} +1 -1
  168. package/package.json +11 -11
  169. package/dist/EvidenceViewOffer-5MB4ZXKM.js +0 -2
  170. package/dist/FolderPicker-SYFXH6D5.js +0 -2
  171. package/dist/SingleShotApp-U54ETXS3.js +0 -2
  172. package/dist/TestMdRunView-WA4TC5PT.js +0 -2
  173. package/dist/bridge-X5DEJL6F.js +0 -2
  174. package/dist/chunk-53MPG2J3.js +0 -11
  175. package/dist/chunk-KN65CUNT.js +0 -15
  176. package/dist/chunk-L4M7753M.js +0 -2
  177. package/dist/chunk-LBNADEQN.js +0 -8
  178. package/dist/chunk-LNV7C2YO.js +0 -6
  179. package/dist/chunk-ZZTZJPT2.js +0 -88
  180. package/dist/install-5WJLE7XT.js +0 -2
  181. package/dist/login-flow-PRXFPRYZ.js +0 -2
  182. package/dist/objective-variable-gate-76GYUHEP.js +0 -2
  183. package/dist/pipeline-A2OGF4XW.js +0 -2
  184. package/dist/prepare-target-P6BWJZBZ.js +0 -2
  185. package/dist/registry-GOLIFVK5.js +0 -2
  186. package/dist/tcg-generate-SZZ7MJXY.js +0 -2
  187. package/dist/testmd-actions-MRIUOOXO.js +0 -2
  188. package/dist/testmd-sync-UYVJ47BN.js +0 -2
  189. package/dist/token-refresh-KN5JK2U4.js +0 -2
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{j as be,k as se,l as ae,m as xe,n as De,o as ce}from"./chunk-75I46VTM.js";import{a as re,c as ie,d as Pe,f as oe}from"./chunk-SQDQADWD.js";import{d as Ee}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-TCAHDVII.js";import{a as ee,b as W,c as ne,d as G,e as $e,g as O,h as te}from"./chunk-W5TTF7GB.js";import{a as _e}from"./chunk-BZAGVBCX.js";import{b as J,c as Q,d as X}from"./chunk-P3JUE2RM.js";import{j as ke,l as Re}from"./chunk-AHXOKBVE.js";import{P as E,Q as ge,S as he,U as ve,V as we,W as ye,X as Z}from"./chunk-6LGED4FC.js";import{C as I}from"./chunk-GP7WD4UY.js";import{H as B,t as pe}from"./chunk-3N6IAVD5.js";import{existsSync as Oe,statSync as Te}from"fs";import{basename as q,resolve as U}from"path";function Ie(e){if(!e||e.stale_refs.length===0)return"\u2014";let n=e.direct_refs??[];return`${e.stale_refs.length} stale${n.length>0?` \xB7 ${n.length} direct`:""}`}function le(e,n){let t=[...e.rows.filter(s=>s.kind!=="REMOVE").map(s=>[s.kind,S(s.ref),s.reason,Ie(s.impact)]),...e.archive.map(s=>["ARCHIVE",S(s.ref),s.why,Ie(s.impact)])],r=Math.max(40,n??100),i=[`reconcile ${e.source_id} \u2014 head ${e.head.status} \xB7 ${t.length} decision${t.length===1?"":"s"}`];return t.length>0&&i.push(...Ee(["kind","ref","why","impact"],t,r,2)),e.changed&&i.push(e.held?`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i.push("each row becomes a card below \u2014 verdicts commit as they land"),e.planPath&&i.push(`plan: ${e.planPath}`),i}var Ue=new Set(["interactive","agent","ci","override"]);function Be(e,n){if(e.mode!==void 0&&!Ue.has(e.mode))return{error:`--mode must be interactive | agent | ci | override, got '${e.mode}'`,code:"MODE_USAGE"};let t=e.mode,r="reconcile without a TTY needs an explicit mode \u2014 pass --mode agent|ci|override, or --plan for a preview";return t==="interactive"&&!n?{error:r}:t||(n?"interactive":e.plan?"override":{error:r})}async function Se(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-3A3BZVQ5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Ve(e,n,t,r){if(Q(t)){let m=X(t),a=m?.sourceIdFor(t)??null;if(m===null||a===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${J.map(f=>f.hint).join("; ")}`};if(r!==void 0&&r!==a)return{error:`--source-id '${r}' does not match this URL's own identity '${a}' \u2014 re-run without --source-id. A source adopted with --as updates by re-running context ingest with the same --as; reconcile follows only the URL's own id`};let c=I(e);if(!c.heads.has(a))return{error:`unknown source '${a}' \u2014 see \`kane-cli context list --type source\`. If this URL was ingested under a custom id, update it by re-running context ingest with the same --as`};if(c.heads.get(a)==null)return{error:`source '${a}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,a,{remoteUrl:t});return _!==null?{error:_}:{sourceId:a,remoteUrl:t}}if(r===void 0)return{error:"reconcile needs --from <file> AND --source-id <id> \u2014 see `kane-cli context list --type source` for ids"};let i=U(n,t);if(!Oe(i)||!Te(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let s=ke(i);if(!s.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${s.allowlist.join(", ")}`};let o=I(e);if(!o.heads.has(r))return{error:`unknown source '${r}' \u2014 see \`kane-cli context list --type source\``};if(o.heads.get(r)==null)return{error:`source '${r}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let w=z(e,r,{filePath:i});if(w!==null)return{error:w};let d=null;try{d=Re(i)}catch{}return d!==null&&d!==r&&o.heads.get(d)!=null?{error:`'${q(i)}' already backs live source '${d}' \u2014 did you mean --source-id ${d}? To truly move these bytes under '${r}', retire '${d}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function K(e,n,t,r=!1,i){if(e.out(`reconcile ${n.source_id}: head ${n.head.status} \u2014 ${C(n.head.before)} \u2192 ${C(n.head.after)}`),r||(e.out(`note: ${n.note}`),e.out(`skipped arms: ${n.skipped_arms}`)),n.changed&&(e.out(n.held?`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i?.({type:"defaults_taken",count:t?.defaultsTaken??0})),r){let s=n.changeset??[],o=(d,m)=>{let a=s.filter(c=>c.kind===d).length;return a>0?`${a} ${m}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${s.length} item(s)${w.length?` \u2014 ${w.join(" \xB7 ")}`:""}`),e.out(`plan: ${n.rows.length} row(s) \u2014 each gets a card below`);return}if(n.changed){let s=n.changeset??[];e.out(`changeset: ${s.length} item(s)`);for(let o of s)if(o.kind==="MODIFY")e.out(` [MODIFY] ${S(o.ref)} \u2014 ${o.summary} (${C(o.old_cid)} \u2192 ${o.new_cid===null?"(staged)":C(o.new_cid)})`);else if(o.kind==="ADD")e.out(` [ADD] ${S(o.ref)}`);else{e.out(` [ARCHIVE] ${S(o.ref)} \u2014 ${o.why}`);let w=de(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let s of n.rows){e.out(` [${s.kind}] ${S(s.ref)} \u2014 ${s.reason}`);let o=de(s.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${s.provenance}`),e.out(` action: ${s.action}`)}}function Ae(e,n){return le({source_id:e.source_id,head:{status:e.head.status},rows:e.rows,archive:(e.changeset??[]).filter(t=>t.kind==="ARCHIVE"),changed:e.changed,held:!!e.held,defaultsTaken:n?.defaultsTaken},process.stdout.columns)}function de(e,n){if(!e||e.stale_refs.length===0)return null;let t=e.direct_refs??[];return`impact: ${n} ${e.stale_refs.length} item(s) stale`+(t.length>0?` \u2014 ${t.length} directly touched: ${t.join(", ")}`:"")}function D(e){return e==="interactive"?"override":e}async function H(e,n,t,r,i,s,o=[],w="override",d,m,a,c,_,f,P){let p;try{p=te(e)}catch(u){return E(r,u instanceof Error?u.message:String(u)),1}try{if(!t){let{runWalkSession:u}=await import("./walk-session-FP52IGLB.js"),{telemetryEnvName:R}=await import("./bootstrap-6IJNZIPT.js");return await u({dir:e,rows:n,archive:o,held:d??null,childMode:w,runDesign:c??null,mark:s,markA:a,...m?{archiveState:m}:{},...f?{meta:{verb:"reconcile",sid:f,env:R()}}:{},...P?{resumeCmd:P}:{},signals:b=>A(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Ye(e,n,t,r,i,s,o,w,d,m)}finally{p()}}var F=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,Le=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,L=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function T(e,n,t){let r=n.rows;e({type:"reconcile_plan",source_id:n.source_id,plan_path:t,rows:r.map(i=>({kind:i.kind,ref:i.ref,why:i.reason})),archive:n.changeset.filter(i=>i.kind==="ARCHIVE").map(i=>({ref:i.ref,why:i.why}))})}function ue(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var j=ue();async function Y(e,n,t,r,i,s,o,w,d){T(i,n,t);let m=n.changeset.filter(_=>_.kind==="ARCHIVE"&&d?.[_.ref]===void 0),a=n.rows,c;try{c=te(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(ue()),2}try{return await je(e,n,t,r,i,s,o,a,m,w)}finally{c()}}async function je(e,n,t,r,i,s,o,w,d,m){let a=0,c=0,_=0,f=0,P=0,p=0,u=0,R=new Set,b=(v,g)=>{try{m?.(v,g)}catch{}};for(let[v,g]of w.entries()){i({type:"reconcile_row_start",kind:g.kind,ref:g.ref,...g.impact?{stale:g.impact.stale_refs.length,direct:g.impact.direct_refs?.length??0}:{}});let h=(l,$,x)=>i({type:"reconcile_row_end",kind:g.kind,ref:g.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(g.applied){c++,h("skipped");continue}if(g.kind==="REMOVE"){P++,h("plan-only");continue}if(g.held_ref&&n.held){let l=new Set;if(g.kind==="MODIFY"&&g.impact){let x=I(e);for(let M of g.impact.stale_refs){let N=x.resolve(M);N&&x.stale(N.tip)==="fresh"&&l.add(M)}}let $=se(e,n.held,g.held_ref,fe);if(!$.ok){_++,u===0&&(u=1),h("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(f++,u===0&&(u=3),h("paused",3)):(_++,u===0&&(u=1),h("failed",x));continue}}a++,$.kind!=="ADD"&&g.impact&&(p+=l.size),b(v,"approved"),A(e,g.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),h("applied");continue}let k=re(I(e),g.ref);if(!k.ok){c++,h("skipped");continue}let y=k.target;if(R.has(y.ucTip)){c++,h("skipped");continue}if(g.kind==="ADD"){let l=await r(y.seamRef,{yes:!0,mode:o});if(l===3){f++,u===0&&(u=3),h("paused",3);continue}if(l!==0){_++,u===0&&(u=1),h("failed",l);continue}R.add(y.ucTip),a++,b(v,"approved"),A(e,g.ref,"gap-resolved-create"),h("applied")}else{let l=await ie(e,y,{yes:!0,mode:o},s,r,"batch");l.outcome==="evolved"?(R.add(y.ucTip),a++,b(v,"approved"),A(e,g.ref,"gap-resolved-evolve"),h("applied")):l.outcome==="paused"?(f++,u===0&&(u=l.code),h("paused",l.code)):l.outcome==="failed"?(_++,u===0&&(u=1),h("failed",l.code)):(c++,h("skipped"))}}return d.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:d.map(v=>({ref:v.ref,why:v.why}))}),f+=d.length,u===0&&(u=3)),i(ue({applied:a,skipped:c,plan_only:P,failed:_,paused:f,stale_created:p})),u}var fe={kind:"human",id:process.env.USER??"operator"};function A(e,n,t,r){_e(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:fe,target:n,...r!==void 0?{reason:r}:{}})}async function Ye(e,n,t,r,i,s,o=[],w="override",d,m){let a=0,c=0,_=0,f=0,P=0,p=0,u=0,R=new Set;for(let[b,v]of n.entries()){if(v.applied){r.out(`skipped ${v.ref} \u2014 already applied (${v.applied.outcome} at ${v.applied.at})`),c++;continue}let g=l=>{try{s?.(b,l)}catch($){E(r,`could not record applied state for ${v.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(v.kind==="REMOVE"){r.out(`REMOVE ${v.ref} \u2014 plan-only in this release (not executed)`),f++;continue}if(v.held_ref&&d){let l=se(e,d,v.held_ref,fe);if(!l.ok){E(r,`held ${v.ref}: ${l.message}`),P++,u===0&&(u=1);continue}if(r.out(`committed ${l.ref} (${v.kind==="ADD"?"minted":"updated \u2014 old\u2192new redirect"})`),l.kind==="ADD"){let $=await i(l.ref,{yes:t,mode:w});if($===3){r.out(`design session for ${l.ref} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above`),p++,u===0&&(u=3),g("approved");continue}if($!==0){E(r,`design run for ${l.ref} ended with exit code ${$}`),P++,u===0&&(u=1),g("approved");continue}}a++,g("approved"),A(e,v.ref,v.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let h=I(e),k=re(h,v.ref);if(!k.ok){r.out(`skipped ${v.ref} \u2014 ${k.message}`),c++;continue}let y=k.target;if(R.has(y.ucTip)){r.out(`skipped ${v.ref} \u2014 use-case ${y.display} already handled in this walk`),c++;continue}if(v.kind==="ADD"){let l=await i(y.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${y.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),p++,u===0&&(u=3);continue}if(l!==0){E(r,`design run for ${y.display} ended with exit code ${l}`),P++,u===0&&(u=1);continue}R.add(y.ucTip),a++,g("approved"),A(e,v.ref,"gap-resolved-create")}else{let l=await ie(e,y,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(y.ucTip),a++,g("approved"),A(e,v.ref,"gap-resolved-evolve")):l.outcome==="paused"?(p++,u===0&&(u=l.code)):l.outcome==="failed"?(P++,u===0&&(u=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&m?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let v=de(b.impact,"retiring drops");v&&r.out(` ${v}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),f++}return r.out(`reconcile walk: ${a} applied, ${c} skipped, ${_} deferred, ${f} plan-only`+(P>0?`, ${P} failed`:"")+(p>0?`, ${p} paused`:"")),u}var Ke=new Set(J.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let s=r.mediaOf(i);if("remoteUrl"in t){let o=X(t.remoteUrl)?.name??"remote";return s.format!==o?`source '${n}' is backed by ${s.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Ke.has(s.format)?`source '${n}' is a remote ${s.format} source \u2014 pass its URL to --from, not a file`:null}function me(e,n,t,r){return"remoteUrl"in n?De(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):xe(e,n.filePath)}function Me(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function He(e,n,t,r,i,s=!1,o=!1){let w=i.seams??{reingest:me(e,t,r,i),reextract:ce(e,{stage:s,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
- `)}})},d=null,m={reingest:w.reingest,reextract:async c=>d=await w.reextract(c)},a;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),a=await(i.buildPlan??ae)(e,n,m)}catch(c){return E(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(a.changed)if(o)for(let c of Ae(a,d))r.out(c);else K(r,a,d,!1,i.emitEvent);return a}async function Ne(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:s},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-AVL3TJA2.js"),import("./chat-controller-3EPK7UZG.js"),import("./reconcile-deps-X6IGH4CA.js")]),w=t.default??t,d=s(),m=o({contextDir:e,note:a=>d.note(a)});return new Promise(a=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:d,verb:"extract",reconcile:m,autoReview:!0,onReviewExit:()=>{c.unmount(),a(0)},onCtrlC:()=>{c.unmount(),a(m.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function We(e,n,t,r,i){let s=W(e,n);if("error"in s)return E(r,s.error),2;let{plan:o,path:w}=s,d=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${q(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${q(w)}`),0;let m=i.runDesignForUc??oe,a=i.runDesignForUc??null,c=i.sessionScript,_=(v,g)=>O(w,v,g),f=(v,g)=>G(w,v,g),P=B(e);if(P===o.head_pin){if(t==="agent"){let g=i.emitEvent??(()=>{});return Y(e,V(o),w,m,g,r,D(t),_,o.archive_state)}let v=ne(o);if(t==="ci"&&v.length>0)return E(r,L(v.length)),2;if(r.out(`applying stored plan ${q(w)} for ${o.source_id} (${o.rows.length} row(s))`),!d)for(let g of le({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(h=>h.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(g);return H(e,o.rows,d,r,m,_,o.changeset??[],D(t),o.held,o.archive_state,f,a,c,o.source_id,F(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(P)}) \u2014 recomputing`),o.held)return Fe(e,o,r,i,t,m,!1);let p=Me(o);if(p===null)return E(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let u=z(e,o.source_id,p);if(u!==null)return E(r,`stored plan cannot replay: ${u}`),2;let R=await He(e,o.source_id,p,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return K(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let v=i.emitEvent??(()=>{});return Y(e,R,null,m,v,r,D(t))}let b=R.changeset.filter(v=>v.kind==="ARCHIVE");return t==="ci"&&b.length>0?(E(r,L(b.length)),2):H(e,R.rows,d,r,m,void 0,R.changeset,D(t),R.held,void 0,void 0,a,c,R.source_id,F(Le(p),R.source_id))}function V(e,n=!1){return{source_id:e.source_id,changed:!0,head:{status:"unchanged",before:e.head_pin,after:e.head_pin},note:e.note,skipped_arms:e.skipped_arms,changeset:e.changeset??[],rows:n?e.rows.filter(t=>t.applied===void 0):e.rows,...e.held?{held:e.held}:{}}}async function Ge(e,n,t,r,i,s,o){let w=r.runDesignForUc??null,d=r.sessionScript,m=$e(e,n);if(m===null)return null;if("error"in m)return E(t,m.error),2;let{plan:a,path:c}=m,_=a.rows.filter(u=>u.applied===void 0),f=ne(a),P=r.emitEvent??(()=>{});if(_.length===0&&f.length===0){t.out(`already reconciled \u2014 plan ${a.created} applied ${a.rows.length} row(s)`);let u=Pe(I(e)).staleCount;return u>0&&(t.out(`${u} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),P({type:"stale_debt",count:u})),i==="agent"&&(T(P,V(a),c),P({...j})),0}let p=B(e);return p!==a.head_pin?(t.out(`plan ${a.created} superseded \u2014 graph moved (${C(a.head_pin)} \u2192 ${C(p)}); recomputing`),Fe(e,a,t,r,i,s,o)):(t.out(`resuming plan ${a.created} \u2014 ${_.length} pending row(s)${f.length>0?`, ${f.length} undecided archive item(s)`:""}`),o?(K(t,V(a),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(T(P,V(a),c),P({...j})),0):i==="agent"?Y(e,V(a),c,s,P,t,D(i),(u,R)=>O(c,u,R),a.archive_state):i==="ci"&&f.length>0?(E(t,L(f.length)),2):H(e,a.rows,i==="override"||i==="ci",t,s,(u,R)=>O(c,u,R),a.changeset??[],D(i),a.held,a.archive_state,(u,R)=>G(c,u,R),w,d,a.source_id,F(a.backing_path??a.remote_url,a.source_id)))}async function Fe(e,n,t,r,i,s,o){let w=r.runDesignForUc??null,d=r.sessionScript,m;if(n.held){let h=I(e),k=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),y=[];for(let l of n.held.rows){if(k.has(l.temp_ref))continue;if(!l.matched_cid){y.push(l);continue}let $=h.tipOf(l.matched_cid);if(h.superseded.get($)===null){t.out(`dropped held "${l.title}" \u2014 its use-case was retired meanwhile`),r.emitEvent?.({type:"held_dropped",ref:l.temp_ref,title:l.title,reason:"target_retired"});continue}y.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}m={source_id:n.held.source_id,rows:y}}let a=Me(n);if(a===null)return E(t,`stored plan for ${n.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let c=z(e,n.source_id,a);if(c!==null)return E(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:me(e,a,t,r),reextract:ce(e,{stage:m!==void 0,hostOut:h=>t.out(h),hostEmit:h=>{h.type!=="run_start"&&r.emitEvent?.(h)},...r.emitEvent?{}:{hostProgress:h=>process.stderr.write(h+`
4
- `)}})},f;try{f=await(r.buildPlan??ae)(e,n.source_id,_,{resumeHeld:m})}catch(h){return E(t,`reconcile failed: ${h instanceof Error?h.message:String(h)}`),1}if(i==="interactive"&&!o)for(let h of Ae(f,null))t.out(h);else K(t,f,null,!1,r.emitEvent);let P=B(e),p=null;if(P!=null){let h={},k=new Set(f.changeset.filter(y=>y.kind==="ARCHIVE").map(y=>y.ref));for(let[y,l]of Object.entries(n.archive_state??{}))k.has(y)&&(h[y]=l);p=ee(e,{version:2,source_id:f.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:P,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:f.skipped_arms,note:f.note,changeset:f.changeset,rows:f.rows,...f.held?{held:f.held}:{},...Object.keys(h).length>0?{archive_state:h}:{}}),t.out(`plan stored: ${p}`)}if(o){if(i==="agent"){let h=r.emitEvent??(()=>{});T(h,f,p),h({...j})}return 0}let u=r.emitEvent??(()=>{}),R=p?W(e,p).plan.archive_state:void 0,b=p?(h,k)=>O(p,h,k):void 0,v=p?(h,k)=>G(p,h,k):void 0;if(i==="agent")return Y(e,f,p,s,u,t,D(i),b,R);let g=f.changeset.filter(h=>h.kind==="ARCHIVE"&&R?.[h.ref]===void 0);return i==="ci"&&g.length>0?(E(t,L(g.length)),2):H(e,f.rows,i==="override"||i==="ci",t,s,b,f.changeset,D(i),f.held,R,v,w,d,f.source_id,F(n.backing_path??n.remote_url,f.source_id))}async function Ce(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:s}=await import("./bootstrap-6IJNZIPT.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:U(r,".context"),env:s(),applyPlanPath:typeof e.apply=="string"?U(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});{let m=Oe(U(r,".context"))?ye(U(r,".context")):null;if(m)return e.mode==="agent"?t.emitEvent?.(Z(m)):(E(n,m.text),(n.err??n.out)(`next: ${m.remedy}`)),await o.end({exit_code:2}),2}let w=await ve(U(r,".context"));w&&(e.mode==="agent"?t.emitEvent?.(we(w)):(n.err??n.out)(w.text));let d=await qe(e,n,t,r);return d===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:d}),d}async function qe(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,s=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return E(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&Q(e.from);if(o&&(!e.from||!e.sourceId&&!w))return E(n,"reconcile needs --from <file|url> AND --source-id <id> (files only \u2014 a URL derives its own id) \u2014 see `kane-cli context list --type source` for ids"),2;if(e.from&&s!==void 0)return E(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let d=ge(r,n);if(!d)return 2;if(e.mode!==void 0&&!Ue.has(e.mode))return Se(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let m=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!m&&!n.isTTY)return E(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let a=!e.plan,c="override";if(e.from){let k=Be(e,n.isTTY);if(typeof k=="object")return k.code==="MODE_USAGE"?Se(k.error):(E(n,k.error),2);c=k}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:k}=await import("./reconcile-deps-X6IGH4CA.js"),y=s===void 0?k({contextDir:d}).pending():null;if(y?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(E(n,`a held changeset for ${y.source} awaits review (${y.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ne)(d)}let l=e.mode??"interactive";return We(d,s===void 0?void 0:U(r,s),l,n,t)}let f=Ve(d,r,e.from,e.sourceId);if("error"in f)return E(n,f.error),2;if(!i){let{sessionsHoldingSource:k}=await import("./sessions-NH7WQWMX.js"),{holders:y,corrupt:l}=k(d,f.sourceId);if(l>0)return E(n,`cannot verify review holds \u2014 ${l} session file(s) unreadable; inspect with kane-cli context sessions list, clean with kane-cli context sessions clean, then retry [SESSIONS_UNREADABLE]`),2;if(y.length>0)return E(n,`session ${y[0]} holds item(s) for review pinned to ${f.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${y[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let k=t.seams?.reingest??me(d,f,n,t),y;try{y=await k(f.sourceId)}catch($){return E(n,$ instanceof Error?$.message:String($)),1}let l=y.status==="unchanged"?null:be(d,f.sourceId);if(y.status!=="unchanged"&&!l)return n.out(`${f.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${f.sourceId}`),0;if(l){let x=await(t.chatMount??(async M=>{let{bindExtractInteractive:N}=await import("./extract-bind-D5BYYGYA.js");return N(M)}))({mode:"interactive",posture:"reconcile",source:f.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:M}=await import("./sessions-NH7WQWMX.js");if(M(d,f.sourceId).holders.length===0)return 0}return x}}let P="remoteUrl"in f?{remoteUrl:f.remoteUrl}:{filePath:f.filePath},p=await He(d,f.sourceId,P,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!p)return 1;let u=t.runDesignForUc??oe,R=t.runDesignForUc??null,b=t.sessionScript;if(!p.changed){let k=await Ge(d,f.sourceId,n,t,c,u,!!e.plan);if(k!==null)return k;if(K(n,p,null,!1,t.emitEvent),c==="agent"){let y=t.emitEvent??(()=>{});T(y,p,null),y({...j})}return 0}let v=B(d),g=null;if(v!=null?g=ee(d,{version:2,source_id:p.source_id,..."remoteUrl"in P?{remote_url:P.remoteUrl}:{backing_path:P.filePath},head_pin:v,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:p.skipped_arms,note:p.note,changeset:p.changeset,rows:p.rows,...p.held?{held:p.held}:{}}):E(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let k=t.emitEvent??(()=>{});if(!a)return T(k,p,g),k({...j}),0;let y=g?(l,$)=>O(g,l,$):void 0;return Y(d,p,g,u,k,n,D(c),y)}if(!a)return g&&n.out(`plan stored: ${g}`),0;let h=p.changeset.filter(k=>k.kind==="ARCHIVE");if(c==="ci"&&h.length>0)return g&&n.out(`plan stored: ${g}`),E(n,L(h.length)),2;if(g){n.out(`plan stored: ${g}`);let k=g;return H(d,ze(d,k)??p.rows,_,n,u,(y,l)=>O(k,y,l),p.changeset,D(c),p.held,void 0,void 0,R,b,p.source_id,F(e.from,p.source_id))}return H(d,p.rows,_,n,u,void 0,p.changeset,D(c),p.held,void 0,void 0,R,b,p.source_id,F(e.from,p.source_id))}function ze(e,n){let t=W(e,n);return"error"in t?null:t.plan.rows}async function hn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-3A3BZVQ5.js"),s=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:s.out,err:m=>s.event({type:"error",message:m}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),d=2;try{d=await w({event:m=>s.event(m)},()=>Ce(e,o,{...n,emitEvent:m=>s.event(m)},r))}catch(m){m instanceof pe?(d=2,s.event(Z({code:m.code,text:m.message,remedy:m.remedy}))):(d=1,s.event({type:"error",message:m instanceof Error?m.message:String(m)}))}return s.done(d)}return Ce(e,he(),n,r)}export{Be as a,Ve as b,D as c,A as d,Ce as e,hn as f};
2
+ import{j as be,k as se,l as ae,m as xe,n as De,o as ce}from"./chunk-ORQGQSWG.js";import{a as re,c as ie,d as Pe,f as oe}from"./chunk-PGXJ275T.js";import{d as Ee}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-TCAHDVII.js";import{a as ee,b as W,c as ne,d as G,e as $e,g as O,h as te}from"./chunk-W5TTF7GB.js";import{a as _e}from"./chunk-BZAGVBCX.js";import{b as J,c as Q,d as X}from"./chunk-Q77QO3PC.js";import{j as ke,l as Re}from"./chunk-AHXOKBVE.js";import{P as E,Q as ge,S as he,U as ve,V as we,W as ye,X as Z}from"./chunk-UHSNUUX3.js";import{C as I}from"./chunk-GP7WD4UY.js";import{H as B,t as pe}from"./chunk-3N6IAVD5.js";import{existsSync as Oe,statSync as Te}from"fs";import{basename as q,resolve as U}from"path";function Ie(e){if(!e||e.stale_refs.length===0)return"\u2014";let n=e.direct_refs??[];return`${e.stale_refs.length} stale${n.length>0?` \xB7 ${n.length} direct`:""}`}function le(e,n){let t=[...e.rows.filter(s=>s.kind!=="REMOVE").map(s=>[s.kind,S(s.ref),s.reason,Ie(s.impact)]),...e.archive.map(s=>["ARCHIVE",S(s.ref),s.why,Ie(s.impact)])],r=Math.max(40,n??100),i=[`reconcile ${e.source_id} \u2014 head ${e.head.status} \xB7 ${t.length} decision${t.length===1?"":"s"}`];return t.length>0&&i.push(...Ee(["kind","ref","why","impact"],t,r,2)),e.changed&&i.push(e.held?`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i.push("each row becomes a card below \u2014 verdicts commit as they land"),e.planPath&&i.push(`plan: ${e.planPath}`),i}var Ue=new Set(["interactive","agent","ci","override"]);function Be(e,n){if(e.mode!==void 0&&!Ue.has(e.mode))return{error:`--mode must be interactive | agent | ci | override, got '${e.mode}'`,code:"MODE_USAGE"};let t=e.mode,r="reconcile without a TTY needs an explicit mode \u2014 pass --mode agent|ci|override, or --plan for a preview";return t==="interactive"&&!n?{error:r}:t||(n?"interactive":e.plan?"override":{error:r})}async function Se(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-3A3BZVQ5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Ve(e,n,t,r){if(Q(t)){let m=X(t),a=m?.sourceIdFor(t)??null;if(m===null||a===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${J.map(f=>f.hint).join("; ")}`};if(r!==void 0&&r!==a)return{error:`--source-id '${r}' does not match this URL's own identity '${a}' \u2014 re-run without --source-id. A source adopted with --as updates by re-running context ingest with the same --as; reconcile follows only the URL's own id`};let c=I(e);if(!c.heads.has(a))return{error:`unknown source '${a}' \u2014 see \`kane-cli context list --type source\`. If this URL was ingested under a custom id, update it by re-running context ingest with the same --as`};if(c.heads.get(a)==null)return{error:`source '${a}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,a,{remoteUrl:t});return _!==null?{error:_}:{sourceId:a,remoteUrl:t}}if(r===void 0)return{error:"reconcile needs --from <file> AND --source-id <id> \u2014 see `kane-cli context list --type source` for ids"};let i=U(n,t);if(!Oe(i)||!Te(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let s=ke(i);if(!s.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${s.allowlist.join(", ")}`};let o=I(e);if(!o.heads.has(r))return{error:`unknown source '${r}' \u2014 see \`kane-cli context list --type source\``};if(o.heads.get(r)==null)return{error:`source '${r}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let w=z(e,r,{filePath:i});if(w!==null)return{error:w};let d=null;try{d=Re(i)}catch{}return d!==null&&d!==r&&o.heads.get(d)!=null?{error:`'${q(i)}' already backs live source '${d}' \u2014 did you mean --source-id ${d}? To truly move these bytes under '${r}', retire '${d}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function K(e,n,t,r=!1,i){if(e.out(`reconcile ${n.source_id}: head ${n.head.status} \u2014 ${C(n.head.before)} \u2192 ${C(n.head.after)}`),r||(e.out(`note: ${n.note}`),e.out(`skipped arms: ${n.skipped_arms}`)),n.changed&&(e.out(n.held?`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i?.({type:"defaults_taken",count:t?.defaultsTaken??0})),r){let s=n.changeset??[],o=(d,m)=>{let a=s.filter(c=>c.kind===d).length;return a>0?`${a} ${m}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${s.length} item(s)${w.length?` \u2014 ${w.join(" \xB7 ")}`:""}`),e.out(`plan: ${n.rows.length} row(s) \u2014 each gets a card below`);return}if(n.changed){let s=n.changeset??[];e.out(`changeset: ${s.length} item(s)`);for(let o of s)if(o.kind==="MODIFY")e.out(` [MODIFY] ${S(o.ref)} \u2014 ${o.summary} (${C(o.old_cid)} \u2192 ${o.new_cid===null?"(staged)":C(o.new_cid)})`);else if(o.kind==="ADD")e.out(` [ADD] ${S(o.ref)}`);else{e.out(` [ARCHIVE] ${S(o.ref)} \u2014 ${o.why}`);let w=de(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let s of n.rows){e.out(` [${s.kind}] ${S(s.ref)} \u2014 ${s.reason}`);let o=de(s.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${s.provenance}`),e.out(` action: ${s.action}`)}}function Ae(e,n){return le({source_id:e.source_id,head:{status:e.head.status},rows:e.rows,archive:(e.changeset??[]).filter(t=>t.kind==="ARCHIVE"),changed:e.changed,held:!!e.held,defaultsTaken:n?.defaultsTaken},process.stdout.columns)}function de(e,n){if(!e||e.stale_refs.length===0)return null;let t=e.direct_refs??[];return`impact: ${n} ${e.stale_refs.length} item(s) stale`+(t.length>0?` \u2014 ${t.length} directly touched: ${t.join(", ")}`:"")}function D(e){return e==="interactive"?"override":e}async function H(e,n,t,r,i,s,o=[],w="override",d,m,a,c,_,f,P){let p;try{p=te(e)}catch(u){return E(r,u instanceof Error?u.message:String(u)),1}try{if(!t){let{runWalkSession:u}=await import("./walk-session-MUGS6CZY.js"),{telemetryEnvName:R}=await import("./bootstrap-KCPWDBLX.js");return await u({dir:e,rows:n,archive:o,held:d??null,childMode:w,runDesign:c??null,mark:s,markA:a,...m?{archiveState:m}:{},...f?{meta:{verb:"reconcile",sid:f,env:R()}}:{},...P?{resumeCmd:P}:{},signals:b=>A(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Ye(e,n,t,r,i,s,o,w,d,m)}finally{p()}}var F=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,Le=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,L=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function T(e,n,t){let r=n.rows;e({type:"reconcile_plan",source_id:n.source_id,plan_path:t,rows:r.map(i=>({kind:i.kind,ref:i.ref,why:i.reason})),archive:n.changeset.filter(i=>i.kind==="ARCHIVE").map(i=>({ref:i.ref,why:i.why}))})}function ue(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var j=ue();async function Y(e,n,t,r,i,s,o,w,d){T(i,n,t);let m=n.changeset.filter(_=>_.kind==="ARCHIVE"&&d?.[_.ref]===void 0),a=n.rows,c;try{c=te(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(ue()),2}try{return await je(e,n,t,r,i,s,o,a,m,w)}finally{c()}}async function je(e,n,t,r,i,s,o,w,d,m){let a=0,c=0,_=0,f=0,P=0,p=0,u=0,R=new Set,b=(v,g)=>{try{m?.(v,g)}catch{}};for(let[v,g]of w.entries()){i({type:"reconcile_row_start",kind:g.kind,ref:g.ref,...g.impact?{stale:g.impact.stale_refs.length,direct:g.impact.direct_refs?.length??0}:{}});let h=(l,$,x)=>i({type:"reconcile_row_end",kind:g.kind,ref:g.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(g.applied){c++,h("skipped");continue}if(g.kind==="REMOVE"){P++,h("plan-only");continue}if(g.held_ref&&n.held){let l=new Set;if(g.kind==="MODIFY"&&g.impact){let x=I(e);for(let M of g.impact.stale_refs){let N=x.resolve(M);N&&x.stale(N.tip)==="fresh"&&l.add(M)}}let $=se(e,n.held,g.held_ref,fe);if(!$.ok){_++,u===0&&(u=1),h("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(f++,u===0&&(u=3),h("paused",3)):(_++,u===0&&(u=1),h("failed",x));continue}}a++,$.kind!=="ADD"&&g.impact&&(p+=l.size),b(v,"approved"),A(e,g.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),h("applied");continue}let k=re(I(e),g.ref);if(!k.ok){c++,h("skipped");continue}let y=k.target;if(R.has(y.ucTip)){c++,h("skipped");continue}if(g.kind==="ADD"){let l=await r(y.seamRef,{yes:!0,mode:o});if(l===3){f++,u===0&&(u=3),h("paused",3);continue}if(l!==0){_++,u===0&&(u=1),h("failed",l);continue}R.add(y.ucTip),a++,b(v,"approved"),A(e,g.ref,"gap-resolved-create"),h("applied")}else{let l=await ie(e,y,{yes:!0,mode:o},s,r,"batch");l.outcome==="evolved"?(R.add(y.ucTip),a++,b(v,"approved"),A(e,g.ref,"gap-resolved-evolve"),h("applied")):l.outcome==="paused"?(f++,u===0&&(u=l.code),h("paused",l.code)):l.outcome==="failed"?(_++,u===0&&(u=1),h("failed",l.code)):(c++,h("skipped"))}}return d.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:d.map(v=>({ref:v.ref,why:v.why}))}),f+=d.length,u===0&&(u=3)),i(ue({applied:a,skipped:c,plan_only:P,failed:_,paused:f,stale_created:p})),u}var fe={kind:"human",id:process.env.USER??"operator"};function A(e,n,t,r){_e(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:fe,target:n,...r!==void 0?{reason:r}:{}})}async function Ye(e,n,t,r,i,s,o=[],w="override",d,m){let a=0,c=0,_=0,f=0,P=0,p=0,u=0,R=new Set;for(let[b,v]of n.entries()){if(v.applied){r.out(`skipped ${v.ref} \u2014 already applied (${v.applied.outcome} at ${v.applied.at})`),c++;continue}let g=l=>{try{s?.(b,l)}catch($){E(r,`could not record applied state for ${v.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(v.kind==="REMOVE"){r.out(`REMOVE ${v.ref} \u2014 plan-only in this release (not executed)`),f++;continue}if(v.held_ref&&d){let l=se(e,d,v.held_ref,fe);if(!l.ok){E(r,`held ${v.ref}: ${l.message}`),P++,u===0&&(u=1);continue}if(r.out(`committed ${l.ref} (${v.kind==="ADD"?"minted":"updated \u2014 old\u2192new redirect"})`),l.kind==="ADD"){let $=await i(l.ref,{yes:t,mode:w});if($===3){r.out(`design session for ${l.ref} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above`),p++,u===0&&(u=3),g("approved");continue}if($!==0){E(r,`design run for ${l.ref} ended with exit code ${$}`),P++,u===0&&(u=1),g("approved");continue}}a++,g("approved"),A(e,v.ref,v.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let h=I(e),k=re(h,v.ref);if(!k.ok){r.out(`skipped ${v.ref} \u2014 ${k.message}`),c++;continue}let y=k.target;if(R.has(y.ucTip)){r.out(`skipped ${v.ref} \u2014 use-case ${y.display} already handled in this walk`),c++;continue}if(v.kind==="ADD"){let l=await i(y.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${y.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),p++,u===0&&(u=3);continue}if(l!==0){E(r,`design run for ${y.display} ended with exit code ${l}`),P++,u===0&&(u=1);continue}R.add(y.ucTip),a++,g("approved"),A(e,v.ref,"gap-resolved-create")}else{let l=await ie(e,y,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(y.ucTip),a++,g("approved"),A(e,v.ref,"gap-resolved-evolve")):l.outcome==="paused"?(p++,u===0&&(u=l.code)):l.outcome==="failed"?(P++,u===0&&(u=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&m?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let v=de(b.impact,"retiring drops");v&&r.out(` ${v}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),f++}return r.out(`reconcile walk: ${a} applied, ${c} skipped, ${_} deferred, ${f} plan-only`+(P>0?`, ${P} failed`:"")+(p>0?`, ${p} paused`:"")),u}var Ke=new Set(J.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let s=r.mediaOf(i);if("remoteUrl"in t){let o=X(t.remoteUrl)?.name??"remote";return s.format!==o?`source '${n}' is backed by ${s.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Ke.has(s.format)?`source '${n}' is a remote ${s.format} source \u2014 pass its URL to --from, not a file`:null}function me(e,n,t,r){return"remoteUrl"in n?De(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):xe(e,n.filePath)}function Me(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function He(e,n,t,r,i,s=!1,o=!1){let w=i.seams??{reingest:me(e,t,r,i),reextract:ce(e,{stage:s,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
+ `)}})},d=null,m={reingest:w.reingest,reextract:async c=>d=await w.reextract(c)},a;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),a=await(i.buildPlan??ae)(e,n,m)}catch(c){return E(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(a.changed)if(o)for(let c of Ae(a,d))r.out(c);else K(r,a,d,!1,i.emitEvent);return a}async function Ne(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:s},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-2GPR4S7I.js"),import("./chat-controller-3EPK7UZG.js"),import("./reconcile-deps-ZCJ2QCK5.js")]),w=t.default??t,d=s(),m=o({contextDir:e,note:a=>d.note(a)});return new Promise(a=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:d,verb:"extract",reconcile:m,autoReview:!0,onReviewExit:()=>{c.unmount(),a(0)},onCtrlC:()=>{c.unmount(),a(m.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function We(e,n,t,r,i){let s=W(e,n);if("error"in s)return E(r,s.error),2;let{plan:o,path:w}=s,d=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${q(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${q(w)}`),0;let m=i.runDesignForUc??oe,a=i.runDesignForUc??null,c=i.sessionScript,_=(v,g)=>O(w,v,g),f=(v,g)=>G(w,v,g),P=B(e);if(P===o.head_pin){if(t==="agent"){let g=i.emitEvent??(()=>{});return Y(e,V(o),w,m,g,r,D(t),_,o.archive_state)}let v=ne(o);if(t==="ci"&&v.length>0)return E(r,L(v.length)),2;if(r.out(`applying stored plan ${q(w)} for ${o.source_id} (${o.rows.length} row(s))`),!d)for(let g of le({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(h=>h.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(g);return H(e,o.rows,d,r,m,_,o.changeset??[],D(t),o.held,o.archive_state,f,a,c,o.source_id,F(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(P)}) \u2014 recomputing`),o.held)return Fe(e,o,r,i,t,m,!1);let p=Me(o);if(p===null)return E(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let u=z(e,o.source_id,p);if(u!==null)return E(r,`stored plan cannot replay: ${u}`),2;let R=await He(e,o.source_id,p,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return K(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let v=i.emitEvent??(()=>{});return Y(e,R,null,m,v,r,D(t))}let b=R.changeset.filter(v=>v.kind==="ARCHIVE");return t==="ci"&&b.length>0?(E(r,L(b.length)),2):H(e,R.rows,d,r,m,void 0,R.changeset,D(t),R.held,void 0,void 0,a,c,R.source_id,F(Le(p),R.source_id))}function V(e,n=!1){return{source_id:e.source_id,changed:!0,head:{status:"unchanged",before:e.head_pin,after:e.head_pin},note:e.note,skipped_arms:e.skipped_arms,changeset:e.changeset??[],rows:n?e.rows.filter(t=>t.applied===void 0):e.rows,...e.held?{held:e.held}:{}}}async function Ge(e,n,t,r,i,s,o){let w=r.runDesignForUc??null,d=r.sessionScript,m=$e(e,n);if(m===null)return null;if("error"in m)return E(t,m.error),2;let{plan:a,path:c}=m,_=a.rows.filter(u=>u.applied===void 0),f=ne(a),P=r.emitEvent??(()=>{});if(_.length===0&&f.length===0){t.out(`already reconciled \u2014 plan ${a.created} applied ${a.rows.length} row(s)`);let u=Pe(I(e)).staleCount;return u>0&&(t.out(`${u} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),P({type:"stale_debt",count:u})),i==="agent"&&(T(P,V(a),c),P({...j})),0}let p=B(e);return p!==a.head_pin?(t.out(`plan ${a.created} superseded \u2014 graph moved (${C(a.head_pin)} \u2192 ${C(p)}); recomputing`),Fe(e,a,t,r,i,s,o)):(t.out(`resuming plan ${a.created} \u2014 ${_.length} pending row(s)${f.length>0?`, ${f.length} undecided archive item(s)`:""}`),o?(K(t,V(a),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(T(P,V(a),c),P({...j})),0):i==="agent"?Y(e,V(a),c,s,P,t,D(i),(u,R)=>O(c,u,R),a.archive_state):i==="ci"&&f.length>0?(E(t,L(f.length)),2):H(e,a.rows,i==="override"||i==="ci",t,s,(u,R)=>O(c,u,R),a.changeset??[],D(i),a.held,a.archive_state,(u,R)=>G(c,u,R),w,d,a.source_id,F(a.backing_path??a.remote_url,a.source_id)))}async function Fe(e,n,t,r,i,s,o){let w=r.runDesignForUc??null,d=r.sessionScript,m;if(n.held){let h=I(e),k=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),y=[];for(let l of n.held.rows){if(k.has(l.temp_ref))continue;if(!l.matched_cid){y.push(l);continue}let $=h.tipOf(l.matched_cid);if(h.superseded.get($)===null){t.out(`dropped held "${l.title}" \u2014 its use-case was retired meanwhile`),r.emitEvent?.({type:"held_dropped",ref:l.temp_ref,title:l.title,reason:"target_retired"});continue}y.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}m={source_id:n.held.source_id,rows:y}}let a=Me(n);if(a===null)return E(t,`stored plan for ${n.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let c=z(e,n.source_id,a);if(c!==null)return E(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:me(e,a,t,r),reextract:ce(e,{stage:m!==void 0,hostOut:h=>t.out(h),hostEmit:h=>{h.type!=="run_start"&&r.emitEvent?.(h)},...r.emitEvent?{}:{hostProgress:h=>process.stderr.write(h+`
4
+ `)}})},f;try{f=await(r.buildPlan??ae)(e,n.source_id,_,{resumeHeld:m})}catch(h){return E(t,`reconcile failed: ${h instanceof Error?h.message:String(h)}`),1}if(i==="interactive"&&!o)for(let h of Ae(f,null))t.out(h);else K(t,f,null,!1,r.emitEvent);let P=B(e),p=null;if(P!=null){let h={},k=new Set(f.changeset.filter(y=>y.kind==="ARCHIVE").map(y=>y.ref));for(let[y,l]of Object.entries(n.archive_state??{}))k.has(y)&&(h[y]=l);p=ee(e,{version:2,source_id:f.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:P,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:f.skipped_arms,note:f.note,changeset:f.changeset,rows:f.rows,...f.held?{held:f.held}:{},...Object.keys(h).length>0?{archive_state:h}:{}}),t.out(`plan stored: ${p}`)}if(o){if(i==="agent"){let h=r.emitEvent??(()=>{});T(h,f,p),h({...j})}return 0}let u=r.emitEvent??(()=>{}),R=p?W(e,p).plan.archive_state:void 0,b=p?(h,k)=>O(p,h,k):void 0,v=p?(h,k)=>G(p,h,k):void 0;if(i==="agent")return Y(e,f,p,s,u,t,D(i),b,R);let g=f.changeset.filter(h=>h.kind==="ARCHIVE"&&R?.[h.ref]===void 0);return i==="ci"&&g.length>0?(E(t,L(g.length)),2):H(e,f.rows,i==="override"||i==="ci",t,s,b,f.changeset,D(i),f.held,R,v,w,d,f.source_id,F(n.backing_path??n.remote_url,f.source_id))}async function Ce(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:s}=await import("./bootstrap-KCPWDBLX.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:U(r,".context"),env:s(),applyPlanPath:typeof e.apply=="string"?U(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});{let m=Oe(U(r,".context"))?ye(U(r,".context")):null;if(m)return e.mode==="agent"?t.emitEvent?.(Z(m)):(E(n,m.text),(n.err??n.out)(`next: ${m.remedy}`)),await o.end({exit_code:2}),2}let w=await ve(U(r,".context"));w&&(e.mode==="agent"?t.emitEvent?.(we(w)):(n.err??n.out)(w.text));let d=await qe(e,n,t,r);return d===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:d}),d}async function qe(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,s=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return E(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&Q(e.from);if(o&&(!e.from||!e.sourceId&&!w))return E(n,"reconcile needs --from <file|url> AND --source-id <id> (files only \u2014 a URL derives its own id) \u2014 see `kane-cli context list --type source` for ids"),2;if(e.from&&s!==void 0)return E(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let d=ge(r,n);if(!d)return 2;if(e.mode!==void 0&&!Ue.has(e.mode))return Se(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let m=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!m&&!n.isTTY)return E(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let a=!e.plan,c="override";if(e.from){let k=Be(e,n.isTTY);if(typeof k=="object")return k.code==="MODE_USAGE"?Se(k.error):(E(n,k.error),2);c=k}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:k}=await import("./reconcile-deps-ZCJ2QCK5.js"),y=s===void 0?k({contextDir:d}).pending():null;if(y?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(E(n,`a held changeset for ${y.source} awaits review (${y.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ne)(d)}let l=e.mode??"interactive";return We(d,s===void 0?void 0:U(r,s),l,n,t)}let f=Ve(d,r,e.from,e.sourceId);if("error"in f)return E(n,f.error),2;if(!i){let{sessionsHoldingSource:k}=await import("./sessions-NH7WQWMX.js"),{holders:y,corrupt:l}=k(d,f.sourceId);if(l>0)return E(n,`cannot verify review holds \u2014 ${l} session file(s) unreadable; inspect with kane-cli context sessions list, clean with kane-cli context sessions clean, then retry [SESSIONS_UNREADABLE]`),2;if(y.length>0)return E(n,`session ${y[0]} holds item(s) for review pinned to ${f.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${y[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let k=t.seams?.reingest??me(d,f,n,t),y;try{y=await k(f.sourceId)}catch($){return E(n,$ instanceof Error?$.message:String($)),1}let l=y.status==="unchanged"?null:be(d,f.sourceId);if(y.status!=="unchanged"&&!l)return n.out(`${f.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${f.sourceId}`),0;if(l){let x=await(t.chatMount??(async M=>{let{bindExtractInteractive:N}=await import("./extract-bind-7IDQS4QP.js");return N(M)}))({mode:"interactive",posture:"reconcile",source:f.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:M}=await import("./sessions-NH7WQWMX.js");if(M(d,f.sourceId).holders.length===0)return 0}return x}}let P="remoteUrl"in f?{remoteUrl:f.remoteUrl}:{filePath:f.filePath},p=await He(d,f.sourceId,P,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!p)return 1;let u=t.runDesignForUc??oe,R=t.runDesignForUc??null,b=t.sessionScript;if(!p.changed){let k=await Ge(d,f.sourceId,n,t,c,u,!!e.plan);if(k!==null)return k;if(K(n,p,null,!1,t.emitEvent),c==="agent"){let y=t.emitEvent??(()=>{});T(y,p,null),y({...j})}return 0}let v=B(d),g=null;if(v!=null?g=ee(d,{version:2,source_id:p.source_id,..."remoteUrl"in P?{remote_url:P.remoteUrl}:{backing_path:P.filePath},head_pin:v,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:p.skipped_arms,note:p.note,changeset:p.changeset,rows:p.rows,...p.held?{held:p.held}:{}}):E(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let k=t.emitEvent??(()=>{});if(!a)return T(k,p,g),k({...j}),0;let y=g?(l,$)=>O(g,l,$):void 0;return Y(d,p,g,u,k,n,D(c),y)}if(!a)return g&&n.out(`plan stored: ${g}`),0;let h=p.changeset.filter(k=>k.kind==="ARCHIVE");if(c==="ci"&&h.length>0)return g&&n.out(`plan stored: ${g}`),E(n,L(h.length)),2;if(g){n.out(`plan stored: ${g}`);let k=g;return H(d,ze(d,k)??p.rows,_,n,u,(y,l)=>O(k,y,l),p.changeset,D(c),p.held,void 0,void 0,R,b,p.source_id,F(e.from,p.source_id))}return H(d,p.rows,_,n,u,void 0,p.changeset,D(c),p.held,void 0,void 0,R,b,p.source_id,F(e.from,p.source_id))}function ze(e,n){let t=W(e,n);return"error"in t?null:t.plan.rows}async function hn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-3A3BZVQ5.js"),s=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:s.out,err:m=>s.event({type:"error",message:m}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),d=2;try{d=await w({event:m=>s.event(m)},()=>Ce(e,o,{...n,emitEvent:m=>s.event(m)},r))}catch(m){m instanceof pe?(d=2,s.event(Z({code:m.code,text:m.message,remedy:m.remedy}))):(d=1,s.event({type:"error",message:m instanceof Error?m.message:String(m)}))}return s.done(d)}return Ce(e,he(),n,r)}export{Be as a,Ve as b,D as c,A as d,Ce as e,hn as f};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as y}from"./chunk-OH2NSBO6.js";import{createServer as b}from"http";import{createReadStream as C,promises as S}from"fs";import{randomBytes as R}from"crypto";var u="127.0.0.1";function A(n,e){if(!n)return null;let o=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!o)return null;let[,a,r]=o;if(a===""&&r==="")return null;if(a===""){let i=Number(r);return i===0||e===0?"unsatisfiable":{start:Math.max(0,e-i),end:e-1}}let t=Number(a);if(t>=e)return"unsatisfiable";let c=r===""?e-1:Math.min(Number(r),e-1);return c<t?null:{start:t,end:c}}async function I(n){let e=R(16).toString("hex"),o=b((r,t)=>{H(r,t,n,e).catch(()=>t.destroy())});await new Promise((r,t)=>{o.once("error",t),o.listen(n.port??0,u,()=>{o.removeListener("error",t),r()})});let a=o.address().port;return{port:a,urlFor:r=>`http://${u}:${a}/${e}/${encodeURIComponent(r)}`,close:()=>new Promise(r=>{o.close(()=>r()),o.closeAllConnections()})}}async function H(n,e,o,a){let r=n.url??"/",t=s=>{try{o.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:s,path:r})}catch{}};if(n.headers.host!==`${u}:${n.socket.localPort}`){t("host_mismatch"),e.writeHead(403).end();return}let c=n.headers.origin;if(c!==void 0&&!o.allowedOrigins.includes(c)){t("origin_denied"),e.writeHead(403).end();return}let i=c?{"Access-Control-Allow-Origin":c,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(n.method==="OPTIONS"){let s={...i,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};n.headers["access-control-request-private-network"]==="true"&&(s["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,s).end();return}if(n.method!=="GET"&&n.method!=="HEAD"){e.writeHead(405,i).end();return}let v;try{let s=new URL(n.url??"/",`http://${u}`).pathname.split("/");if(s.length!==3||s[1]!==a){t("bad_token"),e.writeHead(404,i).end();return}v=decodeURIComponent(s[2])}catch{t("not_found"),e.writeHead(404,i).end();return}let g=o.packs.get(v);if(!g){t("not_found"),e.writeHead(404,i).end();return}let d;try{let s=await S.stat(g);if(!s.isFile())throw new Error("not a file");d=s.size}catch{t("not_found"),e.writeHead(404,i).end();return}let h={...i,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(n.method==="HEAD"){e.writeHead(200,{...h,"Content-Length":String(d)}).end();return}let l=A(n.headers.range,d);if(l==="unsatisfiable"){t("unsatisfiable"),e.writeHead(416,{...i,"Content-Range":`bytes */${d}`}).end();return}let[m,p,w]=l===null?[0,d-1,200]:[l.start,l.end,206],E={...h,"Content-Length":String(p-m+1)};if(w===206&&(E["Content-Range"]=`bytes ${m}-${p}/${d}`),e.writeHead(w,E),d===0){e.end();return}let f=C(g,{start:m,end:p});f.on("error",()=>e.destroy()),e.on("close",()=>f.destroy()),f.pipe(e)}function O(n,e){return(e??y(n).evidenceViewerUrl).replace(/\/+$/,"")}function k(n,e){return`${e}/?pack=${encodeURIComponent(n)}`}function P(n){return`evidence: view locally with \`kane-cli evidence serve ${n}\``}export{A as a,I as b,O as c,k as d,P as e};
2
+ import{a as y}from"./chunk-EPE2ELDH.js";import{createServer as b}from"http";import{createReadStream as C,promises as S}from"fs";import{randomBytes as R}from"crypto";var u="127.0.0.1";function A(n,e){if(!n)return null;let o=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!o)return null;let[,a,r]=o;if(a===""&&r==="")return null;if(a===""){let i=Number(r);return i===0||e===0?"unsatisfiable":{start:Math.max(0,e-i),end:e-1}}let t=Number(a);if(t>=e)return"unsatisfiable";let c=r===""?e-1:Math.min(Number(r),e-1);return c<t?null:{start:t,end:c}}async function I(n){let e=R(16).toString("hex"),o=b((r,t)=>{H(r,t,n,e).catch(()=>t.destroy())});await new Promise((r,t)=>{o.once("error",t),o.listen(n.port??0,u,()=>{o.removeListener("error",t),r()})});let a=o.address().port;return{port:a,urlFor:r=>`http://${u}:${a}/${e}/${encodeURIComponent(r)}`,close:()=>new Promise(r=>{o.close(()=>r()),o.closeAllConnections()})}}async function H(n,e,o,a){let r=n.url??"/",t=s=>{try{o.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:s,path:r})}catch{}};if(n.headers.host!==`${u}:${n.socket.localPort}`){t("host_mismatch"),e.writeHead(403).end();return}let c=n.headers.origin;if(c!==void 0&&!o.allowedOrigins.includes(c)){t("origin_denied"),e.writeHead(403).end();return}let i=c?{"Access-Control-Allow-Origin":c,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(n.method==="OPTIONS"){let s={...i,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};n.headers["access-control-request-private-network"]==="true"&&(s["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,s).end();return}if(n.method!=="GET"&&n.method!=="HEAD"){e.writeHead(405,i).end();return}let v;try{let s=new URL(n.url??"/",`http://${u}`).pathname.split("/");if(s.length!==3||s[1]!==a){t("bad_token"),e.writeHead(404,i).end();return}v=decodeURIComponent(s[2])}catch{t("not_found"),e.writeHead(404,i).end();return}let g=o.packs.get(v);if(!g){t("not_found"),e.writeHead(404,i).end();return}let d;try{let s=await S.stat(g);if(!s.isFile())throw new Error("not a file");d=s.size}catch{t("not_found"),e.writeHead(404,i).end();return}let h={...i,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(n.method==="HEAD"){e.writeHead(200,{...h,"Content-Length":String(d)}).end();return}let l=A(n.headers.range,d);if(l==="unsatisfiable"){t("unsatisfiable"),e.writeHead(416,{...i,"Content-Range":`bytes */${d}`}).end();return}let[m,p,w]=l===null?[0,d-1,200]:[l.start,l.end,206],E={...h,"Content-Length":String(p-m+1)};if(w===206&&(E["Content-Range"]=`bytes ${m}-${p}/${d}`),e.writeHead(w,E),d===0){e.end();return}let f=C(g,{start:m,end:p});f.on("error",()=>e.destroy()),e.on("close",()=>f.destroy()),f.pipe(e)}function O(n,e){return(e??y(n).evidenceViewerUrl).replace(/\/+$/,"")}function k(n,e){return`${e}/?pack=${encodeURIComponent(n)}`}function P(n){return`evidence: view locally with \`kane-cli evidence serve ${n}\``}export{A as a,I as b,O as c,k as d,P as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as f}from"./chunk-J7NRD4Q7.js";import{c as g}from"./chunk-UD7KKHPW.js";import{existsSync as u}from"fs";import{dirname as A,resolve as l}from"path";import{fileURLToPath as E}from"url";var p=A(E(import.meta.url));function _(){return[l(p,".."),l(p,"../../..")]}function x(s){return{"darwin-arm64":"kane-cli-darwin-arm64","darwin-x64":"kane-cli-darwin-x64","linux-x64":"kane-cli-linux-x64","linux-arm64":"kane-cli-linux-arm64","win32-x64":"kane-cli-win-x64"}[s]??null}function T(s){return{"darwin-arm64":"kane-cli-assurance-darwin-arm64","darwin-x64":"kane-cli-assurance-darwin-x64","linux-x64":"kane-cli-assurance-linux-x64","linux-arm64":"kane-cli-assurance-linux-arm64","win32-x64":"kane-cli-assurance-win-x64"}[s]??null}function I(s=_()){let n=x(`${process.platform}-${process.arch}`),i=T(`${process.platform}-${process.arch}`),a=process.platform==="win32"?"assurance-agent.exe":"assurance-agent";for(let e of s){for(let t of i?["@testmuai","@lambdatestincprivate"]:[]){let m=l(e,"node_modules",t,i,"bin",a);if(u(m))return{cmd:m,args:[],tier:"platform"}}for(let t of n?["@testmuai","@lambdatestincprivate"]:[]){let m=l(e,"node_modules",t,n,"bin",a);if(u(m))return{cmd:m,args:[],tier:"platform"}}let c=l(e,"dist","bin",a);if(u(c))return{cmd:c,args:[],tier:"embedded"};let r=l(e,"../assurance-agent/dist",a);if(u(r))return{cmd:r,args:[],tier:"sibling"};let o=l(e,"../assurance-agent/main.py");if(u(o)){let t=l(e,"../assurance-agent/.venv/bin/python");return{cmd:u(t)?t:"python3",args:[o],tier:"dev-python"}}}return null}function U(s,n={}){return{...process.env,...n,...f(),TESTMUAI_SOURCE:"kane-cli",TESTMUAI_SESSION_ID:s,ASSURANCE_LOG_LEVEL:process.env.ASSURANCE_LOG_LEVEL??"info"}}async function P(){if(process.env.TESTMUAI_API_KEY||process.env.TESTMUAI_BASIC_AUTH)return{};try{let{CredentialsManager:s}=await import("./credentials-Q4WH5CBN.js"),n=process.env.TESTMUAI_ENV==="stage"?"stage":"prod",i=new s,a=i.getActiveProfile()??"default",e={TESTMUAI_ENV:n},c=i.loadBasicAuth(a,n);if(c)return e.TESTMUAI_BASIC_AUTH=Buffer.from(`${c.username}:${c.access_key}`,"utf8").toString("base64"),e;let r=i.loadCredentials(a,n);if(r){try{let{refreshOAuthToken:t}=await import("./token-refresh-KN5JK2U4.js");await t({creds:i,profile:a,env:n,credentials:r})}catch{}let o=i.loadCredentials(a,n)??r;if(typeof o.access_token=="string"){let t=await w(n,o.access_token);return t?(e.TESTMUAI_BASIC_AUTH=t,e):(e.TESTMUAI_API_KEY=o.access_token,e)}}return{}}catch{return{}}}var h=8e3;function d(){return g("warn: session auth may expire during long runs \u2014 if that happens, run `kane-cli login` and retry","AUTH_EXCHANGE_FAILED"),null}async function w(s,n){try{let[{getEnvironment:i},{ControllerClient:a}]=await Promise.all([import("./config-3AKWRTFS.js"),import("./controller-client-ZF5IXRUV.js")]),e=new a(i(s).controllerBaseUrl,n),c;try{let r=await Promise.race([e.getTmsCredentials().catch(()=>null),new Promise(o=>{c=setTimeout(()=>o(null),h)})]);if(typeof r?.username!="string"||!r.username||typeof r.access_key!="string"||!r.access_key)return d();try{let[{refreshIdentitySnapshot:o},{telemetryEnvName:t}]=await Promise.all([import("./identity-ADZ4PAJF.js"),import("./bootstrap-6IJNZIPT.js")]);await o(t(),r)}catch{}return Buffer.from(`${r.username}:${r.access_key}`,"utf8").toString("base64")}finally{clearTimeout(c)}}catch{return d()}}export{x as a,T as b,I as c,U as d,P as e};
2
+ import{b as f}from"./chunk-DMT3W26F.js";import{c as g}from"./chunk-UD7KKHPW.js";import{existsSync as u}from"fs";import{dirname as A,resolve as l}from"path";import{fileURLToPath as E}from"url";var p=A(E(import.meta.url));function _(){return[l(p,".."),l(p,"../../..")]}function x(s){return{"darwin-arm64":"kane-cli-darwin-arm64","darwin-x64":"kane-cli-darwin-x64","linux-x64":"kane-cli-linux-x64","linux-arm64":"kane-cli-linux-arm64","win32-x64":"kane-cli-win-x64"}[s]??null}function T(s){return{"darwin-arm64":"kane-cli-assurance-darwin-arm64","darwin-x64":"kane-cli-assurance-darwin-x64","linux-x64":"kane-cli-assurance-linux-x64","linux-arm64":"kane-cli-assurance-linux-arm64","win32-x64":"kane-cli-assurance-win-x64"}[s]??null}function I(s=_()){let n=x(`${process.platform}-${process.arch}`),i=T(`${process.platform}-${process.arch}`),a=process.platform==="win32"?"assurance-agent.exe":"assurance-agent";for(let e of s){for(let t of i?["@testmuai","@lambdatestincprivate"]:[]){let m=l(e,"node_modules",t,i,"bin",a);if(u(m))return{cmd:m,args:[],tier:"platform"}}for(let t of n?["@testmuai","@lambdatestincprivate"]:[]){let m=l(e,"node_modules",t,n,"bin",a);if(u(m))return{cmd:m,args:[],tier:"platform"}}let c=l(e,"dist","bin",a);if(u(c))return{cmd:c,args:[],tier:"embedded"};let r=l(e,"../assurance-agent/dist",a);if(u(r))return{cmd:r,args:[],tier:"sibling"};let o=l(e,"../assurance-agent/main.py");if(u(o)){let t=l(e,"../assurance-agent/.venv/bin/python");return{cmd:u(t)?t:"python3",args:[o],tier:"dev-python"}}}return null}function U(s,n={}){return{...process.env,...n,...f(),TESTMUAI_SOURCE:"kane-cli",TESTMUAI_SESSION_ID:s,ASSURANCE_LOG_LEVEL:process.env.ASSURANCE_LOG_LEVEL??"info"}}async function P(){if(process.env.TESTMUAI_API_KEY||process.env.TESTMUAI_BASIC_AUTH)return{};try{let{CredentialsManager:s}=await import("./credentials-GWLYYRTL.js"),n=process.env.TESTMUAI_ENV==="stage"?"stage":"prod",i=new s,a=i.getActiveProfile()??"default",e={TESTMUAI_ENV:n},c=i.loadBasicAuth(a,n);if(c)return e.TESTMUAI_BASIC_AUTH=Buffer.from(`${c.username}:${c.access_key}`,"utf8").toString("base64"),e;let r=i.loadCredentials(a,n);if(r){try{let{refreshOAuthToken:t}=await import("./token-refresh-NTE4LQRN.js");await t({creds:i,profile:a,env:n,credentials:r})}catch{}let o=i.loadCredentials(a,n)??r;if(typeof o.access_token=="string"){let t=await w(n,o.access_token);return t?(e.TESTMUAI_BASIC_AUTH=t,e):(e.TESTMUAI_API_KEY=o.access_token,e)}}return{}}catch{return{}}}var h=8e3;function d(){return g("warn: session auth may expire during long runs \u2014 if that happens, run `kane-cli login` and retry","AUTH_EXCHANGE_FAILED"),null}async function w(s,n){try{let[{getEnvironment:i},{ControllerClient:a}]=await Promise.all([import("./config-UGCWZGH5.js"),import("./controller-client-ZF5IXRUV.js")]),e=new a(i(s).controllerBaseUrl,n),c;try{let r=await Promise.race([e.getTmsCredentials().catch(()=>null),new Promise(o=>{c=setTimeout(()=>o(null),h)})]);if(typeof r?.username!="string"||!r.username||typeof r.access_key!="string"||!r.access_key)return d();try{let[{refreshIdentitySnapshot:o},{telemetryEnvName:t}]=await Promise.all([import("./identity-ADZ4PAJF.js"),import("./bootstrap-KCPWDBLX.js")]);await o(t(),r)}catch{}return Buffer.from(`${r.username}:${r.access_key}`,"utf8").toString("base64")}finally{clearTimeout(c)}}catch{return d()}}export{x as a,T as b,I as c,U as d,P as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-X74PP5NJ.js";import{y as t}from"./chunk-B2ZGG7WM.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a,b as n}from"./chunk-C44QQJR4.js";import{a as R}from"./chunk-6YGTRKDT.js";import{e as c}from"./chunk-UR6MHSHU.js";var p=c(R(),1);var e=c(x(),1);function v(){return[{name:"convert",label:"Converting session data",status:"pending"},{name:"zip",label:"Compressing artifacts",status:"pending"},{name:"presign",label:"Requesting upload URLs",status:"pending"},{name:"upload",label:"Uploading to KaneAI",status:"pending"},{name:"atomic_replace",label:"Replacing local output",status:"pending"},{name:"commit_lock",label:"Committing to TMS",status:"pending"},{name:"finalize",label:"Finalizing test case",status:"pending"},{name:"code_export",label:"Downloading test code",status:"pending"}]}function U(s,o,d,i){return s.map(l=>l.name===o?{...l,status:d,detail:i}:l)}function D(s){let o=s/1e3;if(o<60)return`${o.toFixed(1)}s`;let d=Math.floor(o/60),i=Math.round(o%60);return`${d}m ${i}s`}function w(s){let[o,d]=(0,p.useState)(0),i=p.default.useRef(Date.now());return(0,p.useEffect)(()=>{if(!s)return;i.current=Date.now();let l=setInterval(()=>{d(Date.now()-i.current)},100);return()=>clearInterval(l)},[s]),o}function h({steps:s,status:o,testUrl:d,error:i}){let l=w(o==="uploading");return o==="uploading"?(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.orange,children:"\u2601 "}),(0,e.jsx)(n,{color:t.orange,bold:!0,children:"Saving to KaneAI"}),(0,e.jsxs)(n,{color:t.dim,children:[" ",D(l)]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:s.filter(r=>r.status!=="skipped"||r.detail).map((r,S,T)=>{let b=S===T.length-1?"\u2514\u2500":"\u251C\u2500",u=r.status==="done",m=r.status==="running",g=r.status==="failed",B=r.status==="skipped";return(0,e.jsxs)(a,{children:[(0,e.jsxs)(n,{color:t.dim,children:[" ",b," "]}),(0,e.jsx)(a,{width:3,children:m?(0,e.jsx)(f,{}):u?(0,e.jsx)(n,{color:t.green,children:"\u2713"}):g?(0,e.jsx)(n,{color:t.red,children:"\u2717"}):B?(0,e.jsx)(n,{color:t.muted,children:"\u2013"}):(0,e.jsx)(n,{color:t.muted,children:"\u25CB"})}),(0,e.jsx)(n,{color:u?t.dim:m?void 0:g?t.red:t.muted,children:r.label}),r.detail&&(0,e.jsxs)(n,{color:t.dim,children:[" ",r.detail]})]},r.name)})}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(n,{color:t.muted,children:" press Ctrl+C twice to force exit"})})]}):o==="success"?(0,e.jsx)(e.Fragment,{}):(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.red,children:"\u2601 "}),(0,e.jsx)(n,{color:t.red,bold:!0,children:"Save failed"})]}),i&&(0,e.jsxs)(a,{marginTop:0,children:[(0,e.jsx)(n,{color:t.dim,children:" "}),(0,e.jsx)(n,{color:t.dim,children:i})]})]})}export{v as a,U as b,h as c};
2
+ import{a as f}from"./chunk-5HTSKF5K.js";import{y as t}from"./chunk-HYTBEPC2.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a,b as n}from"./chunk-C44QQJR4.js";import{a as R}from"./chunk-6YGTRKDT.js";import{e as c}from"./chunk-UR6MHSHU.js";var p=c(R(),1);var e=c(x(),1);function v(){return[{name:"convert",label:"Converting session data",status:"pending"},{name:"zip",label:"Compressing artifacts",status:"pending"},{name:"presign",label:"Requesting upload URLs",status:"pending"},{name:"upload",label:"Uploading to KaneAI",status:"pending"},{name:"atomic_replace",label:"Replacing local output",status:"pending"},{name:"commit_lock",label:"Committing to TMS",status:"pending"},{name:"finalize",label:"Finalizing test case",status:"pending"},{name:"code_export",label:"Downloading test code",status:"pending"}]}function U(s,o,d,i){return s.map(l=>l.name===o?{...l,status:d,detail:i}:l)}function D(s){let o=s/1e3;if(o<60)return`${o.toFixed(1)}s`;let d=Math.floor(o/60),i=Math.round(o%60);return`${d}m ${i}s`}function w(s){let[o,d]=(0,p.useState)(0),i=p.default.useRef(Date.now());return(0,p.useEffect)(()=>{if(!s)return;i.current=Date.now();let l=setInterval(()=>{d(Date.now()-i.current)},100);return()=>clearInterval(l)},[s]),o}function h({steps:s,status:o,testUrl:d,error:i}){let l=w(o==="uploading");return o==="uploading"?(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.orange,children:"\u2601 "}),(0,e.jsx)(n,{color:t.orange,bold:!0,children:"Saving to KaneAI"}),(0,e.jsxs)(n,{color:t.dim,children:[" ",D(l)]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:s.filter(r=>r.status!=="skipped"||r.detail).map((r,S,T)=>{let b=S===T.length-1?"\u2514\u2500":"\u251C\u2500",u=r.status==="done",m=r.status==="running",g=r.status==="failed",B=r.status==="skipped";return(0,e.jsxs)(a,{children:[(0,e.jsxs)(n,{color:t.dim,children:[" ",b," "]}),(0,e.jsx)(a,{width:3,children:m?(0,e.jsx)(f,{}):u?(0,e.jsx)(n,{color:t.green,children:"\u2713"}):g?(0,e.jsx)(n,{color:t.red,children:"\u2717"}):B?(0,e.jsx)(n,{color:t.muted,children:"\u2013"}):(0,e.jsx)(n,{color:t.muted,children:"\u25CB"})}),(0,e.jsx)(n,{color:u?t.dim:m?void 0:g?t.red:t.muted,children:r.label}),r.detail&&(0,e.jsxs)(n,{color:t.dim,children:[" ",r.detail]})]},r.name)})}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(n,{color:t.muted,children:" press Ctrl+C twice to force exit"})})]}):o==="success"?(0,e.jsx)(e.Fragment,{}):(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.red,children:"\u2601 "}),(0,e.jsx)(n,{color:t.red,bold:!0,children:"Save failed"})]}),i&&(0,e.jsxs)(a,{marginTop:0,children:[(0,e.jsx)(n,{color:t.dim,children:" "}),(0,e.jsx)(n,{color:t.dim,children:i})]})]})}export{v as a,U as b,h as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{homedir as s}from"os";import{join as t}from"path";var g="0.8.14";var a=t(s(),".testmuai","kaneai"),b=t(a,"profiles"),h=t(a,"tui-config.json"),_=t(a,"media"),A="https://registry.npmjs.org/@testmuai/kane-cli",x="https://api.github.com/repos/LambdaTest/kane-cli/releases",i="@testmuai/kane-cli-skill",L=`https://registry.npmjs.org/${i}`,r="kane-cli",u=[{dir:t(s(),".claude","skills",r),agent:"Claude Code"},{dir:t(s(),".agents","skills",r),agent:"Codex CLI"},{dir:t(s(),".gemini","skills",r),agent:"Gemini CLI"}],U="https://dd-proxy.lambdatest.com/intake/kane-cli",R="https://kaneai-playground.lambdatest.io",I=9222,E=9230,C=t(a,"chrome-profiles"),o=t(a,"hints"),T=t(o,"state.json");function f(e){return t(o,`catalog-${e}.json`)}var c=t(a,"mobile");function S(e,n="android"){return t(c,n==="ios"?`device-catalog-ios-${e}.json`:`device-catalog-${e}.json`)}var l="127.0.0.1",B=18392,v=18400,p="/callback";function N(e){return`http://${l}:${e}${p}`}var O="KANE CLI",P="*",k={prod:{authBaseUrl:"https://auth.lambdatest.com",consentUrl:"https://accounts.lambdatest.com",controllerBaseUrl:"https://kaneai-api.lambdatest.com/v16-controller/v1",tmsBaseUrl:"https://test-manager-api.lambdatest.com/api",testGeneratorBaseUrl:"https://test-manager-api.lambdatest.com",secretsBaseUrl:"https://api-hyperexecute.lambdatest.com",testManagerUiUrl:"https://test-manager.lambdatest.com",shareApiBaseUrl:"https://api.lambdatest.com",v16ServerHost:"https://kaneai-api.lambdatest.com/v16-server",evidenceViewerUrl:"https://evidence.lambdatest.com",mediaArtefactsHost:"prod-mobile-artefacts.lambdatest.com",mobileAppBaseUrl:"https://api.lambdatest.com"},stage:{authBaseUrl:"https://stage-auth.lambdatestinternal.com",consentUrl:"https://stage-accounts.lambdatestinternal.com",controllerBaseUrl:"https://auteur-stage-automind.lambdatestinternal.com/v16-controller/v1",tmsBaseUrl:"https://stage-test-manager-api.lambdatestinternal.com/api",testGeneratorBaseUrl:"https://stage-test-manager-api.lambdatestinternal.com",secretsBaseUrl:"https://api-stage-hyperexecute.lambdatestinternal.com",testManagerUiUrl:"https://stage-test-manager.lambdatestinternal.com",shareApiBaseUrl:"https://stage-api.lambdatestinternal.com",v16ServerHost:"https://auteur-stage-automind.lambdatestinternal.com/v16-server",evidenceViewerUrl:"https://stage-evidence.lambdatestinternal.com",mediaArtefactsHost:"stage-mobile-artefacts.lambdatestinternal.com",mobileAppBaseUrl:"https://stage-api.lambdatestinternal.com"}},D={orange:"#ff9500",generateAccent:"#0d9488",assuranceAccent:"#b388ff",purple:"#b388ff",secondary:"#888888",dim:"#666666",muted:"#444444",green:"#4ade80",red:"#ef4444",amber:"#fbbf24"};export{g as a,a as b,h as c,_ as d,A as e,x as f,i as g,u as h,U as i,R as j,I as k,E as l,C as m,T as n,f as o,S as p,l as q,B as r,v as s,p as t,N as u,O as v,P as w,k as x,D as y};
2
+ import{homedir as s}from"os";import{join as t}from"path";var g="0.8.15";var a=t(s(),".testmuai","kaneai"),b=t(a,"profiles"),h=t(a,"tui-config.json"),_=t(a,"media"),A="https://registry.npmjs.org/@testmuai/kane-cli",x="https://api.github.com/repos/LambdaTest/kane-cli/releases",i="@testmuai/kane-cli-skill",L=`https://registry.npmjs.org/${i}`,r="kane-cli",u=[{dir:t(s(),".claude","skills",r),agent:"Claude Code"},{dir:t(s(),".agents","skills",r),agent:"Codex CLI"},{dir:t(s(),".gemini","skills",r),agent:"Gemini CLI"}],U="https://dd-proxy.lambdatest.com/intake/kane-cli",R="https://kaneai-playground.lambdatest.io",I=9222,E=9230,C=t(a,"chrome-profiles"),o=t(a,"hints"),T=t(o,"state.json");function f(e){return t(o,`catalog-${e}.json`)}var c=t(a,"mobile");function S(e,n="android"){return t(c,n==="ios"?`device-catalog-ios-${e}.json`:`device-catalog-${e}.json`)}var l="127.0.0.1",B=18392,v=18400,p="/callback";function N(e){return`http://${l}:${e}${p}`}var O="KANE CLI",P="*",k={prod:{authBaseUrl:"https://auth.lambdatest.com",consentUrl:"https://accounts.lambdatest.com",controllerBaseUrl:"https://kaneai-api.lambdatest.com/v16-controller/v1",tmsBaseUrl:"https://test-manager-api.lambdatest.com/api",testGeneratorBaseUrl:"https://test-manager-api.lambdatest.com",secretsBaseUrl:"https://api-hyperexecute.lambdatest.com",testManagerUiUrl:"https://test-manager.lambdatest.com",shareApiBaseUrl:"https://api.lambdatest.com",v16ServerHost:"https://kaneai-api.lambdatest.com/v16-server",evidenceViewerUrl:"https://evidence.lambdatest.com",mediaArtefactsHost:"prod-mobile-artefacts.lambdatest.com",mobileAppBaseUrl:"https://api.lambdatest.com"},stage:{authBaseUrl:"https://stage-auth.lambdatestinternal.com",consentUrl:"https://stage-accounts.lambdatestinternal.com",controllerBaseUrl:"https://auteur-stage-automind.lambdatestinternal.com/v16-controller/v1",tmsBaseUrl:"https://stage-test-manager-api.lambdatestinternal.com/api",testGeneratorBaseUrl:"https://stage-test-manager-api.lambdatestinternal.com",secretsBaseUrl:"https://api-stage-hyperexecute.lambdatestinternal.com",testManagerUiUrl:"https://stage-test-manager.lambdatestinternal.com",shareApiBaseUrl:"https://stage-api.lambdatestinternal.com",v16ServerHost:"https://auteur-stage-automind.lambdatestinternal.com/v16-server",evidenceViewerUrl:"https://stage-evidence.lambdatestinternal.com",mediaArtefactsHost:"stage-mobile-artefacts.lambdatestinternal.com",mobileAppBaseUrl:"https://stage-api.lambdatestinternal.com"}},D={orange:"#ff9500",generateAccent:"#0d9488",assuranceAccent:"#b388ff",purple:"#b388ff",secondary:"#888888",dim:"#666666",muted:"#444444",green:"#4ade80",red:"#ef4444",amber:"#fbbf24"};export{g as a,a as b,h as c,_ as d,A as e,x as f,i as g,u as h,U as i,R as j,I as k,E as l,C as m,T as n,f as o,S as p,l as q,B as r,v as s,p as t,N as u,O as v,P as w,k as x,D as y};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{h as w}from"./chunk-TAOHYWEO.js";import{a as h}from"./chunk-RZ4F3BHX.js";import{b as f}from"./chunk-B2ZGG7WM.js";import{mkdtemp as O,rm as $}from"fs/promises";import{createWriteStream as R}from"fs";import{Readable as U}from"stream";import{pipeline as F}from"stream/promises";import{tmpdir as T}from"os";import{basename as z,join as A}from"path";import{access as x,cp as P,mkdir as g,readdir as y,readFile as S,rename as I,rm as k,stat as b,writeFile as v}from"fs/promises";import{basename as D,join as d}from"path";function u(){return d(f,"mobile","apps")}function m(){return d(u(),"index.json")}function C(){return{readIndex:async()=>{try{let e=JSON.parse(await S(m(),"utf8"));return{apps:Array.isArray(e.apps)?e.apps:[]}}catch{return{apps:[]}}},writeIndex:async r=>{await g(u(),{recursive:!0});let e=`${m()}.tmp`;await v(e,JSON.stringify(r,null,2)),await I(e,m())},exists:async r=>{try{return await x(r),!0}catch{return!1}},copy:(r,e)=>P(r,e,{recursive:!0,force:!0}),remove:r=>k(r,{recursive:!0,force:!0}),sizeOf:async r=>{try{return(await b(r)).size}catch{return}},now:()=>new Date}}var c=class{deps;constructor(e={}){this.deps={...C(),...e}}async list(){let{apps:e}=await this.deps.readIndex();return[...e].sort((t,s)=>s.lastUsedAt.localeCompare(t.lastUsedAt))}async find(e){return(await this.deps.readIndex()).apps.find(t=>t.key===e)}async put(e){let t=await this.deps.readIndex(),s=t.apps.find(n=>n.key===e.key),a=this.deps.now().toISOString();if(s&&await this.deps.exists(s.path))return s.lastUsedAt=a,await this.deps.writeIndex(t),s;s&&(t.apps=t.apps.filter(n=>n.key!==e.key));let l=D(e.name??e.sourcePath),o=d(u(),e.key),p=d(o,l);await g(o,{recursive:!0}),await this.deps.copy(e.sourcePath,p);let i={key:e.key,path:p,name:l,source:e.source,...e.source==="local"?{originPath:e.sourcePath}:{},addedAt:a,lastUsedAt:a,...await this.deps.sizeOf(p).then(n=>n?{bytes:n}:{})};return t.apps=[...t.apps.filter(n=>n.key!==e.key),i],await this.deps.writeIndex(t),i}async exists(e){if(await this.deps.sizeOf(e.path)!==void 0)return!0;try{return await y(e.path),!0}catch{return!1}}async forget(e){let t=await this.deps.readIndex(),s=t.apps.find(a=>a.key===e);s&&(await this.deps.remove(s.path),t.apps=t.apps.filter(a=>a.key!==e),await this.deps.writeIndex(t))}async prune(){let e=await this.deps.readIndex(),t=[];for(let s of e.apps)if(await this.deps.sizeOf(s.path)!==void 0)t.push(s);else try{await y(s.path),t.push(s)}catch{}return t.length!==e.apps.length&&await this.deps.writeIndex({apps:t}),t}};var E=30*6e4,j=/^APP\d{6,}$/;function Y(r){return!!r&&j.test(r.trim())}function _(){return{store:new c,client:(r,e)=>new w(r,e),fetchToFile:async(r,e)=>{let t=await h(r,{method:"GET",signal:AbortSignal.timeout(E)});if(!t.ok)throw new Error(`Downloading the app failed: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("Downloading the app failed: empty response body");await F(U.fromWeb(t.body),R(e))}}}async function Z(r,e={}){let t={..._(),...e},s=r.appId.trim(),a=await t.store.find(s);if(a&&await t.store.exists(a))return r.onProgress?.(`using the copy of ${a.name} already on this machine`),await t.store.put({key:s,sourcePath:a.path,source:"cloud",name:a.name}),{path:a.path,name:a.name,fromStore:!0};r.onProgress?.(`looking up ${s}\u2026`);let o=await t.client(r.baseUrl,r.auth).details(s);if(r.accepts&&!r.accepts.some(i=>o.name.toLowerCase().endsWith(i)))throw new Error(`${o.name} cannot run on this device \u2014 expected ${r.accepts.join(" or ")}.`);r.onProgress?.(`downloading ${o.name} \u2014 this can take a while, please wait\u2026`);let p=await O(A(T(),"kane-app-dl-"));try{let i=A(p,z(o.name));await t.fetchToFile(o.url,i);let n=await t.store.put({key:s,sourcePath:i,source:"cloud",name:o.name});return r.onProgress?.(`${o.name} is ready`),{path:n.path,name:n.name,fromStore:!1,details:o}}finally{await $(p,{recursive:!0,force:!0})}}export{c as a,Y as b,Z as c};
2
+ import{h as w}from"./chunk-TAOHYWEO.js";import{a as h}from"./chunk-RZ4F3BHX.js";import{b as f}from"./chunk-HYTBEPC2.js";import{mkdtemp as O,rm as $}from"fs/promises";import{createWriteStream as R}from"fs";import{Readable as U}from"stream";import{pipeline as F}from"stream/promises";import{tmpdir as T}from"os";import{basename as z,join as A}from"path";import{access as x,cp as P,mkdir as g,readdir as y,readFile as S,rename as I,rm as k,stat as b,writeFile as v}from"fs/promises";import{basename as D,join as d}from"path";function u(){return d(f,"mobile","apps")}function m(){return d(u(),"index.json")}function C(){return{readIndex:async()=>{try{let e=JSON.parse(await S(m(),"utf8"));return{apps:Array.isArray(e.apps)?e.apps:[]}}catch{return{apps:[]}}},writeIndex:async r=>{await g(u(),{recursive:!0});let e=`${m()}.tmp`;await v(e,JSON.stringify(r,null,2)),await I(e,m())},exists:async r=>{try{return await x(r),!0}catch{return!1}},copy:(r,e)=>P(r,e,{recursive:!0,force:!0}),remove:r=>k(r,{recursive:!0,force:!0}),sizeOf:async r=>{try{return(await b(r)).size}catch{return}},now:()=>new Date}}var c=class{deps;constructor(e={}){this.deps={...C(),...e}}async list(){let{apps:e}=await this.deps.readIndex();return[...e].sort((t,s)=>s.lastUsedAt.localeCompare(t.lastUsedAt))}async find(e){return(await this.deps.readIndex()).apps.find(t=>t.key===e)}async put(e){let t=await this.deps.readIndex(),s=t.apps.find(n=>n.key===e.key),a=this.deps.now().toISOString();if(s&&await this.deps.exists(s.path))return s.lastUsedAt=a,await this.deps.writeIndex(t),s;s&&(t.apps=t.apps.filter(n=>n.key!==e.key));let l=D(e.name??e.sourcePath),o=d(u(),e.key),p=d(o,l);await g(o,{recursive:!0}),await this.deps.copy(e.sourcePath,p);let i={key:e.key,path:p,name:l,source:e.source,...e.source==="local"?{originPath:e.sourcePath}:{},addedAt:a,lastUsedAt:a,...await this.deps.sizeOf(p).then(n=>n?{bytes:n}:{})};return t.apps=[...t.apps.filter(n=>n.key!==e.key),i],await this.deps.writeIndex(t),i}async exists(e){if(await this.deps.sizeOf(e.path)!==void 0)return!0;try{return await y(e.path),!0}catch{return!1}}async forget(e){let t=await this.deps.readIndex(),s=t.apps.find(a=>a.key===e);s&&(await this.deps.remove(s.path),t.apps=t.apps.filter(a=>a.key!==e),await this.deps.writeIndex(t))}async prune(){let e=await this.deps.readIndex(),t=[];for(let s of e.apps)if(await this.deps.sizeOf(s.path)!==void 0)t.push(s);else try{await y(s.path),t.push(s)}catch{}return t.length!==e.apps.length&&await this.deps.writeIndex({apps:t}),t}};var E=30*6e4,j=/^APP\d{6,}$/;function Y(r){return!!r&&j.test(r.trim())}function _(){return{store:new c,client:(r,e)=>new w(r,e),fetchToFile:async(r,e)=>{let t=await h(r,{method:"GET",signal:AbortSignal.timeout(E)});if(!t.ok)throw new Error(`Downloading the app failed: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("Downloading the app failed: empty response body");await F(U.fromWeb(t.body),R(e))}}}async function Z(r,e={}){let t={..._(),...e},s=r.appId.trim(),a=await t.store.find(s);if(a&&await t.store.exists(a))return r.onProgress?.(`using the copy of ${a.name} already on this machine`),await t.store.put({key:s,sourcePath:a.path,source:"cloud",name:a.name}),{path:a.path,name:a.name,fromStore:!0};r.onProgress?.(`looking up ${s}\u2026`);let o=await t.client(r.baseUrl,r.auth).details(s);if(r.accepts&&!r.accepts.some(i=>o.name.toLowerCase().endsWith(i)))throw new Error(`${o.name} cannot run on this device \u2014 expected ${r.accepts.join(" or ")}.`);r.onProgress?.(`downloading ${o.name} \u2014 this can take a while, please wait\u2026`);let p=await O(A(T(),"kane-app-dl-"));try{let i=A(p,z(o.name));await t.fetchToFile(o.url,i);let n=await t.store.put({key:s,sourcePath:i,source:"cloud",name:o.name});return r.onProgress?.(`${o.name} is ready`),{path:n.path,name:n.name,fromStore:!1,details:o}}finally{await $(p,{recursive:!0,force:!0})}}export{c as a,Y as b,Z as c};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{e as $e}from"./chunk-GPIXV7AV.js";import{a as te}from"./chunk-X74PP5NJ.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-7L25ZNNP.js";import{a as ve}from"./chunk-ARG56PJG.js";import{y as i}from"./chunk-B2ZGG7WM.js";import{b as ye}from"./chunk-DFS4RMVP.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{e as $e}from"./chunk-Z3YYMZHT.js";import{a as te}from"./chunk-5HTSKF5K.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-YGMUNNKH.js";import{a as ve}from"./chunk-XXE7W5AV.js";import{y as i}from"./chunk-HYTBEPC2.js";import{b as ye}from"./chunk-DFS4RMVP.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,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as k}from"./chunk-4BBDKWM3.js";import{a as m}from"./chunk-BPMSNGXQ.js";import{r as a}from"./chunk-RSSOJ3L2.js";import{a as y}from"./chunk-OH2NSBO6.js";import{a as h}from"./chunk-IQ7NGOAT.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-SHSXOYKT.js";import{a as m}from"./chunk-BPMSNGXQ.js";import{r as a}from"./chunk-RSSOJ3L2.js";import{a as y}from"./chunk-EPE2ELDH.js";import{a as h}from"./chunk-NWNG5UWD.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-KN5JK2U4.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-NTE4LQRN.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 V,c as H,d as W,e as ie,f as se}from"./chunk-3SPOJWRA.js";import{a as le}from"./chunk-DA57DXCF.js";import{c as te}from"./chunk-M7DN6FO3.js";import{a as oe}from"./chunk-O5AS2ZIX.js";import{a as re}from"./chunk-4BBDKWM3.js";import{b as Z}from"./chunk-WOA7VCGA.js";import{b as ee}from"./chunk-YHR2YAN5.js";import{a as I}from"./chunk-BPMSNGXQ.js";import{a as T,b as j,d as ne}from"./chunk-VE3SUJMA.js";import{b as Q}from"./chunk-TZXXJWHA.js";import{r as C}from"./chunk-RSSOJ3L2.js";import{b as Y}from"./chunk-AC7BPO4X.js";import{i as J}from"./chunk-Z7S3IWUX.js";import{a as D}from"./chunk-OH2NSBO6.js";import{a as B,e as K}from"./chunk-EYOCNMUM.js";import{a as z}from"./chunk-IQ7NGOAT.js";import{a as q}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as L,j as G}from"./chunk-C44QQJR4.js";import{a as ve}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var s=F(ve(),1);import{basename as he}from"path";var n=F(q(),1);function Ge({resultRef:x,mode:g="singleshot",loginCompleteRef:d}){let{exit:m}=G(),A=(0,s.useRef)(new z),E=(0,s.useRef)(new oe),v=(0,s.useRef)(new te),o=A.current,l=E.current,O=v.current,ae=V(),[h,f]=(0,s.useState)(g==="login"?"login":"gate"),[M,ce]=(0,s.useState)(null),[Pe,R]=(0,s.useState)(null),[we,$]=(0,s.useState)(null),[X,ue]=(0,s.useState)(null),[N,_]=(0,s.useState)([]),P=(0,s.useCallback)((e,t,i,r)=>O.log(e,t,i,r),[O]),be=(0,s.useCallback)((e,t)=>{e?T(o,l,e,t):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[o,l]),y=(0,s.useCallback)(()=>{if(g==="login")d&&(d.current=!0),m();else{let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(t.kind==="unset"||t.kind==="choose-mobile")&&Q();f(i?"target":"input")}},[g,m,d,l]),S=(0,s.useCallback)((e,t)=>{let i=T(o,l,e,t);if(g==="login"){f("ensure-project");return}ne(i)?y():i.projectId?f("ensure-folder"):f("ensure-project")},[o,l,y,g]);L((e,t)=>{t.ctrl&&e==="c"&&C(0,"Ctrl+C exit")});let U=(0,s.useRef)(!1);s.default.useEffect(()=>{U.current||(U.current=!0,g!=="login"&&se(o,P).then(e=>{ce(e),e.status==="authenticated"?S(e.result.profile,e.result.env):e.status==="needs_pick"?f("pick"):(R(e.profile??null),$(e.env??null),f("login"))}).catch(e=>{ue(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[o,P]);let fe=(0,s.useCallback)(e=>{x.current={objective:e},m()},[x,m]),de=(0,s.useCallback)(async(e,t)=>{o.setActiveProfile(e),o.setDefaultEnv(t),(await ie(o,e,t,P)).status==="authenticated"?S(e,t):(R(e),$(t),f("login"))},[o,P,S]),w=(0,s.useCallback)(()=>{let e=o.getActiveProfile(),t=o.getDefaultEnv();if(!e)return null;let i=D(t),r=o.loadBasicAuth(e,t);return new re(i.controllerBaseUrl,async()=>o.loadCredentials(e,t)?.access_token??null,r,P)},[o,P]),ge=(0,s.useCallback)(async()=>{let e=w();if(!e)return null;let t=e.cached??await e.resolve();if(!t)return null;let i=D(o.getDefaultEnv()),r=new I(i.tmsBaseUrl,t.username,t.access_key);try{let p=(await r.listProjects()).find(k=>k.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let b=await r.createProject("KaneAI Generated");return{id:b.id,name:b.name}}catch{return null}},[w,o]),pe=(0,s.useCallback)(async e=>{let t=w();if(!t)return null;let i=t.cached??await t.resolve();if(!i)return null;let r=D(o.getDefaultEnv()),a=new I(r.tmsBaseUrl,i.username,i.access_key);try{let b=(await a.listFolders(e)).find(me=>me.name==="Untitled");if(b)return{id:b.id,name:b.name};let k=await a.createFolder(e,"Untitled");return{id:k.id,name:k.name}}catch{return null}},[w,o]);if(h==="gate")return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(X)return(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"red",children:X}),(0,n.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(h==="pick"&&M?.status==="needs_pick")return(0,n.jsx)(xe,{profiles:M.profiles,onSelect:de});if(h==="login")return(0,n.jsx)(W,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:async(e,t,i,r)=>{let{validateBasicAuth:a}=await import("./validate-basic-RCBEELSB.js");await a(t,i,r),o.saveBasicAuth(e,t,{username:i,access_key:r}),o.setActiveProfile(e),o.setDefaultEnv(t)},onOAuthLogin:async(e,t)=>{let{LoginFlow:i}=await import("./login-flow-PRXFPRYZ.js");o.setDefaultEnv(t),o.setActiveProfile(e),await new i(e,t,o).login()},onComplete:(e,t)=>{R(e),$(t),o.setActiveProfile(e),o.setDefaultEnv(t),S(e,t)},onCancel:()=>{C(0,"Login cancelled")}});if(h==="ensure-project"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=()=>{if(g==="login"){f("ensure-folder");return}T(o,l,e,t).folderId?y():f("ensure-folder")};return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(Z,{resolver:w(),currentProjectId:l.load().project_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{projectId:r,projectName:a}),_(p=>[...p,`\u2713 Project: ${a} (${r})`]),i()},onCancel:async()=>{let r=await ge();r&&(j(o,l,e,t,{projectId:r.id,projectName:r.name}),_(a=>[...a,`\u2713 Default project: ${r.name} (${r.id})`]),i())}})]})}if(h==="ensure-folder"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=o.loadProfileConfig(e,t);return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(ee,{resolver:w(),projectId:i?.project_id??"",currentFolderId:l.load().folder_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{folderId:r,folderName:a}),_(p=>[...p,`\u2713 Folder: ${a} (${r})`]),y()},onCancel:async()=>{if(!i?.project_id)return;let r=await pe(i.project_id);r&&(j(o,l,e,t,{folderId:r.id,folderName:r.name}),_(a=>[...a,`\u2713 Default folder: ${r.name} (${r.id})`]),y())}})]})}if(h==="target"){let e=B(l.load().mobile?.tui_target,l.load().mobile?.default_target?.kind).kind==="choose-mobile";return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(le,{mode:e?"mobile-only":"all",onSelect:t=>{l.setMobile({tui_target:t}),f("input")},onCancel:()=>f("input")})})}if(h==="input"){let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(()=>{if(t.kind==="emulator"||t.kind==="simulator"){let r=J(e?.default_target)??"(no device)",a=e?.default_app?Y(e.default_app)?e.default_app:he(e.default_app):"(no app)";return`Config: ${K(t.kind)} \xB7 ${r} \xB7 ${a}`}return"Config: Desktop \xB7 Chrome"})();return(0,n.jsxs)(c,{flexDirection:"column",children:[N.length>0&&(0,n.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:N.map((r,a)=>(0,n.jsx)(u,{color:"green",children:r},a))}),(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"gray",children:i})}),(0,n.jsx)(H,{onSubmit:fe,onEscape:()=>C(0,"User pressed Escape"),history:ae,placeholder:"Type an objective..."})]})}return(0,n.jsx)(n.Fragment,{})}function xe({profiles:x,onSelect:g}){let[d,m]=(0,s.useState)(0),[A,E]=(0,s.useState)(!1);return L((v,o)=>{if(!A){if(o.escape){C(0,"Profile picker cancelled");return}if(o.upArrow&&d>0&&m(l=>l-1),o.downArrow&&d<x.length-1&&m(l=>l+1),o.return){E(!0);let l=x[d];g(l.profile,l.env).catch(()=>E(!1))}}}),(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,n.jsx)(c,{marginTop:1,flexDirection:"column",children:x.map((v,o)=>(0,n.jsxs)(u,{children:[o===d?"\u276F ":" ",(0,n.jsx)(u,{color:o===d?"#ff9500":"white",bold:o===d,children:v.profile}),(0,n.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),A&&(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{Ge as a};
2
+ import{b as V,c as H,d as W,e as ie,f as se}from"./chunk-AYJ2YZP5.js";import{a as le}from"./chunk-YAAQER2L.js";import{c as te}from"./chunk-JSS22MFY.js";import{a as oe}from"./chunk-MLYNVJNH.js";import{a as re}from"./chunk-SHSXOYKT.js";import{b as Z}from"./chunk-Z73ZYROU.js";import{b as ee}from"./chunk-OWGFFJKK.js";import{a as I}from"./chunk-BPMSNGXQ.js";import{a as T,b as j,d as ne}from"./chunk-VE3SUJMA.js";import{b as Q}from"./chunk-TZXXJWHA.js";import{r as C}from"./chunk-RSSOJ3L2.js";import{b as Y}from"./chunk-IAHOLH5W.js";import{i as J}from"./chunk-Z7S3IWUX.js";import{a as D}from"./chunk-EPE2ELDH.js";import{a as B,e as K}from"./chunk-EYOCNMUM.js";import{a as z}from"./chunk-NWNG5UWD.js";import{a as q}from"./chunk-HCBYKLMW.js";import{a as c,b as u,i as L,j as G}from"./chunk-C44QQJR4.js";import{a as ve}from"./chunk-6YGTRKDT.js";import{e as F}from"./chunk-UR6MHSHU.js";var s=F(ve(),1);import{basename as he}from"path";var n=F(q(),1);function Ge({resultRef:x,mode:g="singleshot",loginCompleteRef:d}){let{exit:m}=G(),A=(0,s.useRef)(new z),E=(0,s.useRef)(new oe),v=(0,s.useRef)(new te),o=A.current,l=E.current,O=v.current,ae=V(),[h,f]=(0,s.useState)(g==="login"?"login":"gate"),[M,ce]=(0,s.useState)(null),[Pe,R]=(0,s.useState)(null),[we,$]=(0,s.useState)(null),[X,ue]=(0,s.useState)(null),[N,_]=(0,s.useState)([]),P=(0,s.useCallback)((e,t,i,r)=>O.log(e,t,i,r),[O]),be=(0,s.useCallback)((e,t)=>{e?T(o,l,e,t):l.save({project_id:null,project_name:null,folder_id:null,folder_name:null})},[o,l]),y=(0,s.useCallback)(()=>{if(g==="login")d&&(d.current=!0),m();else{let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(t.kind==="unset"||t.kind==="choose-mobile")&&Q();f(i?"target":"input")}},[g,m,d,l]),S=(0,s.useCallback)((e,t)=>{let i=T(o,l,e,t);if(g==="login"){f("ensure-project");return}ne(i)?y():i.projectId?f("ensure-folder"):f("ensure-project")},[o,l,y,g]);L((e,t)=>{t.ctrl&&e==="c"&&C(0,"Ctrl+C exit")});let U=(0,s.useRef)(!1);s.default.useEffect(()=>{U.current||(U.current=!0,g!=="login"&&se(o,P).then(e=>{ce(e),e.status==="authenticated"?S(e.result.profile,e.result.env):e.status==="needs_pick"?f("pick"):(R(e.profile??null),$(e.env??null),f("login"))}).catch(e=>{ue(`Auth check failed: ${e instanceof Error?e.message:String(e)}`)}))},[o,P]);let fe=(0,s.useCallback)(e=>{x.current={objective:e},m()},[x,m]),de=(0,s.useCallback)(async(e,t)=>{o.setActiveProfile(e),o.setDefaultEnv(t),(await ie(o,e,t,P)).status==="authenticated"?S(e,t):(R(e),$(t),f("login"))},[o,P,S]),w=(0,s.useCallback)(()=>{let e=o.getActiveProfile(),t=o.getDefaultEnv();if(!e)return null;let i=D(t),r=o.loadBasicAuth(e,t);return new re(i.controllerBaseUrl,async()=>o.loadCredentials(e,t)?.access_token??null,r,P)},[o,P]),ge=(0,s.useCallback)(async()=>{let e=w();if(!e)return null;let t=e.cached??await e.resolve();if(!t)return null;let i=D(o.getDefaultEnv()),r=new I(i.tmsBaseUrl,t.username,t.access_key);try{let p=(await r.listProjects()).find(k=>k.name==="KaneAI Generated");if(p)return{id:p.project_id,name:p.name};let b=await r.createProject("KaneAI Generated");return{id:b.id,name:b.name}}catch{return null}},[w,o]),pe=(0,s.useCallback)(async e=>{let t=w();if(!t)return null;let i=t.cached??await t.resolve();if(!i)return null;let r=D(o.getDefaultEnv()),a=new I(r.tmsBaseUrl,i.username,i.access_key);try{let b=(await a.listFolders(e)).find(me=>me.name==="Untitled");if(b)return{id:b.id,name:b.name};let k=await a.createFolder(e,"Untitled");return{id:k.id,name:k.name}}catch{return null}},[w,o]);if(h==="gate")return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"yellow",children:"Checking authentication..."})});if(X)return(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"red",children:X}),(0,n.jsx)(u,{color:"gray",children:"Press Ctrl+C to exit."})]});if(h==="pick"&&M?.status==="needs_pick")return(0,n.jsx)(xe,{profiles:M.profiles,onSelect:de});if(h==="login")return(0,n.jsx)(W,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:async(e,t,i,r)=>{let{validateBasicAuth:a}=await import("./validate-basic-OKLJLDML.js");await a(t,i,r),o.saveBasicAuth(e,t,{username:i,access_key:r}),o.setActiveProfile(e),o.setDefaultEnv(t)},onOAuthLogin:async(e,t)=>{let{LoginFlow:i}=await import("./login-flow-5HL2QYEL.js");o.setDefaultEnv(t),o.setActiveProfile(e),await new i(e,t,o).login()},onComplete:(e,t)=>{R(e),$(t),o.setActiveProfile(e),o.setDefaultEnv(t),S(e,t)},onCancel:()=>{C(0,"Login cancelled")}});if(h==="ensure-project"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=()=>{if(g==="login"){f("ensure-folder");return}T(o,l,e,t).folderId?y():f("ensure-folder")};return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(Z,{resolver:w(),currentProjectId:l.load().project_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{projectId:r,projectName:a}),_(p=>[...p,`\u2713 Project: ${a} (${r})`]),i()},onCancel:async()=>{let r=await ge();r&&(j(o,l,e,t,{projectId:r.id,projectName:r.name}),_(a=>[...a,`\u2713 Default project: ${r.name} (${r.id})`]),i())}})]})}if(h==="ensure-folder"){let e=o.getActiveProfile()??"default",t=o.getDefaultEnv(),i=o.loadProfileConfig(e,t);return(0,n.jsxs)(c,{flexDirection:"column",children:[(0,n.jsx)(c,{paddingX:1,marginBottom:1,children:(0,n.jsx)(u,{color:"yellow",children:"Project & folder are required to save tests \xB7 Esc to use defaults \xB7 Ctrl+C to exit"})}),(0,n.jsx)(ee,{resolver:w(),projectId:i?.project_id??"",currentFolderId:l.load().folder_id,env:t,onSelect:(r,a)=>{j(o,l,e,t,{folderId:r,folderName:a}),_(p=>[...p,`\u2713 Folder: ${a} (${r})`]),y()},onCancel:async()=>{if(!i?.project_id)return;let r=await pe(i.project_id);r&&(j(o,l,e,t,{folderId:r.id,folderName:r.name}),_(a=>[...a,`\u2713 Default folder: ${r.name} (${r.id})`]),y())}})]})}if(h==="target"){let e=B(l.load().mobile?.tui_target,l.load().mobile?.default_target?.kind).kind==="choose-mobile";return(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(le,{mode:e?"mobile-only":"all",onSelect:t=>{l.setMobile({tui_target:t}),f("input")},onCancel:()=>f("input")})})}if(h==="input"){let e=l.load().mobile,t=B(e?.tui_target,e?.default_target?.kind),i=(()=>{if(t.kind==="emulator"||t.kind==="simulator"){let r=J(e?.default_target)??"(no device)",a=e?.default_app?Y(e.default_app)?e.default_app:he(e.default_app):"(no app)";return`Config: ${K(t.kind)} \xB7 ${r} \xB7 ${a}`}return"Config: Desktop \xB7 Chrome"})();return(0,n.jsxs)(c,{flexDirection:"column",children:[N.length>0&&(0,n.jsx)(c,{flexDirection:"column",paddingX:1,marginBottom:1,children:N.map((r,a)=>(0,n.jsx)(u,{color:"green",children:r},a))}),(0,n.jsx)(c,{paddingX:1,children:(0,n.jsx)(u,{color:"gray",children:i})}),(0,n.jsx)(H,{onSubmit:fe,onEscape:()=>C(0,"User pressed Escape"),history:ae,placeholder:"Type an objective..."})]})}return(0,n.jsx)(n.Fragment,{})}function xe({profiles:x,onSelect:g}){let[d,m]=(0,s.useState)(0),[A,E]=(0,s.useState)(!1);return L((v,o)=>{if(!A){if(o.escape){C(0,"Profile picker cancelled");return}if(o.upArrow&&d>0&&m(l=>l-1),o.downArrow&&d<x.length-1&&m(l=>l+1),o.return){E(!0);let l=x[d];g(l.profile,l.env).catch(()=>E(!1))}}}),(0,n.jsxs)(c,{flexDirection:"column",paddingX:1,children:[(0,n.jsx)(u,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,n.jsx)(c,{marginTop:1,flexDirection:"column",children:x.map((v,o)=>(0,n.jsxs)(u,{children:[o===d?"\u276F ":" ",(0,n.jsx)(u,{color:o===d?"#ff9500":"white",bold:o===d,children:v.profile}),(0,n.jsxs)(u,{color:"gray",children:[" [",v.env,"]"]})]},`${v.profile}-${v.env}`))}),A&&(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(u,{color:"yellow",children:"Validating credentials..."})})]})}export{Ge as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as R}from"./chunk-TDPWFYTJ.js";import{a as x}from"./chunk-O5AS2ZIX.js";import{d as S}from"./chunk-RQLU4NDG.js";import{a as y}from"./chunk-MMBBQ4OZ.js";import{a as p}from"./chunk-OH2NSBO6.js";import{d as g,i as E}from"./chunk-B2ZGG7WM.js";import{spawn as M,execSync as h}from"child_process";import{appendFileSync as b,existsSync as m,mkdirSync as C}from"fs";import{homedir as L}from"os";import{join as V,resolve as s,dirname as v,delimiter as T}from"path";import{fileURLToPath as U}from"url";import{createInterface as I}from"readline";async function*A(e){let n=I({input:e,crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let i=JSON.parse(o);i&&typeof i.type=="string"&&(yield i)}catch{}}}function O(e){return e==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_BIFURCATION_PHASES:"1"},unset:["V16_NETWORK_WS","V16_NETWORK_SSE"]}:{set:{V16_BIFURCATION_PHASES:"1"},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_NETWORK_WS","V16_NETWORK_SSE"]}}function w(e){return e?{set:{},unset:["V16_AGENT_SKIP_CP_FINAL"]}:{set:{V16_AGENT_SKIP_CP_FINAL:"true"},unset:[]}}function N(e){return e==="dom"?{set:{V16_AGENT_ENABLE_TEXTUAL_VISUAL:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_TEXTUAL_VISUAL"]}}var c=v(U(import.meta.url));function k(){for(let e of["python3","python"])try{return h(`${e} --version`,{stdio:"ignore"}),e}catch{}return null}function D(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",r={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"linux-arm64":["@testmuai/kane-cli-linux-arm64","@lambdatestincprivate/kane-cli-linux-arm64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},o=`${process.platform}-${process.arch}`,i=r[o];if(i)for(let t of i){let a=[s(c,"..","node_modules",t,"bin",n),s(c,"..","..","node_modules",t,"bin",n),s(c,"..","..","..","node_modules",t,"bin",n),s(c,"..","..","..","..","node_modules",t,"bin",n)];for(let u of a)if(m(u))return{cmd:u,args:[]}}let d=[s(c,"bin",n),s(c,"..","bin",n),s(c,"..","..","..","..","v16-runner","dist",n),s(c,"..","..","..","v16-runner","dist",n),s(c,"..","..","v16-runner","dist",n),s(process.cwd(),"v16-runner","dist",n),s(process.cwd(),"..","v16-runner","dist",n)];for(let t of d)if(m(t))return{cmd:t,args:[]};let l=[s(c,"..","..","v16-runner"),s(c,"..","..","..","..","v16-runner"),s(c,"..","..","..","v16-runner"),s(process.cwd(),"v16-runner"),s(process.cwd(),"..","v16-runner")];for(let t of l)if(m(s(t,"main.py"))){for(let u of[s(t,".venv","bin","python"),s(t,"..",".venv","bin","python"),s(t,"..","browser-agent",".venv","bin","python")])if(m(u))return{cmd:u,args:["main.py"],cwd:t};let a=k();if(a)return{cmd:a,args:["main.py"],cwd:t}}return null}function P(e){return e?V(L(),".testmuai","kaneai","sessions",e,"runner-stderr.log"):null}function K(e){let n=M(e.runner.cmd,e.runner.args,{stdio:["pipe","pipe","pipe"],env:e.env,cwd:e.runner.cwd});n.stdin.on("error",()=>{});let r=P(e.sessionId);if(r)try{C(v(r),{recursive:!0})}catch{}let o=1e5,i="";n.stderr.on("data",u=>{if(i+=u.toString(),i.length>o&&(i=i.slice(-o)),r)try{b(r,u)}catch{}}),n.on("error",u=>{e.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:u.message})});let d=null,l=null,t=new Promise(u=>{n.on("close",(f,_)=>{d=f,l=_?String(_):null,e.log?.("info","RUNNER_EXIT","Runner exited",{code:f,signal:l??"none"}),u({code:f,signal:l})})}),a=A(n.stdout);return{child:n,events:a,getStderr:()=>i,getExitCode:()=>d,getExitSignal:()=>l,exited:t}}async function B(e,n){if(!n?.platform||!n.target_kind)return;let r=await S(n.platform)?.toolEnv(n.target_kind)??{dirs:[]};if(r.dirs.length>0&&(e.PATH=[...r.dirs,e.PATH??""].filter(Boolean).join(T)),r.appiumHome&&(e.APPIUM_HOME=r.appiumHome),r.wdaRoot&&(e.TESTMU_IOS_WDA_DERIVED_DATA=r.wdaRoot),n.platform==="android"){let o=y();o&&(e.PATH=[o.platformToolsDir,e.PATH??""].filter(Boolean).join(T),e.ANDROID_HOME=o.root,e.ANDROID_SDK_ROOT=o.root)}}function H(e){let n={...process.env};e.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8",n.PYTHONUTF8="1");let r=p(e.environment);n.V16_SERVER_API_HOST=r.v16ServerHost,n.ATMS_URL=r.tmsBaseUrl.replace(/\/api\/?$/,""),e.username&&e.accessKey&&(n.LT_USERNAME=e.username,n.LT_ACCESS_KEY=e.accessKey),e.sessionId&&(n.TESTMUAI_SESSION_ID=e.sessionId);let o=O(e.mode??"testing");Object.assign(n,o.set);for(let a of o.unset)delete n[a];let i=new x().load(),d=N(e.assertionMode??(i.assertion_mode==="visual"?"visual":"dom"));Object.assign(n,d.set);for(let a of d.unset)delete n[a];let l=e.finalValidation??i.final_validation,t=w(l);Object.assign(n,t.set);for(let a of t.unset)delete n[a];return n}function G(e,n){let r=p(n?.environment),o=R();o!==void 0&&e.ap_mode===void 0&&(e.ap_mode=o),e.telemetry_proxy_url===void 0&&process.env.KANE_TELEMETRY!=="0"&&(e.telemetry_proxy_url=E),e.media_upload===void 0&&e.org_id&&e.username&&e.access_key&&(e.media_upload={url:r.shareApiBaseUrl.replace(/\/$/,"")+"/mfs/v1.0/media/upload",artefacts_host:r.mediaArtefactsHost,org_id:e.org_id,media_dir:g})}async function oe(e,n){let r=D();if(!r)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");process.env.KANE_SPAWN_DEBUG&&process.stderr.write(`[spawn-debug] ${JSON.stringify(r)}
2
+ import{a as R}from"./chunk-TDPWFYTJ.js";import{a as x}from"./chunk-MLYNVJNH.js";import{d as S}from"./chunk-A557OSRS.js";import{a as y}from"./chunk-MMBBQ4OZ.js";import{a as p}from"./chunk-EPE2ELDH.js";import{d as g,i as E}from"./chunk-HYTBEPC2.js";import{spawn as M,execSync as h}from"child_process";import{appendFileSync as b,existsSync as m,mkdirSync as C}from"fs";import{homedir as L}from"os";import{join as V,resolve as s,dirname as v,delimiter as T}from"path";import{fileURLToPath as U}from"url";import{createInterface as I}from"readline";async function*A(e){let n=I({input:e,crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let i=JSON.parse(o);i&&typeof i.type=="string"&&(yield i)}catch{}}}function O(e){return e==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_BIFURCATION_PHASES:"1"},unset:["V16_NETWORK_WS","V16_NETWORK_SSE"]}:{set:{V16_BIFURCATION_PHASES:"1"},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_NETWORK_WS","V16_NETWORK_SSE"]}}function w(e){return e?{set:{},unset:["V16_AGENT_SKIP_CP_FINAL"]}:{set:{V16_AGENT_SKIP_CP_FINAL:"true"},unset:[]}}function N(e){return e==="dom"?{set:{V16_AGENT_ENABLE_TEXTUAL_VISUAL:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_TEXTUAL_VISUAL"]}}var c=v(U(import.meta.url));function k(){for(let e of["python3","python"])try{return h(`${e} --version`,{stdio:"ignore"}),e}catch{}return null}function D(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",r={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"linux-arm64":["@testmuai/kane-cli-linux-arm64","@lambdatestincprivate/kane-cli-linux-arm64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},o=`${process.platform}-${process.arch}`,i=r[o];if(i)for(let t of i){let a=[s(c,"..","node_modules",t,"bin",n),s(c,"..","..","node_modules",t,"bin",n),s(c,"..","..","..","node_modules",t,"bin",n),s(c,"..","..","..","..","node_modules",t,"bin",n)];for(let u of a)if(m(u))return{cmd:u,args:[]}}let d=[s(c,"bin",n),s(c,"..","bin",n),s(c,"..","..","..","..","v16-runner","dist",n),s(c,"..","..","..","v16-runner","dist",n),s(c,"..","..","v16-runner","dist",n),s(process.cwd(),"v16-runner","dist",n),s(process.cwd(),"..","v16-runner","dist",n)];for(let t of d)if(m(t))return{cmd:t,args:[]};let l=[s(c,"..","..","v16-runner"),s(c,"..","..","..","..","v16-runner"),s(c,"..","..","..","v16-runner"),s(process.cwd(),"v16-runner"),s(process.cwd(),"..","v16-runner")];for(let t of l)if(m(s(t,"main.py"))){for(let u of[s(t,".venv","bin","python"),s(t,"..",".venv","bin","python"),s(t,"..","browser-agent",".venv","bin","python")])if(m(u))return{cmd:u,args:["main.py"],cwd:t};let a=k();if(a)return{cmd:a,args:["main.py"],cwd:t}}return null}function P(e){return e?V(L(),".testmuai","kaneai","sessions",e,"runner-stderr.log"):null}function K(e){let n=M(e.runner.cmd,e.runner.args,{stdio:["pipe","pipe","pipe"],env:e.env,cwd:e.runner.cwd});n.stdin.on("error",()=>{});let r=P(e.sessionId);if(r)try{C(v(r),{recursive:!0})}catch{}let o=1e5,i="";n.stderr.on("data",u=>{if(i+=u.toString(),i.length>o&&(i=i.slice(-o)),r)try{b(r,u)}catch{}}),n.on("error",u=>{e.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:u.message})});let d=null,l=null,t=new Promise(u=>{n.on("close",(f,_)=>{d=f,l=_?String(_):null,e.log?.("info","RUNNER_EXIT","Runner exited",{code:f,signal:l??"none"}),u({code:f,signal:l})})}),a=A(n.stdout);return{child:n,events:a,getStderr:()=>i,getExitCode:()=>d,getExitSignal:()=>l,exited:t}}async function B(e,n){if(!n?.platform||!n.target_kind)return;let r=await S(n.platform)?.toolEnv(n.target_kind)??{dirs:[]};if(r.dirs.length>0&&(e.PATH=[...r.dirs,e.PATH??""].filter(Boolean).join(T)),r.appiumHome&&(e.APPIUM_HOME=r.appiumHome),r.wdaRoot&&(e.TESTMU_IOS_WDA_DERIVED_DATA=r.wdaRoot),n.platform==="android"){let o=y();o&&(e.PATH=[o.platformToolsDir,e.PATH??""].filter(Boolean).join(T),e.ANDROID_HOME=o.root,e.ANDROID_SDK_ROOT=o.root)}}function H(e){let n={...process.env};e.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8",n.PYTHONUTF8="1");let r=p(e.environment);n.V16_SERVER_API_HOST=r.v16ServerHost,n.ATMS_URL=r.tmsBaseUrl.replace(/\/api\/?$/,""),e.username&&e.accessKey&&(n.LT_USERNAME=e.username,n.LT_ACCESS_KEY=e.accessKey),e.sessionId&&(n.TESTMUAI_SESSION_ID=e.sessionId);let o=O(e.mode??"testing");Object.assign(n,o.set);for(let a of o.unset)delete n[a];let i=new x().load(),d=N(e.assertionMode??(i.assertion_mode==="visual"?"visual":"dom"));Object.assign(n,d.set);for(let a of d.unset)delete n[a];let l=e.finalValidation??i.final_validation,t=w(l);Object.assign(n,t.set);for(let a of t.unset)delete n[a];return n}function G(e,n){let r=p(n?.environment),o=R();o!==void 0&&e.ap_mode===void 0&&(e.ap_mode=o),e.telemetry_proxy_url===void 0&&process.env.KANE_TELEMETRY!=="0"&&(e.telemetry_proxy_url=E),e.media_upload===void 0&&e.org_id&&e.username&&e.access_key&&(e.media_upload={url:r.shareApiBaseUrl.replace(/\/$/,"")+"/mfs/v1.0/media/upload",artefacts_host:r.mediaArtefactsHost,org_id:e.org_id,media_dir:g})}async function oe(e,n){let r=D();if(!r)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");process.env.KANE_SPAWN_DEBUG&&process.stderr.write(`[spawn-debug] ${JSON.stringify(r)}
3
3
  `);let o=H({environment:n?.environment,mode:n?.mode,assertionMode:n?.assertionMode,finalValidation:n?.finalValidation,username:e.username,accessKey:e.access_key,sessionId:e.session_id});e.device?.platform&&await B(o,e.device),G(e,{environment:n?.environment});let i=K({env:o,runner:r,log:n?.log,sessionId:e.session_id}),d=i.child;d.stdin.write(JSON.stringify(e)+`
4
4
  `);let l=P(e.session_id);if(l)try{C(v(l),{recursive:!0}),b(l,`--- runner spawn ${new Date().toISOString()} run_index=${e.run_index} ---
5
5
  `)}catch{}return{child:d,events:i.events,sendUserResponse(t){let a=JSON.stringify({type:"user_response",answer:t});try{d.stdin.write(a+`
@@ -0,0 +1,15 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as R,c as S}from"./chunk-CAOZKSQ3.js";import{dirname as W,basename as N,join as d}from"path";function G(t){let e=N(t);return e.endsWith("_test.md")?e.slice(0,-8):e.endsWith("_module.md")?e.slice(0,-10):e.endsWith(".md")?e.slice(0,-3):e}function f(t){return d(W(t),`output-${G(t)}`)}function rt(t){return d(f(t),"Result.md")}function _(t){return d(f(t),".internal")}function w(t){return d(_(t),"meta.json")}function ot(t){return d(_(t),"execution.json")}function st(t,e,n){return d(f(t),`${e}-${n}-code`)}function dt(t){return d(f(t),"generated-code")}function at(t){return f(t)+".staging"}function J(t){return d(_(t),"steps")}function ct(t,e,n){return d(J(t),`${e}-${n}`)}import{writeFileSync as L,mkdirSync as H,readFileSync as U}from"fs";import{dirname as k}from"path";function j(t){try{return JSON.parse(U(w(t),"utf8"))}catch{return null}}function ft(t){let e=w(t.sourcePath);try{H(k(e),{recursive:!0})}catch(r){return process.stderr.write(`
3
+ \u26A0 Failed to create output directory.
4
+ ${r.message}
5
+ Path: ${k(e)}
6
+
7
+ `),e}let n={commit_id:t.commitId};t.testId!==void 0&&(n.test_id=t.testId),t.testcaseId!==void 0&&(n.testcase_id=t.testcaseId),t.projectId!==void 0&&(n.project_id=t.projectId),t.folderId!==void 0&&(n.folder_id=t.folderId),t.orgId!==void 0&&(n.org_id=t.orgId),t.sessionName!==void 0&&(n.session_name=t.sessionName),t.plan!==void 0&&(n.plan=t.plan),t.media&&Object.keys(t.media).length>0&&(n.media=t.media);try{L(e,JSON.stringify(n,null,2)+`
8
+ `,"utf8")}catch(r){process.stderr.write(`
9
+ \u26A0 Failed to write meta.json.
10
+ ${r.message}
11
+ Path: ${e}
12
+
13
+ `)}return e}import{readFileSync as z,existsSync as q}from"fs";import{basename as C,dirname as B,isAbsolute as Q,resolve as F}from"path";import{createHash as O}from"crypto";function h(t){if(t==null)return null;if(Array.isArray(t))return t.map(h);if(typeof t=="object"){let e={};for(let n of Object.keys(t).sort()){let r=t[n];r!==void 0&&(e[n]=h(r))}return e}return t}function Y(t){if(t.body.kind!=="objective")throw new Error("stepMd5: only objective steps have an md5; @import rows do not");let e={...t.config??{},optional:t.optional??!1},n=JSON.stringify(h(e));return O("md5").update(t.body.text).update(`
14
+ `).update(n).digest("hex")}function I(t){let e={};for(let[r,o]of Object.entries(t.bindings??{}))e[r]={value:o.value,...o.secret===!0?{secret:!0}:{},...o.syntax?{syntax:o.syntax}:{}};let n=JSON.stringify(h({bindings:e,optional:t.optional}));return O("md5").update(t.path).update(`
15
+ `).update(n).digest("hex")}function bt(t){return Y({index:t.trace[t.trace.length-1].stepIndex,heading:t.trace[t.trace.length-1].heading,verifies:[],body:{kind:"objective",text:t.objective},config:t.parsedConfig,headingLine:1,optional:t.optional})}var T=["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"],X=["app","no_reset","os_version","device_name"],Z=["mode","on_lock_conflict","tags","dataset","target","chrome_profile","cdp_endpoint","ws_endpoint","headless","app","no_reset","os_version","device_name"],g=class extends Error{constructor(e){super(e),this.name="TestMdResolveError"}};function v(t){let e=C(t);return e.endsWith("_test.md")?"test":e.endsWith("_module.md")?"module":"helper"}function Rt(t){let e=F(t),n=E(e),r=tt(n.global),o=[],a=[],s=[{file:e,kind:v(e)}],c=[];return $(n,a,o,[],e,{},s,c,{}),o.forEach((u,b)=>u.flatIndex=b+1),{rootPath:e,rootTitle:n.title,rootGlobal:n.global,rootSteps:n.steps,chrome:r,steps:o,unitFiles:s,warnings:c}}function St(t){let e=[];for(let n of t.unitFiles){if(n.kind!=="test")continue;let r=j(n.file);r&&e.push({file:n.file,...r.project_id?{project_id:String(r.project_id)}:{},...r.org_id?{org_id:String(r.org_id)}:{}})}return e}function E(t){if(!q(t))throw new g(`@import path not found: ${t}`);let e=z(t,"utf8");return R(t,e)}function $(t,e,n,r,o,a,s,c,p){if(e.includes(t.path)){let i=[...e,t.path].map(l=>C(l)).join(" \u2192 ");throw new g(`cyclic reference: ${i}`)}e.push(t.path);let u=r.length===0,b=t.global.variables??{};for(let i of Object.keys(a))if(Object.hasOwn(b,i))throw new g(`callsite binding '${i}' collides with a declared variable in ${t.path} (frontmatter variables are pinned; parameters are its undeclared names)`);let x=t.global;if(!u){let i={...t.global};for(let l of Z)i[l]!==void 0&&(c.push(`${t.path}: '${l}' is root-governed on imported units \u2014 ignored`),delete i[l]);i.url!==void 0&&(p.pending=String(i.url),delete i.url),x=i}let P=new Map;for(let i of t.steps){let l=i.body.kind!=="objective";if(i.optional&&l&&!u)throw new g(`intermediate-ref 'optional' is not supported in v1: ${t.path}:${i.headingLine}`);if(i.body.kind==="objective"){let y={file:t.path,stepIndex:i.index,heading:i.heading,optional:i.optional??!1},K=et(x,i.config,a),M={flatIndex:0,objective:i.body.text,sourceFile:t.path,trace:[...r,y],config:K,parsedConfig:i.config,optional:i.optional??!1,verifies:i.verifies,owningFile:t.path,unitKind:v(t.path),...i.replayOnly?{replayOnly:i.replayOnly}:{},...i.controlFlow?{controlFlow:i.controlFlow}:{},...i.block?{block:{...i.block,id:nt(i,n.length+1,P)}}:{}};p.pending&&(M.unitEntryUrl=p.pending,p.pending=void 0),n.push(M);continue}let V={file:t.path,stepIndex:i.index,heading:i.heading,optional:i.optional??!1,rowMd5:I({path:i.body.path,bindings:i.body.bindings,optional:i.optional??!1})},A=B(t.path),m=Q(i.body.path)?i.body.path:F(A,i.body.path),D=E(m);s.some(y=>y.file===m)||s.push({file:m,kind:v(m)}),$(D,e,n,[...r,V],o,i.body.bindings??{},s,c,p)}u||(p.pending=void 0),e.pop()}function tt(t){let e={};for(let n of T){if(n==="target"){let r=S(t);r!==void 0&&(e.target=r);continue}t[n]!==void 0&&(e[n]=t[n])}return e}function et(t,e,n){let r={};for(let[s,c]of Object.entries(t))T.includes(s)||X.includes(s)||(r[s]=c);let o={...r,...e??{}},a={...n,...t.variables??{},...e?.variables??{}};return Object.keys(a).length>0?o.variables=a:delete o.variables,o}function nt(t,e,n){let r=t.block.id;if(t.controlFlow==="if"||t.controlFlow==="while")return n.set(r,e),e;let o=n.get(r);if(o===void 0)throw new g(`block member before its opener in ${t.heading}`);return o}export{G as a,f as b,rt as c,_ as d,w as e,ot as f,st as g,dt as h,at as i,J as j,ct as k,I as l,bt as m,j as n,ft as o,g as p,v as q,Rt as r,St as s};
@@ -1,17 +1,17 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as m}from"./chunk-VZ7KXRXB.js";import{a as _}from"./chunk-TDPWFYTJ.js";import{b as h}from"./chunk-B2ZGG7WM.js";import{randomUUID as O}from"crypto";import{mkdirSync as D,writeFileSync as b,appendFileSync as A,existsSync as R}from"fs";import{join as u}from"path";import{writeFileSync as I,mkdirSync as j,existsSync as L}from"fs";import{join as p,relative as $}from"path";function f(n){let t=Object.keys(n.frontmatter).length>0?m(n.frontmatter).trimEnd():"",s=["---"];return t&&s.push(t),s.push("---",""),s.push(`# ${n.heading}`,""),n.steps.forEach((i,r)=>{s.push(`## Step ${r+1}`,i,"")}),s.join(`
3
- `)}function v(n,e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.replace(new RegExp(`\\{\\{\\s*${s}(?=\\s*\\}\\}|[.\\[])`,"g"),`{{${t}.${e}`)}function U(n,e){let t={},s={},i=e;for(let[r,l]of Object.entries(n)){if(r.startsWith("global.")||r.startsWith("secrets.user.")||r.startsWith("environment.")){let o=r.startsWith("secrets.user.");t[r]={value:l.value,secret:o,syntax:`{{${r}}}`,type:o?"secret":r.startsWith("environment.")?"environment":"global"},s[r]=r;continue}if(l.secret){let o=`secrets.user.${r}`;t[o]={value:l.value,secret:!0,syntax:`{{secrets.user.${r}}}`,type:"secret"},s[r]=o,i=v(i,r,"secrets.user")}else{let o=`global.${r}`;t[o]={value:l.value,secret:!1,syntax:`{{global.${r}}}`,type:"global"},s[r]=o,i=v(i,r,"global")}}return{variables:t,objective:i,keyMap:s}}var x=/\{\{\s*(?:global|secrets\.user|environment)\.([^{}]+?)\s*\}\}/g;function c(n){return typeof n!="string"||!n.includes("{{")?n:n.replace(x,"{{$1}}")}function d(n){if(typeof n=="string")return c(n);if(Array.isArray(n))return n.map(e=>d(e));if(n&&typeof n=="object"){let e={};for(let[t,s]of Object.entries(n))e[t]=d(s);return e}return n}var N=new Set(["username","access_key","oauth","profile","project_id","folder_id"]),E=new Set(["model","env"]),g=class{constructor(e){this.opts=e}objectives=[];flushed=!1;lastWrittenPath=null;lastCollisionSuffixed=!1;appendObjective(e){this.objectives.push(e)}flush(){if(this.flushed||(this.flushed=!0,this.objectives.length===0))return;let e=this.opts.getName();if(!e)return;let t=p(this.opts.cwd,".testmuai","tests");try{j(t,{recursive:!0})}catch(a){process.stderr.write(`
4
- \u26A0 Failed to create ${$(this.opts.cwd,t)}/
2
+ import{a as _}from"./chunk-27ERHOW3.js";import{c as m}from"./chunk-VZ7KXRXB.js";import{a as f}from"./chunk-TDPWFYTJ.js";import{b as h}from"./chunk-HYTBEPC2.js";import{randomUUID as A}from"crypto";import{mkdirSync as k,writeFileSync as R,appendFileSync as C,existsSync as S}from"fs";import{join as u}from"path";import{writeFileSync as L,mkdirSync as $,existsSync as E}from"fs";import{join as p,relative as N}from"path";function v(n){let t=Object.keys(n.frontmatter).length>0?m(n.frontmatter).trimEnd():"",s=["---"];return t&&s.push(t),s.push("---",""),s.push(`# ${n.heading}`,""),n.steps.forEach((i,r)=>{s.push(`## Step ${r+1}`,i,"")}),s.join(`
3
+ `)}function I(n,e){let t=e.syntax?.trim()??"";return t.startsWith("${")&&t.endsWith("}")?t:"${"+n+"}"}function b(n,e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return n.replace(new RegExp(`\\{\\{\\s*${s}(?=\\s*\\}\\}|[.\\[])`,"g"),`{{${t}.${e}`)}function P(n,e){let t={},s={},i=e;for(let[r,l]of Object.entries(n)){if(_(l)){t[r]={value:l.value,secret:!!l.secret,syntax:I(r,l),type:"parameter"},s[r]=r;continue}if(r.startsWith("global.")||r.startsWith("secrets.user.")||r.startsWith("environment.")){let o=r.startsWith("secrets.user.");t[r]={value:l.value,secret:o,syntax:`{{${r}}}`,type:o?"secret":r.startsWith("environment.")?"environment":"global"},s[r]=r;continue}if(l.secret){let o=`secrets.user.${r}`;t[o]={value:l.value,secret:!0,syntax:`{{secrets.user.${r}}}`,type:"secret"},s[r]=o,i=b(i,r,"secrets.user")}else{let o=`global.${r}`;t[o]={value:l.value,secret:!1,syntax:`{{global.${r}}}`,type:"global"},s[r]=o,i=b(i,r,"global")}}return{variables:t,objective:i,keyMap:s}}var j=/\{\{\s*(?:global|secrets\.user|environment)\.([^{}]+?)\s*\}\}/g;function c(n){return typeof n!="string"||!n.includes("{{")?n:n.replace(j,"{{$1}}")}function d(n){if(typeof n=="string")return c(n);if(Array.isArray(n))return n.map(e=>d(e));if(n&&typeof n=="object"){let e={};for(let[t,s]of Object.entries(n))e[t]=d(s);return e}return n}var F=new Set(["username","access_key","oauth","profile","project_id","folder_id"]),O=new Set(["model","env"]),g=class{constructor(e){this.opts=e}objectives=[];flushed=!1;lastWrittenPath=null;lastCollisionSuffixed=!1;appendObjective(e){this.objectives.push(e)}flush(){if(this.flushed||(this.flushed=!0,this.objectives.length===0))return;let e=this.opts.getName();if(!e)return;let t=p(this.opts.cwd,".testmuai","tests");try{$(t,{recursive:!0})}catch(a){process.stderr.write(`
4
+ \u26A0 Failed to create ${N(this.opts.cwd,t)}/
5
5
  ${a.message}
6
6
  Your test recording was NOT saved.
7
7
 
8
- `);return}let s=p(t,`${e}_test.md`),i=2,r=!1;for(;L(s);)s=p(t,`${e}-${i}_test.md`),i++,r=!0;let l=d(F(this.opts.getResolvedGlobal())),o=f({frontmatter:l,heading:`Session: ${e}`,steps:this.objectives.map(c)});try{I(s,o,"utf8")}catch(a){process.stderr.write(`
8
+ `);return}let s=p(t,`${e}_test.md`),i=2,r=!1;for(;E(s);)s=p(t,`${e}-${i}_test.md`),i++,r=!0;let l=d(D(this.opts.getResolvedGlobal())),o=v({frontmatter:l,heading:`Session: ${e}`,steps:this.objectives.map(c)});try{L(s,o,"utf8")}catch(a){process.stderr.write(`
9
9
  \u26A0 Failed to save your test recording.
10
10
  ${a.message}
11
11
  Path: ${s}
12
12
 
13
- `);return}this.lastWrittenPath=s,this.lastCollisionSuffixed=r}};function F(n){let e={};for(let[t,s]of Object.entries(n))N.has(t)||E.has(t)||(e[t]=s);return e}var k=u(h,"sessions"),S=class{sessionId;sessionDir;runs=[];_flows=[];_nextIndex=0;_started=!1;_testId=null;_testcaseId=null;_projectId=null;_orgId=null;_userName=null;_userEmail=null;_uploadStatus="pending";_uploadAttempts=0;_uploadError=null;_firstObjective=null;_firstUrl=null;_auteurVariables={};_screenshotSas=null;_model="";_environment="";_profile=null;_plan=null;_startedAt="";_remoteLogger=null;_earlyLogBuffer=[];_recorder=null;_resolvedGlobal={};_sessionName=null;_recordingEnabled=!0;_stepRunRecords=[];constructor(e){this.sessionId=O();let t=e?.baseDir?u(e.baseDir,"sessions"):k;this.sessionDir=u(t,this.sessionId)}setResolvedGlobal(e){this._resolvedGlobal={...this._resolvedGlobal,...e}}setSessionName(e){this._sessionName=e}get sessionName(){return this._sessionName}setRecordingEnabled(e){this._recordingEnabled=e}get recorder(){return this._recorder}flushRecorder(){try{this._recorder?.flush()}catch(e){process.stderr.write(`[recorder] flush failed: ${e.message}
14
- `)}}start(e){if(!this._started){this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString();try{D(this.sessionDir,{recursive:!0}),this._recorder=new g({cwd:process.cwd(),getResolvedGlobal:()=>this._resolvedGlobal,getName:()=>this._sessionName});let t={session_id:this.sessionId,started_at:this._startedAt,model:e.model,environment:e.environment,profile:e.profile,plan:this._plan,objectives:[],runs:[],status:"in_progress"};b(u(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
15
- `)}catch{}this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`),this._earlyLogBuffer.push({level:"info",event:"SESSION_START",message:"Session started",context:{session_id:this.sessionId}},{level:"info",event:"CONFIG",message:"Session config",context:{model:e.model,environment:e.environment,profile:e.profile}})}}setPlan(e){this._plan=e;let t={level:"info",event:"SESSION_INFO",message:"Session info",context:{session_id:this.sessionId,plan:e??null}};this._remoteLogger?this._remoteLogger.log(t.level,t.event,t.message,t.context):this._earlyLogBuffer.push(t)}get plan(){return this._plan}get apMode(){return _()??"v2"}setRemoteLogger(e){this._remoteLogger=e;for(let t of this._earlyLogBuffer)e.log(t.level,t.event,t.message,t.context);this._earlyLogBuffer=[]}get hasRemoteLogger(){return this._remoteLogger!==null}setAuteurVariables(e){Object.assign(this._auteurVariables,e)}get auteurVariables(){return this._auteurVariables}setScreenshotSas(e){this._screenshotSas=e}get screenshotSas(){return this._screenshotSas}get screenshotBaseUrl(){return this._screenshotSas?`${this._screenshotSas.base_url}/${this._screenshotSas.container}`:""}get startedAt(){return this._startedAt||new Date().toISOString()}log(e,t,s,i){if(t===void 0){this._log(e);let o=e.indexOf(" "),a=o>0?e.slice(0,o):e,y=o>0?e.slice(o+1):"",w=/fail|error/i.test(e)?"error":"info";this._remoteLogger?.log(w,a,y||e);return}let r=e,l=s;this._log(`${t} ${l}`,i),this._remoteLogger?.log(r,t,l,i)}logStep(e,t,s){this._log(`${e} ${t}`,s);let i=this._nextIndex>0?this._nextIndex-1:0;this._remoteLogger?.logStep(i,e,t,s)}logCommand(e){this._log(`COMMAND ${e}`)}logRunStart(e,t,s){this._log(`RUN ${e} START objective="${t.slice(0,100)}" url=${s}`),this._remoteLogger?.setRunIndex(e),this._remoteLogger?.log("info","RUN_START",`Run ${e} started`,{run_index:e,objective:t,url:s})}logRunEnd(e,t,s,i,r){let l=(s??0).toFixed(1),o=(i??"").slice(0,100),a=r==null||r===""||Number.isNaN(Number(r))?null:Number(r);this._log(`RUN ${e} END status=${t} duration=${l}s summary="${o}"`,a!=null?{result_code:a}:void 0),this._remoteLogger?.log("info","RUN_END",`Run ${e} ended`,{run_index:e,status:t,duration:s??0,summary:i??"",result_code:a}),t!=="failed"&&t!=="error"&&this._remoteLogger?.discardSteps(e)}escalateRun(e){this._remoteLogger?.escalate(e)}logChromeLaunch(e,t){this._log(`CHROME LAUNCH port=${e} endpoint=${t}`),this._remoteLogger?.log("info","CHROME_LAUNCH","Chrome launched",{port:e,cdp_endpoint:t})}async finish(e="complete"){this._log(`SESSION END status=${e} total_runs=${this.runs.length}`),this._remoteLogger?.log("info","SESSION_END","Session ended",{status:e,total_runs:this.runs.length}),await this._remoteLogger?.shutdown();let t={session_id:this.sessionId,started_at:this._startedAt,ended_at:new Date().toISOString(),model:this._model,environment:this._environment,profile:this._profile,plan:this._plan,status:e,total_runs:this.runs.length,test_id:this._testId,testcase_id:this._testcaseId,commit_id:this.sessionId,project_id:this._projectId,upload_status:this._uploadStatus,upload_attempts:this._uploadAttempts,last_upload_attempt:this._uploadAttempts>0?new Date().toISOString():null,upload_error:this._uploadError,runs:this.runs.map(s=>({index:s.index,objective:s.objective,status:s.status,summary:s.summary,run_dir:s.run_dir}))};R(this.sessionDir)&&b(u(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
16
- `),this.flushRecorder(),this._recorder=null}nextRunIndex(){return this._nextIndex}addRunResult(e,t){this.runs.push(e),this._nextIndex+=t??1,this._recordingEnabled&&this._recorder?.appendObjective(e.objective)}getContext(){return{prior_runs:this.runs.map(e=>({index:e.index,objective:e.objective,summary:e.summary,status:e.status,memory:e.context.memory,variables:e.context.variables,pointer:e.context.pointer}))}}addFlow(e){let t={...e,index:this._flows.length+1};return this._flows.push(t),t}getFlows(){return[...this._flows]}getFlow(e){return this._flows.find(t=>t.index===e)}clearFlows(){this._flows=[]}recordStepRun(e){this._stepRunRecords.push(e)}getStepRunRecords(){return[...this._stepRunRecords]}getRunsAsStepRecords(){return this.runs.map((e,t)=>({testmdStepIndex:t+1,runIndex:e.index,totalRunDirs:e.run_dirs?.length??1}))}snapshot(){return{runsLen:this.runs.length,nextRunIndex:this._nextIndex,stepRunRecordsLen:this._stepRunRecords.length}}rollback(e){this.runs.length=e.runsLen,this._nextIndex=e.nextRunIndex,this._stepRunRecords.length=e.stepRunRecordsLen}setTestId(e){this._testId=e}get testId(){return this._testId}setTestcaseId(e){this._testcaseId=e}get testcaseId(){return this._testcaseId}setProjectId(e){this._projectId=e}setOrgId(e){this._orgId=e}get orgId(){return this._orgId}setUserIdentity(e,t){e&&(this._userName=e),t&&(this._userEmail=t)}get userName(){return this._userName}get userEmail(){return this._userEmail}setFirstRun(e,t){this._firstObjective||(this._firstObjective=e,this._firstUrl=t)}get firstObjective(){return this._firstObjective}get firstUrl(){return this._firstUrl}getRunDirs(){let e=[];for(let t of this.runs)t.run_dirs&&t.run_dirs.length>0?e.push(...t.run_dirs):t.run_dir&&e.push(t.run_dir);return e}getRunObjectives(){let e=[];for(let t of this.runs)t.flow_objectives&&t.flow_objectives.length>0?e.push(...t.flow_objectives):e.push(t.objective);return e}getRunMetadata(){let e=[];for(let t of this.runs)if(t.perFlowMetadata&&t.perFlowMetadata.length>0)e.push(...t.perFlowMetadata);else{let s={resultCode:t.resultCode,reasonCode:t.reasonCode,errorMessage:t.status==="failed"?t.summary??null:null,summary:t.summary,oneLiner:t.oneLiner},i=t.run_dirs?.length??1;for(let r=0;r<i;r++)e.push(s)}return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e,t){if(!(!this._started||!R(this.sessionDir)))try{let s=new Date().toISOString().slice(0,19).replace("T"," "),i=u(this.sessionDir,"tui.log"),r=t&&Object.keys(t).length>0?` ${JSON.stringify(t)}`:"";A(i,`[${s}] ${e}${r}
17
- `)}catch{}}};export{f as a,U as b,S as c};
13
+ `);return}this.lastWrittenPath=s,this.lastCollisionSuffixed=r}};function D(n){let e={};for(let[t,s]of Object.entries(n))F.has(t)||O.has(t)||(e[t]=s);return e}var T=u(h,"sessions"),y=class{sessionId;sessionDir;runs=[];_flows=[];_nextIndex=0;_started=!1;_testId=null;_testcaseId=null;_projectId=null;_orgId=null;_userName=null;_userEmail=null;_uploadStatus="pending";_uploadAttempts=0;_uploadError=null;_firstObjective=null;_firstUrl=null;_auteurVariables={};_screenshotSas=null;_model="";_environment="";_profile=null;_plan=null;_startedAt="";_remoteLogger=null;_earlyLogBuffer=[];_recorder=null;_resolvedGlobal={};_sessionName=null;_recordingEnabled=!0;_stepRunRecords=[];constructor(e){this.sessionId=A();let t=e?.baseDir?u(e.baseDir,"sessions"):T;this.sessionDir=u(t,this.sessionId)}setResolvedGlobal(e){this._resolvedGlobal={...this._resolvedGlobal,...e}}setSessionName(e){this._sessionName=e}get sessionName(){return this._sessionName}setRecordingEnabled(e){this._recordingEnabled=e}get recorder(){return this._recorder}flushRecorder(){try{this._recorder?.flush()}catch(e){process.stderr.write(`[recorder] flush failed: ${e.message}
14
+ `)}}start(e){if(!this._started){this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString();try{k(this.sessionDir,{recursive:!0}),this._recorder=new g({cwd:process.cwd(),getResolvedGlobal:()=>this._resolvedGlobal,getName:()=>this._sessionName});let t={session_id:this.sessionId,started_at:this._startedAt,model:e.model,environment:e.environment,profile:e.profile,plan:this._plan,objectives:[],runs:[],status:"in_progress"};R(u(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
15
+ `)}catch{}this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`),this._earlyLogBuffer.push({level:"info",event:"SESSION_START",message:"Session started",context:{session_id:this.sessionId}},{level:"info",event:"CONFIG",message:"Session config",context:{model:e.model,environment:e.environment,profile:e.profile}})}}setPlan(e){this._plan=e;let t={level:"info",event:"SESSION_INFO",message:"Session info",context:{session_id:this.sessionId,plan:e??null}};this._remoteLogger?this._remoteLogger.log(t.level,t.event,t.message,t.context):this._earlyLogBuffer.push(t)}get plan(){return this._plan}get apMode(){return f()??"v2"}setRemoteLogger(e){this._remoteLogger=e;for(let t of this._earlyLogBuffer)e.log(t.level,t.event,t.message,t.context);this._earlyLogBuffer=[]}get hasRemoteLogger(){return this._remoteLogger!==null}setAuteurVariables(e){Object.assign(this._auteurVariables,e)}get auteurVariables(){return this._auteurVariables}setScreenshotSas(e){this._screenshotSas=e}get screenshotSas(){return this._screenshotSas}get screenshotBaseUrl(){return this._screenshotSas?`${this._screenshotSas.base_url}/${this._screenshotSas.container}`:""}get startedAt(){return this._startedAt||new Date().toISOString()}log(e,t,s,i){if(t===void 0){this._log(e);let o=e.indexOf(" "),a=o>0?e.slice(0,o):e,w=o>0?e.slice(o+1):"",x=/fail|error/i.test(e)?"error":"info";this._remoteLogger?.log(x,a,w||e);return}let r=e,l=s;this._log(`${t} ${l}`,i),this._remoteLogger?.log(r,t,l,i)}logStep(e,t,s){this._log(`${e} ${t}`,s);let i=this._nextIndex>0?this._nextIndex-1:0;this._remoteLogger?.logStep(i,e,t,s)}logCommand(e){this._log(`COMMAND ${e}`)}logRunStart(e,t,s){this._log(`RUN ${e} START objective="${t.slice(0,100)}" url=${s}`),this._remoteLogger?.setRunIndex(e),this._remoteLogger?.log("info","RUN_START",`Run ${e} started`,{run_index:e,objective:t,url:s})}logRunEnd(e,t,s,i,r){let l=(s??0).toFixed(1),o=(i??"").slice(0,100),a=r==null||r===""||Number.isNaN(Number(r))?null:Number(r);this._log(`RUN ${e} END status=${t} duration=${l}s summary="${o}"`,a!=null?{result_code:a}:void 0),this._remoteLogger?.log("info","RUN_END",`Run ${e} ended`,{run_index:e,status:t,duration:s??0,summary:i??"",result_code:a}),t!=="failed"&&t!=="error"&&this._remoteLogger?.discardSteps(e)}escalateRun(e){this._remoteLogger?.escalate(e)}logChromeLaunch(e,t){this._log(`CHROME LAUNCH port=${e} endpoint=${t}`),this._remoteLogger?.log("info","CHROME_LAUNCH","Chrome launched",{port:e,cdp_endpoint:t})}async finish(e="complete"){this._log(`SESSION END status=${e} total_runs=${this.runs.length}`),this._remoteLogger?.log("info","SESSION_END","Session ended",{status:e,total_runs:this.runs.length}),await this._remoteLogger?.shutdown();let t={session_id:this.sessionId,started_at:this._startedAt,ended_at:new Date().toISOString(),model:this._model,environment:this._environment,profile:this._profile,plan:this._plan,status:e,total_runs:this.runs.length,test_id:this._testId,testcase_id:this._testcaseId,commit_id:this.sessionId,project_id:this._projectId,upload_status:this._uploadStatus,upload_attempts:this._uploadAttempts,last_upload_attempt:this._uploadAttempts>0?new Date().toISOString():null,upload_error:this._uploadError,runs:this.runs.map(s=>({index:s.index,objective:s.objective,status:s.status,summary:s.summary,run_dir:s.run_dir}))};S(this.sessionDir)&&R(u(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
16
+ `),this.flushRecorder(),this._recorder=null}nextRunIndex(){return this._nextIndex}addRunResult(e,t){this.runs.push(e),this._nextIndex+=t??1,this._recordingEnabled&&this._recorder?.appendObjective(e.objective)}getContext(){return{prior_runs:this.runs.map(e=>({index:e.index,objective:e.objective,summary:e.summary,status:e.status,memory:e.context.memory,variables:e.context.variables,pointer:e.context.pointer}))}}addFlow(e){let t={...e,index:this._flows.length+1};return this._flows.push(t),t}getFlows(){return[...this._flows]}getFlow(e){return this._flows.find(t=>t.index===e)}clearFlows(){this._flows=[]}recordStepRun(e){this._stepRunRecords.push(e)}getStepRunRecords(){return[...this._stepRunRecords]}getRunsAsStepRecords(){return this.runs.map((e,t)=>({testmdStepIndex:t+1,runIndex:e.index,totalRunDirs:e.run_dirs?.length??1}))}snapshot(){return{runsLen:this.runs.length,nextRunIndex:this._nextIndex,stepRunRecordsLen:this._stepRunRecords.length}}rollback(e){this.runs.length=e.runsLen,this._nextIndex=e.nextRunIndex,this._stepRunRecords.length=e.stepRunRecordsLen}setTestId(e){this._testId=e}get testId(){return this._testId}setTestcaseId(e){this._testcaseId=e}get testcaseId(){return this._testcaseId}setProjectId(e){this._projectId=e}setOrgId(e){this._orgId=e}get orgId(){return this._orgId}setUserIdentity(e,t){e&&(this._userName=e),t&&(this._userEmail=t)}get userName(){return this._userName}get userEmail(){return this._userEmail}setFirstRun(e,t){this._firstObjective||(this._firstObjective=e,this._firstUrl=t)}get firstObjective(){return this._firstObjective}get firstUrl(){return this._firstUrl}getRunDirs(){let e=[];for(let t of this.runs)t.run_dirs&&t.run_dirs.length>0?e.push(...t.run_dirs):t.run_dir&&e.push(t.run_dir);return e}getRunObjectives(){let e=[];for(let t of this.runs)t.flow_objectives&&t.flow_objectives.length>0?e.push(...t.flow_objectives):e.push(t.objective);return e}getRunMetadata(){let e=[];for(let t of this.runs)if(t.perFlowMetadata&&t.perFlowMetadata.length>0)e.push(...t.perFlowMetadata);else{let s={resultCode:t.resultCode,reasonCode:t.reasonCode,errorMessage:t.status==="failed"?t.summary??null:null,summary:t.summary,oneLiner:t.oneLiner},i=t.run_dirs?.length??1;for(let r=0;r<i;r++)e.push(s)}return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e,t){if(!(!this._started||!S(this.sessionDir)))try{let s=new Date().toISOString().slice(0,19).replace("T"," "),i=u(this.sessionDir,"tui.log"),r=t&&Object.keys(t).length>0?` ${JSON.stringify(t)}`:"";C(i,`[${s}] ${e}${r}
17
+ `)}catch{}}};export{v as a,P as b,y as c};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as V}from"./chunk-HYTBEPC2.js";import{existsSync as R,readdirSync as D,readFileSync as S}from"fs";import{join as b}from"path";var T="--variables",E=["global","smart","environment","secrets","totp"],F=/^[a-z][a-z0-9_]*$/;function M(e){return typeof e=="string"?e.trim().length>0:typeof e=="number"&&Number.isFinite(e)}function p(e,t,n){let r=JSON.parse(e);if(!(!r||typeof r!="object")){for(let[o,i]of Object.entries(r))if(i&&typeof i=="object"&&"value"in i){let c={has_value:M(i.value),source:t};n.set(u(o),c)}}}function w(e,t){if(!R(e))return;let n;try{n=D(e).filter(r=>r.endsWith(".json")).sort()}catch{return}for(let r of n){let o=b(e,r);try{p(S(o,"utf-8"),o,t)}catch{}}}function W(e){return{globalDir:b(V,"variables"),localDir:b(e,".testmuai","variables")}}function q(e){let t=new Map;if(w(e.globalDir,t),w(e.localDir,t),e.file&&R(e.file))try{p(S(e.file,"utf-8"),e.file,t)}catch{}if(e.inline)try{p(e.inline,T,t)}catch{}return t}function m(e){let t=e.trim();if(!t)return null;let n=t.split(/[.[]/).map(r=>r.trim()).filter(Boolean);return n.length===0||E.includes(n[0])?null:n[0]}function u(e){let t=/^(?:global|secrets\.user|environment)\.(.+)$/.exec(e);return t?t[1]:e}function H(e){if(!e||!e.trim())return"variable name is empty";let t=e.split(".")[0];return E.includes(t)?`'${e}' starts with a runtime namespace (global/secrets/smart/environment/totp) \u2014 declare the bare name`:F.test(e)?null:`'${e}' is not lower_snake_case (letters, digits, underscores; starts with a letter)`}import{basename as z}from"path";var ee="objective",C=/(\\?)\{\{\s*([^{}]+?)\s*\}\}/g;function v(e){let t=[];if(!e)return t;for(let n of e.matchAll(C)){if(n[1])continue;let r=m(n[2]??"");r&&!t.includes(r)&&t.push(r)}return t}var $=/(\\?)\$\{\s*([^{}]+?)\s*\}/g;function B(e){let t=[];if(!e)return t;for(let n of e.matchAll($)){if(n[1])continue;let r=(n[2]??"").split(/[.[]/)[0]?.trim()??"";r&&!t.includes(r)&&t.push(r)}return t}function te(e,t,n){return U(e.map(({text:r,usedBy:o})=>B(r).filter(i=>!t.has(i)).map(i=>({name:i,reason:"not_a_dataset_column",dataset:n,used_by:[o]}))))}var P=/\b(?:store|save|extract|remember|capture)\b/i,Z=/\bas\s+(?:['"`]([A-Za-z_][A-Za-z0-9_]*)['"`]|([A-Za-z_][A-Za-z0-9_]*)(?=\s*(?:,|$)))/gi,J=new Set(["a","an","the"]);function I(e){let t=[];if(!e)return t;for(let n of e.split(/[.;\n]/))if(P.test(n))for(let r of n.matchAll(Z)){let o=r[1]??r[2];!o||J.has(o.toLowerCase())||t.includes(o)||t.push(o)}return t}function A(e,t,n){let r=t.get(e);return r?r.has_value?null:{name:e,reason:"value_missing",file:r.source,used_by:[n]}:{name:e,reason:"not_declared",used_by:[n]}}function re(e,t,n,r=[]){let o=new Set([...r,...I(e)]),i=[];for(let c of v(e)){if(o.has(c))continue;let l=A(c,t,n);l&&i.push(l)}return i}function ne(e,t,n={}){let r=e.rootGlobal.variables??{},o=new Set(n.produced??[]),i=n.authorFrom??0,c=[];for(let l of e.steps){let k=l.flatIndex-1>=i,f=I(l.objective);if(!k){for(let s of f)o.add(s);continue}let j={file:z(l.sourceFile),step:l.flatIndex},N=l.config.variables??{},d=new Map,_=s=>m(u(s))??u(s);for(let[s,a]of Object.entries(r))d.set(_(s),a.value);for(let[s,a]of Object.entries(N))d.set(_(s),a.value);let g=new Set,y=(s,a)=>{if(o.has(s)||f.includes(s))return;let h=d.get(s);if(h===void 0){g.add(s);return}if(a.has(s)){g.add(s);return}a.add(s);for(let O of v(h))y(O,a);a.delete(s)};for(let s of v(l.objective))y(s,new Set);let x=[];for(let s of g){let a=A(s,t,j);a&&x.push(a)}c.push(x);for(let s of f)o.add(s)}return U(c)}function se(e){let t=new Set,n=e&&typeof e=="object"?e:null;for(let r of n?.prior_runs??[])for(let o of Object.keys(r.variables??{}))t.add(o);return[...t]}function U(e){let t=new Map;for(let n of e)for(let r of n){let o=t.get(r.name);o?o.used_by.push(...r.used_by):t.set(r.name,{...r,used_by:[...r.used_by]})}return[...t.values()].sort((n,r)=>n.name<r.name?-1:1)}export{T as a,W as b,q as c,H as d,ee as e,v as f,te as g,re as h,ne as i,se as j,U as k};
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as y}from"./chunk-WD52ZNQY.js";import{b as l,d,e as m,g,h as S}from"./chunk-KN65CUNT.js";import{a as f}from"./chunk-O5AS2ZIX.js";import{r as u,s as p}from"./chunk-RSSOJ3L2.js";import{existsSync as s,mkdirSync as h,readFileSync as C,renameSync as w,writeFileSync as R}from"fs";import{join as x}from"path";function G(e){y(l(e));let r=l(e);if(!s(r))return;let n=x(r,"meta.json"),o=m(e);if(s(n)&&!s(o))try{h(d(e),{recursive:!0}),w(n,o)}catch(t){process.stderr.write(`warn: meta.json migration failed: ${t.message}
2
+ import{b as y}from"./chunk-WD52ZNQY.js";import{b as l,d,e as m,g,h as S}from"./chunk-JQCOKL6U.js";import{a as f}from"./chunk-MLYNVJNH.js";import{r as u,s as p}from"./chunk-RSSOJ3L2.js";import{existsSync as s,mkdirSync as h,readFileSync as C,renameSync as w,writeFileSync as R}from"fs";import{join as x}from"path";function G(e){y(l(e));let r=l(e);if(!s(r))return;let n=x(r,"meta.json"),o=m(e);if(s(n)&&!s(o))try{h(d(e),{recursive:!0}),w(n,o)}catch(t){process.stderr.write(`warn: meta.json migration failed: ${t.message}
3
3
  `)}let a=S(e);if(s(a)){let t="python";try{let i=new f().load();i.code_export?.language&&(t=i.code_export.language)}catch{}let c=g(e,"playwright",t);if(!s(c))try{w(a,c)}catch(i){process.stderr.write(`warn: generated-code migration failed: ${i.message}
4
4
  `)}}if(s(o))try{let t=JSON.parse(C(o,"utf8"));"md5sum"in t&&(delete t.md5sum,R(o,JSON.stringify(t,null,2)+`
5
5
  `,"utf8"))}catch(t){process.stderr.write(`warn: meta.json md5sum strip failed: ${t.message}
6
- `)}}async function O(e){if(!e.isInteractive)return{recovered:!1};if(E(e.creds))return{recovered:!1};let{SingleShotApp:r}=await import("./SingleShotApp-U54ETXS3.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:o}=await import("./build-JIKYOZUH.js"),a=await import("./react-QWOAB3TB.js"),t={current:null},c={current:!1},{waitUntilExit:i,unmount:v}=o(a.default.createElement(n,null,a.default.createElement(r,{resultRef:t,mode:"login",loginCompleteRef:c})),{exitOnCtrlC:!1});p(()=>v()),await i();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),c.current?{recovered:!0}:(u(0,"Startup gate cancelled"),{recovered:!1})}function E(e){let r=e.getActiveProfile(),n=e.getDefaultEnv();if(!r||!!!(e.loadBasicAuth(r,n)||e.loadCredentials(r,n)))return!1;let a=e.loadProfileConfig(r,n)??{};return!!a.project_id&&!!a.folder_id}export{G as a,O as b};
6
+ `)}}async function O(e){if(!e.isInteractive)return{recovered:!1};if(E(e.creds))return{recovered:!1};let{SingleShotApp:r}=await import("./SingleShotApp-IPNZBFXB.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:o}=await import("./build-JIKYOZUH.js"),a=await import("./react-QWOAB3TB.js"),t={current:null},c={current:!1},{waitUntilExit:i,unmount:v}=o(a.default.createElement(n,null,a.default.createElement(r,{resultRef:t,mode:"login",loginCompleteRef:c})),{exitOnCtrlC:!1});p(()=>v()),await i();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),c.current?{recovered:!0}:(u(0,"Startup gate cancelled"),{recovered:!1})}function E(e){let r=e.getActiveProfile(),n=e.getDefaultEnv();if(!r||!!!(e.loadBasicAuth(r,n)||e.loadCredentials(r,n)))return!1;let a=e.loadProfileConfig(r,n)??{};return!!a.project_id&&!!a.folder_id}export{G as a,O as b};