@testmuai/kane-cli 0.3.7 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/{ChromeProfilePicker-CBF6SP67.js → ChromeProfilePicker-27QCT4NT.js} +1 -1
  2. package/dist/{CliFeedbackPrompt-P2FJBV3S.js → CliFeedbackPrompt-LMXDRY5F.js} +1 -1
  3. package/dist/{CliUploadProgress-B4CVWX62.js → CliUploadProgress-QP5SPC7G.js} +1 -1
  4. package/dist/ConfigView-RQM2JY4K.js +2 -0
  5. package/dist/FolderPicker-YN2YQJXI.js +2 -0
  6. package/dist/HelpView-2IYG5AC3.js +2 -0
  7. package/dist/{InfoBox-SYT7CVM4.js → InfoBox-JELKGWY5.js} +1 -1
  8. package/dist/{LinksBox-R3VLKMYS.js → LinksBox-NUSUOUIW.js} +1 -1
  9. package/dist/{ProfilesView-XKUXSFMQ.js → ProfilesView-RXYI2IS3.js} +1 -1
  10. package/dist/{ProjectPicker-TWTR6SWR.js → ProjectPicker-RUR7HH2P.js} +1 -1
  11. package/dist/{SaveSessionPrompt-WAVXAYCK.js → SaveSessionPrompt-GUBVAQ3O.js} +1 -1
  12. package/dist/SingleShotApp-3XDTU2BU.js +2 -0
  13. package/dist/SummaryBox-5Y2YYOUM.js +2 -0
  14. package/dist/TestMdRunView-PPZPUVVZ.js +2 -0
  15. package/dist/{WhoamiView-YG6SSQTV.js → WhoamiView-IJZUFJ7B.js} +1 -1
  16. package/dist/{changelog-M5VP33UN.js → changelog-N4SSER5V.js} +1 -1
  17. package/dist/chunk-3C7ATCDM.js +2 -0
  18. package/dist/chunk-3Z4EHIOW.js +2 -0
  19. package/dist/chunk-5TOE4RHH.js +2 -0
  20. package/dist/chunk-6IQWD272.js +2 -0
  21. package/dist/{chunk-VUIXILBR.js → chunk-6NEJEMA6.js} +8 -8
  22. package/dist/{chunk-KX7K3Y7R.js → chunk-7G7ZLAJH.js} +1 -1
  23. package/dist/{chunk-X5CCG35O.js → chunk-7RPMUEEN.js} +1 -1
  24. package/dist/{chunk-PQGNWC33.js → chunk-AT2Y5UNP.js} +1 -1
  25. package/dist/chunk-BKXTOQWL.js +5 -0
  26. package/dist/chunk-CGAX3AXA.js +2 -0
  27. package/dist/chunk-CKY3UXTY.js +2 -0
  28. package/dist/chunk-DTFPHZE7.js +62 -0
  29. package/dist/chunk-H4XV224I.js +6 -0
  30. package/dist/chunk-H6OVTXJQ.js +2 -0
  31. package/dist/chunk-HN7DVSVI.js +11 -0
  32. package/dist/chunk-HYVAYSRZ.js +2 -0
  33. package/dist/chunk-IH45REQA.js +2 -0
  34. package/dist/chunk-J37YPPCD.js +2 -0
  35. package/dist/chunk-JCR3T34A.js +20 -0
  36. package/dist/chunk-JLOY7SNA.js +14 -0
  37. package/dist/chunk-L3RTVAPG.js +6 -0
  38. package/dist/chunk-LMV2F35W.js +2 -0
  39. package/dist/chunk-LRF6UP42.js +10 -0
  40. package/dist/chunk-M5RHRHFC.js +9 -0
  41. package/dist/{chunk-QKM3RHSQ.js → chunk-O2UU4TS5.js} +1 -1
  42. package/dist/chunk-PKQJHIKJ.js +2 -0
  43. package/dist/{chunk-74MJWDIW.js → chunk-PN7LNQ7G.js} +1 -1
  44. package/dist/{chunk-L256AYYL.js → chunk-PWHFNSDC.js} +1 -1
  45. package/dist/{chunk-BDC7IOXP.js → chunk-SJ7VGRQU.js} +11 -11
  46. package/dist/chunk-TAEW7PXN.js +2 -0
  47. package/dist/chunk-UJZCMEEH.js +8 -0
  48. package/dist/chunk-UVBDUDSL.js +2 -0
  49. package/dist/chunk-VS2BXLH4.js +2 -0
  50. package/dist/chunk-VTDVK3DK.js +2 -0
  51. package/dist/chunk-XQXSPUIX.js +2 -0
  52. package/dist/generate-headless-7UYAPXE5.js +18 -0
  53. package/dist/index.js +34 -38
  54. package/dist/{login-flow-3YFO62HA.js → login-flow-LK7GAUCZ.js} +1 -1
  55. package/dist/persist-recorded-session-VEFILVPX.js +3 -0
  56. package/dist/{pipeline-L3VM7QEX.js → pipeline-3GVPCDRE.js} +1 -1
  57. package/dist/{recording-banner-Q66Y2UIC.js → recording-banner-WS4Y7LVH.js} +1 -1
  58. package/dist/run-test-md-SXZUOYSG.js +14 -0
  59. package/dist/tcg-generate-CEBFKKJE.js +2 -0
  60. package/dist/testmd-actions-IZPOBSTC.js +2 -0
  61. package/dist/{validate-basic-JJOEAFLT.js → validate-basic-Y73NBDAD.js} +1 -1
  62. package/dist/{version-check-WWOS4OEZ.js → version-check-LNKXGYZE.js} +1 -1
  63. package/package.json +5 -5
  64. package/dist/ConfigView-PCX3TZNC.js +0 -2
  65. package/dist/FolderPicker-UTY6XQHP.js +0 -2
  66. package/dist/HelpView-CDK7II5Q.js +0 -2
  67. package/dist/SingleShotApp-JH6A65TZ.js +0 -2
  68. package/dist/SummaryBox-FDNFQYSC.js +0 -2
  69. package/dist/TestMdRunView-E4UDWIGT.js +0 -2
  70. package/dist/chunk-2SXNPFGD.js +0 -2
  71. package/dist/chunk-5XTLIGWL.js +0 -2
  72. package/dist/chunk-EIZXV3UH.js +0 -2
  73. package/dist/chunk-G7VF5SDK.js +0 -10
  74. package/dist/chunk-HROFBRMS.js +0 -5
  75. package/dist/chunk-JHNEE2MB.js +0 -2
  76. package/dist/chunk-KMTNMUVS.js +0 -8
  77. package/dist/chunk-LYSEA5FB.js +0 -6
  78. package/dist/chunk-MJQ2EHSC.js +0 -2
  79. package/dist/chunk-OQZG3V6B.js +0 -2
  80. package/dist/chunk-PJMTAAZ7.js +0 -2
  81. package/dist/chunk-PYU2JPAY.js +0 -2
  82. package/dist/chunk-QCNKJUPT.js +0 -2
  83. package/dist/chunk-R7JZMKC7.js +0 -9
  84. package/dist/chunk-TP6KYKPD.js +0 -2
  85. package/dist/chunk-U4XV5KUD.js +0 -2
  86. package/dist/chunk-VS5FTXRZ.js +0 -13
  87. package/dist/chunk-WZCGEQ6M.js +0 -2
  88. package/dist/chunk-X7VI7KK3.js +0 -11
  89. package/dist/chunk-YX3YFXT5.js +0 -2
  90. package/dist/chunk-ZAUHYR76.js +0 -2
  91. package/dist/chunk-ZY4BZQHD.js +0 -2
  92. package/dist/persist-recorded-session-LVQLORT4.js +0 -3
  93. package/dist/run-test-md-5TNUTTEA.js +0 -64
  94. package/dist/testmd-actions-O4NTH2OR.js +0 -20
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-JHNEE2MB.js";import{c as h,q as u,r as d}from"./chunk-5XTLIGWL.js";import{a}from"./chunk-RZ4F3BHX.js";import{readFileSync as c,writeFileSync as p,mkdirSync as y,readdirSync as l,unlinkSync as s,existsSync as g,chmodSync as v}from"fs";import{join as n,dirname as S}from"path";var m=class{baseDir;profilesDir;configFile;constructor(t=h){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(c(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){y(this.baseDir,{recursive:!0,mode:448}),p(this.configFile,JSON.stringify(t,null,2)+`
2
+ import{a as f}from"./chunk-J37YPPCD.js";import{c as h,q as u,r as d}from"./chunk-3Z4EHIOW.js";import{a}from"./chunk-RZ4F3BHX.js";import{readFileSync as c,writeFileSync as p,mkdirSync as y,readdirSync as l,unlinkSync as s,existsSync as g,chmodSync as v}from"fs";import{join as n,dirname as S}from"path";var m=class{baseDir;profilesDir;configFile;constructor(t=h){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(c(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){y(this.baseDir,{recursive:!0,mode:448}),p(this.configFile,JSON.stringify(t,null,2)+`
3
3
  `),v(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(t){let r=this.readConfig();r.active_profile=t,this.writeConfig(r)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(t){let r=this.readConfig();r.default_env=t,this.writeConfig(r)}credentialsPath(t,r){return n(this.profilesDir,t,r,"credentials")}clientPath(t,r){return n(this.profilesDir,t,r,"client.json")}basicAuthPath(t,r){return n(this.profilesDir,t,r,"basic-auth")}profileConfigPath(t,r){return n(this.profilesDir,t,r,"profile-config.json")}saveProfileConfig(t,r,e){let i=this.loadProfileConfig(t,r)??{};this.writeSecure(this.profileConfigPath(t,r),{...i,...e})}loadProfileConfig(t,r){try{return JSON.parse(c(this.profileConfigPath(t,r),"utf-8"))}catch{return null}}writeSecure(t,r){try{y(S(t),{recursive:!0,mode:448}),p(t,JSON.stringify(r,null,2)+`
4
4
  `),v(t,384)}catch(e){let i=e instanceof Error?e.message:String(e);process.stderr.write(`[auth] Failed to save credentials: ${i}
5
5
  `)}}saveCredentials(t,r,e){this.writeSecure(this.credentialsPath(t,r),e)}loadCredentials(t,r){try{return JSON.parse(c(this.credentialsPath(t,r),"utf-8"))}catch{return null}}saveClient(t,r,e){this.writeSecure(this.clientPath(t,r),e)}loadClient(t,r){try{return JSON.parse(c(this.clientPath(t,r),"utf-8"))}catch{return null}}getActiveCredentials(){let t=this.getActiveProfile();if(!t)return{credentials:null,profile:null,env:null};let r=this.getDefaultEnv();return{credentials:this.loadCredentials(t,r),profile:t,env:r}}saveBasicAuth(t,r,e){this.writeSecure(this.basicAuthPath(t,r),e)}loadBasicAuth(t,r){try{return JSON.parse(c(this.basicAuthPath(t,r),"utf-8"))}catch{return null}}deleteBasicAuth(t,r){try{s(this.basicAuthPath(t,r))}catch{}}resolveAuth(){let t=this.getActiveProfile();if(!t)return null;let r=this.getDefaultEnv(),e=this.loadBasicAuth(t,r);return e?{method:"basic",...e,profile:t,env:r}:this.loadCredentials(t,r)?{method:"oauth",profile:t,env:r}:null}listProfiles(){let t=[];try{for(let r of l(this.profilesDir)){let e=n(this.profilesDir,r);try{for(let i of l(e)){let o=n(e,i),w=g(n(o,"credentials")),k=g(n(o,"client.json")),C=g(n(o,"basic-auth"));(w||k||C)&&t.push({profile:r,env:i})}}catch{}}}catch{}return t}deleteProfile(t,r){try{s(this.credentialsPath(t,r))}catch{}if(this.getActiveProfile()===t){let e=this.readConfig();delete e.active_profile,this.writeConfig(e)}}deleteProfileFull(t,r){if(r){try{s(this.credentialsPath(t,r))}catch{}try{s(this.clientPath(t,r))}catch{}try{s(this.basicAuthPath(t,r))}catch{}try{s(this.profileConfigPath(t,r))}catch{}}else try{let e=n(this.profilesDir,t);for(let i of l(e)){try{s(n(e,i,"credentials"))}catch{}try{s(n(e,i,"client.json"))}catch{}try{s(n(e,i,"basic-auth"))}catch{}try{s(n(e,i,"profile-config.json"))}catch{}}}catch{}}};import{createHash as A,randomBytes as b}from"crypto";var _=class{authBaseUrl;consentUrl;constructor(t="prod"){let r=f(t);this.authBaseUrl=r.authBaseUrl,this.consentUrl=r.consentUrl}static generatePkce(){let t=b(96).toString("base64url").slice(0,128),r=A("sha256").update(t).digest("base64url");return[t,r]}buildAuthorizationUrl(t,r,e,i){let o=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:i,scope:d,code_challenge:r,code_challenge_method:"S256",state:e});return`${this.consentUrl}/oauth2?${o.toString()}`}async registerClient(t){let r=await a(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:u,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!r.ok)throw new Error(`DCR failed: ${r.status} ${await r.text()}`);return r.json()}async exchangeCode(t,r,e,i){let o=await a(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:i,client_id:r,code_verifier:e})});if(!o.ok)throw new Error(`Token exchange failed: ${o.status}`);return o.json()}async refreshToken(t,r){let e=await a(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:r})});if(!e.ok)throw new Error(`Token refresh failed: ${e.status}`);return e.json()}async revokeToken(t,r,e="access_token"){await a(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:e,client_id:r})})}async validateToken(t){let r=new AbortController,e=setTimeout(()=>r.abort(),1e4);try{let i=await a(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:r.signal});return clearTimeout(e),i.ok}catch{return clearTimeout(e),!1}}};export{m as a,_ 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-5XTLIGWL.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,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};
