@testmuai/kane-cli 0.4.0 → 0.4.1

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 (99) hide show
  1. package/dist/{ChromeProfilePicker-27QCT4NT.js → ChromeProfilePicker-63JS7QX6.js} +1 -1
  2. package/dist/{CliFeedbackPrompt-LMXDRY5F.js → CliFeedbackPrompt-3SDJ5GZP.js} +1 -1
  3. package/dist/{CliUploadProgress-QP5SPC7G.js → CliUploadProgress-ZSZ7TGCN.js} +1 -1
  4. package/dist/ConfigView-OOQYCHWM.js +2 -0
  5. package/dist/FolderPicker-FILMS64I.js +2 -0
  6. package/dist/{HelpView-2IYG5AC3.js → HelpView-KBFE4EMP.js} +1 -1
  7. package/dist/{InfoBox-JELKGWY5.js → InfoBox-QECFIGGW.js} +1 -1
  8. package/dist/{LinksBox-NUSUOUIW.js → LinksBox-2L2UX4LB.js} +1 -1
  9. package/dist/{ProfilesView-RXYI2IS3.js → ProfilesView-72UTQ5PX.js} +1 -1
  10. package/dist/ProjectPicker-NLEAW232.js +2 -0
  11. package/dist/{SaveSessionPrompt-GUBVAQ3O.js → SaveSessionPrompt-VNJDLJTF.js} +1 -1
  12. package/dist/SingleShotApp-V2UTGNZO.js +2 -0
  13. package/dist/{SummaryBox-5Y2YYOUM.js → SummaryBox-O772FRGO.js} +1 -1
  14. package/dist/TestMdRunView-OVHCLNI7.js +2 -0
  15. package/dist/WhoamiView-LR2EFCTK.js +2 -0
  16. package/dist/{changelog-N4SSER5V.js → changelog-VCAUV47V.js} +1 -1
  17. package/dist/{chunk-H4XV224I.js → chunk-45VTQLJS.js} +1 -1
  18. package/dist/{chunk-LMV2F35W.js → chunk-4QO6JYHX.js} +1 -1
  19. package/dist/chunk-77SZF4ZU.js +2 -0
  20. package/dist/{chunk-PKQJHIKJ.js → chunk-7I2SQ2KP.js} +1 -1
  21. package/dist/{chunk-VS2BXLH4.js → chunk-7NDFOI6Z.js} +1 -1
  22. package/dist/chunk-7U4NY37W.js +22 -0
  23. package/dist/chunk-AGS57DSG.js +17 -0
  24. package/dist/chunk-C6S4IEBC.js +2 -0
  25. package/dist/chunk-CMRNCZGV.js +6 -0
  26. package/dist/{chunk-XQXSPUIX.js → chunk-DAVPOA2L.js} +1 -1
  27. package/dist/{chunk-6NEJEMA6.js → chunk-EEF6OT52.js} +1 -1
  28. package/dist/{chunk-H6OVTXJQ.js → chunk-FGC74Z76.js} +1 -1
  29. package/dist/chunk-FPFOW6BS.js +2 -0
  30. package/dist/{chunk-6IQWD272.js → chunk-G6AXOEED.js} +1 -1
  31. package/dist/{chunk-PN7LNQ7G.js → chunk-H4XK55B3.js} +1 -1
  32. package/dist/{chunk-VTDVK3DK.js → chunk-HUOC7DUT.js} +1 -1
  33. package/dist/{chunk-3Z4EHIOW.js → chunk-IBDWHXNE.js} +1 -1
  34. package/dist/{chunk-O2UU4TS5.js → chunk-J2KTLZAW.js} +1 -1
  35. package/dist/{chunk-AT2Y5UNP.js → chunk-JGXJDTMO.js} +1 -1
  36. package/dist/chunk-JJERCR2W.js +5 -0
  37. package/dist/{chunk-PWHFNSDC.js → chunk-KJEJ7VW5.js} +1 -1
  38. package/dist/{chunk-J37YPPCD.js → chunk-LAR7I5SR.js} +1 -1
  39. package/dist/chunk-LEXQLAWB.js +60 -0
  40. package/dist/chunk-LOIRZFV3.js +10 -0
  41. package/dist/chunk-LPUQ4HWQ.js +2 -0
  42. package/dist/{chunk-7RPMUEEN.js → chunk-OFEPMULV.js} +1 -1
  43. package/dist/chunk-OIPVMEM7.js +2 -0
  44. package/dist/{chunk-CKY3UXTY.js → chunk-P7ZUISQG.js} +1 -1
  45. package/dist/{chunk-JCR3T34A.js → chunk-RHUD7MK4.js} +2 -2
  46. package/dist/{chunk-CGAX3AXA.js → chunk-RJNGCQCL.js} +1 -1
  47. package/dist/chunk-T46Z27UL.js +5 -0
  48. package/dist/chunk-TCLKNUAL.js +17 -0
  49. package/dist/{chunk-TAEW7PXN.js → chunk-UHFCCGVX.js} +1 -1
  50. package/dist/{chunk-5TOE4RHH.js → chunk-UYHNJUPY.js} +1 -1
  51. package/dist/{chunk-IH45REQA.js → chunk-V3FSESZ4.js} +1 -1
  52. package/dist/{chunk-HYVAYSRZ.js → chunk-VKG45YIL.js} +1 -1
  53. package/dist/chunk-YAVIOVVP.js +2 -0
  54. package/dist/{chunk-UJZCMEEH.js → chunk-YSSBAIJI.js} +1 -1
  55. package/dist/{chunk-M5RHRHFC.js → chunk-Z7AXAKPX.js} +1 -1
  56. package/dist/chunk-ZUIWBVGF.js +14 -0
  57. package/dist/exit-manager-V2NW7A7U.js +2 -0
  58. package/dist/generate-headless-XWVVEFQR.js +18 -0
  59. package/dist/index.js +38 -33
  60. package/dist/list-commands-Y6A3XR4L.js +2 -0
  61. package/dist/login-flow-MKAYO6IS.js +2 -0
  62. package/dist/{persist-recorded-session-VEFILVPX.js → persist-recorded-session-WBPLUA55.js} +1 -1
  63. package/dist/{pipeline-3GVPCDRE.js → pipeline-L5TDZMLS.js} +1 -1
  64. package/dist/{recording-banner-WS4Y7LVH.js → recording-banner-Q36WARSF.js} +1 -1
  65. package/dist/require-project-folder-DBXAG7FB.js +2 -0
  66. package/dist/resolver-IDCGRPFJ.js +2 -0
  67. package/dist/run-test-md-H2X6CUIX.js +14 -0
  68. package/dist/scrollback-6GINSTL2.js +2 -0
  69. package/dist/tcg-generate-WURS7TXW.js +2 -0
  70. package/dist/testmd-actions-MQ3N7IS4.js +2 -0
  71. package/dist/{tms-client-R5ZIAOBH.js → tms-client-NNYXLXZK.js} +1 -1
  72. package/dist/token-refresh-HHNMHTYX.js +2 -0
  73. package/dist/validate-basic-VFJZKHOE.js +2 -0
  74. package/dist/{version-check-LNKXGYZE.js → version-check-5NUDIYG4.js} +1 -1
  75. package/package.json +5 -5
  76. package/dist/ConfigView-RQM2JY4K.js +0 -2
  77. package/dist/FolderPicker-YN2YQJXI.js +0 -2
  78. package/dist/ProjectPicker-RUR7HH2P.js +0 -2
  79. package/dist/SingleShotApp-3XDTU2BU.js +0 -2
  80. package/dist/TestMdRunView-PPZPUVVZ.js +0 -2
  81. package/dist/WhoamiView-IJZUFJ7B.js +0 -2
  82. package/dist/chunk-3C7ATCDM.js +0 -2
  83. package/dist/chunk-7CLUJYMW.js +0 -2
  84. package/dist/chunk-7G7ZLAJH.js +0 -5
  85. package/dist/chunk-BKXTOQWL.js +0 -5
  86. package/dist/chunk-BPF7TDRU.js +0 -2
  87. package/dist/chunk-DTFPHZE7.js +0 -62
  88. package/dist/chunk-JLOY7SNA.js +0 -14
  89. package/dist/chunk-L3RTVAPG.js +0 -6
  90. package/dist/chunk-LRF6UP42.js +0 -10
  91. package/dist/chunk-SJ7VGRQU.js +0 -17
  92. package/dist/chunk-UVBDUDSL.js +0 -2
  93. package/dist/generate-headless-7UYAPXE5.js +0 -18
  94. package/dist/login-flow-LK7GAUCZ.js +0 -2
  95. package/dist/resolver-OA35IO7J.js +0 -2
  96. package/dist/run-test-md-SXZUOYSG.js +0 -14
  97. package/dist/tcg-generate-CEBFKKJE.js +0 -2
  98. package/dist/testmd-actions-IZPOBSTC.js +0 -2
  99. package/dist/validate-basic-Y73NBDAD.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as D,b as A}from"./chunk-7G7ZLAJH.js";import{l as S,m as C,n as P,o as U,p as N}from"./chunk-3Z4EHIOW.js";import{createServer as Oe}from"http";import{randomBytes as He}from"crypto";import{URL as $e}from"url";import Z from"process";import{Buffer as ee}from"buffer";import re from"path";import{fileURLToPath as ke}from"url";import{promisify as Le}from"util";import te from"child_process";import Me,{constants as Ie}from"fs/promises";import Y from"process";import G,{constants as me}from"fs/promises";import j from"process";import le from"os";import L from"fs";import se from"fs";import z from"fs";var E;function ie(){try{return z.statSync("/.dockerenv"),!0}catch{return!1}}function ae(){try{return z.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function B(){return E===void 0&&(E=ie()||ae()),E}var k,ce=()=>{try{return se.statSync("/run/.containerenv"),!0}catch{return!1}};function u(){return k===void 0&&(k=ce()||B()),k}var K=()=>{if(j.platform!=="linux")return!1;if(le.release().toLowerCase().includes("microsoft"))return!u();try{if(L.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!u()}catch{}return L.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||L.existsSync("/run/WSL")?!u():!1},d=j.env.__IS_WSL_TEST__?K:K();var de=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let t="/etc/wsl.conf",n=!1;try{await G.access(t,me.F_OK),n=!0}catch{}if(!n)return e;let o=await G.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return i?(r=i.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),fe=async()=>`${await de()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,M=async()=>d?fe():`${Y.env.SYSTEMROOT||Y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function f(e,r,t){let n=o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let o=t();return n(o),o},set(o){n(o)}}),e}import{promisify as Pe}from"util";import O from"process";import{execFile as Ae}from"child_process";import{promisify as pe}from"util";import ue from"process";import{execFile as ge}from"child_process";var he=pe(ge);async function I(){if(ue.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await he("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import we from"process";import{promisify as xe}from"util";import{execFile as ye,execFileSync as cr}from"child_process";var ve=xe(ye);async function X(e,{humanReadableOutput:r=!0,signal:t}={}){if(we.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],o={};t&&(o.signal=t);let{stdout:i}=await ve("osascript",["-e",e,n],o);return i.trim()}async function T(e){return X(`tell application "Finder" to set app_path to application file id "${e}" as string
2
+ import{a as D}from"./chunk-T46Z27UL.js";import{a as A}from"./chunk-OIPVMEM7.js";import{l as S,m as C,n as P,o as U,p as N}from"./chunk-IBDWHXNE.js";import{createServer as Oe}from"http";import{randomBytes as He}from"crypto";import{URL as $e}from"url";import Z from"process";import{Buffer as ee}from"buffer";import re from"path";import{fileURLToPath as ke}from"url";import{promisify as Le}from"util";import te from"child_process";import Me,{constants as Ie}from"fs/promises";import Y from"process";import G,{constants as me}from"fs/promises";import j from"process";import le from"os";import L from"fs";import se from"fs";import z from"fs";var E;function ie(){try{return z.statSync("/.dockerenv"),!0}catch{return!1}}function ae(){try{return z.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function B(){return E===void 0&&(E=ie()||ae()),E}var k,ce=()=>{try{return se.statSync("/run/.containerenv"),!0}catch{return!1}};function u(){return k===void 0&&(k=ce()||B()),k}var K=()=>{if(j.platform!=="linux")return!1;if(le.release().toLowerCase().includes("microsoft"))return!u();try{if(L.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!u()}catch{}return L.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||L.existsSync("/run/WSL")?!u():!1},d=j.env.__IS_WSL_TEST__?K:K();var de=(()=>{let e="/mnt/",r;return async function(){if(r)return r;let t="/etc/wsl.conf",n=!1;try{await G.access(t,me.F_OK),n=!0}catch{}if(!n)return e;let o=await G.readFile(t,{encoding:"utf8"}),i=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return i?(r=i.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),fe=async()=>`${await de()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,M=async()=>d?fe():`${Y.env.SYSTEMROOT||Y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function f(e,r,t){let n=o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let o=t();return n(o),o},set(o){n(o)}}),e}import{promisify as Pe}from"util";import O from"process";import{execFile as Ae}from"child_process";import{promisify as pe}from"util";import ue from"process";import{execFile as ge}from"child_process";var he=pe(ge);async function I(){if(ue.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await he("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import we from"process";import{promisify as xe}from"util";import{execFile as ye,execFileSync as cr}from"child_process";var ve=xe(ye);async function X(e,{humanReadableOutput:r=!0,signal:t}={}){if(we.platform!=="darwin")throw new Error("macOS only");let n=r?[]:["-ss"],o={};t&&(o.signal=t);let{stdout:i}=await ve("osascript",["-e",e,n],o);return i.trim()}async function T(e){return X(`tell application "Finder" to set app_path to application file id "${e}" as string
3
3
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as be}from"util";import{execFile as Se}from"child_process";var Ce=be(Se),y={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},ur=new Map(Object.entries(y)),F=class extends Error{};async function _(e=Ce){let{stdout:r}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(r);if(!t)throw new F(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);let{id:n}=t.groups,o=n.lastIndexOf("."),i=n.lastIndexOf("-"),c=o===-1?void 0:n.slice(0,o),a=i===-1?void 0:n.slice(0,i);return y[n]??y[c]??y[a]??{name:n,id:n}}var Ee=Pe(Ae),Be=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase());async function H(){if(O.platform==="darwin"){let e=await I();return{name:await T(e),id:e}}if(O.platform==="linux"){let{stdout:e}=await Ee("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:Be(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(O.platform==="win32")return _();throw new Error("Only macOS, Linux, and Windows are supported")}var Te=Le(te.execFile),$=re.dirname(ke(import.meta.url)),q=re.join($,"xdg-open"),{platform:w,arch:V}=Z;async function Fe(){let e=await M(),r=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=ee.from(r,"utf16le").toString("base64"),{stdout:n}=await Te(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),o=n.trim(),i={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return i[o]?{id:i[o]}:{}}var J=async(e,r)=>{let t;for(let n of e)try{return await r(n)}catch(o){t=o}throw t},v=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return J(e.app,a=>v({...e,app:a}));let{name:r,arguments:t=[]}=e.app??{};if(t=[...t],Array.isArray(r))return J(r,a=>v({...e,app:{name:a,arguments:t}}));if(r==="browser"||r==="browserPrivate"){let a={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},s=d?await Fe():await H();if(s.id in a){let m=a[s.id];return r==="browserPrivate"&&t.push(l[m]),v({...e,app:{name:g[m],arguments:t}})}throw new Error(`${s.name} is not supported as a default browser`)}let n,o=[],i={};if(w==="darwin")n="open",e.wait&&o.push("--wait-apps"),e.background&&o.push("--background"),e.newInstance&&o.push("--new"),r&&o.push("-a",r);else if(w==="win32"||d&&!u()&&!r){n=await M(),o.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),d||(i.windowsVerbatimArguments=!0);let a=["Start"];e.wait&&a.push("-Wait"),r?(a.push(`"\`"${r}\`""`),e.target&&t.push(e.target)):e.target&&a.push(`"${e.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),a.push("-ArgumentList",t.join(","))),e.target=ee.from(a.join(" "),"utf16le").toString("base64")}else{if(r)n=r;else{let a=!$||$==="/",l=!1;try{await Me.access(q,Ie.X_OK),l=!0}catch{}n=Z.versions.electron??(w==="android"||a||!l)?"xdg-open":q}t.length>0&&o.push(...t),e.wait||(i.stdio="ignore",i.detached=!0)}w==="darwin"&&t.length>0&&o.push("--args",...t),e.target&&o.push(e.target);let c=te.spawn(n,o,i);return e.wait?new Promise((a,l)=>{c.once("error",l),c.once("close",s=>{if(!e.allowNonzeroExitCode&&s>0){l(new Error(`Exited with code ${s}`));return}a(c)})}):(c.unref(),c)},_e=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return v({...r,target:e})};function Q(e){if(typeof e=="string"||Array.isArray(e))return e;let{[V]:r}=e;if(!r)throw new Error(`${V} is not supported`);return r}function b({[w]:e},{wsl:r}){if(r&&d)return Q(r);if(!e)throw new Error(`${w} is not supported`);return Q(e)}var g={};f(g,"chrome",()=>b({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));f(g,"brave",()=>b({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));f(g,"firefox",()=>b({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));f(g,"edge",()=>b({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));f(g,"browser",()=>"browser");f(g,"browserPrivate",()=>"browserPrivate");var oe=_e;var ne=class{profile;environment;creds;oauth;constructor(r="default",t="prod",n){this.profile=r,this.environment=t,this.creds=n??new D,this.oauth=new A(t)}async login(){let{server:r,port:t}=await this.startCallbackServer(),n=N(t);try{let o=this.creds.loadClient(this.profile,this.environment),i=o?.redirect_uris;(!o||!i?.includes(n))&&(o=await this.oauth.registerClient(n),this.creds.saveClient(this.profile,this.environment,o));let c=o.client_id,[a,l]=A.generatePkce(),s=He(32).toString("hex"),m=this.oauth.buildAuthorizationUrl(c,l,s,n),p=await this.waitForCallback(r,t,m,s);if(!p)throw new Error("Login cancelled or timed out");let h=await this.oauth.exchangeCode(p,c,a,n),x={access_token:h.access_token,refresh_token:h.refresh_token,expires_at:Math.floor(Date.now()/1e3)+h.expires_in,scope:h.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,x),this.creds.setActiveProfile(this.profile),x}catch(o){throw r.close(),o}}startCallbackServer(){return new Promise((r,t)=>{let n=C,o=()=>{let i=Oe();i.on("error",c=>{c.code==="EADDRINUSE"&&n<P?(n++,o()):t(new Error(`Failed to start callback server: ${c.message}. Ports ${C}-${P} are all in use.`))}),i.listen(n,S,()=>{r({server:i,port:n})})};o()})}waitForCallback(r,t,n,o){return new Promise(i=>{let c=!1,a=setTimeout(()=>l(null),12e4),l=s=>{c||(c=!0,clearTimeout(a),r.close(),i(s))};r.on("request",(s,m)=>{let p=new $e(s.url??"/",`http://${S}:${t}`);if(p.pathname!==U){m.writeHead(404),m.end();return}let h=p.searchParams.get("state"),x=p.searchParams.get("code");if(p.searchParams.get("error")){m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"error",title:"Login failed",message:"We couldn't complete the sign-in. You can close this tab and try again from your terminal."})),l(null);return}if(h!==o){m.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"error",title:"Invalid state",message:"The sign-in response didn't match this session. Please return to your terminal and try again."})),l(null);return}m.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),m.end(R({state:"success",title:"You're signed in",message:"Head back to your terminal \u2014 KaneAI is ready when you are.",autoClose:!0})),l(x)}),oe(n).catch(s=>{let m=s instanceof Error?s.message:String(s);process.stderr.write(`[auth] Could not open browser: ${m}
4
4
  Please open this URL manually: ${n}
5
5
  `)})})}};function R(e){let r=e.state==="success",t=r?"#22c55e":"#ef4444",n=r?"rgba(34, 197, 94, 0.12)":"rgba(239, 68, 68, 0.12)",o=r?'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7"/></svg>':'<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg>',i=e.autoClose?"<script>setTimeout(function(){try{window.close();}catch(e){}}, 1500);</script>":"";return`<!doctype html>
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as s}from"./chunk-HCBYKLMW.js";import{t as n}from"./chunk-3Z4EHIOW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
2
+ import{t as n}from"./chunk-IBDWHXNE.js";import{a as s}from"./chunk-HCBYKLMW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as je}from"./chunk-H4XK55B3.js";import{a as de,b as $e}from"./chunk-7NDFOI6Z.js";import{d as Pe,f as pe}from"./chunk-LOIRZFV3.js";import{a as Ce}from"./chunk-UYHNJUPY.js";import{a as Ie}from"./chunk-HUOC7DUT.js";import{b as _e}from"./chunk-C6S4IEBC.js";import{t as i}from"./chunk-IBDWHXNE.js";import{a as M}from"./chunk-HCBYKLMW.js";import{a as l,b as r,i as Ee,j as ke,k as me}from"./chunk-C44QQJR4.js";import{a as le}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var Q=$(le(),1);var A=$(le(),1);var L=$(le(),1);function Se(e){let t=e.indexOf(": ");return t>0&&t<15?e.slice(t+2):e}function ve(e){return e.map(t=>{let s=t.children?ve(t.children):t.children;return t.status==="running"?{...t,status:"stopped",phase:void 0,children:s}:s!==t.children?{...t,children:s}:t})}function Oe(e,t,s,a){let[h,u]=(0,L.useState)(!1),[d,c]=(0,L.useState)([]),[D,C]=(0,L.useState)(null),[k,_]=(0,L.useState)(null),[N,f]=(0,L.useState)(null),[m,y]=(0,L.useState)(null),[P,z]=(0,L.useState)([]),[q,Z]=(0,L.useState)(null),[se,fe]=(0,L.useState)(void 0),U=(0,L.useRef)(null),G=(0,L.useRef)(null),Y=(0,L.useRef)(0),J=(0,L.useRef)(!1),p=(0,L.useCallback)(async(B,ae)=>{let we=U.current;if(we){try{await we.exited}catch{}U.current=null}c([]),C(null),_(null),f(null),y(null),z([]),Z(null),fe(B.max_steps),u(!0),G.current=null,Y.current=0;let W;try{W=je(B,ae)}catch(oe){f(oe instanceof Error?oe.message:String(oe)),u(!1);return}U.current=W,Pe("runner",()=>W.cancel()),(async()=>{J.current=!1;let oe=!1;for await(let n of W.events){if(J.current)break;switch(n.type){case"run_start":if(G.current&&!G.current.isSingleFlow){let w=Y.current;Y.current++,c(E=>E.map((R,T)=>T===w?{...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 w=n.flows??[],E=n.count??w.length,R={flows:w,isSingleFlow:n.is_single_flow??E<=1};y(R),G.current=R,Y.current=0,c(w.map((T,x)=>({index:x+1,objective:T??`Flow ${x+1}`,status:"pending"})));break}case"step_start":{t?.("STEP_START",`Step ${n.index} started`,{index:n.index,objective:n.objective,child_id:n.child_id});let w=n.index,E=n.objective??`Step ${w}`,R=n.child_id,T=G.current&&!G.current.isSingleFlow;if(R)c(x=>{let v=x.findIndex(ee=>ee.status==="running"||ee.children?.some(ze=>ze.status==="running"));if(v===-1)return x;let j=[...x],O={...j[v]},re=[...O.children??[]].map(ee=>ee.status==="running"?{...ee,status:"stopped",phase:void 0}:ee);return re.push({index:w,objective:E,status:"running"}),O.children=re,j[v]=O,j});else if(T){let x=Math.max(0,Y.current-1);c(v=>{let j=[...v];if(x>=j.length)return v;let O={...j[x]},re=[...O.children??[]].map(ee=>ee.status==="running"?{...ee,status:"stopped",phase:void 0}:ee);return re.push({index:w,objective:E,status:"running"}),O.children=re,O.status="running",j[x]=O,j})}else c(x=>{let v=ve(x);return v.some(O=>O.index===w)?v.map(O=>O.index===w?{...O,status:"running",objective:E}:O):[...v,{index:w,objective:E,status:"running"}]});break}case"step_event":{t?.("STEP_EVENT",`Step ${n.index} ${n.event}`,{index:n.index,phase:n.event,action_type:n.action_type,detail:n.detail,child_id:n.child_id});let w=n.child_id,E=G.current&&!G.current.isSingleFlow;if(n.event==="cm_init"&&n.checkpoint_count!=null){z(R=>[...R,n.checkpoint_count]);break}if(n.event==="replay_started"){Z({recordingLength:n.recording_length??0});break}if(n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&s?.(n.detail),w)c(R=>R.map(T=>{if(!T.children)return T;let x=T.children.map(v=>{if(v.index!==n.index)return v;let j={phase:n.event};return n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&(j.objective=n.detail),n.action_type&&(j.actionType=n.action_type),{...v,...j}});return{...T,children:x}}));else if(E){let R=Math.max(0,Y.current-1);c(T=>{let x=[...T];if(R>=x.length)return T;let v={...x[R]},j=[...v.children??[]];if(!j.some(te=>te.index===n.index))j.push({index:n.index,objective:`Step ${n.index}`,status:"running",phase:n.event,actionType:n.action_type});else for(let te=0;te<j.length;te++){if(j[te].index!==n.index)continue;let re={phase:n.event};n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&(re.objective=n.detail),n.action_type&&(re.actionType=n.action_type),j[te]={...j[te],...re}}return v.children=j,x[R]=v,x})}else c(R=>R.some(x=>x.index===n.index)?R.map(x=>{if(x.index!==n.index)return x;let v={phase:n.event};return n.event==="reasoning"&&n.detail&&n.detail!=="reasoning"&&(v.objective=n.detail),n.action_type&&(v.actionType=n.action_type),{...x,...v}}):[...ve(R),{index:n.index,objective:`Step ${n.index}`,status:"running",phase:n.event,actionType:n.action_type}]);break}case"step_end":{t?.("STEP_END",`Step ${n.index} ${n.status}`,{index:n.index,status:n.status,duration:n.duration,summary:n.summary,child_id:n.child_id}),a?.();let w=n.child_id,E=G.current&&!G.current.isSingleFlow;if(w)c(R=>R.map(T=>{if(!T.children)return T;let x=T.children.map(v=>v.index===n.index?{...v,status:n.status,duration:n.duration,phase:void 0,objective:v.objective.startsWith("Step ")?Se(n.summary||v.objective):v.objective}:v);return{...T,children:x}}));else if(E){let R=Math.max(0,Y.current-1);c(T=>{let x=[...T];if(R>=x.length)return T;let v={...x[R]},j=(v.children??[]).map(O=>O.index===n.index?{...O,status:n.status,duration:n.duration,phase:void 0,objective:O.objective.startsWith("Step ")?Se(n.summary||O.objective):O.objective}:O);return v.children=j,x[R]=v,x})}else c(R=>R.map(T=>T.index===n.index?{...T,status:n.status,duration:n.duration,phase:void 0,objective:T.objective.startsWith("Step ")?Se(n.summary||T.objective):T.objective}:T));{let T=G.current&&!G.current.isSingleFlow?Math.max(0,Y.current-1):0;e?.(n.index,T,n.child_id)}break}case"child_agent_start":{let w=n.objective??"";c(E=>E.map(R=>R.status==="running"?{...R,objective:`${w} (branch)`,phase:`child: ${w.slice(0,50)}`,branchObjective:w}:R));break}case"child_agent_end":c(w=>w.map(E=>E.phase?.startsWith("child:")?{...E,phase:`child ${n.success?"done":"failed"}`}:E));break;case"ask_user":C(n.question??"");break;case"run_end":c(w=>w.map(E=>E.status==="running"?{...E,status:n.status,phase:void 0}:E)),u(!1),_(n),oe=!0;break;case"error":u(!1),f(n.message??"Runner error"),c(w=>w.map(E=>E.status==="running"?{...E,status:"failed",phase:void 0}:E));break}}let{code:ne,signal:Re}=await W.exited,be=W.stderr,Ve=ne===0&&!Re,ue=[];ne!==null&&ne!==0&&ue.push(`Runner exited with code ${ne}`),Re&&ue.push(`Runner killed by signal ${Re}`),be&&(!Ve||!oe?ue.push(be):ae?.log?.("debug","RUNNER_STDERR_BENIGN","Runner stderr on clean exit",{stderr:be})),U.current===W&&(ue.length>0&&f(ue.join(`
3
+ `)),u(!1),pe("runner","Event stream ended"),U.current=null)})().catch(oe=>{let ne=[`Runner event loop error: ${oe}`];W.exitCode!==null&&W.exitCode!==0&&ne.push(`Exit code: ${W.exitCode}`),W.exitSignal&&ne.push(`Signal: ${W.exitSignal}`),W.stderr&&ne.push(W.stderr),U.current===W&&(f(ne.join(`
4
+ `)),u(!1),pe("runner","Event loop error"),U.current=null)})},[e,t,s,a]),b=(0,L.useCallback)(B=>{U.current?.sendUserResponse(B),C(null)},[]),S=(0,L.useCallback)(()=>{let B=U.current;B&&(B.sendCancel("user"),u(!1),C(null),setTimeout(()=>{U.current===B&&(pe("runner","User cancelled run"),U.current=null)},5e3))},[]),g=(0,L.useCallback)(()=>{c([]),_(null),f(null)},[]);return(0,L.useEffect)(()=>()=>{J.current=!0,pe("runner","Component unmounted"),U.current=null},[]),{isRunning:h,steps:d,askingUser:D,lastRunEnd:k,runError:N,bifurcationInfo:m,cmInitCounts:P,replayInfo:q,maxSteps:se,startRun:p,sendAnswer:b,cancelRun:S,clearLastRun:g}}function ye(e){let t=e.flatMap(u=>[u,...u.children??[]]),s=t.filter(u=>u.status==="passed").length,a=t.filter(u=>u.status==="failed").length,h=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:s,failed:a,total:h}}function Le(e){let t=Oe(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[s,a]=(0,A.useState)(0),[h,u]=(0,A.useState)("idle"),d=(0,A.useRef)("idle"),c=(0,A.useRef)(0),D=(0,A.useRef)(!1),C=(0,A.useRef)(null),k=(0,A.useRef)(null),_=(0,A.useCallback)(m=>{d.current=m,u(m)},[]),N=(0,A.useCallback)(async m=>{let y=await e.getNextConfig(m);if(!y){_("done"),e.onAllComplete?.();return}let P=m?c.current+1:0;c.current=P,a(P),e.onStepStart?.(y,P),C.current=null,k.current=null,_("running"),await t.startRun(y,e.spawnOpts)},[t,e,_]);(0,A.useEffect)(()=>{D.current||(D.current=!0,N(null))},[]),(0,A.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===C.current||d.current!=="running")return;C.current=t.lastRunEnd,d.current="transitioning",u("transitioning");let m=t.lastRunEnd,y=ye(t.steps),P=t.bifurcationInfo,z={status:m.status==="passed"?"passed":"failed",duration_s:m.duration??0,reason:m.reason,runEnd:m,hadError:!1,stepsPassed:y.passed,stepsFailed:y.failed,stepsTotal:y.total,bifurcationFlows:P&&!P.isSingleFlow?P.flows:null};if(!(e.onStepEnd?.(z,c.current)??!0)){_("done"),e.onAllComplete?.();return}N(z)},[t.lastRunEnd]),(0,A.useEffect)(()=>{if(!t.runError||t.runError===k.current||t.lastRunEnd||d.current!=="running")return;k.current=t.runError,d.current="transitioning",u("transitioning");let m=ye(t.steps),y={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:m.passed,stepsFailed:m.failed,stepsTotal:m.total,bifurcationFlows:null};if(!(e.onStepEnd?.(y,c.current)??!0)){_("done"),e.onAllComplete?.();return}N(y)},[t.runError,t.lastRunEnd]);let f=(0,A.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:s,phase:h,cancel:f}}var Te=$(le(),1);var ge=$(M(),1),De=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Fe({label:e,hasBifurcation:t=!1}){let[s,a]=(0,Te.useState)(0),[h,u]=(0,Te.useState)(0);de(()=>{a(c=>(c+1)%De.length)},80),de(()=>{u(c=>(c+1)%4)},400);let d=e??(t?"Planning approach":"Analyzing objective");return(0,ge.jsxs)(l,{marginLeft:1,children:[(0,ge.jsxs)(r,{color:i.orange,children:[De[s]," "]}),(0,ge.jsxs)(r,{color:i.dim,children:[d,".".repeat(h+1)]})]})}function Me(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let s=e.steps.findIndex(h=>h.status==="running");return(s===-1?e.cmInitCounts.length===0:s>=e.cmInitCounts.length)?{label:s>0?`Planning flow ${s+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(s=>s.children?.length)?null:{hasBifurcation:!!t}}var F=$(le(),1);var Ne=$(le(),1);var xe=$(M(),1),Xe="#ffc580",Ye="#ffd9a8",Ae="#ffffff";function qe({text:e,active:t=!0}){let[s,a]=(0,Ne.useState)(0),h=4;if(de(()=>{a(d=>(d+1)%(e.length+h*2))},t?80:null),!t)return(0,xe.jsx)(r,{color:Ae,children:e});let u=e.split("").map((d,c)=>{let D=s-h,C=Math.abs(c-D-h/2),k;return C<=h/2?k=Xe:C<=h?k=Ye:k=Ae,(0,xe.jsx)(r,{color:k,children:d},c)});return(0,xe.jsx)(r,{children:u})}var K=$(M(),1),Je={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function he({currentStep:e,maxSteps:t,elapsed:s,status:a}){let{stdout:h}=me(),u=h?.columns??80,d=Je[a]??i.orange,c=s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m ${Math.round(s%60)}s`;return(0,K.jsxs)(l,{flexDirection:"column",marginTop:1,children:[(0,K.jsx)(r,{color:i.muted,children:"\u2500".repeat(Math.min(u,60))}),(0,K.jsxs)(l,{children:[(0,K.jsx)(r,{children:" "}),(0,K.jsx)(r,{color:i.dim,children:"Steps "}),(0,K.jsx)(r,{bold:!0,children:e}),(0,K.jsxs)(r,{color:i.dim,children:["/",t]}),(0,K.jsx)(r,{children:" "}),(0,K.jsx)(r,{color:i.dim,children:"Elapsed "}),(0,K.jsx)(r,{bold:!0,children:c}),(0,K.jsx)(r,{children:" "}),(0,K.jsx)(r,{color:i.dim,children:"Status "}),(0,K.jsx)(r,{bold:!0,color:d,children:a})]})]})}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 ie=$(M(),1);function Be({steps:e,flows:t,cmInitCounts:s,renderStep:a}){return(0,ie.jsxs)(l,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,ie.jsxs)(r,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((h,u)=>(0,ie.jsxs)(l,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,ie.jsxs)(r,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??h.objective]}),s&&s[u]!=null&&(0,ie.jsxs)(r,{color:i.dim,children:[" \u25AA Generated task with ",s[u]," checkpoints"]}),h.children&&h.children.length>0?h.children.map(d=>a(d,`f${u}-${d.index}`)):h.status==="pending"&&(0,ie.jsx)(r,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var o=$(M(),1);function X({step:e,indent:t=2}){let s=e.actionType?Ue(e.actionType):null,a=e.status==="running",h=e.status==="passed",u=e.status==="failed",d=e.status==="pending"||e.status==="stopped",{stdout:c}=me(),D=c?.columns??80,C=Math.max(20,D-t-21),k=e.objective??"",_=k.length>C?k.slice(0,C-1)+"\u2026":k,N=(e.duration??0)*1e3,f=e.duration!=null?N<1e3?`${Math.round(N)}ms`:`${(N/1e3).toFixed(1)}s`:"";return(0,o.jsxs)(l,{flexDirection:"column",children:[(0,o.jsxs)(l,{marginLeft:t,children:[(0,o.jsx)(l,{width:4,children:(0,o.jsxs)(r,{color:i.muted,children:[String(e.index).padStart(2," ")," "]})}),(0,o.jsx)(l,{width:3,children:a?(0,o.jsx)($e,{}):h?(0,o.jsx)(r,{color:i.green,bold:!0,children:"\u2713"}):u?(0,o.jsx)(r,{color:i.red,bold:!0,children:"\u2717"}):(0,o.jsx)(r,{color:i.muted,children:"\u25CB"})}),(0,o.jsx)(l,{flexGrow:1,children:a?(0,o.jsx)(qe,{text:_,active:!0}):u?(0,o.jsx)(r,{color:i.red,children:_}):d?(0,o.jsx)(r,{color:i.dim,children:_}):(0,o.jsx)(r,{color:i.dim,children:_})}),(h||u)&&s?(0,o.jsx)(l,{width:3,marginLeft:1,children:(0,o.jsx)(r,{color:i.muted,children:s})}):(0,o.jsx)(l,{width:3,marginLeft:1}),(0,o.jsx)(l,{width:7,justifyContent:"flex-end",children:(0,o.jsx)(r,{color:i.dim,children:f})})]}),e.children&&e.children.length>0&&(0,o.jsx)(l,{flexDirection:"column",children:e.children.map((m,y)=>(0,o.jsx)(X,{step:m,indent:t+2},`child-${y}`))})]})}function Ze(e){return e.type==="cm_init"?(0,o.jsx)(l,{marginLeft:2,paddingLeft:1,children:(0,o.jsxs)(r,{color:i.dim,children:["\u25AA Generated task with ",e.count," checkpoints"]})}):(0,o.jsx)(l,{marginLeft:2,paddingLeft:1,children:(0,o.jsx)(X,{step:e.step})})}function Ge({steps:e,bifurcated:t,flows:s,cmInitCounts:a,maxSteps:h=50,staticSteps:u=!1,onStepCommit:d}){let c=(0,F.useRef)(new Set),D=(0,F.useRef)(!1),C=(0,F.useRef)(new Set),k=(0,F.useRef)(!1),_=(0,F.useRef)(new Set),N=(0,F.useRef)(0);(0,F.useEffect)(()=>{e.length===0&&N.current>0&&(c.current.clear(),D.current=!1,C.current.clear(),k.current=!1,_.current.clear()),N.current=e.length},[e.length]);let f=e.flatMap(p=>[p,...p.children??[]]),m=f.some(p=>p.status==="running"),y=f.some(p=>p.status==="failed"),P=f.length===0||f.every(p=>p.status==="pending"),z=f.filter(p=>p.status==="passed"||p.status==="failed").length,q;P?q="starting":m?q="running":y?q="failed":q="passed";let Z=(0,F.useRef)(null),[se,fe]=(0,F.useState)(0);(0,F.useEffect)(()=>{f.length===0||P?(Z.current=null,fe(0)):m&&Z.current==null&&(Z.current=Date.now())},[m,P,f.length]),(0,F.useEffect)(()=>{if(!m)return;let p=setInterval(()=>{Z.current!=null&&fe((Date.now()-Z.current)/1e3)},500);return()=>clearInterval(p)},[m]);let U=(0,F.useRef)(new Set),[,G]=(0,F.useState)(0),Y=(0,F.useRef)(!1);(0,F.useEffect)(()=>{if(!d||!u||t)return;let p=[];!Y.current&&a&&a[0]!=null&&(Y.current=!0,a[0]>0&&p.push({key:"cm_init_0",type:"cm_init",count:a[0]}));for(let b of e)(b.status==="passed"||b.status==="failed")&&!U.current.has(b.index)&&(U.current.add(b.index),p.push({key:`step_${b.index}`,type:"step",step:{...b,children:b.children?[...b.children]:void 0}}));if(p.length>0){for(let b of p)d(Ze(b));G(b=>b+1)}},[e,t,a,u,d]),(0,F.useEffect)(()=>{if(!d||u)return;let p=c.current.size;if(!t&&!k.current&&a&&a[0]!=null&&(k.current=!0,a[0]>0&&d((0,o.jsx)(l,{marginLeft:2,children:(0,o.jsxs)(r,{color:i.dim,children:["\u25A0 Generated task with ",a[0]," checkpoints"]})}))),t&&s&&!D.current&&(D.current=!0,d((0,o.jsx)(r,{color:i.purple,children:"\u2501\u2501 Bifurcated into "+s.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),t){let b=e.flatMap((S,g)=>{let B=S.children??[];return!C.current.has(g)&&B.length>0&&(C.current.add(g),d((0,o.jsx)(r,{color:i.purple,children:" Flow "+(g+1)+": "+(s?.[g]??"")})),a?.[g]!=null&&a[g]>0&&!_.current.has(g)&&(_.current.add(g),d((0,o.jsx)(l,{marginLeft:2,children:(0,o.jsxs)(r,{color:i.dim,children:[" \u25AA Generated task with ",a[g]," checkpoints"]})})))),a?.[g]!=null&&a[g]>0&&C.current.has(g)&&!_.current.has(g)&&(_.current.add(g),d((0,o.jsx)(l,{marginLeft:2,children:(0,o.jsxs)(r,{color:i.dim,children:[" \u25AA Generated task with ",a[g]," checkpoints"]})}))),B});for(let S of b){let g=`${S.index}-${S.objective}`;c.current.has(g)||(S.status==="passed"||S.status==="failed"||S.status==="stopped")&&(c.current.add(g),d((0,o.jsx)(l,{marginLeft:2,children:(0,o.jsx)(X,{step:S})})))}}else for(let b of e){let S=`${b.index}-${b.objective}`,g=!!b.branchObjective;g&&!c.current.has(S)&&(c.current.add(S),d((0,o.jsx)(l,{marginLeft:2,children:(0,o.jsx)(X,{step:{...b,children:void 0}})})));for(let B of b.children??[]){let ae=`child-${b.index}-${B.index}-${B.objective}`;c.current.has(ae)||(B.status==="passed"||B.status==="failed"||B.status==="stopped")&&(c.current.add(ae),d((0,o.jsx)(l,{marginLeft:4,children:(0,o.jsx)(X,{step:B})})))}!g&&!c.current.has(S)&&(b.status==="passed"||b.status==="failed"||b.status==="stopped")&&(c.current.add(S),d((0,o.jsx)(l,{marginLeft:2,children:(0,o.jsx)(X,{step:{...b,children:void 0}})})))}c.current.size>p&&G(b=>b+1)},[e,d,t,s,a]);let J=[];if(u&&!t)for(let p of e)U.current.has(p.index)||J.push(p);else if(d&&!u)if(t)for(let p of e){let S=(p.children??[]).filter(g=>{let B=`${g.index}-${g.objective}`;return!c.current.has(B)});S.length>0&&J.push({...p,children:S})}else for(let p of e){let b=`${p.index}-${p.objective}`,S=c.current.has(b),g=(p.children??[]).filter(B=>{let ae=`child-${p.index}-${B.index}-${B.objective}`;return!c.current.has(ae)});S?g.length>0&&J.push({...p,children:g}):J.push({...p,children:g})}if(!u){let p=d?J:e;return(0,o.jsxs)(l,{flexDirection:"column",children:[t?d?p.length>0?(0,o.jsx)(l,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:p.map((S,g)=>(0,o.jsx)(l,{flexDirection:"column",marginTop:g>0?1:0,children:S.children&&S.children.length>0?S.children.map(B=>(0,o.jsx)(X,{step:B},`f${g}-${B.index}`)):S.status==="pending"&&(0,o.jsx)(r,{color:i.dim,children:" \u25CB Waiting..."})},g))}):null:(0,o.jsx)(Be,{steps:e,flows:s,cmInitCounts:a,renderStep:(S,g)=>(0,o.jsx)(X,{step:S},g)}):(0,o.jsxs)(l,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!d&&a&&a[0]!=null&&(0,o.jsxs)(r,{color:i.dim,children:["\u25AA Generated task with ",a[0]," checkpoints"]}),p.map(S=>{let g=`${S.index}-${S.objective}`;return d&&c.current.has(g)?(0,o.jsx)(l,{flexDirection:"column",children:(S.children??[]).map(B=>(0,o.jsx)(l,{marginLeft:2,children:(0,o.jsx)(X,{step:B})},B.index))},`branch-children-${S.index}`):(0,o.jsx)(X,{step:S},S.index)})]}),m&&(0,o.jsx)(he,{currentStep:z,maxSteps:h,elapsed:se,status:q})]})}return t?(0,o.jsxs)(l,{flexDirection:"column",children:[(0,o.jsx)(Be,{steps:e,flows:s,cmInitCounts:a,renderStep:(p,b)=>(0,o.jsx)(X,{step:p},b)}),m&&(0,o.jsx)(he,{currentStep:z,maxSteps:h,elapsed:se,status:q})]}):(0,o.jsxs)(l,{flexDirection:"column",children:[J.length>0&&(0,o.jsx)(l,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:J.map(p=>(0,o.jsx)(X,{step:p},p.index))}),m&&(0,o.jsx)(he,{currentStep:z,maxSteps:h,elapsed:se,status:q})]})}var ce=$(M(),1);function We({runner:e,runKey:t,onStepCommit:s}){let a=Me({isRunning:e.isRunning,bifurcationInfo:e.bifurcationInfo,steps:e.steps,cmInitCounts:e.cmInitCounts,replayInfo:e.replayInfo});return(0,ce.jsxs)(ce.Fragment,{children:[a&&(0,ce.jsx)(Fe,{label:a.label,hasBifurcation:a.hasBifurcation}),e.isRunning&&e.steps.length>0&&(0,ce.jsx)(Ge,{steps:e.steps,bifurcated:!!e.bifurcationInfo&&!e.bifurcationInfo.isSingleFlow,flows:e.bifurcationInfo?.flows,cmInitCounts:e.cmInitCounts,maxSteps:e.maxSteps,onStepCommit:s},`run-${t}`)]})}var H=$(M(),1),en=64;function nn(e){return e.split(`
5
+ `).map(t=>t.replace(/^[-–•]\s*/,"").trim()).filter(t=>t.length>0)}function Ke({status:e,summary:t,duration:s,steps:a,stepsPassed:h,stepsFailed:u,reason:d,creditsConsumed:c}){let D=e==="passed",C=D?i.green:i.red,k=D?"\u2713":"\u2717",_=e.toUpperCase(),N=h??(D?a:Math.max(0,a-1)),f=u??(D?0:1),m=f>0?`${a} steps (${N} passed, ${f} failed)`:`${a} steps`,y=s<60?`${s.toFixed(1)}s`:`${Math.floor(s/60)}m ${Math.round(s%60)}s`,P=nn(t);return(0,H.jsx)(l,{flexDirection:"column",marginTop:1,children:(0,H.jsxs)(l,{borderStyle:"round",borderColor:C,flexDirection:"column",paddingX:2,paddingY:1,width:en+6,children:[(0,H.jsxs)(l,{flexDirection:"column",children:[(0,H.jsxs)(r,{bold:!0,color:C,children:[k," ",_]}),(0,H.jsxs)(r,{color:i.dim,wrap:"wrap",children:[m," \xB7 ",y,typeof c=="number"&&c>0?` \xB7 ${parseFloat(c.toFixed(4))} credits`:""]})]}),P.length>0&&(0,H.jsx)(l,{flexDirection:"column",marginTop:1,marginLeft:1,children:P.map((z,q)=>(0,H.jsxs)(l,{marginBottom:q<P.length-1?1:0,children:[(0,H.jsx)(r,{color:i.orange,children:"\u25CF "}),(0,H.jsx)(l,{flexShrink:1,children:(0,H.jsx)(r,{wrap:"wrap",children:z})})]},q))}),d&&!D&&(0,H.jsx)(l,{marginTop:1,children:(0,H.jsxs)(r,{color:i.red,wrap:"wrap",children:["Reason: ",d]})})]})})}var V=$(M(),1);function He({message:e,code:t,remediation:s,docsUrl:a}){return(0,V.jsx)(Ie,{title:"Error",variant:"error",children:(0,V.jsxs)(l,{flexDirection:"column",paddingY:1,children:[(0,V.jsxs)(r,{color:i.red,bold:!0,children:[" \u2717 ",e]}),t&&(0,V.jsxs)(l,{marginTop:0,marginLeft:5,children:[(0,V.jsx)(r,{color:i.muted,children:"Code: "}),(0,V.jsx)(r,{color:i.dim,children:t})]}),s&&(0,V.jsxs)(l,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,V.jsx)(r,{color:i.green,bold:!0,children:"Fix:"}),(0,V.jsxs)(r,{color:i.orange,children:["$ ",s]})]}),a&&(0,V.jsxs)(l,{marginTop:1,marginLeft:5,children:[(0,V.jsx)(r,{color:i.muted,children:"Docs: "}),(0,V.jsx)(r,{color:i.orange,underline:!0,children:a})]})]})})}var I=$(M(),1);function rt(e){let{exit:t}=ke(),{append:s}=_e(),a=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{a.current||(a.current=!0,s((0,I.jsx)(l,{flexDirection:"column",marginBottom:1,children:(0,I.jsxs)(l,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,I.jsx)(r,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,I.jsx)(r,{color:i.dim,children:" \u2502 "}),(0,I.jsx)(r,{color:i.orange,children:e.topBanner.model}),(0,I.jsx)(r,{color:i.dim,children:" \u2502 "}),(0,I.jsx)(r,{color:i.dim,children:e.topBanner.auth})]})})),s((0,I.jsx)(tn,{data:e.globalConfig})),e.priorAttemptRollup&&s((0,I.jsx)(r,{color:i.dim,children:` \u21B3 replayed ${e.priorAttemptRollup.startIdx}..${e.priorAttemptRollup.endIdx-1} (${e.priorAttemptRollup.count} steps, from prior attempt)`})))},[]);let h=(0,Q.useRef)(null),u=(0,Q.useCallback)(async f=>{let m=await e.getNextStep(f);return m?(h.current=m,m.config):(h.current=null,null)},[e]),d=(0,Q.useCallback)((f,m)=>{let y=h.current;if(!y)return;let P=y.mode==="replay"?"cyan":"#dc4e08",z=y.modeReason?` (${y.modeReason})`:"",q=y.perStepOverrides?Object.entries(y.perStepOverrides):[];s((0,I.jsxs)(l,{flexDirection:"column",marginBottom:0,children:[(0,I.jsxs)(r,{children:[(0,I.jsxs)(r,{color:i.dim,children:[y.banner.stepLabel," "]}),(0,I.jsxs)(r,{color:P,children:["[",y.mode,"]"]}),(0,I.jsx)(r,{color:i.dim,children:z})]}),(0,I.jsx)(r,{color:i.dim,children:y.banner.objective}),q.length>0&&(0,I.jsxs)(r,{color:i.dim,children:["overrides: ",q.map(([Z,se])=>`${Z}=${se}`).join(", ")]})]}))},[s]),c=(0,Q.useRef)(0),D=(0,Q.useRef)(!1),C=(0,Q.useCallback)((f,m)=>(f.hadError?s((0,I.jsx)(He,{message:f.reason??"Runner error",code:"RUNNER_ERROR"})):s((0,I.jsx)(l,{flexDirection:"column",marginBottom:1,children:(0,I.jsx)(Ke,{status:f.status,summary:f.runEnd?.summary??"",duration:f.runEnd?.duration??0,steps:f.stepsTotal,stepsPassed:f.stepsPassed,stepsFailed:f.stepsFailed,reason:f.runEnd?.reason,creditsConsumed:f.runEnd?.credits_consumed})})),e.onStepEnd?.(f,m)??!0),[s,e]),k=Le({getNextConfig:u,onStepStart:d,onStepEnd:C,onAllComplete:()=>{e.onAllComplete(),e.exitOnComplete!==!1&&setImmediate(()=>t())},screenshotDispatcher:e.screenshotDispatcher,stepLogger:e.stepLogger,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete,spawnOpts:e.spawnOpts}),_=250,N=5e3;return Ee((f,m)=>{if(m.ctrl&&f==="c"){let y=Date.now(),P=y-c.current;if(P<_)return;D.current&&P<N?(k.cancel(),e.onCancel?.(),e.exitOnComplete!==!1&&setImmediate(()=>t())):(D.current=!0,s((0,I.jsx)(r,{color:"yellow",children:"press Ctrl+C again to cancel run"}))),c.current=y}}),(0,I.jsx)(l,{flexDirection:"column",children:k.phase!=="done"&&(0,I.jsx)(We,{runner:k.runner,runKey:k.currentStepIndex,onStepCommit:s})})}function tn({data:e}){return(0,I.jsx)(Ce,{title:"test.md run",titleColor:"#ff9500",borderColor:i.dim,rows:[{label:"source",value:e.source},{label:"steps",value:`${e.steps.total} (${e.steps.replay} replay, ${e.steps.author} author per walker)`},{label:"model",value:e.model},{label:"viewport",value:`${e.viewport.width} x ${e.viewport.height}`},{label:"chrome",value:e.chrome},{label:"session",value:e.session},{label:"variables",value:`${e.variables.count} (${e.variables.secrets} secret)`},{label:"flags",value:e.flags.length>0?e.flags.join(" "):"(none)"}]})}export{Ge as a,Fe as b,Me as c,Oe as d,ye as e,Ke as f,He as g,rt as h};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as $}from"./chunk-YCCUBQY4.js";import{a as U}from"./chunk-TAEW7PXN.js";import{a as k}from"./chunk-J37YPPCD.js";import{a as _}from"./chunk-AT2Y5UNP.js";import{a as O}from"./chunk-HCBYKLMW.js";import{t as i}from"./chunk-3Z4EHIOW.js";import{a as u,b as s}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{a as T}from"./chunk-7CLUJYMW.js";import{e as S}from"./chunk-UR6MHSHU.js";var e=S(K(),1);var r=S(O(),1);function V(n,x,c){return{id:n,label:`${x} (${n})`,isActive:n===c}}function se({resolver:n,currentProjectId:x,env:c,onSelect:w,onCancel:C}){let[q,B]=(0,e.useState)([]),[D,l]=(0,e.useState)(!0),[H,m]=(0,e.useState)(!1),[J,g]=(0,e.useState)(!1),[Q,P]=(0,e.useState)(null),[d,p]=(0,e.useState)("list"),[v,R]=(0,e.useState)(""),[E,h]=(0,e.useState)(null),[I,X]=(0,e.useState)(""),b=(0,e.useRef)(!1),A=(0,e.useRef)(!0);(0,e.useEffect)(()=>{if(!n){P("Login first to browse projects"),l(!1);return}let o=new AbortController,a=I.trim();return A.current?l(!0):a&&g(!0),m(!0),P(null),(async()=>{try{let t=n.cached??await n.resolve();if(!t){P("Login first to browse projects"),l(!1),m(!1),g(!1);return}let L=k(c),F=new T(L.tmsBaseUrl,t.username,t.access_key),f=!0,N=0,G=a?{signal:o.signal,name:a,perPage:10}:{signal:o.signal,perPage:10};for await(let y of F.listProjectsStream(G)){if(f&&(l(!1),g(!1),A.current=!1,f=!1),y.totalLoaded===0&&y.done&&N===0&&!a){b.current=!0,p("naming"),m(!1);return}let M=y.projects.map(j=>V(j.project_id,j.name,x));B(N===0?M:j=>[...j,...M]),N+=y.projects.length,y.done&&m(!1)}f&&(l(!1),m(!1),g(!1))}catch(t){if(t?.name==="AbortError")return;P(t instanceof Error?t.message:String(t)),l(!1),m(!1),g(!1)}})(),()=>o.abort()},[n,x,c,I]);let Y=(0,e.useCallback)(o=>{let a=o.trim();if(!a){h("Name cannot be empty");return}h(null),p("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let t=n.cached??await n.resolve();if(!t)throw new Error("Not authenticated");let L=k(c),f=await new T(L.tmsBaseUrl,t.username,t.access_key).createProject(a);w(f.id,f.name)}catch(t){h(t instanceof Error?t.message:String(t)),p("naming")}})()},[n,c,w]),z=(0,e.useCallback)(()=>{R(""),h(null),b.current?C():p("list")},[C]);return d==="naming"||d==="creating"?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(s,{color:i.orange,bold:!0,children:"Create new project"}),b.current&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"No projects yet \u2014 let's create one."})}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(s,{color:i.dim,children:"Name: "}),d==="naming"?(0,r.jsx)($,{value:v,onChange:o=>{R(o),E&&h(null)},onSubmit:Y,onCancel:z}):(0,r.jsx)(s,{children:v})]}),E&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.red,children:E})}),d==="creating"&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"Creating..."})}),d==="naming"&&(0,r.jsx)(_,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:b.current?"cancel":"back"})]}):(0,r.jsx)(U,{title:"Projects",items:q,loading:D,loadingMore:H,searching:J,preserveSelectionById:!0,onSearch:X,error:Q,itemNoun:"projects",onTab:()=>{b.current=!1,p("naming")},extraHint:"tab to create new",onSelect:o=>{let a=o.label.replace(` (${o.id})`,"");w(o.id,a)},onCancel:C})}export{V as a,se as b};
2
+ import{a as $}from"./chunk-YCCUBQY4.js";import{a as U}from"./chunk-UHFCCGVX.js";import{a as T}from"./chunk-LPUQ4HWQ.js";import{a as k}from"./chunk-LAR7I5SR.js";import{a as _}from"./chunk-JGXJDTMO.js";import{t as i}from"./chunk-IBDWHXNE.js";import{a as O}from"./chunk-HCBYKLMW.js";import{a as u,b as s}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{e as S}from"./chunk-UR6MHSHU.js";var e=S(K(),1);var r=S(O(),1);function V(n,x,c){return{id:n,label:`${x} (${n})`,isActive:n===c}}function se({resolver:n,currentProjectId:x,env:c,onSelect:w,onCancel:C}){let[q,B]=(0,e.useState)([]),[D,l]=(0,e.useState)(!0),[H,m]=(0,e.useState)(!1),[J,g]=(0,e.useState)(!1),[Q,P]=(0,e.useState)(null),[d,p]=(0,e.useState)("list"),[v,R]=(0,e.useState)(""),[E,h]=(0,e.useState)(null),[I,X]=(0,e.useState)(""),b=(0,e.useRef)(!1),A=(0,e.useRef)(!0);(0,e.useEffect)(()=>{if(!n){P("Login first to browse projects"),l(!1);return}let o=new AbortController,a=I.trim();return A.current?l(!0):a&&g(!0),m(!0),P(null),(async()=>{try{let t=n.cached??await n.resolve();if(!t){P("Login first to browse projects"),l(!1),m(!1),g(!1);return}let L=k(c),F=new T(L.tmsBaseUrl,t.username,t.access_key),f=!0,N=0,G=a?{signal:o.signal,name:a,perPage:10}:{signal:o.signal,perPage:10};for await(let y of F.listProjectsStream(G)){if(f&&(l(!1),g(!1),A.current=!1,f=!1),y.totalLoaded===0&&y.done&&N===0&&!a){b.current=!0,p("naming"),m(!1);return}let M=y.projects.map(j=>V(j.project_id,j.name,x));B(N===0?M:j=>[...j,...M]),N+=y.projects.length,y.done&&m(!1)}f&&(l(!1),m(!1),g(!1))}catch(t){if(t?.name==="AbortError")return;P(t instanceof Error?t.message:String(t)),l(!1),m(!1),g(!1)}})(),()=>o.abort()},[n,x,c,I]);let Y=(0,e.useCallback)(o=>{let a=o.trim();if(!a){h("Name cannot be empty");return}h(null),p("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let t=n.cached??await n.resolve();if(!t)throw new Error("Not authenticated");let L=k(c),f=await new T(L.tmsBaseUrl,t.username,t.access_key).createProject(a);w(f.id,f.name)}catch(t){h(t instanceof Error?t.message:String(t)),p("naming")}})()},[n,c,w]),z=(0,e.useCallback)(()=>{R(""),h(null),b.current?C():p("list")},[C]);return d==="naming"||d==="creating"?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:i.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(s,{color:i.orange,bold:!0,children:"Create new project"}),b.current&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"No projects yet \u2014 let's create one."})}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(s,{color:i.dim,children:"Name: "}),d==="naming"?(0,r.jsx)($,{value:v,onChange:o=>{R(o),E&&h(null)},onSubmit:Y,onCancel:z}):(0,r.jsx)(s,{children:v})]}),E&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.red,children:E})}),d==="creating"&&(0,r.jsx)(u,{marginTop:1,children:(0,r.jsx)(s,{color:i.dim,children:"Creating..."})}),d==="naming"&&(0,r.jsx)(_,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:b.current?"cancel":"back"})]}):(0,r.jsx)(U,{title:"Projects",items:q,loading:D,loadingMore:H,searching:J,preserveSelectionById:!0,onSearch:X,error:Q,itemNoun:"projects",onTab:()=>{b.current=!1,p("naming")},extraHint:"tab to create new",onSelect:o=>{let a=o.label.replace(` (${o.id})`,"");w(o.id,a)},onCancel:C})}export{V as a,se as b};
@@ -1,2 +1,2 @@
1
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};
2
+ import{s}from"./chunk-IBDWHXNE.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,60 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as Re,b as Zt}from"./chunk-C5UNZ6ZY.js";import{a as tr}from"./chunk-EEF6OT52.js";import{c as Xt}from"./chunk-S3DAAAE5.js";import{b as Yt,c as it,d as at,e as ve,f as lt,g as er}from"./chunk-HN7DVSVI.js";import{a as Oe,b as se,c as Qt,e as ae,f as nt,i as Jt,j as ot}from"./chunk-AH4AXJML.js";import{b as de}from"./chunk-AGS57DSG.js";import{a as zt}from"./chunk-WAOCHXJ5.js";import{a as Wt,b as st}from"./chunk-H4XK55B3.js";import{a as Bt,b as Vt,c as rt,d as Le,e as Ht,f as Kt}from"./chunk-LOIRZFV3.js";import{f as qt,g as Gt}from"./chunk-TCLKNUAL.js";import{a as Mt}from"./chunk-LPUQ4HWQ.js";import{a as Te,b as $t}from"./chunk-NLCCBXXV.js";import{a as z}from"./chunk-LAR7I5SR.js";import{a as D}from"./chunk-RZ4F3BHX.js";import{a as Ut}from"./chunk-E47GFYXA.js";import{a as Ft,c as Xe,g as Nt,h as ue,i as et,j as tt}from"./chunk-IBDWHXNE.js";import{join as Ve,basename as mn}from"path";import{existsSync as ts,readFileSync as pn}from"fs";import{existsSync as ct}from"fs";import{join as De,basename as rr}from"path";function sr(e,t){if(!t||!ct(t))return e.steps.map(()=>({kind:"author",reason:"no-result-md"}));let r=at(t),s=[],n=new Set,o=new Map;function a(i){let m=ve(i),p=De(m,"Result.md");if(o.has(p))return o.get(p);let h=ct(p)?at(p):null;return o.set(p,h),h}function l(i){for(let m=1;m<i.trace.length;m++){let h=i.trace[m-1].file===e.rootPath?r:a(i.trace.slice(0,m));if(!h)return{kind:"author",reason:"no-result-md"};let C=i.trace[m-1].stepIndex,b=h.steps[C-1];if(!b)return{kind:"author",reason:"no-result-md"};if(b.kind!=="import")return{kind:"author",reason:"structure-mismatch"};let I=rr(b.importPath),R=rr(i.trace[m].file);if(I!==R)return{kind:"author",reason:"structure-mismatch"};if(b.status!=="passed")return{kind:"author",reason:"recorded-failed"}}return null}for(let i of e.steps){let m=i.trace[i.trace.length-1].file,p=i.trace[i.trace.length-1].stepIndex,h=n.has(m);for(let R=0;R<i.trace.length-1&&!h;R++)n.has(i.trace[R].file)&&(h=!0);if(h){s.push({kind:"author",reason:"downstream-of-divergence"});continue}let C=l(i);if(C){s.push(C);for(let R=0;R<i.trace.length;R++)n.add(i.trace[R].file);continue}let b=m===e.rootPath?r:a(i.trace),I=gs(i,b,p);if(s.push(I),I.kind==="author"){n.add(m);for(let R=0;R<i.trace.length-1;R++)n.add(i.trace[R].file)}}return s}function gs(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=Yt(e);if(n!==s.md5)return{kind:"author",reason:"md5-mismatch"};let o=e.trace.length===1?Jt(e.trace[0].file,r,n.slice(0,8)):De(ve(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 nr(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 or(e){return De(e.recordingDir,"flows","0","actions.ndjson")}function ir(e,t){if(process.env.KANE_REPLAY_TRACE==="1")for(let r=0;r<e.steps.length;r++){let s=e.steps[r],n=t[r],o=" ".repeat(s.trace.length-1),a=`step ${s.flatIndex}`;n.kind==="replay"?process.stderr.write(`[replay-trace] ${o}${a}: REPLAY (would skip; v1 always authors)
3
+ `):process.stderr.write(`[replay-trace] ${o}${a}: AUTHOR (${n.reason})
4
+ `)}}function me(e){process.env.KANE_REPLAY_TRACE==="1"&&process.stderr.write(e)}function ar(e,t){let r=e===0?"(none)":`0..${e-1}`,s=e>=t?"(none)":`${e}..${t-1}`;me(`[replay-trace] phase: replay ${r}, author ${s}
5
+ `)}function lr(e,t){me(`[replay-trace] step ${e}: REPLAY ${t==="ok"?"OK":"FAILED"}
6
+ `)}function cr(e,t,r){me(`[replay-trace] shrink ${e}/${t} \u2192 new boundary ${r}
7
+ `)}function ur(e,t){me(`[replay-trace] complete-reauthor (${e} shrinks exhausted of ${t})
8
+ `)}function ut(){me(`[replay-trace] force-author (--author) \u2014 walker bypassed
9
+ `)}function dr(e){me(`[replay-trace] cancelled at step ${e}
10
+ `)}import{join as bs}from"path";function dt(e){let t={objective:e.step.objective,model:"v16-alpha",width:e.windowSize.width,height:e.windowSize.height,session_id:e.sessionId,run_index:e.runIndex,stream:!0,mode:"replay",replay:{recording_path:or(e.decision),step_label:e.step.objective},screenshot_dir:bs(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 mr(e){let t=e.forceAuthor?0:je(e.decisions),r=0,s=!1;for(;;){let n=e.session.snapshot(),o=e.accumulator.snapshot(),a=await e.runReplayPhase(t);if(a.cancelled)return s=!0,dr(a.failedAt??0),{authorBoundary:t,cancelledInPhase:s,shrinkCount:r};if(a.failedAt===null)return{authorBoundary:t,cancelledInPhase:s,shrinkCount:r};let l=Zt({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 ur(r+1,e.maxShrinks),{authorBoundary:0,cancelledInPhase:s,shrinkCount:r};r++,cr(r,Re.maxShrinks,l.newAuthorBoundary),t=l.newAuthorBoundary}}var ys=15e3,mt=3,pr=[500,1e3];async function pt(e){if(process.env.KANE_LOCK_CONFLICT_SIMULATE==="1")return{ok:!1,reason:"concurrent",httpStatus:409,message:"simulated contention (KANE_LOCK_CONFLICT_SIMULATE=1)"};let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground`,r=await Ue(t,{from_commit_id:e.fromCommitId,new_commit_id:e.newCommitId},e.auth);return r.ok?{ok:!0,sessionExpiresAt:j(r.body,"session_expires_at")??""}:{ok:!1,...Ss(r)}}function Ss(e){let t=j(e.body,"error")??j(e.body,"code")??"",r=j(e.body,"message")??j(e.body,"detail")??e.text??`HTTP ${e.status}`,s;return e.status===0?s="network":e.status===401||e.status===403?s="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?s="base_mismatch":e.status===409?s="concurrent":e.status===422?s="disabled":e.status===400&&/no committed/i.test(r)?s="no_commits":e.status===400?s="missing_field":e.status>=500||e.status===408||e.status===429?s="network":s="other",{reason:s,httpStatus:e.status,message:r}}async function hr(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/playground/reserve`,r=await Ue(t,void 0,e.auth);return r.ok?{ok:!0,sessionExpiresAt:j(r.body,"session_expires_at")??""}:{ok:!1,expired:r.status===404,httpStatus:r.status,message:j(r.body,"message")??j(r.body,"detail")??r.text??`HTTP ${r.status}`}}async function gr(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/commit`,r={commit_id:e.body.commitId,from_commit_id:e.body.fromCommitId,commit_message:e.body.commitMessage,total_steps:e.body.totalSteps};e.body.timeTaken!==void 0&&(r.time_taken=e.body.timeTaken),e.body.objectives!==void 0&&(r.objectives=e.body.objectives);let s=await Ue(t,r,e.auth);return s.ok?{ok:!0,testId:j(s.body,"test_id")??e.testId,testcaseId:j(s.body,"testcase_id")??"",projectId:j(s.body,"project_id"),isTestCaseDeleted:typeof s.body?.is_test_case_deleted=="boolean"?s.body.is_test_case_deleted:void 0}:{ok:!1,...vs(s)}}function vs(e){let t=j(e.body,"error")??j(e.body,"code")??"",r=j(e.body,"message")??j(e.body,"detail")??e.text??`HTTP ${e.status}`,s;return e.status===0?s="network":e.status===401||e.status===403?s="auth":e.status===409&&t==="PlaygroundBaseCommitMismatch"?s="base_mismatch":e.status===409&&t==="PlaygroundCommitLockMismatch"?s="lock_mismatch":e.status===409?s="expired":e.status===422?s="not_found":e.status>=500||e.status===408||e.status===429?s="network":s="other",{reason:s,httpStatus:e.status,message:r}}async function br(e){let t=`${e.baseUrl}/test/${encodeURIComponent(e.testId)}/commit`,r={discard:!0,commit_id:e.body.commitId,from_commit_id:e.body.fromCommitId,commit_message:"(discarded)",total_steps:1},s=await Ue(t,r,e.auth);return s.ok?{ok:!0}:{ok:!1,reason:j(s.body,"error")??"other",httpStatus:s.status,message:j(s.body,"message")??j(s.body,"detail")??s.text??`HTTP ${s.status}`}}async function Ue(e,t,r){let s=null;for(let n=1;n<=mt;n++){let o=new AbortController,a=setTimeout(()=>o.abort(),ys);try{let l=await D(e,{method:"POST",headers:{Authorization:Te(r.username,r.accessKey),"Content-Type":"application/json",Accept:"application/json"},...t!==void 0?{body:JSON.stringify(t)}:{},signal:o.signal});clearTimeout(a);let i=await l.text(),m=null;if(i)try{m=JSON.parse(i)}catch{}let p=l.status>=500||l.status===408||l.status===429;if(l.ok||!p)return{ok:l.ok,status:l.status,body:m,text:i};if(n<mt){await fr(pr[n-1]??1e3);continue}return{ok:!1,status:l.status,body:m,text:i}}catch(l){if(clearTimeout(a),s=l,n<mt){await fr(pr[n-1]??1e3);continue}}}return{ok:!1,status:0,body:null,text:s?.message??"exhausted retries"}}function fr(e){return new Promise(t=>setTimeout(t,e))}function j(e,t){if(typeof e!="object"||e===null)return;let r=e[t];return typeof r=="string"?r:void 0}var Rs=60*1e3,yr="lock-heartbeat",pe=null,ft=null,Sr={register:(e,t)=>Le(e,t),deregister:e=>Ht(e),cleanup:(e,t)=>Kt(e,t),remoteLogger:null};function vr(){pe!==null&&(clearInterval(pe),pe=null)}function ht(e){if(pe!==null)return;let t=e.lifecycle??Sr;ft=t,pe=setInterval(async()=>{let r=await hr({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
+ `)}},Rs),t.register(yr,()=>vr())}function gt(){pe!==null&&(vr(),(ft??Sr).deregister(yr),ft=null)}import{readFileSync as Rr,readdirSync as wr,existsSync as le}from"fs";import{join as ee}from"path";function Ir(e,t,r,s,n,o){try{let a=ee(e,"runs",String(t),"run-test");if(!le(a)){n("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:r,reason:"runsDir_not_found",path:a});return}let l=a;if(o){let R=ee(a,`child-${o}`);if(!le(R)){n("warn","SCREENSHOT_SKIP","Child dir not found",{step_index:r,child_id:o,reason:"child_dir_not_found",path:R});return}let c=wr(R).filter(x=>le(ee(R,x,"screenshots")));if(c.length===0){n("warn","SCREENSHOT_SKIP","No screenshots dir under child",{step_index:r,child_id:o,reason:"no_child_screenshots_dir"});return}l=ee(R,c[0])}else if(!le(ee(a,"screenshots"))){let R=wr(a).filter(c=>le(ee(a,c,"screenshots")));if(R.length===0){n("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:r,reason:"no_screenshots_dir"});return}l=ee(a,R[0])}let i=ee(l,"screenshots",`step_${String(r).padStart(3,"0")}.png`);if(!le(i)){n("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:r,child_id:o,reason:"screenshot_not_found",path:i});return}let m=ee(a,"actions.ndjson");if(!le(m)){n("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:r,reason:"ndjson_not_found"});return}let p=Rr(m,"utf-8").trim().split(`
12
+ `),h=p[p.length-1];if(!h){n("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:r,reason:"ndjson_empty"});return}let b=JSON.parse(h).action_id;if(!b){n("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:r,reason:"no_action_id"});return}let I=Rr(i);s.enqueue(b,I),n("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:r,child_id:o,action_id:b,size:I.length})}catch(a){n("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:r,error:a instanceof Error?a.message:String(a)})}}import{dirname as ws,join as Is}from"path";function _r(e,t,r){let s=e.total_runs??1,n=e.run_dir,o,a;if(s>1&&n){let l=ws(n);o=Array.from({length:s},(i,m)=>Is(l,String(t+m))),r&&r.length===s&&(a=r)}return{allRunDirs:o,flowObjectives:a}}function kr(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 _s}from"child_process";async function Cr(e,t,r=100){let s=`${e.replace(/\/+$/,"")}/json/version`,n=await D(s);if(!n.ok)throw new Error(`CDP /json/version returned ${n.status}`);let o=await n.json();if(!o.webSocketDebuggerUrl)throw new Error("CDP /json/version missing webSocketDebuggerUrl");let a=new Ut(o.webSocketDebuggerUrl);await new Promise((P,_)=>{a.once("open",P),a.once("error",_)});let l=1,i=new Map;a.on("message",P=>{let _;try{_=JSON.parse(P.toString())}catch{return}if(_.id==null)return;let L=i.get(_.id);L&&(i.delete(_.id),_.error?L.reject(new Error(_.error.message)):L.resolve(_.result))});function m(P,_){let L=l++;return new Promise((Q,$)=>{i.set(L,{resolve:ce=>Q(ce),reject:$});let be={id:L,method:P};_&&(be.params=_),a.send(JSON.stringify(be))})}let h=(await m("Target.getTargets")).targetInfos.find(P=>P.type==="page");if(!h)throw a.close(),new Error("CDP: no page target found");let b=(await m("Browser.getWindowForTarget",{targetId:h.targetId})).windowId,I="",R=!1,c=null,x=!1;a.on("close",()=>{x=!0}),a.on("error",()=>{x=!0});async function f(){if(!R){if(x){R=!0;return}try{let _=(await m("Browser.getWindowBounds",{windowId:b})).bounds,L=`${_.left}:${_.top}:${_.width}:${_.height}`;L!==I&&(I=L,t({left:_.left,top:_.top,width:_.width,height:_.height}))}catch{}R||(c=setTimeout(f,r))}}return f(),{stop(){if(!R){R=!0,c&&clearTimeout(c);try{a.close()}catch{}}}}}var ks=new Set(["1","true","yes"]);function Er(e){if(e?.headless)return null;let t=process.env.KANE_CLI_DISABLE_MARKER;if(t!=null&&ks.has(t.toLowerCase()))return null;let r=Wt();if(!r)return null;let s=[...r.args,"overlay"];e?.text&&s.push(e.text);let n;try{n=_s(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&&Cr(e.cdpEndpoint,i=>o({type:"bounds",...i})).then(i=>{a=i.stop}).catch(()=>{});let l=!1;return{setRunActive(i){l||o({type:"run_active",active:i})},setStepText(i){if(l)return;let m=i.trim();m&&o({type:"step_text",text:m})},setStepComplete(){l||o({type:"step_complete"})},kill(){if(!l){l=!0,a?.();try{n.stdin?.end()}catch{}try{n.kill("SIGTERM")}catch{}}}}}function Ar(e,t,r){return`${e}/projects/${t}/test-cases/${r}`}function bt(e,t,r,s){return`${Ar(e,t,r)}/dashboard/share/${s}?type=summary&agentView=true&fqdn=summary-page`}function xr(e,t,r){return`${Ar(e,t,r)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{mkdtempSync as Us,rmSync as Fs}from"fs";import{join as Ns}from"path";import{tmpdir as $s}from"os";import{spawn as Pr,spawnSync as Cs}from"child_process";import{existsSync as yt}from"fs";import{createConnection as Es}from"net";import{homedir as we,platform as _e}from"os";import{join as Ie}from"path";var As=new Set(["1","true","yes"]),Ne=class extends Error{constructor(t){super(t),this.name="ChromeNotFoundError"}};function mo(e){return e instanceof Ne?e.message:`Chrome failed: ${e instanceof Error?e.message:String(e)}`}var $e={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 xs(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let e=_e(),t=$e[e]??$e.linux;for(let r of t)if(yt(r))return r;return e==="win32"?"chrome.exe":"google-chrome"}function Ps(){if(process.env.KANE_CLI_CHROME_PATH)return yt(process.env.KANE_CLI_CHROME_PATH);let e=_e();if(($e[e]??$e.linux).some(n=>yt(n)))return!0;let r=e==="win32"?"chrome.exe":"google-chrome",s=e==="win32"?"where":"which";try{return Cs(s,[r],{stdio:"ignore"}).status===0}catch{return!1}}function Ts(){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 Ls(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 Os(e){return new Promise(t=>{let r=Es({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 Ds(){for(let e=et;e<=tt;e++)if(!await Os(e))return e;throw new Error(`All CDP ports ${et}-${tt} are in use. Close other Chrome instances.`)}async function js(e,t=15e3){let r=Date.now(),s=`http://127.0.0.1:${e}/json/version`;for(;Date.now()-r<t;){try{if((await D(s)).ok)return`http://127.0.0.1:${e}`}catch{}await new Promise(n=>setTimeout(n,200))}throw new Error(`Chrome CDP not ready after ${t}ms on port ${e}`)}async function Tr(e){let t=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(t!=null&&As.has(t.toLowerCase()))&&!Ps())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 Ne(Ts());let s=_e(),n=await Ds(),o=xs(),a=Ls({port:n,...e});e.startUrl&&a.push(e.startUrl);let l=Pr(o,a,{stdio:"ignore",detached:!0});l.unref();let i=await new Promise((m,p)=>{l.on("error",h=>{p(new Error(`Failed to launch Chrome: ${h.message}. Is Chrome installed at ${o}?`))}),l.on("close",h=>{h!==null&&h!==0&&p(new Error(`Chrome exited during startup with code ${h}`))}),js(n).then(m,p)});return{process:l,port:n,cdpEndpoint:i,kill(){try{if(l.pid)if(s==="win32")Pr("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 Lr(e){if(e.cft)return{instance:null,tempDir:null};if(e.wsEndpoint)return{wsEndpoint:e.wsEndpoint,instance:null,tempDir:null};if(e.cdpEndpoint){let n=await D(`${e.cdpEndpoint}/json/version`);if(!n.ok)throw new Error(`CDP endpoint not reachable: ${e.cdpEndpoint} (${n.status})`);return{cdpEndpoint:e.cdpEndpoint,instance:null,tempDir:null}}let t,r=null;if(e.config.chrome_profile_path)t=e.config.chrome_profile_path.replace("~",process.env.HOME??"~");else{r=Us(Ns($s(),"kane-clean-")),t=r;let n=r;Le("tempDir",()=>{try{Fs(n,{recursive:!0,force:!0})}catch{}})}let s=await Tr({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 Or(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 Ms,readFileSync as jr,existsSync as Ur}from"fs";import{join as Bs}from"path";function Dr(e,t){if(!Ur(e))return{};let r={},s;try{s=Ms(e).filter(n=>n.endsWith(".json")).sort()}catch{return{}}for(let n of s)try{let o=jr(Bs(e,n),"utf-8"),a=JSON.parse(o);if(a&&typeof a=="object"){for(let[l,i]of Object.entries(a))if(i&&typeof i=="object"&&"value"in i){let m=i;r[l]={value:m.value,secret:m.secret??!1,syntax:m.syntax??`{{${l}}}`}}}}catch{t?t("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:n}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${n}
18
+ `)}return r}function Fr(e){if(!Ur(e))throw new Error(`Variables file not found: ${e}`);let t=jr(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 Nr(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=Dr(e,r),n=Dr(t,r);return{...s,...n}}var fe=class{constructor(t){this.baseUrl=t}async pushSecret(t){let r=Te(t.username,t.accessKey),s=await D(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:r,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:t.secretKey,secretValue:t.secretValue,orgId:t.orgId,username:t.username,scope:"user",type:"user",accessKey:t.accessKey})});if(!s.ok)throw new Error(`Push secret failed: ${s.status} ${await s.text()}`)}static extractVariableKeys(t){let r=t.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),s=new Set;for(let n of r)s.add(n[1]);return[...s]}};var he=class extends $t{constructor(t,r,s){super(t,{username:r,accessKey:s})}async upsertVariable(t){let r=t.environmentId??0,s=await D(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:t.name,value:String(t.value),type:"variable",value_type:"string",is_persist:t.isPersist??!1,environment_id:r})});if(s.ok)return{id:(await s.json()).id??0};if(s.status!==409&&s.status!==422)return{id:0};if(!(await D(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(t.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(t.value),value_type:"string",type:"variable",environment_id:r})})).ok)return{id:0};let o=await D(`${this.baseUrl}/v1/variables/${encodeURIComponent(t.name)}?environment_id=${r}`,{method:"GET",headers:this.headers()});return o.ok?{id:(await o.json()).data?.id??0}:{id:0}}};function Mr(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 Br(e){let t=$r(e.globalDir,e.localDir,e.onLoadError),r=e.file?Fr(e.file):{},s=e.inline?Nr(e.inline):{},n={...t,...r,...s},o=Object.keys(n).length>0,{variables:a,objective:l}=o?de(n,e.objective):{variables:{},objective:e.objective},i=Object.entries(n).filter(([,p])=>p.secret),m=Object.entries(n).filter(([,p])=>!p.secret);return{raw:n,auteur:a,auteurObjective:l,secretEntries:i,nonSecretEntries:m}}async function Vr(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 Vs,existsSync as Hs}from"fs";function St(e){if(!Hs(e))return null;try{return Vs(e,"utf-8").trim()||null}catch{return null}}import{writeFileSync as Ks,mkdirSync as qs}from"fs";import{dirname as Hr}from"path";function vt(e){let t=ae(e.sourcePath);try{qs(Hr(t),{recursive:!0})}catch(s){return process.stderr.write(`
19
+ \u26A0 Failed to create output directory.
20
+ ${s.message}
21
+ Path: ${Hr(t)}
22
+
23
+ `),t}let r={commit_id:e.commitId};e.testId!==void 0&&(r.test_id=e.testId),e.testcaseId!==void 0&&(r.testcase_id=e.testcaseId),e.projectId!==void 0&&(r.project_id=e.projectId),e.folderId!==void 0&&(r.folder_id=e.folderId),e.orgId!==void 0&&(r.org_id=e.orgId),e.sessionName!==void 0&&(r.session_name=e.sessionName),e.plan!==void 0&&(r.plan=e.plan);try{Ks(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 Gs=()=>{};async function Kr(e,t,r){let s=t.log??Gs,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),plan:e.session.plan??void 0})}catch(i){s("error","FINALIZE_META_WRITE_ERROR","meta.json write failed",{error:String(i)})}if(o?.codeExportDir)try{let i=e.tuiConfig.code_export?.language??"python";lt(o.codeExportDir,nt(r.sourcePath,"playwright",i))}catch(i){s("error","FINALIZE_CODE_COPY_ERROR","code-export copy failed",{error:String(i)})}}else if(e.session.recorder?.lastWrittenPath){let i=e.session.recorder.lastWrittenPath,m=e.session.getFlows(),p=m.map((b,I)=>({index:I+1,heading:`Step ${I+1}`,headingLine:0,body:{kind:"objective",text:b.objective}})),h=m.map((b,I)=>({rootStepIndex:I+1,status:b.status==="passed"?"passed":b.status==="failed"?"failed":"skipped",duration_s:b.duration,reason:b.reason})),C=h.some(b=>b.status==="failed")?"failed":"passed";try{l=it({sourcePath:i,title:e.session.sessionName??"Session",rootSteps:p,outcomes:h,overallStatus:C,startedISO:e.session.startedAt,durationS:h.reduce((b,I)=>b+(I.duration_s??0),0),sessionId:e.session.sessionId})}catch(b){s("error","FINALIZE_TUI_RESULT_MD_ERROR","TUI _Result.md write failed",{error:String(b)})}try{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,plan:e.session.plan??void 0})}catch(b){s("error","FINALIZE_TUI_META_WRITE_ERROR","TUI meta.json write failed",{error:String(b)})}if(o?.codeExportDir)try{let b=e.tuiConfig.code_export?.language??"python";lt(o.codeExportDir,nt(i,"playwright",b))}catch(b){s("error","FINALIZE_TUI_CODE_COPY_ERROR","TUI code-export copy failed",{error:String(b)})}e.session.recorder.lastCollisionSuffixed&&process.stderr.write(`Saved to ${i} (renamed: ${e.session.sessionName}_test.md already existed)
30
+ `)}try{t.runCleanup?.()}catch(i){s("error","FINALIZE_CLEANUP_ERROR","Cleanup hook threw",{error:String(i)})}try{await e.session.finish("complete")}catch(i){s("error","FINALIZE_SESSION_FINISH_ERROR","session.finish threw",{error:String(i)})}return{uploadResult:o,feedbackChoice:a,resultMdPath:l}}import{readFileSync as Gr,writeFileSync as zr,existsSync as Wr}from"fs";function qr(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=zs(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 zs(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 Ws(e){if(!(!e.shouldReplaceLocalOutput||!e.resolvedTest||!e.sourcePath||!e.stepRunRecords||!e.outcomes||!e.overallStatus))return async()=>{er({resolvedTest:e.resolvedTest,sessionDir:e.session.sessionDir,stepRunRecords:e.stepRunRecords,outcomes:e.outcomes,overallStatus:e.overallStatus,startedISO:e.startedISO??new Date().toISOString(),durationS:e.durationS??0,sessionId:e.session.sessionId,commitId:e.fromCommitId??"",tmsIds:e.tmsIds??{},codeExportDir:e.codeExportDir}),ot(se(e.sourcePath));let t=new Set;for(let r of e.resolvedTest.steps)if(r.trace.length>1){let s=ve(r.trace);if(t.has(s))continue;t.add(s),Wr(`${s}.staging`)&&ot(s)}}}function Qs(e){if(!(!e.shouldCommit||e.isFirstRun||!e.tmsBaseUrl||!e.testId||!e.fromCommitId||!e.newCommitId||!e.basicAuth||!e.resolvedTest||!e.decisions))return async()=>{let t=qr(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 gr({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(Gr(n,"utf8"));o.commit_id=e.newCommitId,zr(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 Js(e){if(!(!e.isFirstRun||!e.sourcePath))return async t=>{if(!e.sourcePath)return;let r=ae(e.sourcePath);try{let s=Wr(r)?JSON.parse(Gr(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),zr(r,JSON.stringify(s,null,2)+`
33
+ `,"utf8")}catch(s){process.stderr.write(`warn: failed to update meta.json after endTest: ${s.message}
34
+ `)}}}function Qr(e){let t=z(e.env),{session:r,auth:s}=e,n=s.basicAuth?{username:s.basicAuth.username,accessKey:s.basicAuth.access_key}:s.token,o=s.resolvedCreds?.username??s.basicAuth?.username??"",a=s.resolvedCreds?.access_key??s.basicAuth?.access_key??"",l=s.resolvedCreds?.org_id??0,i=s.resolvedCreds?.user_id??0,m=[];for(let I of Object.keys(r.auteurVariables))I.startsWith("secrets.user.")&&m.push({key_name:I.replace("secrets.user.",""),scope:"user"});let h=r.getContext().prior_runs.map(I=>I.status),C=r.auteurVariables,b=Object.keys(C).length>0;return{controllerBaseUrl:t.controllerBaseUrl,tmsBaseUrl:t.tmsBaseUrl,auth:n,authResolver:s.resolver,sessionId:r.sessionId,sessionDir:r.sessionDir,testId:r.testId,commitId:r.sessionId,projectId:e.projectId,folderId:e.folderId,firstObjective:r.firstObjective??"KaneAI Test",firstUrl:r.firstUrl??"",runDirs:r.getRunDirs(),runObjectives:r.getRunObjectives(),runMetadata:r.getRunMetadata(),startedAt:r.startedAt,endedAt:new Date().toISOString(),totalSteps:e.totalSteps,totalDuration:e.totalDuration,runStatuses:h,orgId:l,userId:i,tmsUsername:o,tmsAccessKey:a,screenshotBaseUrl:r.screenshotBaseUrl,screenshotExtMap:e.screenshotExtMap,shareApiBaseUrl:t.shareApiBaseUrl,variables:b?C:void 0,variableIds:e.variableIds,secrets:m,codeExport:e.codeExport,onProgress:e.onProgress,log:e.log,shouldUploadArtifacts:e.shouldUploadArtifacts,shouldReplaceLocalOutput:e.shouldReplaceLocalOutput,shouldCommit:e.shouldCommit,isFirstRun:e.isFirstRun,onAtomicReplace:Ws(e),onCommitLock:Qs(e),onFinalizeSuccess:Js(e)}}var Jr=["python","javascript"];function Ys(e){if(e!==void 0){if(!Jr.includes(e))throw new Error(`--code-language must be one of: ${Jr.join(", ")} (got "${e}")`);return e}}function Yr(e,t){let r=Ys(e.codeLanguage);return{enabled:e.codeExport??t.enabled,language:r??t.language,skipValidation:e.skipCodeValidation??t.skip_validation}}async function Zr(e){try{let r=await new Mt(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 Zs=null,Xs=()=>Zs??=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 Xs();if(n)try{let i=await n(t.buffer).webp({quality:80}).toBuffer();r=new Uint8Array(i)}catch(i){r=new Uint8Array(t.buffer),s="image/png",this.log?.("warn","SCREENSHOT_CONVERT_FAILED","WebP conversion failed, using PNG",{operation_id:t.operationId,error:i instanceof Error?i.message:String(i)})}else r=new Uint8Array(t.buffer),s="image/png";let o=s==="image/webp"?"webp":"png",a=`test_screenshots/untagged_screenshot/${t.operationId}.${o}`,l=`${this.sas.base_url}/${this.sas.container}/${a}?${this.sas.sas_token}`;for(let i=0;i<=this.maxRetries;i++)try{let m=await D(l,{method:"PUT",headers:{"Content-Type":s,"x-ms-blob-type":"BlockBlob"},body:r});if(m.ok){this.uploadedExt.set(t.operationId,o);return}if(i<this.maxRetries){await this.backoff(i);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed after retries",{operation_id:t.operationId,status:m.status,attempts:this.maxRetries+1})}catch{if(i<this.maxRetries){await this.backoff(i);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed (network error)",{operation_id:t.operationId,error:"network",attempts:this.maxRetries+1})}}backoff(t){let r=t===0?1e3:3e3;return new Promise(s=>setTimeout(s,r))}getExt(t){return this.uploadedExt.get(t)??"png"}getExtMap(){return this.uploadedExt}isNearExpiry(){if(!this.sas.expiry)return!1;let t=new Date(this.sas.expiry).getTime();return Date.now()>t-5*6e4}};var ke=class{config;buffer=[];stepBuffer=new Map;flushTimer=null;currentRunIndex=null;stopped=!1;_droppedBatches=0;_droppedEntries=0;constructor(t){this.config=t}start(){if(this.flushTimer)return;let t=this.config.flushIntervalMs??5e3;this.flushTimer=setInterval(()=>{this.flush().catch(()=>{})},t),this.flushTimer.unref&&this.flushTimer.unref()}setRunIndex(t){this.currentRunIndex=t}log(t,r,s,n={}){if(this.stopped)return;let o=this.buildEntry(t,r,s,n);this.buffer.push(o)}logStep(t,r,s,n={}){if(this.stopped)return;let o=this.buildEntry("debug",r,s,n);o.run_index=t,this.stepBuffer.has(t)||this.stepBuffer.set(t,[]),this.stepBuffer.get(t).push(o)}escalate(t){let r=this.stepBuffer.get(t);r&&r.length>0&&this.buffer.push(...r),this.stepBuffer.delete(t)}discardSteps(t){this.stepBuffer.delete(t)}async flush(){if(this.buffer.length===0)return;let t=this.buffer.splice(0),r=null;try{r=await this.config.getToken()}catch{this.buffer.unshift(...t);return}let s={"Content-Type":"application/json"};r&&(s.Authorization=`Bearer ${r}`);let n=JSON.stringify(t);for(let o=0;o<3;o++){try{let a=new AbortController,l=setTimeout(()=>a.abort(),1e4),i=await D(this.config.proxyUrl,{method:"POST",headers:s,body:n,signal:a.signal});if(clearTimeout(l),i.ok)return}catch{}o<2&&await new Promise(a=>setTimeout(a,1e3*Math.pow(2,o)))}this._droppedBatches++,this._droppedEntries+=t.length}get droppedBatches(){return this._droppedBatches}get droppedEntries(){return this._droppedEntries}async shutdown(){this._droppedBatches>0&&this.log("warn","LOG_DROPS",`Dropped ${this._droppedEntries} entries in ${this._droppedBatches} batches`,{dropped_batches:this._droppedBatches,dropped_entries:this._droppedEntries}),this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),await this.flush()}shutdownSync(){this.stopped=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}get bufferSize(){return this.buffer.length}stepBufferSize(t){return this.stepBuffer.get(t)?.length??0}buildEntry(t,r,s,n){return{hostname:"kane-cli",service:"kane-cli",ddsource:"kane-cli",ddtags:`version:${this.config.device.cli_version}`,level:t,event:r,message:s,session_id:this.config.sessionId,run_index:r.startsWith("tcg_")?null:this.currentRunIndex,identity:this.config.identity,device:this.config.device,context:n,timestamp:new Date().toISOString()}}};import{platform as en,arch as tn}from"os";function Xr(e){let t={proxyUrl:Nt,sessionId:e.sessionId,identity:e.identity,device:{cli_version:Ft,platform:en(),arch:tn()},getToken:e.getToken};return new ke(t)}import{execSync as rn}from"child_process";import{readFileSync as sn}from"fs";import{createHash as nn}from"crypto";import{hostname as on,platform as an,arch as ln}from"os";var Be=null;function es(){return Be||(Be=cn(),Be)}function cn(){let e=an();if(e==="darwin")try{let s=rn("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=sn("/etc/machine-id","utf-8").trim();if(r)return r}catch{}let t=`${on()}:${e}:${ln()}`;return nn("sha256").update(t).digest("hex").slice(0,32)}async function un(e){try{let t=z(e.env),s=await new zt(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 dn(e){if(e.session.hasRemoteLogger||!e.tmsCreds)return null;let t=e.tmsCreds,r=Xr({sessionId:e.session.sessionId,identity:{org_id:String(t.org_id??""),user_id:String(t.user_id??""),machine_id:es(),email:t.email??null,email_domain:t.email_domain??"unknown",user_type:t.user_type??"unknown",env:e.env,plan:t.plan??"unknown"},getToken:e.getToken});return e.session.setRemoteLogger(r),r.start(),r}async function _t(e){let[t,r]=await Promise.allSettled([e.skipScreenshotQueue?Promise.resolve(null):un({env:e.env,auth:e.auth,session:e.session,log:e.log}),dn({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 Rt(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 wt(e.env,e.tmsCreds,r,t);return It(s,t),s}case"login":case"switch":{let r=t.state.identityServicesRef.current;r&&(await Rt(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 wt(e.env,n,s,t);return It(o,t),o}case"logout":{let r=t.state.identityServicesRef.current;return r&&(await Rt(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 Rt(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 wt(e.env,s,o,t);return It(a,t),a}}}async function wt(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}:_t({env:e,tmsCreds:t,resolver:r,auth:a,getToken:()=>s.auth.getToken(),session:s.getSession(),log:s.log,skipScreenshotQueue:s.options?.skipScreenshotQueue})}function It(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:m,environment:p,envConfig:h,profile:C,model:b,creds:I,configStore:R,session:c}=e,x=!1,f=await bn(s,l,o,{resolvedAuth:i,tmsBaseUrl:h.tmsBaseUrl},c.sessionId,r);if(f.abort)return{overallStatus:"failed",exitCode:f.abort.exitCode,outputDir:se(s),durationS:0,uploadResult:null};let P=f.lockAcquired,_=!1,L=!1,Q=!1;P&&t.onLockState({phase:"acquired",scope:"preemptive"}),c.start({model:b,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 _t({env:p,tmsCreds:i.resolvedCreds??null,resolver:i.resolver,auth:be,getToken:async()=>i.token??null,session:c,log:(d,S,y,g)=>c.log(d,S,y,g),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{Xt(o.name)}catch(u){return process.stderr.write(`error: ${u.message}
35
+ `),{overallStatus:"failed",exitCode:2,outputDir:se(s),durationS:0,uploadResult:null}}c.setSessionName(o.name)}let Ge={};for(let[u,d]of Object.entries(l.rootGlobal))He.includes(u)||(Ge[u]=d);for(let[u,d]of Object.entries(m))He.includes(u)||d!==void 0&&(Ge[u]=d);let K={...l.chrome};for(let u of He){let d=m[u];d!==void 0&&(K[u]=d)}let ns={...Ge,...K};c.setResolvedGlobal(ns);let kt=I.getActiveProfile()??"default",Ct=I.getDefaultEnv(),{rehydrateIfStale:os}=await import("./profile-sync-DTTRRIVP.js");os(I,R,kt,Ct);let B=R.load(),q=B.project_id??null,Ce=B.folder_id??null;if(i.basicAuth){let u=await Gt({creds:I,config:R,profile:kt,env:Ct,tmsCreds:i.basicAuth,isLocal:!!o.local,log:(d,S,y,g)=>c.log(d,S,y,g),onAnnounce:e.onAnnounce});if(u.status==="ok")q=u.projectId,Ce=u.folderId,B=R.load(),a&&u.autoDefaulted&&process.stdout.write(qt(u.autoDefaulted));else if(u.status==="cancelled"){process.stderr.write(`error: project/folder configuration failed. See remediation above, or use --local.
36
+ `);let{shutdown:d}=await import("./exit-manager-V2NW7A7U.js");return d(2,"project/folder gate failed"),{}}}let J;try{J=await Lr({config:{chrome_profile_path:K.chrome_profile??null,window_size:{width:1920,height:1080}},startUrl:ue,headless:K.headless??!1,wsEndpoint:K.ws_endpoint,cdpEndpoint:K.cdp_endpoint})}catch(u){return process.stderr.write(`error: Chrome launch failed: ${u.message}
37
+ `),await c.finish("complete"),{overallStatus:"failed",exitCode:2,outputDir:se(s),durationS:0,uploadResult:null}}let Ee=J.instance;Ee&&r.register("chrome",()=>{try{Ee.kill()}catch{}});let F=null,Et=J.cdpEndpoint??K.cdp_endpoint;if(Et&&!K.ws_endpoint&&!K.headless)try{F=Er({headless:K.headless??!1,cdpEndpoint:Et,chromePid:Ee?.process.pid}),F&&r.register("marker-overlay",()=>F.kill())}catch(u){c.log("warn","OVERLAY_SPAWN_FAILED","Marker overlay spawn failed",{error:String(u)})}i.resolvedCreds?.org_id!==void 0&&c.setOrgId(String(i.resolvedCreds.org_id));let ne=Br({objective:"",globalDir:Ve(Xe,"variables"),localDir:Ve(n,".testmuai","variables"),file:o.variablesFile,inline:o.variables}),is=l.rootGlobal.variables??{},V=fn(ne.raw,is);c.setAuteurVariables(V.auteur);let At=St(Ve(Xe,"global-memory.md"))??void 0,xt=St(Ve(n,".testmuai","context.md"))??void 0;o.local?process.stderr.write(`info: --local \u2014 KaneAI upload skipped
38
+ `):i.basicAuth?q||process.stderr.write(`warn: KaneAI upload skipped \u2014 no project configured.
39
+ `):process.stderr.write(`warn: KaneAI upload skipped \u2014 TMS credentials could not be resolved.
40
+ Run 'kane-cli login' (OAuth) or 'kane-cli config set-username/set-access-key' (basic auth).
41
+ `);let ye=!o.local&&!!i.basicAuth&&q!=null;if(c.log("info","PIPELINE_GATE_STATE","Initial gate state (run-start)",{phase:"run-start",shouldUploadArtifacts:ye,lockHeld:P,isFirstRun:f.isFirstRun,hasAuth:f.hasAuth}),ye&&f.testId==null){let u=z(p);try{let d=await Zr({tmsBaseUrl:u.tmsBaseUrl,auth:i.basicAuth,objective:l.steps[0].objective,url:"",projectId:q,folderId:Ce??"",hasCustomProfile:!!K.chrome_profile,log:(S,y,g,v)=>c.log(S,y,g,v)});d&&c.setTestId(d)}catch(d){process.stderr.write(`warn: ATM test creation failed: ${d.message}
42
+ `)}}else f.testId&&c.setTestId(f.testId);let Ae={};if(i.basicAuth&&!o.local&&(V.secretEntries.length>0||V.nonSecretEntries.length>0))try{Ae=await Vr({variables:V,auth:i.basicAuth,orgId:String(i.resolvedCreds?.org_id??""),env:p,localMode:!!o.local,log:(u,d,S,y)=>c.log(u,d,S,y)})}catch(u){process.stderr.write(`warn: variable/secret push failed: ${u.message}
43
+ `)}let ze=new Map;for(let[u,d]of V.nonSecretEntries)ze.set(u,d.value);let We=new Map;for(let[u,d]of V.secretEntries)We.set(u,d.value);async function Qe(u){if(!i.basicAuth||o.local)return;let d=[],S=[];for(let[g,v]of Object.entries(u))if(v.secret){if(We.get(g)===v.value)continue;S.push([g,v])}else{if(ze.get(g)===v.value)continue;d.push([g,v])}if(d.length===0&&S.length===0)return;let y=z(p);if(d.length>0){let g=new he(y.tmsBaseUrl,i.basicAuth.username,i.basicAuth.access_key);for(let[v,w]of d)try{let E=await g.upsertVariable({name:v,value:w.value});Ae[v]=E.id,ze.set(v,w.value),c.log("info","VAR_PUSH_STEP","Variable updated mid-run",{name:v})}catch(E){c.log("warn","VAR_PUSH_STEP_FAILED","Mid-run variable push failed",{name:v,error:String(E)})}}if(S.length>0){let g=new fe(y.secretsBaseUrl);for(let[v,w]of S)try{await g.pushSecret({secretKey:v,secretValue:w.value,username:i.basicAuth.username,accessKey:i.basicAuth.access_key,orgId:String(i.resolvedCreds?.org_id??"")}),We.set(v,w.value),c.log("info","SECRET_PUSH_STEP","Secret updated mid-run",{name:v})}catch(E){c.log("warn","SECRET_PUSH_STEP_FAILED","Mid-run secret push failed",{name:v,error:String(E)})}}}let Se=ce?(u,d,S)=>{if(!(P||f.isFirstRun))return;let y=$+d;Ir(c.sessionDir,y,u,ce,(g,v,w,E)=>c.log(g,v,w,E),S)}:void 0,Pt=l.rootTitle??l.rootSteps[0]?.heading??mn(s),as=Object.keys(V.raw).length>0?de(V.raw,Pt).objective:Pt;c.setFirstRun(as,ue);let te=new Fe(l),Je=new Date().toISOString(),ls=Date.now(),cs=typeof o.maxSteps=="string"&&o.maxSteps!==""?parseInt(o.maxSteps,10):void 0;function Tt(u,d){let S=l.steps[u],y=rs(S.config,m),g=ge(ne.raw,y.variables,S.objective);return Or({objective:g.objective,url:u===0?ue:void 0,model:b,chrome:J,auth:i,sessionId:c.sessionId,runIndex:d,windowSize:{width:1920,height:1080},maxSteps:y.max_steps??cs??30,headless:K.headless??!1,variables:Object.keys(g.variables).length>0?g.variables:void 0,globalContext:y.global_context??At,localContext:y.local_context??xt,sessionContext:c.getContext()})}function Lt(u){let S=l.steps[u].trace[0].stepIndex,y=l.rootSteps.find(v=>v.index===S);l.steps.slice(0,u).some(v=>v.trace[0].stepIndex===S)||t.onAgentEvent({type:"test_md_step_start",step_index:S,heading:y.heading,ref:y.body.kind==="import_ref"?{kind:"import",label:y.body.path}:null})}function Ye(u,d,S,y,g,v){let w=l.steps[u],E=w.trace[0].stepIndex,W=!l.steps.slice(u+1).some(O=>O.trace[0].stepIndex===E),G=S?.status==="passed"?"passed":"failed",U=S?.reason??g??void 0,H=S?.duration??v,{continueOverall:M}=te.recordStep(w,{status:G,duration_s:H,reason:U}),Y=rs(w.config,m),Z=ge(ne.raw,Y.variables,w.objective).objective;if(S){let O=_r(S,d,y);c.addRunResult(kr(S,Z,d,O),S.total_runs)}else c.addRunResult({index:d,objective:Z,status:G,summary:"",context:{memory:{},variables:{},pointer:""}},1);if(W||!M){let O=te.snapshotOutcomes().find(k=>k.rootStepIndex===E);t.onAgentEvent({type:"test_md_step_end",step_index:E,status:O.status,duration_s:O.duration_s??0,ref_kind:O.refKind??null,inlined_count:O.inlinedCount??null,failed_sub_step_index:O.failedSubStepIndex??null})}return M}async function us(u){ar(u,l.steps.length);for(let d=0;d<u;d++){if(x)return{failedAt:d,cancelled:!0};let S=l.steps[d],y=f.decisions[d];if(y.kind!=="replay")return process.stderr.write(`error: runReplayPhase invoked on a non-replay decision at step ${d}
44
+ `),{failedAt:d,cancelled:!1};let g=c.nextRunIndex();$=g;let v=d===0?ue:void 0,w={width:B.window_size.width,height:B.window_size.height},E=ge(ne.raw,S.config.variables,S.objective),W=dt({step:S,decision:y,chrome:J,auth:i,sessionId:c.sessionId,runIndex:g,sessionDir:c.sessionDir,windowSize:w,forceNavigateUrl:v,sessionContext:c.getContext(),variables:Object.keys(E.variables).length>0?E.variables:void 0});await Qe(E.raw),Lt(d);let G=Date.now(),U=null,H=null;try{let O=st(W,{environment:p});r.register("runner",()=>{rt()&&(x=!0);try{O.cancel()}catch{}}),F?.setRunActive(!0);try{for await(let k of O.events){if(t.onAgentEvent(k),k.type==="step_event"&&k.event==="reasoning"?F?.setStepText(k.detail):k.type==="step_end"&&(k.status==="passed"&&F?.setStepComplete(),Se&&Se(k.index,0,k.child_id)),k.type==="run_end"){U=k;break}if(k.type==="error"){H=k.message??"runner error";break}}try{O.cancel()}catch{}if(!U&&!H){let{code:k}=await O.exited;k!==0&&(H=`runner exited with code ${k}`)}}finally{F?.setRunActive(!1),r.cleanup("runner","Replay step complete")}}catch(O){H=O.message}if(x)return{failedAt:d,cancelled:!0};let M=Math.round((Date.now()-G)/1e3),Y=Ye(d,g,U,null,H,M);c.recordStepRun({testmdStepIndex:l.steps[d].flatIndex,runIndex:g,totalRunDirs:1});let Z=!!H||U?.status==="failed";if(lr(d,Z?"failed":"ok"),Z||!Y)return{failedAt:d,cancelled:!1}}return{failedAt:null,cancelled:!1}}let Ot=async()=>{if(P)return!0;let u=i.basicAuth;if(!u){let g=await i.resolver.resolve(!0);g?.username&&g?.access_key&&(u={username:g.username,access_key:g.access_key},i.basicAuth=u)}if(!f.testId||!f.fromCommitId||!u)return process.stderr.write(`error: cannot acquire lock \u2014 missing required state
45
+ `),!1;let d=c.sessionId,S=o.onLockConflict??l.rootGlobal.on_lock_conflict??"readonly",y=await ss({tmsBaseUrl:h.tmsBaseUrl,testId:f.testId,fromCommitId:f.fromCommitId,newCommitId:d,basicAuth:u,onLockConflict:S});return y==="ok"?(P=!0,f.newCommitId=d,c.log("info","MID_RUN_LOCK_ACQUIRED","Mid-run lock acquired",{test_id:f.testId}),a&&t.onLockState({phase:"acquired",scope:"mid_run"}),ht({baseUrl:Ke(h.tmsBaseUrl),testId:f.testId,auth:qe(u),lifecycle:r}),!0):(c.log("error","MID_RUN_LOCK_CONFLICT","Mid-run lock acquisition failed",{reason:y}),a&&t.onLockState({phase:"conflict",scope:"mid_run",reason:y}),process.stderr.write(`error: mid-run lock acquisition failed (${y})
46
+ `),!1)};if(a){let u=o.author===!0;u&&(ut(),c.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let{authorBoundary:d,cancelledInPhase:S,shrinkCount:y}=await mr({decisions:f.decisions,forceAuthor:u,hasRetry:o.retry===!0||o.retryCount!==void 0,maxShrinks:o.retryCount!==void 0?parseInt(o.retryCount,10):Re.maxShrinks,runReplayPhase:us,session:c,accumulator:te,acquireLockIfNeeded:Ot});if(Q=y>0,y>0&&(c.log("info","RETRY_TRIGGERED","Retry loop triggered",{shrink_count:y,final_author_boundary:d}),t.onRetryAttempt({shrink_count:y,final_author_boundary:d,complete_reauthor:d===0})),d===0&&y>0&&c.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback",{shrink_count:y}),!S&&d>=0)for(let g=d;g<l.steps.length;g++){let v=l.steps[g];if(!te.shouldRunFlatStep(v))continue;Lt(g),_=!0;let w=c.nextRunIndex();$=w,await Qe(ge(ne.raw,v.config.variables,v.objective).raw);let E=Tt(g,w),W=Date.now(),G=null,U=null,H=null,M=!1,Y=0;try{let k=st(E,{environment:p});r.register("runner",()=>{rt()&&(x=!0);try{k.cancel()}catch{}}),F?.setRunActive(!0);try{for await(let T of k.events){if(t.onAgentEvent(T),T.type==="bifurcation"){let A=T.count??T.flows?.length??0;(T.is_single_flow??A<=1)||(H=T.flows??null,M=!0,Y=0)}else if(T.type==="run_start"&&M)Y++;else if(T.type==="step_event"&&T.event==="reasoning")F?.setStepText(T.detail);else if(T.type==="step_end"&&(T.status==="passed"&&F?.setStepComplete(),Se)){let A=M?Math.max(0,Y-1):0;Se(T.index,A,T.child_id)}if(T.type==="run_end"){G=T;break}if(T.type==="error"){U=T.message??"runner error";break}}try{k.cancel()}catch{}}finally{F?.setRunActive(!1),r.cleanup("runner","Step complete")}}catch(k){U=k.message}let Z=Math.round((Date.now()-W)/1e3),O=Ye(g,w,G,H,U,Z);if(c.recordStepRun({testmdStepIndex:l.steps[g].flatIndex,runIndex:w,totalRunDirs:G?.total_runs??1}),!O||x)break}}else{let{effectiveDecisions:u}=await import("./effective-decisions-DRM3JSR4.js"),{decideRetry:d}=await import("./replay-policy-6USQBT3E.js"),S=o.retry===!0||o.retryCount!==void 0,y=o.retryCount!==void 0?parseInt(o.retryCount,10):Re.maxShrinks,g=o.author===!0;g&&(ut(),c.log("info","FORCE_AUTHOR_RUN","--author flag set; walker bypassed"));let v=g?0:je(f.decisions),w=0,E=null,W=f.decisions.filter(M=>M.kind==="replay").length,G=f.decisions.length-W,U=[];o.push&&U.push("--push"),S&&U.push("--retry"),o.retryCount!==void 0&&U.push(`--retry-count=${o.retryCount}`),g&&U.push("--author");let H={source:s,steps:{total:f.decisions.length,replay:W,author:G},model:b,viewport:{width:B.window_size.width,height:B.window_size.height},chrome:J.cdpEndpoint??J.wsEndpoint??"managed",session:c.sessionName??"ephemeral",variables:{count:Object.keys(V.raw).length,secrets:Object.values(V.raw).filter(M=>M.secret).length,names:Object.keys(V.raw)},flags:U,mode:m.mode??"testing"};for(;;){let M=c.snapshot(),Y=te.snapshot(),Z=u(f.decisions,v,g);if(w>=1){let A=v===0?`\u21BB Complete re-author \u2014 retry budget exhausted (${w}/${y})`:`\u21BB Retry ${w}/${y} \u2014 replay 0..${v-1}, author ${v}..${f.decisions.length-1}
47
+ reason: replay miss at step ${(E??0)+1}`;process.stderr.write(A+`
48
+ `)}let O=w>=1&&v>0&&E!==null?{startIdx:0,endIdx:E,count:E}:void 0;F?.setRunActive(!0);let k=await vn({decisions:Z,resolved:l,session:c,accumulator:te,tuiConfig:B,globalConfig:H,buildStepConfigAt:Tt,buildReplayConfig:A=>{let X=f.decisions[A];if(X.kind!=="replay")throw new Error("expected replay decision at index "+A);let re=l.steps[A];return dt({step:re,decision:X,chrome:J,auth:i,sessionId:c.sessionId,runIndex:c.nextRunIndex(),sessionDir:c.sessionDir,windowSize:{width:B.window_size.width,height:B.window_size.height},forceNavigateUrl:A===0?ue:void 0,sessionContext:c.getContext(),variables:hn(ne.raw,re.config.variables,re.objective)})},onAnyAuthorStep:()=>{_=!0},onCancel:()=>{L=!0},topBannerModel:b,topBannerAuth:`${I.getActiveProfile()??"no profile"}/${p}`,spawnOpts:{environment:p,mode:m.mode??"testing",log:(A,X,re,Ze)=>c.log(A,X,re,Ze)},priorAttemptRollup:O,pushStepLevelDelta:(A,X)=>Qe(ge(ne.raw,A,X).raw),onSequencerStepEnd:(A,X,re,Ze)=>{let ps=Math.round((Date.now()-Ze)/1e3),fs=A.hadError?A.reason??"runner error":null,hs=Ye(X,re,A.runEnd,A.bifurcationFlows??null,fs,ps);return c.recordStepRun({testmdStepIndex:l.steps[X].flatIndex,runIndex:re,totalRunDirs:A.runEnd?.total_runs??A.bifurcationFlows?.length??1}),hs},screenshotDispatcher:Se,onReasoning:A=>F?.setStepText(A),onStepComplete:()=>F?.setStepComplete(),onSpawnStart:A=>{$=A},host:t});if(F?.setRunActive(!1),k.cancelled){r.cleanup("marker-overlay","user cancelled run"),r.cleanup("chrome","user cancelled run");break}if(k.failedAt===null)break;let T=d({failedAt:k.failedAt,shrinkCount:w,hasRetry:S,maxShrinks:y});if(T.kind==="fail"||!P&&!await Ot())break;c.rollback(M),te.rollback(Y),T.kind==="complete-reauthor"?v=0:v=T.newAuthorBoundary,w++,Q=!0,c.log("info","RETRY_TRIGGERED","Retry loop triggered (TTY)",{shrink_count:w,failed_at:E}),v===0&&c.log("info","COMPLETE_REAUTHOR_TRIGGERED","Complete reauthor fallback (TTY)",{shrink_count:w}),E=k.failedAt}}let N=te.finalize(),oe=Math.round((Date.now()-ls)/1e3),ds={session:c,resolvedAuth:i,chromeResult:J,chromeInstance:Ee??null,testId:c.testId??null,preparedVariables:V,variableIds:Ae,globalContext:At,localContext:xt,tuiConfig:B,env:p,localMode:!!o.local},ie=await Kr(ds,{performUpload:async()=>{if(!i.basicAuth)return null;let u=z(p),d=(_||o.push===!0)&&!L,S=(P||f.isFirstRun)&&!L&&N.overallStatus==="passed",y=ye&&(P||f.isFirstRun);c.log("info","PIPELINE_GATE_STATE","Derived gate state (finalize)",{phase:"finalize",shouldUploadArtifacts:ye,shouldUploadPipeline:y,shouldReplaceLocalOutput:d,shouldCommit:S,lockHeld:P,anyAuthorStepRan:_,cancelled:L,overallStatus:N.overallStatus});let g=Qr({session:c,env:p,auth:i,variables:V,variableIds:Ae,projectId:q,folderId:Ce,totalSteps:N.outcomes.length,totalDuration:oe,screenshotExtMap:ce?.getExtMap(),codeExport:Yr({codeExport:o.codeExport,codeLanguage:o.codeLanguage,skipCodeValidation:o.skipCodeValidation},B.code_export),onProgress:()=>{},log:(w,E,W,G)=>c.log(w,E,W,G),shouldUploadArtifacts:y,shouldReplaceLocalOutput:d,shouldCommit:S,isFirstRun:f.isFirstRun,resolvedTest:l,sourcePath:s,stepRunRecords:c.getStepRunRecords(),outcomes:N.outcomes,overallStatus:N.overallStatus,fromCommitId:f.fromCommitId,startedISO:Je,durationS:oe,tmsIds:{testId:f.testId??c.testId??void 0,testcaseId:f.testcaseId??c.testcaseId??void 0,projectId:q??void 0,folderId:Ce??void 0,orgId:c.orgId??void 0,sessionName:c.sessionName??Oe(s)},tmsBaseUrl:h.tmsBaseUrl,testId:f.testId??void 0,newCommitId:f.newCommitId??void 0,basicAuth:i.basicAuth??void 0,decisions:f.decisions,wantsPush:o.push===!0,retryTriggered:Q,forceAuthor:o.author===!0});f.newCommitId!=null&&(g.skipTmsFinalize=!0);let v=new tr(g);return a?await v.execute():await t.runUpload(v,w=>{if(w.testcaseId&&w.shareId&&q)return bt(u.testManagerUiUrl,q,w.testcaseId,w.shareId)})},runCleanup:()=>{r.cleanup("chrome","test.md run complete")},log:(u,d,S,y)=>c.log(u,d,S,y)},{overallStatus:N.overallStatus,outcomes:N.outcomes,sourcePath:s,title:l.rootTitle,rootSteps:l.rootSteps,startedISO:Je,durationS:oe,localMode:!!o.local,skipLocalWrites:!0});await yn(s,f,c,N.outcomes,N.overallStatus,Je,oe,ie.uploadResult,B,o,{resolvedAuth:i,tmsBaseUrl:h.tmsBaseUrl},P);let Dt=z(p),xe=ie.uploadResult?.testcaseId,Pe=xe&&ie.uploadResult?.shareId&&q?bt(Dt.testManagerUiUrl,q,xe,ie.uploadResult.shareId):void 0,jt={overallStatus:N.overallStatus,durationS:oe,decisions:f.decisions,outcomes:N.outcomes,cancelled:L,retryTriggered:Q,lockHeld:P,anyAuthorStepRan:_,isFirstRun:f.isFirstRun,wantsPush:o.push===!0,uploadResult:ie.uploadResult,shouldUploadArtifacts:ye,shouldReplaceLocalOutput:_&&!L,shouldCommit:(P||f.isFirstRun)&&!L&&N.overallStatus==="passed",shareUrl:Pe},{buildSummaryEvent:ms}=await import("./SummaryBox-O772FRGO.js");if(a?t.onAgentEvent(ms(jt)):await t.onSummary(jt),!a){let u=xe&&q?xr(Dt.testManagerUiUrl,q,xe):void 0;await t.onLinks({recordedTestPath:s,outputDir:se(s),shareableLink:Pe,testCaseLink:u,codeExportDir:ie.uploadResult?.codeExportDir})}return t.onAgentEvent({type:"test_md_done",overall_status:N.overallStatus,duration_s:oe,session_id:c.sessionId,...Pe?{share_url:Pe}:{}}),{overallStatus:N.overallStatus,exitCode:N.overallStatus==="passed"?0:1,outputDir:se(s),durationS:oe,uploadResult:ie.uploadResult}}function fn(e,t){let r={...e,...t},s=Object.keys(r).length>0?de(r,""):{variables:{},objective:"",keyMap:{}};return{raw:r,auteur:s.variables,auteurObjective:"",secretEntries:Object.entries(r).filter(([,n])=>n.secret),nonSecretEntries:Object.entries(r).filter(([,n])=>!n.secret)}}function ge(e,t,r){let s={...e,...t??{}};if(Object.keys(s).length===0)return{raw:s,variables:{},objective:r};let n=de(s,r);return{raw:s,variables:Mr(n.variables,n.objective),objective:n.objective}}function hn(e,t,r){let s=ge(e,t,r).variables;return Object.keys(s).length>0?s:void 0}function rs(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 gn(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}async function bn(e,t,r,s,n,o){let a=Qt(e),l=sr(t,ts(a)?a:null);ir(t,l);let i=ae(e),m=ts(i)?JSON.parse(pn(i,"utf8")):null,p=m?.testcase_id,h=m?.test_id,C=m?.commit_id,b=r.push===!0,I=r.retry===!0||r.retryCount!==void 0,R=r.author===!0;b&&!p&&process.stderr.write(`[--push] no meta.json yet \u2014 flag is a no-op on first run
49
+ `),R&&(p=void 0,h=void 0,C=void 0);let c=s.resolvedAuth.basicAuth;if(!c){let $=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&&(nr(l)||b);if(b&&!f)return process.stderr.write(`error: --push requires authenticated credentials for the lock API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
50
+ `),{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};if(I&&!f)return process.stderr.write(`error: --retry requires authenticated credentials for the lock API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
51
+ `),{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};if(R&&!x)return process.stderr.write(`error: --author requires authenticated credentials for the TMS API. Run 'kane-cli login' (OAuth) or pass --username/--access-key inline.
52
+ `),{resolved:t,decisions:l,testId:h,testcaseId:p,fromCommitId:C,newCommitId:null,isFirstRun:!1,hasAuth:x,canLock:f,lockAcquired:!1,abort:{exitCode:2}};let _=null,L=!1;if(P){_=n;let Q=r.onLockConflict??t.rootGlobal.on_lock_conflict??"readonly",$=await ss({tmsBaseUrl:s.tmsBaseUrl,testId:h,fromCommitId:C,newCommitId:_,basicAuth:c,onLockConflict:Q});if($==="ok")L=!0,ht({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 ss(e){let t=Ke(e.tmsBaseUrl),r=qe(e.basicAuth),s={baseUrl:t,testId:e.testId,fromCommitId:e.fromCommitId,newCommitId:e.newCommitId,auth:r},n=await pt(s);if(n.ok)return"ok";if(!(n.reason==="concurrent"||n.reason==="base_mismatch"))return process.stderr.write(`[lock] acquire failed: ${n.reason} (HTTP ${n.httpStatus}): ${n.message}
53
+ `),"abort";let a=n.reason==="concurrent"?"concurrent session":"base commit mismatch (pull latest)";if(e.onLockConflict==="fail")return process.stderr.write(`[lock] ${a}; aborting (--on-lock-conflict fail)
54
+ `),"abort";if(e.onLockConflict==="wait"){if(n.reason==="base_mismatch")return process.stderr.write(`[lock] base commit mismatch \u2014 pull latest; aborting
55
+ `),"abort";for(;;){process.stderr.write(`[lock] waiting (concurrent session)...
56
+ `),await new Promise(i=>setTimeout(i,3e4));let l=await pt(s);if(l.ok)return"ok";if(l.reason!=="concurrent")return process.stderr.write(`[lock] wait drifted to ${l.reason} (HTTP ${l.httpStatus}): ${l.message}; aborting
57
+ `),"abort"}}return process.stderr.write(`[lock] ${a} \u2014 running in readonly mode (no commit)
58
+ `),"readonly"}async function yn(e,t,r,s,n,o,a,l,i,m,p,h){let{decisions:C,testId:b,testcaseId:I,fromCommitId:R,newCommitId:c}=t;if(!(n==="passed")&&h&&b&&R&&c){process.stderr.write(`[lock] run failed (${n}); discarding new commit
59
+ `),await Sn(p,b,R,c),gt();return}gt()}async function Sn(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 br({baseUrl:Ke(e.tmsBaseUrl),testId:t,body:{commitId:s,fromCommitId:r},auth:qe(n)});o.ok||process.stderr.write(`warn: discardLock failed: ${o.reason} (HTTP ${o.httpStatus}): ${o.message}
60
+ `)}async function 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 m=e.decisions[s],p=e.resolved.steps[s],h=s;s++;let C=e.session.nextRunIndex();n=h,o=C,a=Date.now(),e.onSpawnStart?.(C),m.kind==="author"&&e.onAnyAuthorStep(),await e.pushStepLevelDelta(p.config.variables,p.objective);let b=m.kind==="replay"?e.buildReplayConfig(h):e.buildStepConfigAt(h,C),I=m.kind==="replay"?"md5-match":m.reason,R=p.config??{},c={};for(let[x,f]of Object.entries(R))f!=null&&x!=="variables"&&(c[x]=f);return{config:b,banner:{stepLabel:`Step ${h+1}/${e.decisions.length}`,objective:gn(p.objective,100)},mode:m.kind,modeReason:I,perStepOverrides:Object.keys(c).length>0?c:void 0}};return await e.host.runSteps({topBanner:{model:e.topBannerModel,auth:e.topBannerAuth},globalConfig:e.globalConfig,getNextStep:l,onStepEnd:i=>(i.status==="failed"&&n>=0&&e.decisions[n]?.kind==="replay"&&(t=n),e.onSequencerStepEnd(i,n,o,a)),onAllComplete:()=>{},onCancel:()=>{r=!0,e.onCancel()},spawnOpts:e.spawnOpts,priorAttemptRollup:e.priorAttemptRollup,screenshotDispatcher:e.screenshotDispatcher,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete}),{failedAt:t,cancelled:r}}export{_r as a,kr as b,Ne as c,mo as d,Tr as e,Er as f,Ir as g,bt as h,xr as i,Lr as j,Or as k,Mr as l,Br as m,Vr as n,St as o,Qr as p,Yr as q,Zr as r,_t as s,Ci as t,la as u,fn as v,ge as w,hn as x,rs as y};
@@ -0,0 +1,10 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ var v=()=>!!process.env.KANE_DEV_MODE,t=[],u=!1,f=null,c=null,a=null,i=null;function x(e){i=e}function m(){return i}function h(){return u}function y(e,r){t=t.filter(o=>o.name!==e),t.push({name:e,fn:r})}function R(e){t=t.filter(r=>r.name!==e)}function w(e,r){let o=t.find(n=>n.name===e);if(!o)return;t=t.filter(n=>n.name!==e);let s=!0;try{o.fn()}catch(n){s=!1,process.stderr.write(`[exit-manager] cleanup(${e}) failed: ${n instanceof Error?n.message:String(n)}
3
+ `)}r&&s&&v()&&process.stderr.write(`[exit-manager] cleanup(${e}): ${r}
4
+ `)}function l(e,r,o=!1){if(u){process.exit(f??e);return}if(u=!0,f=e,o&&i)try{i.log("error","CRASH",r),i.shutdownSync()}catch{}let s=[...t].reverse(),n=[];for(let g of s)try{g.fn(),n.push(g.name)}catch(d){process.stderr.write(`[exit-manager] cleanup(${g.name}) failed: ${d instanceof Error?d.message:String(d)}
5
+ `)}if(t=[],v()&&(process.stderr.write(`[exit-manager] shutdown(${e}): ${r}
6
+ `),n.length>0&&process.stderr.write(`[exit-manager] cleaned up: ${n.join(", ")}
7
+ `)),o&&a){try{a()}catch{}process.stderr.write(`
8
+ Kane CLI crashed unexpectedly: ${r}
9
+ `+(n.length>0?`Resources cleaned up (${n.join(", ")}).
10
+ `:"")),process.exit(e);return}if(c&&!o){c();return}process.exit(e)}function E(e){c=e}function $(e){a=e}var p=!1;function S(){p||(p=!0,process.on("SIGINT",()=>{l(130,"Received SIGINT",!0)}),process.on("SIGTERM",()=>{l(143,"Received SIGTERM",!0)}),process.on("uncaughtException",e=>{l(1,`Uncaught exception: ${e.message}`,!0)}),process.on("unhandledRejection",e=>{l(1,`Unhandled rejection: ${String(e)}`,!0)}))}function L(){t=[],u=!1,f=null,c=null,a=null,i=null,p=!1}export{x as a,m as b,h as c,y as d,R as e,w as f,l as g,E as h,$ as i,S as j,L as k};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as h}from"./chunk-NLCCBXXV.js";import{a as n}from"./chunk-RZ4F3BHX.js";var f=class extends h{constructor(e,t,s){super(e,{username:t,accessKey:s})}async listProjects(e){let t=[],s=!1;for await(let r of this.listProjectsStream({log:e})){if(e&&!s&&r.projects.length>0){let o=r.projects[0];e("info","PROJECT_SAMPLE","Project list sample",{project_id:o.project_id,name:o.name}),s=!0}t.push(...r.projects)}return t}async*listProjectsStream(e){let t=e?.perPage??200,s=e?.maxPages??100,r=e?.signal,o=e?.log,d=e?.name?.trim(),a=0;for(let i=1;i<=s;i++){if(r?.aborted)return;let g=`${this.baseUrl}/v1/projects?page=${i}&per_page=${t}&sort=created_at`;d&&(g+=`&filter[name]=${encodeURIComponent(d)}`);let p=AbortSignal.timeout(15e3),j=r?AbortSignal.any([r,p]):p,c;try{c=await n(g,{method:"GET",headers:this.headers(),signal:j})}catch(l){if(r?.aborted)return;if(i===1)throw l;o?.("warn","PROJECTS_STREAM_PARTIAL","stream stopped mid-page",{page:i,total_loaded:a,error:l instanceof Error?l.message:String(l)}),yield{page:i,projects:[],totalLoaded:a,done:!0};return}if(!c.ok){if(i===1)throw new Error(`listProjects ${c.status}: ${await c.text()}`);o?.("warn","PROJECTS_STREAM_PARTIAL","stream stopped on non-OK response",{page:i,status:c.status,total_loaded:a}),yield{page:i,projects:[],totalLoaded:a,done:!0};return}let m=(await c.json()).data??[];a+=m.length;let u=m.length<t;if(yield{page:i,projects:m,totalLoaded:a,done:u},u)return}o?.("warn","PROJECTS_STREAM_MAXPAGES","max pages reached",{max_pages:s,total_loaded:a}),yield{page:s,projects:[],totalLoaded:a,done:!0}}async getDefaultFolder(e){let t=await n(`${this.baseUrl}/v1/projects/${e}/folder/default`,{method:"GET",headers:this.headers()});if(!t.ok)throw new Error(`Get default folder failed: ${t.status} ${await t.text()}`);return(await t.json()).id}async listFolders(e){let t=await n(`${this.baseUrl}/v1/folder/entity/${e}`,{method:"GET",headers:this.headers()});if(!t.ok)throw new Error(`List folders failed: ${t.status} ${await t.text()}`);return(await t.json()).data??[]}async validateProjectFolder(e,t){let s;try{s=await n(`${this.baseUrl}/v1/folder/entity/${e}`,{method:"GET",headers:this.headers()})}catch{return{project:"error",folder:"error"}}if(s.status>=400&&s.status<500)return{project:"missing",folder:"missing"};if(!s.ok)return{project:"error",folder:"error"};let r;try{r=await s.json()}catch{return{project:"error",folder:"error"}}return{project:"ok",folder:(r.data??[]).some(a=>a.id===t)?"ok":"missing"}}async createProject(e,t=""){let s=await n(`${this.baseUrl}/v1/projects`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({name:e,description:t,tags:[],source:"KTM"})});if(!s.ok)throw new Error(`Create project failed: ${s.status} ${await s.text()}`);return{id:(await s.json()).id,name:e}}async createFolder(e,t,s=""){let r=await n(`${this.baseUrl}/v1/folder`,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({folders:[{name:t,description:s,entity_id:e,entity_type:"project"}]})});if(!r.ok)throw new Error(`Create folder failed: ${r.status} ${await r.text()}`);return{id:(await r.json()).id,name:t}}async createAtmTest(e,t){let s=t?`Bearer ${t}`:this.authHeader,r=await n(`${this.baseUrl}/kane-cli/v1/test`,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(`Create ATM test failed: ${r.status} ${await r.text()}`);let o=await r.json();if(!o.test_id)throw new Error("Create ATM test returned no test_id");return o.test_id}async endTest(e,t,s){let r=s?`Bearer ${s}`:this.authHeader,o=new URLSearchParams({commit_id:t.commit_id,time_taken:String(t.time_taken),steps_count:String(t.steps_count),commit_message:t.commit_message}),d={};t.objectives&&t.objectives.length>0&&(d.objectives=t.objectives);let a=await n(`${this.baseUrl}/kane-cli/v1/test/${e}?${o.toString()}`,{method:"DELETE",headers:{Authorization:r,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(d)});if(!a.ok)throw new Error(`End test failed: ${a.status} ${await a.text()}`);let i=await a.json();return{testcase_id:i.data?.testcase_id??"",test_id:i.data?.test_id??e,project_id:i.data?.project_id??""}}async submitFeedback(e,t){let s=t?`Bearer ${t}`:this.authHeader,r={instruction_id:e.instruction_id,test_id:e.test_id,feedback_type:e.feedback_type,mode:e.mode??"human"};e.details&&(r.details=e.details);let o=await n(`${this.baseUrl}/atm/v1/generative-feedback`,{method:"POST",headers:{Authorization:s,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Submit feedback failed: ${o.status} ${await o.text()}`);return await o.json()}};export{f as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,c,e as o}from"./chunk-3Z4EHIOW.js";import{a as l}from"./chunk-RZ4F3BHX.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
2
+ import{a as l}from"./chunk-RZ4F3BHX.js";import{a,c,e as o}from"./chunk-IBDWHXNE.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as c}from"./chunk-LAR7I5SR.js";import{a as n}from"./chunk-RZ4F3BHX.js";import{q as s,r as a}from"./chunk-IBDWHXNE.js";import{createHash as h,randomBytes as g}from"crypto";var l=class{authBaseUrl;consentUrl;constructor(t="prod"){let e=c(t);this.authBaseUrl=e.authBaseUrl,this.consentUrl=e.consentUrl}static generatePkce(){let t=g(96).toString("base64url").slice(0,128),e=h("sha256").update(t).digest("base64url");return[t,e]}buildAuthorizationUrl(t,e,r,o){let i=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:o,scope:a,code_challenge:e,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${i.toString()}`}async registerClient(t){let e=await n(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:s,redirect_uris:[t],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!e.ok)throw new Error(`DCR failed: ${e.status} ${await e.text()}`);return e.json()}async exchangeCode(t,e,r,o){let i=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:t,redirect_uri:o,client_id:e,code_verifier:r})});if(!i.ok)throw new Error(`Token exchange failed: ${i.status}`);return i.json()}async refreshToken(t,e){let r=await n(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:e})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(t,e,r="access_token"){await n(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,token_type_hint:r,client_id:e})})}async validateToken(t){let e=new AbortController,r=setTimeout(()=>e.abort(),1e4);try{let o=await n(`${this.authBaseUrl}/api/user`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json","Content-Type":"application/json"},signal:e.signal});return clearTimeout(r),o.ok}catch{return clearTimeout(r),!1}}};export{l as a};
@@ -1,2 +1,2 @@
1
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};
2
+ import{a as A}from"./chunk-YCCUBQY4.js";import{a as _}from"./chunk-UHFCCGVX.js";import{a as k}from"./chunk-LPUQ4HWQ.js";import{a as B}from"./chunk-LAR7I5SR.js";import{a as R}from"./chunk-JGXJDTMO.js";import{t as c}from"./chunk-IBDWHXNE.js";import{a as P}from"./chunk-HCBYKLMW.js";import{a as u,b as l}from"./chunk-C44QQJR4.js";import{a as J}from"./chunk-6YGTRKDT.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};
@@ -1,10 +1,10 @@
1
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}.
2
+ import{a as L,b as et}from"./chunk-CMRNCZGV.js";import{a as U,b as X}from"./chunk-77SZF4ZU.js";import{a as Z,b as tt}from"./chunk-MDBXYXSC.js";import{a as C,b as J,e as P,f as Q}from"./chunk-AH4AXJML.js";import{a as W}from"./chunk-YSSBAIJI.js";import{a as z}from"./chunk-UHFCCGVX.js";import{a as N}from"./chunk-T46Z27UL.js";import{a as G}from"./chunk-LAR7I5SR.js";import{a as I}from"./chunk-RZ4F3BHX.js";import{t as h}from"./chunk-IBDWHXNE.js";import{a as $}from"./chunk-HCBYKLMW.js";import{a as k,b as g,i as K}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.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
3
  Switch profiles with \`kane-cli profiles switch\` to act on it.
4
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
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
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}
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-H2X6CUIX.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
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
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
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.
@@ -1,2 +1,2 @@
1
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};
2
+ import{b as B}from"./chunk-S3DAAAE5.js";import{a as g}from"./chunk-UYHNJUPY.js";import{t as s}from"./chunk-IBDWHXNE.js";import{a as w}from"./chunk-HCBYKLMW.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,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{c as g}from"./chunk-IBDWHXNE.js";import{readFileSync as o,writeFileSync as h,mkdirSync as u,readdirSync as a,unlinkSync as s,existsSync as l,chmodSync as f}from"fs";import{join as n,dirname as P}from"path";var d=class{baseDir;profilesDir;configFile;constructor(t=g){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(o(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){u(this.baseDir,{recursive:!0,mode:448}),h(this.configFile,JSON.stringify(t,null,2)+`
3
+ `),f(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(t){let i=this.readConfig();i.active_profile=t,this.writeConfig(i)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(t){let i=this.readConfig();i.default_env=t,this.writeConfig(i)}credentialsPath(t,i){return n(this.profilesDir,t,i,"credentials")}clientPath(t,i){return n(this.profilesDir,t,i,"client.json")}basicAuthPath(t,i){return n(this.profilesDir,t,i,"basic-auth")}profileConfigPath(t,i){return n(this.profilesDir,t,i,"profile-config.json")}saveProfileConfig(t,i,r){let e=this.loadProfileConfig(t,i)??{};this.writeSecure(this.profileConfigPath(t,i),{...e,...r})}loadProfileConfig(t,i){try{return JSON.parse(o(this.profileConfigPath(t,i),"utf-8"))}catch{return null}}writeSecure(t,i){try{u(P(t),{recursive:!0,mode:448}),h(t,JSON.stringify(i,null,2)+`
4
+ `),f(t,384)}catch(r){let e=r instanceof Error?r.message:String(r);process.stderr.write(`[auth] Failed to save credentials: ${e}
5
+ `)}}saveCredentials(t,i,r){this.writeSecure(this.credentialsPath(t,i),r)}loadCredentials(t,i){try{return JSON.parse(o(this.credentialsPath(t,i),"utf-8"))}catch{return null}}saveClient(t,i,r){this.writeSecure(this.clientPath(t,i),r)}loadClient(t,i){try{return JSON.parse(o(this.clientPath(t,i),"utf-8"))}catch{return null}}getActiveCredentials(){let t=this.getActiveProfile();if(!t)return{credentials:null,profile:null,env:null};let i=this.getDefaultEnv();return{credentials:this.loadCredentials(t,i),profile:t,env:i}}saveBasicAuth(t,i,r){this.writeSecure(this.basicAuthPath(t,i),r)}loadBasicAuth(t,i){try{return JSON.parse(o(this.basicAuthPath(t,i),"utf-8"))}catch{return null}}deleteBasicAuth(t,i){try{s(this.basicAuthPath(t,i))}catch{}}resolveAuth(){let t=this.getActiveProfile();if(!t)return null;let i=this.getDefaultEnv(),r=this.loadBasicAuth(t,i);return r?{method:"basic",...r,profile:t,env:i}:this.loadCredentials(t,i)?{method:"oauth",profile:t,env:i}:null}listProfiles(){let t=[];try{for(let i of a(this.profilesDir)){let r=n(this.profilesDir,i);try{for(let e of a(r)){let c=n(r,e),v=l(n(c,"credentials")),p=l(n(c,"client.json")),y=l(n(c,"basic-auth"));(v||p||y)&&t.push({profile:i,env:e})}}catch{}}}catch{}return t}deleteProfile(t,i){try{s(this.credentialsPath(t,i))}catch{}if(this.getActiveProfile()===t){let r=this.readConfig();delete r.active_profile,this.writeConfig(r)}}deleteProfileFull(t,i){if(i){try{s(this.credentialsPath(t,i))}catch{}try{s(this.clientPath(t,i))}catch{}try{s(this.basicAuthPath(t,i))}catch{}try{s(this.profileConfigPath(t,i))}catch{}}else try{let r=n(this.profilesDir,t);for(let e of a(r)){try{s(n(r,e,"credentials"))}catch{}try{s(n(r,e,"client.json"))}catch{}try{s(n(r,e,"basic-auth"))}catch{}try{s(n(r,e,"profile-config.json"))}catch{}}}catch{}}};export{d as a};