@testmuai/kane-cli 0.4.0 → 0.4.2

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 (109) hide show
  1. package/dist/{ChromeProfilePicker-27QCT4NT.js → ChromeProfilePicker-HNP7QQ4J.js} +1 -1
  2. package/dist/{CliFeedbackPrompt-LMXDRY5F.js → CliFeedbackPrompt-OSNATI4W.js} +1 -1
  3. package/dist/{CliUploadProgress-QP5SPC7G.js → CliUploadProgress-7HRWDZ4P.js} +1 -1
  4. package/dist/ConfigView-PQH67FUK.js +2 -0
  5. package/dist/FolderPicker-SET7IG6S.js +2 -0
  6. package/dist/HelpView-HFKFRKG3.js +2 -0
  7. package/dist/{InfoBox-JELKGWY5.js → InfoBox-3IN3IZ2I.js} +1 -1
  8. package/dist/{LinksBox-NUSUOUIW.js → LinksBox-DI5QKX6K.js} +1 -1
  9. package/dist/{ProfilesView-RXYI2IS3.js → ProfilesView-N6XNSUHQ.js} +1 -1
  10. package/dist/ProjectPicker-6QIVHOO7.js +2 -0
  11. package/dist/{SaveSessionPrompt-GUBVAQ3O.js → SaveSessionPrompt-7CZHPNYK.js} +1 -1
  12. package/dist/SingleShotApp-A4VXMXEZ.js +2 -0
  13. package/dist/{SummaryBox-5Y2YYOUM.js → SummaryBox-7ZK2A6MA.js} +1 -1
  14. package/dist/TestMdRunView-KGHEZZBK.js +2 -0
  15. package/dist/WhoamiView-3E447A3G.js +2 -0
  16. package/dist/{changelog-N4SSER5V.js → changelog-ZBTZCYKI.js} +1 -1
  17. package/dist/chunk-34YRU7WM.js +6 -0
  18. package/dist/chunk-3QWAABMG.js +2 -0
  19. package/dist/{chunk-CKY3UXTY.js → chunk-4UKCDU64.js} +1 -1
  20. package/dist/{chunk-PWHFNSDC.js → chunk-4ZHU4DLD.js} +1 -1
  21. package/dist/{chunk-5TOE4RHH.js → chunk-7CBWZLRS.js} +1 -1
  22. package/dist/{chunk-PKQJHIKJ.js → chunk-AAJSF67A.js} +1 -1
  23. package/dist/{chunk-JCR3T34A.js → chunk-AKKATURY.js} +2 -2
  24. package/dist/chunk-BM25JQ3Z.js +17 -0
  25. package/dist/chunk-C6S4IEBC.js +2 -0
  26. package/dist/{chunk-TAEW7PXN.js → chunk-CZBHDBID.js} +1 -1
  27. package/dist/chunk-DGUXTSHM.js +11 -0
  28. package/dist/chunk-DQASLGFG.js +60 -0
  29. package/dist/{chunk-6NEJEMA6.js → chunk-EEF6OT52.js} +1 -1
  30. package/dist/{chunk-LMV2F35W.js → chunk-ELZIC2EH.js} +1 -1
  31. package/dist/chunk-FFTIDI5K.js +5 -0
  32. package/dist/chunk-FPFOW6BS.js +2 -0
  33. package/dist/{chunk-AT2Y5UNP.js → chunk-GNJBT6SS.js} +1 -1
  34. package/dist/{chunk-UJZCMEEH.js → chunk-H2P7UJAU.js} +1 -1
  35. package/dist/chunk-K4PLPKPF.js +5 -0
  36. package/dist/{chunk-7RPMUEEN.js → chunk-KPF3BPJ5.js} +1 -1
  37. package/dist/chunk-LOIRZFV3.js +10 -0
  38. package/dist/{chunk-O2UU4TS5.js → chunk-LOSNFBZV.js} +1 -1
  39. package/dist/chunk-LPUQ4HWQ.js +2 -0
  40. package/dist/chunk-LY5LHKGG.js +18 -0
  41. package/dist/chunk-NKFXY5TF.js +22 -0
  42. package/dist/chunk-OISHNB7D.js +2 -0
  43. package/dist/chunk-PF7PBYCJ.js +5 -0
  44. package/dist/{chunk-VS2BXLH4.js → chunk-PQIPYWTP.js} +1 -1
  45. package/dist/chunk-QXVI3LI4.js +6 -0
  46. package/dist/{chunk-CGAX3AXA.js → chunk-R7T6Z6QW.js} +1 -1
  47. package/dist/chunk-RCL22HDJ.js +2 -0
  48. package/dist/{chunk-XQXSPUIX.js → chunk-RD6G3CMN.js} +1 -1
  49. package/dist/chunk-RLSBAT6P.js +2 -0
  50. package/dist/chunk-S7JV4A3U.js +2 -0
  51. package/dist/{chunk-IH45REQA.js → chunk-TQGNNJX5.js} +1 -1
  52. package/dist/{chunk-VTDVK3DK.js → chunk-UHGECBEN.js} +1 -1
  53. package/dist/chunk-VBZIIF5N.js +17 -0
  54. package/dist/chunk-VL57GII7.js +2 -0
  55. package/dist/chunk-WFSTRBQF.js +2 -0
  56. package/dist/chunk-Y6IUJZMV.js +2 -0
  57. package/dist/{chunk-HYVAYSRZ.js → chunk-YB67GRWE.js} +1 -1
  58. package/dist/exit-manager-V2NW7A7U.js +2 -0
  59. package/dist/generate-headless-WL6A6ACX.js +21 -0
  60. package/dist/index.js +41 -31
  61. package/dist/list-commands-MK4W3Q7O.js +2 -0
  62. package/dist/login-flow-CDR6ARK3.js +2 -0
  63. package/dist/{persist-recorded-session-VEFILVPX.js → persist-recorded-session-A5EJ25AE.js} +1 -1
  64. package/dist/{pipeline-3GVPCDRE.js → pipeline-L5TDZMLS.js} +1 -1
  65. package/dist/{recording-banner-WS4Y7LVH.js → recording-banner-6UI6NNRK.js} +1 -1
  66. package/dist/require-project-folder-J5WZR653.js +2 -0
  67. package/dist/resolver-IDCGRPFJ.js +2 -0
  68. package/dist/run-test-md-I76IV7QA.js +14 -0
  69. package/dist/scrollback-6GINSTL2.js +2 -0
  70. package/dist/skill-installer-ZLBRT4QP.js +3 -0
  71. package/dist/tcg-generate-R6P4QUGO.js +2 -0
  72. package/dist/testmd-actions-W2INQVTH.js +2 -0
  73. package/dist/{tms-client-R5ZIAOBH.js → tms-client-NNYXLXZK.js} +1 -1
  74. package/dist/token-refresh-4QLWR5ZI.js +2 -0
  75. package/dist/validate-basic-QUPVT2EV.js +2 -0
  76. package/dist/{version-check-LNKXGYZE.js → version-check-RVK5YKDZ.js} +1 -1
  77. package/package.json +8 -6
  78. package/dist/ConfigView-RQM2JY4K.js +0 -2
  79. package/dist/FolderPicker-YN2YQJXI.js +0 -2
  80. package/dist/HelpView-2IYG5AC3.js +0 -2
  81. package/dist/ProjectPicker-RUR7HH2P.js +0 -2
  82. package/dist/SingleShotApp-3XDTU2BU.js +0 -2
  83. package/dist/TestMdRunView-PPZPUVVZ.js +0 -2
  84. package/dist/WhoamiView-IJZUFJ7B.js +0 -2
  85. package/dist/chunk-3C7ATCDM.js +0 -2
  86. package/dist/chunk-3Z4EHIOW.js +0 -2
  87. package/dist/chunk-6IQWD272.js +0 -2
  88. package/dist/chunk-7CLUJYMW.js +0 -2
  89. package/dist/chunk-7G7ZLAJH.js +0 -5
  90. package/dist/chunk-BKXTOQWL.js +0 -5
  91. package/dist/chunk-BPF7TDRU.js +0 -2
  92. package/dist/chunk-DTFPHZE7.js +0 -62
  93. package/dist/chunk-H4XV224I.js +0 -6
  94. package/dist/chunk-H6OVTXJQ.js +0 -2
  95. package/dist/chunk-J37YPPCD.js +0 -2
  96. package/dist/chunk-JLOY7SNA.js +0 -14
  97. package/dist/chunk-L3RTVAPG.js +0 -6
  98. package/dist/chunk-LRF6UP42.js +0 -10
  99. package/dist/chunk-M5RHRHFC.js +0 -9
  100. package/dist/chunk-PN7LNQ7G.js +0 -5
  101. package/dist/chunk-SJ7VGRQU.js +0 -17
  102. package/dist/chunk-UVBDUDSL.js +0 -2
  103. package/dist/generate-headless-7UYAPXE5.js +0 -18
  104. package/dist/login-flow-LK7GAUCZ.js +0 -2
  105. package/dist/resolver-OA35IO7J.js +0 -2
  106. package/dist/run-test-md-SXZUOYSG.js +0 -14
  107. package/dist/tcg-generate-CEBFKKJE.js +0 -2
  108. package/dist/testmd-actions-IZPOBSTC.js +0 -2
  109. package/dist/validate-basic-Y73NBDAD.js +0 -2