@@ -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-5XTLIGWL.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{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};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as je}from"./chunk-PN7LNQ7G.js";import{a as pe,b as $e}from"./chunk-VS2BXLH4.js";import{d as Pe,f as fe}from"./chunk-LRF6UP42.js";import{a as _e}from"./chunk-5TOE4RHH.js";import{a as Ce}from"./chunk-VTDVK3DK.js";import{a as U}from"./chunk-HCBYKLMW.js";import{t as s}from"./chunk-3Z4EHIOW.js";import{a,b as o,d as ge,i as Ee,j as Ie,k as xe}from"./chunk-C44QQJR4.js";import{a as ue}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var Y=$(ue(),1);var G=$(ue(),1);var F=$(ue(),1);function ve(e){let n=e.indexOf(": ");return n>0&&n<15?e.slice(n+2):e}function Te(e){return e.map(n=>{let l=n.children?Te(n.children):n.children;return n.status==="running"?{...n,status:"stopped",phase:void 0,children:l}:l!==n.children?{...n,children:l}:n})}function Le(e,n,l,c){let[b,u]=(0,F.useState)(!1),[f,d]=(0,F.useState)([]),[M,I]=(0,F.useState)(null),[P,C]=(0,F.useState)(null),[N,j]=(0,F.useState)(null),[y,g]=(0,F.useState)(null),[T,B]=(0,F.useState)([]),[q,J]=(0,F.useState)(null),[oe,ce]=(0,F.useState)(void 0),_=(0,F.useRef)(null),H=(0,F.useRef)(null),Q=(0,F.useRef)(0),le=(0,F.useRef)(!1),ee=(0,F.useCallback)(async(h,L)=>{let me=_.current;if(me){try{await me.exited}catch{}_.current=null}d([]),I(null),C(null),j(null),g(null),B([]),J(null),ce(h.max_steps),u(!0),H.current=null,Q.current=0;let W;try{W=je(h,L)}catch(ie){j(ie instanceof Error?ie.message:String(ie)),u(!1);return}_.current=W,Pe("runner",()=>W.cancel()),(async()=>{le.current=!1;let ie=!1;for await(let t of W.events){if(le.current)break;switch(t.type){case"run_start":if(H.current&&!H.current.isSingleFlow){let k=Q.current;Q.current++,d(E=>E.map((R,v)=>v===k?{...R,status:"running"}:R.status==="running"&&!R.children?.some(x=>x.status==="running")?{...R,status:R.children?.some(x=>x.status==="failed")?"failed":"passed"}:R))}break;case"bifurcation":{let k=t.flows??[],E=t.count??k.length,R={flows:k,isSingleFlow:t.is_single_flow??E<=1};g(R),H.current=R,Q.current=0,d(k.map((v,x)=>({index:x+1,objective:v??`Flow ${x+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 k=t.index,E=t.objective??`Step ${k}`,R=t.child_id,v=H.current&&!H.current.isSingleFlow;if(R)d(x=>{let S=x.findIndex(Z=>Z.status==="running"||Z.children?.some(ze=>ze.status==="running"));if(S===-1)return x;let O=[...x],D={...O[S]},re=[...D.children??[]].map(Z=>Z.status==="running"?{...Z,status:"stopped",phase:void 0}:Z);return re.push({index:k,objective:E,status:"running"}),D.children=re,O[S]=D,O});else if(v){let x=Math.max(0,Q.current-1);d(S=>{let O=[...S];if(x>=O.length)return S;let D={...O[x]},re=[...D.children??[]].map(Z=>Z.status==="running"?{...Z,status:"stopped",phase:void 0}:Z);return re.push({index:k,objective:E,status:"running"}),D.children=re,D.status="running",O[x]=D,O})}else d(x=>{let S=Te(x);return S.some(D=>D.index===k)?S.map(D=>D.index===k?{...D,status:"running",objective:E}:D):[...S,{index:k,objective:E,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 k=t.child_id,E=H.current&&!H.current.isSingleFlow;if(t.event==="cm_init"&&t.checkpoint_count!=null){B(R=>[...R,t.checkpoint_count]);break}if(t.event==="replay_started"){J({recordingLength:t.recording_length??0});break}if(t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&l?.(t.detail),k)d(R=>R.map(v=>{if(!v.children)return v;let x=v.children.map(S=>{if(S.index!==t.index)return S;let O={phase:t.event};return t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&(O.objective=t.detail),t.action_type&&(O.actionType=t.action_type),{...S,...O}});return{...v,children:x}}));else if(E){let R=Math.max(0,Q.current-1);d(v=>{let x=[...v];if(R>=x.length)return v;let S={...x[R]},O=[...S.children??[]];if(!O.some(ne=>ne.index===t.index))O.push({index:t.index,objective:`Step ${t.index}`,status:"running",phase:t.event,actionType:t.action_type});else for(let ne=0;ne<O.length;ne++){if(O[ne].index!==t.index)continue;let re={phase:t.event};t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&(re.objective=t.detail),t.action_type&&(re.actionType=t.action_type),O[ne]={...O[ne],...re}}return S.children=O,x[R]=S,x})}else d(R=>R.some(x=>x.index===t.index)?R.map(x=>{if(x.index!==t.index)return x;let S={phase:t.event};return t.event==="reasoning"&&t.detail&&t.detail!=="reasoning"&&(S.objective=t.detail),t.action_type&&(S.actionType=t.action_type),{...x,...S}}):[...Te(R),{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 k=t.child_id,E=H.current&&!H.current.isSingleFlow;if(k)d(R=>R.map(v=>{if(!v.children)return v;let x=v.children.map(S=>S.index===t.index?{...S,status:t.status,duration:t.duration,phase:void 0,objective:S.objective.startsWith("Step ")?ve(t.summary||S.objective):S.objective}:S);return{...v,children:x}}));else if(E){let R=Math.max(0,Q.current-1);d(v=>{let x=[...v];if(R>=x.length)return v;let S={...x[R]},O=(S.children??[]).map(D=>D.index===t.index?{...D,status:t.status,duration:t.duration,phase:void 0,objective:D.objective.startsWith("Step ")?ve(t.summary||D.objective):D.objective}:D);return S.children=O,x[R]=S,x})}else d(R=>R.map(v=>v.index===t.index?{...v,status:t.status,duration:t.duration,phase:void 0,objective:v.objective.startsWith("Step ")?ve(t.summary||v.objective):v.objective}:v));{let v=H.current&&!H.current.isSingleFlow?Math.max(0,Q.current-1):0;e?.(t.index,v,t.child_id)}break}case"child_agent_start":{let k=t.objective??"";d(E=>E.map(R=>R.status==="running"?{...R,objective:`${k} (branch)`,phase:`child: ${k.slice(0,50)}`,branchObjective:k}:R));break}case"child_agent_end":d(k=>k.map(E=>E.phase?.startsWith("child:")?{...E,phase:`child ${t.success?"done":"failed"}`}:E));break;case"ask_user":I(t.question??"");break;case"run_end":d(k=>k.map(E=>E.status==="running"?{...E,status:t.status,phase:void 0}:E)),u(!1),C(t),ie=!0;break;case"error":u(!1),j(t.message??"Runner error"),d(k=>k.map(E=>E.status==="running"?{...E,status:"failed",phase:void 0}:E));break}}let{code:te,signal:Se}=await W.exited,ye=W.stderr,Ve=te===0&&!Se,de=[];te!==null&&te!==0&&de.push(`Runner exited with code ${te}`),Se&&de.push(`Runner killed by signal ${Se}`),ye&&(!Ve||!ie?de.push(ye):L?.log?.("debug","RUNNER_STDERR_BENIGN","Runner stderr on clean exit",{stderr:ye})),_.current===W&&(de.length>0&&j(de.join(`
3
+ `)),u(!1),fe("runner","Event stream ended"),_.current=null)})().catch(ie=>{let te=[`Runner event loop error: ${ie}`];W.exitCode!==null&&W.exitCode!==0&&te.push(`Exit code: ${W.exitCode}`),W.exitSignal&&te.push(`Signal: ${W.exitSignal}`),W.stderr&&te.push(W.stderr),_.current===W&&(j(te.join(`
4
+ `)),u(!1),fe("runner","Event loop error"),_.current=null)})},[e,n,l,c]),r=(0,F.useCallback)(h=>{_.current?.sendUserResponse(h),I(null)},[]),m=(0,F.useCallback)(()=>{let h=_.current;h&&(h.sendCancel("user"),u(!1),I(null),setTimeout(()=>{_.current===h&&(fe("runner","User cancelled run"),_.current=null)},5e3))},[]),p=(0,F.useCallback)(()=>{d([]),C(null),j(null)},[]);return(0,F.useEffect)(()=>()=>{le.current=!0,fe("runner","Component unmounted"),_.current=null},[]),{isRunning:b,steps:f,askingUser:M,lastRunEnd:P,runError:N,bifurcationInfo:y,cmInitCounts:T,replayInfo:q,maxSteps:oe,startRun:ee,sendAnswer:r,cancelRun:m,clearLastRun:p}}function we(e){let n=e.flatMap(u=>[u,...u.children??[]]),l=n.filter(u=>u.status==="passed").length,c=n.filter(u=>u.status==="failed").length,b=n.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:l,failed:c,total:b}}function Oe(e){let n=Le(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[l,c]=(0,G.useState)(0),[b,u]=(0,G.useState)("idle"),f=(0,G.useRef)("idle"),d=(0,G.useRef)(0),M=(0,G.useRef)(!1),I=(0,G.useRef)(null),P=(0,G.useRef)(null),C=(0,G.useCallback)(y=>{f.current=y,u(y)},[]),N=(0,G.useCallback)(async y=>{let g=await e.getNextConfig(y);if(!g){C("done"),e.onAllComplete?.();return}let T=y?d.current+1:0;d.current=T,c(T),e.onStepStart?.(g,T),I.current=null,P.current=null,C("running"),await n.startRun(g,e.spawnOpts)},[n,e,C]);(0,G.useEffect)(()=>{M.current||(M.current=!0,N(null))},[]),(0,G.useEffect)(()=>{if(!n.lastRunEnd||n.lastRunEnd===I.current||f.current!=="running")return;I.current=n.lastRunEnd,f.current="transitioning",u("transitioning");let y=n.lastRunEnd,g=we(n.steps),T=n.bifurcationInfo,B={status:y.status==="passed"?"passed":"failed",duration_s:y.duration??0,reason:y.reason,runEnd:y,hadError:!1,stepsPassed:g.passed,stepsFailed:g.failed,stepsTotal:g.total,bifurcationFlows:T&&!T.isSingleFlow?T.flows:null};if(!(e.onStepEnd?.(B,d.current)??!0)){C("done"),e.onAllComplete?.();return}N(B)},[n.lastRunEnd]),(0,G.useEffect)(()=>{if(!n.runError||n.runError===P.current||n.lastRunEnd||f.current!=="running")return;P.current=n.runError,f.current="transitioning",u("transitioning");let y=we(n.steps),g={status:"failed",duration_s:0,reason:n.runError,runEnd:null,hadError:!0,stepsPassed:y.passed,stepsFailed:y.failed,stepsTotal:y.total,bifurcationFlows:null};if(!(e.onStepEnd?.(g,d.current)??!0)){C("done"),e.onAllComplete?.();return}N(g)},[n.runError,n.lastRunEnd]);let j=(0,G.useCallback)(()=>{n.cancelRun()},[n]);return{runner:n,currentStepIndex:l,phase:b,cancel:j}}var Be=$(ue(),1);var he=$(U(),1),De=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Fe({label:e,hasBifurcation:n=!1}){let[l,c]=(0,Be.useState)(0),[b,u]=(0,Be.useState)(0);pe(()=>{c(d=>(d+1)%De.length)},80),pe(()=>{u(d=>(d+1)%4)},400);let f=e??(n?"Planning approach":"Analyzing objective");return(0,he.jsxs)(a,{marginLeft:1,children:[(0,he.jsxs)(o,{color:s.orange,children:[De[l]," "]}),(0,he.jsxs)(o,{color:s.dim,children:[f,".".repeat(b+1)]})]})}function Me(e){if(!e.isRunning||e.replayInfo)return null;let n=e.bifurcationInfo;if(n&&!n.isSingleFlow){let l=e.steps.findIndex(b=>b.status==="running");return(l===-1?e.cmInitCounts.length===0:l>=e.cmInitCounts.length)?{label:l>0?`Planning flow ${l+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(l=>l.children?.length)?null:{hasBifurcation:!!n}}var A=$(ue(),1);var Ae=$(ue(),1);var Re=$(U(),1),Xe="#ffc580",Ye="#ffd9a8",Ne="#ffffff";function qe({text:e,active:n=!0}){let[l,c]=(0,Ae.useState)(0),b=4;if(pe(()=>{c(f=>(f+1)%(e.length+b*2))},n?80:null),!n)return(0,Re.jsx)(o,{color:Ne,children:e});let u=e.split("").map((f,d)=>{let M=l-b,I=Math.abs(d-M-b/2),P;return I<=b/2?P=Xe:I<=b?P=Ye:P=Ne,(0,Re.jsx)(o,{color:P,children:f},d)});return(0,Re.jsx)(o,{children:u})}var K=$(U(),1),Je={starting:s.orange,running:s.orange,passed:s.green,failed:s.red,cancelled:s.dim,timed_out:s.orange};function be({currentStep:e,maxSteps:n,elapsed:l,status:c}){let{stdout:b}=xe(),u=b?.columns??80,f=Je[c]??s.orange,d=l<60?`${l.toFixed(1)}s`:`${Math.floor(l/60)}m ${Math.round(l%60)}s`;return(0,K.jsxs)(a,{flexDirection:"column",marginTop:1,children:[(0,K.jsx)(o,{color:s.muted,children:"\u2500".repeat(Math.min(u,60))}),(0,K.jsxs)(a,{children:[(0,K.jsx)(o,{children:" "}),(0,K.jsx)(o,{color:s.dim,children:"Steps "}),(0,K.jsx)(o,{bold:!0,children:e}),(0,K.jsxs)(o,{color:s.dim,children:["/",n]}),(0,K.jsx)(o,{children:" "}),(0,K.jsx)(o,{color:s.dim,children:"Elapsed "}),(0,K.jsx)(o,{bold:!0,children:d}),(0,K.jsx)(o,{children:" "}),(0,K.jsx)(o,{color:s.dim,children:"Status "}),(0,K.jsx)(o,{bold:!0,color:f,children:c})]})]})}var Qe={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 Ue(e){return Qe[e]??"\u25CF"}var se=$(U(),1);function ke({steps:e,flows:n,cmInitCounts:l,renderStep:c}){return(0,se.jsxs)(a,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,se.jsxs)(o,{color:s.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((b,u)=>(0,se.jsxs)(a,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,se.jsxs)(o,{color:s.orange,children:["Flow ",u+1,": ",n?.[u]??b.objective]}),l&&l[u]!=null&&(0,se.jsxs)(o,{color:s.dim,children:[" \u25AA Generated task with ",l[u]," checkpoints"]}),b.children&&b.children.length>0?b.children.map(f=>c(f,`f${u}-${f.index}`)):b.status==="pending"&&(0,se.jsx)(o,{color:s.dim,children:" \u25CB Waiting..."})]},u))]})}var i=$(U(),1);function X({step:e,indent:n=2}){let l=e.actionType?Ue(e.actionType):null,c=e.status==="running",b=e.status==="passed",u=e.status==="failed",f=e.status==="pending"||e.status==="stopped",{stdout:d}=xe(),M=d?.columns??80,I=Math.max(20,M-n-21),P=e.objective??"",C=P.length>I?P.slice(0,I-1)+"\u2026":P,N=(e.duration??0)*1e3,j=e.duration!=null?N<1e3?`${Math.round(N)}ms`:`${(N/1e3).toFixed(1)}s`:"";return(0,i.jsxs)(a,{flexDirection:"column",children:[(0,i.jsxs)(a,{marginLeft:n,children:[(0,i.jsx)(a,{width:4,children:(0,i.jsxs)(o,{color:s.muted,children:[String(e.index).padStart(2," ")," "]})}),(0,i.jsx)(a,{width:3,children:c?(0,i.jsx)($e,{}):b?(0,i.jsx)(o,{color:s.green,bold:!0,children:"\u2713"}):u?(0,i.jsx)(o,{color:s.red,bold:!0,children:"\u2717"}):(0,i.jsx)(o,{color:s.muted,children:"\u25CB"})}),(0,i.jsx)(a,{flexGrow:1,children:c?(0,i.jsx)(qe,{text:C,active:!0}):u?(0,i.jsx)(o,{color:s.red,children:C}):f?(0,i.jsx)(o,{color:s.dim,children:C}):(0,i.jsx)(o,{color:s.dim,children:C})}),(b||u)&&l?(0,i.jsx)(a,{width:3,marginLeft:1,children:(0,i.jsx)(o,{color:s.muted,children:l})}):(0,i.jsx)(a,{width:3,marginLeft:1}),(0,i.jsx)(a,{width:7,justifyContent:"flex-end",children:(0,i.jsx)(o,{color:s.dim,children:j})})]}),e.children&&e.children.length>0&&(0,i.jsx)(a,{flexDirection:"column",children:e.children.map((y,g)=>(0,i.jsx)(X,{step:y,indent:n+2},`child-${g}`))})]})}function Ge({steps:e,bifurcated:n,flows:l,cmInitCounts:c,maxSteps:b=50,staticSteps:u=!1,onStepCommit:f}){let d=(0,A.useRef)(new Set),M=(0,A.useRef)(!1),I=(0,A.useRef)(new Set),P=(0,A.useRef)(!1),C=(0,A.useRef)(new Set),N=(0,A.useRef)(0);(0,A.useEffect)(()=>{e.length===0&&N.current>0&&(d.current.clear(),M.current=!1,I.current.clear(),P.current=!1,C.current.clear()),N.current=e.length},[e.length]);let j=e.flatMap(r=>[r,...r.children??[]]),y=j.some(r=>r.status==="running"),g=j.some(r=>r.status==="failed"),T=j.length===0||j.every(r=>r.status==="pending"),B=j.filter(r=>r.status==="passed"||r.status==="failed").length,q;T?q="starting":y?q="running":g?q="failed":q="passed";let J=(0,A.useRef)(null),[oe,ce]=(0,A.useState)(0);(0,A.useEffect)(()=>{j.length===0||T?(J.current=null,ce(0)):y&&J.current==null&&(J.current=Date.now())},[y,T,j.length]),(0,A.useEffect)(()=>{if(!y)return;let r=setInterval(()=>{J.current!=null&&ce((Date.now()-J.current)/1e3)},500);return()=>clearInterval(r)},[y]);let _=(0,A.useRef)(new Set),[H,Q]=(0,A.useState)([]),le=(0,A.useRef)(!1);(0,A.useEffect)(()=>{if(!u||n)return;let r=[];if(!n&&!le.current&&c&&c[0]!=null&&(le.current=!0,c[0]>0&&r.push({key:"cm_init_0",type:"cm_init",count:c[0]})),n){!_.current.has(-1)&&e.length>0&&(_.current.add(-1),r.push({key:"bif_header",type:"bifurcation_header",flowCount:l?.length??e.length}));for(let m=0;m<e.length;m++){let p=e[m],h=-(m+10);_.current.has(h)||(_.current.add(h),r.push({key:`flow_header_${m}`,type:"flow_header",flowIdx:m,label:l?.[m]??p.objective,cmCount:c?.[m]}));for(let L of p.children??[])(L.status==="passed"||L.status==="failed")&&!_.current.has(L.index)&&(_.current.add(L.index),r.push({key:`step_f${m}_${L.index}`,type:"step",step:{...L}}))}}else for(let m of e)(m.status==="passed"||m.status==="failed")&&!_.current.has(m.index)&&(_.current.add(m.index),r.push({key:`step_${m.index}`,type:"step",step:{...m,children:m.children?[...m.children]:void 0}}));r.length>0&&Q(m=>[...m,...r])},[e,n,l,c,u]),(0,A.useEffect)(()=>{if(f)if(!n&&!P.current&&c&&c[0]!=null&&(P.current=!0,c[0]>0&&f((0,i.jsx)(a,{marginLeft:2,children:(0,i.jsxs)(o,{color:s.dim,children:["\u25A0 Generated task with ",c[0]," checkpoints"]})}))),n&&l&&!M.current&&(M.current=!0,f((0,i.jsx)(o,{color:s.purple,children:"\u2501\u2501 Bifurcated into "+l.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),n){let r=e.flatMap((m,p)=>{let h=m.children??[];return!I.current.has(p)&&h.length>0&&(I.current.add(p),f((0,i.jsx)(o,{color:s.purple,children:" Flow "+(p+1)+": "+(l?.[p]??"")})),c?.[p]!=null&&c[p]>0&&!C.current.has(p)&&(C.current.add(p),f((0,i.jsx)(a,{marginLeft:2,children:(0,i.jsxs)(o,{color:s.dim,children:[" \u25AA Generated task with ",c[p]," checkpoints"]})})))),c?.[p]!=null&&c[p]>0&&I.current.has(p)&&!C.current.has(p)&&(C.current.add(p),f((0,i.jsx)(a,{marginLeft:2,children:(0,i.jsxs)(o,{color:s.dim,children:[" \u25AA Generated task with ",c[p]," checkpoints"]})}))),h});for(let m of r){let p=`${m.index}-${m.objective}`;d.current.has(p)||(m.status==="passed"||m.status==="failed"||m.status==="stopped")&&(d.current.add(p),f((0,i.jsx)(a,{marginLeft:2,children:(0,i.jsx)(X,{step:m})})))}}else for(let r of e){let m=`${r.index}-${r.objective}`,p=!!r.branchObjective;p&&!d.current.has(m)&&(d.current.add(m),f((0,i.jsx)(a,{marginLeft:2,children:(0,i.jsx)(X,{step:{...r,children:void 0}})})));for(let h of r.children??[]){let L=`child-${r.index}-${h.index}-${h.objective}`;d.current.has(L)||(h.status==="passed"||h.status==="failed"||h.status==="stopped")&&(d.current.add(L),f((0,i.jsx)(a,{marginLeft:4,children:(0,i.jsx)(X,{step:h})})))}!p&&!d.current.has(m)&&(r.status==="passed"||r.status==="failed"||r.status==="stopped")&&(d.current.add(m),f((0,i.jsx)(a,{marginLeft:2,children:(0,i.jsx)(X,{step:{...r,children:void 0}})})))}},[e,f,n,l,c]);let ee=[];if(f)if(n)for(let r of e){let p=(r.children??[]).filter(h=>{let L=`${h.index}-${h.objective}`;return!d.current.has(L)});p.length>0&&ee.push({...r,children:p})}else for(let r of e){let m=`${r.index}-${r.objective}`,p=d.current.has(m),h=(r.children??[]).filter(L=>{let me=`child-${r.index}-${L.index}-${L.objective}`;return!d.current.has(me)});p?h.length>0&&ee.push({...r,children:h}):ee.push({...r,children:h})}else if(u){if(!n)for(let r of e)_.current.has(r.index)||ee.push(r)}if(!u){let r=f?ee:e;return(0,i.jsxs)(a,{flexDirection:"column",children:[n?f?r.length>0?(0,i.jsx)(a,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:r.map((p,h)=>(0,i.jsx)(a,{flexDirection:"column",marginTop:h>0?1:0,children:p.children&&p.children.length>0?p.children.map(L=>(0,i.jsx)(X,{step:L},`f${h}-${L.index}`)):p.status==="pending"&&(0,i.jsx)(o,{color:s.dim,children:" \u25CB Waiting..."})},h))}):null:(0,i.jsx)(ke,{steps:e,flows:l,cmInitCounts:c,renderStep:(p,h)=>(0,i.jsx)(X,{step:p},h)}):(0,i.jsxs)(a,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!f&&c&&c[0]!=null&&(0,i.jsxs)(o,{color:s.dim,children:["\u25AA Generated task with ",c[0]," checkpoints"]}),r.map(p=>{let h=`${p.index}-${p.objective}`;return f&&d.current.has(h)?(0,i.jsx)(a,{flexDirection:"column",children:(p.children??[]).map(L=>(0,i.jsx)(a,{marginLeft:2,children:(0,i.jsx)(X,{step:L})},L.index))},`branch-children-${p.index}`):(0,i.jsx)(X,{step:p},p.index)})]}),y&&(0,i.jsx)(be,{currentStep:B,maxSteps:b,elapsed:oe,status:q})]})}return n?(0,i.jsxs)(a,{flexDirection:"column",children:[(0,i.jsx)(ke,{steps:e,flows:l,cmInitCounts:c,renderStep:(r,m)=>(0,i.jsx)(X,{step:r},m)}),y&&(0,i.jsx)(be,{currentStep:B,maxSteps:b,elapsed:oe,status:q})]}):(0,i.jsxs)(a,{flexDirection:"column",children:[(0,i.jsx)(ge,{items:H,children:r=>r.type==="cm_init"?(0,i.jsx)(a,{marginLeft:2,paddingLeft:1,children:(0,i.jsxs)(o,{color:s.dim,children:["\u25AA Generated task with ",r.count," checkpoints"]})},r.key):r.type==="bifurcation_header"?(0,i.jsx)(a,{marginLeft:2,paddingLeft:1,children:(0,i.jsxs)(o,{color:s.dim,children:["\u2501\u2501 Bifurcated into ",r.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},r.key):r.type==="flow_header"?(0,i.jsxs)(a,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,i.jsxs)(o,{color:s.orange,children:["Flow ",r.flowIdx+1,": ",r.label]}),r.cmCount!=null&&(0,i.jsxs)(o,{color:s.dim,children:[" \u25AA Generated task with ",r.cmCount," checkpoints"]})]},r.key):(0,i.jsx)(a,{marginLeft:2,paddingLeft:1,children:(0,i.jsx)(X,{step:r.step})},r.key)}),ee.length>0&&(0,i.jsx)(a,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:ee.map(r=>(0,i.jsx)(X,{step:r},r.index))}),y&&(0,i.jsx)(be,{currentStep:B,maxSteps:b,elapsed:oe,status:q})]})}var ae=$(U(),1);function We({runner:e,runKey:n,onStepCommit:l}){let c=Me({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)(Fe,{label:c.label,hasBifurcation:c.hasBifurcation}),e.isRunning&&e.steps.length>0&&(0,ae.jsx)(Ge,{steps:e.steps,bifurcated:!!e.bifurcationInfo&&!e.bifurcationInfo.isSingleFlow,flows:e.bifurcationInfo?.flows,cmInitCounts:e.cmInitCounts,maxSteps:e.maxSteps,onStepCommit:l},`run-${n}`)]})}var V=$(U(),1),Ze=64;function et(e){return e.split(`
5
+ `).map(n=>n.replace(/^[-–•]\s*/,"").trim()).filter(n=>n.length>0)}function Ke({status:e,summary:n,duration:l,steps:c,stepsPassed:b,stepsFailed:u,reason:f,creditsConsumed:d}){let M=e==="passed",I=M?s.green:s.red,P=M?"\u2713":"\u2717",C=e.toUpperCase(),N=b??(M?c:Math.max(0,c-1)),j=u??(M?0:1),y=j>0?`${c} steps (${N} passed, ${j} failed)`:`${c} steps`,g=l<60?`${l.toFixed(1)}s`:`${Math.floor(l/60)}m ${Math.round(l%60)}s`,T=et(n);return(0,V.jsx)(a,{flexDirection:"column",marginTop:1,children:(0,V.jsxs)(a,{borderStyle:"round",borderColor:I,flexDirection:"column",paddingX:2,paddingY:1,width:Ze+6,children:[(0,V.jsxs)(a,{flexDirection:"column",children:[(0,V.jsxs)(o,{bold:!0,color:I,children:[P," ",C]}),(0,V.jsxs)(o,{color:s.dim,wrap:"wrap",children:[y," \xB7 ",g,typeof d=="number"&&d>0?` \xB7 ${parseFloat(d.toFixed(4))} credits`:""]})]}),T.length>0&&(0,V.jsx)(a,{flexDirection:"column",marginTop:1,marginLeft:1,children:T.map((B,q)=>(0,V.jsxs)(a,{marginBottom:q<T.length-1?1:0,children:[(0,V.jsx)(o,{color:s.orange,children:"\u25CF "}),(0,V.jsx)(a,{flexShrink:1,children:(0,V.jsx)(o,{wrap:"wrap",children:B})})]},q))}),f&&!M&&(0,V.jsx)(a,{marginTop:1,children:(0,V.jsxs)(o,{color:s.red,wrap:"wrap",children:["Reason: ",f]})})]})})}var z=$(U(),1);function He({message:e,code:n,remediation:l,docsUrl:c}){return(0,z.jsx)(Ce,{title:"Error",variant:"error",children:(0,z.jsxs)(a,{flexDirection:"column",paddingY:1,children:[(0,z.jsxs)(o,{color:s.red,bold:!0,children:[" \u2717 ",e]}),n&&(0,z.jsxs)(a,{marginTop:0,marginLeft:5,children:[(0,z.jsx)(o,{color:s.muted,children:"Code: "}),(0,z.jsx)(o,{color:s.dim,children:n})]}),l&&(0,z.jsxs)(a,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,z.jsx)(o,{color:s.green,bold:!0,children:"Fix:"}),(0,z.jsxs)(o,{color:s.orange,children:["$ ",l]})]}),c&&(0,z.jsxs)(a,{marginTop:1,marginLeft:5,children:[(0,z.jsx)(o,{color:s.muted,children:"Docs: "}),(0,z.jsx)(o,{color:s.orange,underline:!0,children:c})]})]})})}var w=$(U(),1);function en(e){let{exit:n}=Ie(),l=(0,Y.useRef)(0),[c,b]=(0,Y.useState)([{id:"top-banner",content:(0,w.jsx)(a,{flexDirection:"column",marginBottom:1,children:(0,w.jsxs)(a,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,w.jsx)(o,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,w.jsx)(o,{color:s.dim,children:" \u2502 "}),(0,w.jsx)(o,{color:s.orange,children:e.topBanner.model}),(0,w.jsx)(o,{color:s.dim,children:" \u2502 "}),(0,w.jsx)(o,{color:s.dim,children:e.topBanner.auth})]})})},{id:"global-config",content:(0,w.jsx)(tt,{data:e.globalConfig})},...e.priorAttemptRollup?[{id:"prior-rollup",content:(0,w.jsx)(o,{color:s.dim,children:` \u21B3 replayed ${e.priorAttemptRollup.startIdx}..${e.priorAttemptRollup.endIdx-1} (${e.priorAttemptRollup.count} steps, from prior attempt)`})}]:[]]),u=(0,Y.useCallback)(g=>{let T=`s-${++l.current}`;b(B=>[...B,{id:T,content:g}])},[]),f=(0,Y.useRef)(null),d=(0,Y.useCallback)(async g=>{let T=await e.getNextStep(g);return T?(f.current=T,T.config):(f.current=null,null)},[e]),M=(0,Y.useCallback)((g,T)=>{let B=f.current;if(!B)return;let q=B.mode==="replay"?"cyan":"#dc4e08",J=B.modeReason?` (${B.modeReason})`:"",oe=B.perStepOverrides?Object.entries(B.perStepOverrides):[];u((0,w.jsxs)(a,{flexDirection:"column",marginBottom:0,children:[(0,w.jsxs)(o,{children:[(0,w.jsxs)(o,{color:s.dim,children:[B.banner.stepLabel," "]}),(0,w.jsxs)(o,{color:q,children:["[",B.mode,"]"]}),(0,w.jsx)(o,{color:s.dim,children:J})]}),(0,w.jsx)(o,{color:s.dim,children:B.banner.objective}),oe.length>0&&(0,w.jsxs)(o,{color:s.dim,children:["overrides: ",oe.map(([ce,_])=>`${ce}=${_}`).join(", ")]})]}))},[u]),I=(0,Y.useRef)(0),P=(0,Y.useRef)(!1),C=(0,Y.useCallback)((g,T)=>(g.hadError?u((0,w.jsx)(He,{message:g.reason??"Runner error",code:"RUNNER_ERROR"})):u((0,w.jsx)(a,{flexDirection:"column",marginBottom:1,children:(0,w.jsx)(Ke,{status:g.status,summary:g.runEnd?.summary??"",duration:g.runEnd?.duration??0,steps:g.stepsTotal,stepsPassed:g.stepsPassed,stepsFailed:g.stepsFailed,reason:g.runEnd?.reason,creditsConsumed:g.runEnd?.credits_consumed})})),e.onStepEnd?.(g,T)??!0),[u,e]),N=Oe({getNextConfig:d,onStepStart:M,onStepEnd:C,onAllComplete:()=>{e.onAllComplete(),e.exitOnComplete!==!1&&setImmediate(()=>n())},screenshotDispatcher:e.screenshotDispatcher,stepLogger:e.stepLogger,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete,spawnOpts:e.spawnOpts}),j=250,y=5e3;return Ee((g,T)=>{if(T.ctrl&&g==="c"){let B=Date.now(),q=B-I.current;if(q<j)return;P.current&&q<y?(N.cancel(),e.onCancel?.(),e.exitOnComplete!==!1&&setImmediate(()=>n())):(P.current=!0,u((0,w.jsx)(o,{color:"yellow",children:"press Ctrl+C again to cancel run"}))),I.current=B}}),(0,w.jsxs)(a,{flexDirection:"column",children:[(0,w.jsx)(ge,{items:c,children:g=>(0,w.jsx)(a,{children:g.content},g.id)}),N.phase!=="done"&&(0,w.jsx)(We,{runner:N.runner,runKey:N.currentStepIndex,onStepCommit:u})]})}function tt({data:e}){return(0,w.jsx)(_e,{title:"test.md run",titleColor:"#ff9500",borderColor:s.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{Ge as a,Fe as b,Me as c,Le as d,we as e,Ke as f,He as g,en as h};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as B}from"./chunk-S3DAAAE5.js";import{a as g}from"./chunk-5TOE4RHH.js";import{a as w}from"./chunk-HCBYKLMW.js";import{t as s}from"./chunk-3Z4EHIOW.js";import{a as x,b as t,c as h,i as P,j as S}from"./chunk-C44QQJR4.js";import{a as C}from"./chunk-6YGTRKDT.js";import{e as T}from"./chunk-UR6MHSHU.js";var o=T(C(),1);var e=T(w(),1);function D({defaultName:i,onSubmit:c}){let[d,p]=(0,o.useState)("confirm"),[f,a]=(0,o.useState)(""),[m,u]=(0,o.useState)(null),l=(0,o.useMemo)(()=>f.trim()||i,[f,i]);return P((n,r)=>{if(d==="confirm"){if(n==="y"||n==="Y"){a(i),p("name");return}if(n==="n"||n==="N"||r.escape||r.ctrl&&n==="c"){c(null);return}if(r.return){c(i);return}return}if(r.return){if(!B(l)){u(`name "${l}" is invalid; allowed: letters, digits, underscore, hyphen`);return}c(l);return}if(r.escape||r.ctrl&&n==="c"){c(null);return}if(r.backspace||r.delete){a(v=>v.slice(0,-1)),u(null);return}n&&!r.ctrl&&!r.meta&&(a(v=>v+n),u(null))}),d==="confirm"?(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsx)(t,{color:s.orange,children:i})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save with this name"}),(0,e.jsx)(t,{color:s.dim,children:"Y \u2014 edit name"}),(0,e.jsx)(t,{color:s.dim,children:"N/esc \u2014 discard session"})]})}):(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsxs)(x,{children:[(0,e.jsx)(t,{color:s.orange,children:f}),(0,e.jsx)(t,{inverse:!0,children:" "})]})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[m&&(0,e.jsx)(t,{color:s.red,children:m}),(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save \xB7 esc \u2014 discard"})]})})}function V(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}async function Y(i){return new Promise(c=>{function d(){let{exit:a}=S(),[m,u]=(0,o.useState)(!1);return(0,o.useEffect)(()=>{if(m){let l=setTimeout(()=>a(),50);return()=>clearTimeout(l)}},[m,a]),(0,e.jsx)(D,{defaultName:i,onSubmit:l=>{c(l),u(!0)}})}let{waitUntilExit:p,unmount:f}=h((0,e.jsx)(d,{}),{stdout:process.stderr,exitOnCtrlC:!1});p().then(()=>{try{f()}catch{}})})}export{D as a,V as b,Y as c};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as A}from"./chunk-YCCUBQY4.js";import{a as _}from"./chunk-TAEW7PXN.js";import{a as B}from"./chunk-J37YPPCD.js";import{a as R}from"./chunk-AT2Y5UNP.js";import{a as P}from"./chunk-HCBYKLMW.js";import{t as c}from"./chunk-3Z4EHIOW.js";import{a as u,b as l}from"./chunk-C44QQJR4.js";import{a as J}from"./chunk-6YGTRKDT.js";import{a as k}from"./chunk-7CLUJYMW.js";import{e as L}from"./chunk-UR6MHSHU.js";var t=L(J(),1);var e=L(P(),1);function X(n,i,y,m){return{id:n,label:`${i} (${n}) \xB7 ${y} tests`,isActive:n===m}}function W({resolver:n,projectId:i,currentFolderId:y,env:m,onSelect:x,onCancel:w}){let[I,M]=(0,t.useState)([]),[$,d]=(0,t.useState)(!0),[O,g]=(0,t.useState)(!1),[U,N]=(0,t.useState)(null),[p,b]=(0,t.useState)("list"),[S,v]=(0,t.useState)(""),[E,f]=(0,t.useState)(null),h=(0,t.useRef)(!1);(0,t.useEffect)(()=>{if(!n){N("Login first to browse folders"),d(!1);return}let o=new AbortController;return d(!0),g(!0),(async()=>{try{let r=n.cached??await n.resolve();if(!r){N("Login first to browse folders"),d(!1),g(!1);return}let a=B(m),T=new k(a.tmsBaseUrl,r.username,r.access_key),F=(async function*(){if(o.signal.aborted)return;let s=await T.listFolders(i);yield{page:1,folders:s,totalLoaded:s.length,done:!0}})();for await(let s of F){if(d(!1),s.totalLoaded===0){h.current=!0,b("naming"),g(!1);return}M(s.folders.map(C=>X(C.id,C.name,C.test_cases_count,y))),s.done&&g(!1)}}catch(r){if(r?.name==="AbortError")return;N(r instanceof Error?r.message:String(r)),d(!1),g(!1)}})(),()=>o.abort()},[n,i,y,m]);let D=(0,t.useCallback)(o=>{let r=o.trim();if(!r){f("Name cannot be empty");return}if(!i){f("No project selected \u2014 pick a project first");return}f(null),b("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let a=n.cached??await n.resolve();if(!a)throw new Error("Not authenticated");let T=B(m),s=await new k(T.tmsBaseUrl,a.username,a.access_key).createFolder(i,r);x(s.id,s.name)}catch(a){f(a instanceof Error?a.message:String(a)),b("naming")}})()},[n,i,m,x]),H=(0,t.useCallback)(()=>{v(""),f(null),h.current?w():b("list")},[w]);return p==="naming"||p==="creating"?(0,e.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:c.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:c.orange,bold:!0,children:"Create new folder"}),h.current&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.dim,children:"No folders yet \u2014 let's create one."})}),(0,e.jsxs)(u,{marginTop:1,children:[(0,e.jsx)(l,{color:c.dim,children:"Name: "}),p==="naming"?(0,e.jsx)(A,{value:S,onChange:o=>{v(o),E&&f(null)},onSubmit:D,onCancel:H}):(0,e.jsx)(l,{children:S})]}),E&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.red,children:E})}),p==="creating"&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.dim,children:"Creating..."})}),p==="naming"&&(0,e.jsx)(R,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:h.current?"cancel":"back"})]}):(0,e.jsx)(_,{title:"Folders",items:I,loading:$,loadingMore:O,preserveSelectionById:!0,error:U,itemNoun:"folders",onTab:()=>{h.current=!1,b("naming")},extraHint:"tab to create new",onSelect:o=>{let r=o.label.split(" (")[0];x(o.id,r)},onCancel:w})}export{X as a,W as b};
@@ -0,0 +1,62 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as Xt}from"./chunk-UVBDUDSL.js";import{b as Wt,c as it,d as at,e as Se,f as lt,g as Yt}from"./chunk-HN7DVSVI.js";import{a as Oe,b as te,c as Gt,e as ae,f as nt,i as zt,j as ot}from"./chunk-AH4AXJML.js";import{a as qt,b as st}from"./chunk-PN7LNQ7G.js";import{a as Re,b as Qt}from"./chunk-C5UNZ6ZY.js";import{c as Jt}from"./chunk-S3DAAAE5.js";import{a as Zt}from"./chunk-6NEJEMA6.js";import{a as Bt,b as Vt,c as rt,d as Le,e as Ht,f as Kt}from"./chunk-LRF6UP42.js";import{a as Mt}from"./chunk-WAOCHXJ5.js";import{a as z}from"./chunk-J37YPPCD.js";import{a as jt}from"./chunk-E47GFYXA.js";import{a as Ut,c as Xe,g as Ft,h as ue,i as et,j as tt}from"./chunk-3Z4EHIOW.js";import{a as Nt}from"./chunk-7CLUJYMW.js";import{a as Te,b as $t}from"./chunk-NLCCBXXV.js";import{a as O}from"./chunk-RZ4F3BHX.js";import{join as Ve,basename as dn}from"path";import{existsSync as es,readFileSync as mn}from"fs";import{existsSync as ct}from"fs";import{join as De,basename as er}from"path";function tr(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 d=Se(i),p=De(d,"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 d=1;d<i.trace.length;d++){let h=i.trace[d-1].file===e.rootPath?r:a(i.trace.slice(0,d));if(!h)return{kind:"author",reason:"no-result-md"};let C=i.trace[d-1].stepIndex,y=h.steps[C-1];if(!y)return{kind:"author",reason:"no-result-md"};if(y.kind!=="import")return{kind:"author",reason:"structure-mismatch"};let I=er(y.importPath),R=er(i.trace[d].file);if(I!==R)return{kind:"author",reason:"structure-mismatch"};if(y.status!=="passed")return{kind:"author",reason:"recorded-failed"}}return null}for(let i of e.steps){let d=i.trace[i.trace.length-1].file,p=i.trace[i.trace.length-1].stepIndex,h=n.has(d);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 y=d===e.rootPath?r:a(i.trace),I=hs(i,y,p);if(s.push(I),I.kind==="author"){n.add(d);for(let R=0;R<i.trace.length-1;R++)n.add(i.trace[R].file)}}return s}function hs(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=Wt(e);if(n!==s.md5)return{kind:"author",reason:"md5-mismatch"};let o=e.trace.length===1?zt(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 rr(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 sr(e){return De(e.recordingDir,"flows","0","actions.ndjson")}function nr(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 de(e){process.env.KANE_REPLAY_TRACE==="1"&&process.stderr.write(e)}function or(e,t){let r=e===0?"(none)":`0..${e-1}`,s=e>=t?"(none)":`${e}..${t-1}`;de(`[replay-trace] phase: replay ${r}, author ${s}
5
+ `)}function ir(e,t){de(`[replay-trace] step ${e}: REPLAY ${t==="ok"?"OK":"FAILED"}
6
+ `)}function ar(e,t,r){de(`[replay-trace] shrink ${e}/${t} \u2192 new boundary ${r}
7
+ `)}function lr(e,t){de(`[replay-trace] complete-reauthor (${e} shrinks exhausted of ${t})
8
+ `)}function cr(){de(`[replay-trace] force-author (--author) \u2014 walker bypassed
9
+ `)}function ur(e){de(`[replay-trace] cancelled at step ${e}
10
+ `)}import{join as gs}from"path";function ut(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:sr(e.decision),step_label:e.step.objective},screenshot_dir:gs(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 dr(e){let t=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,ur(a.failedAt??0),{authorBoundary:t,cancelledInPhase:s,shrinkCount:r};if(a.failedAt===null)return{authorBoundary:t,cancelledInPhase:s,shrinkCount:r};let l=Qt({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 lr(r+1,e.maxShrinks),{authorBoundary:0,cancelledInPhase:s,shrinkCount:r};r++,ar(r,Re.maxShrinks,l.newAuthorBoundary),t=l.newAuthorBoundary}}var bs=15e3,dt=3,mr=[500,1e3];async function mt(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:D(r.body,"session_expires_at")??""}:{ok:!1,...ys(r)}}function ys(e){let t=D(e.body,"error")??D(e.body,"code")??"",r=D(e.body,"message")??D(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 fr(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:D(r.body,"session_expires_at")??""}:{ok:!1,expired:r.status===404,httpStatus:r.status,message:D(r.body,"message")??D(r.body,"detail")??r.text??`HTTP ${r.status}`}}async function hr(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:D(s.body,"test_id")??e.testId,testcaseId:D(s.body,"testcase_id")??"",projectId:D(s.body,"project_id"),isTestCaseDeleted:typeof s.body?.is_test_case_deleted=="boolean"?s.body.is_test_case_deleted:void 0}:{ok:!1,...vs(s)}}function vs(e){let t=D(e.body,"error")??D(e.body,"code")??"",r=D(e.body,"message")??D(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 gr(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:D(s.body,"error")??"other",httpStatus:s.status,message:D(s.body,"message")??D(s.body,"detail")??s.text??`HTTP ${s.status}`}}async function Ue(e,t,r){let s=null;for(let n=1;n<=dt;n++){let o=new AbortController,a=setTimeout(()=>o.abort(),bs);try{let l=await O(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(),d=null;if(i)try{d=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:d,text:i};if(n<dt){await pr(mr[n-1]??1e3);continue}return{ok:!1,status:l.status,body:d,text:i}}catch(l){if(clearTimeout(a),s=l,n<dt){await pr(mr[n-1]??1e3);continue}}}return{ok:!1,status:0,body:null,text:s?.message??"exhausted retries"}}function pr(e){return new Promise(t=>setTimeout(t,e))}function D(e,t){if(typeof e!="object"||e===null)return;let r=e[t];return typeof r=="string"?r:void 0}var Ss=60*1e3,br="lock-heartbeat",me=null,pt=null,yr={register:(e,t)=>Le(e,t),deregister:e=>Ht(e),cleanup:(e,t)=>Kt(e,t),remoteLogger:null};function vr(){me!==null&&(clearInterval(me),me=null)}function ft(e){if(me!==null)return;let t=e.lifecycle??yr;pt=t,me=setInterval(async()=>{let r=await fr({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
+ `)}},Ss),t.register(br,()=>vr())}function ht(){me!==null&&(vr(),(pt??yr).deregister(br),pt=null)}import{readFileSync as Sr,readdirSync as Rr,existsSync as le}from"fs";import{join as Z}from"path";function wr(e,t,r,s,n,o){try{let a=Z(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=Z(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=Rr(R).filter(x=>le(Z(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=Z(R,c[0])}else if(!le(Z(a,"screenshots"))){let R=Rr(a).filter(c=>le(Z(a,c,"screenshots")));if(R.length===0){n("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:r,reason:"no_screenshots_dir"});return}l=Z(a,R[0])}let i=Z(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 d=Z(a,"actions.ndjson");if(!le(d)){n("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:r,reason:"ndjson_not_found"});return}let p=Sr(d,"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 y=JSON.parse(h).action_id;if(!y){n("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:r,reason:"no_action_id"});return}let I=Sr(i);s.enqueue(y,I),n("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:r,child_id:o,action_id:y,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 Rs,join as ws}from"path";function Ir(e,t,r){let s=e.total_runs??1,n=e.run_dir,o,a;if(s>1&&n){let l=Rs(n);o=Array.from({length:s},(i,d)=>ws(l,String(t+d))),r&&r.length===s&&(a=r)}return{allRunDirs:o,flowObjectives:a}}function _r(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 Is}from"child_process";async function kr(e,t,r=100){let s=`${e.replace(/\/+$/,"")}/json/version`,n=await O(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 jt(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 d(P,_){let L=l++;return new Promise((W,$)=>{i.set(L,{resolve:ce=>W(ce),reject:$});let be={id:L,method:P};_&&(be.params=_),a.send(JSON.stringify(be))})}let h=(await d("Target.getTargets")).targetInfos.find(P=>P.type==="page");if(!h)throw a.close(),new Error("CDP: no page target found");let y=(await d("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 d("Browser.getWindowBounds",{windowId:y})).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 _s=new Set(["1","true","yes"]);function Cr(e){if(e?.headless)return null;let t=process.env.KANE_CLI_DISABLE_MARKER;if(t!=null&&_s.has(t.toLowerCase()))return null;let r=qt();if(!r)return null;let s=[...r.args,"overlay"];e?.text&&s.push(e.text);let n;try{n=Is(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&&kr(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 d=i.trim();d&&o({type:"step_text",text:d})},setStepComplete(){l||o({type:"step_complete"})},kill(){if(!l){l=!0,a?.();try{n.stdin?.end()}catch{}try{n.kill("SIGTERM")}catch{}}}}}function Er(e,t,r){return`${e}/projects/${t}/test-cases/${r}`}function gt(e,t,r,s){return`${Er(e,t,r)}/dashboard/share/${s}?type=summary&agentView=true&fqdn=summary-page`}function Ar(e,t,r){return`${Er(e,t,r)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{mkdtempSync as js,rmSync as Us}from"fs";import{join as Fs}from"path";import{tmpdir as $s}from"os";import{spawn as xr,spawnSync as ks}from"child_process";import{existsSync as bt}from"fs";import{createConnection as Cs}from"net";import{homedir as we,platform as _e}from"os";import{join as Ie}from"path";var Es=new Set(["1","true","yes"]),$e=class extends Error{constructor(t){super(t),this.name="ChromeNotFoundError"}};function uo(e){return e instanceof $e?e.message:`Chrome failed: ${e instanceof Error?e.message:String(e)}`}var Ne={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 As(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let e=_e(),t=Ne[e]??Ne.linux;for(let r of t)if(bt(r))return r;return e==="win32"?"chrome.exe":"google-chrome"}function xs(){if(process.env.KANE_CLI_CHROME_PATH)return bt(process.env.KANE_CLI_CHROME_PATH);let e=_e();if((Ne[e]??Ne.linux).some(n=>bt(n)))return!0;let r=e==="win32"?"chrome.exe":"google-chrome",s=e==="win32"?"where":"which";try{return ks(s,[r],{stdio:"ignore"}).status===0}catch{return!1}}function Ps(){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 Ts(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 Ls(e){return new Promise(t=>{let r=Cs({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 Os(){for(let e=et;e<=tt;e++)if(!await Ls(e))return e;throw new Error(`All CDP ports ${et}-${tt} are in use. Close other Chrome instances.`)}async function Ds(e,t=15e3){let r=Date.now(),s=`http://127.0.0.1:${e}/json/version`;for(;Date.now()-r<t;){try{if((await O(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 Pr(e){let t=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(t!=null&&Es.has(t.toLowerCase()))&&!xs())throw Vt()?.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 $e(Ps());let s=_e(),n=await Os(),o=As(),a=Ts({port:n,...e});e.startUrl&&a.push(e.startUrl);let l=xr(o,a,{stdio:"ignore",detached:!0});l.unref();let i=await new Promise((d,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}`))}),Ds(n).then(d,p)});return{process:l,port:n,cdpEndpoint:i,kill(){try{if(l.pid)if(s==="win32")xr("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 Tr(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 O(`${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=js(Fs($s(),"kane-clean-")),t=r;let n=r;Le("tempDir",()=>{try{Us(n,{recursive:!0,force:!0})}catch{}})}let s=await Pr({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 Lr(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 Ns,readFileSync as Dr,existsSync as jr}from"fs";import{join as Ms}from"path";function Or(e,t){if(!jr(e))return{};let r={},s;try{s=Ns(e).filter(n=>n.endsWith(".json")).sort()}catch{return{}}for(let n of s)try{let o=Dr(Ms(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 d=i;r[l]={value:d.value,secret:d.secret??!1,syntax:d.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 Ur(e){if(!jr(e))throw new Error(`Variables file not found: ${e}`);let t=Dr(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 Fr(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=Or(e,r),n=Or(t,r);return{...s,...n}}function pe(e,t){let r={},s={},n=t;for(let[o,a]of Object.entries(e))if(a.secret){let l=`secrets.user.${o}`;r[l]={value:a.value,secret:!0,syntax:`{{secrets.user.${o}}}`,type:"secret"},s[o]=l,n=n.replaceAll(`{{${o}}}`,`{{secrets.user.${o}}}`)}else{let l=`global.${o}`;r[l]={value:a.value,secret:!1,syntax:`{{global.${o}}}`,type:"global"},s[o]=l,n=n.replaceAll(`{{${o}}}`,`{{global.${o}}}`)}return{variables:r,objective:n,keyMap:s}}var fe=class{constructor(t){this.baseUrl=t}async pushSecret(t){let r=Te(t.username,t.accessKey),s=await O(`${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 O(`${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 O(`${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 O(`${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 Nr(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 Mr(e){let t=$r(e.globalDir,e.localDir,e.onLoadError),r=e.file?Ur(e.file):{},s=e.inline?Fr(e.inline):{},n={...t,...r,...s},o=Object.keys(n).length>0,{variables:a,objective:l}=o?pe(n,e.objective):{variables:{},objective:e.objective},i=Object.entries(n).filter(([,p])=>p.secret),d=Object.entries(n).filter(([,p])=>!p.secret);return{raw:n,auteur:a,auteurObjective:l,secretEntries:i,nonSecretEntries:d}}async function Br(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 Bs,existsSync as Vs}from"fs";function yt(e){if(!Vs(e))return null;try{return Bs(e,"utf-8").trim()||null}catch{return null}}import{writeFileSync as Hs,mkdirSync as Ks}from"fs";import{dirname as Vr}from"path";function vt(e){let t=ae(e.sourcePath);try{Ks(Vr(t),{recursive:!0})}catch(s){return process.stderr.write(`
19
+ \u26A0 Failed to create output directory.
20
+ ${s.message}
21
+ Path: ${Vr(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);try{Hs(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 qs=()=>{};async function Hr(e,t,r){let s=t.log??qs,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{vt({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)})}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,d=e.session.getFlows(),p=d.map((y,I)=>({index:I+1,heading:`Step ${I+1}`,headingLine:0,body:{kind:"objective",text:y.objective}})),h=d.map((y,I)=>({rootStepIndex:I+1,status:y.status==="passed"?"passed":y.status==="failed"?"failed":"skipped",duration_s:y.duration,reason:y.reason})),C=h.some(y=>y.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((y,I)=>y+(I.duration_s??0),0),sessionId:e.session.sessionId})}catch(y){s("error","FINALIZE_TUI_RESULT_MD_ERROR","TUI _Result.md write failed",{error:String(y)})}try{vt({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})}catch(y){s("error","FINALIZE_TUI_META_WRITE_ERROR","TUI meta.json write failed",{error:String(y)})}if(o?.codeExportDir)try{let y=e.tuiConfig.code_export?.language??"python";lt(o.codeExportDir,nt(i,"playwright",y))}catch(y){s("error","FINALIZE_TUI_CODE_COPY_ERROR","TUI code-export copy failed",{error:String(y)})}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 qr,writeFileSync as Gr,existsSync as zr}from"fs";function Kr(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=Gs(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 Gs(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 zs(e){if(!(!e.shouldReplaceLocalOutput||!e.resolvedTest||!e.sourcePath||!e.stepRunRecords||!e.outcomes||!e.overallStatus))return async()=>{Yt({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(te(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),zr(`${s}.staging`)&&ot(s)}}}function Ws(e){if(!(!e.shouldCommit||e.isFirstRun||!e.tmsBaseUrl||!e.testId||!e.fromCommitId||!e.newCommitId||!e.basicAuth||!e.resolvedTest||!e.decisions))return async()=>{let t=Kr(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 hr({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(qr(n,"utf8"));o.commit_id=e.newCommitId,Gr(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 Qs(e){if(!(!e.isFirstRun||!e.sourcePath))return async t=>{if(!e.sourcePath)return;let r=ae(e.sourcePath);try{let s=zr(r)?JSON.parse(qr(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),Gr(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 Wr(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,d=[];for(let I of Object.keys(r.auteurVariables))I.startsWith("secrets.user.")&&d.push({key_name:I.replace("secrets.user.",""),scope:"user"});let h=r.getContext().prior_runs.map(I=>I.status),C=r.auteurVariables,y=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:y?C:void 0,variableIds:e.variableIds,secrets:d,codeExport:e.codeExport,onProgress:e.onProgress,log:e.log,shouldUploadArtifacts:e.shouldUploadArtifacts,shouldReplaceLocalOutput:e.shouldReplaceLocalOutput,shouldCommit:e.shouldCommit,isFirstRun:e.isFirstRun,onAtomicReplace:zs(e),onCommitLock:Ws(e),onFinalizeSuccess:Qs(e)}}var Qr=["python","javascript"];function Js(e){if(e!==void 0){if(!Qr.includes(e))throw new Error(`--code-language must be one of: ${Qr.join(", ")} (got "${e}")`);return e}}function Jr(e,t){let r=Js(e.codeLanguage);return{enabled:e.codeExport??t.enabled,language:r??t.language,skipValidation:e.skipCodeValidation??t.skip_validation}}async function Yr(e){try{let r=await new Nt(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 Ys=null,Zs=()=>Ys??=import("sharp").then(e=>e.default??e).catch(()=>null),Me=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 Zs();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 d=await O(l,{method:"PUT",headers:{"Content-Type":s,"x-ms-blob-type":"BlockBlob"},body:r});if(d.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:d.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 O(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 Xs,arch as en}from"os";function Zr(e){let t={proxyUrl:Ft,sessionId:e.sessionId,identity:e.identity,device:{cli_version:Ut,platform:Xs(),arch:en()},getToken:e.getToken};return new ke(t)}import{execSync as tn}from"child_process";import{readFileSync as rn}from"fs";import{createHash as sn}from"crypto";import{hostname as nn,platform as on,arch as an}from"os";var Be=null;function Xr(){return Be||(Be=ln(),Be)}function ln(){let e=on();if(e==="darwin")try{let s=tn("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=rn("/etc/machine-id","utf-8").trim();if(r)return r}catch{}let t=`${nn()}:${e}:${an()}`;return sn("sha256").update(t).digest("hex").slice(0,32)}async function cn(e){try{let t=z(e.env),s=await new Mt(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 Me(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 un(e){if(e.session.hasRemoteLogger||!e.tmsCreds)return null;let t=e.tmsCreds,r=Zr({sessionId:e.session.sessionId,identity:{org_id:String(t.org_id??""),user_id:String(t.user_id??""),machine_id:Xr(),email:t.email??null,email_domain:t.email_domain??"unknown",user_type:t.user_type??"unknown",env:e.env},getToken:e.getToken});return e.session.setRemoteLogger(r),r.start(),r}async function It(e){let[t,r]=await Promise.allSettled([e.skipScreenshotQueue?Promise.resolve(null):cn({env:e.env,auth:e.auth,session:e.session,log:e.log}),un({env:e.env,tmsCreds:e.tmsCreds,getToken:e.getToken,session:e.session})]);return{resolver:e.resolver,screenshotQueue:t.status==="fulfilled"?t.value:null,remoteLogger:r.status==="fulfilled"?r.value:null}}async function St(e){await Promise.allSettled([e.screenshotQueue?.drain(),e.remoteLogger?.shutdown()])}async function Ci(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 Rt(e.env,e.tmsCreds,r,t);return wt(s,t),s}case"login":case"switch":{let r=t.state.identityServicesRef.current;r&&(await St(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 Rt(e.env,n,s,t);return wt(o,t),o}case"logout":{let r=t.state.identityServicesRef.current;return r&&(await St(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 St(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 Rt(e.env,s,o,t);return wt(a,t),a}}}async function Rt(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}:It({env:e,tmsCreds:t,resolver:r,auth:a,getToken:()=>s.auth.getToken(),session:s.getSession(),log:s.log,skipScreenshotQueue:s.options?.skipScreenshotQueue})}function wt(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 la(e,t,r){let{path:s,cwd:n,opts:o,isAgent:a,resolved:l,resolvedAuth:i,cliOverrides:d,environment:p,envConfig:h,profile:C,model:y,creds:I,configStore:R,session:c}=e,x=!1,f=await gn(s,l,o,{resolvedAuth:i,tmsBaseUrl:h.tmsBaseUrl},c.sessionId,r);if(f.abort)return{overallStatus:"failed",exitCode:f.abort.exitCode,outputDir:te(s),durationS:0,uploadResult:null};let P=f.lockAcquired,_=!1,L=!1,W=!1;P&&t.onLockState({phase:"acquired",scope:"preemptive"}),c.start({model:y,environment:p,profile:C}),c.setRecordingEnabled(!1);let $=0,be=i.basicAuth?{username:i.basicAuth.username,accessKey:i.basicAuth.access_key}:i.token??null,ce=null;if(be!==null){let u=await It({env:p,tmsCreds:i.resolvedCreds??null,resolver:i.resolver,auth:be,getToken:async()=>i.token??null,session:c,log:(m,g,b,v)=>c.log(m,g,b,v),skipScreenshotQueue:!!o.local||!i.basicAuth});ce=u.screenshotQueue,u.remoteLogger&&(r.register("remote-logger",()=>u.remoteLogger.shutdownSync()),r.remoteLogger=u.remoteLogger,e.skipGlobalRemoteLogger||Bt(u.remoteLogger))}if(o.name){try{Jt(o.name)}catch(u){return process.stderr.write(`error: ${u.message}
35
+ `),{overallStatus:"failed",exitCode:2,outputDir:te(s),durationS:0,uploadResult:null}}c.setSessionName(o.name)}let Ge={};for(let[u,m]of Object.entries(l.rootGlobal))He.includes(u)||(Ge[u]=m);for(let[u,m]of Object.entries(d))He.includes(u)||m!==void 0&&(Ge[u]=m);let K={...l.chrome};for(let u of He){let m=d[u];m!==void 0&&(K[u]=m)}let ss={...Ge,...K};c.setResolvedGlobal(ss);let Q;try{Q=await Tr({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}
36
+ `),await c.finish("complete"),{overallStatus:"failed",exitCode:2,outputDir:te(s),durationS:0,uploadResult:null}}let Ce=Q.instance;Ce&&r.register("chrome",()=>{try{Ce.kill()}catch{}});let j=null,_t=Q.cdpEndpoint??K.cdp_endpoint;if(_t&&!K.ws_endpoint&&!K.headless)try{j=Cr({headless:K.headless??!1,cdpEndpoint:_t,chromePid:Ce?.process.pid}),j&&r.register("marker-overlay",()=>j.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 re=Mr({objective:"",globalDir:Ve(Xe,"variables"),localDir:Ve(n,".testmuai","variables"),file:o.variablesFile,inline:o.variables}),ns=l.rootGlobal.variables??{},B=pn(re.raw,ns);c.setAuteurVariables(B.auteur);let kt=yt(Ve(Xe,"global-memory.md"))??void 0,Ct=yt(Ve(n,".testmuai","context.md"))??void 0,Et=I.getActiveProfile()??"default",At=I.getDefaultEnv(),{rehydrateIfStale:os}=await import("./profile-sync-DTTRRIVP.js");os(I,R,Et,At);let V=R.load(),H=V.project_id??null,Ee=V.folder_id??null;if(!o.local&&!H&&i.basicAuth)try{let u=await Xt({creds:I,config:R,profile:Et,env:At,tmsCreds:i.basicAuth,log:(m,g,b,v)=>c.log(m,g,b,v)});H=u.projectId,Ee=u.folderId,V=R.load(),process.stderr.write(`info: using project '${u.projectName}' / folder '${u.folderName}' (auto-configured)
37
+ `)}catch(u){process.stderr.write(`warn: could not auto-configure project/folder: ${u.message}
38
+ KaneAI upload will be skipped for this run.
39
+ `)}o.local?process.stderr.write(`info: --local \u2014 KaneAI upload skipped
40
+ `):i.basicAuth?H||process.stderr.write(`warn: KaneAI upload skipped \u2014 no project configured.
41
+ `):process.stderr.write(`warn: KaneAI upload skipped \u2014 TMS credentials could not be resolved.
42
+ Run 'kane-cli login' (OAuth) or 'kane-cli config set-username/set-access-key' (basic auth).
43
+ `);let ye=!o.local&&!!i.basicAuth&&H!=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 m=await Yr({tmsBaseUrl:u.tmsBaseUrl,auth:i.basicAuth,objective:l.steps[0].objective,url:"",projectId:H,folderId:Ee??"",hasCustomProfile:!!K.chrome_profile,log:(g,b,v,S)=>c.log(g,b,v,S)});m&&c.setTestId(m)}catch(m){process.stderr.write(`warn: ATM test creation failed: ${m.message}
44
+ `)}}else f.testId&&c.setTestId(f.testId);let Ae={};if(i.basicAuth&&!o.local&&(B.secretEntries.length>0||B.nonSecretEntries.length>0))try{Ae=await Br({variables:B,auth:i.basicAuth,orgId:String(i.resolvedCreds?.org_id??""),env:p,localMode:!!o.local,log:(u,m,g,b)=>c.log(u,m,g,b)})}catch(u){process.stderr.write(`warn: variable/secret push failed: ${u.message}
45
+ `)}let ze=new Map;for(let[u,m]of B.nonSecretEntries)ze.set(u,m.value);let We=new Map;for(let[u,m]of B.secretEntries)We.set(u,m.value);async function Qe(u){if(!i.basicAuth||o.local)return;let m=[],g=[];for(let[v,S]of Object.entries(u))if(S.secret){if(We.get(v)===S.value)continue;g.push([v,S])}else{if(ze.get(v)===S.value)continue;m.push([v,S])}if(m.length===0&&g.length===0)return;let b=z(p);if(m.length>0){let v=new he(b.tmsBaseUrl,i.basicAuth.username,i.basicAuth.access_key);for(let[S,k]of m)try{let E=await v.upsertVariable({name:S,value:k.value});Ae[S]=E.id,ze.set(S,k.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(g.length>0){let v=new fe(b.secretsBaseUrl);for(let[S,k]of g)try{await v.pushSecret({secretKey:S,secretValue:k.value,username:i.basicAuth.username,accessKey:i.basicAuth.access_key,orgId:String(i.resolvedCreds?.org_id??"")}),We.set(S,k.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,m,g)=>{if(!(P||f.isFirstRun))return;let b=$+m;wr(c.sessionDir,b,u,ce,(v,S,k,E)=>c.log(v,S,k,E),g)}:void 0,xt=l.rootTitle??l.rootSteps[0]?.heading??dn(s),is=Object.keys(B.raw).length>0?pe(B.raw,xt).objective:xt;c.setFirstRun(is,ue);let X=new Fe(l),Je=new Date().toISOString(),as=Date.now(),ls=typeof o.maxSteps=="string"&&o.maxSteps!==""?parseInt(o.maxSteps,10):void 0;function Pt(u,m){let g=l.steps[u],b=ts(g.config,d),v=ge(re.raw,b.variables,g.objective);return Lr({objective:v.objective,url:u===0?ue:void 0,model:y,chrome:Q,auth:i,sessionId:c.sessionId,runIndex:m,windowSize:{width:1920,height:1080},maxSteps:b.max_steps??ls??30,headless:K.headless??!1,variables:Object.keys(v.variables).length>0?v.variables:void 0,globalContext:b.global_context??kt,localContext:b.local_context??Ct,sessionContext:c.getContext()})}function Tt(u){let g=l.steps[u].trace[0].stepIndex,b=l.rootSteps.find(S=>S.index===g);l.steps.slice(0,u).some(S=>S.trace[0].stepIndex===g)||t.onAgentEvent({type:"test_md_step_start",step_index:g,heading:b.heading,ref:b.body.kind==="import_ref"?{kind:"import",label:b.body.path}:null})}function Ye(u,m,g,b,v,S){let k=l.steps[u],E=k.trace[0].stepIndex,q=!l.steps.slice(u+1).some(A=>A.trace[0].stepIndex===E),G=g?.status==="passed"?"passed":"failed",F=g?.reason??v??void 0,N=g?.duration??S,{continueOverall:M}=X.recordStep(k,{status:G,duration_s:N,reason:F}),oe=ts(k.config,d),J=ge(re.raw,oe.variables,k.objective).objective;if(g){let A=Ir(g,m,b);c.addRunResult(_r(g,J,m,A),g.total_runs)}else c.addRunResult({index:m,objective:J,status:G,summary:"",context:{memory:{},variables:{},pointer:""}},1);if(q||!M){let A=X.snapshotOutcomes().find(w=>w.rootStepIndex===E);t.onAgentEvent({type:"test_md_step_end",step_index:E,status:A.status,duration_s:A.duration_s??0,ref_kind:A.refKind??null,inlined_count:A.inlinedCount??null,failed_sub_step_index:A.failedSubStepIndex??null})}return M}async function cs(u){or(u,l.steps.length);for(let m=0;m<u;m++){if(x)return{failedAt:m,cancelled:!0};let g=l.steps[m],b=f.decisions[m];if(b.kind!=="replay")return process.stderr.write(`error: runReplayPhase invoked on a non-replay decision at step ${m}
46
+ `),{failedAt:m,cancelled:!1};let v=c.nextRunIndex();$=v;let S=m===0?ue:void 0,k={width:V.window_size.width,height:V.window_size.height},E=ge(re.raw,g.config.variables,g.objective),q=ut({step:g,decision:b,chrome:Q,auth:i,sessionId:c.sessionId,runIndex:v,sessionDir:c.sessionDir,windowSize:k,forceNavigateUrl:S,sessionContext:c.getContext(),variables:Object.keys(E.variables).length>0?E.variables:void 0});await Qe(E.raw),Tt(m);let G=Date.now(),F=null,N=null;try{let A=st(q,{environment:p});r.register("runner",()=>{rt()&&(x=!0);try{A.cancel()}catch{}}),j?.setRunActive(!0);try{for await(let w of A.events){if(t.onAgentEvent(w),w.type==="step_event"&&w.event==="reasoning"?j?.setStepText(w.detail):w.type==="step_end"&&(w.status==="passed"&&j?.setStepComplete(),ve&&ve(w.index,0,w.child_id)),w.type==="run_end"){F=w;break}if(w.type==="error"){N=w.message??"runner error";break}}try{A.cancel()}catch{}if(!F&&!N){let{code:w}=await A.exited;w!==0&&(N=`runner exited with code ${w}`)}}finally{j?.setRunActive(!1),r.cleanup("runner","Replay step complete")}}catch(A){N=A.message}if(x)return{failedAt:m,cancelled:!0};let M=Math.round((Date.now()-G)/1e3),oe=Ye(m,v,F,null,N,M);c.recordStepRun({testmdStepIndex:l.steps[m].flatIndex,runIndex:v,totalRunDirs:1});let J=!!N||F?.status==="failed";if(ir(m,J?"failed":"ok"),J||!oe)return{failedAt:m,cancelled:!1}}return{failedAt:null,cancelled:!1}}let Lt=async()=>{if(P)return!0;let u=i.basicAuth;if(!u){let v=await i.resolver.resolve(!0);v?.username&&v?.access_key&&(u={username:v.username,access_key:v.access_key},i.basicAuth=u)}if(!f.testId||!f.fromCommitId||!u)return process.stderr.write(`error: cannot acquire lock \u2014 missing required state
47
+ `),!1;let m=c.sessionId,g=o.onLockConflict??l.rootGlobal.on_lock_conflict??"readonly",b=await rs({tmsBaseUrl:h.tmsBaseUrl,testId:f.testId,fromCommitId:f.fromCommitId,newCommitId:m,basicAuth:u,onLockConflict:g});return b==="ok"?(P=!0,f.newCommitId=m,c.log("info","MID_RUN_LOCK_ACQUIRED","Mid-run lock acquired",{test_id:f.testId}),a&&t.onLockState({phase:"acquired",scope:"mid_run"}),ft({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:b}),a&&t.onLockState({phase:"conflict",scope:"mid_run",reason:b}),process.stderr.write(`error: mid-run lock acquisition failed (${b})
48
+ `),!1)};if(a){let{authorBoundary:u,cancelledInPhase:m,shrinkCount:g}=await dr({decisions:f.decisions,hasRetry:o.retry===!0||o.retryCount!==void 0,maxShrinks:o.retryCount!==void 0?parseInt(o.retryCount,10):Re.maxShrinks,runReplayPhase:cs,session:c,accumulator:X,acquireLockIfNeeded:Lt});if(W=g>0,g>0&&(c.log("info","RETRY_TRIGGERED","Retry loop triggered",{shrink_count:g,final_author_boundary:u}),t.onRetryAttempt({shrink_count:g,final_author_boundary:u,complete_reauthor:u===0})),u===0&&g>0&&c.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback",{shrink_count:g}),!m&&u>=0)for(let b=u;b<l.steps.length;b++){let v=l.steps[b];if(!X.shouldRunFlatStep(v))continue;Tt(b),_=!0;let S=c.nextRunIndex();$=S,await Qe(ge(re.raw,v.config.variables,v.objective).raw);let k=Pt(b,S),E=Date.now(),q=null,G=null,F=null,N=!1,M=0;try{let A=st(k,{environment:p});r.register("runner",()=>{rt()&&(x=!0);try{A.cancel()}catch{}}),j?.setRunActive(!0);try{for await(let w of A.events){if(t.onAgentEvent(w),w.type==="bifurcation"){let ie=w.count??w.flows?.length??0;(w.is_single_flow??ie<=1)||(F=w.flows??null,N=!0,M=0)}else if(w.type==="run_start"&&N)M++;else if(w.type==="step_event"&&w.event==="reasoning")j?.setStepText(w.detail);else if(w.type==="step_end"&&(w.status==="passed"&&j?.setStepComplete(),ve)){let ie=N?Math.max(0,M-1):0;ve(w.index,ie,w.child_id)}if(w.type==="run_end"){q=w;break}if(w.type==="error"){G=w.message??"runner error";break}}try{A.cancel()}catch{}}finally{j?.setRunActive(!1),r.cleanup("runner","Step complete")}}catch(A){G=A.message}let oe=Math.round((Date.now()-E)/1e3),J=Ye(b,S,q,F,G,oe);if(c.recordStepRun({testmdStepIndex:l.steps[b].flatIndex,runIndex:S,totalRunDirs:q?.total_runs??1}),!J||x)break}}else{let{effectiveDecisions:u}=await import("./effective-decisions-DRM3JSR4.js"),{decideRetry:m}=await import("./replay-policy-6USQBT3E.js"),g=o.retry===!0||o.retryCount!==void 0,b=o.retryCount!==void 0?parseInt(o.retryCount,10):Re.maxShrinks,v=o.author===!0;v&&(cr(),c.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let S=v?0:je(f.decisions),k=0,E=null,q=f.decisions.filter(M=>M.kind==="replay").length,G=f.decisions.length-q,F=[];o.push&&F.push("--push"),g&&F.push("--retry"),o.retryCount!==void 0&&F.push(`--retry-count=${o.retryCount}`),v&&F.push("--author");let N={source:s,steps:{total:f.decisions.length,replay:q,author:G},model:y,viewport:{width:V.window_size.width,height:V.window_size.height},chrome:Q.cdpEndpoint??Q.wsEndpoint??"managed",session:c.sessionName??"ephemeral",variables:{count:Object.keys(B.raw).length,secrets:Object.values(B.raw).filter(M=>M.secret).length,names:Object.keys(B.raw)},flags:F,mode:d.mode??"testing"};for(;;){let M=c.snapshot(),oe=X.snapshot(),J=u(f.decisions,S,v);if(k>=1){let T=S===0?`\u21BB Complete re-author \u2014 retry budget exhausted (${k}/${b})`:`\u21BB Retry ${k}/${b} \u2014 replay 0..${S-1}, author ${S}..${f.decisions.length-1}
49
+ reason: replay miss at step ${(E??0)+1}`;process.stderr.write(T+`
50
+ `)}let A=k>=1&&S>0&&E!==null?{startIdx:0,endIdx:E,count:E}:void 0;j?.setRunActive(!0);let w=await vn({decisions:J,resolved:l,session:c,accumulator:X,tuiConfig:V,globalConfig:N,buildStepConfigAt:Pt,buildReplayConfig:T=>{let Y=f.decisions[T];if(Y.kind!=="replay")throw new Error("expected replay decision at index "+T);let ee=l.steps[T];return ut({step:ee,decision:Y,chrome:Q,auth:i,sessionId:c.sessionId,runIndex:c.nextRunIndex(),sessionDir:c.sessionDir,windowSize:{width:V.window_size.width,height:V.window_size.height},forceNavigateUrl:T===0?ue:void 0,sessionContext:c.getContext(),variables:fn(re.raw,ee.config.variables,ee.objective)})},onAnyAuthorStep:()=>{_=!0},onCancel:()=>{L=!0},topBannerModel:y,topBannerAuth:`${I.getActiveProfile()??"no profile"}/${p}`,spawnOpts:{environment:p,mode:d.mode??"testing",log:(T,Y,ee,Ze)=>c.log(T,Y,ee,Ze)},priorAttemptRollup:A,pushStepLevelDelta:(T,Y)=>Qe(ge(re.raw,T,Y).raw),onSequencerStepEnd:(T,Y,ee,Ze)=>{let ms=Math.round((Date.now()-Ze)/1e3),ps=T.hadError?T.reason??"runner error":null,fs=Ye(Y,ee,T.runEnd,T.bifurcationFlows??null,ps,ms);return c.recordStepRun({testmdStepIndex:l.steps[Y].flatIndex,runIndex:ee,totalRunDirs:T.runEnd?.total_runs??T.bifurcationFlows?.length??1}),fs},screenshotDispatcher:ve,onReasoning:T=>j?.setStepText(T),onStepComplete:()=>j?.setStepComplete(),onSpawnStart:T=>{$=T},host:t});if(j?.setRunActive(!1),w.cancelled){r.cleanup("marker-overlay","user cancelled run"),r.cleanup("chrome","user cancelled run");break}if(w.failedAt===null)break;let ie=m({failedAt:w.failedAt,shrinkCount:k,hasRetry:g,maxShrinks:b});if(ie.kind==="fail"||!P&&!await Lt())break;c.rollback(M),X.rollback(oe),ie.kind==="complete-reauthor"?S=0:S=ie.newAuthorBoundary,k++,W=!0,c.log("info","RETRY_TRIGGERED","Retry loop triggered (TTY)",{shrink_count:k,failed_at:E}),S===0&&c.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback (TTY)",{shrink_count:k}),E=w.failedAt}}let U=X.finalize(),se=Math.round((Date.now()-as)/1e3),us={session:c,resolvedAuth:i,chromeResult:Q,chromeInstance:Ce??null,testId:c.testId??null,preparedVariables:B,variableIds:Ae,globalContext:kt,localContext:Ct,tuiConfig:V,env:p,localMode:!!o.local},ne=await Hr(us,{performUpload:async()=>{if(!i.basicAuth)return null;let u=z(p),m=(_||o.push===!0)&&!L,g=(P||f.isFirstRun)&&!L&&U.overallStatus==="passed",b=ye&&(P||f.isFirstRun);c.log("info","PIPELINE_GATE_STATE","Derived gate state (finalize)",{phase:"finalize",shouldUploadArtifacts:ye,shouldUploadPipeline:b,shouldReplaceLocalOutput:m,shouldCommit:g,lockHeld:P,anyAuthorStepRan:_,cancelled:L,overallStatus:U.overallStatus});let v=Wr({session:c,env:p,auth:i,variables:B,variableIds:Ae,projectId:H,folderId:Ee,totalSteps:U.outcomes.length,totalDuration:se,screenshotExtMap:ce?.getExtMap(),codeExport:Jr({codeExport:o.codeExport,codeLanguage:o.codeLanguage,skipCodeValidation:o.skipCodeValidation},V.code_export),onProgress:()=>{},log:(k,E,q,G)=>c.log(k,E,q,G),shouldUploadArtifacts:b,shouldReplaceLocalOutput:m,shouldCommit:g,isFirstRun:f.isFirstRun,resolvedTest:l,sourcePath:s,stepRunRecords:c.getStepRunRecords(),outcomes:U.outcomes,overallStatus:U.overallStatus,fromCommitId:f.fromCommitId,startedISO:Je,durationS:se,tmsIds:{testId:f.testId??c.testId??void 0,testcaseId:f.testcaseId??c.testcaseId??void 0,projectId:H??void 0,folderId:Ee??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:W,forceAuthor:o.author===!0});f.newCommitId!=null&&(v.skipTmsFinalize=!0);let S=new Zt(v);return a?await S.execute():await t.runUpload(S,k=>{if(k.testcaseId&&k.shareId&&H)return gt(u.testManagerUiUrl,H,k.testcaseId,k.shareId)})},runCleanup:()=>{r.cleanup("chrome","test.md run complete")},log:(u,m,g,b)=>c.log(u,m,g,b)},{overallStatus:U.overallStatus,outcomes:U.outcomes,sourcePath:s,title:l.rootTitle,rootSteps:l.rootSteps,startedISO:Je,durationS:se,localMode:!!o.local,skipLocalWrites:!0});await bn(s,f,c,U.outcomes,U.overallStatus,Je,se,ne.uploadResult,V,o,{resolvedAuth:i,tmsBaseUrl:h.tmsBaseUrl},P);let Ot=z(p),xe=ne.uploadResult?.testcaseId,Pe=xe&&ne.uploadResult?.shareId&&H?gt(Ot.testManagerUiUrl,H,xe,ne.uploadResult.shareId):void 0,Dt={overallStatus:U.overallStatus,durationS:se,decisions:f.decisions,outcomes:U.outcomes,cancelled:L,retryTriggered:W,lockHeld:P,anyAuthorStepRan:_,isFirstRun:f.isFirstRun,wantsPush:o.push===!0,uploadResult:ne.uploadResult,shouldUploadArtifacts:ye,shouldReplaceLocalOutput:_&&!L,shouldCommit:(P||f.isFirstRun)&&!L&&U.overallStatus==="passed",shareUrl:Pe},{buildSummaryEvent:ds}=await import("./SummaryBox-5Y2YYOUM.js");if(a?t.onAgentEvent(ds(Dt)):await t.onSummary(Dt),!a){let u=xe&&H?Ar(Ot.testManagerUiUrl,H,xe):void 0;await t.onLinks({recordedTestPath:s,outputDir:te(s),shareableLink:Pe,testCaseLink:u,codeExportDir:ne.uploadResult?.codeExportDir})}return t.onAgentEvent({type:"test_md_done",overall_status:U.overallStatus,duration_s:se,session_id:c.sessionId,...Pe?{share_url:Pe}:{}}),{overallStatus:U.overallStatus,exitCode:U.overallStatus==="passed"?0:1,outputDir:te(s),durationS:se,uploadResult:ne.uploadResult}}function pn(e,t){let r={...e,...t},s=Object.keys(r).length>0?pe(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=pe(s,r);return{raw:s,variables:Nr(n.variables,n.objective),objective:n.objective}}function fn(e,t,r){let s=ge(e,t,r).variables;return Object.keys(s).length>0?s:void 0}function ts(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 hn(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}async function gn(e,t,r,s,n,o){let a=Gt(e),l=tr(t,es(a)?a:null);nr(t,l);let i=ae(e),d=es(i)?JSON.parse(mn(i,"utf8")):null,p=d?.testcase_id,h=d?.test_id,C=d?.commit_id,y=r.push===!0,I=r.retry===!0||r.retryCount!==void 0,R=r.author===!0;y&&!p&&process.stderr.write(`[--push] no meta.json yet \u2014 flag is a no-op on first run
51
+ `),R&&(p=void 0,h=void 0,C=void 0);let c=s.resolvedAuth.basicAuth;if(!c){let $=await s.resolvedAuth.resolver.resolve(!0);$?.username&&$?.access_key&&(c={username:$.username,access_key:$.access_key},s.resolvedAuth.basicAuth=c)}let x=!!c,f=!r.local&&x&&h!=null&&C!=null&&p!=null,P=f&&(rr(l)||y);if(y&&!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.
52
+ `),{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.
53
+ `),{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.
54
+ `),{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 W=r.onLockConflict??t.rootGlobal.on_lock_conflict??"readonly",$=await rs({tmsBaseUrl:s.tmsBaseUrl,testId:h,fromCommitId:C,newCommitId:_,basicAuth:c,onLockConflict:W});if($==="ok")L=!0,ft({baseUrl:Ke(s.tmsBaseUrl),testId:h,auth:qe(c),lifecycle:o});else{if($==="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 rs(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 mt(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}
55
+ `),"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)
56
+ `),"abort";if(e.onLockConflict==="wait"){if(n.reason==="base_mismatch")return process.stderr.write(`[lock] base commit mismatch \u2014 pull latest; aborting
57
+ `),"abort";for(;;){process.stderr.write(`[lock] waiting (concurrent session)...
58
+ `),await new Promise(i=>setTimeout(i,3e4));let l=await mt(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
59
+ `),"abort"}}return process.stderr.write(`[lock] ${a} \u2014 running in readonly mode (no commit)
60
+ `),"readonly"}async function bn(e,t,r,s,n,o,a,l,i,d,p,h){let{decisions:C,testId:y,testcaseId:I,fromCommitId:R,newCommitId:c}=t;if(!(n==="passed")&&h&&y&&R&&c){process.stderr.write(`[lock] run failed (${n}); discarding new commit
61
+ `),await yn(p,y,R,c),ht();return}ht()}async function yn(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 gr({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}
62
+ `)}async function vn(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 d=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),d.kind==="author"&&e.onAnyAuthorStep(),await e.pushStepLevelDelta(p.config.variables,p.objective);let y=d.kind==="replay"?e.buildReplayConfig(h):e.buildStepConfigAt(h,C),I=d.kind==="replay"?"md5-match":d.reason,R=p.config??{},c={};for(let[x,f]of Object.entries(R))f!=null&&x!=="variables"&&(c[x]=f);return{config:y,banner:{stepLabel:`Step ${h+1}/${e.decisions.length}`,objective:hn(p.objective,100)},mode:d.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{Ir as a,_r as b,$e as c,uo as d,Pr as e,Cr as f,wr as g,gt as h,Ar as i,Tr as j,Lr as k,Nr as l,Mr as m,Br as n,yt as o,Wr as p,Jr as q,Yr as r,It as s,Ci as t,la as u,pn as v,ge as w,fn as x,ts as y};
@@ -0,0 +1,6 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as z}from"./chunk-PN7LNQ7G.js";import{a as R}from"./chunk-SJ7VGRQU.js";import{a as q}from"./chunk-NLCCBXXV.js";function O(e){return["completed","failed","ended","stopped"].includes(e.trim().toLowerCase())}function ue(e){return["ended","stopped"].includes(e.trim().toLowerCase())}function D(e){return{requestId:e.requestId,objective:e.objective,status:"",turnActive:!1,scenarios:[],thinking:"",thinkingLog:[],chatLog:[],progress:0}}function de(e){return e.pendingClarification===void 0?e:{...e,pendingClarification:void 0}}function le(e){return{...e,turnActive:!0,error:void 0,thinking:"",thinkingLog:[]}}function A(e,t){switch(t.type){case"thinking":return{...e,status:"thinking",thinking:e.thinking+t.delta};case"thinking_done":return{...e,thinkingLog:[...e.thinkingLog,{text:e.thinking,tookMs:t.tookMs}],thinking:""};case"progress":return{...e,progress:t.pct};case"snapshot":return{...e,scenarios:t.data.scenarios,status:t.data.status,headline:t.data.headline??e.headline};case"chat":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}]};case"clarification":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}],pendingClarification:t.text};case"limit":return{...e,limits:{scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit}};case"error":return{...e,error:t.message};case"done":return{...e,status:t.status,turnActive:!1,error:t.status==="failed"&&!e.error?"generation failed":e.error}}}function N(e,t){let n=[],i=e.type??"",p=e.status??"";if(i==="ping")return n;switch(i){case"thinking_token":typeof e.data=="string"&&n.push({type:"thinking",delta:e.data});break;case"thinking_stopped":{let s=e.data??{},u=Q(s.time_taken);n.push({type:"thinking_done",text:typeof e.data=="string"?e.data:s.message??"",tookMs:u});break}case"progress":{let s=e.data??{};typeof s.progress=="number"&&n.push({type:"progress",pct:s.progress});break}case"clarification":{let s=e.data??{};typeof s.message=="string"&&n.push({type:"clarification",text:s.message});break}case"chatting_stopped":{let s=e.data??{};typeof s.message=="string"&&s.message.length>0&&n.push({type:"chat",text:s.message});break}case"limit_update":{let s=e.data??{},u=s.test_cases_limit??e.test_cases_limit,f=s.per_scenario_test_cases_limit??e.per_scenario_test_cases_limit;n.push({type:"limit",scenarioLimit:u,perScenarioLimit:f});break}case"error":{let s=typeof e.data=="string"?e.data:e.data?.message??"generation error";n.push({type:"error",message:s});break}case"request_cancelled":return n.push({type:"done",status:"stopped"}),n;case"session_ended":return n.push({type:"done",status:"ended"}),n;default:break}if(Array.isArray(e.scenarios)&&n.push({type:"snapshot",data:{requestId:t,status:p,headline:e.headline,scenarios:e.scenarios}}),p&&O(p)){let s=p.trim().toLowerCase();n.push({type:"done",status:s})}return n}function Q(e){if(!e)return;let t=/^([\d.]+)(ms|s)?$/.exec(e.trim());if(!t)return;let n=Number(t[1]);if(Number.isFinite(n))return t[2]==="ms"?Math.round(n):Math.round(n*1e3)}var E=class extends Error{constructor(t){super(t),this.name="AuthError"}},M=class extends Error{constructor(t){super(t),this.name="ForbiddenError"}},F=class extends Error{constructor(t){super(t),this.name="InsufficientCreditsError"}},k=class extends Error{constructor(n,i){super(n);this.cause=i;this.name="TransportError"}};function v(e,t){let n=t?.message??t?.error??`HTTP ${e}`;return e===401?new E(n):e===403?t?.key==="insufficient_credits"?new F(n):new M(n):new k(n)}async function*H(e){let t=e.fetchImpl??fetch,n=e.maxRetries??5,i=e.maxBackoffMs??3e4,p=e.connectTimeoutMs??1e4,s=0,u=!1;for(;;){if(e.signal.aborted)return;let f=new AbortController,d=()=>f.abort();e.signal.addEventListener("abort",d,{once:!0});let g=setTimeout(()=>f.abort(),p),b;try{b=await t(e.url,{method:"GET",headers:{Authorization:await e.authHeader(),Accept:"text/event-stream"},signal:f.signal})}catch(m){if(clearTimeout(g),e.signal.removeEventListener("abort",d),e.signal.aborted)return;if(++s>n)throw new k("SSE connect failed",m);await B(I(s,i));continue}if(clearTimeout(g),!b.ok){e.signal.removeEventListener("abort",d);let m=await Y(b);if(b.status===401&&u){if(++s>n)throw v(401,m);await B(I(s,i));continue}throw v(b.status,m)}if(!b.body)throw e.signal.removeEventListener("abort",d),new k("SSE response had no body");u=!0,s=0;let w=b.body.getReader(),h=new TextDecoder("utf-8"),y="";try{for(;;){if(e.signal.aborted){await w.cancel().catch(()=>{});return}let{done:m,value:r}=await w.read();if(m)break;y+=h.decode(r,{stream:!0});let a;for(;(a=y.indexOf(`
3
+
4
+ `))>=0;){let o=y.slice(0,a);y=y.slice(a+2);let c=V(o);c&&(yield c)}}}catch(m){if(e.signal.aborted)return;if(++s>n)throw new k("SSE stream dropped",m);await B(I(s,i));continue}finally{e.signal.removeEventListener("abort",d)}return}}function V(e){let t="message",n="";for(let i of e.split(`
5
+ `))i.startsWith("event:")?t=i.slice(6).trim():i.startsWith("data:")&&(n+=i.slice(5).trim());if(t!=="message"||!n)return null;try{let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}catch{return null}}function I(e,t){return Math.min(t,1e3*2**(e-1))}function B(e){return new Promise(t=>setTimeout(t,e))}async function Y(e){try{return await e.clone().json()}catch{return}}function ke(e,t={}){let n=t.fetchImpl??fetch,i=new Map,p=!0;async function s(){let r=await e.authResolver.resolve();if(!r)throw new E("unauthorized; run `kane-cli login`");return q(r.username,r.access_key)}function u(r){return`${e.baseUrl}${r}`}async function f(r){if(!r.ok){let a;try{a=await r.clone().json()}catch{a=void 0}throw v(r.status,a)}return r.json()}function d(r){let a=r?.data??r;return{request_id:a.request_id??a.id,status:a.status??""}}function g(r,a,o,c){let l=D({requestId:r,objective:a});c&&(l=A(l,{type:"snapshot",data:c}),c.status==="cleaned_up"&&(l={...l,error:"session was reaped (cleaned_up) \u2014 continuing will destructively regenerate"}));let S=new AbortController;o&&(o.aborted?S.abort():o.addEventListener("abort",()=>S.abort(),{once:!0})),i.set(r,S);let x={requestId:r,state:l,events:void 0};return x.events=(async function*(){try{let C=H({url:u(`/requests/${r}/sse`),authHeader:s,signal:S.signal,log:e.log,fetchImpl:n});for await(let L of C)for(let $ of N(L,r))x.state=A(x.state,$),yield $}finally{i.delete(r)}})(),x}async function b(r,a){let o=new FormData;o.append("prompt",r.prompt),p=r.memoryEnhancement??!0,o.append("memory_enhancement",String(p)),r.scenarioLimit!==void 0&&o.append("test_scenario_limit",String(r.scenarioLimit)),r.perScenarioLimit!==void 0&&o.append("per_scenario_test_cases_limit",String(r.perScenarioLimit));let c=r.projectId??e.projectId,l=r.folderId??e.folderId;c&&o.append("project_id",c),l&&o.append("folder_id",l);let S=await n(u("/requests"),{method:"POST",headers:{Authorization:await s()},body:o}),x=await f(S),{request_id:C}=d(x),L=String(C);return g(L,r.prompt,a)}async function w(r,a){let o=await n(u(`/requests/${r}`),{method:"GET",headers:{Authorization:await s()}}),c=await f(o),l=c?.data??c,S={requestId:r,status:l.status??"",headline:l.headline,scenarios:Array.isArray(l.scenarios)?l.scenarios:[]};return g(r,"",a,S)}async function h(r,a,o){let c=new FormData;c.append("prompt",a),c.append("chat_enabled","true"),c.append("memory_enhancement",String(p)),o&&c.append("mappings",JSON.stringify(o));let l=await n(u(`/requests/${r}`),{method:"PUT",headers:{Authorization:await s()},body:c});if(!l.ok){let S;try{S=await l.clone().json()}catch{}throw v(l.status,S)}}async function y(r){i.get(r)?.abort();let o=await n(u(`/requests/${r}/stop`),{method:"DELETE",headers:{Authorization:await s()}});if(!o.ok&&o.status!==404){let c;try{c=await o.clone().json()}catch{}throw v(o.status,c)}}async function m(r){i.get(r)?.abort();let o=await n(u(`/requests/${r}/end`),{method:"DELETE",headers:{Authorization:await s()}});if(!o.ok&&o.status!==404){let c;try{c=await o.clone().json()}catch{}throw v(o.status,c)}}return{start:b,attach:w,chat:h,cancel:y,end:m}}function j(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(n==null||typeof n!="object")return[];let i=n;if(typeof i.step!="string")return[];let p=typeof i.expected_result=="string"?i.expected_result:typeof i.outcome=="string"?i.outcome:"";t.push({step:i.step,expected:p})}return t}var ee=30,te=300;function J(){return{mode:"testing",max_steps:ee,timeout:te,variables:{}}}function U(e){return e.title??`Test case ${e.id}`}function Ce(e,t){return R({frontmatter:J(),heading:U(t),steps:e.sub_objectives.map(n=>n.objective)})}function G(e){let t=j(e.manual_steps).map(n=>n.step);return R({frontmatter:J(),heading:U(e),steps:t})}import{mkdtempSync as ne,mkdirSync as P,writeFileSync as W,rmSync as X,renameSync as re,existsSync as Z,readFileSync as se}from"fs";import{join as _,resolve as ie}from"path";async function Fe(e,t,n,i=G){(n.redirectBareCwd??!0)&&ie(t)===process.cwd()&&(t=_(t,".testmuai","tests"));let p=T(e.objective)??e.headline,s=T(n.suiteName)??`${T(K(p,4))??"tcg"}-${e.requestId}`,u=s,f=_(t,s);Z(f)&&!ae(f,e.requestId)&&(u=`${s}-${e.requestId}`);let d=_(t,u),g=[],b=new Map;for(let h of e.scenarios){let y=(h.test_cases??[]).filter(oe);if(y.length===0)continue;let m=T(ce(h.scode))??T(h.sid)??`s${h.id}`,r=b.get(m)??new Set;b.set(m,r);for(let a of y){let o=T(K(a.title,5))??"case",c=`${o}_test.md`;for(let l=2;r.has(c);l++)c=`${o}-${l}_test.md`;r.add(c),g.push({dir:m,file:c,tc:a})}}if(g.length===0)return{suiteDir:d,paths:[],warning:"no functional test cases generated"};P(t,{recursive:!0});let w=ne(_(t,".tcg-tmp-"));try{P(_(w,"helpers"),{recursive:!0}),W(_(w,".tcg-suite.json"),JSON.stringify({requestId:e.requestId,suiteName:u}));let h=[],y=new Set;for(let r of g){let a=_(w,r.dir);y.has(a)||(P(a,{recursive:!0}),y.add(a));let o=_(a,r.file);W(o,i(r.tc)),h.push(o)}Z(d)&&X(d,{recursive:!0,force:!0}),re(w,d);let m=h.map(r=>r.replace(w,d));return{suiteDir:d,paths:m}}catch(h){try{X(w,{recursive:!0,force:!0})}catch{}throw h}}function oe(e){return(e.category??"").trim().toLowerCase()==="functional"}function ae(e,t){try{return JSON.parse(se(_(e,".tcg-suite.json"),"utf-8"))?.requestId===t}catch{return!1}}function T(e){return e&&e.length>0?e:void 0}function K(e,t){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).slice(0,t).join("-"):""}function ce(e){return e?e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,""):""}function Pe(e){let t=[];e.title&&t.push(e.title),e.description&&t.push("",e.description);let n=j(e.manual_steps);return n.length>0&&(t.push("","Steps:"),n.forEach((i,p)=>{t.push(`${p+1}. ${i.step}`)})),t.join(`
6
+ `).trim()}function ze(e){return{mode:"bifurcate",objective:e.objective,model:e.model,session_id:e.sessionId,run_index:0,width:0,height:0,stream:!0,variables:e.variables,...e.auth}}async function Oe(e,t,n){let i=z(e,t),p=()=>i.cancel();n?.addEventListener("abort",p);let s=null,u=null;try{for await(let f of i.events)if(f.type==="bifurcation_result"){let d=f,g=d.sub_objectives??[];s={sub_objectives:g,extracted_variables:d.extracted_variables??{},total_flows:d.total_flows??g.length,is_single_flow:d.is_single_flow??g.length<=1,credits_consumed:d.credits_consumed??0}}else f.type==="error"&&(u=f.message??"bifurcation error")}finally{n?.removeEventListener("abort",p),i.cancel()}if(s)return s;throw new Error(u??"bifurcation produced no result")}export{O as a,ue as b,D as c,de as d,le as e,A as f,E as g,ke as h,j as i,Ce as j,G as k,Fe as l,oe as m,Pe as n,ze as o,Oe as p};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as m}from"./chunk-AT2Y5UNP.js";import{a as p}from"./chunk-HCBYKLMW.js";import{t}from"./chunk-3Z4EHIOW.js";import{a,b as r,i as u}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as n}from"./chunk-UR6MHSHU.js";var c=n(b(),1);var e=n(p(),1);function R({onSubmit:l}){let[o,f]=(0,c.useState)(0),s=(0,c.useRef)(!1);return u((x,i)=>{s.current||(i.leftArrow||i.rightArrow?f(d=>d===0?1:0):i.return?(s.current=!0,l(o===0?"positive":"negative")):i.escape&&(s.current=!0,l(null)))}),(0,e.jsxs)(a,{flexDirection:"column",marginTop:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(r,{color:t.secondary,children:"Rate this session: "}),(0,e.jsx)(r,{color:o===0?t.orange:t.dim,children:o===0?"[ \u{1F44D} ]":" \u{1F44D} "}),(0,e.jsx)(r,{children:" "}),(0,e.jsx)(r,{color:o===1?t.orange:t.dim,children:o===1?"[ \u{1F44E} ]":" \u{1F44E} "})]}),(0,e.jsx)(m,{bindings:[{keys:"\u2190/\u2192",label:"select"},{keys:"\u21B5",label:"submit"}],escBackLabel:"skip"})]})}export{R as a};
@@ -0,0 +1,11 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{c as O,h as F}from"./chunk-AH4AXJML.js";import{a as k}from"./chunk-L5LI2JF4.js";import{readFileSync as se,existsSync as ne}from"fs";import{basename as C,dirname as oe,isAbsolute as re,resolve as L}from"path";var u=class extends Error{constructor(s,o,n){super(`[${o}${n!=null?`:${n}`:""}] ${s}`);this.file=o;this.line=n;this.name="TestMdParseError"}},U=new Set(["username","access_key","oauth","profile","project_id","folder_id"]),D=new Set(["mode","max_steps","timeout","global_context","local_context","variables","session_context","code_export","code_language","target","chrome_profile","cdp_endpoint","ws_endpoint","headless","on_lock_conflict"]),$=new Set(["optional"]),V=new Set(["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"]),Q=new Set(["mode","on_lock_conflict"]);function R(e,t){let s=t.split(`
3
+ `),{global:o,bodyStartLine:n}=X(e,s),{title:r,steps:i}=Z(e,s,n);return{path:e,title:r,global:o,steps:i}}function X(e,t){if(t[0]?.trim()!=="---")return{global:{},bodyStartLine:0};let s=-1;for(let r=1;r<t.length;r++)if(t[r].trim()==="---"){s=r;break}if(s===-1)throw new u("frontmatter is missing closing '---'",e,1);let o=t.slice(1,s).join(`
4
+ `),n;try{n=k(o)??{}}catch(r){throw new u(`invalid YAML in frontmatter: ${r.message}`,e,1)}if(M(e,n,"frontmatter",1),n.on_lock_conflict!==void 0){let r=n.on_lock_conflict;if(r!=="readonly"&&r!=="fail"&&r!=="wait")throw new u(`on_lock_conflict must be 'readonly' | 'fail' | 'wait', got: ${JSON.stringify(r)}`,e,1)}return E(e,n,1),{global:n,bodyStartLine:s+1}}function Z(e,t,s){let o,n=s;for(;n<t.length&&t[n].trim()==="";)n++;let r=n<t.length?/^#\s+(.+?)\s*$/.exec(t[n]):null;r&&(o=r[1],n++);let i=[];for(let d=n;d<t.length;d++)/^##\s/.test(t[d])&&i.push(d);let a=[];for(let d=0;d<i.length;d++){let c=i[d],p=i[d+1]??t.length,m=t[c].replace(/^##\s+/,"").trim(),g=t.slice(c+1,p),{config:l,body:f,optional:h}=ee(e,c+1,g);a.push({index:d+1,heading:m,config:l,body:f,headingLine:c+1,optional:h})}return{title:o,steps:a}}function ee(e,t,s){let o=0;for(;o<s.length&&s[o].trim()==="";)o++;let n,r=t;if(o<s.length&&/^```yaml\s*$/.test(s[o])){let l=o;r=t+l,o++;let f=-1;for(;o<s.length;){if(/^```\s*$/.test(s[o])){f=o;break}o++}if(f===-1)throw new u("step-config fenced ```yaml block is not closed",e,r);let h=s.slice(l+1,f).join(`
5
+ `);try{n=k(h)??{}}catch(I){throw new u(`invalid YAML in step config: ${I.message}`,e,r)}o=f+1}let i=te(s.slice(o)),a=i.filter(l=>l.trim()!=="");if(a.length>0&&/^@session\s+/.test(a[0].trim()))throw new u("@session is no longer supported (iteration 3); use @import instead",e,t);let d=/^@import\s+(\S.*)$/,p=i.filter(l=>d.test(l.trim())).length>0;if(p&&a.length!==1)throw new u("step body must be exactly one of prose / @import",e,t);let m=!1,g;if(n){if(M(e,n,p?"step config (ref)":"step config (objective)",r),p||E(e,n,r),typeof n.optional=="boolean")m=n.optional;else if(n.optional!==void 0)throw new u(`step config 'optional' must be boolean: got ${typeof n.optional}`,e,r);let l={...n};delete l.optional,Object.keys(l).length>0&&(g=l)}return p?{body:{kind:"import_ref",path:d.exec(a[0].trim())[1].trim()},optional:m}:{body:{kind:"objective",text:i.join(`
6
+ `).trim()},config:g,optional:m}}function te(e){let t=0,s=e.length;for(;t<s&&e[t].trim()==="";)t++;for(;s>t&&e[s-1].trim()==="";)s--;return e.slice(t,s)}function E(e,t,s){let o=t.variables;if(o==null)return;if(typeof o!="object"||Array.isArray(o))throw new u("variables must be an object map",e,s);let n={};for(let[r,i]of Object.entries(o))if(typeof i=="string")n[r]={value:i};else if(i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.value=="string")n[r]=i;else throw new u(`variable '${r}' must be a string or { value: ... } object`,e,s);t.variables=n}function M(e,t,s,o){for(let n of Object.keys(t)){if(U.has(n))throw new u(`auth/identity keys are CLI-only: ${n}`,e,o);if(s==="frontmatter"){if($.has(n))throw new u(`step-only key in frontmatter: ${n}`,e,o);if(!D.has(n))throw new u(`unknown config key: ${n}`,e,o)}else if(s==="step config (objective)"){if(!D.has(n)&&!$.has(n))throw new u(`unknown config key: ${n}`,e,o);if(V.has(n))throw new u(`chrome config is global-only: ${n}`,e,o);if(Q.has(n))throw new u(`'${n}' is run-level and cannot be set per-step`,e,o)}else if(!$.has(n))throw new u(`step config on @import may only contain 'optional': got ${n}`,e,o)}}var T=["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"],b=class extends Error{constructor(t){super(t),this.name="TestMdResolveError"}};function Be(e){let t=L(e),s=A(t),o=ie(s.global),n=[];return B(s,[],n,[],t),n.forEach((i,a)=>i.flatIndex=a+1),{rootPath:t,rootTitle:s.title,rootGlobal:s.global,rootSteps:s.steps,chrome:o,steps:n}}function A(e){if(!ne(e))throw new b(`@import path not found: ${e}`);let t=se(e,"utf8");return R(e,t)}function B(e,t,s,o,n){if(t.includes(e.path)){let i=[...t,e.path].map(a=>C(a)).join(" \u2192 ");throw new b(`cyclic reference: ${i}`)}t.push(e.path);let r=o.length===0;for(let i of e.steps){let a=i.body.kind!=="objective";if(i.optional&&a&&!r)throw new b(`intermediate-ref 'optional' is not supported in v1: ${e.path}:${i.headingLine}`);let d={file:e.path,stepIndex:i.index,heading:i.heading,optional:i.optional??!1};if(i.body.kind==="objective"){let g=ae(e.global,i.config);s.push({flatIndex:0,objective:i.body.text,sourceFile:e.path,trace:[...o,d],config:g,parsedConfig:i.config,optional:i.optional??!1});continue}let c=oe(e.path),p=re(i.body.path)?i.body.path:L(c,i.body.path);if(C(p).endsWith("_test.md"))throw new b(`cannot @import a test file: only helpers may be imported (got ${p})`);let m=A(p);B(m,t,s,[...o,d],n)}t.pop()}function ie(e){let t={};for(let s of T)e[s]!==void 0&&(t[s]=e[s]);return t}function ae(e,t){let s={};for(let[o,n]of Object.entries(e))T.includes(o)||(s[o]=n);return{...s,...t??{}}}import{mkdirSync as _,writeFileSync as Ee}from"fs";import{join as S}from"path";import{createHash as le}from"crypto";function j(e){if(e==null)return null;if(Array.isArray(e))return e.map(j);if(typeof e=="object"){let t={};for(let s of Object.keys(e).sort()){let o=e[s];o!==void 0&&(t[s]=j(o))}return t}return e}function de(e){if(e.body.kind!=="objective")throw new Error("stepMd5: only objective steps have an md5; @import rows do not");let t={...e.config??{},optional:e.optional??!1},s=JSON.stringify(j(t));return le("md5").update(e.body.text).update(`
7
+ `).update(s).digest("hex")}function x(e){return de({index:e.trace[e.trace.length-1].stepIndex,heading:e.trace[e.trace.length-1].heading,body:{kind:"objective",text:e.objective},config:e.parsedConfig,headingLine:1,optional:e.optional})}import{writeFileSync as pe,mkdirSync as ce,readFileSync as fe}from"fs";import{dirname as ue,basename as K}from"path";function w(e){let t=e.outPath??O(e.sourcePath);ce(ue(t),{recursive:!0});let s=[];s.push("---"),s.push(`test: ../${K(e.sourcePath)}`),s.push(`status: ${e.overallStatus}`),s.push(`started: ${e.startedISO}`),s.push(`duration_s: ${e.durationS}`),s.push(`session_id: ${e.sessionId}`),s.push("---",""),s.push(`# ${e.title??K(e.sourcePath)} \u2014 Result`,"");for(let o=0;o<e.rootSteps.length;o++){let n=e.rootSteps[o],r=e.outcomes.find(i=>i.rootStepIndex===o+1);if(s.push(ge(n,r)),n.body.kind==="objective"&&r?.stepMd5&&s.push(`md5: ${r.stepMd5}`),r?.status==="failed"&&r.reason&&s.push(`Reason: ${r.reason}`),r?.softFailures?.length)for(let i of r.softFailures){let a=i.reason?`: ${i.reason}`:"";s.push(`\u26A0 optional sub-step ${i.subStepIndex} failed${a}`)}n.body.kind==="objective"&&r?.status!=="skipped"&&s.push(n.body.text),s.push("")}return pe(t,s.join(`
8
+ `),"utf8"),t}function ge(e,t){if(!t)return`## ${e.heading} (no outcome)`;let s=t.duration_s!=null?`${t.duration_s}s`:"\u2014";if(t.status==="skipped")return`## ${e.heading} \u23ED skipped`;let o=t.softFailed?" (optional)":"";if(t.refKind&&t.status==="passed"){let n=t.helperResultRelPath?` \u2192 ${t.helperResultRelPath}`:"";return`## ${e.heading} \u2713 passed (via @${t.refKind} ${t.refLabel} \u2014 ${t.inlinedCount} inlined steps, ${s}${n})`}if(t.refKind&&t.status==="failed"){let n=t.failedSubStepIndex&&t.failedSubStepIndex.length>0?` \u2014 at sub-step ${t.failedSubStepIndex.join(" \u2192 sub-step ")}`:"",r=t.helperResultRelPath?` \u2192 ${t.helperResultRelPath}`:"";return`## ${e.heading} \u2717 failed${o} (via @${t.refKind} ${t.refLabel}${n}, ${s}${r})`}return t.status==="passed"?`## ${e.heading} \u2713 passed (${s})`:`## ${e.heading} \u2717 failed${o} (${s})`}var me=/^##\s+(.+?)\s+(✓ passed|✗ failed(?:\s+\(optional\))?|⏭ skipped)(?:\s+\((.*)\))?\s*$/,he=/via\s+@\w+\s+(\S+).*?(?:→\s+(\S+))?\s*$/,Se=/^md5:\s+([a-f0-9]{32})\s*$/;function Je(e){let s=fe(e,"utf8").split(`
9
+ `),o="passed";if(s[0]?.trim()==="---")for(let r=1;r<s.length&&s[r].trim()!=="---";r++){let i=/^status:\s+(passed|failed|interrupted)\s*$/.exec(s[r]);i&&(o=i[1])}let n=[];for(let r=0;r<s.length;r++){let i=me.exec(s[r]);if(!i)continue;let a=i[1],d=i[2],c=i[3]??"",p=d.startsWith("\u2713")?"passed":d.startsWith("\u23ED")?"skipped":"failed";if(/via\s+@/.test(c)){let g=he.exec(c),l=g?.[1]??"",f=g?.[2]??null;n.push({kind:"import",heading:a,status:p,md5:null,importPath:l,helperResultRelPath:f})}else{let g=null;for(let l=r+1;l<s.length&&!/^##\s/.test(s[l]);l++){if(s[l].trim()==="")continue;let f=Se.exec(s[l]);if(f){g=f[1];break}break}n.push({kind:"objective",heading:a,status:p,md5:g})}}return{overallStatus:o,steps:n}}import{copyFileSync as be,existsSync as ye,mkdirSync as ve,writeFileSync as Re}from"fs";import{join as y}from"path";function H(e){for(let t=0;t<e.totalRunDirs;t++){let s=e.runIndex+t,o=y(e.sessionDir,"runs",String(s)),n=y(e.stagingStepDir,"flows",String(t));ve(n,{recursive:!0});let r=[y(o,"run-test","actions.ndjson"),y(o,"actions.ndjson")],i=y(n,"actions.ndjson"),a=!1;for(let d of r)if(ye(d)){be(d,i),a=!0;break}a||Re(i,"")}}import{basename as xe,dirname as we,join as Ie}from"path";function G(e){let t=xe(e);return t.endsWith("_test.md")?t.slice(0,-8):t.endsWith(".md")?t.slice(0,-3):t}function ke(e){if(e.length<2)throw new Error("helperOutputDirName requires trace length >= 2 (root + at least one helper)");let t=G(e[0].file),s=G(e[e.length-1].file),o=e.slice(0,-1).map(n=>String(n.stepIndex));return`helper-output-${s}-${t}-${o.join("-")}`}function v(e){if(e.length<2)throw new Error("helperOutputDirPath requires trace length >= 2");let t=e[e.length-1].file;return Ie(we(t),ke(e))}import{existsSync as N,mkdirSync as $e,rmSync as je,cpSync as _e}from"fs";function W(e,t){N(e)&&(N(t)&&je(t,{recursive:!0,force:!0}),$e(t,{recursive:!0}),_e(e,t,{recursive:!0}))}import{readFileSync as Pe}from"fs";import{join as Oe,relative as Fe}from"path";function J(e){let t=De(e.resolvedTest,e.runByStep),s=new Map;for(let o of t.values()){let n=s.get(o.helperFile);n||(n=R(o.helperFile,Pe(o.helperFile,"utf8")),s.set(o.helperFile,n));let r=[],i=!1;for(let d of n.steps){let c=d.index,p=o.resolvedSteps.filter(l=>l.trace[o.helperDepth].stepIndex===c);if(p.length===0){r.push({rootStepIndex:c,status:"skipped"});continue}let m=p[0].trace[0].stepIndex,g=e.outcomes.find(l=>l.rootStepIndex===m);if(!g){r.push({rootStepIndex:c,status:"skipped"});continue}if(d.body.kind==="objective"){let l=p[0],f=Y(l,g);f==="failed"&&(i=!0);let h={rootStepIndex:c,status:f};f==="passed"&&(h.stepMd5=x(l)),r.push(h)}else{let l=!1,f=!1;for(let z of p){let P=Y(z,g);P!=="skipped"&&(f=!0),P==="failed"&&(l=!0)}let h=l?"failed":f?"passed":"skipped";h==="failed"&&(i=!0);let I=v(p[0].trace.slice(0,o.helperDepth+2)),q=Fe(o.finalDir,I);r.push({rootStepIndex:c,status:h,refKind:"import",refLabel:d.body.path,inlinedCount:p.length,helperResultRelPath:`${q}/Result.md`})}}let a=i?"failed":"passed";w({sourcePath:o.helperFile,title:n.title,rootSteps:n.steps,outcomes:r,overallStatus:a,startedISO:e.startedISO,durationS:0,sessionId:e.sessionId,outPath:Oe(o.stagingDir,"Result.md")})}}function De(e,t){let s=new Map;for(let o of e.steps)if(t.has(o.flatIndex))for(let n=1;n<o.trace.length;n++){let r=o.trace.slice(0,n+1),i=v(r),a=s.get(i);a||(a={stagingDir:`${i}.staging`,finalDir:i,helperFile:r[n].file,helperDepth:n,resolvedSteps:[]},s.set(i,a)),a.resolvedSteps.push(o)}return s}function Y(e,t){if(t.status==="passed")return"passed";if(t.status==="skipped")return"skipped";let s=e.trace.slice(1).map(r=>r.stepIndex),o=t.failedSubStepIndex??[],n=Math.min(s.length,o.length);for(let r=0;r<n;r++)if(s[r]!==o[r])return s[r]<o[r]?"passed":"skipped";return s.length===o.length?"failed":s.length<o.length?"passed":"skipped"}function St(e){let t=F(e.resolvedTest.rootPath);_(S(t,".internal"),{recursive:!0});let s=new Map;for(let n of e.stepRunRecords)s.set(n.testmdStepIndex,n);for(let n of e.resolvedTest.steps){let r=s.get(n.flatIndex);if(!r)continue;let i=n.trace[n.trace.length-1].stepIndex,a=x(n),d=a.slice(0,8),c;if(n.trace.length===1)c=S(t,".internal","steps",`${i}-${d}`);else{let p=`${v(n.trace)}.staging`;_(S(p,".internal"),{recursive:!0}),c=S(p,".internal","steps",`${i}-${d}`)}if(_(c,{recursive:!0}),H({sessionDir:e.sessionDir,runIndex:r.runIndex,totalRunDirs:r.totalRunDirs,stagingStepDir:c}),n.trace.length===1){let p=n.trace[0].stepIndex,m=e.outcomes.find(g=>g.rootStepIndex===p);m&&m.stepMd5==null&&(m.stepMd5=a)}}J({resolvedTest:e.resolvedTest,outcomes:e.outcomes,startedISO:e.startedISO,sessionId:e.sessionId,runByStep:s}),w({sourcePath:e.resolvedTest.rootPath,title:e.resolvedTest.rootTitle,rootSteps:e.resolvedTest.rootSteps,outcomes:e.outcomes,overallStatus:e.overallStatus,startedISO:e.startedISO,durationS:e.durationS,sessionId:e.sessionId,outPath:S(t,"Result.md")});let o={};if(e.commitId&&(o.commit_id=e.commitId),e.tmsIds.testId&&(o.test_id=e.tmsIds.testId),e.tmsIds.testcaseId&&(o.testcase_id=e.tmsIds.testcaseId),e.tmsIds.projectId&&(o.project_id=e.tmsIds.projectId),e.tmsIds.folderId&&(o.folder_id=e.tmsIds.folderId),e.tmsIds.orgId&&(o.org_id=e.tmsIds.orgId),e.tmsIds.sessionName&&(o.session_name=e.tmsIds.sessionName),Ee(S(t,".internal","meta.json"),JSON.stringify(o,null,2)+`
10
+ `,"utf8"),e.codeExportDir){let n=e.codeExportLanguage??"python",r=S(t,`playwright-${n}-code`);try{W(e.codeExportDir,r)}catch(i){process.stderr.write(`warn: codegen copy failed: ${i.message}
11
+ `)}}}export{Be as a,x as b,w as c,Je as d,v as e,W as f,St as g};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as b}from"./chunk-AT2Y5UNP.js";import{a as L}from"./chunk-HCBYKLMW.js";import{k as d,t as o}from"./chunk-3Z4EHIOW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as S}from"./chunk-5TOE4RHH.js";import{a as R}from"./chunk-HCBYKLMW.js";import{t as o}from"./chunk-3Z4EHIOW.js";import{a as x,b as c,j as y}from"./chunk-C44QQJR4.js";import{a as w}from"./chunk-6YGTRKDT.js";import{e as b}from"./chunk-UR6MHSHU.js";var T=b(w(),1);var i=b(R(),1);function L(e){let t=e.decisions.filter(l=>l.kind==="replay").length,r=e.decisions.filter(l=>l.kind==="author").length,d=e.outcomes.filter(l=>l.status==="passed").length,p=e.outcomes.filter(l=>l.status==="failed").length,f=e.outcomes.filter(l=>l.status==="skipped").length,a=o.green,n;e.cancelled||e.overallStatus==="interrupted"?(a=o.orange,n="CANCELLED"):e.overallStatus==="failed"?(a=o.red,n="FAILED"):n="PASSED";let s=`${n} \xB7 ${e.durationS}s \xB7 ${e.outcomes.length} steps (${d} passed, ${p} failed, ${f} skipped)`,k=`${t} replay \xB7 ${r} author`,C=e.retryTriggered,_="yes \u2014 run recovered after a replay miss",u,g=o.dim;if(e.cancelled)u="\u2013 not committed (cancellation)";else if(e.overallStatus==="failed")u="\u2013 not committed (run failed)",g=o.red;else if(!e.shouldCommit)e.isFirstRun?u="\u2013 not committed (first run skipped commit)":e.lockHeld?u="\u2013 not committed":u="\u2013 not committed (readonly fallback / no lock)";else{let l=e.uploadResult?.testcaseId;u=l?`\u2713 pushed (testcase=${l})`:"\u2713 pushed",g=o.green}let v=e.shouldReplaceLocalOutput?"output dir replaced":e.anyAuthorStepRan?"untouched (cancellation or no replace)":"untouched (replay-only)",m,h=o.dim;return e.shouldUploadArtifacts?e.uploadResult?.success?(m="\u2713 TMS",h=o.green):e.uploadResult?(m=`\u2717 failed${e.uploadResult.error?`: ${e.uploadResult.error}`:""}`,h=o.red):m="\u2013 not run":m="\u2013 skipped (--local or no auth)",{resultLine:{color:a,text:s},breakdown:k,showRetries:C,retriesText:_,commitText:u,commitColor:g,artifactsText:v,uploadText:m,uploadColor:h}}function O(e){let t=e.decisions.filter(s=>s.kind==="replay").length,r=e.decisions.filter(s=>s.kind==="author").length,d=e.outcomes.filter(s=>s.status==="passed").length,p=e.outcomes.filter(s=>s.status==="failed").length,f=e.outcomes.filter(s=>s.status==="skipped").length,a,n=!1;return e.cancelled?a="cancellation":e.overallStatus==="failed"?a="run_failed":e.shouldCommit&&e.uploadResult?.testcaseId?(a="ok",n=!0):!e.shouldCommit&&!e.lockHeld&&!e.isFirstRun?a="readonly_fallback":a="not_committed",{type:"test_md_summary",overall_status:e.overallStatus,duration_s:e.durationS,steps:{total:e.outcomes.length,passed:d,failed:p,skipped:f,replay_decisions:t,author_decisions:r},retries:{triggered:e.retryTriggered},commit:{committed:n,reason:a,...e.uploadResult?.testcaseId?{testcase_id:e.uploadResult.testcaseId}:{}},artifacts:{replaced:e.shouldReplaceLocalOutput},upload:{performed:e.shouldUploadArtifacts,...e.uploadResult?{succeeded:!!e.uploadResult.success}:{}},...e.shareUrl?{share_url:e.shareUrl}:{},cancelled:e.cancelled}}function A({data:e}){let t=L(e),r=[{label:"result",value:(0,i.jsx)(c,{color:t.resultLine.color,bold:!0,children:t.resultLine.text})},{label:"breakdown",value:(0,i.jsx)(c,{color:o.dim,children:t.breakdown})}];return t.showRetries&&r.push({label:"retries",value:(0,i.jsx)(c,{color:o.orange,children:t.retriesText})}),r.push({label:"commit",value:(0,i.jsx)(c,{color:t.commitColor,children:t.commitText})}),r.push({label:"artifacts",value:(0,i.jsx)(c,{color:o.dim,children:t.artifactsText})}),r.push({label:"upload",value:(0,i.jsx)(c,{color:t.uploadColor,children:t.uploadText})}),(0,i.jsx)(S,{title:"Run summary",titleColor:"#ff9500",rows:r})}function I({data:e}){let{exit:t}=y();return(0,T.useEffect)(()=>{let r=setTimeout(()=>t(),50);return()=>clearTimeout(r)},[t]),(0,i.jsx)(x,{flexDirection:"column",children:(0,i.jsx)(A,{data:e})})}export{L as a,O as b,A as c,I as d};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{s}from"./chunk-3Z4EHIOW.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost}}export{n as a};
@@ -0,0 +1,20 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as L,b as et}from"./chunk-L3RTVAPG.js";import{b as U,c as X}from"./chunk-3C7ATCDM.js";import{a as C,b as J,e as P,f as Q}from"./chunk-AH4AXJML.js";import{a as Z,b as tt}from"./chunk-MDBXYXSC.js";import{a as W}from"./chunk-UJZCMEEH.js";import{a as z}from"./chunk-TAEW7PXN.js";import{a as N}from"./chunk-7G7ZLAJH.js";import{a as G}from"./chunk-J37YPPCD.js";import{a as $}from"./chunk-HCBYKLMW.js";import{t as h}from"./chunk-3Z4EHIOW.js";import{a as k,b as g,i as K}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{a as I}from"./chunk-RZ4F3BHX.js";import{e as R}from"./chunk-UR6MHSHU.js";var M=R(B(),1);import{existsSync as D,readFileSync as jt,rmSync as dt,unlinkSync as Bt}from"fs";import{resolve as Y}from"path";import{promises as rt,realpathSync as _t}from"fs";import{homedir as xt}from"os";import{join as H,parse as wt,relative as nt,resolve as ot}from"path";var it=new Set(["node_modules",".git","dist","build",".next",".venv","venv","target","__pycache__"]),v=class extends Error{constructor(i){super(`refusing to scan '${i}'. Run from your project root, or pass --root <dir>.`);this.cwd=i;this.name="HomeRefusedError"}};function st(t){try{return _t(ot(t))}catch{return ot(t)}}function yt(t){let r=st(t),i=st(xt()),n=wt(r).root;if(process.platform==="win32"){let o=e=>e.toLowerCase();return o(r)===o(i)||o(r)===o(n)}return r===i||r===n}async function A(t){if(yt(t.root))throw new v(t.root);let r=t.maxEntries??5e4,i=t.maxResults??5e3,n=new Set(t.ignore??[]),o=[],e=0,s=0,c=!1,d,l=[t.root];for(;l.length>0&&!c;){let a=l.shift(),m;try{m=await rt.readdir(a,{withFileTypes:!0})}catch{continue}s++;for(let E of m){if(e++,e>r){c=!0,d="max_entries";break}let x=E.name,T=H(a,x);if(E.isDirectory()){if(it.has(x)||x.startsWith(".")||x.startsWith("output-")||n.has(x))continue;l.push(T)}else if(E.isFile()&&x.endsWith("_test.md")&&(o.push({path:T,relPath:nt(t.root,T),source:"cwd"}),o.length>=i)){c=!0,d="max_results";break}}t.onProgress?.(s,o.length)}if(!c){let m=[{dir:H(t.root,".testmuai","tests"),depth:0}];for(;m.length>0&&!c;){let{dir:E,depth:x}=m.shift(),T;try{T=await rt.readdir(E,{withFileTypes:!0})}catch{continue}s++;for(let f of T){if(e++,e>r){c=!0,d="max_entries";break}let w=f.name,y=H(E,w);if(f.isDirectory()){if(x>=20||w.startsWith(".")||w.startsWith("output-")||it.has(w))continue;m.push({dir:y,depth:x+1})}else if(f.isFile()&&w.endsWith("_test.md")&&(o.push({path:y,relPath:nt(t.root,y),source:"tests-dir"}),o.length>=i)){c=!0,d="max_results";break}}}}return{results:o,aborted:c,abortReason:d,dirsScanned:s}}import{mkdirSync as kt,writeFileSync as Et}from"fs";import{join as bt}from"path";function at(t,r){return`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}async function Tt(t){let r=Z({tmsBaseUrl:t.tmsBaseUrl,testcaseId:t.testcaseId,codeExport:{enabled:!0,language:t.language,skipValidation:t.skipValidation}}),i=await I(r.url,{method:"POST",headers:{"content-type":"application/json",authorization:at(t.auth.username,t.auth.access_key)},body:JSON.stringify(r.body)});if(!i.ok)throw new Error(`code-export trigger failed: ${i.status} ${await i.text()}`);t.log("info","CODE_EXPORT_TRIGGERED","Code export triggered",{testcase_id:t.testcaseId})}async function St(t){let r=tt({tmsBaseUrl:t.tmsBaseUrl,testcaseId:t.testcaseId}),i=t.pollIntervalMs??5e3,n=t.timeoutMs??3e5,o=Date.now()+n;for(;Date.now()<o;){let e=await I(r,{headers:{authorization:at(t.auth.username,t.auth.access_key),accept:"application/json"}});if(!e.ok){await new Promise(l=>setTimeout(l,i));continue}let c=(await e.json()).data?.find(l=>l.code_name==="kane-cli-trigger");if(!c){await new Promise(l=>setTimeout(l,i));continue}let d=(c.status??"").toLowerCase();if(d==="in progress"||d==="in_progress"||d==="pending"){await new Promise(l=>setTimeout(l,i));continue}if(!c.url||c.url.length===0)throw new Error(`code-export status=${c.status} but no files returned`);kt(t.outDir,{recursive:!0});for(let l of c.url){let a=bt(t.outDir,l.file_name),m=await I(l.file_url);if(!m.ok){t.log("warn","CODE_EXPORT_FILE_FAILED","Failed to download file",{file_name:l.file_name,status:m.status});continue}let E=await m.text();Et(a,E,"utf-8")}return t.log("info","CODE_EXPORT_DOWNLOADED","Code export saved",{out_dir:t.outDir,file_count:c.url.length}),t.outDir}throw new Error("code-export polling timed out")}async function ct(t){return await Tt(t),await St(t)}var b=R(B(),1);import{existsSync as Rt,readFileSync as vt}from"fs";var p=R($(),1);function Pt(t){L(t);let r=P(t);if(!Rt(r))return null;try{return JSON.parse(vt(r,"utf8"))}catch{return{}}}function Mt(t){return t===null?"never_run":t.testcase_id?"synced":"local_only"}function Dt(t){return t==="synced"?"\u2601":t==="local_only"?"\u25A3":"\u25CB"}function Ct(t){return t==="tests-dir"?"\u2726":" "}function Ot(t,r){return r==="all"?!0:r==="synced"?t.status==="synced":r==="local"?t.status==="local_only":r==="never_run"?t.status==="never_run":r==="cli"?t.source==="tests-dir":r==="hand"?t.source==="cwd":!0}var V=["all","synced","local","never_run","cli","hand"];function Ft(t){let r=V.indexOf(t);return V[(r+1)%V.length]}function lt({root:t,currentOrgId:r,onSelect:i,onCancel:n}){let[o,e]=(0,b.useState)([]),[s,c]=(0,b.useState)(null),[d,l]=(0,b.useState)(!0),[a,m]=(0,b.useState)("all");(0,b.useEffect)(()=>{(async()=>{try{let f=await A({root:t}),w=[];for(let y of f.results){let j=Pt(y.path);j?.org_id!==void 0&&j.org_id!==r||w.push({path:y.path,relPath:y.relPath,name:C(y.path),status:Mt(j),source:y.source})}e(w),l(!1)}catch(f){f instanceof v,c(f.message),l(!1)}})()},[t,r]);let E=(0,b.useMemo)(()=>o.filter(f=>Ot(f,a)).map(f=>({id:f.path,label:`${Dt(f.status)} ${Ct(f.source)} ${f.relPath}`})),[o,a]),x=(0,b.useMemo)(()=>It(a,o),[a,o]);if(s)return(0,p.jsxs)(k,{flexDirection:"column",borderStyle:"round",borderColor:h.red,paddingX:2,paddingY:1,children:[(0,p.jsx)(g,{color:h.red,bold:!0,children:"testmd"}),(0,p.jsx)(k,{marginTop:1,children:(0,p.jsx)(g,{color:h.red,children:s})})]});let T=a==="all"?"all":$t(a);return(0,p.jsx)(z,{title:`testmd \xB7 filter: ${T}`,items:E,loading:d,itemNoun:"tests",onSelect:f=>{let w=o.find(y=>y.path===f.id);w&&i(w)},onCancel:n,onTab:()=>m(f=>Ft(f)),extraHint:"cycle filter",footer:x})}function $t(t){return t==="synced"?"synced (\u2601)":t==="local"?"local (\u25A3)":t==="never_run"?"never run (\u25CB)":t==="cli"?"cli-generated (\u2726)":t==="hand"?"hand-written":"all"}function It(t,r){let i={synced:r.filter(o=>o.status==="synced").length,local:r.filter(o=>o.status==="local_only").length,never:r.filter(o=>o.status==="never_run").length,cli:r.filter(o=>o.source==="tests-dir").length,hand:r.filter(o=>o.source==="cwd").length},n=o=>o?h.orange:h.dim;return(0,p.jsxs)(k,{flexDirection:"column",children:[(0,p.jsx)(g,{color:h.dim,children:"legend:"}),(0,p.jsxs)(k,{children:[(0,p.jsx)(g,{color:n(t==="synced"),children:` \u2601 synced (${i.synced}) `}),(0,p.jsx)(g,{color:n(t==="local"),children:`\u25A3 local (${i.local}) `}),(0,p.jsx)(g,{color:n(t==="never_run"),children:`\u25CB never run (${i.never})`})]}),(0,p.jsxs)(k,{children:[(0,p.jsx)(g,{color:n(t==="cli"),children:` \u2726 cli-generated (${i.cli}) `}),(0,p.jsx)(g,{color:n(t==="hand"),children:` hand-written (${i.hand})`})]})]})}var O=R(B(),1);import{existsSync as Lt,readFileSync as At}from"fs";var u=R($(),1);function ut({path:t,relPath:r,onAction:i,onBack:n,onView:o}){let[e,s]=(0,O.useState)(null),[c,d]=(0,O.useState)(!1);(0,O.useEffect)(()=>{let a=P(t);if(Lt(a))try{s(JSON.parse(At(a,"utf8")))}catch{s(null)}},[t]),K((a,m)=>{if(m.escape){if(c){d(!1);return}n();return}if(c){a==="y"||a==="Y"?(d(!1),i("delete")):(a==="n"||a==="N")&&d(!1);return}a==="r"&&i("run"),a==="e"&&e?.testcase_id&&i("export"),a==="d"&&d(!0),a==="v"&&o&&o()});let l=({k:a,v:m})=>m?(0,u.jsxs)(g,{children:[(0,u.jsx)(g,{color:h.dim,children:a.padEnd(14)}),m]}):null;return(0,u.jsxs)(k,{flexDirection:"column",borderStyle:"round",borderColor:h.orange,paddingX:2,paddingY:1,children:[(0,u.jsx)(g,{color:h.orange,bold:!0,children:r}),(0,u.jsx)(k,{marginTop:1,flexDirection:"column",children:e?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsx)(l,{k:"test_id",v:e.test_id}),(0,u.jsx)(l,{k:"testcase_id",v:e.testcase_id}),(0,u.jsx)(l,{k:"project_id",v:e.project_id}),(0,u.jsx)(l,{k:"folder_id",v:e.folder_id}),(0,u.jsx)(l,{k:"org_id",v:e.org_id}),(0,u.jsx)(l,{k:"session_name",v:e.session_name}),(0,u.jsx)(l,{k:"commit_id",v:e.commit_id})]}):(0,u.jsx)(g,{color:h.dim,children:"(never run \u2014 no meta.json)"})}),c?(0,u.jsx)(k,{marginTop:1,children:(0,u.jsxs)(g,{color:h.red,bold:!0,children:["Delete ",r," and its output dir? [y/n]"]})}):(0,u.jsx)(k,{marginTop:1,children:(0,u.jsxs)(g,{color:h.dim,children:["[r] run [e] export",e?.testcase_id?"":" (need testcase_id)"," [d] delete",o?" [v] view":""," [Esc] back"]})})]})}function F(t){L(t);let r=P(t);if(!D(r))return null;try{return JSON.parse(jt(r,"utf8"))}catch{return null}}function ft(t,r){return!t||t.org_id===void 0?!0:t.org_id===r}function q(t,r){return ft(t,r)?null:(process.stderr.write(`error: this test belongs to org ${t.org_id}; you are logged in as org ${r}.
3
+ Switch profiles with \`kane-cli profiles switch\` to act on it.
4
+ `),2)}async function Me(t={}){let r=!!process.stdin.isTTY&&!t.json,i=new N,n=new W;await et({isInteractive:r,creds:i,config:n});let o=i.getDefaultEnv()??"prod";try{let e=await X({creds:i,env:o,log:()=>{}});return e.resolvedCreds?.org_id===void 0?(process.stderr.write("error: TMS did not return an org_id. Run `kane-cli login` again.\n"),{ok:!1,code:2}):{ok:!0,orgId:String(e.resolvedCreds.org_id)}}catch(e){if(e instanceof U)return process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),{ok:!1,code:2};throw e}}async function De(t,r){if(process.stdin.isTTY&&!t.json)return await Jt(r,t.root);let i=t.root??process.cwd(),n;try{n=await A({root:i,ignore:t.ignore})}catch(o){if(o instanceof v)return process.stderr.write(`error: ${o.message}
5
+ `),2;throw o}for(let o of n.results){let e=F(o.path);if(!ft(e,r))continue;let s={path:o.relPath.startsWith(".")?o.relPath:`./${o.relPath}`,name:C(o.path),has_meta:e!==null,source:o.source,synced:!!e?.testcase_id};e&&(e.test_id&&(s.test_id=e.test_id),e.testcase_id&&(s.testcase_id=e.testcase_id),e.org_id&&(s.org_id=e.org_id),e.project_id&&(s.project_id=e.project_id),e.folder_id&&(s.folder_id=e.folder_id)),process.stdout.write(JSON.stringify(s)+`
6
+ `)}return n.aborted&&process.stderr.write(`warn: walk aborted (${n.abortReason}). Pass --root or --ignore to narrow.
7
+ `),0}var mt=-1001,gt=-1002,pt=-1003,_={action:null,path:null};function Nt(t,r){return _.action=t,_.path=r,t==="run"?mt:t==="export"?gt:pt}function Wt({root:t,currentOrgId:r,onComplete:i}){let[n,o]=M.default.useState({kind:"list"});return M.default.useEffect(()=>{n.kind==="exiting"&&i(n.code)},[n,i]),n.kind==="list"?M.default.createElement(lt,{root:t,currentOrgId:r,onSelect:e=>o({kind:"inspect",path:e.path,relPath:e.relPath}),onCancel:()=>o({kind:"exiting",code:0})}):n.kind==="inspect"?M.default.createElement(ut,{path:n.path,relPath:n.relPath,onAction:async e=>{o({kind:"exiting",code:Nt(e,n.path)})},onBack:()=>o({kind:"list"})}):null}async function Jt(t,r){let i=r??process.cwd(),{render:n}=await import("./build-JIKYOZUH.js"),o=await new Promise(e=>{let{unmount:s,waitUntilExit:c}=n(M.default.createElement(Wt,{root:i,currentOrgId:t,onComplete:d=>{s(),e(d)}}),{stdout:process.stderr,exitOnCtrlC:!0});c().then(()=>e(0)).catch(()=>e(0))});if(o===mt&&_.path){let{runTestMdFile:e}=await import("./run-test-md-SXZUOYSG.js"),s=await e(_.path,{});return _.action=null,_.path=null,s}if(o===gt&&_.path){let e=await Xt(_.path,{},t);return _.action=null,_.path=null,e}if(o===pt&&_.path){let e=await Ut(_.path,!0,t);return _.action=null,_.path=null,e}return o}async function Ce(t,r){let i=Y(t);if(!D(i))return process.stderr.write(`error: file not found: ${i}
8
+ `),2;let n=F(i),o=q(n,r);if(o!==null)return o;let e={path:i,name:C(i),has_meta:n!==null};return n&&(n.commit_id&&(e.commit_id=n.commit_id),n.test_id&&(e.test_id=n.test_id),n.testcase_id&&(e.testcase_id=n.testcase_id),n.project_id&&(e.project_id=n.project_id),n.folder_id&&(e.folder_id=n.folder_id),n.org_id&&(e.org_id=n.org_id),n.session_name&&(e.session_name=n.session_name)),process.stdout.write(JSON.stringify(e)+`
9
+ `),0}async function Ut(t,r,i){let n=Y(t);if(!D(n))return process.stderr.write(`error: file not found: ${n}
10
+ `),2;let o=F(n),e=q(o,i);if(e!==null)return e;if(!r)return process.stderr.write(`error: refusing to delete without --yes.
11
+ This will remove '${n}' and '${J(n)}/'.
12
+ `),2;let s=J(n);if(D(s))try{dt(s,{recursive:!0,force:!0})}catch(c){return process.stderr.write(`error: failed to remove ${s}: ${c.message}
13
+ `),2}try{Bt(n)}catch(c){return process.stderr.write(`error: failed to remove ${n}: ${c.message}
14
+ `),2}return process.stderr.write(`removed ${n} and ${s}/
15
+ `),0}var S=class extends Error{kind;constructor(r,i){super(i),this.name="ExportError",this.kind=r}};async function Oe(t,r){let{codeDir:i}=await ht(t,r);return{codeDir:i}}async function ht(t,r){let i=F(t);if(!i?.testcase_id)throw new S("not-synced","this test has not been synced to TMS \u2014 run `kane-cli testmd run` first.");let n=new W().load(),o=r.language??n.code_export?.language;if(!o)throw new S("no-language","--language not provided and no default in tui-config.");let e=r.output??Q(t,"playwright",o),s=D(e);if(s&&!r.force){let a=!1;try{let{readdirSync:m}=await import("fs");a=m(e).length>0}catch{}if(a)return{kind:"reused",codeDir:e}}s&&r.force&&dt(e,{recursive:!0,force:!0});let c=new N,d=r.env??c.getDefaultEnv()??"prod",l;try{l=await X({creds:c,env:d,log:()=>{}})}catch(a){throw a instanceof U?new S("auth-fail","not authenticated. Run `kane-cli login` first."):a}if(!l.basicAuth)throw new S("auth-incomplete","TMS basic auth could not be resolved. Run `kane-cli login` again.");try{let a=G(d);await ct({tmsBaseUrl:a.tmsBaseUrl,testcaseId:i.testcase_id,auth:l.basicAuth,language:o,framework:"playwright",skipValidation:n.code_export?.skip_validation??!0,outDir:e,log:()=>{}})}catch(a){throw new S("export-fail",`code export failed: ${a.message}`)}return{kind:"exported",codeDir:e}}async function Xt(t,r,i){let n=Y(t);if(!D(n))return process.stderr.write(`error: file not found: ${n}
16
+ `),2;let o=F(n),e=q(o,i);if(e!==null)return e;try{let s=await ht(n,r);return s.kind==="reused"?process.stderr.write(`reusing existing export at ${s.codeDir}
17
+ `):process.stderr.write(`exported to ${s.codeDir}
18
+ `),0}catch(s){if(s instanceof S)return s.kind==="not-synced"?(process.stderr.write("error: this test has not been synced to TMS \u2014 run `kane-cli testmd run` first.\n"),2):s.kind==="no-language"?(process.stderr.write(`error: --language not provided and no default in tui-config.
19
+ `),2):s.kind==="auth-fail"?(process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),2):s.kind==="auth-incomplete"?(process.stderr.write("error: TMS basic auth could not be resolved. Run `kane-cli login` again.\n"),2):(process.stderr.write(`error: ${s.message}
20
+ `),2);throw s}}export{lt as a,ut as b,F as c,ft as d,q as e,Me as f,De as g,Jt as h,Ce as i,Ut as j,S as k,Oe as l,Xt as m};