@@ -0,0 +1,60 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as Re,b as Xt}from"./chunk-C5UNZ6ZY.js";import{a as rr}from"./chunk-EEF6OT52.js";import{c as er}from"./chunk-S3DAAAE5.js";import{b as Zt,c as it,d as at,e as Se,f as lt,g as tr}from"./chunk-HN7DVSVI.js";import{a as Oe,b as se,c as Qt,e as ae,f as nt,i as Yt,j as ot}from"./chunk-AH4AXJML.js";import{b as de}from"./chunk-BM25JQ3Z.js";import{a as Wt}from"./chunk-WAOCHXJ5.js";import{a as Jt,b as st}from"./chunk-K4PLPKPF.js";import{a as Vt,b as Ht,c as rt,d as Le,e as Kt,f as qt}from"./chunk-LOIRZFV3.js";import{f as Gt,g as zt}from"./chunk-VBZIIF5N.js";import{a as Bt}from"./chunk-LPUQ4HWQ.js";import{a as Te,b as $t}from"./chunk-NLCCBXXV.js";import{a as z}from"./chunk-S7JV4A3U.js";import{a as D}from"./chunk-RZ4F3BHX.js";import{a as Ft}from"./chunk-E47GFYXA.js";import{a as Nt,c as Xe,i as Mt,j as ue,k as et,l as tt}from"./chunk-3QWAABMG.js";import{join as Ve,basename as fn}from"path";import{existsSync as rs,readFileSync as hn}from"fs";import{existsSync as ct}from"fs";import{join as De,basename as sr}from"path";function nr(e,t){if(!t||!ct(t))return e.steps.map(()=>({kind:"author",reason:"no-result-md"}));let r=at(t),s=[],n=new Set,o=new Map;function a(i){let m=Se(i),p=De(m,"Result.md");if(o.has(p))return o.get(p);let h=ct(p)?at(p):null;return o.set(p,h),h}function l(i){for(let m=1;m<i.trace.length;m++){let h=i.trace[m-1].file===e.rootPath?r:a(i.trace.slice(0,m));if(!h)return{kind:"author",reason:"no-result-md"};let C=i.trace[m-1].stepIndex,b=h.steps[C-1];if(!b)return{kind:"author",reason:"no-result-md"};if(b.kind!=="import")return{kind:"author",reason:"structure-mismatch"};let I=sr(b.importPath),R=sr(i.trace[m].file);if(I!==R)return{kind:"author",reason:"structure-mismatch"};if(b.status!=="passed")return{kind:"author",reason:"recorded-failed"}}return null}for(let i of e.steps){let m=i.trace[i.trace.length-1].file,p=i.trace[i.trace.length-1].stepIndex,h=n.has(m);for(let R=0;R<i.trace.length-1&&!h;R++)n.has(i.trace[R].file)&&(h=!0);if(h){s.push({kind:"author",reason:"downstream-of-divergence"});continue}let C=l(i);if(C){s.push(C);for(let R=0;R<i.trace.length;R++)n.add(i.trace[R].file);continue}let b=m===e.rootPath?r:a(i.trace),I=bs(i,b,p);if(s.push(I),I.kind==="author"){n.add(m);for(let R=0;R<i.trace.length-1;R++)n.add(i.trace[R].file)}}return s}function bs(e,t,r){if(!t)return{kind:"author",reason:"no-result-md"};let s=t.steps[r-1];if(!s)return{kind:"author",reason:"no-result-md"};if(s.kind!=="objective")return{kind:"author",reason:"structure-mismatch"};if(s.status!=="passed")return{kind:"author",reason:"recorded-failed"};let n=Zt(e);if(n!==s.md5)return{kind:"author",reason:"md5-mismatch"};let o=e.trace.length===1?Yt(e.trace[0].file,r,n.slice(0,8)):De(Se(e.trace),".internal","steps",`${r}-${n.slice(0,8)}`),a=De(o,"flows","0","actions.ndjson");return ct(a)?{kind:"replay",recordingDir:o}:{kind:"author",reason:"missing-recording"}}function or(e){return e.some(t=>t.kind==="author")}function je(e){for(let t=0;t<e.length;t++)if(e[t].kind==="author")return t;return e.length}function ir(e){return De(e.recordingDir,"flows","0","actions.ndjson")}function ar(e,t){if(process.env.KANE_REPLAY_TRACE==="1")for(let r=0;r<e.steps.length;r++){let s=e.steps[r],n=t[r],o=" ".repeat(s.trace.length-1),a=`step ${s.flatIndex}`;n.kind==="replay"?process.stderr.write(`[replay-trace] ${o}${a}: REPLAY (would skip; v1 always authors)
3
+ `):process.stderr.write(`[replay-trace] ${o}${a}: AUTHOR (${n.reason})
4
+ `)}}function me(e){process.env.KANE_REPLAY_TRACE==="1"&&process.stderr.write(e)}function lr(e,t){let r=e===0?"(none)":`0..${e-1}`,s=e>=t?"(none)":`${e}..${t-1}`;me(`[replay-trace] phase: replay ${r}, author ${s}
5
+ `)}function cr(e,t){me(`[replay-trace] step ${e}: REPLAY ${t==="ok"?"OK":"FAILED"}
6
+ `)}function ur(e,t,r){me(`[replay-trace] shrink ${e}/${t} \u2192 new boundary ${r}
7
+ `)}function dr(e,t){me(`[replay-trace] complete-reauthor (${e} shrinks exhausted of ${t})
8
+ `)}function ut(){me(`[replay-trace] force-author (--author) \u2014 walker bypassed
9
+ `)}function mr(e){me(`[replay-trace] cancelled at step ${e}
10
+ `)}import{join as ys}from"path";function dt(e){let t={objective:e.step.objective,model:"v16-alpha",width:e.windowSize.width,height:e.windowSize.height,session_id:e.sessionId,run_index:e.runIndex,stream:!0,mode:"replay",replay:{recording_path:ir(e.decision),step_label:e.step.objective},screenshot_dir:ys(e.sessionDir,"runs",String(e.runIndex)),run_id:"run",test_id:"test"};return e.forceNavigateUrl&&(t.url=e.forceNavigateUrl),e.chrome.wsEndpoint?t.ws_endpoint=e.chrome.wsEndpoint:e.chrome.cdpEndpoint&&(t.cdp_endpoint=e.chrome.cdpEndpoint),e.auth.basicAuth?(t.username=e.auth.basicAuth.username,t.access_key=e.auth.basicAuth.access_key):e.auth.token&&(t.auth={type:"bearer",token:e.auth.token}),e.variables&&Object.keys(e.variables).length>0&&(t.variables=e.variables),e.sessionContext&&(t.session_context=e.sessionContext),t}async function pr(e){let t=e.forceAuthor?0:je(e.decisions),r=0,s=!1;for(;;){let n=e.session.snapshot(),o=e.accumulator.snapshot(),a=await e.runReplayPhase(t);if(a.cancelled)return s=!0,mr(a.failedAt??0),{authorBoundary:t,cancelledInPhase:s,shrinkCount:r};if(a.failedAt===null)return{authorBoundary:t,cancelledInPhase:s,shrinkCount:r};let l=Xt({failedAt:a.failedAt,shrinkCount:r,hasRetry:e.hasRetry,maxShrinks:e.maxShrinks});if(l.kind==="fail")return{authorBoundary:-1,cancelledInPhase:s,shrinkCount:r};if(e.acquireLockIfNeeded&&!await e.acquireLockIfNeeded())return{authorBoundary:-1,cancelledInPhase:s,shrinkCount:r};if(e.session.rollback(n),e.accumulator.rollback(o),l.kind==="complete-reauthor")return dr(r+1,e.maxShrinks),{authorBoundary:0,cancelledInPhase:s,shrinkCount:r};r++,ur(r,Re.maxShrinks,l.newAuthorBoundary),t=l.newAuthorBoundary}}var vs=15e3,mt=3,fr=[500,1e3];async function pt(e){if(process.env.KANE_LOCK_CONFLICT_SIMULATE==="1")return{ok:!1,reason:"concurrent",httpStatus:409,message:"simulated contention (KANE_LOCK_CONFLICT_SIMULATE=1)"};let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground`,r=await Ue(t,{from_commit_id:e.fromCommitId,new_commit_id:e.newCommitId},e.auth);return r.ok?{ok:!0,sessionExpiresAt:j(r.body,"session_expires_at")??""}:{ok:!1,...Ss(r)}}function Ss(e){let t=j(e.body,"error")??j(e.body,"code")??"",r=j(e.body,"message")??j(e.body,"detail")??e.text??`HTTP ${e.status}`,s;return e.status===0?s="network":e.status===401||e.status===403?s="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?s="base_mismatch":e.status===409?s="concurrent":e.status===422?s="disabled":e.status===400&&/no committed/i.test(r)?s="no_commits":e.status===400?s="missing_field":e.status>=500||e.status===408||e.status===429?s="network":s="other",{reason:s,httpStatus:e.status,message:r}}async function gr(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground/reserve`,r=await Ue(t,void 0,e.auth);return r.ok?{ok:!0,sessionExpiresAt:j(r.body,"session_expires_at")??""}:{ok:!1,expired:r.status===404,httpStatus:r.status,message:j(r.body,"message")??j(r.body,"detail")??r.text??`HTTP ${r.status}`}}async function br(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/commit`,r={commit_id:e.body.commitId,from_commit_id:e.body.fromCommitId,commit_message:e.body.commitMessage,total_steps:e.body.totalSteps};e.body.timeTaken!==void 0&&(r.time_taken=e.body.timeTaken),e.body.objectives!==void 0&&(r.objectives=e.body.objectives);let s=await Ue(t,r,e.auth);return s.ok?{ok:!0,testId:j(s.body,"test_id")??e.testId,testcaseId:j(s.body,"testcase_id")??"",projectId:j(s.body,"project_id"),isTestCaseDeleted:typeof s.body?.is_test_case_deleted=="boolean"?s.body.is_test_case_deleted:void 0}:{ok:!1,...Rs(s)}}function Rs(e){let t=j(e.body,"error")??j(e.body,"code")??"",r=j(e.body,"message")??j(e.body,"detail")??e.text??`HTTP ${e.status}`,s;return e.status===0?s="network":e.status===401||e.status===403?s="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?s="base_mismatch":e.status===409&&t==="PlaygroundCommitLockMismatch"?s="lock_mismatch":e.status===409?s="expired":e.status===422?s="not_found":e.status>=500||e.status===408||e.status===429?s="network":s="other",{reason:s,httpStatus:e.status,message:r}}async function yr(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/commit`,r={discard:!0,commit_id:e.body.commitId,from_commit_id:e.body.fromCommitId,commit_message:"(discarded)",total_steps:1},s=await Ue(t,r,e.auth);return s.ok?{ok:!0}:{ok:!1,reason:j(s.body,"error")??"other",httpStatus:s.status,message:j(s.body,"message")??j(s.body,"detail")??s.text??`HTTP ${s.status}`}}async function Ue(e,t,r){let s=null;for(let n=1;n<=mt;n++){let o=new AbortController,a=setTimeout(()=>o.abort(),vs);try{let l=await D(e,{method:"POST",headers:{Authorization:Te(r.username,r.accessKey),"Content-Type":"application/json",Accept:"application/json"},...t!==void 0?{body:JSON.stringify(t)}:{},signal:o.signal});clearTimeout(a);let i=await l.text(),m=null;if(i)try{m=JSON.parse(i)}catch{}let p=l.status>=500||l.status===408||l.status===429;if(l.ok||!p)return{ok:l.ok,status:l.status,body:m,text:i};if(n<mt){await hr(fr[n-1]??1e3);continue}return{ok:!1,status:l.status,body:m,text:i}}catch(l){if(clearTimeout(a),s=l,n<mt){await hr(fr[n-1]??1e3);continue}}}return{ok:!1,status:0,body:null,text:s?.message??"exhausted retries"}}function hr(e){return new Promise(t=>setTimeout(t,e))}function j(e,t){if(typeof e!="object"||e===null)return;let r=e[t];return typeof r=="string"?r:void 0}var ws=60*1e3,vr="lock-heartbeat",pe=null,ft=null,Sr={register:(e,t)=>Le(e,t),deregister:e=>Kt(e),cleanup:(e,t)=>qt(e,t),remoteLogger:null};function Rr(){pe!==null&&(clearInterval(pe),pe=null)}function ht(e){if(pe!==null)return;let t=e.lifecycle??Sr;ft=t,pe=setInterval(async()=>{let r=await gr({baseUrl:e.baseUrl,testId:e.testId,auth:e.auth});if(!r.ok){let s=r.expired?"session expired":r.message;process.stderr.write(`[lock] heartbeat failed: ${s}; continuing run
11
+ `)}},ws),t.register(vr,()=>Rr())}function gt(){pe!==null&&(Rr(),(ft??Sr).deregister(vr),ft=null)}import{readFileSync as wr,readdirSync as Ir,existsSync as le}from"fs";import{join as ee}from"path";function _r(e,t,r,s,n,o){try{let a=ee(e,"runs",String(t),"run-test");if(!le(a)){n("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:r,reason:"runsDir_not_found",path:a});return}let l=a;if(o){let R=ee(a,`child-${o}`);if(!le(R)){n("warn","SCREENSHOT_SKIP","Child dir not found",{step_index:r,child_id:o,reason:"child_dir_not_found",path:R});return}let c=Ir(R).filter(x=>le(ee(R,x,"screenshots")));if(c.length===0){n("warn","SCREENSHOT_SKIP","No screenshots dir under child",{step_index:r,child_id:o,reason:"no_child_screenshots_dir"});return}l=ee(R,c[0])}else if(!le(ee(a,"screenshots"))){let R=Ir(a).filter(c=>le(ee(a,c,"screenshots")));if(R.length===0){n("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:r,reason:"no_screenshots_dir"});return}l=ee(a,R[0])}let i=ee(l,"screenshots",`step_${String(r).padStart(3,"0")}.png`);if(!le(i)){n("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:r,child_id:o,reason:"screenshot_not_found",path:i});return}let m=ee(a,"actions.ndjson");if(!le(m)){n("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:r,reason:"ndjson_not_found"});return}let p=wr(m,"utf-8").trim().split(`
12
+ `),h=p[p.length-1];if(!h){n("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:r,reason:"ndjson_empty"});return}let b=JSON.parse(h).action_id;if(!b){n("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:r,reason:"no_action_id"});return}let I=wr(i);s.enqueue(b,I),n("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:r,child_id:o,action_id:b,size:I.length})}catch(a){n("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:r,error:a instanceof Error?a.message:String(a)})}}import{dirname as Is,join as _s}from"path";function kr(e,t,r){let s=e.total_runs??1,n=e.run_dir,o,a;if(s>1&&n){let l=Is(n);o=Array.from({length:s},(i,m)=>_s(l,String(t+m))),r&&r.length===s&&(a=r)}return{allRunDirs:o,flowObjectives:a}}function Cr(e,t,r,s){return{index:r,objective:t,summary:e.summary,oneLiner:e.one_liner,status:e.status,resultCode:e.result_code,reasonCode:e.reason_code,perFlowMetadata:e.per_flow_metadata,context:e.context??{memory:{},variables:{},pointer:""},run_dir:e.run_dir,run_dirs:s.allRunDirs,flow_objectives:s.flowObjectives}}var Fe=class{constructor(t){this.resolved=t;this.outcomes=t.rootSteps.map(r=>({rootStepIndex:r.index,status:"skipped"}))}outcomes;skipRoot=null;overallHalted=!1;shouldRunFlatStep(t){if(this.overallHalted)return!1;let r=t.trace[0].stepIndex;return!(this.skipRoot!==null&&r===this.skipRoot)}recordStep(t,r){let s=t.trace[0].stepIndex,n=this.outcomes.find(i=>i.rootStepIndex===s),o=this.resolved.rootSteps.find(i=>i.index===s),a=o.body.kind!=="objective";return a&&(n.refKind="import",n.refLabel=o.body.path,n.inlinedCount=(n.inlinedCount??0)+1,n.duration_s=(n.duration_s??0)+r.duration_s),r.status==="passed"?(a?n.status!=="failed"&&(n.status="passed"):(n.status="passed",n.duration_s=r.duration_s),{continueOverall:!0}):t.optional?(n.softFailures=n.softFailures??[],n.softFailures.push({subStepIndex:t.trace[t.trace.length-1].stepIndex,reason:r.reason}),{continueOverall:!0}):(n.status="failed",n.duration_s=a?n.duration_s:r.duration_s,n.failedSubStepIndex=a?t.trace.slice(1).map(i=>i.stepIndex):void 0,n.reason=r.reason,this.skipRoot=s,o.optional??!1?(n.softFailed=!0,{continueOverall:!0}):(this.overallHalted=!0,{continueOverall:!1}))}snapshotOutcomes(){return[...this.outcomes]}snapshot(){return{outcomes:this.outcomes.map(t=>({...t,softFailures:t.softFailures?[...t.softFailures]:void 0})),skipRoot:this.skipRoot,overallHalted:this.overallHalted}}rollback(t){this.outcomes=t.outcomes.map(r=>({...r,softFailures:r.softFailures?[...r.softFailures]:void 0})),this.skipRoot=t.skipRoot,this.overallHalted=t.overallHalted}finalize(){let t=this.outcomes.some(s=>s.status==="failed"&&!s.softFailed)?"failed":"passed",r=this.outcomes.reduce((s,n)=>s+(n.duration_s??0),0);return{overallStatus:t,outcomes:this.outcomes,totalDurationS:r}}};import{spawn as ks}from"child_process";async function Er(e,t,r=100){let s=`${e.replace(/\/+$/,"")}/json/version`,n=await D(s);if(!n.ok)throw new Error(`CDP /json/version returned ${n.status}`);let o=await n.json();if(!o.webSocketDebuggerUrl)throw new Error("CDP /json/version missing webSocketDebuggerUrl");let a=new Ft(o.webSocketDebuggerUrl);await new Promise((P,_)=>{a.once("open",P),a.once("error",_)});let l=1,i=new Map;a.on("message",P=>{let _;try{_=JSON.parse(P.toString())}catch{return}if(_.id==null)return;let L=i.get(_.id);L&&(i.delete(_.id),_.error?L.reject(new Error(_.error.message)):L.resolve(_.result))});function m(P,_){let L=l++;return new Promise((J,M)=>{i.set(L,{resolve:ce=>J(ce),reject:M});let be={id:L,method:P};_&&(be.params=_),a.send(JSON.stringify(be))})}let h=(await m("Target.getTargets")).targetInfos.find(P=>P.type==="page");if(!h)throw a.close(),new Error("CDP: no page target found");let b=(await m("Browser.getWindowForTarget",{targetId:h.targetId})).windowId,I="",R=!1,c=null,x=!1;a.on("close",()=>{x=!0}),a.on("error",()=>{x=!0});async function f(){if(!R){if(x){R=!0;return}try{let _=(await m("Browser.getWindowBounds",{windowId:b})).bounds,L=`${_.left}:${_.top}:${_.width}:${_.height}`;L!==I&&(I=L,t({left:_.left,top:_.top,width:_.width,height:_.height}))}catch{}R||(c=setTimeout(f,r))}}return f(),{stop(){if(!R){R=!0,c&&clearTimeout(c);try{a.close()}catch{}}}}}var Cs=new Set(["1","true","yes"]);function Ar(e){if(e?.headless)return null;let t=process.env.KANE_CLI_DISABLE_MARKER;if(t!=null&&Cs.has(t.toLowerCase()))return null;let r=Jt();if(!r)return null;let s=[...r.args,"overlay"];e?.text&&s.push(e.text);let n;try{n=ks(r.cmd,s,{cwd:r.cwd,stdio:["pipe","ignore","ignore"],detached:!1,windowsHide:!0})}catch{return null}function o(i){if(!(!n.stdin||n.stdin.destroyed))try{n.stdin.write(JSON.stringify(i)+`
13
+ `)}catch{}}e?.chromePid&&e.chromePid>0&&o({type:"chrome_pid",pid:e.chromePid});let a=null;e?.cdpEndpoint&&Er(e.cdpEndpoint,i=>o({type:"bounds",...i})).then(i=>{a=i.stop}).catch(()=>{});let l=!1;return{setRunActive(i){l||o({type:"run_active",active:i})},setStepText(i){if(l)return;let m=i.trim();m&&o({type:"step_text",text:m})},setStepComplete(){l||o({type:"step_complete"})},kill(){if(!l){l=!0,a?.();try{n.stdin?.end()}catch{}try{n.kill("SIGTERM")}catch{}}}}}function xr(e,t,r){return`${e}/projects/${t}/test-cases/${r}`}function bt(e,t,r,s){return`${xr(e,t,r)}/dashboard/share/${s}?type=summary&agentView=true&fqdn=summary-page`}function Pr(e,t,r){return`${xr(e,t,r)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{mkdtempSync as Fs,rmSync as Ns}from"fs";import{join as Ms}from"path";import{tmpdir as $s}from"os";import{spawn as Tr,spawnSync as Es}from"child_process";import{existsSync as yt}from"fs";import{createConnection as As}from"net";import{homedir as we,platform as _e}from"os";import{join as Ie}from"path";var xs=new Set(["1","true","yes"]),Ne=class extends Error{constructor(t){super(t),this.name="ChromeNotFoundError"}};function fo(e){return e instanceof Ne?e.message:`Chrome failed: ${e instanceof Error?e.message:String(e)}`}var Me={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",Ie(we(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",Ie(we(),"Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"),"/Applications/Chromium.app/Contents/MacOS/Chromium"],linux:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/google-chrome-for-testing","/usr/local/bin/google-chrome-for-testing",Ie(we(),"chrome-for-testing/chrome-linux64/chrome"),"/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],win32:["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",Ie(we(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",Ie(we(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function Ps(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let e=_e(),t=Me[e]??Me.linux;for(let r of t)if(yt(r))return r;return e==="win32"?"chrome.exe":"google-chrome"}function Ts(){if(process.env.KANE_CLI_CHROME_PATH)return yt(process.env.KANE_CLI_CHROME_PATH);let e=_e();if((Me[e]??Me.linux).some(n=>yt(n)))return!0;let r=e==="win32"?"chrome.exe":"google-chrome",s=e==="win32"?"where":"which";try{return Es(s,[r],{stdio:"ignore"}).status===0}catch{return!1}}function Ls(){let e=_e();return e==="darwin"?["Google Chrome is required but was not found at any standard path.","","Install via Homebrew (recommended):"," brew install --cask google-chrome","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
14
+ `):e==="linux"?["Google Chrome is required but was not found at /usr/bin/google-chrome.","(amd64 / x86_64 only \u2014 Google does not ship Chrome for Linux ARM.)","","Debian / Ubuntu (any version):"," wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"," sudo apt install -y ./google-chrome-stable_current_amd64.deb","","Fedora / RHEL / AlmaLinux / Rocky:"," sudo dnf install -y https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
15
+ `):e==="win32"?["Google Chrome is required but was not found in Program Files or AppData.","","Install via winget (Windows 10 1809+):"," winget install --id Google.Chrome -e --silent","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=C:\\path\\to\\chrome.exe","to point at a non-standard install."].join(`
16
+ `):["Google Chrome is required.","Install from https://www.google.com/chrome/","(Note: no official Chrome builds for BSD or Alpine/musl Linux.)"].join(`
17
+ `)}function Os(e){let t=_e(),r=[`--remote-debugging-port=${e.port}`,`--user-data-dir=${e.userDataDir}`,`--window-size=${e.width},${e.height}`,"--no-first-run","--no-default-browser-check","--disable-blink-features=AutomationControlled","--disable-features=DownloadBubble,DownloadBubbleV2","--safebrowsing-disable-download-protection","--disable-popup-blocking","--disable-notifications","--disable-infobars","--disable-translate","--disable-prompt-on-repost","--disable-background-networking","--disable-client-side-phishing-detection","--disable-default-apps","--disable-hang-monitor","--disable-sync","--metrics-recording-only","--safebrowsing-disable-auto-update","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--test-type=webdriver","--allow-pre-commit-input","--enable-logging","--v=1"];return t==="linux"&&(r.push("--no-sandbox"),r.push("--disable-dev-shm-usage"),r.push("--password-store=basic")),t==="darwin"&&r.push("--use-mock-keychain"),e.headless&&r.push("--headless=new"),r}function Ds(e){return new Promise(t=>{let r=As({port:e,host:"127.0.0.1"});r.setTimeout(1e3),r.on("connect",()=>{r.destroy(),t(!0)}),r.on("timeout",()=>{r.destroy(),t(!1)}),r.on("error",()=>{r.destroy(),t(!1)})})}async function js(){for(let e=et;e<=tt;e++)if(!await Ds(e))return e;throw new Error(`All CDP ports ${et}-${tt} are in use. Close other Chrome instances.`)}async function Us(e,t=15e3){let r=Date.now(),s=`http://127.0.0.1:${e}/json/version`;for(;Date.now()-r<t;){try{if((await D(s)).ok)return`http://127.0.0.1:${e}`}catch{}await new Promise(n=>setTimeout(n,200))}throw new Error(`Chrome CDP not ready after ${t}ms on port ${e}`)}async function Lr(e){let t=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(t!=null&&xs.has(t.toLowerCase()))&&!Ts())throw Ht()?.log("error","CHROME_NOT_FOUND","Startup gate: Chrome unavailable at standard system paths",{platform:process.platform,kane_cli_chrome_path:process.env.KANE_CLI_CHROME_PATH??null,skip_browser_download:process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD??null}),new Ne(Ls());let s=_e(),n=await js(),o=Ps(),a=Os({port:n,...e});e.startUrl&&a.push(e.startUrl);let l=Tr(o,a,{stdio:"ignore",detached:!0});l.unref();let i=await new Promise((m,p)=>{l.on("error",h=>{p(new Error(`Failed to launch Chrome: ${h.message}. Is Chrome installed at ${o}?`))}),l.on("close",h=>{h!==null&&h!==0&&p(new Error(`Chrome exited during startup with code ${h}`))}),Us(n).then(m,p)});return{process:l,port:n,cdpEndpoint:i,kill(){try{if(l.pid)if(s==="win32")Tr("taskkill",["/pid",String(l.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-l.pid,"SIGKILL")}catch{l.kill("SIGKILL")}else l.kill("SIGKILL")}catch{}}}}async function Or(e){if(e.cft)return{instance:null,tempDir:null};if(e.wsEndpoint)return{wsEndpoint:e.wsEndpoint,instance:null,tempDir:null};if(e.cdpEndpoint){let n=await D(`${e.cdpEndpoint}/json/version`);if(!n.ok)throw new Error(`CDP endpoint not reachable: ${e.cdpEndpoint} (${n.status})`);return{cdpEndpoint:e.cdpEndpoint,instance:null,tempDir:null}}let t,r=null;if(e.config.chrome_profile_path)t=e.config.chrome_profile_path.replace("~",process.env.HOME??"~");else{r=Fs(Ms($s(),"kane-clean-")),t=r;let n=r;Le("tempDir",()=>{try{Ns(n,{recursive:!0,force:!0})}catch{}})}let s=await Lr({userDataDir:t,width:e.config.window_size.width,height:e.config.window_size.height,startUrl:e.startUrl,headless:e.headless});return{cdpEndpoint:s.cdpEndpoint,instance:s,tempDir:r}}function Dr(e){let t={objective:e.objective,model:e.model,width:e.windowSize.width,height:e.windowSize.height,session_id:e.sessionId,run_index:e.runIndex,stream:!0,max_steps:e.maxSteps??30,headless:e.headless??!1};return e.url&&(t.url=e.url),e.chrome.wsEndpoint?t.ws_endpoint=e.chrome.wsEndpoint:e.chrome.cdpEndpoint&&(t.cdp_endpoint=e.chrome.cdpEndpoint),e.auth.basicAuth?(t.username=e.auth.basicAuth.username,t.access_key=e.auth.basicAuth.access_key):e.auth.token&&(t.auth={type:"bearer",token:e.auth.token}),e.disableAskUser&&(t.disable_ask_user=!0),e.enableTaskSkills&&(t.enable_task_skills=!0),e.variables&&Object.keys(e.variables).length>0&&(t.variables=e.variables),e.globalContext&&(t.global_context=e.globalContext),e.localContext&&(t.local_context=e.localContext),e.sessionContext&&(t.session_context=e.sessionContext),t}import{readdirSync as Bs,readFileSync as Ur,existsSync as Fr}from"fs";import{join as Vs}from"path";function jr(e,t){if(!Fr(e))return{};let r={},s;try{s=Bs(e).filter(n=>n.endsWith(".json")).sort()}catch{return{}}for(let n of s)try{let o=Ur(Vs(e,n),"utf-8"),a=JSON.parse(o);if(a&&typeof a=="object"){for(let[l,i]of Object.entries(a))if(i&&typeof i=="object"&&"value"in i){let m=i;r[l]={value:m.value,secret:m.secret??!1,syntax:m.syntax??`{{${l}}}`}}}}catch{t?t("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:n}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${n}
18
+ `)}return r}function Nr(e){if(!Fr(e))throw new Error(`Variables file not found: ${e}`);let t=Ur(e,"utf-8"),r=JSON.parse(t),s={};if(r&&typeof r=="object"){for(let[n,o]of Object.entries(r))if(o&&typeof o=="object"&&"value"in o){let a=o;s[n]={value:a.value,secret:a.secret??!1,syntax:a.syntax??`{{${n}}}`}}}return s}function Mr(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Invalid --variables JSON")}let r={};if(t&&typeof t=="object"){for(let[s,n]of Object.entries(t))if(n&&typeof n=="object"&&"value"in n){let o=n;r[s]={value:o.value,secret:o.secret??!1,syntax:o.syntax??`{{${s}}}`}}}return r}function $r(e,t,r){let s=jr(e,r),n=jr(t,r);return{...s,...n}}var fe=class{constructor(t){this.baseUrl=t}async pushSecret(t){let r=Te(t.username,t.accessKey),s=await D(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:r,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:t.secretKey,secretValue:t.secretValue,orgId:t.orgId,username:t.username,scope:"user",type:"user",accessKey:t.accessKey})});if(!s.ok)throw new Error(`Push secret failed: ${s.status} ${await s.text()}`)}static extractVariableKeys(t){let r=t.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),s=new Set;for(let n of r)s.add(n[1]);return[...s]}};var he=class extends $t{constructor(t,r,s){super(t,{username:r,accessKey:s})}async upsertVariable(t){let r=t.environmentId??0,s=await D(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:t.name,value:String(t.value),type:"variable",value_type:"string",is_persist:t.isPersist??!1,environment_id:r})});if(s.ok)return{id:(await s.json()).id??0};if(s.status!==409&&s.status!==422)return{id:0};if(!(await D(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(t.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(t.value),value_type:"string",type:"variable",environment_id:r})})).ok)return{id:0};let o=await D(`${this.baseUrl}/v1/variables/${encodeURIComponent(t.name)}?environment_id=${r}`,{method:"GET",headers:this.headers()});return o.ok?{id:(await o.json()).data?.id??0}:{id:0}}};function Br(e,t){if(Object.keys(e).length===0)return{};let r={};for(let[s,n]of Object.entries(e)){let o=n.syntax??`{{${s}}}`;t.includes(o)&&(r[s]=n)}return r}function Vr(e){let t=$r(e.globalDir,e.localDir,e.onLoadError),r=e.file?Nr(e.file):{},s=e.inline?Mr(e.inline):{},n={...t,...r,...s},o=Object.keys(n).length>0,{variables:a,objective:l}=o?de(n,e.objective):{variables:{},objective:e.objective},i=Object.entries(n).filter(([,p])=>p.secret),m=Object.entries(n).filter(([,p])=>!p.secret);return{raw:n,auteur:a,auteurObjective:l,secretEntries:i,nonSecretEntries:m}}async function Hr(e){if(e.localMode)return{};let t=z(e.env);if(e.variables.secretEntries.length>0){let s=new fe(t.secretsBaseUrl);for(let[n,o]of e.variables.secretEntries)s.pushSecret({secretKey:n,secretValue:o.value,username:e.auth.username,accessKey:e.auth.access_key,orgId:e.orgId}).then(()=>e.log("info","SECRET_PUSH_OK","Secret pushed",{key:n})).catch(a=>e.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:n,error:String(a)}))}let r={};if(e.variables.nonSecretEntries.length>0){let s=new he(t.tmsBaseUrl,e.auth.username,e.auth.access_key);for(let[n,o]of e.variables.nonSecretEntries)try{let a=await s.upsertVariable({name:n,value:o.value});r[n]=a.id,e.log("info","VAR_PUSH_OK","Variable pushed",{name:n,id:a.id})}catch(a){e.log("error","VAR_PUSH_FAILED","Variable push failed",{name:n,error:String(a)})}}return r}import{readFileSync as Hs,existsSync as Ks}from"fs";function vt(e){if(!Ks(e))return null;try{return Hs(e,"utf-8").trim()||null}catch{return null}}import{writeFileSync as qs,mkdirSync as Gs}from"fs";import{dirname as Kr}from"path";function St(e){let t=ae(e.sourcePath);try{Gs(Kr(t),{recursive:!0})}catch(s){return process.stderr.write(`
19
+ \u26A0 Failed to create output directory.
20
+ ${s.message}
21
+ Path: ${Kr(t)}
22
+
23
+ `),t}let r={commit_id:e.commitId};e.testId!==void 0&&(r.test_id=e.testId),e.testcaseId!==void 0&&(r.testcase_id=e.testcaseId),e.projectId!==void 0&&(r.project_id=e.projectId),e.folderId!==void 0&&(r.folder_id=e.folderId),e.orgId!==void 0&&(r.org_id=e.orgId),e.sessionName!==void 0&&(r.session_name=e.sessionName),e.plan!==void 0&&(r.plan=e.plan);try{qs(t,JSON.stringify(r,null,2)+`
24
+ `,"utf8")}catch(s){process.stderr.write(`
25
+ \u26A0 Failed to write meta.json.
26
+ ${s.message}
27
+ Path: ${t}
28
+
29
+ `)}return t}var zs=()=>{};async function qr(e,t,r){let s=t.log??zs,n=e.session.testId??null,o=null,a=null,l=null;if(!r.localMode&&t.performUpload)try{o=await t.performUpload(),o?.success&&(o.testId&&(n=o.testId),o.testcaseId&&e.session.setTestcaseId(o.testcaseId))}catch(i){s("error","FINALIZE_UPLOAD_ERROR","Upload pipeline threw",{error:String(i)})}if(t.renderFeedbackPrompt)try{a=await t.renderFeedbackPrompt(),a&&n&&t.submitFeedback&&t.submitFeedback(n,a).catch(i=>{s("error","FINALIZE_FEEDBACK_SUBMIT_ERROR","Feedback submit failed",{error:String(i)})})}catch(i){s("error","FINALIZE_FEEDBACK_RENDER_ERROR","Feedback prompt threw",{error:String(i)})}if(e.session.flushRecorder(),r.skipLocalWrites)s("info","FINALIZE_SKIP_LOCAL_WRITES","Skipping local writes (testmd flow handles via staging)");else if(r.sourcePath&&r.rootSteps&&r.outcomes){try{l=it({sourcePath:r.sourcePath,title:r.title,rootSteps:r.rootSteps,outcomes:r.outcomes,overallStatus:r.overallStatus,startedISO:r.startedISO,durationS:r.durationS,sessionId:e.session.sessionId})}catch(i){s("error","FINALIZE_RESULT_MD_ERROR","_Result.md write failed",{error:String(i)})}try{St({sourcePath:r.sourcePath,commitId:e.session.sessionId,testId:n??void 0,testcaseId:e.session.testcaseId??void 0,projectId:e.tuiConfig.project_id??void 0,folderId:e.tuiConfig.folder_id??void 0,orgId:e.session.orgId??void 0,sessionName:e.session.sessionName??Oe(r.sourcePath),plan:e.session.plan??void 0})}catch(i){s("error","FINALIZE_META_WRITE_ERROR","meta.json write failed",{error:String(i)})}if(o?.codeExportDir)try{let i=e.tuiConfig.code_export?.language??"python";lt(o.codeExportDir,nt(r.sourcePath,"playwright",i))}catch(i){s("error","FINALIZE_CODE_COPY_ERROR","code-export copy failed",{error:String(i)})}}else if(e.session.recorder?.lastWrittenPath){let i=e.session.recorder.lastWrittenPath,m=e.session.getFlows(),p=m.map((b,I)=>({index:I+1,heading:`Step ${I+1}`,headingLine:0,body:{kind:"objective",text:b.objective}})),h=m.map((b,I)=>({rootStepIndex:I+1,status:b.status==="passed"?"passed":b.status==="failed"?"failed":"skipped",duration_s:b.duration,reason:b.reason})),C=h.some(b=>b.status==="failed")?"failed":"passed";try{l=it({sourcePath:i,title:e.session.sessionName??"Session",rootSteps:p,outcomes:h,overallStatus:C,startedISO:e.session.startedAt,durationS:h.reduce((b,I)=>b+(I.duration_s??0),0),sessionId:e.session.sessionId})}catch(b){s("error","FINALIZE_TUI_RESULT_MD_ERROR","TUI _Result.md write failed",{error:String(b)})}try{St({sourcePath:i,commitId:e.session.sessionId,testId:n??void 0,testcaseId:e.session.testcaseId??void 0,sessionName:e.session.sessionName??void 0,projectId:e.tuiConfig.project_id??void 0,folderId:e.tuiConfig.folder_id??void 0,plan:e.session.plan??void 0})}catch(b){s("error","FINALIZE_TUI_META_WRITE_ERROR","TUI meta.json write failed",{error:String(b)})}if(o?.codeExportDir)try{let b=e.tuiConfig.code_export?.language??"python";lt(o.codeExportDir,nt(i,"playwright",b))}catch(b){s("error","FINALIZE_TUI_CODE_COPY_ERROR","TUI code-export copy failed",{error:String(b)})}e.session.recorder.lastCollisionSuffixed&&process.stderr.write(`Saved to ${i} (renamed: ${e.session.sessionName}_test.md already existed)
30
+ `)}try{t.runCleanup?.()}catch(i){s("error","FINALIZE_CLEANUP_ERROR","Cleanup hook threw",{error:String(i)})}try{await e.session.finish("complete")}catch(i){s("error","FINALIZE_SESSION_FINISH_ERROR","session.finish threw",{error:String(i)})}return{uploadResult:o,feedbackChoice:a,resultMdPath:l}}import{readFileSync as zr,writeFileSync as Wr,existsSync as Jr}from"fs";function Gr(e,t,r){if(r.forceAuthor)return"re-recorded from scratch";if(r.retryTriggered)return"re-recorded after retry";if(t.length>0&&t.every(a=>a.kind==="author"&&a.reason==="no-result-md"))return"initial recording";if(t.length>0&&t.every(a=>a.kind==="replay"))return r.wantsPush?"re-recorded (no source changes)":"no changes";let s=[];for(let a=0;a<t.length;a++){let l=t[a];if(!l||l.kind!=="author"||l.reason==="downstream-of-divergence"||l.reason==="no-result-md")continue;let i=Ws(e,e.steps[a]);switch(l.reason){case"structure-mismatch":s.push(`added/removed: ${i}`);break;case"md5-mismatch":s.push(`modified: ${i}`);break;case"missing-recording":s.push(`re-recorded: ${i}`);break;case"recorded-failed":s.push(`re-authored after failure: ${i}`);break}}if(s.length===0)return"automated commit";let n=s.filter((a,l)=>l===0||s[l-1]!==a),o=n.slice(0,3).join("; ");return n.length>3?`${o}; +${n.length-3} more`:o}function Ws(e,t){if(!t)return"unknown step";let r=t.trace[0]?.stepIndex;if(r==null)return"unknown step";let n=e.rootSteps[r-1]?.heading?.trim()??"";return t.trace.length>1?n?`imported step in "${n}"`:`imported step ${r}`:n||`step ${r}`}function Js(e){if(!(!e.shouldReplaceLocalOutput||!e.resolvedTest||!e.sourcePath||!e.stepRunRecords||!e.outcomes||!e.overallStatus))return async()=>{tr({resolvedTest:e.resolvedTest,sessionDir:e.session.sessionDir,stepRunRecords:e.stepRunRecords,outcomes:e.outcomes,overallStatus:e.overallStatus,startedISO:e.startedISO??new Date().toISOString(),durationS:e.durationS??0,sessionId:e.session.sessionId,commitId:e.fromCommitId??"",tmsIds:e.tmsIds??{},codeExportDir:e.codeExportDir}),ot(se(e.sourcePath));let t=new Set;for(let r of e.resolvedTest.steps)if(r.trace.length>1){let s=Se(r.trace);if(t.has(s))continue;t.add(s),Jr(`${s}.staging`)&&ot(s)}}}function Qs(e){if(!(!e.shouldCommit||e.isFirstRun||!e.tmsBaseUrl||!e.testId||!e.fromCommitId||!e.newCommitId||!e.basicAuth||!e.resolvedTest||!e.decisions))return async()=>{let t=Gr(e.resolvedTest,e.decisions,{wantsPush:e.wantsPush??!1,retryTriggered:e.retryTriggered??!1,forceAuthor:e.forceAuthor??!1}),r=e.resolvedTest.steps.map(n=>n.objective).filter(n=>typeof n=="string"&&n.length>0).slice(0,50),s=await br({baseUrl:`${e.tmsBaseUrl}/kane-cli/v1`,testId:e.testId,body:{commitId:e.newCommitId,fromCommitId:e.fromCommitId,commitMessage:t,totalSteps:e.resolvedTest.steps.length,timeTaken:Math.round(e.durationS??0),objectives:r},auth:{username:e.basicAuth.username,accessKey:e.basicAuth.access_key}});if(s.ok&&e.sourcePath){let n=ae(e.sourcePath);try{let o=JSON.parse(zr(n,"utf8"));o.commit_id=e.newCommitId,Wr(n,JSON.stringify(o,null,2)+`
31
+ `,"utf8")}catch(o){process.stderr.write(`warn: failed to update meta.json commit_id: ${o.message}
32
+ `)}}return s}}function Ys(e){if(!(!e.isFirstRun||!e.sourcePath))return async t=>{if(!e.sourcePath)return;let r=ae(e.sourcePath);try{let s=Jr(r)?JSON.parse(zr(r,"utf8")):{};e.session.sessionId&&(s.commit_id=e.session.sessionId),t&&(s.testcase_id=t),e.tmsIds?.testId&&(s.test_id=e.tmsIds.testId),e.tmsIds?.projectId&&(s.project_id=e.tmsIds.projectId),e.tmsIds?.folderId&&(s.folder_id=e.tmsIds.folderId),e.tmsIds?.orgId&&(s.org_id=e.tmsIds.orgId),e.tmsIds?.sessionName&&(s.session_name=e.tmsIds.sessionName),Wr(r,JSON.stringify(s,null,2)+`
33
+ `,"utf8")}catch(s){process.stderr.write(`warn: failed to update meta.json after endTest: ${s.message}
34
+ `)}}}function Qr(e){let t=z(e.env),{session:r,auth:s}=e,n=s.basicAuth?{username:s.basicAuth.username,accessKey:s.basicAuth.access_key}:s.token,o=s.resolvedCreds?.username??s.basicAuth?.username??"",a=s.resolvedCreds?.access_key??s.basicAuth?.access_key??"",l=s.resolvedCreds?.org_id??0,i=s.resolvedCreds?.user_id??0,m=[];for(let I of Object.keys(r.auteurVariables))I.startsWith("secrets.user.")&&m.push({key_name:I.replace("secrets.user.",""),scope:"user"});let h=r.getContext().prior_runs.map(I=>I.status),C=r.auteurVariables,b=Object.keys(C).length>0;return{controllerBaseUrl:t.controllerBaseUrl,tmsBaseUrl:t.tmsBaseUrl,auth:n,authResolver:s.resolver,sessionId:r.sessionId,sessionDir:r.sessionDir,testId:r.testId,commitId:r.sessionId,projectId:e.projectId,folderId:e.folderId,firstObjective:r.firstObjective??"KaneAI Test",firstUrl:r.firstUrl??"",runDirs:r.getRunDirs(),runObjectives:r.getRunObjectives(),runMetadata:r.getRunMetadata(),startedAt:r.startedAt,endedAt:new Date().toISOString(),totalSteps:e.totalSteps,totalDuration:e.totalDuration,runStatuses:h,orgId:l,userId:i,tmsUsername:o,tmsAccessKey:a,screenshotBaseUrl:r.screenshotBaseUrl,screenshotExtMap:e.screenshotExtMap,shareApiBaseUrl:t.shareApiBaseUrl,variables:b?C:void 0,variableIds:e.variableIds,secrets:m,codeExport:e.codeExport,onProgress:e.onProgress,log:e.log,shouldUploadArtifacts:e.shouldUploadArtifacts,shouldReplaceLocalOutput:e.shouldReplaceLocalOutput,shouldCommit:e.shouldCommit,isFirstRun:e.isFirstRun,onAtomicReplace:Js(e),onCommitLock:Qs(e),onFinalizeSuccess:Ys(e)}}var Yr=["python","javascript"];function Zs(e){if(e!==void 0){if(!Yr.includes(e))throw new Error(`--code-language must be one of: ${Yr.join(", ")} (got "${e}")`);return e}}function Zr(e,t){let r=Zs(e.codeLanguage);return{enabled:e.codeExport??t.enabled,language:r??t.language,skipValidation:e.skipCodeValidation??t.skip_validation}}async function Xr(e){try{let r=await new Bt(e.tmsBaseUrl,e.auth.username,e.auth.access_key).createAtmTest({objective:e.objective.slice(0,100),creation_mode:"KANECLI",playground_disabled:e.hasCustomProfile,testURL:e.url,project_id:e.projectId,folder_id:e.folderId,authoring_version:4});return e.log("info","ATM_CREATE_OK","Test created",{test_id:r}),r}catch(t){return e.log("error","ATM_CREATE_FAILED","Test creation failed",{error:t instanceof Error?t.message:String(t)}),null}}var Xs=null,en=()=>Xs??=import("sharp").then(e=>e.default??e).catch(()=>null),$e=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;log;uploadedExt=new Map;constructor(t,r=3,s){this.sas=t,this.maxWorkers=r,this.log=s}updateSas(t){this.sas=t}enqueue(t,r){this.queue.push({operationId:t,buffer:r}),this.pump()}async drain(t=3e4){if(!(this.queue.length===0&&this.activeCount===0))return new Promise(r=>{this.drainResolvers.push(r),setTimeout(()=>{r()},t)})}pump(){for(;this.activeCount<this.maxWorkers&&this.queue.length>0;){let t=this.queue.shift();this.activeCount++,this.processJob(t).finally(()=>{if(this.activeCount--,this.pump(),this.queue.length===0&&this.activeCount===0){for(let r of this.drainResolvers)r();this.drainResolvers=[]}})}}async processJob(t){let r,s="image/webp",n=await en();if(n)try{let i=await n(t.buffer).webp({quality:80}).toBuffer();r=new Uint8Array(i)}catch(i){r=new Uint8Array(t.buffer),s="image/png",this.log?.("warn","SCREENSHOT_CONVERT_FAILED","WebP conversion failed, using PNG",{operation_id:t.operationId,error:i instanceof Error?i.message:String(i)})}else r=new Uint8Array(t.buffer),s="image/png";let o=s==="image/webp"?"webp":"png",a=`test_screenshots/untagged_screenshot/${t.operationId}.${o}`,l=`${this.sas.base_url}/${this.sas.container}/${a}?${this.sas.sas_token}`;for(let i=0;i<=this.maxRetries;i++)try{let m=await D(l,{method:"PUT",headers:{"Content-Type":s,"x-ms-blob-type":"BlockBlob"},body:r});if(m.ok){this.uploadedExt.set(t.operationId,o);return}if(i<this.maxRetries){await this.backoff(i);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed after retries",{operation_id:t.operationId,status:m.status,attempts:this.maxRetries+1})}catch{if(i<this.maxRetries){await this.backoff(i);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed (network error)",{operation_id:t.operationId,error:"network",attempts:this.maxRetries+1})}}backoff(t){let r=t===0?1e3:3e3;return new Promise(s=>setTimeout(s,r))}getExt(t){return this.uploadedExt.get(t)??"png"}getExtMap(){return this.uploadedExt}isNearExpiry(){if(!this.sas.expiry)return!1;let t=new Date(this.sas.expiry).getTime();return Date.now()>t-5*6e4}};var ke=class{config;buffer=[];stepBuffer=new Map;flushTimer=null;currentRunIndex=null;stopped=!1;_droppedBatches=0;_droppedEntries=0;constructor(t){this.config=t}start(){if(this.flushTimer)return;let t=this.config.flushIntervalMs??5e3;this.flushTimer=setInterval(()=>{this.flush().catch(()=>{})},t),this.flushTimer.unref&&this.flushTimer.unref()}setRunIndex(t){this.currentRunIndex=t}log(t,r,s,n={}){if(this.stopped)return;let o=this.buildEntry(t,r,s,n);this.buffer.push(o)}logStep(t,r,s,n={}){if(this.stopped)return;let o=this.buildEntry("debug",r,s,n);o.run_index=t,this.stepBuffer.has(t)||this.stepBuffer.set(t,[]),this.stepBuffer.get(t).push(o)}escalate(t){let r=this.stepBuffer.get(t);r&&r.length>0&&this.buffer.push(...r),this.stepBuffer.delete(t)}discardSteps(t){this.stepBuffer.delete(t)}async flush(){if(this.buffer.length===0)return;let t=this.buffer.splice(0),r=null;try{r=await this.config.getToken()}catch{this.buffer.unshift(...t);return}let s={"Content-Type":"application/json"};r&&(s.Authorization=`Bearer ${r}`);let n=JSON.stringify(t);for(let o=0;o<3;o++){try{let a=new AbortController,l=setTimeout(()=>a.abort(),1e4),i=await D(this.config.proxyUrl,{method:"POST",headers:s,body:n,signal:a.signal});if(clearTimeout(l),i.ok)return}catch{}o<2&&await new Promise(a=>setTimeout(a,1e3*Math.pow(2,o)))}this._droppedBatches++,this._droppedEntries+=t.length}get droppedBatches(){return this._droppedBatches}get droppedEntries(){return this._droppedEntries}async shutdown(){this._droppedBatches>0&&this.log("warn","LOG_DROPS",`Dropped ${this._droppedEntries} entries in ${this._droppedBatches} batches`,{dropped_batches:this._droppedBatches,dropped_entries:this._droppedEntries}),this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush()}shutdownSync(){this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}get bufferSize(){return this.buffer.length}stepBufferSize(t){return this.stepBuffer.get(t)?.length??0}buildEntry(t,r,s,n){return{hostname:"kane-cli",service:"kane-cli",ddsource:"kane-cli",ddtags:`version:${this.config.device.cli_version}`,level:t,event:r,message:s,session_id:this.config.sessionId,run_index:r.startsWith("tcg_")?null:this.currentRunIndex,identity:this.config.identity,device:this.config.device,context:n,timestamp:new Date().toISOString()}}};import{platform as rn,arch as sn}from"os";function Rt(e=process.env){try{let t=e.KANE_CLI_USER_AGENT;return t&&t.trim()?tn(t):e.CLAUDECODE==="1"||e.CLAUDE_CODE_ENTRYPOINT?"claude-code":e.CURSOR_TRACE_ID||e.TERM_PROGRAM==="cursor"?"cursor":e.TERM_PROGRAM==="vscode"||e.VSCODE_PID?"vscode":e.CI==="true"||e.GITHUB_ACTIONS==="true"||e.GITLAB_CI==="true"||e.CIRCLECI==="true"||e.BUILDKITE==="true"?"ci":"unknown"}catch{return"unknown"}}function tn(e){return e.toLowerCase().replace(/[^a-z0-9_-]/g,"-").slice(0,40)}function es(e){let t={proxyUrl:Mt,sessionId:e.sessionId,identity:e.identity,device:{cli_version:Nt,platform:rn(),arch:sn(),host_agent:Rt(),invocation_mode:e.invocationMode},getToken:e.getToken};return new ke(t)}import{execSync as nn}from"child_process";import{readFileSync as on}from"fs";import{createHash as an}from"crypto";import{hostname as ln,platform as cn,arch as un}from"os";var Be=null;function ts(){return Be||(Be=dn(),Be)}function dn(){let e=cn();if(e==="darwin")try{let s=nn("ioreg -rd1 -c IOPlatformExpertDevice",{encoding:"utf-8",timeout:5e3}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(s?.[1])return s[1]}catch{}if(e==="linux")try{let r=on("/etc/machine-id","utf-8").trim();if(r)return r}catch{}let t=`${ln()}:${e}:${un()}`;return an("sha256").update(t).digest("hex").slice(0,32)}async function mn(e){try{let t=z(e.env),s=await new Wt(t.controllerBaseUrl,e.auth).getScreenshotSas();return e.session.setScreenshotSas(s),e.log("info","SCREENSHOT_SAS_OK","Screenshot SAS fetched",{base_url:s.base_url,container:s.container,expiry:s.expiry}),new $e(s,3,e.log)}catch(t){return e.log("warn","SCREENSHOT_SAS_FAIL","Screenshot SAS fetch failed",{error:t instanceof Error?t.message:String(t)}),null}}async function pn(e){if(e.session.hasRemoteLogger||!e.tmsCreds)return null;let t=e.tmsCreds,r=es({sessionId:e.session.sessionId,identity:{org_id:String(t.org_id??""),user_id:String(t.user_id??""),machine_id:ts(),email:t.email??null,email_domain:t.email_domain??"unknown",user_type:t.user_type??"unknown",env:e.env,plan:t.plan??"unknown"},invocationMode:e.invocationMode,getToken:e.getToken});return e.session.setRemoteLogger(r),r.start(),r}async function kt(e){let[t,r]=await Promise.allSettled([e.skipScreenshotQueue?Promise.resolve(null):mn({env:e.env,auth:e.auth,session:e.session,log:e.log}),pn({env:e.env,tmsCreds:e.tmsCreds,getToken:e.getToken,session:e.session,invocationMode:e.invocationMode})]);return{resolver:e.resolver,screenshotQueue:t.status==="fulfilled"?t.value:null,remoteLogger:r.status==="fulfilled"?r.value:null}}async function wt(e){await Promise.allSettled([e.screenshotQueue?.drain(),e.remoteLogger?.shutdown()])}async function Ti(e,t){switch(e.kind){case"boot":{if(t.state.identityServicesRef.current)return t.state.identityServicesRef.current;let r=t.auth.initResolver(e.env);r.prime(e.tmsCreds),t.state.setTmsCredsCache(e.tmsCreds);let s=await It(e.env,e.tmsCreds,r,t);return _t(s,t),s}case"login":case"switch":{let r=t.state.identityServicesRef.current;r&&(await wt(r),r.resolver.revoke()),t.state.identityServicesRef.current=null,t.state.screenshotQueueRef.current=null,t.state.setTmsCredsCache(null);let s=t.auth.initResolver(e.env),n=await s.resolve(!0).catch(()=>null);if(!n)return t.log("warn","IDENTITY_VALIDATE_FAILED","Identity validation failed",{kind:e.kind,env:e.env}),null;t.state.setTmsCredsCache(n);let o=await It(e.env,n,s,t);return _t(o,t),o}case"logout":{let r=t.state.identityServicesRef.current;return r&&(await wt(r),r.resolver.revoke()),t.state.identityServicesRef.current=null,t.state.screenshotQueueRef.current=null,t.state.setTmsCredsCache(null),null}case"resessionize":{let r=t.state.identityServicesRef.current;r&&await wt(r),t.state.identityServicesRef.current=null,t.state.screenshotQueueRef.current=null;let s=t.state.getTmsCredsCache(),n=t.auth.getResolver(),o=n??t.auth.initResolver(e.env);!n&&s&&o.prime(s);let a=await It(e.env,s,o,t);return _t(a,t),a}}}async function It(e,t,r,s){let n=s.auth.getBasicAuth(),o=n?null:await s.auth.getToken(),a=n?{username:n.username,accessKey:n.access_key}:o??null;return a===null?{resolver:r,screenshotQueue:null,remoteLogger:null}:kt({env:e,tmsCreds:t,resolver:r,auth:a,getToken:()=>s.auth.getToken(),session:s.getSession(),log:s.log,skipScreenshotQueue:s.options?.skipScreenshotQueue,invocationMode:"tui"})}function _t(e,t){t.state.identityServicesRef.current=e,t.state.screenshotQueueRef.current=e.screenshotQueue,e.remoteLogger&&(t.exit.registerCleanup("remote-logger",()=>e.remoteLogger.shutdownSync()),t.exit.setExitRemoteLogger(e.remoteLogger))}var He=["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"];async function pa(e,t,r){let{path:s,cwd:n,opts:o,isAgent:a,resolved:l,resolvedAuth:i,cliOverrides:m,environment:p,envConfig:h,profile:C,model:b,creds:I,configStore:R,session:c}=e,x=!1,f=await vn(s,l,o,{resolvedAuth:i,tmsBaseUrl:h.tmsBaseUrl},c.sessionId,r);if(f.abort)return{overallStatus:"failed",exitCode:f.abort.exitCode,outputDir:se(s),durationS:0,uploadResult:null};let P=f.lockAcquired,_=!1,L=!1,J=!1;P&&t.onLockState({phase:"acquired",scope:"preemptive"}),c.start({model:b,environment:p,profile:C}),c.setRecordingEnabled(!1);let M=0,be=i.basicAuth?{username:i.basicAuth.username,accessKey:i.basicAuth.access_key}:i.token??null,ce=null;if(be!==null){let u=await kt({env:p,tmsCreds:i.resolvedCreds??null,resolver:i.resolver,auth:be,getToken:async()=>i.token??null,session:c,log:(d,v,y,g)=>c.log(d,v,y,g),skipScreenshotQueue:!!o.local||!i.basicAuth,invocationMode:a?"agent":"cli"});ce=u.screenshotQueue,u.remoteLogger&&(r.register("remote-logger",()=>u.remoteLogger.shutdownSync()),r.remoteLogger=u.remoteLogger,e.skipGlobalRemoteLogger||Vt(u.remoteLogger))}if(o.name){try{er(o.name)}catch(u){return process.stderr.write(`error: ${u.message}
35
+ `),{overallStatus:"failed",exitCode:2,outputDir:se(s),durationS:0,uploadResult:null}}c.setSessionName(o.name)}let Ge={};for(let[u,d]of Object.entries(l.rootGlobal))He.includes(u)||(Ge[u]=d);for(let[u,d]of Object.entries(m))He.includes(u)||d!==void 0&&(Ge[u]=d);let K={...l.chrome};for(let u of He){let d=m[u];d!==void 0&&(K[u]=d)}let os={...Ge,...K};c.setResolvedGlobal(os);let Ct=I.getActiveProfile()??"default",Et=I.getDefaultEnv(),{rehydrateIfStale:is}=await import("./profile-sync-DTTRRIVP.js");is(I,R,Ct,Et);let B=R.load(),q=B.project_id??null,Ce=B.folder_id??null;if(i.basicAuth){let u=await zt({creds:I,config:R,profile:Ct,env:Et,tmsCreds:i.basicAuth,isLocal:!!o.local,log:(d,v,y,g)=>c.log(d,v,y,g),onAnnounce:e.onAnnounce});if(u.status==="ok")q=u.projectId,Ce=u.folderId,B=R.load(),a&&u.autoDefaulted&&process.stdout.write(Gt(u.autoDefaulted));else if(u.status==="cancelled"){process.stderr.write(`error: project/folder configuration failed. See remediation above, or use --local.
36
+ `);let{shutdown:d}=await import("./exit-manager-V2NW7A7U.js");return d(2,"project/folder gate failed"),{}}}let Q;try{Q=await Or({config:{chrome_profile_path:K.chrome_profile??null,window_size:{width:1920,height:1080}},startUrl:ue,headless:K.headless??!1,wsEndpoint:K.ws_endpoint,cdpEndpoint:K.cdp_endpoint})}catch(u){return process.stderr.write(`error: Chrome launch failed: ${u.message}
37
+ `),await c.finish("complete"),{overallStatus:"failed",exitCode:2,outputDir:se(s),durationS:0,uploadResult:null}}let Ee=Q.instance;Ee&&r.register("chrome",()=>{try{Ee.kill()}catch{}});let F=null,At=Q.cdpEndpoint??K.cdp_endpoint;if(At&&!K.ws_endpoint&&!K.headless)try{F=Ar({headless:K.headless??!1,cdpEndpoint:At,chromePid:Ee?.process.pid}),F&&r.register("marker-overlay",()=>F.kill())}catch(u){c.log("warn","OVERLAY_SPAWN_FAILED","Marker overlay spawn failed",{error:String(u)})}i.resolvedCreds?.org_id!==void 0&&c.setOrgId(String(i.resolvedCreds.org_id));let ne=Vr({objective:"",globalDir:Ve(Xe,"variables"),localDir:Ve(n,".testmuai","variables"),file:o.variablesFile,inline:o.variables}),as=l.rootGlobal.variables??{},V=gn(ne.raw,as);c.setAuteurVariables(V.auteur);let xt=vt(Ve(Xe,"global-memory.md"))??void 0,Pt=vt(Ve(n,".testmuai","context.md"))??void 0;o.local?process.stderr.write(`info: --local \u2014 KaneAI upload skipped
38
+ `):i.basicAuth?q||process.stderr.write(`warn: KaneAI upload skipped \u2014 no project configured.
39
+ `):process.stderr.write(`warn: KaneAI upload skipped \u2014 TMS credentials could not be resolved.
40
+ Run 'kane-cli login' (OAuth) or 'kane-cli config set-username/set-access-key' (basic auth).
41
+ `);let ye=!o.local&&!!i.basicAuth&&q!=null;if(c.log("info","PIPELINE_GATE_STATE","Initial gate state (run-start)",{phase:"run-start",shouldUploadArtifacts:ye,lockHeld:P,isFirstRun:f.isFirstRun,hasAuth:f.hasAuth}),ye&&f.testId==null){let u=z(p);try{let d=await Xr({tmsBaseUrl:u.tmsBaseUrl,auth:i.basicAuth,objective:l.steps[0].objective,url:"",projectId:q,folderId:Ce??"",hasCustomProfile:!!K.chrome_profile,log:(v,y,g,S)=>c.log(v,y,g,S)});d&&c.setTestId(d)}catch(d){process.stderr.write(`warn: ATM test creation failed: ${d.message}
42
+ `)}}else f.testId&&c.setTestId(f.testId);let Ae={};if(i.basicAuth&&!o.local&&(V.secretEntries.length>0||V.nonSecretEntries.length>0))try{Ae=await Hr({variables:V,auth:i.basicAuth,orgId:String(i.resolvedCreds?.org_id??""),env:p,localMode:!!o.local,log:(u,d,v,y)=>c.log(u,d,v,y)})}catch(u){process.stderr.write(`warn: variable/secret push failed: ${u.message}
43
+ `)}let ze=new Map;for(let[u,d]of V.nonSecretEntries)ze.set(u,d.value);let We=new Map;for(let[u,d]of V.secretEntries)We.set(u,d.value);async function Je(u){if(!i.basicAuth||o.local)return;let d=[],v=[];for(let[g,S]of Object.entries(u))if(S.secret){if(We.get(g)===S.value)continue;v.push([g,S])}else{if(ze.get(g)===S.value)continue;d.push([g,S])}if(d.length===0&&v.length===0)return;let y=z(p);if(d.length>0){let g=new he(y.tmsBaseUrl,i.basicAuth.username,i.basicAuth.access_key);for(let[S,w]of d)try{let E=await g.upsertVariable({name:S,value:w.value});Ae[S]=E.id,ze.set(S,w.value),c.log("info","VAR_PUSH_STEP","Variable updated mid-run",{name:S})}catch(E){c.log("warn","VAR_PUSH_STEP_FAILED","Mid-run variable push failed",{name:S,error:String(E)})}}if(v.length>0){let g=new fe(y.secretsBaseUrl);for(let[S,w]of v)try{await g.pushSecret({secretKey:S,secretValue:w.value,username:i.basicAuth.username,accessKey:i.basicAuth.access_key,orgId:String(i.resolvedCreds?.org_id??"")}),We.set(S,w.value),c.log("info","SECRET_PUSH_STEP","Secret updated mid-run",{name:S})}catch(E){c.log("warn","SECRET_PUSH_STEP_FAILED","Mid-run secret push failed",{name:S,error:String(E)})}}}let ve=ce?(u,d,v)=>{if(!(P||f.isFirstRun))return;let y=M+d;_r(c.sessionDir,y,u,ce,(g,S,w,E)=>c.log(g,S,w,E),v)}:void 0,Tt=l.rootTitle??l.rootSteps[0]?.heading??fn(s),ls=Object.keys(V.raw).length>0?de(V.raw,Tt).objective:Tt;c.setFirstRun(ls,ue);let te=new Fe(l),Qe=new Date().toISOString(),cs=Date.now(),us=typeof o.maxSteps=="string"&&o.maxSteps!==""?parseInt(o.maxSteps,10):void 0;function Lt(u,d){let v=l.steps[u],y=ss(v.config,m),g=ge(ne.raw,y.variables,v.objective);return Dr({objective:g.objective,url:u===0?ue:void 0,model:b,chrome:Q,auth:i,sessionId:c.sessionId,runIndex:d,windowSize:{width:1920,height:1080},maxSteps:y.max_steps??us??30,headless:K.headless??!1,variables:Object.keys(g.variables).length>0?g.variables:void 0,globalContext:y.global_context??xt,localContext:y.local_context??Pt,sessionContext:c.getContext()})}function Ot(u){let v=l.steps[u].trace[0].stepIndex,y=l.rootSteps.find(S=>S.index===v);l.steps.slice(0,u).some(S=>S.trace[0].stepIndex===v)||t.onAgentEvent({type:"test_md_step_start",step_index:v,heading:y.heading,ref:y.body.kind==="import_ref"?{kind:"import",label:y.body.path}:null})}function Ye(u,d,v,y,g,S){let w=l.steps[u],E=w.trace[0].stepIndex,W=!l.steps.slice(u+1).some(O=>O.trace[0].stepIndex===E),G=v?.status==="passed"?"passed":"failed",U=v?.reason??g??void 0,H=v?.duration??S,{continueOverall:$}=te.recordStep(w,{status:G,duration_s:H,reason:U}),Y=ss(w.config,m),Z=ge(ne.raw,Y.variables,w.objective).objective;if(v){let O=kr(v,d,y);c.addRunResult(Cr(v,Z,d,O),v.total_runs)}else c.addRunResult({index:d,objective:Z,status:G,summary:"",context:{memory:{},variables:{},pointer:""}},1);if(W||!$){let O=te.snapshotOutcomes().find(k=>k.rootStepIndex===E);t.onAgentEvent({type:"test_md_step_end",step_index:E,status:O.status,duration_s:O.duration_s??0,ref_kind:O.refKind??null,inlined_count:O.inlinedCount??null,failed_sub_step_index:O.failedSubStepIndex??null})}return $}async function ds(u){lr(u,l.steps.length);for(let d=0;d<u;d++){if(x)return{failedAt:d,cancelled:!0};let v=l.steps[d],y=f.decisions[d];if(y.kind!=="replay")return process.stderr.write(`error: runReplayPhase invoked on a non-replay decision at step ${d}
44
+ `),{failedAt:d,cancelled:!1};let g=c.nextRunIndex();M=g;let S=d===0?ue:void 0,w={width:B.window_size.width,height:B.window_size.height},E=ge(ne.raw,v.config.variables,v.objective),W=dt({step:v,decision:y,chrome:Q,auth:i,sessionId:c.sessionId,runIndex:g,sessionDir:c.sessionDir,windowSize:w,forceNavigateUrl:S,sessionContext:c.getContext(),variables:Object.keys(E.variables).length>0?E.variables:void 0});await Je(E.raw),Ot(d);let G=Date.now(),U=null,H=null;try{let O=st(W,{environment:p});r.register("runner",()=>{rt()&&(x=!0);try{O.cancel()}catch{}}),F?.setRunActive(!0);try{for await(let k of O.events){if(t.onAgentEvent(k),k.type==="step_event"&&k.event==="reasoning"?F?.setStepText(k.detail):k.type==="step_end"&&(k.status==="passed"&&F?.setStepComplete(),ve&&ve(k.index,0,k.child_id)),k.type==="run_end"){U=k;break}if(k.type==="error"){H=k.message??"runner error";break}}try{O.cancel()}catch{}if(!U&&!H){let{code:k}=await O.exited;k!==0&&(H=`runner exited with code ${k}`)}}finally{F?.setRunActive(!1),r.cleanup("runner","Replay step complete")}}catch(O){H=O.message}if(x)return{failedAt:d,cancelled:!0};let $=Math.round((Date.now()-G)/1e3),Y=Ye(d,g,U,null,H,$);c.recordStepRun({testmdStepIndex:l.steps[d].flatIndex,runIndex:g,totalRunDirs:1});let Z=!!H||U?.status==="failed";if(cr(d,Z?"failed":"ok"),Z||!Y)return{failedAt:d,cancelled:!1}}return{failedAt:null,cancelled:!1}}let Dt=async()=>{if(P)return!0;let u=i.basicAuth;if(!u){let g=await i.resolver.resolve(!0);g?.username&&g?.access_key&&(u={username:g.username,access_key:g.access_key},i.basicAuth=u)}if(!f.testId||!f.fromCommitId||!u)return process.stderr.write(`error: cannot acquire lock \u2014 missing required state
45
+ `),!1;let d=c.sessionId,v=o.onLockConflict??l.rootGlobal.on_lock_conflict??"readonly",y=await ns({tmsBaseUrl:h.tmsBaseUrl,testId:f.testId,fromCommitId:f.fromCommitId,newCommitId:d,basicAuth:u,onLockConflict:v});return y==="ok"?(P=!0,f.newCommitId=d,c.log("info","MID_RUN_LOCK_ACQUIRED","Mid-run lock acquired",{test_id:f.testId}),a&&t.onLockState({phase:"acquired",scope:"mid_run"}),ht({baseUrl:Ke(h.tmsBaseUrl),testId:f.testId,auth:qe(u),lifecycle:r}),!0):(c.log("error","MID_RUN_LOCK_CONFLICT","Mid-run lock acquisition failed",{reason:y}),a&&t.onLockState({phase:"conflict",scope:"mid_run",reason:y}),process.stderr.write(`error: mid-run lock acquisition failed (${y})
46
+ `),!1)};if(a){let u=o.author===!0;u&&(ut(),c.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let{authorBoundary:d,cancelledInPhase:v,shrinkCount:y}=await pr({decisions:f.decisions,forceAuthor:u,hasRetry:o.retry===!0||o.retryCount!==void 0,maxShrinks:o.retryCount!==void 0?parseInt(o.retryCount,10):Re.maxShrinks,runReplayPhase:ds,session:c,accumulator:te,acquireLockIfNeeded:Dt});if(J=y>0,y>0&&(c.log("info","RETRY_TRIGGERED","Retry loop triggered",{shrink_count:y,final_author_boundary:d}),t.onRetryAttempt({shrink_count:y,final_author_boundary:d,complete_reauthor:d===0})),d===0&&y>0&&c.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback",{shrink_count:y}),!v&&d>=0)for(let g=d;g<l.steps.length;g++){let S=l.steps[g];if(!te.shouldRunFlatStep(S))continue;Ot(g),_=!0;let w=c.nextRunIndex();M=w,await Je(ge(ne.raw,S.config.variables,S.objective).raw);let E=Lt(g,w),W=Date.now(),G=null,U=null,H=null,$=!1,Y=0;try{let k=st(E,{environment:p});r.register("runner",()=>{rt()&&(x=!0);try{k.cancel()}catch{}}),F?.setRunActive(!0);try{for await(let T of k.events){if(t.onAgentEvent(T),T.type==="bifurcation"){let A=T.count??T.flows?.length??0;(T.is_single_flow??A<=1)||(H=T.flows??null,$=!0,Y=0)}else if(T.type==="run_start"&&$)Y++;else if(T.type==="step_event"&&T.event==="reasoning")F?.setStepText(T.detail);else if(T.type==="step_end"&&(T.status==="passed"&&F?.setStepComplete(),ve)){let A=$?Math.max(0,Y-1):0;ve(T.index,A,T.child_id)}if(T.type==="run_end"){G=T;break}if(T.type==="error"){U=T.message??"runner error";break}}try{k.cancel()}catch{}}finally{F?.setRunActive(!1),r.cleanup("runner","Step complete")}}catch(k){U=k.message}let Z=Math.round((Date.now()-W)/1e3),O=Ye(g,w,G,H,U,Z);if(c.recordStepRun({testmdStepIndex:l.steps[g].flatIndex,runIndex:w,totalRunDirs:G?.total_runs??1}),!O||x)break}}else{let{effectiveDecisions:u}=await import("./effective-decisions-DRM3JSR4.js"),{decideRetry:d}=await import("./replay-policy-6USQBT3E.js"),v=o.retry===!0||o.retryCount!==void 0,y=o.retryCount!==void 0?parseInt(o.retryCount,10):Re.maxShrinks,g=o.author===!0;g&&(ut(),c.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let S=g?0:je(f.decisions),w=0,E=null,W=f.decisions.filter($=>$.kind==="replay").length,G=f.decisions.length-W,U=[];o.push&&U.push("--push"),v&&U.push("--retry"),o.retryCount!==void 0&&U.push(`--retry-count=${o.retryCount}`),g&&U.push("--author");let H={source:s,steps:{total:f.decisions.length,replay:W,author:G},model:b,viewport:{width:B.window_size.width,height:B.window_size.height},chrome:Q.cdpEndpoint??Q.wsEndpoint??"managed",session:c.sessionName??"ephemeral",variables:{count:Object.keys(V.raw).length,secrets:Object.values(V.raw).filter($=>$.secret).length,names:Object.keys(V.raw)},flags:U,mode:m.mode??"testing"};for(;;){let $=c.snapshot(),Y=te.snapshot(),Z=u(f.decisions,S,g);if(w>=1){let A=S===0?`\u21BB Complete re-author \u2014 retry budget exhausted (${w}/${y})`:`\u21BB Retry ${w}/${y} \u2014 replay 0..${S-1}, author ${S}..${f.decisions.length-1}
47
+ reason: replay miss at step ${(E??0)+1}`;process.stderr.write(A+`
48
+ `)}let O=w>=1&&S>0&&E!==null?{startIdx:0,endIdx:E,count:E}:void 0;F?.setRunActive(!0);let k=await wn({decisions:Z,resolved:l,session:c,accumulator:te,tuiConfig:B,globalConfig:H,buildStepConfigAt:Lt,buildReplayConfig:A=>{let X=f.decisions[A];if(X.kind!=="replay")throw new Error("expected replay decision at index "+A);let re=l.steps[A];return dt({step:re,decision:X,chrome:Q,auth:i,sessionId:c.sessionId,runIndex:c.nextRunIndex(),sessionDir:c.sessionDir,windowSize:{width:B.window_size.width,height:B.window_size.height},forceNavigateUrl:A===0?ue:void 0,sessionContext:c.getContext(),variables:bn(ne.raw,re.config.variables,re.objective)})},onAnyAuthorStep:()=>{_=!0},onCancel:()=>{L=!0},topBannerModel:b,topBannerAuth:`${I.getActiveProfile()??"no profile"}/${p}`,spawnOpts:{environment:p,mode:m.mode??"testing",log:(A,X,re,Ze)=>c.log(A,X,re,Ze)},priorAttemptRollup:O,pushStepLevelDelta:(A,X)=>Je(ge(ne.raw,A,X).raw),onSequencerStepEnd:(A,X,re,Ze)=>{let fs=Math.round((Date.now()-Ze)/1e3),hs=A.hadError?A.reason??"runner error":null,gs=Ye(X,re,A.runEnd,A.bifurcationFlows??null,hs,fs);return c.recordStepRun({testmdStepIndex:l.steps[X].flatIndex,runIndex:re,totalRunDirs:A.runEnd?.total_runs??A.bifurcationFlows?.length??1}),gs},screenshotDispatcher:ve,onReasoning:A=>F?.setStepText(A),onStepComplete:()=>F?.setStepComplete(),onSpawnStart:A=>{M=A},host:t});if(F?.setRunActive(!1),k.cancelled){r.cleanup("marker-overlay","user cancelled run"),r.cleanup("chrome","user cancelled run");break}if(k.failedAt===null)break;let T=d({failedAt:k.failedAt,shrinkCount:w,hasRetry:v,maxShrinks:y});if(T.kind==="fail"||!P&&!await Dt())break;c.rollback($),te.rollback(Y),T.kind==="complete-reauthor"?S=0:S=T.newAuthorBoundary,w++,J=!0,c.log("info","RETRY_TRIGGERED","Retry loop triggered (TTY)",{shrink_count:w,failed_at:E}),S===0&&c.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback (TTY)",{shrink_count:w}),E=k.failedAt}}let N=te.finalize(),oe=Math.round((Date.now()-cs)/1e3),ms={session:c,resolvedAuth:i,chromeResult:Q,chromeInstance:Ee??null,testId:c.testId??null,preparedVariables:V,variableIds:Ae,globalContext:xt,localContext:Pt,tuiConfig:B,env:p,localMode:!!o.local},ie=await qr(ms,{performUpload:async()=>{if(!i.basicAuth)return null;let u=z(p),d=(_||o.push===!0)&&!L,v=(P||f.isFirstRun)&&!L&&N.overallStatus==="passed",y=ye&&(P||f.isFirstRun);c.log("info","PIPELINE_GATE_STATE","Derived gate state (finalize)",{phase:"finalize",shouldUploadArtifacts:ye,shouldUploadPipeline:y,shouldReplaceLocalOutput:d,shouldCommit:v,lockHeld:P,anyAuthorStepRan:_,cancelled:L,overallStatus:N.overallStatus});let g=Qr({session:c,env:p,auth:i,variables:V,variableIds:Ae,projectId:q,folderId:Ce,totalSteps:N.outcomes.length,totalDuration:oe,screenshotExtMap:ce?.getExtMap(),codeExport:Zr({codeExport:o.codeExport,codeLanguage:o.codeLanguage,skipCodeValidation:o.skipCodeValidation},B.code_export),onProgress:()=>{},log:(w,E,W,G)=>c.log(w,E,W,G),shouldUploadArtifacts:y,shouldReplaceLocalOutput:d,shouldCommit:v,isFirstRun:f.isFirstRun,resolvedTest:l,sourcePath:s,stepRunRecords:c.getStepRunRecords(),outcomes:N.outcomes,overallStatus:N.overallStatus,fromCommitId:f.fromCommitId,startedISO:Qe,durationS:oe,tmsIds:{testId:f.testId??c.testId??void 0,testcaseId:f.testcaseId??c.testcaseId??void 0,projectId:q??void 0,folderId:Ce??void 0,orgId:c.orgId??void 0,sessionName:c.sessionName??Oe(s)},tmsBaseUrl:h.tmsBaseUrl,testId:f.testId??void 0,newCommitId:f.newCommitId??void 0,basicAuth:i.basicAuth??void 0,decisions:f.decisions,wantsPush:o.push===!0,retryTriggered:J,forceAuthor:o.author===!0});f.newCommitId!=null&&(g.skipTmsFinalize=!0);let S=new rr(g);return a?await S.execute():await t.runUpload(S,w=>{if(w.testcaseId&&w.shareId&&q)return bt(u.testManagerUiUrl,q,w.testcaseId,w.shareId)})},runCleanup:()=>{r.cleanup("chrome","test.md run complete")},log:(u,d,v,y)=>c.log(u,d,v,y)},{overallStatus:N.overallStatus,outcomes:N.outcomes,sourcePath:s,title:l.rootTitle,rootSteps:l.rootSteps,startedISO:Qe,durationS:oe,localMode:!!o.local,skipLocalWrites:!0});await Sn(s,f,c,N.outcomes,N.overallStatus,Qe,oe,ie.uploadResult,B,o,{resolvedAuth:i,tmsBaseUrl:h.tmsBaseUrl},P);let jt=z(p),xe=ie.uploadResult?.testcaseId,Pe=xe&&ie.uploadResult?.shareId&&q?bt(jt.testManagerUiUrl,q,xe,ie.uploadResult.shareId):void 0,Ut={overallStatus:N.overallStatus,durationS:oe,decisions:f.decisions,outcomes:N.outcomes,cancelled:L,retryTriggered:J,lockHeld:P,anyAuthorStepRan:_,isFirstRun:f.isFirstRun,wantsPush:o.push===!0,uploadResult:ie.uploadResult,shouldUploadArtifacts:ye,shouldReplaceLocalOutput:_&&!L,shouldCommit:(P||f.isFirstRun)&&!L&&N.overallStatus==="passed",shareUrl:Pe},{buildSummaryEvent:ps}=await import("./SummaryBox-7ZK2A6MA.js");if(a?t.onAgentEvent(ps(Ut)):await t.onSummary(Ut),!a){let u=xe&&q?Pr(jt.testManagerUiUrl,q,xe):void 0;await t.onLinks({recordedTestPath:s,outputDir:se(s),shareableLink:Pe,testCaseLink:u,codeExportDir:ie.uploadResult?.codeExportDir})}return t.onAgentEvent({type:"test_md_done",overall_status:N.overallStatus,duration_s:oe,session_id:c.sessionId,...Pe?{share_url:Pe}:{}}),{overallStatus:N.overallStatus,exitCode:N.overallStatus==="passed"?0:1,outputDir:se(s),durationS:oe,uploadResult:ie.uploadResult}}function gn(e,t){let r={...e,...t},s=Object.keys(r).length>0?de(r,""):{variables:{},objective:"",keyMap:{}};return{raw:r,auteur:s.variables,auteurObjective:"",secretEntries:Object.entries(r).filter(([,n])=>n.secret),nonSecretEntries:Object.entries(r).filter(([,n])=>!n.secret)}}function ge(e,t,r){let s={...e,...t??{}};if(Object.keys(s).length===0)return{raw:s,variables:{},objective:r};let n=de(s,r);return{raw:s,variables:Br(n.variables,n.objective),objective:n.objective}}function bn(e,t,r){let s=ge(e,t,r).variables;return Object.keys(s).length>0?s:void 0}function ss(e,t){let r=new Set(He),s={...e};for(let[n,o]of Object.entries(t))r.has(n)||n!=="variables"&&o!==void 0&&e[n]===void 0&&(s[n]=o);return s}function yn(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}async function vn(e,t,r,s,n,o){let a=Qt(e),l=nr(t,rs(a)?a:null);ar(t,l);let i=ae(e),m=rs(i)?JSON.parse(hn(i,"utf8")):null,p=m?.testcase_id,h=m?.test_id,C=m?.commit_id,b=r.push===!0,I=r.retry===!0||r.retryCount!==void 0,R=r.author===!0;b&&!p&&process.stderr.write(`[--push] no meta.json yet \u2014 flag is a no-op on first run
49
+ `),R&&(p=void 0,h=void 0,C=void 0);let c=s.resolvedAuth.basicAuth;if(!c){let M=await s.resolvedAuth.resolver.resolve(!0);M?.username&&M?.access_key&&(c={username:M.username,access_key:M.access_key},s.resolvedAuth.basicAuth=c)}let x=!!c,f=!r.local&&x&&h!=null&&C!=null&&p!=null,P=f&&(or(l)||b);if(b&&!f)return process.stderr.write(`error: --push requires authenticated credentials for the lock API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
50
+ `),{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};if(I&&!f)return process.stderr.write(`error: --retry requires authenticated credentials for the lock API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
51
+ `),{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};if(R&&!x)return process.stderr.write(`error: --author requires authenticated credentials for the TMS API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
52
+ `),{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};let _=null,L=!1;if(P){_=n;let J=r.onLockConflict??t.rootGlobal.on_lock_conflict??"readonly",M=await ns({tmsBaseUrl:s.tmsBaseUrl,testId:h,fromCommitId:C,newCommitId:_,basicAuth:c,onLockConflict:J});if(M==="ok")L=!0,ht({baseUrl:Ke(s.tmsBaseUrl),testId:h,auth:qe(c),lifecycle:o});else{if(M==="abort")return{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};_=null}}return{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:_,isFirstRun:p==null,hasAuth:x,canLock:f,lockAcquired:L}}function Ke(e){return`${e}/kane-cli/v1`}function qe(e){return{username:e.username,accessKey:e.access_key}}async function ns(e){let t=Ke(e.tmsBaseUrl),r=qe(e.basicAuth),s={baseUrl:t,testId:e.testId,fromCommitId:e.fromCommitId,newCommitId:e.newCommitId,auth:r},n=await pt(s);if(n.ok)return"ok";if(!(n.reason==="concurrent"||n.reason==="base_mismatch"))return process.stderr.write(`[lock] acquire failed: ${n.reason} (HTTP ${n.httpStatus}): ${n.message}
53
+ `),"abort";let a=n.reason==="concurrent"?"concurrent session":"base commit mismatch (pull latest)";if(e.onLockConflict==="fail")return process.stderr.write(`[lock] ${a}; aborting (--on-lock-conflict fail)
54
+ `),"abort";if(e.onLockConflict==="wait"){if(n.reason==="base_mismatch")return process.stderr.write(`[lock] base commit mismatch \u2014 pull latest; aborting
55
+ `),"abort";for(;;){process.stderr.write(`[lock] waiting (concurrent session)...
56
+ `),await new Promise(i=>setTimeout(i,3e4));let l=await pt(s);if(l.ok)return"ok";if(l.reason!=="concurrent")return process.stderr.write(`[lock] wait drifted to ${l.reason} (HTTP ${l.httpStatus}): ${l.message}; aborting
57
+ `),"abort"}}return process.stderr.write(`[lock] ${a} \u2014 running in readonly mode (no commit)
58
+ `),"readonly"}async function Sn(e,t,r,s,n,o,a,l,i,m,p,h){let{decisions:C,testId:b,testcaseId:I,fromCommitId:R,newCommitId:c}=t;if(!(n==="passed")&&h&&b&&R&&c){process.stderr.write(`[lock] run failed (${n}); discarding new commit
59
+ `),await Rn(p,b,R,c),gt();return}gt()}async function Rn(e,t,r,s){let n=e.resolvedAuth.basicAuth;if(!n){let a=await e.resolvedAuth.resolver.resolve(!0);a?.username&&a?.access_key&&(n={username:a.username,access_key:a.access_key},e.resolvedAuth.basicAuth=n)}if(!n)return;let o=await yr({baseUrl:Ke(e.tmsBaseUrl),testId:t,body:{commitId:s,fromCommitId:r},auth:qe(n)});o.ok||process.stderr.write(`warn: discardLock failed: ${o.reason} (HTTP ${o.httpStatus}): ${o.message}
60
+ `)}async function wn(e){let t=null,r=!1,s=0,n=-1,o=-1,a=0,l=async i=>{if(i&&i.status==="failed")return s>0&&e.decisions[s-1].kind==="replay"&&(t=s-1),null;for(;s<e.decisions.length&&!e.accumulator.shouldRunFlatStep(e.resolved.steps[s]);)s++;if(s>=e.decisions.length)return null;let m=e.decisions[s],p=e.resolved.steps[s],h=s;s++;let C=e.session.nextRunIndex();n=h,o=C,a=Date.now(),e.onSpawnStart?.(C),m.kind==="author"&&e.onAnyAuthorStep(),await e.pushStepLevelDelta(p.config.variables,p.objective);let b=m.kind==="replay"?e.buildReplayConfig(h):e.buildStepConfigAt(h,C),I=m.kind==="replay"?"md5-match":m.reason,R=p.config??{},c={};for(let[x,f]of Object.entries(R))f!=null&&x!=="variables"&&(c[x]=f);return{config:b,banner:{stepLabel:`Step ${h+1}/${e.decisions.length}`,objective:yn(p.objective,100)},mode:m.kind,modeReason:I,perStepOverrides:Object.keys(c).length>0?c:void 0}};return await e.host.runSteps({topBanner:{model:e.topBannerModel,auth:e.topBannerAuth},globalConfig:e.globalConfig,getNextStep:l,onStepEnd:i=>(i.status==="failed"&&n>=0&&e.decisions[n]?.kind==="replay"&&(t=n),e.onSequencerStepEnd(i,n,o,a)),onAllComplete:()=>{},onCancel:()=>{r=!0,e.onCancel()},spawnOpts:e.spawnOpts,priorAttemptRollup:e.priorAttemptRollup,screenshotDispatcher:e.screenshotDispatcher,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete}),{failedAt:t,cancelled:r}}export{kr as a,Cr as b,Ne as c,fo as d,Lr as e,Ar as f,_r as g,bt as h,Pr as i,Or as j,Dr as k,Br as l,Vr as m,Hr as n,vt as o,Qr as p,Zr as q,Xr as r,kt as s,Ti as t,pa as u,gn as v,ge as w,bn as x,ss as y};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as Oc,b as Ic}from"./chunk-MDBXYXSC.js";import{a as Ac}from"./chunk-WAOCHXJ5.js";import{a as Rc}from"./chunk-7CLUJYMW.js";import{a as Tc}from"./chunk-NLCCBXXV.js";import{a as Xt}from"./chunk-RZ4F3BHX.js";import{a as P,b as QE,c as g,d as XE,e as JE,f as ev}from"./chunk-UR6MHSHU.js";var qc=g((XB,Fc)=>{"use strict";var fv=typeof process=="object"&&process&&process.platform==="win32";Fc.exports=fv?{sep:"\\"}:{sep:"/"}});var zc=g((JB,Wc)=>{"use strict";Wc.exports=Bc;function Bc(t,e,r){t instanceof RegExp&&(t=jc(t,r)),e instanceof RegExp&&(e=jc(e,r));var i=Uc(t,e,r);return i&&{start:i[0],end:i[1],pre:r.slice(0,i[0]),body:r.slice(i[0]+t.length,i[1]),post:r.slice(i[1]+e.length)}}function jc(t,e){var r=e.match(t);return r?r[0]:null}Bc.range=Uc;function Uc(t,e,r){var i,n,s,o,a,l=r.indexOf(t),u=r.indexOf(e,l+1),f=l;if(l>=0&&u>0){if(t===e)return[l,u];for(i=[],s=r.length;f>=0&&!a;)f==l?(i.push(f),l=r.indexOf(t,f+1)):i.length==1?a=[i.pop(),u]:(n=i.pop(),n<s&&(s=n,o=u),u=r.indexOf(e,f+1)),f=l<u&&l>=0?l:u;i.length&&(a=[s,o])}return a}});var oa=g((e3,Zc)=>{"use strict";var Gc=zc();Zc.exports=dv;var $c="\0SLASH"+Math.random()+"\0",Hc="\0OPEN"+Math.random()+"\0",sa="\0CLOSE"+Math.random()+"\0",Vc="\0COMMA"+Math.random()+"\0",Yc="\0PERIOD"+Math.random()+"\0";function na(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function cv(t){return t.split("\\\\").join($c).split("\\{").join(Hc).split("\\}").join(sa).split("\\,").join(Vc).split("\\.").join(Yc)}function hv(t){return t.split($c).join("\\").split(Hc).join("{").split(sa).join("}").split(Vc).join(",").split(Yc).join(".")}function Kc(t){if(!t)return[""];var e=[],r=Gc("{","}",t);if(!r)return t.split(",");var i=r.pre,n=r.body,s=r.post,o=i.split(",");o[o.length-1]+="{"+n+"}";var a=Kc(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function dv(t){return t?(t.substr(0,2)==="{}"&&(t="\\{\\}"+t.substr(2)),_i(cv(t),!0).map(hv)):[]}function pv(t){return"{"+t+"}"}function gv(t){return/^-?0\d/.test(t)}function _v(t,e){return t<=e}function yv(t,e){return t>=e}function _i(t,e){var r=[],i=Gc("{","}",t);if(!i)return[t];var n=i.pre,s=i.post.length?_i(i.post,!1):[""];if(/\$$/.test(i.pre))for(var o=0;o<s.length;o++){var a=n+"{"+i.body+"}"+s[o];r.push(a)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),f=l||u,c=i.body.indexOf(",")>=0;if(!f&&!c)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+sa+i.post,_i(t)):[t];var h;if(f)h=i.body.split(/\.\./);else if(h=Kc(i.body),h.length===1&&(h=_i(h[0],!1).map(pv),h.length===1))return s.map(function(R){return i.pre+h[0]+R});var d;if(f){var m=na(h[0]),p=na(h[1]),S=Math.max(h[0].length,h[1].length),y=h.length==3?Math.max(Math.abs(na(h[2])),1):1,b=_v,v=p<m;v&&(y*=-1,b=yv);var E=h.some(gv);d=[];for(var T=m;b(T,p);T+=y){var D;if(u)D=String.fromCharCode(T),D==="\\"&&(D="");else if(D=String(T),E){var x=S-D.length;if(x>0){var O=new Array(x+1).join("0");T<0?D="-"+O+D.slice(1):D=O+D}}d.push(D)}}else{d=[];for(var w=0;w<h.length;w++)d.push.apply(d,_i(h[w],!1))}for(var w=0;w<d.length;w++)for(var o=0;o<s.length;o++){var a=n+d[w]+s[o];(!e||f||a)&&r.push(a)}}return r}});var rh=g((r3,ca)=>{"use strict";var Ne=ca.exports=(t,e,r={})=>(Fn(e),!r.nocomment&&e.charAt(0)==="#"?!1:new Er(e,r).match(t));ca.exports=Ne;var ua=qc();Ne.sep=ua.sep;var Ae=Symbol("globstar **");Ne.GLOBSTAR=Ae;var mv=oa(),Qc={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},fa="[^/]",aa=fa+"*?",bv="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",wv="(?:(?!(?:\\/|^)\\.).)*?",eh=t=>t.split("").reduce((e,r)=>(e[r]=!0,e),{}),Xc=eh("().*{}+?[]^$\\!"),Sv=eh("[.("),Jc=/\/+/;Ne.filter=(t,e={})=>(r,i,n)=>Ne(r,t,e);var Rt=(t,e={})=>{let r={};return Object.keys(t).forEach(i=>r[i]=t[i]),Object.keys(e).forEach(i=>r[i]=e[i]),r};Ne.defaults=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ne;let e=Ne,r=(i,n,s)=>e(i,n,Rt(t,s));return r.Minimatch=class extends e.Minimatch{constructor(n,s){super(n,Rt(t,s))}},r.Minimatch.defaults=i=>e.defaults(Rt(t,i)).Minimatch,r.filter=(i,n)=>e.filter(i,Rt(t,n)),r.defaults=i=>e.defaults(Rt(t,i)),r.makeRe=(i,n)=>e.makeRe(i,Rt(t,n)),r.braceExpand=(i,n)=>e.braceExpand(i,Rt(t,n)),r.match=(i,n,s)=>e.match(i,n,Rt(t,s)),r};Ne.braceExpand=(t,e)=>th(t,e);var th=(t,e={})=>(Fn(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:mv(t)),Ev=1024*64,Fn=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>Ev)throw new TypeError("pattern is too long")},la=Symbol("subparse");Ne.makeRe=(t,e)=>new Er(t,e||{}).makeRe();Ne.match=(t,e,r={})=>{let i=new Er(e,r);return t=t.filter(n=>i.match(n)),i.options.nonull&&!t.length&&t.push(e),t};var vv=t=>t.replace(/\\(.)/g,"$1"),xv=t=>t.replace(/\\([^-\]])/g,"$1"),Tv=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Rv=t=>t.replace(/[[\]\\]/g,"\\$&"),Er=class{constructor(e,r){Fn(e),r||(r={}),this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion!==void 0?r.maxGlobstarRecursion:200,this.set=[],this.pattern=e,this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.make()}debug(){}make(){let e=this.pattern,r=this.options;if(!r.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate();let i=this.globSet=this.braceExpand();r.debug&&(this.debug=(...n)=>console.error(...n)),this.debug(this.pattern,i),i=this.globParts=i.map(n=>n.split(Jc)),this.debug(this.pattern,i),i=i.map((n,s,o)=>n.map(this.parse,this)),this.debug(this.pattern,i),i=i.filter(n=>n.indexOf(!1)===-1),this.debug(this.pattern,i),this.set=i}parseNegate(){if(this.options.nonegate)return;let e=this.pattern,r=!1,i=0;for(let n=0;n<e.length&&e.charAt(n)==="!";n++)r=!r,i++;i&&(this.pattern=e.slice(i)),this.negate=r}matchOne(e,r,i){return r.indexOf(Ae)!==-1?this._matchGlobstar(e,r,i,0,0):this._matchOne(e,r,i,0,0)}_matchGlobstar(e,r,i,n,s){let o=-1;for(let b=s;b<r.length;b++)if(r[b]===Ae){o=b;break}let a=-1;for(let b=r.length-1;b>=0;b--)if(r[b]===Ae){a=b;break}let l=r.slice(s,o),u=i?r.slice(o+1):r.slice(o+1,a),f=i?[]:r.slice(a+1);if(l.length){let b=e.slice(n,n+l.length);if(!this._matchOne(b,l,i,0,0))return!1;n+=l.length}let c=0;if(f.length){if(f.length+n>e.length)return!1;let b=e.length-f.length;if(this._matchOne(e,f,i,b,0))c=f.length;else{if(e[e.length-1]!==""||n+f.length===e.length||!this._matchOne(e,f,i,b-1,0))return!1;c=f.length+1}}if(!u.length){let b=!!c;for(let v=n;v<e.length-c;v++){let E=String(e[v]);if(b=!0,E==="."||E===".."||!this.options.dot&&E.charAt(0)===".")return!1}return i||b}let h=[[[],0]],d=h[0],m=0,p=[0];for(let b of u)b===Ae?(p.push(m),d=[[],0],h.push(d)):(d[0].push(b),m++);let S=h.length-1,y=e.length-c;for(let b of h)b[1]=y-(p[S--]+b[0].length);return!!this._matchGlobStarBodySections(e,h,n,0,i,0,!!c)}_matchGlobStarBodySections(e,r,i,n,s,o,a){let l=r[n];if(!l){for(let c=i;c<e.length;c++){a=!0;let h=e[c];if(h==="."||h===".."||!this.options.dot&&h.charAt(0)===".")return!1}return a}let[u,f]=l;for(;i<=f;){if(this._matchOne(e.slice(0,i+u.length),u,s,i,0)&&o<this.maxGlobstarRecursion){let d=this._matchGlobStarBodySections(e,r,i+u.length,n+1,s,o+1,a);if(d!==!1)return d}let h=e[i];if(h==="."||h===".."||!this.options.dot&&h.charAt(0)===".")return!1;i++}return s||null}_matchOne(e,r,i,n,s){let o,a,l,u;for(o=n,a=s,l=e.length,u=r.length;o<l&&a<u;o++,a++){this.debug("matchOne loop");let f=r[a],c=e[o];if(this.debug(r,f,c),f===!1||f===Ae)return!1;let h;if(typeof f=="string"?(h=c===f,this.debug("string match",f,c,h)):(h=c.match(f),this.debug("pattern match",f,c,h)),!h)return!1}if(o===l&&a===u)return!0;if(o===l)return i;if(a===u)return o===l-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return th(this.pattern,this.options)}parse(e,r){Fn(e);let i=this.options;if(e==="**")if(i.noglobstar)e="*";else return Ae;if(e==="")return"";let n="",s=!1,o=!1,a=[],l=[],u,f=!1,c=-1,h=-1,d,m,p,S=e.charAt(0)===".",y=i.dot||S,b=()=>S?"":y?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",v=x=>x.charAt(0)==="."?"":i.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",E=()=>{if(u){switch(u){case"*":n+=aa,s=!0;break;case"?":n+=fa,s=!0;break;default:n+="\\"+u;break}this.debug("clearStateChar %j %j",u,n),u=!1}};for(let x=0,O;x<e.length&&(O=e.charAt(x));x++){if(this.debug("%s %s %s %j",e,x,n,O),o){if(O==="/")return!1;Xc[O]&&(n+="\\"),n+=O,o=!1;continue}switch(O){case"/":return!1;case"\\":if(f&&e.charAt(x+1)==="-"){n+=O;continue}E(),o=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",e,x,n,O),f){this.debug(" in class"),O==="!"&&x===h+1&&(O="^"),n+=O;continue}if(O==="*"&&u==="*")continue;this.debug("call clearStateChar %j",u),E(),u=O,i.noext&&E();continue;case"(":{if(f){n+="(";continue}if(!u){n+="\\(";continue}let w={type:u,start:x-1,reStart:n.length,open:Qc[u].open,close:Qc[u].close};this.debug(this.pattern," ",w),a.push(w),n+=w.open,w.start===0&&w.type!=="!"&&(S=!0,n+=v(e.slice(x+1))),this.debug("plType %j %j",u,n),u=!1;continue}case")":{let w=a[a.length-1];if(f||!w){n+="\\)";continue}a.pop(),E(),s=!0,m=w,n+=m.close,m.type==="!"&&l.push(Object.assign(m,{reEnd:n.length}));continue}case"|":{let w=a[a.length-1];if(f||!w){n+="\\|";continue}E(),n+="|",w.start===0&&w.type!=="!"&&(S=!0,n+=v(e.slice(x+1)));continue}case"[":if(E(),f){n+="\\"+O;continue}f=!0,h=x,c=n.length,n+=O;continue;case"]":if(x===h+1||!f){n+="\\"+O;continue}d=e.substring(h+1,x);try{RegExp("["+Rv(xv(d))+"]"),n+=O}catch{n=n.substring(0,c)+"(?:$.)"}s=!0,f=!1;continue;default:E(),Xc[O]&&!(O==="^"&&f)&&(n+="\\"),n+=O;break}}for(f&&(d=e.slice(h+1),p=this.parse(d,la),n=n.substring(0,c)+"\\["+p[0],s=s||p[1]),m=a.pop();m;m=a.pop()){let x;x=n.slice(m.reStart+m.open.length),this.debug("setting tail",n,m),x=x.replace(/((?:\\{2}){0,64})(\\?)\|/g,(w,R,A)=>(A||(A="\\"),R+R+A+"|")),this.debug(`tail=%j
2
+ import{a as Oc,b as Ic}from"./chunk-MDBXYXSC.js";import{a as Ac}from"./chunk-WAOCHXJ5.js";import{a as Rc}from"./chunk-LPUQ4HWQ.js";import{a as Tc}from"./chunk-NLCCBXXV.js";import{a as Xt}from"./chunk-RZ4F3BHX.js";import{a as P,b as QE,c as g,d as XE,e as JE,f as ev}from"./chunk-UR6MHSHU.js";var qc=g((XB,Fc)=>{"use strict";var fv=typeof process=="object"&&process&&process.platform==="win32";Fc.exports=fv?{sep:"\\"}:{sep:"/"}});var zc=g((JB,Wc)=>{"use strict";Wc.exports=Bc;function Bc(t,e,r){t instanceof RegExp&&(t=jc(t,r)),e instanceof RegExp&&(e=jc(e,r));var i=Uc(t,e,r);return i&&{start:i[0],end:i[1],pre:r.slice(0,i[0]),body:r.slice(i[0]+t.length,i[1]),post:r.slice(i[1]+e.length)}}function jc(t,e){var r=e.match(t);return r?r[0]:null}Bc.range=Uc;function Uc(t,e,r){var i,n,s,o,a,l=r.indexOf(t),u=r.indexOf(e,l+1),f=l;if(l>=0&&u>0){if(t===e)return[l,u];for(i=[],s=r.length;f>=0&&!a;)f==l?(i.push(f),l=r.indexOf(t,f+1)):i.length==1?a=[i.pop(),u]:(n=i.pop(),n<s&&(s=n,o=u),u=r.indexOf(e,f+1)),f=l<u&&l>=0?l:u;i.length&&(a=[s,o])}return a}});var oa=g((e3,Zc)=>{"use strict";var Gc=zc();Zc.exports=dv;var $c="\0SLASH"+Math.random()+"\0",Hc="\0OPEN"+Math.random()+"\0",sa="\0CLOSE"+Math.random()+"\0",Vc="\0COMMA"+Math.random()+"\0",Yc="\0PERIOD"+Math.random()+"\0";function na(t){return parseInt(t,10)==t?parseInt(t,10):t.charCodeAt(0)}function cv(t){return t.split("\\\\").join($c).split("\\{").join(Hc).split("\\}").join(sa).split("\\,").join(Vc).split("\\.").join(Yc)}function hv(t){return t.split($c).join("\\").split(Hc).join("{").split(sa).join("}").split(Vc).join(",").split(Yc).join(".")}function Kc(t){if(!t)return[""];var e=[],r=Gc("{","}",t);if(!r)return t.split(",");var i=r.pre,n=r.body,s=r.post,o=i.split(",");o[o.length-1]+="{"+n+"}";var a=Kc(s);return s.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function dv(t){return t?(t.substr(0,2)==="{}"&&(t="\\{\\}"+t.substr(2)),_i(cv(t),!0).map(hv)):[]}function pv(t){return"{"+t+"}"}function gv(t){return/^-?0\d/.test(t)}function _v(t,e){return t<=e}function yv(t,e){return t>=e}function _i(t,e){var r=[],i=Gc("{","}",t);if(!i)return[t];var n=i.pre,s=i.post.length?_i(i.post,!1):[""];if(/\$$/.test(i.pre))for(var o=0;o<s.length;o++){var a=n+"{"+i.body+"}"+s[o];r.push(a)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body),u=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body),f=l||u,c=i.body.indexOf(",")>=0;if(!f&&!c)return i.post.match(/,(?!,).*\}/)?(t=i.pre+"{"+i.body+sa+i.post,_i(t)):[t];var h;if(f)h=i.body.split(/\.\./);else if(h=Kc(i.body),h.length===1&&(h=_i(h[0],!1).map(pv),h.length===1))return s.map(function(R){return i.pre+h[0]+R});var d;if(f){var m=na(h[0]),p=na(h[1]),S=Math.max(h[0].length,h[1].length),y=h.length==3?Math.max(Math.abs(na(h[2])),1):1,b=_v,v=p<m;v&&(y*=-1,b=yv);var E=h.some(gv);d=[];for(var T=m;b(T,p);T+=y){var D;if(u)D=String.fromCharCode(T),D==="\\"&&(D="");else if(D=String(T),E){var x=S-D.length;if(x>0){var O=new Array(x+1).join("0");T<0?D="-"+O+D.slice(1):D=O+D}}d.push(D)}}else{d=[];for(var w=0;w<h.length;w++)d.push.apply(d,_i(h[w],!1))}for(var w=0;w<d.length;w++)for(var o=0;o<s.length;o++){var a=n+d[w]+s[o];(!e||f||a)&&r.push(a)}}return r}});var rh=g((r3,ca)=>{"use strict";var Ne=ca.exports=(t,e,r={})=>(Fn(e),!r.nocomment&&e.charAt(0)==="#"?!1:new Er(e,r).match(t));ca.exports=Ne;var ua=qc();Ne.sep=ua.sep;var Ae=Symbol("globstar **");Ne.GLOBSTAR=Ae;var mv=oa(),Qc={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},fa="[^/]",aa=fa+"*?",bv="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",wv="(?:(?!(?:\\/|^)\\.).)*?",eh=t=>t.split("").reduce((e,r)=>(e[r]=!0,e),{}),Xc=eh("().*{}+?[]^$\\!"),Sv=eh("[.("),Jc=/\/+/;Ne.filter=(t,e={})=>(r,i,n)=>Ne(r,t,e);var Rt=(t,e={})=>{let r={};return Object.keys(t).forEach(i=>r[i]=t[i]),Object.keys(e).forEach(i=>r[i]=e[i]),r};Ne.defaults=t=>{if(!t||typeof t!="object"||!Object.keys(t).length)return Ne;let e=Ne,r=(i,n,s)=>e(i,n,Rt(t,s));return r.Minimatch=class extends e.Minimatch{constructor(n,s){super(n,Rt(t,s))}},r.Minimatch.defaults=i=>e.defaults(Rt(t,i)).Minimatch,r.filter=(i,n)=>e.filter(i,Rt(t,n)),r.defaults=i=>e.defaults(Rt(t,i)),r.makeRe=(i,n)=>e.makeRe(i,Rt(t,n)),r.braceExpand=(i,n)=>e.braceExpand(i,Rt(t,n)),r.match=(i,n,s)=>e.match(i,n,Rt(t,s)),r};Ne.braceExpand=(t,e)=>th(t,e);var th=(t,e={})=>(Fn(t),e.nobrace||!/\{(?:(?!\{).)*\}/.test(t)?[t]:mv(t)),Ev=1024*64,Fn=t=>{if(typeof t!="string")throw new TypeError("invalid pattern");if(t.length>Ev)throw new TypeError("pattern is too long")},la=Symbol("subparse");Ne.makeRe=(t,e)=>new Er(t,e||{}).makeRe();Ne.match=(t,e,r={})=>{let i=new Er(e,r);return t=t.filter(n=>i.match(n)),i.options.nonull&&!t.length&&t.push(e),t};var vv=t=>t.replace(/\\(.)/g,"$1"),xv=t=>t.replace(/\\([^-\]])/g,"$1"),Tv=t=>t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Rv=t=>t.replace(/[[\]\\]/g,"\\$&"),Er=class{constructor(e,r){Fn(e),r||(r={}),this.options=r,this.maxGlobstarRecursion=r.maxGlobstarRecursion!==void 0?r.maxGlobstarRecursion:200,this.set=[],this.pattern=e,this.windowsPathsNoEscape=!!r.windowsPathsNoEscape||r.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.partial=!!r.partial,this.make()}debug(){}make(){let e=this.pattern,r=this.options;if(!r.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate();let i=this.globSet=this.braceExpand();r.debug&&(this.debug=(...n)=>console.error(...n)),this.debug(this.pattern,i),i=this.globParts=i.map(n=>n.split(Jc)),this.debug(this.pattern,i),i=i.map((n,s,o)=>n.map(this.parse,this)),this.debug(this.pattern,i),i=i.filter(n=>n.indexOf(!1)===-1),this.debug(this.pattern,i),this.set=i}parseNegate(){if(this.options.nonegate)return;let e=this.pattern,r=!1,i=0;for(let n=0;n<e.length&&e.charAt(n)==="!";n++)r=!r,i++;i&&(this.pattern=e.slice(i)),this.negate=r}matchOne(e,r,i){return r.indexOf(Ae)!==-1?this._matchGlobstar(e,r,i,0,0):this._matchOne(e,r,i,0,0)}_matchGlobstar(e,r,i,n,s){let o=-1;for(let b=s;b<r.length;b++)if(r[b]===Ae){o=b;break}let a=-1;for(let b=r.length-1;b>=0;b--)if(r[b]===Ae){a=b;break}let l=r.slice(s,o),u=i?r.slice(o+1):r.slice(o+1,a),f=i?[]:r.slice(a+1);if(l.length){let b=e.slice(n,n+l.length);if(!this._matchOne(b,l,i,0,0))return!1;n+=l.length}let c=0;if(f.length){if(f.length+n>e.length)return!1;let b=e.length-f.length;if(this._matchOne(e,f,i,b,0))c=f.length;else{if(e[e.length-1]!==""||n+f.length===e.length||!this._matchOne(e,f,i,b-1,0))return!1;c=f.length+1}}if(!u.length){let b=!!c;for(let v=n;v<e.length-c;v++){let E=String(e[v]);if(b=!0,E==="."||E===".."||!this.options.dot&&E.charAt(0)===".")return!1}return i||b}let h=[[[],0]],d=h[0],m=0,p=[0];for(let b of u)b===Ae?(p.push(m),d=[[],0],h.push(d)):(d[0].push(b),m++);let S=h.length-1,y=e.length-c;for(let b of h)b[1]=y-(p[S--]+b[0].length);return!!this._matchGlobStarBodySections(e,h,n,0,i,0,!!c)}_matchGlobStarBodySections(e,r,i,n,s,o,a){let l=r[n];if(!l){for(let c=i;c<e.length;c++){a=!0;let h=e[c];if(h==="."||h===".."||!this.options.dot&&h.charAt(0)===".")return!1}return a}let[u,f]=l;for(;i<=f;){if(this._matchOne(e.slice(0,i+u.length),u,s,i,0)&&o<this.maxGlobstarRecursion){let d=this._matchGlobStarBodySections(e,r,i+u.length,n+1,s,o+1,a);if(d!==!1)return d}let h=e[i];if(h==="."||h===".."||!this.options.dot&&h.charAt(0)===".")return!1;i++}return s||null}_matchOne(e,r,i,n,s){let o,a,l,u;for(o=n,a=s,l=e.length,u=r.length;o<l&&a<u;o++,a++){this.debug("matchOne loop");let f=r[a],c=e[o];if(this.debug(r,f,c),f===!1||f===Ae)return!1;let h;if(typeof f=="string"?(h=c===f,this.debug("string match",f,c,h)):(h=c.match(f),this.debug("pattern match",f,c,h)),!h)return!1}if(o===l&&a===u)return!0;if(o===l)return i;if(a===u)return o===l-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return th(this.pattern,this.options)}parse(e,r){Fn(e);let i=this.options;if(e==="**")if(i.noglobstar)e="*";else return Ae;if(e==="")return"";let n="",s=!1,o=!1,a=[],l=[],u,f=!1,c=-1,h=-1,d,m,p,S=e.charAt(0)===".",y=i.dot||S,b=()=>S?"":y?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",v=x=>x.charAt(0)==="."?"":i.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",E=()=>{if(u){switch(u){case"*":n+=aa,s=!0;break;case"?":n+=fa,s=!0;break;default:n+="\\"+u;break}this.debug("clearStateChar %j %j",u,n),u=!1}};for(let x=0,O;x<e.length&&(O=e.charAt(x));x++){if(this.debug("%s %s %s %j",e,x,n,O),o){if(O==="/")return!1;Xc[O]&&(n+="\\"),n+=O,o=!1;continue}switch(O){case"/":return!1;case"\\":if(f&&e.charAt(x+1)==="-"){n+=O;continue}E(),o=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s %s %s %j <-- stateChar",e,x,n,O),f){this.debug(" in class"),O==="!"&&x===h+1&&(O="^"),n+=O;continue}if(O==="*"&&u==="*")continue;this.debug("call clearStateChar %j",u),E(),u=O,i.noext&&E();continue;case"(":{if(f){n+="(";continue}if(!u){n+="\\(";continue}let w={type:u,start:x-1,reStart:n.length,open:Qc[u].open,close:Qc[u].close};this.debug(this.pattern," ",w),a.push(w),n+=w.open,w.start===0&&w.type!=="!"&&(S=!0,n+=v(e.slice(x+1))),this.debug("plType %j %j",u,n),u=!1;continue}case")":{let w=a[a.length-1];if(f||!w){n+="\\)";continue}a.pop(),E(),s=!0,m=w,n+=m.close,m.type==="!"&&l.push(Object.assign(m,{reEnd:n.length}));continue}case"|":{let w=a[a.length-1];if(f||!w){n+="\\|";continue}E(),n+="|",w.start===0&&w.type!=="!"&&(S=!0,n+=v(e.slice(x+1)));continue}case"[":if(E(),f){n+="\\"+O;continue}f=!0,h=x,c=n.length,n+=O;continue;case"]":if(x===h+1||!f){n+="\\"+O;continue}d=e.substring(h+1,x);try{RegExp("["+Rv(xv(d))+"]"),n+=O}catch{n=n.substring(0,c)+"(?:$.)"}s=!0,f=!1;continue;default:E(),Xc[O]&&!(O==="^"&&f)&&(n+="\\"),n+=O;break}}for(f&&(d=e.slice(h+1),p=this.parse(d,la),n=n.substring(0,c)+"\\["+p[0],s=s||p[1]),m=a.pop();m;m=a.pop()){let x;x=n.slice(m.reStart+m.open.length),this.debug("setting tail",n,m),x=x.replace(/((?:\\{2}){0,64})(\\?)\|/g,(w,R,A)=>(A||(A="\\"),R+R+A+"|")),this.debug(`tail=%j
3
3
  %s`,x,x,m,n);let O=m.type==="*"?aa:m.type==="?"?fa:"\\"+m.type;s=!0,n=n.slice(0,m.reStart)+O+"\\("+x}E(),o&&(n+="\\\\");let T=Sv[n.charAt(0)];for(let x=l.length-1;x>-1;x--){let O=l[x],w=n.slice(0,O.reStart),R=n.slice(O.reStart,O.reEnd-8),A=n.slice(O.reEnd),N=n.slice(O.reEnd-8,O.reEnd)+A,z=w.split(")").length,ue=w.split("(").length-z,Z=A;for(let V=0;V<ue;V++)Z=Z.replace(/\)[+*?]?/,"");A=Z;let te=A===""&&r!==la?"(?:$|\\/)":"";n=w+R+A+te+N}if(n!==""&&s&&(n="(?=.)"+n),T&&(n=b()+n),r===la)return[n,s];if(i.nocase&&!s&&(s=e.toUpperCase()!==e.toLowerCase()),!s)return vv(e);let D=i.nocase?"i":"";try{return Object.assign(new RegExp("^"+n+"$",D),{_glob:e,_src:n})}catch{return new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let r=this.options,i=r.noglobstar?aa:r.dot?bv:wv,n=r.nocase?"i":"",s=e.map(o=>(o=o.map(a=>typeof a=="string"?Tv(a):a===Ae?Ae:a._src).reduce((a,l)=>(a[a.length-1]===Ae&&l===Ae||a.push(l),a),[]),o.forEach((a,l)=>{a!==Ae||o[l-1]===Ae||(l===0?o.length>1?o[l+1]="(?:\\/|"+i+"\\/)?"+o[l+1]:o[l]=i:l===o.length-1?o[l-1]+="(?:\\/|"+i+")?":(o[l-1]+="(?:\\/|\\/"+i+"\\/)"+o[l+1],o[l+1]=Ae))}),o.filter(a=>a!==Ae).join("/"))).join("|");s="^(?:"+s+")$",this.negate&&(s="^(?!"+s+").*$");try{this.regexp=new RegExp(s,n)}catch{this.regexp=!1}return this.regexp}match(e,r=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&r)return!0;let i=this.options;ua.sep!=="/"&&(e=e.split(ua.sep).join("/")),e=e.split(Jc),this.debug(this.pattern,"split",e);let n=this.set;this.debug(this.pattern,"set",n);let s;for(let o=e.length-1;o>=0&&(s=e[o],!s);o--);for(let o=0;o<n.length;o++){let a=n[o],l=e;if(i.matchBase&&a.length===1&&(l=[s]),this.matchOne(l,a,r))return i.flipNegate?!0:!this.negate}return i.flipNegate?!1:this.negate}static defaults(e){return Ne.defaults(e).Minimatch}};Ne.Minimatch=Er});var ah=g((i3,oh)=>{"use strict";oh.exports=sh;var da=P("fs"),{EventEmitter:Av}=P("events"),{Minimatch:ha}=rh(),{resolve:Ov}=P("path");function Iv(t,e){return new Promise((r,i)=>{da.readdir(t,{withFileTypes:!0},(n,s)=>{if(n)switch(n.code){case"ENOTDIR":e?i(n):r([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":r([]);break;default:i(n);break}else r(s)})})}function ih(t,e){return new Promise((r,i)=>{(e?da.stat:da.lstat)(t,(s,o)=>{s?s.code==="ENOENT"?r(e?ih(t,!1):null):r(null):r(o)})})}async function*nh(t,e,r,i,n,s){let o=await Iv(e+t,s);for(let a of o){let l=a.name;l===void 0&&(l=a,i=!0);let u=t+"/"+l,f=u.slice(1),c=e+"/"+f,h=null;(i||r)&&(h=await ih(c,r)),!h&&a.name!==void 0&&(h=a),h===null&&(h={isDirectory:()=>!1}),h.isDirectory()?n(f)||(yield{relative:f,absolute:c,stats:h},yield*nh(u,e,r,i,n,!1)):yield{relative:f,absolute:c,stats:h}}}async function*Dv(t,e,r,i){yield*nh("",t,e,r,i,!0)}function Pv(t){return{pattern:t.pattern,dot:!!t.dot,noglobstar:!!t.noglobstar,matchBase:!!t.matchBase,nocase:!!t.nocase,ignore:t.ignore,skip:t.skip,follow:!!t.follow,stat:!!t.stat,nodir:!!t.nodir,mark:!!t.mark,silent:!!t.silent,absolute:!!t.absolute}}var qn=class extends Av{constructor(e,r,i){if(super(),typeof r=="function"&&(i=r,r=null),this.options=Pv(r||{}),this.matchers=[],this.options.pattern){let n=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=n.map(s=>new ha(s,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let n=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=n.map(s=>new ha(s,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let n=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=n.map(s=>new ha(s,{dot:!0}))}this.iterator=Dv(Ov(e||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,i&&(this._matches=[],this.on("match",n=>this._matches.push(this.options.absolute?n.absolute:n.relative)),this.on("error",n=>i(n)),this.on("end",()=>i(null,this._matches))),setTimeout(()=>this._next(),0)}_shouldSkipDirectory(e){return this.skipMatchers.some(r=>r.match(e))}_fileMatches(e,r){let i=e+(r?"/":"");return(this.matchers.length===0||this.matchers.some(n=>n.match(i)))&&!this.ignoreMatchers.some(n=>n.match(i))&&(!this.options.nodir||!r)}_next(){!this.paused&&!this.aborted?this.iterator.next().then(e=>{if(e.done)this.emit("end");else{let r=e.value.stats.isDirectory();if(this._fileMatches(e.value.relative,r)){let i=e.value.relative,n=e.value.absolute;this.options.mark&&r&&(i+="/",n+="/"),this.options.stat?this.emit("match",{relative:i,absolute:n,stat:e.value.stats}):this.emit("match",{relative:i,absolute:n})}this._next(this.iterator)}}).catch(e=>{this.abort(),this.emit("error",e),!e.code&&!this.options.silent&&console.error(e)}):this.inactive=!0}abort(){this.aborted=!0}pause(){this.paused=!0}resume(){this.paused=!1,this.inactive&&(this.inactive=!1,this._next())}};function sh(t,e,r){return new qn(t,e,r)}sh.ReaddirGlob=qn});var sd={};XE(sd,{all:()=>Ea,allLimit:()=>va,allSeries:()=>xa,any:()=>Pa,anyLimit:()=>La,anySeries:()=>Na,apply:()=>dh,applyEach:()=>bh,applyEachSeries:()=>wh,asyncify:()=>Bn,auto:()=>Ma,autoInject:()=>Sh,cargo:()=>Eh,cargoQueue:()=>vh,compose:()=>xh,concat:()=>_a,concatLimit:()=>bi,concatSeries:()=>ya,constant:()=>Th,default:()=>Mx,detect:()=>ma,detectLimit:()=>ba,detectSeries:()=>wa,dir:()=>Ah,doDuring:()=>Un,doUntil:()=>Oh,doWhilst:()=>Un,during:()=>Hn,each:()=>Sa,eachLimit:()=>Wn,eachOf:()=>qe,eachOfLimit:()=>mi,eachOfSeries:()=>Xe,eachSeries:()=>zn,ensureAsync:()=>ja,every:()=>Ea,everyLimit:()=>va,everySeries:()=>xa,filter:()=>Ta,filterLimit:()=>Ra,filterSeries:()=>Aa,find:()=>ma,findLimit:()=>ba,findSeries:()=>wa,flatMap:()=>_a,flatMapLimit:()=>bi,flatMapSeries:()=>ya,foldl:()=>vr,foldr:()=>Ia,forEach:()=>Sa,forEachLimit:()=>Wn,forEachOf:()=>qe,forEachOfLimit:()=>mi,forEachOfSeries:()=>Xe,forEachSeries:()=>zn,forever:()=>Dh,groupBy:()=>Ph,groupByLimit:()=>Qn,groupBySeries:()=>Lh,inject:()=>vr,log:()=>Nh,map:()=>Kn,mapLimit:()=>Ei,mapSeries:()=>ka,mapValues:()=>Ch,mapValuesLimit:()=>Xn,mapValuesSeries:()=>kh,memoize:()=>Mh,nextTick:()=>Fh,parallel:()=>qh,parallelLimit:()=>jh,priorityQueue:()=>Bh,queue:()=>Ua,race:()=>Uh,reduce:()=>vr,reduceRight:()=>Ia,reflect:()=>Gn,reflectAll:()=>Wh,reject:()=>zh,rejectLimit:()=>Gh,rejectSeries:()=>$h,retry:()=>$n,retryable:()=>Yh,select:()=>Ta,selectLimit:()=>Ra,selectSeries:()=>Aa,seq:()=>qa,series:()=>Kh,setImmediate:()=>At,some:()=>Pa,someLimit:()=>La,someSeries:()=>Na,sortBy:()=>Zh,timeout:()=>Qh,times:()=>Xh,timesLimit:()=>Jn,timesSeries:()=>Jh,transform:()=>ed,tryEach:()=>td,unmemoize:()=>rd,until:()=>id,waterfall:()=>nd,whilst:()=>Hn,wrapSync:()=>Bn});function dh(t,...e){return(...r)=>t(...e,...r)}function wi(t){return function(...e){var r=e.pop();return t.call(this,e,r)}}function _h(t){setTimeout(t,0)}function yh(t){return(e,...r)=>t(()=>e(...r))}function Bn(t){return Si(t)?function(...e){let r=e.pop(),i=t.apply(this,e);return lh(i,r)}:wi(function(e,r){var i;try{i=t.apply(this,e)}catch(n){return r(n)}if(i&&typeof i.then=="function")return lh(i,r);r(null,i)})}function lh(t,e){return t.then(r=>{uh(e,null,r)},r=>{uh(e,r&&(r instanceof Error||r.message)?r:new Error(r))})}function uh(t,e,r){try{t(e,r)}catch(i){At(n=>{throw n},i)}}function Si(t){return t[Symbol.toStringTag]==="AsyncFunction"}function Nv(t){return t[Symbol.toStringTag]==="AsyncGenerator"}function Cv(t){return typeof t[Symbol.asyncIterator]=="function"}function F(t){if(typeof t!="function")throw new Error("expected a function");return Si(t)?Bn(t):t}function M(t,e){if(e||(e=t.length),!e)throw new Error("arity is undefined");function r(...i){return typeof i[e-1]=="function"?t.apply(this,i):new Promise((n,s)=>{i[e-1]=(o,...a)=>{if(o)return s(o);n(a.length>1?a:a[0])},t.apply(this,i)})}return r}function mh(t){return function(r,...i){return M(function(s){var o=this;return t(r,(a,l)=>{F(a).apply(o,i.concat(l))},s)})}}function Ca(t,e,r,i){e=e||[];var n=[],s=0,o=F(r);return t(e,(a,l,u)=>{var f=s++;o(a,(c,h)=>{n[f]=h,u(c)})},a=>{i(a,n)})}function Vn(t){return t&&typeof t.length=="number"&&t.length>=0&&t.length%1===0}function Ot(t){function e(...r){if(t!==null){var i=t;t=null,i.apply(this,r)}}return Object.assign(e,t),e}function kv(t){return t[Symbol.iterator]&&t[Symbol.iterator]()}function Mv(t){var e=-1,r=t.length;return function(){return++e<r?{value:t[e],key:e}:null}}function Fv(t){var e=-1;return function(){var i=t.next();return i.done?null:(e++,{value:i.value,key:e})}}function qv(t){var e=t?Object.keys(t):[],r=-1,i=e.length;return function n(){var s=e[++r];return s==="__proto__"?n():r<i?{value:t[s],key:s}:null}}function jv(t){if(Vn(t))return Mv(t);var e=kv(t);return e?Fv(e):qv(t)}function It(t){return function(...e){if(t===null)throw new Error("Callback was already called.");var r=t;t=null,r.apply(this,e)}}function fh(t,e,r,i){let n=!1,s=!1,o=!1,a=0,l=0;function u(){a>=e||o||n||(o=!0,t.next().then(({value:h,done:d})=>{if(!(s||n)){if(o=!1,d){n=!0,a<=0&&i(null);return}a++,r(h,l,f),l++,u()}}).catch(c))}function f(h,d){if(a-=1,!s){if(h)return c(h);if(h===!1){n=!0,s=!0;return}if(d===Yn||n&&a<=0)return n=!0,i(null);u()}}function c(h){s||(o=!1,n=!0,i(h))}u()}function Bv(t,e,r,i){return $e(e)(t,F(r),i)}function Uv(t,e,r){r=Ot(r);var i=0,n=0,{length:s}=t,o=!1;s===0&&r(null);function a(l,u){l===!1&&(o=!0),o!==!0&&(l?r(l):(++n===s||u===Yn)&&r(null))}for(;i<s;i++)e(t[i],i,It(a))}function Wv(t,e,r){return mi(t,1/0,e,r)}function zv(t,e,r){var i=Vn(t)?Uv:Wv;return i(t,F(e),r)}function Gv(t,e,r){return Ca(qe,t,e,r)}function $v(t,e,r){return mi(t,1,e,r)}function Hv(t,e,r){return Ca(Xe,t,e,r)}function xr(){let t,e;function r(i,...n){if(i)return e(i);t(n.length>1?n:n[0])}return r[Tr]=new Promise((i,n)=>{t=i,e=n}),r}function Ma(t,e,r){typeof e!="number"&&(r=e,e=null),r=Ot(r||xr());var i=Object.keys(t).length;if(!i)return r(null);e||(e=i);var n={},s=0,o=!1,a=!1,l=Object.create(null),u=[],f=[],c={};Object.keys(t).forEach(v=>{var E=t[v];if(!Array.isArray(E)){h(v,[E]),f.push(v);return}var T=E.slice(0,E.length-1),D=T.length;if(D===0){h(v,E),f.push(v);return}c[v]=D,T.forEach(x=>{if(!t[x])throw new Error("async.auto task `"+v+"` has a non-existent dependency `"+x+"` in "+T.join(", "));m(x,()=>{D--,D===0&&h(v,E)})})}),y(),d();function h(v,E){u.push(()=>S(v,E))}function d(){if(!o){if(u.length===0&&s===0)return r(null,n);for(;u.length&&s<e;){var v=u.shift();v()}}}function m(v,E){var T=l[v];T||(T=l[v]=[]),T.push(E)}function p(v){var E=l[v]||[];E.forEach(T=>T()),d()}function S(v,E){if(!a){var T=It((x,...O)=>{if(s--,x===!1){o=!0;return}if(O.length<2&&([O]=O),x){var w={};if(Object.keys(n).forEach(R=>{w[R]=n[R]}),w[v]=O,a=!0,l=Object.create(null),o)return;r(x,w)}else n[v]=O,p(v)});s++;var D=F(E[E.length-1]);E.length>1?D(n,T):D(T)}}function y(){for(var v,E=0;f.length;)v=f.pop(),E++,b(v).forEach(T=>{--c[T]===0&&f.push(T)});if(E!==i)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function b(v){var E=[];return Object.keys(t).forEach(T=>{let D=t[T];Array.isArray(D)&&D.indexOf(v)>=0&&E.push(T)}),E}return r[Tr]}function Qv(t){let e="",r=0,i=t.indexOf("*/");for(;r<t.length;)if(t[r]==="/"&&t[r+1]==="/"){let n=t.indexOf(`
4
4
  `,r);r=n===-1?t.length:n}else if(i!==-1&&t[r]==="/"&&t[r+1]==="*"){let n=t.indexOf("*/",r);n!==-1?(r=n+2,i=t.indexOf("*/",r)):(e+=t[r],r++)}else e+=t[r],r++;return e}function Xv(t){let e=Qv(t.toString()),r=e.match(Vv);if(r||(r=e.match(Yv)),!r)throw new Error(`could not parse args in autoInject
5
5
  Source:
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as h}from"./chunk-AT2Y5UNP.js";import{a as A}from"./chunk-HCBYKLMW.js";import{t as l}from"./chunk-3Z4EHIOW.js";import{a as c,b as f,i as P}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as x}from"./chunk-UR6MHSHU.js";var L=x(B(),1);var n=x(A(),1);function S(r,d,s,u,m){let p=s==="basic"&&u?`basic (${u})`:s,i=20,a=`${r} [${d}]`,g="\xB7".repeat(Math.max(2,i-a.length+3));return{label:`${a} ${g} ${p}`,profile:r,env:d,isActive:m}}function M({creds:r,onSwitch:d,onCancel:s}){let u=r.listProfiles(),m=r.getActiveProfile(),p=r.getDefaultEnv(),i=u.map(e=>{let o=r.loadBasicAuth(e.profile,e.env),t=r.loadCredentials(e.profile,e.env)!==null,v=o?"basic":t?"oauth":"none",b=o?o.username:null,w=e.profile===m&&e.env===p;return S(e.profile,e.env,v,b,w)}),[a,g]=(0,L.useState)(()=>{let e=i.findIndex(o=>o.isActive);return e>=0?e:0});return P((e,o)=>{if(o.escape){s();return}if(o.upArrow){g(t=>Math.max(0,t-1));return}if(o.downArrow){g(t=>Math.min(i.length-1,t+1));return}if(o.return&&i[a]){let t=i[a];t.isActive||d(t.profile,t.env),s();return}}),i.length===0?(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(f,{color:l.dim,children:"No profiles \u2014 use Login to create one"})}),(0,n.jsx)(h,{bindings:[],escBackLabel:"back"})]}):(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{flexDirection:"column",marginTop:1,children:i.map((e,o)=>{let t=o===a,v=t?"\u276F ":" ",b=e.isActive?l.green:t?l.orange:void 0;return(0,n.jsxs)(f,{color:b,children:[v,e.label,e.isActive?" \u25CF active":""]},`${e.profile}-${e.env}`)})}),(0,n.jsx)(h,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"switch"}],escBackLabel:"back"})]})}export{S as a,M as b};
2
+ import{a as h}from"./chunk-GNJBT6SS.js";import{v as l}from"./chunk-3QWAABMG.js";import{a as A}from"./chunk-HCBYKLMW.js";import{a as c,b as f,i as P}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as x}from"./chunk-UR6MHSHU.js";var L=x(B(),1);var n=x(A(),1);function S(r,d,s,u,m){let p=s==="basic"&&u?`basic (${u})`:s,i=20,a=`${r} [${d}]`,g="\xB7".repeat(Math.max(2,i-a.length+3));return{label:`${a} ${g} ${p}`,profile:r,env:d,isActive:m}}function M({creds:r,onSwitch:d,onCancel:s}){let u=r.listProfiles(),m=r.getActiveProfile(),p=r.getDefaultEnv(),i=u.map(e=>{let o=r.loadBasicAuth(e.profile,e.env),t=r.loadCredentials(e.profile,e.env)!==null,v=o?"basic":t?"oauth":"none",b=o?o.username:null,w=e.profile===m&&e.env===p;return S(e.profile,e.env,v,b,w)}),[a,g]=(0,L.useState)(()=>{let e=i.findIndex(o=>o.isActive);return e>=0?e:0});return P((e,o)=>{if(o.escape){s();return}if(o.upArrow){g(t=>Math.max(0,t-1));return}if(o.downArrow){g(t=>Math.min(i.length-1,t+1));return}if(o.return&&i[a]){let t=i[a];t.isActive||d(t.profile,t.env),s();return}}),i.length===0?(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{marginTop:1,children:(0,n.jsx)(f,{color:l.dim,children:"No profiles \u2014 use Login to create one"})}),(0,n.jsx)(h,{bindings:[],escBackLabel:"back"})]}):(0,n.jsxs)(c,{flexDirection:"column",borderStyle:"round",borderColor:l.orange,paddingX:2,paddingY:1,children:[(0,n.jsx)(f,{color:l.orange,bold:!0,children:"Profiles"}),(0,n.jsx)(c,{flexDirection:"column",marginTop:1,children:i.map((e,o)=>{let t=o===a,v=t?"\u276F ":" ",b=e.isActive?l.green:t?l.orange:void 0;return(0,n.jsxs)(f,{color:b,children:[v,e.label,e.isActive?" \u25CF active":""]},`${e.profile}-${e.env}`)})}),(0,n.jsx)(h,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"switch"}],escBackLabel:"back"})]})}export{S as a,M as b};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as Le}from"./chunk-K4PLPKPF.js";import{a as de,b as je}from"./chunk-PQIPYWTP.js";import{d as Oe,f as pe}from"./chunk-LOIRZFV3.js";import{a as Pe}from"./chunk-7CBWZLRS.js";import{a as Ce}from"./chunk-UHGECBEN.js";import{b as _e}from"./chunk-C6S4IEBC.js";import{v as l}from"./chunk-3QWAABMG.js";import{a as N}from"./chunk-HCBYKLMW.js";import{a as u,b as i,i as Ee,j as ke,k as xe}from"./chunk-C44QQJR4.js";import{a as le}from"./chunk-6YGTRKDT.js";import{e as j}from"./chunk-UR6MHSHU.js";var te=j(le(),1);var q=j(le(),1);var D=j(le(),1);function fe(e,n){let s=null,c=(g,p)=>{for(let d=0;d<g.length;d++){let o=g[d],w=[...p,d];n(o)&&(s===null||w.length>s.length)&&(s=w),o.children&&o.children.length>0&&c(o.children,w)}};return c(e,[]),s}function me(e,n,s){if(n.length===0)return[...e];let c=n[0],g=[...e],p=g[c];if(n.length===1)g[c]=s(p);else{let d=n.slice(1),o=me(p.children??[],d,s);g[c]={...p,children:o}}return g}function Te(e){let n=e.indexOf(": ");return n>0&&n<15?e.slice(n+2):e}function Be(e){return e.map(n=>{let s=n.children?Be(n.children):n.children;return n.status==="running"?{...n,status:"stopped",phase:void 0,children:s}:s!==n.children?{...n,children:s}:n})}function De(e,n,s,c){let[g,p]=(0,D.useState)(!1),[d,o]=(0,D.useState)([]),[w,I]=(0,D.useState)(null),[k,_]=(0,D.useState)(null),[U,S]=(0,D.useState)(null),[v,B]=(0,D.useState)(null),[O,Q]=(0,D.useState)([]),[G,ne]=(0,D.useState)(null),[se,ge]=(0,D.useState)(void 0),K=(0,D.useRef)(null),H=(0,D.useRef)(null),Z=(0,D.useRef)(0),ee=(0,D.useRef)(!1),h=(0,D.useCallback)(async(x,A)=>{let re=K.current;if(re){try{await re.exited}catch{}K.current=null}o([]),I(null),_(null),S(null),B(null),Q([]),ne(null),ge(x.max_steps),p(!0),H.current=null,Z.current=0;let F;try{F=Le(x,A)}catch(X){S(X instanceof Error?X.message:String(X)),p(!1);return}K.current=F,Oe("runner",()=>F.cancel()),(async()=>{ee.current=!1;let X=!1;for await(let t of F.events){if(ee.current)break;switch(t.type){case"run_start":if(t.child_id)break;if(H.current&&!H.current.isSingleFlow){let E=Z.current;Z.current++,o(C=>C.map((b,T)=>T===E?{...b,status:"running"}:b.status==="running"&&!b.children?.some(a=>a.status==="running")?{...b,status:b.children?.some(a=>a.status==="failed")?"failed":"passed"}:b))}break;case"bifurcation":{let E=t.flows??[],C=t.count??E.length,b={flows:E,isSingleFlow:t.is_single_flow??C<=1};B(b),H.current=b,Z.current=0,o(E.map((T,a)=>({index:a+1,objective:T??`Flow ${a+1}`,status:"pending"})));break}case"step_start":{n?.("STEP_START",`Step ${t.index} started`,{index:t.index,objective:t.objective,child_id:t.child_id});let E=t.index,C=t.objective??`Step ${E}`,b=t.child_id,T=H.current&&!H.current.isSingleFlow;if(b)o(a=>{let f=fe(a,$=>$.branchChildId===b)??fe(a,$=>$.status==="running");return f?me(a,f,$=>{let L=($.children??[]).map(V=>V.status==="running"&&V.childId===b?{...V,status:"stopped",phase:void 0}:V);return L.push({index:E,objective:C,status:"running",childId:b}),{...$,children:L}}):a});else if(T){let a=Math.max(0,Z.current-1);o(f=>{let $=[...f];if(a>=$.length)return f;let L={...$[a]},ce=[...L.children??[]].map(he=>he.status==="running"&&he.childId===void 0?{...he,status:"stopped",phase:void 0}:he);return ce.push({index:E,objective:C,status:"running"}),L.children=ce,L.status="running",$[a]=L,$})}else o(a=>{let f=Be(a);return f.some(L=>L.index===E)?f.map(L=>L.index===E?{...L,status:"running",objective:C}:L):[...f,{index:E,objective:C,status:"running"}]});break}case"step_event":{n?.("STEP_EVENT",`Step ${t.index} ${t.event}`,{index:t.index,phase:t.event,action_type:t.action_type,detail:t.detail,child_id:t.child_id});let E=t.child_id,C=H.current&&!H.current.isSingleFlow;if(t.event==="cm_init"&&t.checkpoint_count!=null){Q(b=>[...b,t.checkpoint_count]);break}if(t.event==="replay_started"){ne({recordingLength:t.recording_length??0});break}if(t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&s?.(t.detail),E){let b=a=>{if(a.index!==t.index||a.childId!==E)return a;let f={phase:t.event};return t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&(f.objective=t.detail),t.action_type&&(f.actionType=t.action_type),{...a,...f}},T=a=>a.map(f=>{let $=b(f);return $!==f?$:f.children&&f.children.length>0?{...f,children:T(f.children)}:f});o(a=>a.map(f=>f.children?{...f,children:T(f.children)}:f))}else if(C){let b=Math.max(0,Z.current-1);o(T=>{let a=[...T];if(b>=a.length)return T;let f={...a[b]},$=[...f.children??[]];if(!$.some(V=>V.index===t.index&&V.childId===void 0))$.push({index:t.index,objective:`Step ${t.index}`,status:"running",phase:t.event,actionType:t.action_type});else for(let V=0;V<$.length;V++){if($[V].index!==t.index||$[V].childId!==void 0)continue;let ce={phase:t.event};t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&(ce.objective=t.detail),t.action_type&&(ce.actionType=t.action_type),$[V]={...$[V],...ce}}return f.children=$,a[b]=f,a})}else o(b=>b.some(a=>a.index===t.index)?b.map(a=>{if(a.index!==t.index)return a;let f={phase:t.event};return t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&(f.objective=t.detail),t.action_type&&(f.actionType=t.action_type),{...a,...f}}):[...Be(b),{index:t.index,objective:`Step ${t.index}`,status:"running",phase:t.event,actionType:t.action_type}]);break}case"step_end":{n?.("STEP_END",`Step ${t.index} ${t.status}`,{index:t.index,status:t.status,duration:t.duration,summary:t.summary,child_id:t.child_id}),c?.();let E=t.child_id,C=H.current&&!H.current.isSingleFlow;if(E){let b=a=>a.index===t.index&&a.childId===E?{...a,status:t.status,duration:t.duration,phase:void 0,objective:a.objective.startsWith("Step ")?Te(t.summary||a.objective):a.objective}:a,T=a=>a.map(f=>{let $=b(f);return $!==f?$:f.children&&f.children.length>0?{...f,children:T(f.children)}:f});o(a=>a.map(f=>f.children?{...f,children:T(f.children)}:f))}else if(C){let b=Math.max(0,Z.current-1);o(T=>{let a=[...T];if(b>=a.length)return T;let f={...a[b]},$=(f.children??[]).map(L=>L.index===t.index&&L.childId===void 0?{...L,status:t.status,duration:t.duration,phase:void 0,objective:L.objective.startsWith("Step ")?Te(t.summary||L.objective):L.objective}:L);return f.children=$,a[b]=f,a})}else o(b=>b.map(T=>T.index===t.index?{...T,status:t.status,duration:t.duration,phase:void 0,objective:T.objective.startsWith("Step ")?Te(t.summary||T.objective):T.objective}:T));{let T=H.current&&!H.current.isSingleFlow?Math.max(0,Z.current-1):0;e?.(t.index,T,t.child_id)}break}case"child_agent_start":{let E=t.objective??"",C=t.child_id;o(b=>{let T=fe(b,a=>a.status==="running");return T?me(b,T,a=>({...a,objective:`${E} (branch)`,phase:`child: ${E.slice(0,50)}`,branchObjective:E,branchChildId:C})):b});break}case"child_agent_end":{let E=t.child_id,C=`child ${t.success?"done":"failed"}`;o(b=>{let T=fe(b,a=>a.branchChildId===E);return T?me(b,T,a=>({...a,phase:C})):b.map(a=>a.phase?.startsWith("child:")?{...a,phase:C}:a)});break}case"ask_user":I(t.question??"");break;case"run_end":o(E=>E.map(C=>C.status==="running"?{...C,status:t.status,phase:void 0}:C)),p(!1),_(t),X=!0;break;case"error":p(!1),S(t.message??"Runner error"),o(E=>E.map(C=>C.status==="running"?{...C,status:"failed",phase:void 0}:C));break}}let{code:ie,signal:ve}=await F.exited,ye=F.stderr,Xe=ie===0&&!ve,ue=[];ie!==null&&ie!==0&&ue.push(`Runner exited with code ${ie}`),ve&&ue.push(`Runner killed by signal ${ve}`),ye&&(!Xe||!X?ue.push(ye):A?.log?.("debug","RUNNER_STDERR_BENIGN","Runner stderr on clean exit",{stderr:ye})),K.current===F&&(ue.length>0&&S(ue.join(`
3
+ `)),p(!1),pe("runner","Event stream ended"),K.current=null)})().catch(X=>{let ie=[`Runner event loop error: ${X}`];F.exitCode!==null&&F.exitCode!==0&&ie.push(`Exit code: ${F.exitCode}`),F.exitSignal&&ie.push(`Signal: ${F.exitSignal}`),F.stderr&&ie.push(F.stderr),K.current===F&&(S(ie.join(`
4
+ `)),p(!1),pe("runner","Event loop error"),K.current=null)})},[e,n,s,c]),y=(0,D.useCallback)(x=>{K.current?.sendUserResponse(x),I(null)},[]),R=(0,D.useCallback)(()=>{let x=K.current;x&&(x.sendCancel("user"),p(!1),I(null),setTimeout(()=>{K.current===x&&(pe("runner","User cancelled run"),K.current=null)},5e3))},[]),m=(0,D.useCallback)(()=>{o([]),_(null),S(null)},[]);return(0,D.useEffect)(()=>()=>{ee.current=!0,pe("runner","Component unmounted"),K.current=null},[]),{isRunning:g,steps:d,askingUser:w,lastRunEnd:k,runError:U,bifurcationInfo:v,cmInitCounts:O,replayInfo:G,maxSteps:se,startRun:h,sendAnswer:y,cancelRun:R,clearLastRun:m}}function we(e){let n=e.flatMap(p=>[p,...p.children??[]]),s=n.filter(p=>p.status==="passed").length,c=n.filter(p=>p.status==="failed").length,g=n.filter(p=>p.status==="passed"||p.status==="failed").length;return{passed:s,failed:c,total:g}}function Fe(e){let n=De(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[s,c]=(0,q.useState)(0),[g,p]=(0,q.useState)("idle"),d=(0,q.useRef)("idle"),o=(0,q.useRef)(0),w=(0,q.useRef)(!1),I=(0,q.useRef)(null),k=(0,q.useRef)(null),_=(0,q.useCallback)(v=>{d.current=v,p(v)},[]),U=(0,q.useCallback)(async v=>{let B=await e.getNextConfig(v);if(!B){_("done"),e.onAllComplete?.();return}let O=v?o.current+1:0;o.current=O,c(O),e.onStepStart?.(B,O),I.current=null,k.current=null,_("running"),await n.startRun(B,e.spawnOpts)},[n,e,_]);(0,q.useEffect)(()=>{w.current||(w.current=!0,U(null))},[]),(0,q.useEffect)(()=>{if(!n.lastRunEnd||n.lastRunEnd===I.current||d.current!=="running")return;I.current=n.lastRunEnd,d.current="transitioning",p("transitioning");let v=n.lastRunEnd,B=we(n.steps),O=n.bifurcationInfo,Q={status:v.status==="passed"?"passed":"failed",duration_s:v.duration??0,reason:v.reason,runEnd:v,hadError:!1,stepsPassed:B.passed,stepsFailed:B.failed,stepsTotal:B.total,bifurcationFlows:O&&!O.isSingleFlow?O.flows:null};if(!(e.onStepEnd?.(Q,o.current)??!0)){_("done"),e.onAllComplete?.();return}U(Q)},[n.lastRunEnd]),(0,q.useEffect)(()=>{if(!n.runError||n.runError===k.current||n.lastRunEnd||d.current!=="running")return;k.current=n.runError,d.current="transitioning",p("transitioning");let v=we(n.steps),B={status:"failed",duration_s:0,reason:n.runError,runEnd:null,hadError:!0,stepsPassed:v.passed,stepsFailed:v.failed,stepsTotal:v.total,bifurcationFlows:null};if(!(e.onStepEnd?.(B,o.current)??!0)){_("done"),e.onAllComplete?.();return}U(B)},[n.runError,n.lastRunEnd]);let S=(0,q.useCallback)(()=>{n.cancelRun()},[n]);return{runner:n,currentStepIndex:s,phase:g,cancel:S}}var Ie=j(le(),1);var be=j(N(),1),Ae=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Me({label:e,hasBifurcation:n=!1}){let[s,c]=(0,Ie.useState)(0),[g,p]=(0,Ie.useState)(0);de(()=>{c(o=>(o+1)%Ae.length)},80),de(()=>{p(o=>(o+1)%4)},400);let d=e??(n?"Planning approach":"Analyzing objective");return(0,be.jsxs)(u,{marginLeft:1,children:[(0,be.jsxs)(i,{color:l.orange,children:[Ae[s]," "]}),(0,be.jsxs)(i,{color:l.dim,children:[d,".".repeat(g+1)]})]})}function Ne(e){if(!e.isRunning||e.replayInfo)return null;let n=e.bifurcationInfo;if(n&&!n.isSingleFlow){let s=e.steps.findIndex(g=>g.status==="running");return(s===-1?e.cmInitCounts.length===0:s>=e.cmInitCounts.length)?{label:s>0?`Planning flow ${s+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(s=>s.children?.length)?null:{hasBifurcation:!!n}}var M=j(le(),1);var Ue=j(le(),1);var Re=j(N(),1),Ye="#ffc580",Je="#ffd9a8",qe="#ffffff";function Ge({text:e,active:n=!0}){let[s,c]=(0,Ue.useState)(0),g=4;if(de(()=>{c(d=>(d+1)%(e.length+g*2))},n?80:null),!n)return(0,Re.jsx)(i,{color:qe,children:e});let p=e.split("").map((d,o)=>{let w=s-g,I=Math.abs(o-w-g/2),k;return I<=g/2?k=Ye:I<=g?k=Je:k=qe,(0,Re.jsx)(i,{color:k,children:d},o)});return(0,Re.jsx)(i,{children:p})}var z=j(N(),1),Qe={starting:l.orange,running:l.orange,passed:l.green,failed:l.red,cancelled:l.dim,timed_out:l.orange};function Se({currentStep:e,maxSteps:n,elapsed:s,status:c}){let{stdout:g}=xe(),p=g?.columns??80,d=Qe[c]??l.orange,o=s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m ${Math.round(s%60)}s`;return(0,z.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,z.jsx)(i,{color:l.muted,children:"\u2500".repeat(Math.min(p,60))}),(0,z.jsxs)(u,{children:[(0,z.jsx)(i,{children:" "}),(0,z.jsx)(i,{color:l.dim,children:"Steps "}),(0,z.jsx)(i,{bold:!0,children:e}),(0,z.jsxs)(i,{color:l.dim,children:["/",n]}),(0,z.jsx)(i,{children:" "}),(0,z.jsx)(i,{color:l.dim,children:"Elapsed "}),(0,z.jsx)(i,{bold:!0,children:o}),(0,z.jsx)(i,{children:" "}),(0,z.jsx)(i,{color:l.dim,children:"Status "}),(0,z.jsx)(i,{bold:!0,color:d,children:c})]})]})}var Ze={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 Ke(e){return Ze[e]??"\u25CF"}var oe=j(N(),1);function $e({steps:e,flows:n,cmInitCounts:s,renderStep:c}){return(0,oe.jsxs)(u,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,oe.jsxs)(i,{color:l.dim,children:["\u2501\u2501 Bifurcated into ",n?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((g,p)=>(0,oe.jsxs)(u,{flexDirection:"column",marginTop:p>0?1:0,children:[(0,oe.jsxs)(i,{color:l.orange,children:["Flow ",p+1,": ",n?.[p]??g.objective]}),s&&s[p]!=null&&(0,oe.jsxs)(i,{color:l.dim,children:[" \u25AA Generated task with ",s[p]," checkpoints"]}),g.children&&g.children.length>0?g.children.map(d=>{let o=!!d.branchObjective,w=`f${p}-${d.childId??"p"}-${d.index}`;return o?(0,oe.jsxs)(u,{flexDirection:"column",children:[c({...d,children:void 0},w),(d.children??[]).map(I=>(0,oe.jsx)(u,{marginLeft:2,children:c(I,`${w}-${I.childId??"p"}-${I.index}`)},`${w}-${I.childId??"p"}-${I.index}`))]},`${w}-host`):c(d,w)}):g.status==="pending"&&(0,oe.jsx)(i,{color:l.dim,children:" \u25CB Waiting..."})]},p))]})}var r=j(N(),1);function W({step:e,indent:n=2}){let s=e.actionType?Ke(e.actionType):null,c=e.status==="running",g=e.status==="passed",p=e.status==="failed",d=e.status==="pending"||e.status==="stopped",{stdout:o}=xe(),w=o?.columns??80,I=Math.max(20,w-n-21),k=e.objective??"",_=k.length>I?k.slice(0,I-1)+"\u2026":k,U=(e.duration??0)*1e3,S=e.duration!=null?U<1e3?`${Math.round(U)}ms`:`${(U/1e3).toFixed(1)}s`:"";return(0,r.jsxs)(u,{flexDirection:"column",children:[(0,r.jsxs)(u,{marginLeft:n,children:[(0,r.jsx)(u,{width:4,children:(0,r.jsxs)(i,{color:l.muted,children:[String(e.index).padStart(2," ")," "]})}),(0,r.jsx)(u,{width:3,children:c?(0,r.jsx)(je,{}):g?(0,r.jsx)(i,{color:l.green,bold:!0,children:"\u2713"}):p?(0,r.jsx)(i,{color:l.red,bold:!0,children:"\u2717"}):(0,r.jsx)(i,{color:l.muted,children:"\u25CB"})}),(0,r.jsx)(u,{flexGrow:1,children:c?(0,r.jsx)(Ge,{text:_,active:!0}):p?(0,r.jsx)(i,{color:l.red,children:_}):d?(0,r.jsx)(i,{color:l.dim,children:_}):(0,r.jsx)(i,{color:l.dim,children:_})}),(g||p)&&s?(0,r.jsx)(u,{width:3,marginLeft:1,children:(0,r.jsx)(i,{color:l.muted,children:s})}):(0,r.jsx)(u,{width:3,marginLeft:1}),(0,r.jsx)(u,{width:7,justifyContent:"flex-end",children:(0,r.jsx)(i,{color:l.dim,children:S})})]}),e.children&&e.children.length>0&&(0,r.jsx)(u,{flexDirection:"column",children:e.children.map((v,B)=>(0,r.jsx)(W,{step:v,indent:n+2},`child-${B}`))})]})}function et(e){return e.type==="cm_init"?(0,r.jsx)(u,{marginLeft:2,paddingLeft:1,children:(0,r.jsxs)(i,{color:l.dim,children:["\u25AA Generated task with ",e.count," checkpoints"]})}):(0,r.jsx)(u,{marginLeft:2,paddingLeft:1,children:(0,r.jsx)(W,{step:e.step})})}function We({steps:e,bifurcated:n,flows:s,cmInitCounts:c,maxSteps:g=50,staticSteps:p=!1,onStepCommit:d}){let o=(0,M.useRef)(new Set),w=(0,M.useRef)(!1),I=(0,M.useRef)(new Set),k=(0,M.useRef)(!1),_=(0,M.useRef)(new Set),U=(0,M.useRef)(0);(0,M.useEffect)(()=>{e.length===0&&U.current>0&&(o.current.clear(),w.current=!1,I.current.clear(),k.current=!1,_.current.clear()),U.current=e.length},[e.length]);let S=e.flatMap(h=>[h,...h.children??[]]),v=S.some(h=>h.status==="running"),B=S.some(h=>h.status==="failed"),O=S.length===0||S.every(h=>h.status==="pending"),Q=S.filter(h=>h.status==="passed"||h.status==="failed").length,G;O?G="starting":v?G="running":B?G="failed":G="passed";let ne=(0,M.useRef)(null),[se,ge]=(0,M.useState)(0);(0,M.useEffect)(()=>{S.length===0||O?(ne.current=null,ge(0)):v&&ne.current==null&&(ne.current=Date.now())},[v,O,S.length]),(0,M.useEffect)(()=>{if(!v)return;let h=setInterval(()=>{ne.current!=null&&ge((Date.now()-ne.current)/1e3)},500);return()=>clearInterval(h)},[v]);let K=(0,M.useRef)(new Set),[,H]=(0,M.useState)(0),Z=(0,M.useRef)(!1);(0,M.useEffect)(()=>{if(!d||!p||n)return;let h=[];!Z.current&&c&&c[0]!=null&&(Z.current=!0,c[0]>0&&h.push({key:"cm_init_0",type:"cm_init",count:c[0]}));for(let y of e)(y.status==="passed"||y.status==="failed")&&!K.current.has(y.index)&&(K.current.add(y.index),h.push({key:`step_${y.index}`,type:"step",step:{...y,children:y.children?[...y.children]:void 0}}));if(h.length>0){for(let y of h)d(et(y));H(y=>y+1)}},[e,n,c,p,d]),(0,M.useEffect)(()=>{if(!d||p)return;let h=o.current.size;if(!n&&!k.current&&c&&c[0]!=null&&(k.current=!0,c[0]>0&&d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsxs)(i,{color:l.dim,children:["\u25A0 Generated task with ",c[0]," checkpoints"]})}))),n&&s&&!w.current&&(w.current=!0,d((0,r.jsx)(i,{color:l.purple,children:"\u2501\u2501 Bifurcated into "+s.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),n){let y=e.flatMap((R,m)=>{let x=R.children??[];return!I.current.has(m)&&x.length>0&&(I.current.add(m),d((0,r.jsx)(i,{color:l.purple,children:" Flow "+(m+1)+": "+(s?.[m]??"")})),c?.[m]!=null&&c[m]>0&&!_.current.has(m)&&(_.current.add(m),d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsxs)(i,{color:l.dim,children:[" \u25AA Generated task with ",c[m]," checkpoints"]})})))),c?.[m]!=null&&c[m]>0&&I.current.has(m)&&!_.current.has(m)&&(_.current.add(m),d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsxs)(i,{color:l.dim,children:[" \u25AA Generated task with ",c[m]," checkpoints"]})}))),x});for(let R of y){let m=`${R.childId??"p"}-${R.index}-${R.objective}`;if(!!R.branchObjective){o.current.has(m)||(o.current.add(m),d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsx)(W,{step:{...R,children:void 0}})})));for(let A of R.children??[]){let re=`child-${R.childId??"p"}-${R.index}-${A.childId??"p"}-${A.index}-${A.objective}`;o.current.has(re)||(A.status==="passed"||A.status==="failed"||A.status==="stopped")&&(o.current.add(re),d((0,r.jsx)(u,{marginLeft:4,children:(0,r.jsx)(W,{step:A})})))}continue}o.current.has(m)||(R.status==="passed"||R.status==="failed"||R.status==="stopped")&&(o.current.add(m),d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsx)(W,{step:R})})))}}else for(let y of e){let R=`${y.index}-${y.objective}`,m=!!y.branchObjective;m&&!o.current.has(R)&&(o.current.add(R),d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsx)(W,{step:{...y,children:void 0}})})));for(let x of y.children??[]){let A=`child-${y.index}-${x.childId??"p"}-${x.index}-${x.objective}`;o.current.has(A)||(x.status==="passed"||x.status==="failed"||x.status==="stopped")&&(o.current.add(A),d((0,r.jsx)(u,{marginLeft:4,children:(0,r.jsx)(W,{step:x})})))}!m&&!o.current.has(R)&&(y.status==="passed"||y.status==="failed"||y.status==="stopped")&&(o.current.add(R),d((0,r.jsx)(u,{marginLeft:2,children:(0,r.jsx)(W,{step:{...y,children:void 0}})})))}o.current.size>h&&H(y=>y+1)},[e,d,n,s,c]);let ee=[];if(p&&!n)for(let h of e)K.current.has(h.index)||ee.push(h);else if(d&&!p)if(n)for(let h of e){let y=h.children??[],R=[];for(let m of y){let x=`${m.childId??"p"}-${m.index}-${m.objective}`,A=o.current.has(x);if(m.branchObjective){let re=(m.children??[]).filter(F=>{let X=`child-${m.childId??"p"}-${m.index}-${F.childId??"p"}-${F.index}-${F.objective}`;return!o.current.has(X)});(!A||re.length>0)&&R.push({...m,children:re})}else A||R.push(m)}R.length>0&&ee.push({...h,children:R})}else for(let h of e){let y=`${h.index}-${h.objective}`,R=o.current.has(y),m=(h.children??[]).filter(x=>{let A=`child-${h.index}-${x.childId??"p"}-${x.index}-${x.objective}`;return!o.current.has(A)});R?m.length>0&&ee.push({...h,children:m}):ee.push({...h,children:m})}if(!p){let h=d?ee:e;return(0,r.jsxs)(u,{flexDirection:"column",children:[n?d?h.length>0?(0,r.jsx)(u,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:h.map((R,m)=>(0,r.jsx)(u,{flexDirection:"column",marginTop:m>0?1:0,children:R.children&&R.children.length>0?R.children.map(x=>{let A=!!x.branchObjective,re=`${x.childId??"p"}-${x.index}-${x.objective}`,F=o.current.has(re);return A?(0,r.jsxs)(u,{flexDirection:"column",children:[!F&&(0,r.jsx)(W,{step:{...x,children:void 0}}),(x.children??[]).map(X=>(0,r.jsx)(u,{marginLeft:2,children:(0,r.jsx)(W,{step:X})},`f${m}-${x.index}-${X.childId??"p"}-${X.index}`))]},`f${m}-host-${x.childId??"p"}-${x.index}`):(0,r.jsx)(W,{step:x},`f${m}-${x.childId??"p"}-${x.index}`)}):R.status==="pending"&&(0,r.jsx)(i,{color:l.dim,children:" \u25CB Waiting..."})},m))}):null:(0,r.jsx)($e,{steps:e,flows:s,cmInitCounts:c,renderStep:(R,m)=>(0,r.jsx)(W,{step:R},m)}):(0,r.jsxs)(u,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!d&&c&&c[0]!=null&&(0,r.jsxs)(i,{color:l.dim,children:["\u25AA Generated task with ",c[0]," checkpoints"]}),h.map(R=>{let m=`${R.index}-${R.objective}`;return d&&o.current.has(m)?(0,r.jsx)(u,{flexDirection:"column",children:(R.children??[]).map(x=>(0,r.jsx)(u,{marginLeft:2,children:(0,r.jsx)(W,{step:x})},`${x.childId??"p"}-${x.index}`))},`branch-children-${R.index}`):(0,r.jsx)(W,{step:R},R.index)})]}),v&&(0,r.jsx)(Se,{currentStep:Q,maxSteps:g,elapsed:se,status:G})]})}return n?(0,r.jsxs)(u,{flexDirection:"column",children:[(0,r.jsx)($e,{steps:e,flows:s,cmInitCounts:c,renderStep:(h,y)=>(0,r.jsx)(W,{step:h},y)}),v&&(0,r.jsx)(Se,{currentStep:Q,maxSteps:g,elapsed:se,status:G})]}):(0,r.jsxs)(u,{flexDirection:"column",children:[ee.length>0&&(0,r.jsx)(u,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:ee.map(h=>(0,r.jsx)(W,{step:h},h.index))}),v&&(0,r.jsx)(Se,{currentStep:Q,maxSteps:g,elapsed:se,status:G})]})}var ae=j(N(),1);function He({runner:e,runKey:n,onStepCommit:s}){let c=Ne({isRunning:e.isRunning,bifurcationInfo:e.bifurcationInfo,steps:e.steps,cmInitCounts:e.cmInitCounts,replayInfo:e.replayInfo});return(0,ae.jsxs)(ae.Fragment,{children:[c&&(0,ae.jsx)(Me,{label:c.label,hasBifurcation:c.hasBifurcation}),e.isRunning&&e.steps.length>0&&(0,ae.jsx)(We,{steps:e.steps,bifurcated:!!e.bifurcationInfo&&!e.bifurcationInfo.isSingleFlow,flows:e.bifurcationInfo?.flows,cmInitCounts:e.cmInitCounts,maxSteps:e.maxSteps,onStepCommit:s},`run-${n}`)]})}var Y=j(N(),1),tt=64;function nt(e){return e.split(`
5
+ `).map(n=>n.replace(/^[-–•]\s*/,"").trim()).filter(n=>n.length>0)}function Ve({status:e,summary:n,duration:s,steps:c,stepsPassed:g,stepsFailed:p,reason:d,creditsConsumed:o}){let w=e==="passed",I=w?l.green:l.red,k=w?"\u2713":"\u2717",_=e.toUpperCase(),U=g??(w?c:Math.max(0,c-1)),S=p??(w?0:1),v=S>0?`${c} steps (${U} passed, ${S} failed)`:`${c} steps`,B=s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m ${Math.round(s%60)}s`,O=nt(n);return(0,Y.jsx)(u,{flexDirection:"column",marginTop:1,children:(0,Y.jsxs)(u,{borderStyle:"round",borderColor:I,flexDirection:"column",paddingX:2,paddingY:1,width:tt+6,children:[(0,Y.jsxs)(u,{flexDirection:"column",children:[(0,Y.jsxs)(i,{bold:!0,color:I,children:[k," ",_]}),(0,Y.jsxs)(i,{color:l.dim,wrap:"wrap",children:[v," \xB7 ",B,typeof o=="number"&&o>0?` \xB7 ${parseFloat(o.toFixed(4))} credits`:""]})]}),O.length>0&&(0,Y.jsx)(u,{flexDirection:"column",marginTop:1,marginLeft:1,children:O.map((Q,G)=>(0,Y.jsxs)(u,{marginBottom:G<O.length-1?1:0,children:[(0,Y.jsx)(i,{color:l.orange,children:"\u25CF "}),(0,Y.jsx)(u,{flexShrink:1,children:(0,Y.jsx)(i,{wrap:"wrap",children:Q})})]},G))}),d&&!w&&(0,Y.jsx)(u,{marginTop:1,children:(0,Y.jsxs)(i,{color:l.red,wrap:"wrap",children:["Reason: ",d]})})]})})}var J=j(N(),1);function ze({message:e,code:n,remediation:s,docsUrl:c}){return(0,J.jsx)(Ce,{title:"Error",variant:"error",children:(0,J.jsxs)(u,{flexDirection:"column",paddingY:1,children:[(0,J.jsxs)(i,{color:l.red,bold:!0,children:[" \u2717 ",e]}),n&&(0,J.jsxs)(u,{marginTop:0,marginLeft:5,children:[(0,J.jsx)(i,{color:l.muted,children:"Code: "}),(0,J.jsx)(i,{color:l.dim,children:n})]}),s&&(0,J.jsxs)(u,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,J.jsx)(i,{color:l.green,bold:!0,children:"Fix:"}),(0,J.jsxs)(i,{color:l.orange,children:["$ ",s]})]}),c&&(0,J.jsxs)(u,{marginTop:1,marginLeft:5,children:[(0,J.jsx)(i,{color:l.muted,children:"Docs: "}),(0,J.jsx)(i,{color:l.orange,underline:!0,children:c})]})]})})}var P=j(N(),1);function sn(e){let{exit:n}=ke(),{append:s}=_e(),c=(0,te.useRef)(!1);(0,te.useEffect)(()=>{c.current||(c.current=!0,s((0,P.jsx)(u,{flexDirection:"column",marginBottom:1,children:(0,P.jsxs)(u,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,P.jsx)(i,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,P.jsx)(i,{color:l.dim,children:" \u2502 "}),(0,P.jsx)(i,{color:l.orange,children:e.topBanner.model}),(0,P.jsx)(i,{color:l.dim,children:" \u2502 "}),(0,P.jsx)(i,{color:l.dim,children:e.topBanner.auth})]})})),s((0,P.jsx)(rt,{data:e.globalConfig})),e.priorAttemptRollup&&s((0,P.jsx)(i,{color:l.dim,children:` \u21B3 replayed ${e.priorAttemptRollup.startIdx}..${e.priorAttemptRollup.endIdx-1} (${e.priorAttemptRollup.count} steps, from prior attempt)`})))},[]);let g=(0,te.useRef)(null),p=(0,te.useCallback)(async S=>{let v=await e.getNextStep(S);return v?(g.current=v,v.config):(g.current=null,null)},[e]),d=(0,te.useCallback)((S,v)=>{let B=g.current;if(!B)return;let O=B.mode==="replay"?"cyan":"#dc4e08",Q=B.modeReason?` (${B.modeReason})`:"",G=B.perStepOverrides?Object.entries(B.perStepOverrides):[];s((0,P.jsxs)(u,{flexDirection:"column",marginBottom:0,children:[(0,P.jsxs)(i,{children:[(0,P.jsxs)(i,{color:l.dim,children:[B.banner.stepLabel," "]}),(0,P.jsxs)(i,{color:O,children:["[",B.mode,"]"]}),(0,P.jsx)(i,{color:l.dim,children:Q})]}),(0,P.jsx)(i,{color:l.dim,children:B.banner.objective}),G.length>0&&(0,P.jsxs)(i,{color:l.dim,children:["overrides: ",G.map(([ne,se])=>`${ne}=${se}`).join(", ")]})]}))},[s]),o=(0,te.useRef)(0),w=(0,te.useRef)(!1),I=(0,te.useCallback)((S,v)=>(S.hadError?s((0,P.jsx)(ze,{message:S.reason??"Runner error",code:"RUNNER_ERROR"})):s((0,P.jsx)(u,{flexDirection:"column",marginBottom:1,children:(0,P.jsx)(Ve,{status:S.status,summary:S.runEnd?.summary??"",duration:S.runEnd?.duration??0,steps:S.stepsTotal,stepsPassed:S.stepsPassed,stepsFailed:S.stepsFailed,reason:S.runEnd?.reason,creditsConsumed:S.runEnd?.credits_consumed})})),e.onStepEnd?.(S,v)??!0),[s,e]),k=Fe({getNextConfig:p,onStepStart:d,onStepEnd:I,onAllComplete:()=>{e.onAllComplete(),e.exitOnComplete!==!1&&setImmediate(()=>n())},screenshotDispatcher:e.screenshotDispatcher,stepLogger:e.stepLogger,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete,spawnOpts:e.spawnOpts}),_=250,U=5e3;return Ee((S,v)=>{if(v.ctrl&&S==="c"){let B=Date.now(),O=B-o.current;if(O<_)return;w.current&&O<U?(k.cancel(),e.onCancel?.(),e.exitOnComplete!==!1&&setImmediate(()=>n())):(w.current=!0,s((0,P.jsx)(i,{color:"yellow",children:"press Ctrl+C again to cancel run"}))),o.current=B}}),(0,P.jsx)(u,{flexDirection:"column",children:k.phase!=="done"&&(0,P.jsx)(He,{runner:k.runner,runKey:k.currentStepIndex,onStepCommit:s})})}function rt({data:e}){return(0,P.jsx)(Pe,{title:"test.md run",titleColor:"#ff9500",borderColor:l.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{We as a,Me as b,Ne as c,De as d,we as e,Ve as f,ze as g,sn as h};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a}from"./chunk-WAOCHXJ5.js";import{a as c}from"./chunk-NLCCBXXV.js";import{a as o}from"./chunk-RZ4F3BHX.js";var u=class{constructor(e,r,t,s){this.controllerBaseUrl=e;this.getOAuthToken=r;this.directBasicAuth=t;this.log=s}_cached=null;_revoked=!1;_lastError=null;revoke(){this._revoked=!0,this._cached=null}prime(e){this._revoked||(this._cached=e)}get revoked(){return this._revoked}get cached(){return this._cached}get lastError(){return this._lastError}async resolve(e=!1){if(this._cached&&!e)return this._cached;try{let r;if(this.directBasicAuth)r=new a(this.controllerBaseUrl,{username:this.directBasicAuth.username,accessKey:this.directBasicAuth.access_key});else{let s=await this.getOAuthToken();if(!s)return null;r=new a(this.controllerBaseUrl,s)}let t=await r.getTmsCredentials();return this.directBasicAuth&&!t.access_key&&(t.access_key=this.directBasicAuth.access_key),this._cached=t,this._lastError=null,this.log?.("info","AUTH_RESOLVE_OK","Auth resolved",{username:t.username,org_id:t.org_id,user_id:t.user_id}),t}catch(r){return this._lastError=r instanceof Error?r:new Error(String(r)),this.log?.("warn","AUTH_RESOLVE_FAILED","Auth resolve failed",{error:this._lastError.message}),null}}async fetch(e,r={}){if(this._revoked)throw new Error("Resolver has been revoked \u2014 identity changed");let t=await this.resolve();if(!t)throw new Error("Not authenticated \u2014 no credentials resolved");let s=i=>({...r,headers:{...r.headers,Authorization:c(i.username,i.access_key)}}),l=await o(e,s(t));if(l.status===401){if(this._revoked)throw new Error("Resolver has been revoked \u2014 identity changed");this.log?.("warn","AUTH_RESOLVE_401","Got 401, re-resolving",{url:e});let i=await this.resolve(!0);if(!i)throw new Error("Re-authentication failed after 401");return o(e,s(i))}return l}};function f(n){if(!n)return"network";let e=/failed:\s*(\d{3})\b/.exec(n.message)?.[1];return e==="401"||e==="403"?"auth":e?"server":"network"}export{u as a,f as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as s}from"./chunk-HCBYKLMW.js";import{t as n}from"./chunk-3Z4EHIOW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
2
+ import{v as n}from"./chunk-3QWAABMG.js";import{a as s}from"./chunk-HCBYKLMW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as s,h as l}from"./chunk-3Z4EHIOW.js";import{readFileSync as d,writeFileSync as i,mkdirSync as o,existsSync as p}from"fs";import{dirname as a}from"path";var n={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:l,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",code_export:{enabled:!0,language:"python",skip_validation:!0},generate:{scenario_limit:2,per_scenario_limit:3,memory_enabled:!1},last_seen_version:""},c=class{constructor(t=s){this.path=t}exists(){return p(this.path)}load(){try{let t=d(this.path,"utf-8"),e=JSON.parse(t);return{...n,...e,code_export:{...n.code_export,...e.code_export??{}},generate:{...n.generate,...e.generate??{}}}}catch{return{...n,code_export:{...n.code_export},generate:{...n.generate}}}}set(t,e){try{let r=this.load();r[t]=e,o(a(this.path),{recursive:!0}),i(this.path,JSON.stringify(r,null,2)+`
2
+ import{d as s,j as l}from"./chunk-3QWAABMG.js";import{readFileSync as d,writeFileSync as i,mkdirSync as o,existsSync as p}from"fs";import{dirname as a}from"path";var n={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:l,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",code_export:{enabled:!0,language:"python",skip_validation:!0},generate:{scenario_limit:2,per_scenario_limit:3,memory_enabled:!1},last_seen_version:""},c=class{constructor(t=s){this.path=t}exists(){return p(this.path)}load(){try{let t=d(this.path,"utf-8"),e=JSON.parse(t);return{...n,...e,code_export:{...n.code_export,...e.code_export??{}},generate:{...n.generate,...e.generate??{}}}}catch{return{...n,code_export:{...n.code_export},generate:{...n.generate}}}}set(t,e){try{let r=this.load();r[t]=e,o(a(this.path),{recursive:!0}),i(this.path,JSON.stringify(r,null,2)+`
3
3
  `)}catch(r){let g=r instanceof Error?r.message:String(r);process.stderr.write(`[config] Failed to save config: ${g}
4
4
  `)}}save(t){try{let r={...this.load(),...t};o(a(this.path),{recursive:!0}),i(this.path,JSON.stringify(r,null,2)+`
5
5
  `)}catch(e){let r=e instanceof Error?e.message:String(e);process.stderr.write(`[config] Failed to save config: ${r}
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as v}from"./chunk-S7JV4A3U.js";import{spawn as x,execSync as N}from"child_process";import{existsSync as g}from"fs";import{resolve as e,dirname as b}from"path";import{fileURLToPath as A}from"url";import{createInterface as w}from"readline";async function*_(i){let n=w({input:i,crlfDelay:1/0});for await(let l of n){let r=l.trim();if(r)try{let d=JSON.parse(r);d&&typeof d.type=="string"&&(yield d)}catch{}}}function E(i){return i==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_AGENT_SKIP_CP_FINAL:"true",V16_BIFURCATION_PHASES:"1"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_AGENT_SKIP_CP_FINAL","V16_BIFURCATION_PHASES"]}}var c=b(A(import.meta.url));function C(){for(let i of["python3","python"])try{return N(`${i} --version`,{stdio:"ignore"}),i}catch{}return null}function h(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",l={"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"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},r=`${process.platform}-${process.arch}`,d=l[r];if(d)for(let t of d){let a=[e(c,"..","node_modules",t,"bin",n),e(c,"..","..","node_modules",t,"bin",n),e(c,"..","..","..","node_modules",t,"bin",n),e(c,"..","..","..","..","node_modules",t,"bin",n)];for(let u of a)if(g(u))return{cmd:u,args:[]}}let p=[e(c,"bin",n),e(c,"..","bin",n),e(c,"..","..","..","..","v16-runner","dist",n),e(c,"..","..","..","v16-runner","dist",n),e(process.cwd(),"v16-runner","dist",n),e(process.cwd(),"..","v16-runner","dist",n)];for(let t of p)if(g(t))return{cmd:t,args:[]};let s=[e(c,"..","..","..","..","v16-runner"),e(c,"..","..","..","v16-runner"),e(process.cwd(),"v16-runner"),e(process.cwd(),"..","v16-runner")];for(let t of s)if(g(e(t,"main.py"))){for(let u of[e(t,".venv","bin","python"),e(t,"..","browser-agent",".venv","bin","python")])if(g(u))return{cmd:u,args:["main.py"],cwd:t};let a=C();if(a)return{cmd:a,args:["main.py"],cwd:t}}return null}function G(i,n){let l=h();if(!l)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");let r={...process.env};n?.environment&&(r.TESTMUAI_ENV=n.environment),r.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(r.PYTHONIOENCODING="utf-8");let d=v(n?.environment);r.V16_SERVER_API_HOST=d.v16ServerHost,r.ATMS_URL=d.tmsBaseUrl.replace(/\/api\/?$/,""),i.username&&i.access_key&&(r.LT_USERNAME=i.username,r.LT_ACCESS_KEY=i.access_key),i.session_id&&(r.TESTMUAI_SESSION_ID=i.session_id);let p=E(n?.mode??"testing");Object.assign(r,p.set);for(let o of p.unset)delete r[o];let s=x(l.cmd,l.args,{stdio:["pipe","pipe","pipe"],env:r,cwd:l.cwd});s.stdin.on("error",()=>{}),s.stdin.write(JSON.stringify(i)+`
3
+ `);let t=1e5,a="";s.stderr.on("data",o=>{a+=o.toString(),a.length>t&&(a=a.slice(-t))}),s.on("error",o=>{n?.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:o.message})});let u=null,f=null,S=new Promise(o=>{s.on("close",(m,y)=>{u=m,f=y?String(y):null,n?.log?.("info","RUNNER_EXIT","Runner exited",{code:m,signal:f??"none"}),o({code:m,signal:f})})}),R=_(s.stdout);return{child:s,events:R,sendUserResponse(o){let m=JSON.stringify({type:"user_response",answer:o});try{s.stdin.write(m+`
4
+ `)}catch{}},sendCancel(o){let m=JSON.stringify({type:"cancel",reason:o});try{s.stdin.write(m+`
5
+ `)}catch{}},cancel(){s.kill("SIGTERM")},get stderr(){return a},get exitCode(){return u},get exitSignal(){return f},exited:S}}export{h as a,G as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,c,e as o}from"./chunk-3Z4EHIOW.js";import{a as l}from"./chunk-RZ4F3BHX.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
2
+ import{a as l}from"./chunk-RZ4F3BHX.js";import{a,c,e as o}from"./chunk-3QWAABMG.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
@@ -0,0 +1,10 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ var v=()=>!!process.env.KANE_DEV_MODE,t=[],u=!1,f=null,c=null,a=null,i=null;function x(e){i=e}function m(){return i}function h(){return u}function y(e,r){t=t.filter(o=>o.name!==e),t.push({name:e,fn:r})}function R(e){t=t.filter(r=>r.name!==e)}function w(e,r){let o=t.find(n=>n.name===e);if(!o)return;t=t.filter(n=>n.name!==e);let s=!0;try{o.fn()}catch(n){s=!1,process.stderr.write(`[exit-manager] cleanup(${e}) failed: ${n instanceof Error?n.message:String(n)}
3
+ `)}r&&s&&v()&&process.stderr.write(`[exit-manager] cleanup(${e}): ${r}
4
+ `)}function l(e,r,o=!1){if(u){process.exit(f??e);return}if(u=!0,f=e,o&&i)try{i.log("error","CRASH",r),i.shutdownSync()}catch{}let s=[...t].reverse(),n=[];for(let g of s)try{g.fn(),n.push(g.name)}catch(d){process.stderr.write(`[exit-manager] cleanup(${g.name}) failed: ${d instanceof Error?d.message:String(d)}
5
+ `)}if(t=[],v()&&(process.stderr.write(`[exit-manager] shutdown(${e}): ${r}
6
+ `),n.length>0&&process.stderr.write(`[exit-manager] cleaned up: ${n.join(", ")}
7
+ `)),o&&a){try{a()}catch{}process.stderr.write(`
8
+ Kane CLI crashed unexpectedly: ${r}
9
+ `+(n.length>0?`Resources cleaned up (${n.join(", ")}).
10
+ `:"")),process.exit(e);return}if(c&&!o){c();return}process.exit(e)}function E(e){c=e}function $(e){a=e}var p=!1;function S(){p||(p=!0,process.on("SIGINT",()=>{l(130,"Received SIGINT",!0)}),process.on("SIGTERM",()=>{l(143,"Received SIGTERM",!0)}),process.on("uncaughtException",e=>{l(1,`Uncaught exception: ${e.message}`,!0)}),process.on("unhandledRejection",e=>{l(1,`Unhandled rejection: ${String(e)}`,!0)}))}function L(){t=[],u=!1,f=null,c=null,a=null,i=null,p=!1}export{x as a,m as b,h as c,y as d,R as e,w as f,l as g,E as h,$ as i,S as j,L as k};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as D,b as A}from"./chunk-7G7ZLAJH.js";import{l as S,m as C,n as P,o as U,p as N}from"./chunk-3Z4EHIOW.js";import{createServer as Oe}from"http";import{randomBytes as He}from"crypto";import{URL as $e}from"url";import Z from"process";import{Buffer as ee}from"buffer";import re from"path";import{fileURLToPath as ke}from"url";import{promisify as Le}from"util";import te from"child_process";import Me,{constants as Ie}from"fs/promises";import Y from"process";import G,{constants as me}from"fs/promises";import j from"process";import le from"os";import L from"fs";import se from"fs";import z from"fs";var E;function ie(){try{return z.statSync("/.dockerenv"),!0}catch{return!1}}function ae(){try{return z.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function B(){return E===void 0&&(E=ie()||ae()),E}var k,ce=()=>{try{return se.statSync("/run/.containerenv"),!0}catch{return!1}};function u(){return k===void 0&&(k=ce()||B()),k}var K=()=>{if(j.platform!=="linux")return!1;if(le.release().toLowerCase().includes("microsoft"))return!u();try{if(L.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!u()}catch{}return L.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||L.existsSync("/run/WSL")?!u():!1},d=j.env.__IS_WSL_TEST__?K:K();var de=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let t="/etc/wsl.conf",n=!1;try{await G.access(t,me.F_OK),n=!0}catch{}if(!n)return e;let o=await G.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return i?(r=i.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),fe=async()=>`${await de()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,M=async()=>d?fe():`${Y.env.SYSTEMROOT||Y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function f(e,r,t){let n=o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let o=t();return n(o),o},set(o){n(o)}}),e}import{promisify as Pe}from"util";import O from"process";import{execFile as Ae}from"child_process";import{promisify as pe}from"util";import ue from"process";import{execFile as ge}from"child_process";var he=pe(ge);async function I(){if(ue.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await he("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import we from"process";import{promisify as xe}from"util";import{execFile as ye,execFileSync as cr}from"child_process";var ve=xe(ye);async function X(e,{humanReadableOutput:r=!0,signal:t}={}){if(we.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],o={};t&&(o.signal=t);let{stdout:i}=await ve("osascript",["-e",e,n],o);return i.trim()}async function T(e){return X(`tell application "Finder" to set app_path to application file id "${e}" as string
2
+ import{a as D}from"./chunk-PF7PBYCJ.js";import{a as A}from"./chunk-WFSTRBQF.js";import{n as S,o as C,p as P,q as U,r as N}from"./chunk-3QWAABMG.js";import{createServer as Oe}from"http";import{randomBytes as He}from"crypto";import{URL as $e}from"url";import Z from"process";import{Buffer as ee}from"buffer";import re from"path";import{fileURLToPath as ke}from"url";import{promisify as Le}from"util";import te from"child_process";import Me,{constants as Ie}from"fs/promises";import Y from"process";import G,{constants as me}from"fs/promises";import j from"process";import le from"os";import L from"fs";import se from"fs";import z from"fs";var E;function ie(){try{return z.statSync("/.dockerenv"),!0}catch{return!1}}function ae(){try{return z.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function B(){return E===void 0&&(E=ie()||ae()),E}var k,ce=()=>{try{return se.statSync("/run/.containerenv"),!0}catch{return!1}};function u(){return k===void 0&&(k=ce()||B()),k}var K=()=>{if(j.platform!=="linux")return!1;if(le.release().toLowerCase().includes("microsoft"))return!u();try{if(L.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!u()}catch{}return L.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||L.existsSync("/run/WSL")?!u():!1},d=j.env.__IS_WSL_TEST__?K:K();var de=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let t="/etc/wsl.conf",n=!1;try{await G.access(t,me.F_OK),n=!0}catch{}if(!n)return e;let o=await G.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return i?(r=i.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),fe=async()=>`${await de()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,M=async()=>d?fe():`${Y.env.SYSTEMROOT||Y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function f(e,r,t){let n=o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let o=t();return n(o),o},set(o){n(o)}}),e}import{promisify as Pe}from"util";import O from"process";import{execFile as Ae}from"child_process";import{promisify as pe}from"util";import ue from"process";import{execFile as ge}from"child_process";var he=pe(ge);async function I(){if(ue.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await he("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import we from"process";import{promisify as xe}from"util";import{execFile as ye,execFileSync as cr}from"child_process";var ve=xe(ye);async function X(e,{humanReadableOutput:r=!0,signal:t}={}){if(we.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],o={};t&&(o.signal=t);let{stdout:i}=await ve("osascript",["-e",e,n],o);return i.trim()}async function T(e){return X(`tell application "Finder" to set app_path to application file id "${e}" as string
3
3
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as be}from"util";import{execFile as Se}from"child_process";var Ce=be(Se),y={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},ur=new Map(Object.entries(y)),F=class extends Error{};async function _(e=Ce){let{stdout:r}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(r);if(!t)throw new F(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);let{id:n}=t.groups,o=n.lastIndexOf("."),i=n.lastIndexOf("-"),c=o===-1?void 0:n.slice(0,o),a=i===-1?void 0:n.slice(0,i);return y[n]??y[c]??y[a]??{name:n,id:n}}var Ee=Pe(Ae),Be=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase());async function H(){if(O.platform==="darwin"){let e=await I();return{name:await T(e),id:e}}if(O.platform==="linux"){let{stdout:e}=await Ee("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:Be(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(O.platform==="win32")return _();throw new Error("Only macOS, Linux, and Windows are supported")}var Te=Le(te.execFile),$=re.dirname(ke(import.meta.url)),q=re.join($,"xdg-open"),{platform:w,arch:V}=Z;async function Fe(){let e=await M(),r=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=ee.from(r,"utf16le").toString("base64"),{stdout:n}=await Te(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),o=n.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[o]?{id:i[o]}:{}}var J=async(e,r)=>{let t;for(let n of e)try{return await r(n)}catch(o){t=o}throw t},v=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return J(e.app,a=>v({...e,app:a}));let{name:r,arguments:t=[]}=e.app??{};if(t=[...t],Array.isArray(r))return J(r,a=>v({...e,app:{name:a,arguments:t}}));if(r==="browser"||r==="browserPrivate"){let a={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},s=d?await Fe():await H();if(s.id in a){let m=a[s.id];return r==="browserPrivate"&&t.push(l[m]),v({...e,app:{name:g[m],arguments:t}})}throw new Error(`${s.name} is not supported as a default browser`)}let n,o=[],i={};if(w==="darwin")n="open",e.wait&&o.push("--wait-apps"),e.background&&o.push("--background"),e.newInstance&&o.push("--new"),r&&o.push("-a",r);else if(w==="win32"||d&&!u()&&!r){n=await M(),o.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),d||(i.windowsVerbatimArguments=!0);let a=["Start"];e.wait&&a.push("-Wait"),r?(a.push(`"\`"${r}\`""`),e.target&&t.push(e.target)):e.target&&a.push(`"${e.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),e.target=ee.from(a.join(" "),"utf16le").toString("base64")}else{if(r)n=r;else{let a=!$||$==="/",l=!1;try{await Me.access(q,Ie.X_OK),l=!0}catch{}n=Z.versions.electron??(w==="android"||a||!l)?"xdg-open":q}t.length>0&&o.push(...t),e.wait||(i.stdio="ignore",i.detached=!0)}w==="darwin"&&t.length>0&&o.push("--args",...t),e.target&&o.push(e.target);let c=te.spawn(n,o,i);return e.wait?new Promise((a,l)=>{c.once("error",l),c.once("close",s=>{if(!e.allowNonzeroExitCode&&s>0){l(new Error(`Exited with code ${s}`));return}a(c)})}):(c.unref(),c)},_e=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return v({...r,target:e})};function Q(e){if(typeof e=="string"||Array.isArray(e))return e;let{[V]:r}=e;if(!r)throw new Error(`${V} is not supported`);return r}function b({[w]:e},{wsl:r}){if(r&&d)return Q(r);if(!e)throw new Error(`${w} is not supported`);return Q(e)}var g={};f(g,"chrome",()=>b({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));f(g,"brave",()=>b({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));f(g,"firefox",()=>b({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));f(g,"edge",()=>b({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));f(g,"browser",()=>"browser");f(g,"browserPrivate",()=>"browserPrivate");var oe=_e;var ne=class{profile;environment;creds;oauth;constructor(r="default",t="prod",n){this.profile=r,this.environment=t,this.creds=n??new D,this.oauth=new A(t)}async login(){let{server:r,port:t}=await this.startCallbackServer(),n=N(t);try{let o=this.creds.loadClient(this.profile,this.environment),i=o?.redirect_uris;(!o||!i?.includes(n))&&(o=await this.oauth.registerClient(n),this.creds.saveClient(this.profile,this.environment,o));let c=o.client_id,[a,l]=A.generatePkce(),s=He(32).toString("hex"),m=this.oauth.buildAuthorizationUrl(c,l,s,n),p=await this.waitForCallback(r,t,m,s);if(!p)throw new Error("Login cancelled or timed out");let h=await this.oauth.exchangeCode(p,c,a,n),x={access_token:h.access_token,refresh_token:h.refresh_token,expires_at:Math.floor(Date.now()/1e3)+h.expires_in,scope:h.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,x),this.creds.setActiveProfile(this.profile),x}catch(o){throw r.close(),o}}startCallbackServer(){return new Promise((r,t)=>{let n=C,o=()=>{let i=Oe();i.on("error",c=>{c.code==="EADDRINUSE"&&n<P?(n++,o()):t(new Error(`Failed to start callback server: ${c.message}. Ports ${C}-${P} are all in use.`))}),i.listen(n,S,()=>{r({server:i,port:n})})};o()})}waitForCallback(r,t,n,o){return new Promise(i=>{let c=!1,a=setTimeout(()=>l(null),12e4),l=s=>{c||(c=!0,clearTimeout(a),r.close(),i(s))};r.on("request",(s,m)=>{let p=new $e(s.url??"/",`http://${S}:${t}`);if(p.pathname!==U){m.writeHead(404),m.end();return}let h=p.searchParams.get("state"),x=p.searchParams.get("code");if(p.searchParams.get("error")){m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),l(null);return}if(h!==o){m.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),l(null);return}m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),l(x)}),oe(n).catch(s=>{let m=s instanceof Error?s.message:String(s);process.stderr.write(`[auth] Could not open browser: ${m}
4
4
  Please open this URL manually: ${n}
5
5
  `)})})}};function R(e){let r=e.state==="success",t=r?"#22c55e":"#ef4444",n=r?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)",o=r?'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg>':'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',i=e.autoClose?"<script>setTimeout(function(){try{window.close();}catch(e){}}, 1500);</script>":"";return`<!doctype html>
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as h}from"./chunk-NLCCBXXV.js";import{a as n}from"./chunk-RZ4F3BHX.js";var f=class extends h{constructor(e,t,s){super(e,{username:t,accessKey:s})}async listProjects(e){let t=[],s=!1;for await(let r of this.listProjectsStream({log:e})){if(e&&!s&&r.projects.length>0){let o=r.projects[0];e("info","PROJECT_SAMPLE","Project list sample",{project_id:o.project_id,name:o.name}),s=!0}t.push(...r.projects)}return t}async*listProjectsStream(e){let t=e?.perPage??200,s=e?.maxPages??100,r=e?.signal,o=e?.log,d=e?.name?.trim(),a=0;for(let i=1;i<=s;i++){if(r?.aborted)return;let g=`${this.baseUrl}/v1/projects?page=${i}&per_page=${t}&sort=created_at`;d&&(g+=`&filter[name]=${encodeURIComponent(d)}`);let p=AbortSignal.timeout(15e3),j=r?AbortSignal.any([r,p]):p,c;try{c=await n(g,{method:"GET",headers:this.headers(),signal:j})}catch(l){if(r?.aborted)return;if(i===1)throw l;o?.("warn","PROJECTS_STREAM_PARTIAL","stream stopped mid-page",{page:i,total_loaded:a,error:l instanceof Error?l.message:String(l)}),yield{page:i,projects:[],totalLoaded:a,done:!0};return}if(!c.ok){if(i===1)throw new Error(`listProjects ${c.status}: ${await c.text()}`);o?.("warn","PROJECTS_STREAM_PARTIAL","stream stopped on non-OK response",{page:i,status:c.status,total_loaded:a}),yield{page:i,projects:[],totalLoaded:a,done:!0};return}let m=(await c.json()).data??[];a+=m.length;let u=m.length<t;if(yield{page:i,projects:m,totalLoaded:a,done:u},u)return}o?.("warn","PROJECTS_STREAM_MAXPAGES","max pages reached",{max_pages:s,total_loaded:a}),yield{page:s,projects:[],totalLoaded:a,done:!0}}async getDefaultFolder(e){let t=await n(`${this.baseUrl}/v1/projects/${e}/folder/default`,{method:"GET",headers:this.headers()});if(!t.ok)throw new Error(`Get default folder failed: ${t.status} ${await t.text()}`);return(await t.json()).id}async listFolders(e){let t=await n(`${this.baseUrl}/v1/folder/entity/${e}`,{method:"GET",headers:this.headers()});if(!t.ok)throw new Error(`List folders failed: ${t.status} ${await t.text()}`);return(await t.json()).data??[]}async validateProjectFolder(e,t){let s;try{s=await n(`${this.baseUrl}/v1/folder/entity/${e}`,{method:"GET",headers:this.headers()})}catch{return{project:"error",folder:"error"}}if(s.status>=400&&s.status<500)return{project:"missing",folder:"missing"};if(!s.ok)return{project:"error",folder:"error"};let r;try{r=await s.json()}catch{return{project:"error",folder:"error"}}return{project:"ok",folder:(r.data??[]).some(a=>a.id===t)?"ok":"missing"}}async createProject(e,t=""){let s=await n(`${this.baseUrl}/v1/projects`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({name:e,description:t,tags:[],source:"KTM"})});if(!s.ok)throw new Error(`Create project failed: ${s.status} ${await s.text()}`);return{id:(await s.json()).id,name:e}}async createFolder(e,t,s=""){let r=await n(`${this.baseUrl}/v1/folder`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({folders:[{name:t,description:s,entity_id:e,entity_type:"project"}]})});if(!r.ok)throw new Error(`Create folder failed: ${r.status} ${await r.text()}`);return{id:(await r.json()).id,name:t}}async createAtmTest(e,t){let s=t?`Bearer ${t}`:this.authHeader,r=await n(`${this.baseUrl}/kane-cli/v1/test`,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`Create ATM test failed: ${r.status} ${await r.text()}`);let o=await r.json();if(!o.test_id)throw new Error("Create ATM test returned no test_id");return o.test_id}async endTest(e,t,s){let r=s?`Bearer ${s}`:this.authHeader,o=new URLSearchParams({commit_id:t.commit_id,time_taken:String(t.time_taken),steps_count:String(t.steps_count),commit_message:t.commit_message}),d={};t.objectives&&t.objectives.length>0&&(d.objectives=t.objectives);let a=await n(`${this.baseUrl}/kane-cli/v1/test/${e}?${o.toString()}`,{method:"DELETE",headers:{Authorization:r,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`End test failed: ${a.status} ${await a.text()}`);let i=await a.json();return{testcase_id:i.data?.testcase_id??"",test_id:i.data?.test_id??e,project_id:i.data?.project_id??""}}async submitFeedback(e,t){let s=t?`Bearer ${t}`:this.authHeader,r={instruction_id:e.instruction_id,test_id:e.test_id,feedback_type:e.feedback_type,mode:e.mode??"human"};e.details&&(r.details=e.details);let o=await n(`${this.baseUrl}/atm/v1/generative-feedback`,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Submit feedback failed: ${o.status} ${await o.text()}`);return await o.json()}};export{f as a};