@testmuai/kane-cli 0.2.4 → 0.2.6

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 (59) hide show
  1. package/dist/{ChromeProfilePicker-IRZUDC2R.js → ChromeProfilePicker-GFXYO62T.js} +1 -1
  2. package/dist/{CliFeedbackPrompt-RIIDDIY5.js → CliFeedbackPrompt-F3ZTTEUY.js} +1 -1
  3. package/dist/{CliUploadProgress-QF57Z3FD.js → CliUploadProgress-DNE54O2E.js} +1 -1
  4. package/dist/{ConfigView-5R4G4OZ6.js → ConfigView-MTU2VXM3.js} +1 -1
  5. package/dist/FolderPicker-VVQBL3YD.js +2 -0
  6. package/dist/HelpView-WVCLJJMT.js +2 -0
  7. package/dist/{LinksBox-623NMFSA.js → LinksBox-I4PYUQY7.js} +1 -1
  8. package/dist/{LoginWizard-SSE5NJVU.js → LoginWizard-ZGXMGBNJ.js} +1 -1
  9. package/dist/{ProfilesView-DBNO4RSU.js → ProfilesView-AUJOUVYZ.js} +1 -1
  10. package/dist/ProjectPicker-3WKERA5V.js +2 -0
  11. package/dist/{WhoamiView-2VBZBQF7.js → WhoamiView-CY65SJE3.js} +1 -1
  12. package/dist/{changelog-XYK3P4RQ.js → changelog-CHSXQF3G.js} +1 -1
  13. package/dist/chunk-36GHKMI7.js +2 -0
  14. package/dist/chunk-3C7VPJXD.js +2 -0
  15. package/dist/chunk-5BRNKEYT.js +2 -0
  16. package/dist/chunk-6HRAVME7.js +2 -0
  17. package/dist/chunk-6SF4L62W.js +2 -0
  18. package/dist/{chunk-426ZAKPO.js → chunk-ATLXF7HN.js} +1 -1
  19. package/dist/{chunk-LZZDLYE3.js → chunk-CW5PVMPK.js} +1 -1
  20. package/dist/chunk-DXKKUGFG.js +2 -0
  21. package/dist/{chunk-B4K7UTF2.js → chunk-EWT2AY54.js} +1 -1
  22. package/dist/chunk-IFWLAQ3L.js +2 -0
  23. package/dist/chunk-KMHVGLJY.js +2 -0
  24. package/dist/chunk-L5Y2GUO6.js +2 -0
  25. package/dist/chunk-O7HXQ753.js +2 -0
  26. package/dist/chunk-OIERCP6B.js +2 -0
  27. package/dist/{chunk-GNMGQOGV.js → chunk-PSB4TGW4.js} +10 -8
  28. package/dist/chunk-PWGEMRBD.js +2 -0
  29. package/dist/{chunk-BSMUBGQO.js → chunk-THEP5K6T.js} +1 -1
  30. package/dist/{chunk-JXLB6N6Q.js → chunk-WSRUIIRY.js} +1 -1
  31. package/dist/{chunk-GTYF5DR6.js → chunk-Y4NPKZOF.js} +1 -1
  32. package/dist/controller-client-7BIK5FYL.js +2 -0
  33. package/dist/index.js +60 -47
  34. package/dist/logging-O5R56LPM.js +2 -0
  35. package/dist/machine-id-DZN4MYOO.js +2 -0
  36. package/dist/pipeline-NXUVAHY5.js +2 -0
  37. package/dist/resolver-QLDOAIXU.js +2 -0
  38. package/dist/tms-client-T4HO73MT.js +2 -0
  39. package/dist/{updater-H5HYMYRG.js → updater-WVTXO7SS.js} +1 -1
  40. package/dist/{version-check-KS7CP3M5.js → version-check-SR6WBC6M.js} +1 -1
  41. package/package.json +4 -4
  42. package/dist/FolderPicker-G4C4RCP2.js +0 -2
  43. package/dist/HelpView-2ZFLX7JC.js +0 -2
  44. package/dist/ProjectPicker-AFQDF2VS.js +0 -2
  45. package/dist/chunk-3CJ6IY5O.js +0 -2
  46. package/dist/chunk-I7YWZ3D2.js +0 -2
  47. package/dist/chunk-IA4UI2BT.js +0 -2
  48. package/dist/chunk-KSHUUU2I.js +0 -2
  49. package/dist/chunk-NRQDE7HH.js +0 -2
  50. package/dist/chunk-RDG6MGL7.js +0 -2
  51. package/dist/chunk-RPQV6H45.js +0 -2
  52. package/dist/chunk-S2FLPRVR.js +0 -2
  53. package/dist/chunk-XHPTLI5U.js +0 -2
  54. package/dist/chunk-YNF4MUQP.js +0 -2
  55. package/dist/controller-client-PS5GDXE3.js +0 -2
  56. package/dist/exitCleanup-J3GVD6U2.js +0 -2
  57. package/dist/pipeline-7NY333ZT.js +0 -2
  58. package/dist/resolver-L3Z6FAOD.js +0 -2
  59. package/dist/tms-client-QWVBCUUT.js +0 -2
package/dist/index.js CHANGED
@@ -1,51 +1,65 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
3
- import{a as Cn,b as En}from"./chunk-B4K7UTF2.js";import{a as an,b as Gr,c as Zn,d as ts,e as ns}from"./chunk-KSHUUU2I.js";import{a as ss}from"./chunk-IA4UI2BT.js";import{c as Qr}from"./chunk-XHPTLI5U.js";import{b as Yn}from"./chunk-BSMUBGQO.js";import{b as Qn}from"./chunk-LZZDLYE3.js";import{a as ce,b as Xn}from"./chunk-RPQV6H45.js";import{a as cn}from"./chunk-NRQDE7HH.js";import{a as Zr,b as un}from"./chunk-YNF4MUQP.js";import{a as es}from"./chunk-GNMGQOGV.js";import{a as rs}from"./chunk-426ZAKPO.js";import{c as kn}from"./chunk-GTYF5DR6.js";import{a as ln}from"./chunk-3CJ6IY5O.js";import{a as It}from"./chunk-I7YWZ3D2.js";import{b as Xr}from"./chunk-S2FLPRVR.js";import{b as Yr}from"./chunk-JXLB6N6Q.js";import{a as ae}from"./chunk-HCBYKLMW.js";import{a as Pt,c as _e,d as Wr,g as Kn,h as qn,j as Jn,k as zn,l as Gn,m as Kr,n as qr,o as Jr,p as zr,r as m}from"./chunk-RDG6MGL7.js";import{a as v,b as u,c as yn,d as Xt,i as Ze,j as Sn,k as Ot}from"./chunk-Q7JVDEOV.js";import{a as We}from"./chunk-6YGTRKDT.js";import{a as on,c as Ht,e as G}from"./chunk-UR6MHSHU.js";var xn=Ht(Rr=>{"use strict";var Nn=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},kr=class extends Nn{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Rr.CommanderError=Nn;Rr.InvalidArgumentError=kr});var Fn=Ht(Tr=>{"use strict";var{InvalidArgumentError:da}=xn(),Ar=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new da(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function fa(i){let e=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+e+">":"["+e+"]"}Tr.Argument=Ar;Tr.humanReadableArgName=fa});var Pr=Ht(uo=>{"use strict";var{humanReadableArgName:ma}=Fn(),Or=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((n,s)=>n.name().localeCompare(s.name())),t}compareOptions(e,t){let r=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),r=e._getHelpOption();if(r&&!r.hidden){let n=r.short&&e._findOption(r.short),s=r.long&&e._findOption(r.long);!n&&!s?t.push(r):r.long&&!s?t.push(e.createOption(r.long,r.description)):r.short&&!n&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let n=r.options.filter(s=>!s.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>ma(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,n)=>Math.max(r,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,n)=>Math.max(r,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,n)=>Math.max(r,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,n)=>Math.max(r,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let n=e.parent;n;n=n.parent)r=n.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),n=t.helpWidth||80,s=2,a=2;function o(p,b){if(b){let g=`${p.padEnd(r+a)}${b}`;return t.wrap(g,n-s,r+a)}return p}function l(p){return p.join(`
4
- `).replace(/^/gm," ".repeat(s))}let c=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(c=c.concat([t.wrap(d,n,0),""]));let h=t.visibleArguments(e).map(p=>o(t.argumentTerm(p),t.argumentDescription(p)));h.length>0&&(c=c.concat(["Arguments:",l(h),""]));let x=t.visibleOptions(e).map(p=>o(t.optionTerm(p),t.optionDescription(p)));if(x.length>0&&(c=c.concat(["Options:",l(x),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(b=>o(t.optionTerm(b),t.optionDescription(b)));p.length>0&&(c=c.concat(["Global Options:",l(p),""]))}let S=t.visibleCommands(e).map(p=>o(t.subcommandTerm(p),t.subcommandDescription(p)));return S.length>0&&(c=c.concat(["Commands:",l(S),""])),c.join(`
5
- `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,n=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${s}]+`);if(e.match(a))return e;let o=t-r;if(o<n)return e;let l=e.slice(0,r),c=e.slice(r).replace(`\r
3
+ import{c as wn}from"./chunk-Y4NPKZOF.js";import{a as vn,b as xn}from"./chunk-EWT2AY54.js";import{a as mt,b as Co,c as fr,d as Bo,e as $o}from"./chunk-5BRNKEYT.js";import{a as Lo}from"./chunk-3C7VPJXD.js";import{c as Io}from"./chunk-O7HXQ753.js";import{b as ur}from"./chunk-THEP5K6T.js";import{b as dr}from"./chunk-CW5PVMPK.js";import{a as ie,b as cr}from"./chunk-36GHKMI7.js";import{a as Lt}from"./chunk-PWGEMRBD.js";import{b as Po}from"./chunk-KMHVGLJY.js";import{a as Oo}from"./chunk-IFWLAQ3L.js";import{a as Do}from"./chunk-PSB4TGW4.js";import{a as jo}from"./chunk-ATLXF7HN.js";import{a as Yt}from"./chunk-L5Y2GUO6.js";import{a as et}from"./chunk-6SF4L62W.js";import{a as Ro,b as ko}from"./chunk-DXKKUGFG.js";import{b as To}from"./chunk-6HRAVME7.js";import{b as Ao}from"./chunk-WSRUIIRY.js";import{a as re}from"./chunk-HCBYKLMW.js";import{a as ft,c as ve,d as bo,h as Ge,i as or,j as sr,l as ir,m as ar,n as lr,o as _o,p as yo,q as So,r as Eo,t as m}from"./chunk-OIERCP6B.js";import{a as x,b as u,c as hn,d as jt,i as $e,j as gn,k as dt}from"./chunk-Q7JVDEOV.js";import{a as ke}from"./chunk-6YGTRKDT.js";import{a as Xt,c as Rt,e as N}from"./chunk-UR6MHSHU.js";var dn=Rt(zr=>{"use strict";var Jn=class extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},qr=class extends Jn{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};zr.CommanderError=Jn;zr.InvalidArgumentError=qr});var Xn=Rt(Jr=>{"use strict";var{InvalidArgumentError:ul}=dn(),Gr=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new ul(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function dl(o){let e=o.name()+(o.variadic===!0?"...":"");return o.required?"<"+e+">":"["+e+"]"}Jr.Argument=Gr;Jr.humanReadableArgName=dl});var Yr=Rt(ni=>{"use strict";var{humanReadableArgName:fl}=Xn(),Xr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(r=>!r._hidden),n=e._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((r,s)=>r.name().localeCompare(s.name())),t}compareOptions(e,t){let n=r=>r.short?r.short.replace(/^-/,""):r.long.replace(/^--/,"");return n(e).localeCompare(n(t))}visibleOptions(e){let t=e.options.filter(r=>!r.hidden),n=e._getHelpOption();if(n&&!n.hidden){let r=n.short&&e._findOption(n.short),s=n.long&&e._findOption(n.long);!r&&!s?t.push(n):n.long&&!s?t.push(e.createOption(n.long,n.description)):n.short&&!r&&t.push(e.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let n=e.parent;n;n=n.parent){let r=n.options.filter(s=>!s.hidden);t.push(...r)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(n=>fl(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((n,r)=>Math.max(n,t.subcommandTerm(r).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((n,r)=>Math.max(n,t.optionTerm(r).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((n,r)=>Math.max(n,t.optionTerm(r).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((n,r)=>Math.max(n,t.argumentTerm(r).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let r=e.parent;r;r=r.parent)n=r.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,t){let n=t.padWidth(e,t),r=t.helpWidth||80,s=2,a=2;function i(h,y){if(y){let _=`${h.padEnd(n+a)}${y}`;return t.wrap(_,r-s,n+a)}return h}function l(h){return h.join(`
4
+ `).replace(/^/gm," ".repeat(s))}let c=[`Usage: ${t.commandUsage(e)}`,""],f=t.commandDescription(e);f.length>0&&(c=c.concat([t.wrap(f,r,0),""]));let d=t.visibleArguments(e).map(h=>i(t.argumentTerm(h),t.argumentDescription(h)));d.length>0&&(c=c.concat(["Arguments:",l(d),""]));let g=t.visibleOptions(e).map(h=>i(t.optionTerm(h),t.optionDescription(h)));if(g.length>0&&(c=c.concat(["Options:",l(g),""])),this.showGlobalOptions){let h=t.visibleGlobalOptions(e).map(y=>i(t.optionTerm(y),t.optionDescription(y)));h.length>0&&(c=c.concat(["Global Options:",l(h),""]))}let E=t.visibleCommands(e).map(h=>i(t.subcommandTerm(h),t.subcommandDescription(h)));return E.length>0&&(c=c.concat(["Commands:",l(E),""])),c.join(`
5
+ `)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,r=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${s}]+`);if(e.match(a))return e;let i=t-n;if(i<r)return e;let l=e.slice(0,n),c=e.slice(n).replace(`\r
6
6
  `,`
7
- `),d=" ".repeat(r),x="\\s\u200B",S=new RegExp(`
8
- |.{1,${o-1}}([${x}]|$)|[^${x}]+?([${x}]|$)`,"g"),p=c.match(S)||[];return l+p.map((b,g)=>b===`
9
- `?"":(g>0?d:"")+b.trimEnd()).join(`
10
- `)}};uo.Help=Or});var Br=Ht(Dr=>{"use strict";var{InvalidArgumentError:pa}=xn(),Ir=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=ga(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new pa(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return ha(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},$r=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let n=this.negativeOptions.get(r).presetArg,s=n!==void 0?n:!1;return t.negate===(s===e)}};function ha(i){return i.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ga(i){let e,t,r=i.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Dr.Option=Ir;Dr.DualOptions=$r});var mo=Ht(fo=>{"use strict";function xa(i,e){if(Math.abs(i.length-e.length)>3)return Math.max(i.length,e.length);let t=[];for(let r=0;r<=i.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let n=1;n<=i.length;n++){let s=1;i[n-1]===e[r-1]?s=0:s=1,t[n][r]=Math.min(t[n-1][r]+1,t[n][r-1]+1,t[n-1][r-1]+s),n>1&&r>1&&i[n-1]===e[r-2]&&i[n-2]===e[r-1]&&(t[n][r]=Math.min(t[n][r],t[n-2][r-2]+1))}return t[i.length][e.length]}function va(i,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=i.startsWith("--");t&&(i=i.slice(2),e=e.map(a=>a.slice(2)));let r=[],n=3,s=.4;return e.forEach(a=>{if(a.length<=1)return;let o=xa(i,a),l=Math.max(i.length,a.length);(l-o)/l>s&&(o<n?(n=o,r=[a]):o===n&&r.push(a))}),r.sort((a,o)=>a.localeCompare(o)),t&&(r=r.map(a=>`--${a}`)),r.length>1?`
11
- (Did you mean one of ${r.join(", ")}?)`:r.length===1?`
12
- (Did you mean ${r[0]}?)`:""}fo.suggestSimilar=va});var vo=Ht(xo=>{"use strict";var ba=on("events").EventEmitter,jr=on("child_process"),yt=on("path"),Ur=on("fs"),we=on("process"),{Argument:_a,humanReadableArgName:wa}=Fn(),{CommanderError:Vr}=xn(),{Help:ya}=Pr(),{Option:po,DualOptions:Sa}=Br(),{suggestSimilar:ho}=mo(),Lr=class i extends ba{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>we.stdout.write(t),writeErr:t=>we.stderr.write(t),getOutHelpWidth:()=>we.stdout.isTTY?we.stdout.columns:void 0,getErrHelpWidth:()=>we.stderr.isTTY?we.stderr.columns:void 0,outputError:(t,r)=>r(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let n=t,s=r;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,a,o]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(a);return n&&(l.description(n),l._executableHandler=!0),s.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,o&&l.arguments(o),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(e){return new i(e)}createHelp(){return Object.assign(new ya,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
13
- - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new _a(e,t)}argument(e,t,r,n){let s=this.createArgument(e,t);return typeof r=="function"?s.default(n).argParser(r):s.default(r),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,n]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",a=this.createCommand(r);return a.helpOption(!1),n&&a.arguments(n),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
14
- Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new Vr(e,t,r)),we.exit(e)}action(e){let t=r=>{let n=this.registeredArguments.length,s=r.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new po(e,t)}_callParseArg(e,t,r,n){try{return e.parseArg(t,r)}catch(s){if(s.code==="commander.invalidArgument"){let a=`${n} ${s.message}`;this.error(a,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
15
- - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),r=t(e).find(n=>this._findCommand(n));if(r){let n=t(this._findCommand(r)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let n=(s,a,o)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(r);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,a):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(r,s,o)};return this.on("option:"+t,s=>{let a=`error: option '${e.flags}' argument '${s}' is invalid.`;n(s,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let a=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;n(s,a,"env")}),this}_optionEx(e,t,r,n,s){if(typeof t=="object"&&t instanceof po)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,r);if(a.makeOptionMandatory(!!e.mandatory),typeof n=="function")a.default(s).argParser(n);else if(n instanceof RegExp){let o=n;n=(l,c)=>{let d=o.exec(l);return d?d[0]:c},a.default(s).argParser(n)}else a.default(n);return this.addOption(a)}option(e,t,r,n){return this._optionEx({},e,t,r,n)}requiredOption(e,t,r,n){return this._optionEx({mandatory:!0},e,t,r,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){we.versions?.electron&&(t.from="electron");let n=we.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=we.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":we.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(d,h){let x=yt.resolve(d,h);if(Ur.existsSync(x))return x;if(n.includes(yt.extname(h)))return;let S=n.find(p=>Ur.existsSync(`${x}${p}`));if(S)return`${x}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let d;try{d=Ur.realpathSync(this._scriptPath)}catch{d=this._scriptPath}o=yt.resolve(yt.dirname(d),o)}if(o){let d=s(o,a);if(!d&&!e._executableFile&&this._scriptPath){let h=yt.basename(this._scriptPath,yt.extname(this._scriptPath));h!==this._name&&(d=s(o,`${h}-${e._name}`))}a=d||a}r=n.includes(yt.extname(a));let l;we.platform!=="win32"?r?(t.unshift(a),t=go(we.execArgv).concat(t),l=jr.spawn(we.argv[0],t,{stdio:"inherit"})):l=jr.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=go(we.execArgv).concat(t),l=jr.spawn(we.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{we.on(h,()=>{l.killed===!1&&l.exitCode===null&&l.kill(h)})});let c=this._exitCallback;l.on("close",d=>{d=d??1,c?c(new Vr(d,"commander.executeSubCommandAsync","(close)")):we.exit(d)}),l.on("error",d=>{if(d.code==="ENOENT"){let h=o?`searched for local subcommand relative to directory '${o}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",x=`'${a}' does not exist
7
+ `),f=" ".repeat(n),g="\\s\u200B",E=new RegExp(`
8
+ |.{1,${i-1}}([${g}]|$)|[^${g}]+?([${g}]|$)`,"g"),h=c.match(E)||[];return l+h.map((y,_)=>y===`
9
+ `?"":(_>0?f:"")+y.trimEnd()).join(`
10
+ `)}};ni.Help=Xr});var to=Rt(eo=>{"use strict";var{InvalidArgumentError:ml}=dn(),Qr=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=hl(e);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new ml(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return pl(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Zr=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,s=r!==void 0?r:!1;return t.negate===(s===e)}};function pl(o){return o.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function hl(o){let e,t,n=o.split(/[ |,]+/);return n.length>1&&!/^[[<]/.test(n[1])&&(e=n.shift()),t=n.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}eo.Option=Qr;eo.DualOptions=Zr});var oi=Rt(ri=>{"use strict";function gl(o,e){if(Math.abs(o.length-e.length)>3)return Math.max(o.length,e.length);let t=[];for(let n=0;n<=o.length;n++)t[n]=[n];for(let n=0;n<=e.length;n++)t[0][n]=n;for(let n=1;n<=e.length;n++)for(let r=1;r<=o.length;r++){let s=1;o[r-1]===e[n-1]?s=0:s=1,t[r][n]=Math.min(t[r-1][n]+1,t[r][n-1]+1,t[r-1][n-1]+s),r>1&&n>1&&o[r-1]===e[n-2]&&o[r-2]===e[n-1]&&(t[r][n]=Math.min(t[r][n],t[r-2][n-2]+1))}return t[o.length][e.length]}function vl(o,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=o.startsWith("--");t&&(o=o.slice(2),e=e.map(a=>a.slice(2)));let n=[],r=3,s=.4;return e.forEach(a=>{if(a.length<=1)return;let i=gl(o,a),l=Math.max(o.length,a.length);(l-i)/l>s&&(i<r?(r=i,n=[a]):i===r&&n.push(a))}),n.sort((a,i)=>a.localeCompare(i)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
11
+ (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
12
+ (Did you mean ${n[0]}?)`:""}ri.suggestSimilar=vl});var ci=Rt(li=>{"use strict";var xl=Xt("events").EventEmitter,no=Xt("child_process"),lt=Xt("path"),ro=Xt("fs"),xe=Xt("process"),{Argument:wl,humanReadableArgName:bl}=Xn(),{CommanderError:oo}=dn(),{Help:_l}=Yr(),{Option:si,DualOptions:yl}=to(),{suggestSimilar:ii}=oi(),so=class o extends xl{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>xe.stdout.write(t),writeErr:t=>xe.stderr.write(t),getOutHelpWidth:()=>xe.stdout.isTTY?xe.stdout.columns:void 0,getErrHelpWidth:()=>xe.stderr.isTTY?xe.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,s=n;typeof r=="object"&&r!==null&&(s=r,r=null),s=s||{};let[,a,i]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(a);return r&&(l.description(r),l._executableHandler=!0),s.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,i&&l.arguments(i),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),r?this:l}createCommand(e){return new o(e)}createHelp(){return Object.assign(new _l,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
13
+ - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new wl(e,t)}argument(e,t,n,r){let s=this.createArgument(e,t);return typeof n=="function"?s.default(r).argParser(n):s.default(n),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,r]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
14
+ Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new oo(e,t,n)),xe.exit(e)}action(e){let t=n=>{let r=this.registeredArguments.length,s=n.slice(0,r);return this._storeOptionsAsProperties?s[r]=this:s[r]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new si(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(s){if(s.code==="commander.invalidArgument"){let a=`${r} ${s.message}`;this.error(a,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
15
+ - already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=r=>[r.name()].concat(r.aliases()),n=t(e).find(r=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(s,a,i)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(n);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,a):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(n,s,i)};return this.on("option:"+t,s=>{let a=`error: option '${e.flags}' argument '${s}' is invalid.`;r(s,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let a=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;r(s,a,"env")}),this}_optionEx(e,t,n,r,s){if(typeof t=="object"&&t instanceof si)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,n);if(a.makeOptionMandatory(!!e.mandatory),typeof r=="function")a.default(s).argParser(r);else if(r instanceof RegExp){let i=r;r=(l,c)=>{let f=i.exec(l);return f?f[0]:c},a.default(s).argParser(r)}else a.default(r);return this.addOption(a)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(e)!==void 0&&(t=n.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){xe.versions?.electron&&(t.from="electron");let r=xe.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=xe.argv),this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":xe.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function s(f,d){let g=lt.resolve(f,d);if(ro.existsSync(g))return g;if(r.includes(lt.extname(d)))return;let E=r.find(h=>ro.existsSync(`${g}${h}`));if(E)return`${g}${E}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,i=this._executableDir||"";if(this._scriptPath){let f;try{f=ro.realpathSync(this._scriptPath)}catch{f=this._scriptPath}i=lt.resolve(lt.dirname(f),i)}if(i){let f=s(i,a);if(!f&&!e._executableFile&&this._scriptPath){let d=lt.basename(this._scriptPath,lt.extname(this._scriptPath));d!==this._name&&(f=s(i,`${d}-${e._name}`))}a=f||a}n=r.includes(lt.extname(a));let l;xe.platform!=="win32"?n?(t.unshift(a),t=ai(xe.execArgv).concat(t),l=no.spawn(xe.argv[0],t,{stdio:"inherit"})):l=no.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=ai(xe.execArgv).concat(t),l=no.spawn(xe.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(d=>{xe.on(d,()=>{l.killed===!1&&l.exitCode===null&&l.kill(d)})});let c=this._exitCallback;l.on("close",f=>{f=f??1,c?c(new oo(f,"commander.executeSubCommandAsync","(close)")):xe.exit(f)}),l.on("error",f=>{if(f.code==="ENOENT"){let d=i?`searched for local subcommand relative to directory '${i}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",g=`'${a}' does not exist
16
16
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${h}`;throw new Error(x)}else if(d.code==="EACCES")throw new Error(`'${a}' not executable`);if(!c)we.exit(1);else{let h=new Vr(1,"commander.executeSubCommandAsync","(error)");h.nestedError=d,c(h)}}),this.runningCommand=l}_dispatchSubcommand(e,t,r){let n=this._findCommand(e);n||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(r));else return n._parseCommand(t,r)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,n,s)=>{let a=n;if(n!==null&&r.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,n,s,o)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,n)=>{let s=r.defaultValue;r.variadic?n<this.args.length?(s=this.args.slice(n),r.parseArg&&(s=s.reduce((a,o)=>e(r,o,a),r.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],r.parseArg&&(s=e(r,s,r.defaultValue))),t[n]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(a=>{n.push({hookedCommand:s,callback:a})})}),t==="postAction"&&n.reverse(),n.forEach(s=>{r=this._chainOrCall(r,()=>s.callback(s.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let n=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(s=>{n=this._chainOrCall(n,()=>s(this,t))}),n}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(s,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let n=r.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let n=e.find(s=>r.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(r,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],n=t,s=e.slice();function a(l){return l.length>1&&l[0]==="-"}let o=null;for(;s.length;){let l=s.shift();if(l==="--"){n===r&&n.push(l),n.push(...s);break}if(o&&!a(l)){this.emit(`option:${o.name()}`,l);continue}if(o=null,a(l)){let c=this._findOption(l);if(c){if(c.required){let d=s.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;s.length>0&&!a(s[0])&&(d=s.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);o=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),d=this._findOption(l.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,l.slice(c+1));continue}}if(a(l)&&(n=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&r.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){r.push(l),s.length>0&&r.push(...s);break}}if(this._passThroughOptions){n.push(l),s.length>0&&n.push(...s);break}n.push(l)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let n=this.options[r].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
18
+ - ${d}`;throw new Error(g)}else if(f.code==="EACCES")throw new Error(`'${a}' not executable`);if(!c)xe.exit(1);else{let d=new oo(1,"commander.executeSubCommandAsync","(error)");d.nestedError=f,c(d)}}),this.runningCommand=l}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,r,"preSubcommand"),s=this._chainOrCall(s,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(n,r,s)=>{let a=r;if(r!==null&&n.parseArg){let i=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,r,s,i)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let s=n.defaultValue;n.variadic?r<this.args.length?(s=this.args.slice(r),n.parseArg&&(s=s.reduce((a,i)=>e(n,i,a),n.defaultValue))):s===void 0&&(s=[]):r<this.args.length&&(s=this.args[r],n.parseArg&&(s=e(n,s,n.defaultValue))),t[r]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let n=e,r=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(a=>{r.push({hookedCommand:s,callback:a})})}),t==="postAction"&&r.reverse(),r.forEach(s=>{n=this._chainOrCall(n,()=>s.callback(s.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(s=>{r=this._chainOrCall(r,()=>s(this,t))}),r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(s,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(s))r(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(r(),this._processArguments())}else this.commands.length?(r(),this.help({error:!0})):(r(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(n=>{let r=n.attributeName();return this.getOptionValue(r)===void 0?!1:this.getOptionValueSource(r)!=="default"});e.filter(n=>n.conflictsWith.length>0).forEach(n=>{let r=e.find(s=>n.conflictsWith.includes(s.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,s=e.slice();function a(l){return l.length>1&&l[0]==="-"}let i=null;for(;s.length;){let l=s.shift();if(l==="--"){r===n&&r.push(l),r.push(...s);break}if(i&&!a(l)){this.emit(`option:${i.name()}`,l);continue}if(i=null,a(l)){let c=this._findOption(l);if(c){if(c.required){let f=s.shift();f===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,f)}else if(c.optional){let f=null;s.length>0&&!a(s[0])&&(f=s.shift()),this.emit(`option:${c.name()}`,f)}else this.emit(`option:${c.name()}`);i=c.variadic?c:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let c=this._findOption(`-${l[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,l.slice(2)):(this.emit(`option:${c.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let c=l.indexOf("="),f=this._findOption(l.slice(0,c));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,l.slice(c+1));continue}}if(a(l)&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&n.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){n.push(l),s.length>0&&n.push(...s);break}}if(this._passThroughOptions){r.push(l),s.length>0&&r.push(...s);break}r.push(l)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
19
19
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
20
20
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
21
- `),this.outputHelp({error:!0}));let r=t||{},n=r.exitCode||1,s=r.code||"commander.error";this._exit(n,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in we.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,we.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Sa(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,r.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=a=>{let o=a.attributeName(),l=this.getOptionValue(o),c=this.options.find(h=>h.negate&&o===h.attributeName()),d=this.options.find(h=>!h.negate&&o===h.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:d||a},n=a=>{let o=r(a),l=o.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${o.envVar}'`:`option '${o.flags}'`},s=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let a=s.createHelp().visibleOptions(s).filter(o=>o.long).map(o=>o.long);n=n.concat(a),s=s.parent}while(s&&!s._enablePositionalOptions);t=ho(e,n)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),t=ho(e,n)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let n=this.createOption(t,r);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
- `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let n=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>wa(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=yt.basename(e,yt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=n=>this._outputConfiguration.writeErr(n):r=n=>this._outputConfiguration.writeOut(n),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let n=this.helpInformation(r);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=we.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
23
- Expecting one of '${r.join("', '")}'`);let n=`${e}Help`;return this.on(n,s=>{let a;typeof t=="function"?a=t({error:s.error,command:s.command}):a=t,a&&s.write(`${a}
24
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function go(i){return i.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",n="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?n=s[3]:r=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],r=s[3],n=s[4]),t&&n!=="0"?`${t}=${r}:${parseInt(n)+1}`:e})}xo.Command=Lr});var yo=Ht(it=>{"use strict";var{Argument:bo}=Fn(),{Command:Mr}=vo(),{CommanderError:Ca,InvalidArgumentError:_o}=xn(),{Help:Ea}=Pr(),{Option:wo}=Br();it.program=new Mr;it.createCommand=i=>new Mr(i);it.createOption=(i,e)=>new wo(i,e);it.createArgument=(i,e)=>new bo(i,e);it.Command=Mr;it.Option=wo;it.Argument=bo;it.Help=Ea;it.CommanderError=Ca;it.InvalidArgumentError=_o;it.InvalidOptionArgumentError=_o});var Oo=G(We(),1);import Ut from"process";var U=G(We(),1);var he=G(ae(),1);function os({profile:i,environment:e,model:t,tokenValid:r,sessionId:n,runCount:s,viewMode:a}){let{stdout:o}=Ot(),l=o?.columns??80,c=e==="stage";return(0,he.jsxs)(v,{flexDirection:"column",children:[(0,he.jsx)(u,{color:m.muted,children:"\u2500".repeat(l)}),(0,he.jsx)(v,{paddingX:1,children:(0,he.jsxs)(v,{gap:1,children:[(0,he.jsx)(u,{color:m.dimmed,children:"Model:"}),(0,he.jsx)(u,{color:m.dimmed,children:t}),(0,he.jsx)(u,{color:m.muted,children:"|"}),(0,he.jsx)(u,{color:m.dimmed,children:"Session:"}),(0,he.jsx)(u,{color:m.dimmed,children:n.slice(-6)}),(0,he.jsx)(u,{color:m.muted,children:"|"}),(0,he.jsx)(u,{color:r?m.green:m.red,children:"\u25CF"}),(0,he.jsx)(u,{color:m.dimmed,children:r?"authenticated":"not logged in"})]})}),(0,he.jsx)(v,{paddingX:1,children:(0,he.jsxs)(v,{gap:1,children:[(0,he.jsx)(u,{color:m.dimmed,children:i??"no profile"}),(0,he.jsx)(u,{color:m.muted,children:"|"}),c?(0,he.jsx)(u,{color:m.yellow,bold:!0,children:"\u26A0 stage"}):(0,he.jsx)(u,{color:m.green,children:e}),(0,he.jsx)(u,{color:m.muted,children:"|"}),(0,he.jsxs)(u,{color:m.dimmed,children:["runs: ",s]})]})}),(0,he.jsx)(v,{paddingX:1,children:(0,he.jsx)(u,{dimColor:!0,children:a==="chat"?"esc menu ctrl+c cancel/exit":"\u2191\u2193 navigate \u21B5 select esc back"})})]})}var is=G(We(),1);import{readFileSync as $o,writeFileSync as Do,mkdirSync as Bo}from"fs";import{dirname as jo,join as Uo}from"path";var Vo=Uo(_e,"command-history.json"),Lo=200,er=class{entries;filePath;max;constructor(e=Vo,t=Lo){this.filePath=e,this.max=t,this.entries=this._load()}push(e){this.entries.length>0&&this.entries[this.entries.length-1]===e||(this.entries.push(e),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(e){let t=e.toLowerCase(),r=[];for(let n=this.entries.length-1;n>=0;n--)this.entries[n].toLowerCase().includes(t)&&r.push(this.entries[n]);return r}_load(){try{let e=$o(this.filePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}_save(){try{Bo(jo(this.filePath),{recursive:!0}),Do(this.filePath,JSON.stringify(this.entries)+`
25
- `)}catch{}}};function as(i){let e=(0,is.useRef)(null);return e.current||(e.current=new er(i)),e.current}var Kt=G(We(),1);var dn=[[[" "],[" "],[" "],[" "],["\u2584","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],[" "],[" "],[" "],[" "],[" "],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2584","#af87d7"],[" "],[" "],[" "],[" "]],[[" "],[" "],["\u2584","#875faf"],["\u2584","#af87d7","#875faf"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2584","#af87d7","#875faf"],["\u2584","#875faf"],[" "],[" "]],[[" "],[" "],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2584","#000000","#af87d7"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#af87d7"],["\u2588","#af87d7"],["\u2588","#875faf"],[" "],[" "]],[[" "],["\u2588","#875faf"],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2584","#585858","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],["\u2588","#875faf"],[" "]],[[" "],["\u2588","#875faf"],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2588","#585858"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],["\u2588","#875faf"],[" "]],[[" "],[" "],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2584","#000000","#585858"],["\u2588","#000000"],["\u2588","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],[" "],[" "]],[[" "],[" "],["\u2580","#875faf"],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2580","#875faf"],[" "],[" "]],[[" "],[" "],[" "],[" "],[" "],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2580","#af87d7"],["\u2580","#af87d7"],[" "],[" "],[" "],[" "],[" "]]];var ee=G(ae(),1),Rn="#af87d7",tr="#875faf",ls="#5b3a7a",Mo="#ff9500",No="#ea580c",cs="#888888",nr="#666666",Fo="#555555",Wt=[[Rn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Rn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Rn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Rn,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[tr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[tr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[tr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588"]],rr=Wt.map(([,i])=>[...i]);function us({visibleRows:i=Wt.length}){let e=Math.min(i,Wt.length);return(0,ee.jsxs)(v,{flexDirection:"column",children:[Wt.slice(0,e).map(([t,r],n)=>{let s=rr[n];return(0,ee.jsx)(u,{children:s.map((a,o)=>{if(a==="\u2588")return(0,ee.jsx)(u,{color:t,children:"\u2588"},o);let l=o>0&&s[o-1]==="\u2588",c=n>0&&o>0&&rr[n-1][o-1]==="\u2588";return l||c?(0,ee.jsx)(u,{color:ls,children:"\u2592"},o):(0,ee.jsx)(u,{children:" "},o)})},n)}),e>=Wt.length&&(0,ee.jsxs)(u,{children:[" ",rr[Wt.length-1].map((t,r)=>t==="\u2588"?(0,ee.jsx)(u,{color:ls,children:"\u2580"},r):(0,ee.jsx)(u,{children:" "},r))]})]})}function Ho({visibleRows:i=dn.length}){let e=Math.min(i,dn.length);return(0,ee.jsx)(v,{flexDirection:"column",children:dn.slice(0,e).map((t,r)=>(0,ee.jsx)(u,{children:t.map((n,s)=>{let a=n[0],o=n[1],l=n[2];return o?(0,ee.jsx)(u,{color:o,backgroundColor:l,children:a},s):(0,ee.jsx)(u,{children:a},s)})},r))})}function An({size:i="compact",helmetVisibleRows:e=dn.length,textVisibleRows:t=Wt.length,showMeta:r=!1,user:n=null,authenticated:s=!1,version:a=""}){return i==="compact"?(0,ee.jsx)(us,{}):(0,ee.jsxs)(v,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,ee.jsx)(u,{color:Mo,italic:!0,children:" Welcome to"}),(0,ee.jsx)(u,{children:" "}),(0,ee.jsxs)(v,{gap:2,children:[(0,ee.jsx)(Ho,{visibleRows:e}),(0,ee.jsxs)(v,{flexDirection:"column",children:[(0,ee.jsx)(us,{visibleRows:t}),(0,ee.jsx)(v,{justifyContent:"flex-end",width:73,children:(0,ee.jsx)(u,{color:No,italic:!0,children:"Command-line interface"})})]})]}),r&&(0,ee.jsxs)(ee.Fragment,{children:[(0,ee.jsx)(u,{children:" "}),(0,ee.jsxs)(u,{children:[(0,ee.jsx)(u,{color:nr,children:" Browser automation powered by AI. "}),(0,ee.jsx)(u,{color:Fo,children:`v${a}`})]}),(0,ee.jsx)(u,{children:" "}),(0,ee.jsx)(u,{children:(0,ee.jsx)(u,{color:nr,children:" KaneCLI can navigate websites, fill forms, test web UI, and extract"})}),(0,ee.jsx)(u,{children:(0,ee.jsx)(u,{color:nr,children:" data \u2014 right from your terminal."})}),(0,ee.jsx)(u,{children:" "}),(0,ee.jsxs)(u,{children:[(0,ee.jsx)(u,{color:cs,children:" \u25CF "}),(0,ee.jsx)(u,{color:cs,children:s?"Logged in as ":"Not logged in"}),s&&n&&(0,ee.jsx)(u,{bold:!0,children:n})]})]})]})}import{readFileSync as fn,writeFileSync as ds,mkdirSync as fs,readdirSync as sr,unlinkSync as dt,existsSync as or,chmodSync as ms}from"fs";import{join as Me,dirname as Wo}from"path";var Ee=class{baseDir;profilesDir;configFile;constructor(e=_e){this.baseDir=e,this.profilesDir=Me(e,"profiles"),this.configFile=Me(e,"config.json")}readConfig(){try{return JSON.parse(fn(this.configFile,"utf-8"))}catch{return{}}}writeConfig(e){fs(this.baseDir,{recursive:!0,mode:448}),ds(this.configFile,JSON.stringify(e,null,2)+`
26
- `),ms(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(e){let t=this.readConfig();t.active_profile=e,this.writeConfig(t)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(e){let t=this.readConfig();t.default_env=e,this.writeConfig(t)}credentialsPath(e,t){return Me(this.profilesDir,e,t,"credentials")}clientPath(e,t){return Me(this.profilesDir,e,t,"client.json")}basicAuthPath(e,t){return Me(this.profilesDir,e,t,"basic-auth")}profileConfigPath(e,t){return Me(this.profilesDir,e,t,"profile-config.json")}saveProfileConfig(e,t,r){let n=this.loadProfileConfig(e,t)??{};this.writeSecure(this.profileConfigPath(e,t),{...n,...r})}loadProfileConfig(e,t){try{return JSON.parse(fn(this.profileConfigPath(e,t),"utf-8"))}catch{return null}}writeSecure(e,t){fs(Wo(e),{recursive:!0,mode:448}),ds(e,JSON.stringify(t,null,2)+`
27
- `),ms(e,384)}saveCredentials(e,t,r){this.writeSecure(this.credentialsPath(e,t),r)}loadCredentials(e,t){try{return JSON.parse(fn(this.credentialsPath(e,t),"utf-8"))}catch{return null}}saveClient(e,t,r){this.writeSecure(this.clientPath(e,t),r)}loadClient(e,t){try{return JSON.parse(fn(this.clientPath(e,t),"utf-8"))}catch{return null}}getActiveCredentials(){let e=this.getActiveProfile();if(!e)return{credentials:null,profile:null,env:null};let t=this.getDefaultEnv();return{credentials:this.loadCredentials(e,t),profile:e,env:t}}saveBasicAuth(e,t,r){this.writeSecure(this.basicAuthPath(e,t),r)}loadBasicAuth(e,t){try{return JSON.parse(fn(this.basicAuthPath(e,t),"utf-8"))}catch{return null}}deleteBasicAuth(e,t){try{dt(this.basicAuthPath(e,t))}catch{}}resolveAuth(){let e=this.getActiveProfile();if(!e)return null;let t=this.getDefaultEnv(),r=this.loadBasicAuth(e,t);return r?{method:"basic",...r,profile:e,env:t}:this.loadCredentials(e,t)?{method:"oauth",profile:e,env:t}:null}listProfiles(){let e=[];try{for(let t of sr(this.profilesDir)){let r=Me(this.profilesDir,t);try{for(let n of sr(r)){let s=Me(r,n),a=or(Me(s,"credentials")),o=or(Me(s,"client.json")),l=or(Me(s,"basic-auth"));(a||o||l)&&e.push({profile:t,env:n})}}catch{}}}catch{}return e}deleteProfile(e,t){try{dt(this.credentialsPath(e,t))}catch{}if(this.getActiveProfile()===e){let r=this.readConfig();delete r.active_profile,this.writeConfig(r)}}deleteProfileFull(e,t){if(t){try{dt(this.credentialsPath(e,t))}catch{}try{dt(this.clientPath(e,t))}catch{}try{dt(this.basicAuthPath(e,t))}catch{}try{dt(this.profileConfigPath(e,t))}catch{}}else try{let r=Me(this.profilesDir,e);for(let n of sr(r)){try{dt(Me(r,n,"credentials"))}catch{}try{dt(Me(r,n,"client.json"))}catch{}try{dt(Me(r,n,"basic-auth"))}catch{}try{dt(Me(r,n,"profile-config.json"))}catch{}}}catch{}}};var lr=G(ae(),1),ir=8,ar=7;function ps({onComplete:i}){let[e,t]=(0,Kt.useState)(0),[r,n]=(0,Kt.useState)(0),[s,a]=(0,Kt.useState)(!1),[o]=(0,Kt.useState)(()=>{let l=new Ee,c=l.getActiveProfile(),d=l.getDefaultEnv(),h=c?l.loadCredentials(c,d):null,x=c?l.loadBasicAuth(c,d):null;return{authenticated:!!(h||x),user:x?.username??c??null}});return an(()=>{t(l=>Math.min(ir,l+1))},e<ir?60:null),an(()=>{n(l=>Math.min(ar,l+1))},r<ar?80:null),(0,Kt.useEffect)(()=>{e>=ir&&r>=ar&&!s&&(a(!0),i?.())},[e,r,s,i]),(0,lr.jsx)(v,{flexDirection:"column",children:(0,lr.jsx)(An,{size:"full",helmetVisibleRows:e,textVisibleRows:r,showMeta:s,user:o.user,authenticated:o.authenticated,version:Pt})})}var vt=G(ae(),1);function hs({entry:i}){return i.type==="input"?(0,vt.jsxs)(v,{children:[(0,vt.jsx)(u,{color:m.purple,children:"\u276F "}),(0,vt.jsx)(u,{children:i.text})]}):i.type==="error"?(0,vt.jsx)(v,{marginLeft:2,children:(0,vt.jsx)(u,{color:m.red,children:i.text})}):(0,vt.jsx)(v,{marginLeft:2,children:(0,vt.jsx)(u,{color:i.type==="info"?m.dimmed:void 0,children:i.text})})}var $t=G(We(),1);var cr=G(We(),1);var ct=G(ae(),1);function gs({history:i,onSelect:e,onClose:t}){let[r,n]=(0,cr.useState)(""),[s,a]=(0,cr.useState)(0),o=r?i.search(r).slice(0,8):[];return Ze((l,c)=>{if(c.escape){t();return}if(c.return){o.length>0&&o[s]?e(o[s]):t();return}if(c.upArrow){a(d=>Math.max(0,d-1));return}if(c.downArrow){a(d=>Math.min(o.length-1,d+1));return}if(c.backspace||c.delete){n(d=>d.slice(0,-1)),a(0);return}l&&!c.ctrl&&!c.meta&&(n(d=>d+l),a(0))}),(0,ct.jsxs)(v,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,ct.jsx)(u,{color:m.muted,bold:!0,children:"reverse search"}),(0,ct.jsxs)(v,{gap:1,children:[(0,ct.jsx)(u,{color:m.dimmed,children:"search:"}),(0,ct.jsx)(u,{children:r}),(0,ct.jsx)(u,{color:m.purple,children:"\u2588"})]}),o.length>0&&(0,ct.jsx)(u,{children:" "}),o.map((l,c)=>(0,ct.jsx)(v,{marginLeft:2,children:(0,ct.jsxs)(u,{color:c===s?m.purple:m.dimmed,bold:c===s,children:[c===s?"\u25B8 ":" ",l]})},`${c}-${l}`))]})}var Ke=G(ae(),1);function xs({onSubmit:i,onEscape:e,history:t,placeholder:r="Type an objective or /command..."}){let[n,s]=(0,$t.useState)([]),[a,o]=(0,$t.useState)(0),[l,c]=(0,$t.useState)("none"),[d,h]=(0,$t.useState)(-1),x=(0,$t.useRef)(""),[S,p]=(0,$t.useState)(!0),{stdout:b}=Ot(),g=b?.columns??80,w=n.join(""),N=(()=>{if(l!=="none"||n.length===0||w.startsWith("/"))return"";let L=t.getAll();for(let M=L.length-1;M>=0;M--)if(L[M].startsWith(w)&&L[M]!==w)return L[M].slice(w.length);return""})();Ze((L,M)=>{if(S&&L&&p(!1),M.return){w.trim()&&(t.push(w.trim()),i(w.trim()),s([]),o(0),c("none"),h(-1),x.current="",p(!0));return}if(M.escape){l!=="none"?c("none"):n.length>0?(s([]),o(0),h(-1),x.current=""):e?.();return}if(M.tab){if(N){let A=w+N;s([...A]),o(A.length);return}return}if(M.ctrl&&L==="r"){c("search");return}if(M.ctrl&&L==="a"){o(0);return}if(M.ctrl&&L==="e"){o(n.length);return}if(M.ctrl&&L==="w"){if(a===0)return;let A=a-1;for(;A>0&&n[A]===" ";)A--;for(;A>0&&n[A-1]!==" ";)A--;let X=[...n.slice(0,A),...n.slice(a)];s(X),o(A);return}if(M.ctrl&&L==="u"){s([]),o(0),h(-1),c("none");return}if(M.meta&&L==="b"){let A=a-1;for(;A>0&&n[A]===" ";)A--;for(;A>0&&n[A-1]!==" ";)A--;o(Math.max(0,A));return}if(M.meta&&L==="f"){let A=a;for(;A<n.length&&n[A]!==" ";)A++;for(;A<n.length&&n[A]===" ";)A++;o(A);return}if(M.leftArrow){o(A=>Math.max(0,A-1));return}if(M.rightArrow){if(a>=n.length&&N){let A=w+N;s([...A]),o(A.length)}else o(A=>Math.min(n.length,A+1));return}if(M.upArrow){if(l==="none"){let A=t.getAll();if(A.length===0)return;if(d===-1){x.current=w,h(A.length-1);let X=A[A.length-1];s([...X]),o(X.length)}else if(d>0){let X=d-1;h(X);let f=A[X];s([...f]),o(f.length)}}return}if(M.downArrow){if(l==="none"){let A=t.getAll();if(d===-1)return;if(d<A.length-1){let X=d+1;h(X);let f=A[X];s([...f]),o(f.length)}else{h(-1);let X=x.current;s([...X]),o(X.length)}}return}if(M.backspace||M.delete){if(a>0){let A=[...n.slice(0,a-1),...n.slice(a)];s(A),o(a-1),h(-1)}return}if(L&&!M.ctrl&&!M.meta){let A=[...n.slice(0,a),...L,...n.slice(a)];s(A),o(a+L.length),h(-1)}},{isActive:l!=="search"});let W=L=>{s([...L]),o(L.length),c("none")},Q=()=>{c("none")},te=(()=>{if(S&&n.length===0)return null;let L=a>=n.length,M=n.slice(0,a).join(""),A=L?" ":n[a],X=L?"":n.slice(a+1).join(""),f="\u276F "+M+A+X+N,k=2,y=k+M.length,C=y+1,P=C+X.length,j=f.length,F=Math.max(1,Math.ceil(j/g)),Z=[];for(let Y=0;Y<F;Y++)Z.push({start:Y*g,end:Math.min((Y+1)*g,j)});return{full:f,p:k,b:y,c:C,a:P,lines:Z}})();return(0,Ke.jsxs)(v,{flexDirection:"column",children:[l==="search"&&(0,Ke.jsx)(gs,{history:t,onSelect:W,onClose:Q}),(0,Ke.jsx)(u,{color:m.muted,children:"\u2500".repeat(g)}),te===null?(0,Ke.jsxs)(v,{children:[(0,Ke.jsx)(u,{color:m.purple,children:"\u276F "}),(0,Ke.jsx)(u,{color:m.dimmed,children:r})]}):(0,Ke.jsx)(v,{flexDirection:"column",children:te.lines.map(({start:L,end:M},A)=>{let{full:X,p:f,b:k,c:y,a:C}=te,P=[];return M>0&&L<f&&P.push((0,Ke.jsx)(u,{color:m.purple,children:X.slice(Math.max(L,0),Math.min(f,M))},"p")),M>f&&L<k&&P.push((0,Ke.jsx)(u,{children:X.slice(Math.max(f,L),Math.min(k,M))},"b")),M>k&&L<y&&P.push((0,Ke.jsx)(u,{color:m.purple,inverse:!0,children:X.slice(Math.max(k,L),Math.min(y,M))},"c")),M>y&&L<C&&P.push((0,Ke.jsx)(u,{children:X.slice(Math.max(y,L),Math.min(C,M))},"a")),M>C&&P.push((0,Ke.jsx)(u,{color:m.dimmed,children:X.slice(Math.max(C,L),M)},"g")),(0,Ke.jsx)(v,{children:P},A)})})]})}var $e=G(We(),1);var bs=G(We(),1);var Tn=G(ae(),1),Ko="#ffc580",qo="#ffd9a8",vs="#ffffff";function _s({text:i,active:e=!0}){let[t,r]=(0,bs.useState)(0),n=4;if(an(()=>{r(a=>(a+1)%(i.length+n*2))},e?80:null),!e)return(0,Tn.jsx)(u,{color:vs,children:i});let s=i.split("").map((a,o)=>{let l=t-n,c=Math.abs(o-l-n/2),d;return c<=n/2?d=Ko:c<=n?d=qo:d=vs,(0,Tn.jsx)(u,{color:d,children:a},o)});return(0,Tn.jsx)(u,{children:s})}var qe=G(ae(),1),Jo={starting:m.cyan,running:m.purple,passed:m.green,failed:m.red,cancelled:m.dimmed,timed_out:m.yellow};function On({currentStep:i,maxSteps:e,elapsed:t,status:r}){let{stdout:n}=Ot(),s=n?.columns??80,a=Jo[r]??m.purple,o=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,qe.jsxs)(v,{flexDirection:"column",marginTop:1,children:[(0,qe.jsx)(u,{color:m.muted,children:"\u2500".repeat(Math.min(s,60))}),(0,qe.jsxs)(v,{children:[(0,qe.jsx)(u,{children:" "}),(0,qe.jsx)(u,{color:m.dimmed,children:"Steps "}),(0,qe.jsx)(u,{bold:!0,children:i}),(0,qe.jsxs)(u,{color:m.dimmed,children:["/",e]}),(0,qe.jsx)(u,{children:" "}),(0,qe.jsx)(u,{color:m.dimmed,children:"Elapsed "}),(0,qe.jsx)(u,{bold:!0,children:o}),(0,qe.jsx)(u,{children:" "}),(0,qe.jsx)(u,{color:m.dimmed,children:"Status "}),(0,qe.jsx)(u,{bold:!0,color:a,children:r})]})]})}var zo={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u26A1"};function ws(i){return zo[i]??"\u25CF"}var D=G(ae(),1);function Dt({step:i,indent:e=2}){let t=i.actionType?ws(i.actionType):null,r=i.status==="running",n=i.status==="passed",s=i.status==="failed",a=i.status==="pending"||i.status==="stopped",{stdout:o}=Ot(),l=o?.columns??80,c=Math.max(20,l-e-21),d=i.objective??"",h=d.length>c?d.slice(0,c-1)+"\u2026":d,x=(i.duration??0)*1e3,S=i.duration!=null?x<1e3?`${Math.round(x)}ms`:`${(x/1e3).toFixed(1)}s`:"";return(0,D.jsxs)(v,{flexDirection:"column",children:[(0,D.jsxs)(v,{marginLeft:e,children:[(0,D.jsx)(v,{width:4,children:(0,D.jsxs)(u,{color:m.muted,children:[String(i.index).padStart(2," ")," "]})}),(0,D.jsx)(v,{width:3,children:r?(0,D.jsx)(Gr,{}):n?(0,D.jsx)(u,{color:m.green,bold:!0,children:"\u2713"}):s?(0,D.jsx)(u,{color:m.red,bold:!0,children:"\u2717"}):(0,D.jsx)(u,{color:m.muted,children:"\u25CB"})}),(0,D.jsx)(v,{flexGrow:1,children:r?(0,D.jsx)(_s,{text:h,active:!0}):s?(0,D.jsx)(u,{color:m.red,children:h}):a?(0,D.jsx)(u,{color:m.dimmed,children:h}):(0,D.jsx)(u,{color:m.greenDim,children:h})}),(n||s)&&t?(0,D.jsx)(v,{width:3,marginLeft:1,children:(0,D.jsx)(u,{color:m.muted,children:t})}):(0,D.jsx)(v,{width:3,marginLeft:1}),(0,D.jsx)(v,{width:7,justifyContent:"flex-end",children:(0,D.jsx)(u,{color:m.dimmed,children:S})})]}),i.children&&i.children.length>0&&(0,D.jsx)(v,{flexDirection:"column",children:i.children.map((p,b)=>(0,D.jsx)(Dt,{step:p,indent:e+2},`child-${b}`))})]})}function Pn({steps:i,bifurcated:e,flows:t,cmInitCounts:r,maxSteps:n=50,staticSteps:s=!1,onStepCommit:a}){let o=(0,$e.useRef)(new Set),l=(0,$e.useRef)(!1),c=(0,$e.useRef)(new Set),d=(0,$e.useRef)(!1),h=(0,$e.useRef)(0);(0,$e.useEffect)(()=>{i.length===0&&h.current>0&&(o.current.clear(),l.current=!1,c.current.clear(),d.current=!1),h.current=i.length},[i.length]);let x=i.flatMap(f=>[f,...f.children??[]]),S=x.some(f=>f.status==="running"),p=x.some(f=>f.status==="failed"),b=x.length===0||x.every(f=>f.status==="pending"),g=x.filter(f=>f.status==="passed"||f.status==="failed").length,w;b?w="starting":S?w="running":p?w="failed":w="passed";let N=(0,$e.useRef)(null),[W,Q]=(0,$e.useState)(0);(0,$e.useEffect)(()=>{x.length===0||b?(N.current=null,Q(0)):S&&N.current==null&&(N.current=Date.now())},[S,b,x.length]),(0,$e.useEffect)(()=>{if(!S)return;let f=setInterval(()=>{N.current!=null&&Q((Date.now()-N.current)/1e3)},500);return()=>clearInterval(f)},[S]);let te=(0,$e.useRef)(new Set),[L,M]=(0,$e.useState)([]),A=(0,$e.useRef)(!1);(0,$e.useEffect)(()=>{if(!s||e)return;let f=[];if(!e&&!A.current&&r&&r[0]!=null&&(A.current=!0,f.push({key:"cm_init_0",type:"cm_init",count:r[0]})),e){!te.current.has(-1)&&i.length>0&&(te.current.add(-1),f.push({key:"bif_header",type:"bifurcation_header",flowCount:t?.length??i.length}));for(let k=0;k<i.length;k++){let y=i[k],C=-(k+10);te.current.has(C)||(te.current.add(C),f.push({key:`flow_header_${k}`,type:"flow_header",flowIdx:k,label:t?.[k]??y.objective,cmCount:r?.[k]}));for(let P of y.children??[])(P.status==="passed"||P.status==="failed")&&!te.current.has(P.index)&&(te.current.add(P.index),f.push({key:`step_f${k}_${P.index}`,type:"step",step:{...P}}))}}else for(let k of i)(k.status==="passed"||k.status==="failed")&&!te.current.has(k.index)&&(te.current.add(k.index),f.push({key:`step_${k.index}`,type:"step",step:{...k,children:k.children?[...k.children]:void 0}}));f.length>0&&M(k=>[...k,...f])},[i,e,t,r,s]),(0,$e.useEffect)(()=>{if(!a)return;!e&&!d.current&&r&&r[0]!=null&&(d.current=!0,a((0,D.jsx)(v,{marginLeft:2,children:(0,D.jsxs)(u,{color:m.dimmed,children:["\u25A0 Generated task with ",r[0]," checkpoints"]})}))),e&&t&&!l.current&&(l.current=!0,a((0,D.jsx)(u,{color:"#b388ff",children:"\u2501\u2501 Bifurcated into "+t.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"})));let f=e?i.flatMap((k,y)=>{let C=k.children??[];return!c.current.has(y)&&C.length>0&&(c.current.add(y),a((0,D.jsx)(u,{color:"#b388ff",children:" Flow "+(y+1)+": "+(t?.[y]??"")}))),C}):i.flatMap(k=>[k,...k.children??[]]);for(let k of f){let y=`${k.index}-${k.objective}`;o.current.has(y)||(k.status==="passed"||k.status==="failed"||k.status==="stopped")&&(o.current.add(y),a((0,D.jsx)(v,{marginLeft:2,children:(0,D.jsx)(Dt,{step:k})})))}},[i,a,e,t,r]);let X=[];if(a)if(e)for(let f of i){let y=(f.children??[]).filter(C=>{let P=`${C.index}-${C.objective}`;return!o.current.has(P)});y.length>0&&X.push({...f,children:y})}else for(let f of i){let k=`${f.index}-${f.objective}`;o.current.has(k)||X.push(f)}else if(s){if(!e)for(let f of i)te.current.has(f.index)||X.push(f)}if(!s){let f=a?X:i;return(0,D.jsxs)(v,{flexDirection:"column",children:[e?a?f.length>0?(0,D.jsx)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:f.map((y,C)=>(0,D.jsx)(v,{flexDirection:"column",marginTop:C>0?1:0,children:y.children&&y.children.length>0?y.children.map(P=>(0,D.jsx)(Dt,{step:P},`f${C}-${P.index}`)):y.status==="pending"&&(0,D.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})},C))}):null:(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,D.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",t?.length??i.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),i.map((y,C)=>(0,D.jsxs)(v,{flexDirection:"column",marginTop:C>0?1:0,children:[(0,D.jsxs)(u,{color:m.purple,children:["Flow ",C+1,": ",t?.[C]??y.objective]}),r&&r[C]!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",r[C]," checkpoints"]}),y.children&&y.children.length>0?y.children.map(P=>(0,D.jsx)(Dt,{step:P},`f${C}-${P.index}`)):y.status==="pending"&&(0,D.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},C))]}):(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&r&&r[0]!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",r[0]," checkpoints"]}),f.map(y=>(0,D.jsx)(Dt,{step:y},y.index))]}),S&&(0,D.jsx)(On,{currentStep:g,maxSteps:n,elapsed:W,status:w})]})}return e?(0,D.jsxs)(v,{flexDirection:"column",children:[(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,D.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",t?.length??i.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),i.map((f,k)=>(0,D.jsxs)(v,{flexDirection:"column",marginTop:k>0?1:0,children:[(0,D.jsxs)(u,{color:m.purple,children:["Flow ",k+1,": ",t?.[k]??f.objective]}),r&&r[k]!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",r[k]," checkpoints"]}),f.children&&f.children.length>0?f.children.map(y=>(0,D.jsx)(Dt,{step:y},`f${k}-${y.index}`)):f.status==="pending"&&(0,D.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},k))]}),S&&(0,D.jsx)(On,{currentStep:g,maxSteps:n,elapsed:W,status:w})]}):(0,D.jsxs)(v,{flexDirection:"column",children:[(0,D.jsx)(Xt,{items:L,children:f=>f.type==="cm_init"?(0,D.jsx)(v,{marginLeft:2,paddingLeft:1,children:(0,D.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",f.count," checkpoints"]})},f.key):f.type==="bifurcation_header"?(0,D.jsx)(v,{marginLeft:2,paddingLeft:1,children:(0,D.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",f.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},f.key):f.type==="flow_header"?(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,D.jsxs)(u,{color:m.purple,children:["Flow ",f.flowIdx+1,": ",f.label]}),f.cmCount!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",f.cmCount," checkpoints"]})]},f.key):(0,D.jsx)(v,{marginLeft:2,paddingLeft:1,children:(0,D.jsx)(Dt,{step:f.step})},f.key)}),X.length>0&&(0,D.jsx)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:X.map(f=>(0,D.jsx)(Dt,{step:f},f.index))}),S&&(0,D.jsx)(On,{currentStep:g,maxSteps:n,elapsed:W,status:w})]})}var ke=G(We(),1);import{readFileSync as Go,writeFileSync as ys,mkdirSync as Ss}from"fs";import{dirname as Cs}from"path";var Es={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:null,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"action",setup_complete:!1},et=class{constructor(e=Wr){this.path=e}load(){try{let e=Go(this.path,"utf-8"),t=JSON.parse(e);return{...Es,...t}}catch{return{...Es}}}set(e,t){let r=this.load();r[e]=t,Ss(Cs(this.path),{recursive:!0}),ys(this.path,JSON.stringify(r,null,2)+`
28
- `)}save(e){let r={...this.load(),...e};Ss(Cs(this.path),{recursive:!0}),ys(this.path,JSON.stringify(r,null,2)+`
29
- `)}};import{createServer as Ai}from"http";import{randomBytes as Ti}from"crypto";import{URL as Oi}from"url";import js from"process";import{Buffer as Us}from"buffer";import Vs from"path";import{fileURLToPath as bi}from"url";import{promisify as _i}from"util";import Ls from"child_process";import wi,{constants as yi}from"fs/promises";import Ts from"process";import Os,{constants as ti}from"fs/promises";import As from"process";import ei from"os";import mr from"fs";import Qo from"fs";import ks from"fs";var ur;function Xo(){try{return ks.statSync("/.dockerenv"),!0}catch{return!1}}function Yo(){try{return ks.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function dr(){return ur===void 0&&(ur=Xo()||Yo()),ur}var fr,Zo=()=>{try{return Qo.statSync("/run/.containerenv"),!0}catch{return!1}};function qt(){return fr===void 0&&(fr=Zo()||dr()),fr}var Rs=()=>{if(As.platform!=="linux")return!1;if(ei.release().toLowerCase().includes("microsoft"))return!qt();try{if(mr.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!qt()}catch{}return mr.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||mr.existsSync("/run/WSL")?!qt():!1},Bt=As.env.__IS_WSL_TEST__?Rs:Rs();var ni=(()=>{let i="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await Os.access(t,ti.F_OK),r=!0}catch{}if(!r)return i;let n=await Os.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(n);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):i}})(),ri=async()=>`${await ni()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,pr=async()=>Bt?ri():`${Ts.env.SYSTEMROOT||Ts.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function jt(i,e,t){let r=n=>Object.defineProperty(i,e,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get(){let n=t();return r(n),n},set(n){r(n)}}),i}import{promisify as hi}from"util";import br from"process";import{execFile as gi}from"child_process";import{promisify as si}from"util";import oi from"process";import{execFile as ii}from"child_process";var ai=si(ii);async function hr(){if(oi.platform!=="darwin")throw new Error("macOS only");let{stdout:i}=await ai("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(i)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import li from"process";import{promisify as ci}from"util";import{execFile as ui,execFileSync as nc}from"child_process";var di=ci(ui);async function Ps(i,{humanReadableOutput:e=!0,signal:t}={}){if(li.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await di("osascript",["-e",i,r],n);return s.trim()}async function gr(i){return Ps(`tell application "Finder" to set app_path to application file id "${i}" as string
30
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as fi}from"util";import{execFile as mi}from"child_process";var pi=fi(mi),In={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"}},lc=new Map(Object.entries(In)),xr=class extends Error{};async function vr(i=pi){let{stdout:e}=await i("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new xr(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,n=r.lastIndexOf("."),s=r.lastIndexOf("-"),a=n===-1?void 0:r.slice(0,n),o=s===-1?void 0:r.slice(0,s);return In[r]??In[a]??In[o]??{name:r,id:r}}var xi=hi(gi),vi=i=>i.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function _r(){if(br.platform==="darwin"){let i=await hr();return{name:await gr(i),id:i}}if(br.platform==="linux"){let{stdout:i}=await xi("xdg-mime",["query","default","x-scheme-handler/http"]),e=i.trim();return{name:vi(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(br.platform==="win32")return vr();throw new Error("Only macOS, Linux, and Windows are supported")}var Si=_i(Ls.execFile),wr=Vs.dirname(bi(import.meta.url)),Is=Vs.join(wr,"xdg-open"),{platform:Yt,arch:$s}=js;async function Ci(){let i=await pr(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Us.from(e,"utf16le").toString("base64"),{stdout:r}=await Si(i,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=r.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[n]?{id:s[n]}:{}}var Ds=async(i,e)=>{let t;for(let r of i)try{return await e(r)}catch(n){t=n}throw t},$n=async i=>{if(i={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...i},Array.isArray(i.app))return Ds(i.app,o=>$n({...i,app:o}));let{name:e,arguments:t=[]}=i.app??{};if(t=[...t],Array.isArray(e))return Ds(e,o=>$n({...i,app:{name:o,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let o={"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"},c=Bt?await Ci():await _r();if(c.id in o){let d=o[c.id];return e==="browserPrivate"&&t.push(l[d]),$n({...i,app:{name:Jt[d],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let r,n=[],s={};if(Yt==="darwin")r="open",i.wait&&n.push("--wait-apps"),i.background&&n.push("--background"),i.newInstance&&n.push("--new"),e&&n.push("-a",e);else if(Yt==="win32"||Bt&&!qt()&&!e){r=await pr(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Bt||(s.windowsVerbatimArguments=!0);let o=["Start"];i.wait&&o.push("-Wait"),e?(o.push(`"\`"${e}\`""`),i.target&&t.push(i.target)):i.target&&o.push(`"${i.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),o.push("-ArgumentList",t.join(","))),i.target=Us.from(o.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let o=!wr||wr==="/",l=!1;try{await wi.access(Is,yi.X_OK),l=!0}catch{}r=js.versions.electron??(Yt==="android"||o||!l)?"xdg-open":Is}t.length>0&&n.push(...t),i.wait||(s.stdio="ignore",s.detached=!0)}Yt==="darwin"&&t.length>0&&n.push("--args",...t),i.target&&n.push(i.target);let a=Ls.spawn(r,n,s);return i.wait?new Promise((o,l)=>{a.once("error",l),a.once("close",c=>{if(!i.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}o(a)})}):(a.unref(),a)},Ei=(i,e)=>{if(typeof i!="string")throw new TypeError("Expected a `target`");return $n({...e,target:i})};function Bs(i){if(typeof i=="string"||Array.isArray(i))return i;let{[$s]:e}=i;if(!e)throw new Error(`${$s} is not supported`);return e}function Dn({[Yt]:i},{wsl:e}){if(e&&Bt)return Bs(e);if(!i)throw new Error(`${Yt} is not supported`);return Bs(i)}var Jt={};jt(Jt,"chrome",()=>Dn({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"]}}));jt(Jt,"brave",()=>Dn({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"]}}));jt(Jt,"firefox",()=>Dn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));jt(Jt,"edge",()=>Dn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));jt(Jt,"browser",()=>"browser");jt(Jt,"browserPrivate",()=>"browserPrivate");var Ms=Ei;import{createHash as ki,randomBytes as Ri}from"crypto";var Ge=class{authBaseUrl;consentUrl;constructor(e="prod"){let t=ce(e);this.authBaseUrl=t.authBaseUrl,this.consentUrl=t.consentUrl}static generatePkce(){let e=Ri(96).toString("base64url").slice(0,128),t=ki("sha256").update(e).digest("base64url");return[e,t]}buildAuthorizationUrl(e,t,r,n){let s=new URLSearchParams({response_type:"code",client_id:e,redirect_uri:n,scope:zr,code_challenge:t,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${s.toString()}`}async registerClient(e){let t=await fetch(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Jr,redirect_uris:[e],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!t.ok)throw new Error(`DCR failed: ${t.status} ${await t.text()}`);return t.json()}async exchangeCode(e,t,r,n){let s=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:n,client_id:t,code_verifier:r})});if(!s.ok)throw new Error(`Token exchange failed: ${s.status}`);return s.json()}async refreshToken(e,t){let r=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:t})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(e,t,r="access_token"){await fetch(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,token_type_hint:r,client_id:t})})}};var bt=class{profile;environment;creds;oauth;constructor(e="default",t="prod",r){this.profile=e,this.environment=t,this.creds=r??new Ee,this.oauth=new Ge(t)}async login(){let{server:e,port:t}=await this.startCallbackServer(),r=qr(t);try{let n=this.creds.loadClient(this.profile,this.environment);n||(n=await this.oauth.registerClient(r),this.creds.saveClient(this.profile,this.environment,n));let s=n.client_id,[a,o]=Ge.generatePkce(),l=Ti(32).toString("hex"),c=this.oauth.buildAuthorizationUrl(s,o,l,r),d=await this.waitForCallback(e,t,c,l);if(!d)throw new Error("Login cancelled or timed out");let h=await this.oauth.exchangeCode(d,s,a,r),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(n){throw e.close(),n}}startCallbackServer(){return new Promise((e,t)=>{let r=zn,n=()=>{let s=Ai();s.on("error",a=>{a.code==="EADDRINUSE"&&r<Gn?(r++,n()):t(new Error(`Failed to start callback server: ${a.message}. Ports ${zn}-${Gn} are all in use.`))}),s.listen(r,Jn,()=>{e({server:s,port:r})})};n()})}waitForCallback(e,t,r,n){return new Promise(s=>{let a=!1,o=l=>{a||(a=!0,e.close(),s(l))};e.on("request",(l,c)=>{let d=new Oi(l.url??"/",`http://${Jn}:${t}`);if(d.pathname!==Kr){c.writeHead(404),c.end();return}let h=d.searchParams.get("state"),x=d.searchParams.get("code");if(d.searchParams.get("error")){c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Login Failed</h1><p>You can close this tab.</p></body></html>"),o(null);return}if(h!==n){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Invalid State</h1></body></html>"),o(null);return}c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Login Successful!</h1><p>You can close this tab and return to the terminal.</p></body></html>"),o(x)}),Ms(r).catch(()=>{}),setTimeout(()=>o(null),12e4)})}};var I=G(ae(),1),Ns="https://kaneai-playground.lambdatest.io";function Fs({onComplete:i}){let[e]=(0,ke.useState)(()=>new et),[t]=(0,ke.useState)(()=>new Ee),[r,n]=(0,ke.useState)(process.env.KANE_DEV_MODE==="1"?"env":"auth"),[s,a]=(0,ke.useState)(0),[o,l]=(0,ke.useState)(""),[c,d]=(0,ke.useState)("username"),[h,x]=(0,ke.useState)(""),[S,p]=(0,ke.useState)(null),[b,g]=(0,ke.useState)(!1),[w,N]=(0,ke.useState)([]),[W,Q]=(0,ke.useState)([]),[te,L]=(0,ke.useState)(null),M=(0,ke.useCallback)(y=>{a(0),l(""),p(null),n(y)},[]),A=(0,ke.useCallback)(()=>{e.set("default_url",Ns),e.set("setup_complete",!0),M("modes")},[e,M]),X=(0,ke.useCallback)(async()=>{let{credentials:y,profile:C,env:P}=t.getActiveCredentials();if(!y||!C||!P)return null;let j=y.expires_at,F=Date.now()/1e3;if(j-F<300){let Z=t.loadClient(C,P);if(!Z)return null;let ue=await new Ge(P).refreshToken(y.refresh_token,Z.client_id),oe={access_token:ue.access_token,refresh_token:ue.refresh_token,expires_at:Math.floor(F)+ue.expires_in,scope:ue.scope};return t.saveCredentials(C,P,oe),oe.access_token}return y.access_token},[t]),f=(0,ke.useCallback)(async()=>{n("loading-projects");try{let y=t.resolveAuth();if(!y)throw new Error("No auth configured");let C=t.getDefaultEnv(),P=ce(C),j,F;if(y.method==="basic")j=y.username,F=y.access_key;else{let oe=await X();if(!oe)throw new Error("Could not get OAuth token");let de=await new ln(P.controllerBaseUrl,oe).getTmsCredentials();j=de.username,F=de.access_key}let ue=(await new It(P.tmsBaseUrl,j,F).listProjects()).map(oe=>({id:oe.project_id,label:`${oe.name} (${oe.project_id})`,isActive:oe.name.toLowerCase().includes("kaneai")}));if(ue.length===0){p("No projects found."),A();return}N(ue),n("project")}catch(y){p(`Could not fetch projects: ${y instanceof Error?y.message:y}`),A()}},[t,X,M,A]),k=(0,ke.useCallback)(async y=>{n("loading-folders");try{let C=t.resolveAuth();if(!C)throw new Error("No auth configured");let P=t.getDefaultEnv(),j=ce(P),F,Z;if(C.method==="basic")F=C.username,Z=C.access_key;else{let de=await X();if(!de)throw new Error("Could not get OAuth token");let sn=await new ln(j.controllerBaseUrl,de).getTmsCredentials();F=sn.username,Z=sn.access_key}let Y=new It(j.tmsBaseUrl,F,Z),ue=await Y.listFolders(y),oe=await Y.getDefaultFolder(y).catch(()=>null);L(oe);let Te=ue.map(de=>({id:de.id,label:`${de.name} (${de.id}) \xB7 ${de.test_cases_count} tests`,isActive:de.id===oe}));if(Te.length===0){oe&&e.set("folder_id",oe),A();return}Q(Te),n("folder")}catch{A()}},[t,X,e,A]);return Ze((y,C)=>{if(!b&&!(r==="loading-projects"||r==="loading-folders")){if(r==="modes"){C.return&&(n("done"),setTimeout(i,300));return}if(r==="env"||r==="auth"){if(C.upArrow)a(j=>Math.max(0,j-1));else if(C.downArrow)a(j=>Math.min(1,j+1));else if(C.return){if(r==="env"){let j=s===0?"prod":"stage";t.setDefaultEnv(j),M("auth")}else if(r==="auth")if(s===0){g(!0);let j=t.getDefaultEnv(),F="default";t.setActiveProfile(F),new bt(F,j,t).login().then(()=>{g(!1),f()}).catch(Y=>{g(!1),p(`Login failed: ${Y.message}`)})}else M("auth-basic"),d("username")}return}if(r==="auth-basic"){if(C.return)if(c==="username"){if(!o.trim()){p("Username is required");return}x(o.trim()),l(""),d("access_key"),p(null)}else{if(!o.trim()){p("Access key is required");return}let P="default",j=t.getDefaultEnv();t.setActiveProfile(P),t.saveBasicAuth(P,j,{username:h,access_key:o.trim()}),f()}else C.backspace||C.delete?l(P=>P.slice(0,-1)):y&&!C.ctrl&&!C.meta&&l(P=>P+y);return}}},{isActive:r!=="project"&&r!=="folder"}),(0,I.jsx)(v,{flexDirection:"column",padding:1,children:(0,I.jsx)(Cn,{title:"Kane CLI \u2014 First-time Setup",variant:r==="done"?"success":"default",children:(0,I.jsxs)(v,{flexDirection:"column",paddingY:1,children:[r==="env"&&(0,I.jsxs)(v,{flexDirection:"column",marginBottom:1,children:[(0,I.jsxs)(v,{children:[(0,I.jsx)(u,{color:m.purple,children:"?"}),(0,I.jsx)(u,{bold:!0,children:" Select environment"})]}),(0,I.jsxs)(v,{marginLeft:2,flexDirection:"column",children:[(0,I.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","prod"]}),(0,I.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","stage"]})]})]}),r==="auth"&&(0,I.jsxs)(v,{flexDirection:"column",marginBottom:1,children:[(0,I.jsxs)(v,{children:[(0,I.jsx)(u,{color:m.purple,children:"?"}),(0,I.jsx)(u,{bold:!0,children:" Which authentication method?"})]}),(0,I.jsxs)(v,{marginLeft:2,flexDirection:"column",children:[(0,I.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","OAuth (browser login)"]}),(0,I.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","Basic (username + access key)"]})]}),b&&(0,I.jsx)(v,{marginTop:1,marginLeft:2,children:(0,I.jsx)(u,{color:m.cyan,children:"\u280B Opening browser for login\u2026"})})]}),r==="auth-basic"&&(0,I.jsxs)(v,{flexDirection:"column",children:[(0,I.jsxs)(v,{marginBottom:c==="access_key"?0:1,children:[(0,I.jsx)(u,{color:c==="access_key"?m.statusPass:m.primary,children:c==="access_key"?"\u2713":"?"}),(0,I.jsx)(u,{bold:!0,children:" Username: "}),c==="username"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(u,{color:m.base,children:o}),(0,I.jsx)(u,{color:m.primary,inverse:!0,children:" "})]}):(0,I.jsx)(u,{color:m.statusPass,children:h})]}),c==="access_key"&&(0,I.jsxs)(v,{marginBottom:1,children:[(0,I.jsx)(u,{color:m.primary,children:"?"}),(0,I.jsx)(u,{bold:!0,children:" Access Key: "}),(0,I.jsx)(u,{color:m.dim,children:"\u2022".repeat(o.length)}),(0,I.jsx)(u,{color:m.primary,inverse:!0,children:" "})]})]}),r==="loading-projects"&&(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.cyan,children:"\u280B Fetching projects\u2026"})}),r==="project"&&(0,I.jsx)(Xn,{title:"Select project",items:w,itemNoun:"projects",onSelect:y=>{e.set("project_id",y.id),k(y.id)},onCancel:()=>{A()}}),r==="loading-folders"&&(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.cyan,children:"\u280B Fetching folders\u2026"})}),r==="folder"&&(0,I.jsx)(Xn,{title:"Select folder",items:W,itemNoun:"folders",onSelect:y=>{e.set("folder_id",y.id),A()},onCancel:()=>{te&&e.set("folder_id",te),A()}}),r==="modes"&&(0,I.jsxs)(v,{flexDirection:"column",children:[(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.statusPass,bold:!0,children:"\u2713 Setup complete!"})}),(0,I.jsx)(v,{marginTop:1,children:(0,I.jsx)(En,{label:"Profile",value:t.getActiveProfile()??"default"})}),(0,I.jsx)(En,{label:"Environment",value:t.getDefaultEnv()}),(0,I.jsx)(En,{label:"Default URL",value:Ns}),(0,I.jsx)(v,{marginTop:1,flexDirection:"column",children:(0,I.jsx)(u,{bold:!0,color:m.primary,children:"Available modes:"})}),(0,I.jsxs)(v,{marginLeft:2,flexDirection:"column",marginTop:1,children:[(0,I.jsxs)(v,{children:[(0,I.jsx)(u,{bold:!0,color:m.base,children:"TUI "}),(0,I.jsx)(u,{color:m.dim,children:"Interactive menu + chat UI"})]}),(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.dim,children:" kane-cli"})}),(0,I.jsxs)(v,{marginTop:1,children:[(0,I.jsx)(u,{bold:!0,color:m.base,children:"CLI "}),(0,I.jsx)(u,{color:m.dim,children:"Headless single-run, JSON output"})]}),(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.dim,children:' kane-cli run "objective" --url <url>'})}),(0,I.jsxs)(v,{marginTop:1,children:[(0,I.jsx)(u,{bold:!0,color:m.base,children:"Agent "}),(0,I.jsx)(u,{color:m.dim,children:"Programmatic setup + run via CLI flags"})]}),(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.dim,children:" kane-cli setup --auth-method basic --username <u> --access-key <k>"})})]}),(0,I.jsxs)(v,{marginTop:1,children:[(0,I.jsx)(u,{color:m.dim,children:"Press "}),(0,I.jsx)(u,{bold:!0,color:m.primary,children:"Enter"}),(0,I.jsx)(u,{color:m.dim,children:" to launch TUI"})]})]}),r==="done"&&(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.statusPass,bold:!0,children:"Launching\u2026"})}),S&&(0,I.jsx)(v,{marginTop:1,children:(0,I.jsx)(u,{color:m.red,children:S})})]})})})}var _t=G(We(),1);var Je=G(ae(),1);function Pi(i,e){let t=[],n=Math.max(e-4,30);t.push({type:"title",text:i.title});for(let s=0;s<i.sections.length;s++){let a=i.sections[s];s>0&&t.push({type:"divider",text:"\u2500".repeat(n)}),a.label&&t.push({type:"header",text:a.label});let o=a.entries.length>0?Math.max(...a.entries.map(l=>l.key.length)):0;for(let l of a.entries){let c="\xB7".repeat(Math.max(2,o-l.key.length+3)),d=`${l.key} ${c} ${l.value}`;t.push({type:"entry",text:d,color:l.color})}}return t.push({type:"footer",text:"esc back"}),t}function Hs({data:i,width:e=60}){let t=Pi(i,e);return(0,Je.jsx)(v,{flexDirection:"column",borderStyle:"round",borderColor:m.primary,paddingX:2,paddingY:1,children:t.map((r,n)=>{if(r.type==="title")return(0,Je.jsx)(u,{color:m.primary,bold:!0,children:r.text},n);if(r.type==="header")return(0,Je.jsx)(v,{marginTop:1,children:(0,Je.jsx)(u,{color:m.dim,children:r.text})},n);if(r.type==="divider")return(0,Je.jsx)(v,{marginTop:1,marginBottom:0,children:(0,Je.jsx)(u,{color:m.ambient,children:r.text})},n);if(r.type==="footer")return(0,Je.jsx)(v,{marginTop:1,children:(0,Je.jsx)(u,{color:m.dim,children:r.text})},n);let s=r.text.match(/^(.+?) (·+) (.+)$/);return s?(0,Je.jsxs)(u,{children:[(0,Je.jsxs)(u,{color:m.secondary,children:[s[1]," "]}),(0,Je.jsxs)(u,{color:m.ambient,children:[s[2]," "]}),(0,Je.jsx)(u,{color:r.color??m.base,children:s[3]})]},n):(0,Je.jsx)(u,{color:r.color??m.base,children:r.text},n)})})}var Ne=G(ae(),1);function Ws(i,e){let t=[];function r(n,s){for(let a of n)t.push({item:a,depth:s}),a.type==="submenu"&&a.children&&e.length>s&&e[s]===a.id&&r(a.children,s+1)}return r(i,0),t}function Ks({items:i,onRunSelected:e,renderLoginWizard:t,renderProfilesView:r,renderChromeProfilePicker:n,renderProjectPicker:s,renderFolderPicker:a}){let[o,l]=(0,_t.useState)({expandedPath:[],selectedIndex:0,inputValue:"",isEditing:!1,isSelecting:!1,feedback:null,activeView:null,infoData:null}),c=Ws(i,o.expandedPath),d=c[o.selectedIndex]?.item,h=(0,_t.useRef)(null),x=(0,_t.useCallback)(p=>{l(b=>({...b,feedback:p})),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{l(b=>({...b,feedback:null})),h.current=null},4e3)},[]);(0,_t.useEffect)(()=>()=>{h.current&&clearTimeout(h.current)},[]);let S=(0,_t.useCallback)(()=>{l(p=>({...p,activeView:null,infoData:null}))},[]);return Ze((p,b)=>{if(o.activeView==="infoView"){b.escape&&S();return}if(!(o.activeView==="loginWizard"||o.activeView==="profilesView"||o.activeView==="chromeProfilePicker"||o.activeView==="projectPicker"||o.activeView==="folderPicker")){if(o.isEditing){if(b.escape){l(g=>({...g,isEditing:!1,inputValue:""}));return}if(b.return){let g=o.inputValue.trim();if(d?.onValue&&g){let w=d.currentValue;d.onValue(g),x(w?`${d.label}: ${w} \u2192 ${g}`:`${d.label}: ${g}`)}l(w=>({...w,isEditing:!1,inputValue:""}));return}if(b.backspace||b.delete){l(g=>({...g,inputValue:g.inputValue.slice(0,-1)}));return}p&&!b.ctrl&&!b.meta&&l(g=>({...g,inputValue:g.inputValue+p}));return}if(o.isSelecting&&d?.options){let g=d.options;if(b.escape){l(w=>({...w,isSelecting:!1}));return}if(b.upArrow){l(w=>({...w,inputValue:String(Math.max(0,Number(w.inputValue||"0")-1))}));return}if(b.downArrow){l(w=>({...w,inputValue:String(Math.min(g.length-1,Number(w.inputValue||"0")+1))}));return}if(b.return){let w=Number(o.inputValue||"0"),N=g[w];if(N&&d.onValue){let W=d.currentValue;d.onValue(N.value),x(W?`${d.label}: ${W} \u2192 ${N.label}`:`${d.label}: ${N.label}`)}l(W=>({...W,isSelecting:!1,inputValue:""}));return}return}if(b.upArrow){l(g=>({...g,selectedIndex:Math.max(0,g.selectedIndex-1)}));return}if(b.downArrow){l(g=>({...g,selectedIndex:Math.min(c.length-1,g.selectedIndex+1)}));return}if(b.escape){l(g=>{if(g.expandedPath.length===0)return g;let w=g.expandedPath.slice(0,-1),N=Ws(i,w),W=g.expandedPath[g.expandedPath.length-1],Q=N.findIndex(te=>te.item.id===W);return{...g,expandedPath:w,selectedIndex:Q>=0?Q:0}});return}if(b.return&&d){if(d.id==="run-start"){e();return}if(d.type==="submenu"){let g=c[o.selectedIndex]?.depth??0;l(w=>({...w,expandedPath:[...w.expandedPath.slice(0,g),d.id],selectedIndex:w.selectedIndex+1}));return}if(d.onInfo){let g=d.onInfo();l(w=>({...w,activeView:"infoView",infoData:g}));return}if(d.onLoginWizard){d.onLoginWizard(),l(g=>({...g,activeView:"loginWizard"}));return}if(d.onProfilesView){d.onProfilesView(),l(g=>({...g,activeView:"profilesView"}));return}if(d.onChromeProfilePicker){d.onChromeProfilePicker(),l(g=>({...g,activeView:"chromeProfilePicker"}));return}if(d.onProjectPicker){d.onProjectPicker(),l(g=>({...g,activeView:"projectPicker"}));return}if(d.onFolderPicker){d.onFolderPicker(),l(g=>({...g,activeView:"folderPicker"}));return}if(d.type==="action"){d.onAction?.(),x(`${d.label} done`);return}if(d.type==="select"&&d.options){let g=d.options.findIndex(w=>w.value===d.currentValue);l(w=>({...w,isSelecting:!0,inputValue:String(Math.max(0,g))}));return}if(d.type==="text-input"){l(g=>({...g,isEditing:!0,inputValue:d.currentValue??""}));return}}}}),(0,Ne.jsx)(v,{flexDirection:"column",paddingX:1,children:o.activeView==="infoView"&&o.infoData?(0,Ne.jsx)(Hs,{data:o.infoData}):o.activeView==="loginWizard"&&t?t(S):o.activeView==="profilesView"&&r?r(S):o.activeView==="chromeProfilePicker"&&n?n(S):o.activeView==="projectPicker"&&s?s(S):o.activeView==="folderPicker"&&a?a(S):(0,Ne.jsxs)(Ne.Fragment,{children:[c.map(({item:p,depth:b},g)=>{let w=g===o.selectedIndex,N=" ".repeat(b),W=w?"\u276F ":" ",Q=p.type==="submenu"?o.expandedPath.includes(p.id)?"\u25BC ":"\u25B6 ":" ",te=p.currentValue!=null?` [${p.currentValue}]`:"";if(w&&o.isSelecting&&p.options){let L=Number(o.inputValue||"0");return(0,Ne.jsxs)(v,{flexDirection:"column",children:[(0,Ne.jsxs)(u,{color:m.cyan,children:[N,W,Q,p.label]}),p.options.map((M,A)=>(0,Ne.jsxs)(u,{color:A===L?m.cyan:void 0,children:[N," ",A===L?"\u276F ":" ",M.label]},M.value))]},p.id)}return w&&o.isEditing?(0,Ne.jsxs)(u,{color:m.cyan,children:[N,W,Q,p.label,": ",o.inputValue,(0,Ne.jsx)(u,{color:m.dimmed,children:"\u2588"})]},p.id):(0,Ne.jsxs)(u,{color:w?m.cyan:void 0,dimColor:!w&&b>0,children:[N,W,Q,p.label,(0,Ne.jsx)(u,{dimColor:!0,children:te})]},p.id)}),o.feedback&&(0,Ne.jsx)(v,{marginTop:1,children:(0,Ne.jsxs)(u,{color:m.green,children:["\u2713 ",o.feedback]})})]})})}import{randomBytes as Ii,randomUUID as $i}from"crypto";import{mkdirSync as Di,writeFileSync as qs,appendFileSync as Bi,existsSync as Js}from"fs";import{join as mn}from"path";var ji=mn(_e,"sessions"),Qt=class{sessionId;sessionDir;runs=[];_nextIndex=0;_started=!1;_testId=null;_testcaseId=null;_projectId=null;_uploadStatus="pending";_uploadAttempts=0;_uploadError=null;_firstObjective=null;_firstUrl=null;_commitId=null;_auteurVariables={};_screenshotSas=null;_model="";_environment="";_profile=null;_startedAt="";constructor(){let e=new Date,t=e.toISOString().slice(0,10),r=e.toTimeString().slice(0,8).replace(/:/g,"-"),n=Ii(3).toString("hex");this.sessionId=`${t}_${r}_${n}`,this.sessionDir=mn(ji,this.sessionId)}start(e){if(this._started)return;this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString(),Di(this.sessionDir,{recursive:!0});let t={session_id:this.sessionId,started_at:this._startedAt,model:e.model,environment:e.environment,profile:e.profile,objectives:[],runs:[],status:"in_progress"};qs(mn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
31
- `),this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`)}setAuteurVariables(e){Object.assign(this._auteurVariables,e)}get auteurVariables(){return this._auteurVariables}setScreenshotSas(e){this._screenshotSas=e}get screenshotSas(){return this._screenshotSas}get screenshotBaseUrl(){return this._screenshotSas?`${this._screenshotSas.base_url}/${this._screenshotSas.container}`:""}get startedAt(){return this._startedAt||new Date().toISOString()}log(e){this._log(e)}logCommand(e){this._log(`COMMAND ${e}`)}logRunStart(e,t,r){this._log(`RUN ${e} START objective="${t.slice(0,100)}" url=${r}`)}logRunEnd(e,t,r,n){let s=(r??0).toFixed(1),a=(n??"").slice(0,100);this._log(`RUN ${e} END status=${t} duration=${s}s summary="${a}"`)}logChromeLaunch(e,t){this._log(`CHROME LAUNCH port=${e} endpoint=${t}`)}finish(e="complete"){this._log(`SESSION END status=${e} total_runs=${this.runs.length}`);let t={session_id:this.sessionId,started_at:this._startedAt,ended_at:new Date().toISOString(),model:this._model,environment:this._environment,profile:this._profile,status:e,total_runs:this.runs.length,test_id:this._testId,testcase_id:this._testcaseId,commit_id:this._commitId,project_id:this._projectId,upload_status:this._uploadStatus,upload_attempts:this._uploadAttempts,last_upload_attempt:this._uploadAttempts>0?new Date().toISOString():null,upload_error:this._uploadError,runs:this.runs.map(r=>({index:r.index,objective:r.objective,status:r.status,summary:r.summary,run_dir:r.run_dir}))};Js(this.sessionDir)&&qs(mn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
32
- `)}nextRunIndex(){return this._nextIndex}addRunResult(e,t){this.runs.push(e),this._nextIndex+=t??1}getContext(){return{prior_runs:this.runs.map(e=>({index:e.index,objective:e.objective,summary:e.summary,status:e.status,memory:e.context.memory,variables:e.context.variables,pointer:e.context.pointer}))}}setTestId(e){this._testId=e}get testId(){return this._testId}setTestcaseId(e){this._testcaseId=e}get testcaseId(){return this._testcaseId}setProjectId(e){this._projectId=e}setFirstRun(e,t){this._firstObjective||(this._firstObjective=e,this._firstUrl=t)}get firstObjective(){return this._firstObjective}get firstUrl(){return this._firstUrl}generateCommitId(){return this._commitId=$i(),this._commitId}get commitId(){return this._commitId}getRunDirs(){let e=[];for(let t of this.runs)t.run_dirs&&t.run_dirs.length>0?e.push(...t.run_dirs):t.run_dir&&e.push(t.run_dir);return e}getRunObjectives(){let e=[];for(let t of this.runs)t.flow_objectives&&t.flow_objectives.length>0?e.push(...t.flow_objectives):e.push(t.objective);return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e){if(!this._started||!Js(this.sessionDir))return;let t=new Date().toISOString().slice(0,19).replace("T"," "),r=mn(this.sessionDir,"tui.log");Bi(r,`[${t}] ${e}
33
- `)}};var Fe=G(We(),1);function zs(){let[i]=(0,Fe.useState)(()=>new Ee),[e,t]=(0,Fe.useState)(()=>{let p=i.resolveAuth();if(!p)return!1;if(p.method==="basic")return!0;let{credentials:b}=i.getActiveCredentials();return b?b.expires_at>Date.now()/1e3:!1}),r=(0,Fe.useRef)(null),n=(0,Fe.useRef)(null),s=(0,Fe.useCallback)(()=>{let p=i.resolveAuth();return p?{method:p.method,profile:p.profile,env:p.env}:null},[i]),a=(0,Fe.useCallback)(async()=>{let{credentials:p,profile:b,env:g}=i.getActiveCredentials();if(!p||!b||!g)return null;let w=p.expires_at,N=Date.now()/1e3;if(w-N<300){if(n.current)return n.current;let W=(async()=>{let Q=i.loadClient(b,g);if(!Q)return null;try{let L=await new Ge(g).refreshToken(p.refresh_token,Q.client_id),M={access_token:L.access_token,refresh_token:L.refresh_token,expires_at:Math.floor(N)+L.expires_in,scope:L.scope};return i.saveCredentials(b,g,M),t(!0),M.access_token}catch{return t(!1),null}finally{n.current=null}})();return n.current=W,W}return t(!0),p.access_token},[i]),o=(0,Fe.useCallback)(()=>{let p=i.resolveAuth();return!p||p.method!=="basic"?null:{username:p.username,access_key:p.access_key}},[i]),l=(0,Fe.useCallback)((p,b)=>{r.current?.revoke();let g=ce(p),w=o(),N=new cn(g.controllerBaseUrl,a,w,b);return r.current=N,N},[o,a]),c=(0,Fe.useCallback)(()=>r.current,[]),d=(0,Fe.useCallback)(()=>{let p=o();if(p)return p;let b=r.current?.cached;return b?{username:b.username,access_key:b.access_key}:null},[o]),h=(0,Fe.useCallback)(async()=>{let p=r.current;return p?p.resolve():null},[]),x=(0,Fe.useCallback)(async(p="default")=>{let b=i.getDefaultEnv();await new bt(p,b,i).login(),t(!0)},[i]),S=(0,Fe.useCallback)(async()=>{let p=i.getActiveProfile();if(!p)return null;let b=i.getDefaultEnv(),g=i.loadCredentials(p,b),w=i.loadClient(p,b);if(g&&w){let W=new Ge(b);W.revokeToken(g.access_token,w.client_id,"access_token").catch(()=>{}),W.revokeToken(g.refresh_token,w.client_id,"refresh_token").catch(()=>{})}i.deleteProfileFull(p,b);let N=i.listProfiles();return N.length>0&&(i.setActiveProfile(N[0].profile),i.setDefaultEnv(N[0].env)),t(!1),{profile:p,env:b}},[i]);return{creds:i,tokenValid:e,setTokenValid:t,getToken:a,getBasicAuth:o,getAuthInfo:s,login:x,logout:S,initResolver:l,getResolver:c,getResolvedBasicAuth:d,resolveBasicAuth:h}}var ft=G(We(),1);import{spawn as Gs}from"child_process";import{existsSync as Ui}from"fs";import{createConnection as Vi}from"net";import{homedir as pn,platform as yr}from"os";import{join as hn}from"path";var Xs={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",hn(pn(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",hn(pn(),"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",hn(pn(),"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",hn(pn(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",hn(pn(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function Li(){let i=yr(),e=Xs[i]??Xs.linux;for(let t of e)if(Ui(t))return t;return i==="win32"?"chrome.exe":"google-chrome"}function Mi(i){let e=yr(),t=[`--remote-debugging-port=${i.port}`,`--user-data-dir=${i.userDataDir}`,`--window-size=${i.width},${i.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 e==="linux"&&(t.push("--no-sandbox"),t.push("--disable-dev-shm-usage"),t.push("--password-store=basic")),e==="darwin"&&t.push("--use-mock-keychain"),i.headless&&t.push("--headless=new"),t}function Ni(i){return new Promise(e=>{let t=Vi({port:i,host:"127.0.0.1"});t.setTimeout(1e3),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{t.destroy(),e(!1)})})}async function Fi(){for(let i=Kn;i<=qn;i++)if(!await Ni(i))return i;throw new Error(`All CDP ports ${Kn}-${qn} are in use. Close other Chrome instances.`)}async function Hi(i,e=15e3){let t=Date.now(),r=`http://127.0.0.1:${i}/json/version`;for(;Date.now()-t<e;){try{if((await fetch(r)).ok)return`http://127.0.0.1:${i}`}catch{}await new Promise(n=>setTimeout(n,200))}throw new Error(`Chrome CDP not ready after ${e}ms on port ${i}`)}async function Bn(i){let e=yr(),t=await Fi(),r=Li(),n=Mi({port:t,...i});i.startUrl&&n.push(i.startUrl);let s=Gs(r,n,{stdio:"ignore",detached:!0,windowsHide:!0});s.unref();let a=await new Promise((o,l)=>{s.on("error",c=>{l(new Error(`Failed to launch Chrome: ${c.message}. Is Chrome installed at ${r}?`))}),s.on("close",c=>{c!==null&&c!==0&&l(new Error(`Chrome exited during startup with code ${c}`))}),Hi(t).then(o,l)});return{process:s,port:t,cdpEndpoint:a,kill(){try{if(s.pid)if(e==="win32")Gs("taskkill",["/pid",String(s.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-s.pid,"SIGKILL")}catch{s.kill("SIGKILL")}else s.kill("SIGKILL")}catch{}}}}import{mkdtempSync as Wi,rmSync as Ki}from"fs";import{join as qi}from"path";import{tmpdir as Ji}from"os";function Ys(){let[i]=(0,ft.useState)(()=>new et),e=(0,ft.useRef)(null),t=(0,ft.useRef)(null),r=(0,ft.useRef)(null),[n,s]=(0,ft.useState)(!1),a=(0,ft.useCallback)(async l=>{if(e.current)return e.current;if(r.current)return r.current;let c=(async()=>{let d=i.load(),h;if(d.chrome_profile_path)h=d.chrome_profile_path.replace("~",process.env.HOME??"~");else{let S=Wi(qi(Ji(),"kane-clean-"));t.current=S,h=S}let x=await Bn({userDataDir:h,width:d.window_size.width,height:d.window_size.height,startUrl:l??d.default_url??void 0});return e.current=x,Zr(()=>x.kill()),s(!0),x})();r.current=c;try{return await c}finally{r.current=null}},[i]),o=(0,ft.useCallback)(()=>{if(e.current?.kill(),e.current=null,t.current){try{Ki(t.current,{recursive:!0,force:!0})}catch{}t.current=null}s(!1)},[]);return{ensureChrome:a,killChrome:o,ready:n}}var Re=G(We(),1);import{spawn as Gi,execSync as Xi}from"child_process";import{existsSync as jn}from"fs";import{resolve as He,dirname as Yi}from"path";import{fileURLToPath as Qi}from"url";import{createInterface as zi}from"readline";async function*Qs(i){let e=zi({input:i,crlfDelay:1/0});for await(let t of e){let r=t.trim();if(r)try{let n=JSON.parse(r);n&&typeof n.type=="string"&&(yield n)}catch{}}}var wt=Yi(Qi(import.meta.url));function Zi(){for(let i of["python3","python"])try{return Xi(`${i} --version`,{stdio:"ignore"}),i}catch{}return null}function ea(){let e=process.platform==="win32"?"v16-runner.exe":"v16-runner",t={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},r=`${process.platform}-${process.arch}`,n=t[r];if(n)for(let o of n){let l=[He(wt,"..","node_modules",o,"bin",e),He(wt,"..","..","node_modules",o,"bin",e),He(wt,"..","..","..","node_modules",o,"bin",e)];for(let c of l)if(jn(c))return{cmd:c,args:[]}}let s=[He(wt,"bin",e),He(wt,"..","bin",e),He(wt,"..","..","..","..","v16-runner","dist",e),He(wt,"..","..","..","v16-runner","dist",e),He(process.cwd(),"v16-runner","dist",e),He(process.cwd(),"..","v16-runner","dist",e)];for(let o of s)if(jn(o))return{cmd:o,args:[]};let a=[He(wt,"..","..","..","..","v16-runner"),He(wt,"..","..","..","v16-runner"),He(process.cwd(),"v16-runner"),He(process.cwd(),"..","v16-runner")];for(let o of a)if(jn(He(o,"main.py"))){for(let c of[He(o,".venv","bin","python"),He(o,"..","browser-agent",".venv","bin","python")])if(jn(c))return{cmd:c,args:["main.py"],cwd:o};let l=Zi();if(l)return{cmd:l,args:["main.py"],cwd:o}}return null}function Un(i,e){let t=ea();if(!t)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");let r={...process.env};e?.environment&&(r.TESTMUAI_ENV=e.environment),r.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(r.PYTHONIOENCODING="utf-8"),r.V16_SERVER_API_HOST=ce(e?.environment).v16ServerHost,i.username&&i.access_key&&(r.LT_USERNAME=i.username,r.LT_ACCESS_KEY=i.access_key);let n=Gi(t.cmd,t.args,{stdio:["pipe","pipe","pipe"],env:r,cwd:t.cwd});n.stdin.on("error",()=>{}),n.stdin.write(JSON.stringify(i)+`
34
- `);let s=1e5,a="";n.stderr.on("data",h=>{a+=h.toString(),a.length>s&&(a=a.slice(-s))});let o=null,l=null,c=new Promise(h=>{n.on("close",(x,S)=>{o=x,l=S?String(S):null,h({code:x,signal:l})})}),d=Qs(n.stdout);return{child:n,events:d,sendUserResponse(h){let x=JSON.stringify({type:"user_response",answer:h});try{n.stdin.write(x+`
35
- `)}catch{}},sendCancel(h){let x=JSON.stringify({type:"cancel",reason:h});try{n.stdin.write(x+`
36
- `)}catch{}},cancel(){n.kill("SIGTERM")},get stderr(){return a},get exitCode(){return o},get exitSignal(){return l},exited:c}}function Sr(i){let e=i.indexOf(": ");return e>0&&e<15?i.slice(e+2):i}function Cr(i){return i.map(e=>{let t=e.children?Cr(e.children):e.children;return e.status==="running"?{...e,status:"stopped",phase:void 0,children:t}:t!==e.children?{...e,children:t}:e})}function Vn(i){let[e,t]=(0,Re.useState)(!1),[r,n]=(0,Re.useState)([]),[s,a]=(0,Re.useState)(null),[o,l]=(0,Re.useState)(null),[c,d]=(0,Re.useState)(null),[h,x]=(0,Re.useState)(null),[S,p]=(0,Re.useState)([]),b=(0,Re.useRef)(null),g=(0,Re.useRef)(null),w=(0,Re.useRef)(0),N=(0,Re.useRef)(!1),W=(0,Re.useCallback)((L,M)=>{b.current&&(b.current.cancel(),b.current=null),n([]),a(null),l(null),d(null),x(null),p([]),t(!0),g.current=null,w.current=0;let A=Un(L,M);b.current=A,(async()=>{N.current=!1;for await(let f of A.events){if(N.current)break;switch(f.type){case"run_start":if(g.current&&!g.current.isSingleFlow){let k=w.current;w.current++,n(y=>y.map((C,P)=>P===k?{...C,status:"running"}:C.status==="running"&&!C.children?.some(j=>j.status==="running")?{...C,status:C.children?.some(j=>j.status==="failed")?"failed":"passed"}:C))}break;case"bifurcation":{let k=f.flows??[],y=f.count??k.length,C={flows:k,isSingleFlow:f.is_single_flow??y<=1};x(C),g.current=C,w.current=0,n(k.map((P,j)=>({index:j+1,objective:P??`Flow ${j+1}`,status:"pending"})));break}case"step_start":{let k=f.index,y=f.objective??`Step ${k}`,C=f.child_id,P=g.current&&!g.current.isSingleFlow;if(C)n(j=>{let F=j.findIndex(Te=>Te.status==="running"||Te.children?.some(de=>de.status==="running"));if(F===-1)return j;let Z=[...j],Y={...Z[F]},oe=[...Y.children??[]].map(Te=>Te.status==="running"?{...Te,status:"stopped",phase:void 0}:Te);return oe.push({index:k,objective:y,status:"running"}),Y.children=oe,Z[F]=Y,Z});else if(P){let j=Math.max(0,w.current-1);n(F=>{let Z=[...F];if(j>=Z.length)return F;let Y={...Z[j]},oe=[...Y.children??[]].map(Te=>Te.status==="running"?{...Te,status:"stopped",phase:void 0}:Te);return oe.push({index:k,objective:y,status:"running"}),Y.children=oe,Y.status="running",Z[j]=Y,Z})}else n(j=>{let F=Cr(j);return F.some(Y=>Y.index===k)?F.map(Y=>Y.index===k?{...Y,status:"running",objective:y}:Y):[...F,{index:k,objective:y,status:"running"}]});break}case"step_event":{let k=f.child_id,y=g.current&&!g.current.isSingleFlow;if(f.event==="cm_init"&&f.checkpoint_count!=null){p(C=>[...C,f.checkpoint_count]);break}if(k)n(C=>C.map(P=>{if(!P.children)return P;let j=P.children.map(F=>{if(F.index!==f.index)return F;let Z={phase:f.event};return f.event==="reasoning"&&f.detail&&f.detail!=="reasoning"&&(Z.objective=f.detail),f.action_type&&(Z.actionType=f.action_type),{...F,...Z}});return{...P,children:j}}));else if(y){let C=Math.max(0,w.current-1);n(P=>{let j=[...P];if(C>=j.length)return P;let F={...j[C]},Z=[...F.children??[]];if(!Z.some(ue=>ue.index===f.index))Z.push({index:f.index,objective:`Step ${f.index}`,status:"running",phase:f.event,actionType:f.action_type});else for(let ue=0;ue<Z.length;ue++){if(Z[ue].index!==f.index)continue;let oe={phase:f.event};f.event==="reasoning"&&f.detail&&f.detail!=="reasoning"&&(oe.objective=f.detail),f.action_type&&(oe.actionType=f.action_type),Z[ue]={...Z[ue],...oe}}return F.children=Z,j[C]=F,j})}else n(C=>C.some(j=>j.index===f.index)?C.map(j=>{if(j.index!==f.index)return j;let F={phase:f.event};return f.event==="reasoning"&&f.detail&&f.detail!=="reasoning"&&(F.objective=f.detail),f.action_type&&(F.actionType=f.action_type),{...j,...F}}):[...Cr(C),{index:f.index,objective:`Step ${f.index}`,status:"running",phase:f.event,actionType:f.action_type}]);break}case"step_end":{let k=f.child_id,y=g.current&&!g.current.isSingleFlow;if(k)n(C=>C.map(P=>{if(!P.children)return P;let j=P.children.map(F=>F.index===f.index?{...F,status:f.status,duration:f.duration,phase:void 0,objective:F.objective.startsWith("Step ")?Sr(f.summary||F.objective):F.objective}:F);return{...P,children:j}}));else if(y){let C=Math.max(0,w.current-1);n(P=>{let j=[...P];if(C>=j.length)return P;let F={...j[C]},Z=(F.children??[]).map(Y=>Y.index===f.index?{...Y,status:f.status,duration:f.duration,phase:void 0,objective:Y.objective.startsWith("Step ")?Sr(f.summary||Y.objective):Y.objective}:Y);return F.children=Z,j[C]=F,j})}else n(C=>C.map(P=>P.index===f.index?{...P,status:f.status,duration:f.duration,phase:void 0,objective:P.objective.startsWith("Step ")?Sr(f.summary||P.objective):P.objective}:P));if(!f.child_id){let P=g.current&&!g.current.isSingleFlow?Math.max(0,w.current-1):0;i?.(f.index,P)}break}case"child_agent_start":{let k=f.objective??"";n(y=>y.map(C=>C.status==="running"?{...C,objective:k,phase:`child: ${k.slice(0,50)}`}:C));break}case"child_agent_end":n(k=>k.map(y=>y.phase?.startsWith("child:")?{...y,phase:`child ${f.success?"done":"failed"}`}:y));break;case"ask_user":a(f.question??"");break;case"run_end":n(k=>k.map(y=>y.status==="running"?{...y,status:f.status,phase:void 0}:y)),l(f),t(!1),b.current=null;break;case"error":d(f.message??"Runner error"),n(k=>k.map(y=>y.status==="running"?{...y,status:"failed",phase:void 0}:y)),t(!1),b.current=null;break}}let X=b.current;if(X){let{code:f,signal:k}=await X.exited,y=X.stderr,C=[];f!==null&&f!==0&&C.push(`Runner exited with code ${f}`),k&&C.push(`Runner killed by signal ${k}`),y&&C.push(y),C.length>0&&d(C.join(`
37
- `))}t(!1),b.current=null})().catch(X=>{let f=b.current,k=[`Runner event loop error: ${X}`];f&&(f.exitCode!==null&&f.exitCode!==0&&k.push(`Exit code: ${f.exitCode}`),f.exitSignal&&k.push(`Signal: ${f.exitSignal}`),f.stderr&&k.push(f.stderr)),d(k.join(`
38
- `)),t(!1),b.current=null})},[i]),Q=(0,Re.useCallback)(L=>{b.current?.sendUserResponse(L),a(null)},[]),te=(0,Re.useCallback)(()=>{let L=b.current;L&&(L.sendCancel("user"),t(!1),a(null),setTimeout(()=>{b.current===L&&(L.cancel(),b.current=null)},5e3))},[]);return(0,Re.useEffect)(()=>()=>{N.current=!0,b.current?.cancel(),b.current=null},[]),{isRunning:e,steps:r,askingUser:s,lastRunEnd:o,runError:c,bifurcationInfo:h,cmInitCounts:S,startRun:W,sendAnswer:Q,cancelRun:te}}var ta=null;function Zs(i){ta=i}import{readdirSync as na,readFileSync as to,existsSync as no}from"fs";import{join as ra}from"path";function eo(i,e){if(!no(i))return{};let t={},r;try{r=na(i).filter(n=>n.endsWith(".json")).sort()}catch{return{}}for(let n of r)try{let s=to(ra(i,n),"utf-8"),a=JSON.parse(s);if(a&&typeof a=="object"){for(let[o,l]of Object.entries(a))if(l&&typeof l=="object"&&"value"in l){let c=l;t[o]={value:c.value,secret:c.secret??!1,syntax:c.syntax??`{{${o}}}`}}}}catch{e?.(`Warning: skipping invalid variables file: ${n}`)}return t}function ro(i){no(i)||(console.error(`Variables file not found: ${i}`),process.exit(2));let e=to(i,"utf-8"),t=JSON.parse(e),r={};if(t&&typeof t=="object"){for(let[n,s]of Object.entries(t))if(s&&typeof s=="object"&&"value"in s){let a=s;r[n]={value:a.value,secret:a.secret??!1,syntax:a.syntax??`{{${n}}}`}}}return r}function so(i){let e;try{e=JSON.parse(i)}catch{console.error("Invalid --variables JSON"),process.exit(2)}let t={};if(e&&typeof e=="object"){for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&"value"in n){let s=n;t[r]={value:s.value,secret:s.secret??!1,syntax:s.syntax??`{{${r}}}`}}}return t}function Ln(i,e,t){let r=eo(i,t),n=eo(e,t);return{...r,...n}}import{readFileSync as sa,existsSync as oa}from"fs";function Zt(i){if(!oa(i))return null;try{return sa(i,"utf-8").trim()||null}catch{return null}}function Mn(i,e){let t={},r={},n=e;for(let[s,a]of Object.entries(i))if(a.secret){let o=`secrets.user.${s}`;t[o]={value:a.value,secret:!0,syntax:`{{secrets.user.${s}}}`,type:"secret"},r[s]=o,n=n.replaceAll(`{{${s}}}`,`{{secrets.user.${s}}}`)}else{let o=`global.${s}`;t[o]={value:a.value,secret:!1,syntax:`{{global.${s}}}`,type:"global"},r[s]=o,n=n.replaceAll(`{{${s}}}`,`{{global.${s}}}`)}return{variables:t,objective:n,keyMap:r}}import{readFileSync as lo,readdirSync as ca,existsSync as gn}from"fs";import{dirname as ua,join as De}from"path";var tt=G(We(),1);var Xe=G(ae(),1),ia=64;function aa(i){return i.split(`
39
- `).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function Er({status:i,summary:e,duration:t,steps:r,stepsPassed:n,stepsFailed:s,reason:a}){let o=i==="passed",l=o?m.green:m.red,c=o?"\u2713":"\u2717",d=i.toUpperCase(),h=n??(o?r:Math.max(0,r-1)),x=s??(o?0:1),S=x>0?`${r} steps (${h} passed, ${x} failed)`:`${r} steps`,p=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,b=aa(e);return(0,Xe.jsx)(v,{flexDirection:"column",marginTop:1,children:(0,Xe.jsxs)(v,{borderStyle:"round",borderColor:l,flexDirection:"column",paddingX:2,paddingY:1,width:ia+6,children:[(0,Xe.jsxs)(v,{children:[(0,Xe.jsxs)(u,{bold:!0,color:l,children:[c," ",d]}),(0,Xe.jsxs)(u,{color:m.dimmed,children:[" ","\xB7 ",S," \xB7 ",p]})]}),b.length>0&&(0,Xe.jsx)(v,{flexDirection:"column",marginTop:1,marginLeft:1,children:b.map((g,w)=>(0,Xe.jsxs)(v,{marginBottom:w<b.length-1?1:0,children:[(0,Xe.jsx)(u,{color:m.primary,children:"\u25CF "}),(0,Xe.jsx)(v,{flexShrink:1,children:(0,Xe.jsx)(u,{wrap:"wrap",children:g})})]},w))}),a&&!o&&(0,Xe.jsx)(v,{marginTop:1,children:(0,Xe.jsxs)(u,{color:m.red,wrap:"wrap",children:["Reason: ",a]})})]})})}var Ye=G(ae(),1);function oo({message:i,code:e,remediation:t,docsUrl:r}){return(0,Ye.jsx)(Cn,{title:"Error",variant:"error",children:(0,Ye.jsxs)(v,{flexDirection:"column",paddingY:1,children:[(0,Ye.jsxs)(u,{color:m.red,bold:!0,children:[" \u2717 ",i]}),e&&(0,Ye.jsxs)(v,{marginTop:0,marginLeft:5,children:[(0,Ye.jsx)(u,{color:m.muted,children:"Code: "}),(0,Ye.jsx)(u,{color:m.dimmed,children:e})]}),t&&(0,Ye.jsxs)(v,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,Ye.jsx)(u,{color:m.green,bold:!0,children:"Fix:"}),(0,Ye.jsxs)(u,{color:m.cyan,children:["$ ",t]})]}),r&&(0,Ye.jsxs)(v,{marginTop:1,marginLeft:5,children:[(0,Ye.jsx)(u,{color:m.muted,children:"Docs: "}),(0,Ye.jsx)(u,{color:m.cyan,underline:!0,children:r})]})]})})}var Ae=G(ae(),1);function io({data:i,color:e}){let t=i.status==="passed"?"passed":"failed";return(0,Ae.jsx)(Er,{status:t,summary:i.summary??"",duration:i.duration,steps:i.stepsTotal,stepsPassed:i.stepsPassed,stepsFailed:i.stepsFailed,reason:i.reason})}function ao({config:i,spawnOpts:e,cancelRef:t,banner:r,onComplete:n,onStepEnd:s}){let{exit:a}=Sn(),o=Vn(s),l=(0,tt.useRef)(!1),c=(0,tt.useRef)(!1),[d,h]=(0,tt.useState)("");(0,tt.useEffect)(()=>{l.current||(l.current=!0,o.startRun(i,e))},[i,e,o]),(0,tt.useEffect)(()=>{t&&(t.current=()=>o.cancelRun())},[t,o]);let x=(0,tt.useRef)(0);Ze((b,g)=>{g.ctrl&&b==="c"&&(o.isRunning?(x.current++,x.current>=2?a():o.cancelRun()):a())}),Ze((b,g)=>{o.askingUser&&(g.return?(o.sendAnswer(d),h("")):g.backspace||g.delete?h(w=>w.slice(0,-1)):b&&!g.ctrl&&!g.meta&&h(w=>w+b))},{isActive:!!o.askingUser}),(0,tt.useEffect)(()=>{if(!o.isRunning&&o.lastRunEnd&&!c.current){c.current=!0;let b=o.steps.flatMap(Q=>{let te=Q.children??[];return[Q,...te]}),g=b.filter(Q=>Q.status==="passed").length,w=b.filter(Q=>Q.status==="failed").length,N=b.filter(Q=>Q.status==="passed"||Q.status==="failed").length,W=o.bifurcationInfo;n({lastRunEnd:o.lastRunEnd,stepsPassed:g,stepsFailed:w,stepsTotal:N,hadError:!1,bifurcationFlows:W&&!W.isSingleFlow?W.flows:null}),a()}},[o.isRunning,o.lastRunEnd,o.steps,n,a]),(0,tt.useEffect)(()=>{o.runError&&!o.isRunning&&!c.current&&(c.current=!0,n({lastRunEnd:null,stepsPassed:0,stepsFailed:0,stepsTotal:0,hadError:!0,bifurcationFlows:null}),a())},[o.runError,o.isRunning,n,a]);let S=o.lastRunEnd?(()=>{let b=o.steps.flatMap(W=>[W,...W.children??[]]),g=b.filter(W=>W.status==="passed").length,w=b.filter(W=>W.status==="failed").length,N=b.filter(W=>W.status==="passed"||W.status==="failed").length;return{status:o.lastRunEnd.status,duration:o.lastRunEnd.duration??0,summary:o.lastRunEnd.summary??"",stepsPassed:g,stepsFailed:w,stepsTotal:N,reason:o.lastRunEnd.reason,finalState:o.lastRunEnd.final_state}})():null,p=(0,tt.useMemo)(()=>r?[{key:"banner",...r}]:[],[r]);return(0,Ae.jsxs)(v,{flexDirection:"column",children:[(0,Ae.jsx)(Xt,{items:p,children:b=>(0,Ae.jsxs)(v,{flexDirection:"column",marginBottom:1,children:[(0,Ae.jsxs)(v,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,Ae.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,Ae.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,Ae.jsx)(u,{color:m.cyan,children:b.model}),(0,Ae.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,Ae.jsx)(u,{color:m.dimmed,children:b.auth})]}),b.status?.map((g,w)=>(0,Ae.jsx)(u,{color:m.dimmed,children:g},w))]},b.key)}),o.steps.length>0&&(0,Ae.jsx)(Pn,{steps:o.steps,bifurcated:!!o.bifurcationInfo&&!o.bifurcationInfo.isSingleFlow,flows:o.bifurcationInfo?.flows,cmInitCounts:o.cmInitCounts,staticSteps:!0}),o.askingUser&&(0,Ae.jsxs)(v,{flexDirection:"column",marginTop:1,children:[(0,Ae.jsxs)(u,{color:m.yellow,children:['Agent is asking: "',o.askingUser,'"']}),(0,Ae.jsxs)(u,{children:["> ",d,"\u2588"]})]}),o.runError&&(0,Ae.jsx)(oo,{message:o.runError,code:"RUNNER_ERROR"}),S&&(0,Ae.jsx)(Er,{status:S.status==="passed"?"passed":"failed",summary:S.summary??"",duration:S.duration,steps:S.stepsTotal,stepsPassed:S.stepsPassed,stepsFailed:S.stepsFailed,reason:S.reason})]})}var en=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString("base64")}`,r=await fetch(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:t,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:e.secretKey,secretValue:e.secretValue,orgId:e.orgId,username:e.username,scope:"user",type:"user",accessKey:e.accessKey})});if(!r.ok)throw new Error(`Push secret failed: ${r.status} ${await r.text()}`)}static extractVariableKeys(e){let t=e.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),r=new Set;for(let n of t)r.add(n[1]);return[...r]}};var tn=class{constructor(e,t,r){this.baseUrl=e;this.authHeader=`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}authHeader;headers(){return{Authorization:this.authHeader,"Content-Type":"application/json",Accept:"application/json"}}async upsertVariable(e){let t=e.environmentId??0,r=await fetch(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:e.name,value:String(e.value),type:"variable",value_type:"string",is_persist:e.isPersist??!1,environment_id:t})});if(r.ok)return{id:(await r.json()).id??0};if(r.status!==409&&r.status!==422)return{id:0};if(!(await fetch(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(e.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(e.value),value_type:"string",type:"variable",environment_id:t})})).ok)return{id:0};let s=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${t}`,{method:"GET",headers:this.headers()});return s.ok?{id:(await s.json()).data?.id??0}:{id:0}}};import la from"sharp";var nn=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;constructor(e,t=3){this.sas=e,this.maxWorkers=t}updateSas(e){this.sas=e}enqueue(e,t){this.queue.push({operationId:e,buffer:t}),this.pump()}async drain(e=3e4){if(!(this.queue.length===0&&this.activeCount===0))return new Promise(t=>{this.drainResolvers.push(t),setTimeout(()=>{t()},e)})}pump(){for(;this.activeCount<this.maxWorkers&&this.queue.length>0;){let e=this.queue.shift();this.activeCount++,this.processJob(e).finally(()=>{if(this.activeCount--,this.pump(),this.queue.length===0&&this.activeCount===0){for(let t of this.drainResolvers)t();this.drainResolvers=[]}})}}async processJob(e){let t,r="image/webp";try{let o=await la(e.buffer).webp({quality:80}).toBuffer();t=new Uint8Array(o)}catch{t=new Uint8Array(e.buffer),r="image/png"}let n=r==="image/webp"?"webp":"png",s=`test_screenshots/untagged_screenshot/${e.operationId}.${n}`,a=`${this.sas.base_url}/${this.sas.container}/${s}?${this.sas.sas_token}`;for(let o=0;o<=this.maxRetries;o++)try{if((await fetch(a,{method:"PUT",headers:{"Content-Type":r,"x-ms-blob-type":"BlockBlob"},body:t})).ok)return;if(o<this.maxRetries){await this.backoff(o);continue}}catch{if(o<this.maxRetries){await this.backoff(o);continue}}}backoff(e){let t=e===0?1e3:3e3;return new Promise(r=>setTimeout(r,t))}isNearExpiry(){if(!this.sas.expiry)return!1;let e=new Date(this.sas.expiry).getTime();return Date.now()>e-5*6e4}};var H=G(ae(),1);function co({localMode:i=!1,codeExport:e=!1,updatePromise:t}={}){let{exit:r}=Sn(),[n]=(0,U.useState)(()=>new Qt),[s]=(0,U.useState)(()=>new et),a=(0,U.useRef)(0),o=(0,U.useCallback)(()=>`msg-${++a.current}`,[]),[l,c]=(0,U.useState)(!1),[d,h]=(0,U.useState)(null),[x,S]=(0,U.useState)(!1),[p,b]=(0,U.useState)(null),[g,w]=(0,U.useState)(!1),[N,W]=(0,U.useState)(0),[Q,te]=(0,U.useState)(!1),[L,M]=(0,U.useState)(null),[A,X]=(0,U.useState)(null),[f,k]=(0,U.useState)(Zn()),[y,C]=(0,U.useState)(null),[P,j]=(0,U.useState)(!1),F=(0,U.useRef)(null),Z=(0,U.useRef)(0),Y=(0,U.useRef)(""),ue=(0,U.useRef)(0),[oe,Te]=(0,U.useState)([]),de=(0,U.useCallback)(_=>{let T=`s-${++ue.current}`;Te(R=>[...R,{id:T,content:_}])},[]),[zt,sn]=(0,U.useState)(()=>new et().load().setup_complete),[Vt,St]=(0,U.useState)("menu"),[fe,nt]=(0,U.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),q=as(),$=zs(),Be=Ys(),bn=(0,U.useCallback)((_,T)=>{let R=F.current;if(!R)return;let O=Z.current+T,V=De(n.sessionDir,"runs",String(O),"run-test");try{if(!gn(V)){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=runsDir_not_found path=${V}`);return}let z=V;if(gn(De(V,"screenshots")))z=V;else{let xe=ca(V).filter(lt=>gn(De(V,lt,"screenshots")));if(xe.length===0){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=no_screenshots_dir`);return}z=De(V,xe[0])}let se=De(z,"screenshots",`step_${String(_).padStart(3,"0")}.png`);if(!gn(se)){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=screenshot_not_found path=${se}`);return}let Ue=lo(se),Se=De(z,"actions.ndjson");if(!gn(Se)){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=ndjson_not_found`);return}let Pe=lo(Se,"utf-8").trim().split(`
40
- `),Le=Pe[Pe.length-1];if(!Le){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=ndjson_empty`);return}let Ce=JSON.parse(Le).action_id;if(!Ce){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=no_action_id`);return}R.enqueue(Ce,Ue),n.log(`SCREENSHOT_UPLOAD enqueued step=${_} action_id=${Ce} size=${Ue.length}`)}catch(z){n.log(`SCREENSHOT_UPLOAD error step=${_}: ${z instanceof Error?z.message:String(z)}`)}},[n]),B=Vn(bn),[K,Ct]=(0,U.useState)(()=>s.load()),[,Gt]=(0,U.useState)(0),Et=(0,U.useCallback)(()=>Gt(_=>_+1),[]),[ve,at]=(0,U.useState)(null),Lt=$.creds.getActiveProfile(),E=$.creds.getDefaultEnv(),ie=(0,U.useCallback)((_,T)=>{let R=_?$.creds.loadProfileConfig(_,T):null;s.save({project_id:R?.project_id??null,project_name:R?.project_name??null,folder_id:R?.folder_id??null,folder_name:R?.folder_name??null}),Ct(s.load())},[$.creds,s]);(0,U.useEffect)(()=>{g||(n.start({model:K.model,environment:E,profile:Lt}),w(!0))},[n,g,K.model,E,Lt]);let J=(0,U.useCallback)(async _=>{let T=ce(_),R=$.getBasicAuth(),O=R?{username:R.username,accessKey:R.access_key}:await $.getToken().then(z=>z??"");if(!O)return;let V=new ln(T.controllerBaseUrl,O);try{let z=await V.getScreenshotSas();n.setScreenshotSas(z),F.current=new nn(z,3),n.log("SCREENSHOT_SAS fetched OK")}catch(z){n.log(`SCREENSHOT_SAS failed: ${z instanceof Error?z.message:String(z)}`)}},[$,n]),ne=(0,U.useCallback)(async _=>{let T=_??$.creds.getDefaultEnv();C(null),F.current=null;let O=await $.initResolver(T,V=>n.log(V)).resolve(!0).catch(()=>null);return C(O),O&&(n.log(`AUTH_RESET resolved: user=${O.username} org=${O.org_id} env=${T}`),await J(T)),O},[$,n,J]),ye=(0,U.useRef)(!1);(0,U.useEffect)(()=>{!l||ye.current||!g||(ye.current=!0,ne().then(_=>{_?n.log(`BOOT_RESOLVE basic auth resolved: user=${_.username} org=${_.org_id}`):n.log("BOOT_RESOLVE failed \u2014 non-controller APIs may fail")}).catch(_=>{n.log(`BOOT_RESOLVE error: ${_ instanceof Error?_.message:String(_)}`)}))},[l,g,ne,n]);let me=(0,U.useCallback)(async()=>{if(y)return n.log(`TMS_CREDS using cached credentials for user=${y.username} org=${y.org_id}`),y;let _=await $.resolveBasicAuth();return _?(n.log(`TMS_CREDS resolved: user=${_.username} org=${_.org_id} user_id=${_.user_id}`),C(_)):n.log("TMS_CREDS failed: no credentials resolved"),_},[$,y,n]),ze=(0,U.useCallback)(async()=>{let _=await me();if(!_)return n.log("PROJECT failed: no TMS credentials"),null;let T=ce(E),R=new It(T.tmsBaseUrl,_.username,_.access_key),O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv(),z=O?$.creds.loadProfileConfig(O,V):null,se=z?.project_id??K.project_id;if(se)n.log(`PROJECT using cached project_id=${se}`);else{n.log("PROJECT no project_id in config, fetching from TMS...");try{n.log(`PROJECT listing projects from: ${T.tmsBaseUrl}/v1/projects`);let Se=await R.listProjects(Le=>n.log(Le));n.log(`PROJECT found ${Se.length} projects`);let Pe=Se.find(Le=>Le.name==="KaneAI Generated");if(Pe)se=Pe.project_id,n.log(`PROJECT using "KaneAI Generated" project_id=${se}`);else if(Se.length>0){let Le=Se[0];se=Le.project_id,n.log(`PROJECT using first project: name="${Le.name}" project_id=${se}`)}se&&s.set("project_id",se)}catch(Se){return n.log(`PROJECT listing failed: ${Se}`),null}}if(!se)return n.log("PROJECT no projects found"),null;let Ue=z?.folder_id??K.folder_id;if(Ue)n.log(`FOLDER using cached folder_id=${Ue}`);else try{n.log(`FOLDER fetching default folder for project_id=${se}`),Ue=await R.getDefaultFolder(se),n.log(`FOLDER got default folder_id=${Ue}`),Ue&&s.set("folder_id",Ue)}catch(Se){return n.log(`FOLDER default folder fetch failed: ${Se}`),null}return{projectId:se,folderId:Ue??""}},[K.project_id,K.folder_id,me,E,s,n]),re=(0,U.useCallback)(_=>{let T=o(),R={..._,id:T};de((0,H.jsx)(hs,{entry:R}))},[o,de]),le=(0,U.useCallback)(async(_,T)=>{let R=n.nextRunIndex();Z.current=R,Y.current=_,n.logRunStart(R,_,T??""),n.setFirstRun(_,T??"");let V=$.getResolvedBasicAuth(),z=null;if(!V&&(z=await $.getToken(),!z)){re({type:"error",text:"Not authenticated. Run /login first."});return}if(R===0&&!i){n.log("ATM_CREATE runIndex=0 \u2014 creating test via ATM endpoint");let Ie=await ze();try{let Nt=ce(E),xt=V?{username:V.username,access_key:V.access_key}:await me(),Ft=xt?.username??"",Tt=xt?.access_key??"",Hr=await new It(Nt.tmsBaseUrl,Ft,Tt).createAtmTest({objective:_.slice(0,100),creation_mode:"KANECLI",playground_disabled:!!K.chrome_profile_path,testURL:T??K.default_url??"",project_id:Ie?.projectId??K.project_id??"",folder_id:Ie?.folderId??K.folder_id??"",authoring_version:4});n.log(`ATM_CREATE success: test_id=${Hr}`),n.setTestId(Hr),Ie?.projectId&&n.setProjectId(Ie.projectId)}catch(Nt){n.log(`ATM_CREATE failed: ${Nt}`)}}let se=null;if(fe.useCft)re({type:"info",text:"CfT mode: Playwright will manage browser"});else if(fe.wsEndpoint)re({type:"info",text:`WS endpoint: ${fe.wsEndpoint.slice(0,60)}...`});else if(fe.cdpEndpoint)re({type:"info",text:`CDP endpoint: ${fe.cdpEndpoint}`});else{re({type:"info",text:"Starting Chrome..."});try{se=await Be.ensureChrome(T)}catch(Ie){re({type:"error",text:`Chrome failed: ${Ie instanceof Error?Ie.message:String(Ie)}`});return}n.logChromeLaunch(se.port,se.cdpEndpoint),re({type:"info",text:`Chrome ready (port ${se.port})`})}let Ue=De(_e,"variables"),Se=De(process.cwd(),".testmuai","variables"),Pe=Ln(Ue,Se),Le=Zt(De(_e,"global-memory.md")),Ve=Zt(De(process.cwd(),".testmuai","context.md")),Ce=Object.keys(Pe).length>0,{variables:xe,objective:lt}=Ce?Mn(Pe,_):{variables:Pe,objective:_};n.setAuteurVariables(xe);let gt=Object.entries(Pe).filter(([,Ie])=>Ie.secret);if(!i&&gt.length>0&&V){let Ie=ce(E),Nt=new en(Ie.secretsBaseUrl),xt=await me();for(let[Ft,Tt]of gt)Nt.pushSecret({secretKey:Ft,secretValue:Tt.value,username:V.username,accessKey:V.access_key,orgId:String(xt?.org_id??"")}).then(()=>n.log(`SECRET_PUSH success key=${Ft}`)).catch(Fr=>n.log(`SECRET_PUSH failed key=${Ft}: ${Fr}`))}let Nr={},wn=Object.entries(Pe).filter(([,Ie])=>!Ie.secret);if(!i&&wn.length>0&&V){let Ie=ce(E),Nt=new tn(Ie.tmsBaseUrl,V.username,V.access_key);for(let[xt,Ft]of wn)try{let Tt=await Nt.upsertVariable({name:xt,value:Ft.value});Nr[xt]=Tt.id,n.log(`VAR_PUSH success name=${xt} id=${Tt.id}`)}catch(Tt){n.log(`VAR_PUSH failed name=${xt}: ${Tt}`)}}let Io={objective:lt,...T?{url:T}:{},model:K.model,...fe.wsEndpoint?{ws_endpoint:fe.wsEndpoint}:fe.cdpEndpoint?{cdp_endpoint:fe.cdpEndpoint}:se?{cdp_endpoint:se.cdpEndpoint}:{},width:K.window_size.width,height:K.window_size.height,session_id:n.sessionId,run_index:R,stream:!0,...fe.maxSteps!==50?{max_steps:fe.maxSteps}:{},...fe.headless?{headless:!0}:{},...V?{username:V.username,access_key:V.access_key}:z?{auth:{type:"bearer",token:z}}:{},session_context:n.getContext(),variables:Object.keys(xe).length>0?xe:void 0,global_context:Le??void 0,local_context:Ve??void 0};T&&b(T),M(null),B.startRun(Io,{environment:E}),W(Ie=>Ie+1)},[$,Be,s,K,n,E,B,re,fe,ze,me]);(0,U.useEffect)(()=>{if(B.bifurcationInfo){let{flows:_,isSingleFlow:T}=B.bifurcationInfo;if(T&&_.length===1&&_[0])n.log(`OBJECTIVE_REWRITTEN ${_[0]}`),re({type:"info",text:`Objective: ${_[0]}`});else if(!T&&_.length>1){let R=[`Bifurcated into ${_.length} flows:`];_.forEach((O,V)=>R.push(` ${V+1}. ${O}`)),n.log(`BIFURCATION ${_.length} flows`),re({type:"info",text:R.join(`
41
- `)})}}},[B.bifurcationInfo,n,re]);let je=U.default.useRef(null),ge=U.default.useRef(0),pe=U.default.useRef(0);(0,U.useEffect)(()=>{if(B.lastRunEnd&&B.lastRunEnd!==je.current){je.current=B.lastRunEnd;let{status:_,duration:T,summary:R,reason:O,context:V}=B.lastRunEnd,z=B.steps.flatMap(xe=>{let lt=xe.children??[];return[xe,...lt]}),se=z.filter(xe=>xe.status==="passed").length,Ue=z.filter(xe=>xe.status==="failed").length,Se=z.filter(xe=>xe.status==="passed"||xe.status==="failed").length;ge.current+=Se,pe.current+=T??0,M({status:_,duration:T??0,summary:R??"",stepsPassed:se,stepsFailed:Ue,stepsTotal:Se,reason:O,finalState:B.lastRunEnd?.final_state}),n.logRunEnd(Z.current,_,T,R);let Pe=B.lastRunEnd?.total_runs??1,Le=B.lastRunEnd?.run_dir,Ve,Ce;if(Pe>1&&Le){let xe=ua(Le),lt=Z.current;Ve=Array.from({length:Pe},(Nr,wn)=>De(xe,String(lt+wn)));let gt=B.bifurcationInfo;gt&&!gt.isSingleFlow&&gt.flows.length===Pe&&(Ce=gt.flows)}n.addRunResult({index:Z.current,objective:Y.current,summary:R,status:_,context:V??{memory:{},variables:{},pointer:""},run_dir:Le,run_dirs:Ve,flow_objectives:Ce},B.lastRunEnd?.total_runs)}},[B.lastRunEnd,n,re]);let ut=(0,U.useRef)(null);(0,U.useEffect)(()=>{B.askingUser&&B.askingUser!==ut.current&&(ut.current=B.askingUser,de((0,H.jsxs)(v,{children:[(0,H.jsx)(u,{color:"#ff9500",children:"? "}),(0,H.jsx)(u,{color:"#ff9500",children:"Agent asks: "}),(0,H.jsx)(u,{children:B.askingUser})]}))),B.askingUser||(ut.current=null)},[B.askingUser,de]);let kt=(0,U.useRef)(null);(0,U.useEffect)(()=>{if(L&&!B.isRunning&&B.lastRunEnd){let _=`${B.lastRunEnd.status}-${B.lastRunEnd.summary?.slice(0,20)}`;if(kt.current===_)return;kt.current=_,de((0,H.jsx)(io,{data:L,color:L.status==="passed"?"#4ade80":"#ef4444"})),M(null)}},[L,B.isRunning,B.lastRunEnd,de]),(0,U.useEffect)(()=>{if(B.runError&&!B.isRunning){let _=B.runError.trim();n.log(`RUNNER_ERROR ${_.replace(/\n/g,"\\n")}`);let R=_.split(`
21
+ `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,s=n.code||"commander.error";this._exit(r,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in xe.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,xe.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new yl(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(r=>!t(r)).forEach(r=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=a=>{let i=a.attributeName(),l=this.getOptionValue(i),c=this.options.find(d=>d.negate&&i===d.attributeName()),f=this.options.find(d=>!d.negate&&i===d.attributeName());return c&&(c.presetArg===void 0&&l===!1||c.presetArg!==void 0&&l===c.presetArg)?c:f||a},r=a=>{let i=n(a),l=i.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${i.envVar}'`:`option '${i.flags}'`},s=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],s=this;do{let a=s.createHelp().visibleOptions(s).filter(i=>i.long).map(i=>i.long);r=r.concat(a),s=s.parent}while(s&&!s._enablePositionalOptions);t=ii(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(s=>{r.push(s.name()),s.alias()&&r.push(s.alias())}),t=ii(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
22
+ `),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>bl(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=lt.basename(e,lt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;return t.error?n=r=>this._outputConfiguration.writeErr(r):n=r=>this._outputConfiguration.writeOut(r),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation(n);if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=xe.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
23
+ Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,s=>{let a;typeof t=="function"?a=t({error:s.error,command:s.command}):a=t,a&&s.write(`${a}
24
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ai(o){return o.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?r=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],n=s[3],r=s[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}li.Command=so});var mi=Rt(Xe=>{"use strict";var{Argument:ui}=Xn(),{Command:io}=ci(),{CommanderError:Sl,InvalidArgumentError:di}=dn(),{Help:El}=Yr(),{Option:fi}=to();Xe.program=new io;Xe.createCommand=o=>new io(o);Xe.createOption=(o,e)=>new fi(o,e);Xe.createArgument=(o,e)=>new ui(o,e);Xe.Command=io;Xe.Option=fi;Xe.Argument=ui;Xe.Help=El;Xe.CommanderError=Sl;Xe.InvalidArgumentError=di;Xe.InvalidOptionArgumentError=di});var yi=N(ke(),1);import fn from"process";var j=N(ke(),1);var he=N(re(),1);function Uo({profile:o,environment:e,model:t,tokenValid:n,sessionId:r,runCount:s,viewMode:a}){let{stdout:i}=dt(),l=i?.columns??80,c=e==="stage";return(0,he.jsxs)(x,{flexDirection:"column",children:[(0,he.jsx)(u,{color:m.muted,children:"\u2500".repeat(l)}),(0,he.jsx)(x,{paddingX:1,children:(0,he.jsxs)(x,{gap:1,children:[(0,he.jsx)(u,{color:m.dimmed,children:"Model:"}),(0,he.jsx)(u,{color:m.dimmed,children:t}),(0,he.jsx)(u,{color:m.muted,children:"|"}),(0,he.jsx)(u,{color:m.dimmed,children:"Session:"}),(0,he.jsx)(u,{color:m.dimmed,children:r.slice(-6)}),(0,he.jsx)(u,{color:m.muted,children:"|"}),(0,he.jsx)(u,{color:n?m.green:m.red,children:"\u25CF"}),(0,he.jsx)(u,{color:m.dimmed,children:n?"authenticated":"not logged in"})]})}),(0,he.jsx)(x,{paddingX:1,children:(0,he.jsxs)(x,{gap:1,children:[(0,he.jsx)(u,{color:m.dimmed,children:o??"no profile"}),(0,he.jsx)(u,{color:m.muted,children:"|"}),c?(0,he.jsx)(u,{color:m.yellow,bold:!0,children:"\u26A0 stage"}):(0,he.jsx)(u,{color:m.green,children:e}),(0,he.jsx)(u,{color:m.muted,children:"|"}),(0,he.jsxs)(u,{color:m.dimmed,children:["runs: ",s]})]})}),(0,he.jsx)(x,{paddingX:1,children:(0,he.jsx)(u,{dimColor:!0,children:a==="chat"?"esc menu ctrl+c cancel/exit":"\u2191\u2193 navigate \u21B5 select esc back"})})]})}var Fo=N(ke(),1);import{readFileSync as Oi,writeFileSync as Di,mkdirSync as Bi}from"fs";import{dirname as $i,join as ji}from"path";var Li=ji(ve,"command-history.json"),Ui=200,mr=class{entries;filePath;max;constructor(e=Li,t=Ui){this.filePath=e,this.max=t,this.entries=this._load()}push(e){this.entries.length>0&&this.entries[this.entries.length-1]===e||(this.entries.push(e),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(e){let t=e.toLowerCase(),n=[];for(let r=this.entries.length-1;r>=0;r--)this.entries[r].toLowerCase().includes(t)&&n.push(this.entries[r]);return n}_load(){try{let e=Oi(this.filePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}_save(){try{Bi($i(this.filePath),{recursive:!0}),Di(this.filePath,JSON.stringify(this.entries)+`
25
+ `)}catch{}}};function Vo(o){let e=(0,Fo.useRef)(null);return e.current||(e.current=new mr(o)),e.current}var Tt=N(ke(),1);var Qt=[[[" "],[" "],[" "],[" "],["\u2584","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],[" "],[" "],[" "],[" "],[" "],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2584","#af87d7"],[" "],[" "],[" "],[" "]],[[" "],[" "],["\u2584","#875faf"],["\u2584","#af87d7","#875faf"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2584","#af87d7","#875faf"],["\u2584","#875faf"],[" "],[" "]],[[" "],[" "],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2584","#000000","#af87d7"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#af87d7"],["\u2588","#af87d7"],["\u2588","#875faf"],[" "],[" "]],[[" "],["\u2588","#875faf"],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2584","#585858","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],["\u2588","#875faf"],[" "]],[[" "],["\u2588","#875faf"],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2588","#585858"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],["\u2588","#875faf"],[" "]],[[" "],[" "],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2584","#000000","#585858"],["\u2588","#000000"],["\u2588","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],[" "],[" "]],[[" "],[" "],["\u2580","#875faf"],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2580","#875faf"],[" "],[" "]],[[" "],[" "],[" "],[" "],[" "],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2580","#af87d7"],["\u2580","#af87d7"],[" "],[" "],[" "],[" "],[" "]]];var te=N(re(),1),bn="#af87d7",pr="#875faf",No="#5b3a7a",Fi="#ff9500",Vi="#ea580c",Mo="#888888",hr="#666666",Ni="#555555",kt=[[bn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[bn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[bn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[bn,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[pr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[pr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[pr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588"]],gr=kt.map(([,o])=>[...o]);function Ho({visibleRows:o=kt.length}){let e=Math.min(o,kt.length);return(0,te.jsxs)(x,{flexDirection:"column",children:[kt.slice(0,e).map(([t,n],r)=>{let s=gr[r];return(0,te.jsx)(u,{children:s.map((a,i)=>{if(a==="\u2588")return(0,te.jsx)(u,{color:t,children:"\u2588"},i);let l=i>0&&s[i-1]==="\u2588",c=r>0&&i>0&&gr[r-1][i-1]==="\u2588";return l||c?(0,te.jsx)(u,{color:No,children:"\u2592"},i):(0,te.jsx)(u,{children:" "},i)})},r)}),e>=kt.length&&(0,te.jsxs)(u,{children:[" ",gr[kt.length-1].map((t,n)=>t==="\u2588"?(0,te.jsx)(u,{color:No,children:"\u2580"},n):(0,te.jsx)(u,{children:" "},n))]})]})}function Mi({visibleRows:o=Qt.length}){let e=Math.min(o,Qt.length);return(0,te.jsx)(x,{flexDirection:"column",children:Qt.slice(0,e).map((t,n)=>(0,te.jsx)(u,{children:t.map((r,s)=>{let a=r[0],i=r[1],l=r[2];return i?(0,te.jsx)(u,{color:i,backgroundColor:l,children:a},s):(0,te.jsx)(u,{children:a},s)})},n))})}function _n({size:o="compact",helmetVisibleRows:e=Qt.length,textVisibleRows:t=kt.length,showMeta:n=!1,user:r=null,authenticated:s=!1,version:a=""}){return o==="compact"?(0,te.jsx)(Ho,{}):(0,te.jsxs)(x,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,te.jsx)(u,{color:Fi,italic:!0,children:" Welcome to"}),(0,te.jsx)(u,{children:" "}),(0,te.jsxs)(x,{gap:2,children:[(0,te.jsx)(Mi,{visibleRows:e}),(0,te.jsxs)(x,{flexDirection:"column",children:[(0,te.jsx)(Ho,{visibleRows:t}),(0,te.jsx)(x,{justifyContent:"flex-end",width:73,children:(0,te.jsx)(u,{color:Vi,italic:!0,children:"Command-line interface"})})]})]}),n&&(0,te.jsxs)(te.Fragment,{children:[(0,te.jsx)(u,{children:" "}),(0,te.jsxs)(u,{children:[(0,te.jsx)(u,{color:hr,children:" Browser automation powered by AI. "}),(0,te.jsx)(u,{color:Ni,children:`v${a}`})]}),(0,te.jsx)(u,{children:" "}),(0,te.jsx)(u,{children:(0,te.jsx)(u,{color:hr,children:" KaneCLI can navigate websites, fill forms, test web UI, and extract"})}),(0,te.jsx)(u,{children:(0,te.jsx)(u,{color:hr,children:" data \u2014 right from your terminal."})}),(0,te.jsx)(u,{children:" "}),(0,te.jsxs)(u,{children:[(0,te.jsx)(u,{color:Mo,children:" \u25CF "}),(0,te.jsx)(u,{color:Mo,children:s?"Logged in as ":"Not logged in"}),s&&r&&(0,te.jsx)(u,{bold:!0,children:r})]})]})]})}import{readFileSync as Zt,writeFileSync as Wo,mkdirSync as Ko,readdirSync as vr,unlinkSync as tt,existsSync as xr,chmodSync as qo}from"fs";import{join as Pe,dirname as Hi}from"path";var ye=class{baseDir;profilesDir;configFile;constructor(e=ve){this.baseDir=e,this.profilesDir=Pe(e,"profiles"),this.configFile=Pe(e,"config.json")}readConfig(){try{return JSON.parse(Zt(this.configFile,"utf-8"))}catch{return{}}}writeConfig(e){Ko(this.baseDir,{recursive:!0,mode:448}),Wo(this.configFile,JSON.stringify(e,null,2)+`
26
+ `),qo(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(e){let t=this.readConfig();t.active_profile=e,this.writeConfig(t)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(e){let t=this.readConfig();t.default_env=e,this.writeConfig(t)}credentialsPath(e,t){return Pe(this.profilesDir,e,t,"credentials")}clientPath(e,t){return Pe(this.profilesDir,e,t,"client.json")}basicAuthPath(e,t){return Pe(this.profilesDir,e,t,"basic-auth")}profileConfigPath(e,t){return Pe(this.profilesDir,e,t,"profile-config.json")}saveProfileConfig(e,t,n){let r=this.loadProfileConfig(e,t)??{};this.writeSecure(this.profileConfigPath(e,t),{...r,...n})}loadProfileConfig(e,t){try{return JSON.parse(Zt(this.profileConfigPath(e,t),"utf-8"))}catch{return null}}writeSecure(e,t){try{Ko(Hi(e),{recursive:!0,mode:448}),Wo(e,JSON.stringify(t,null,2)+`
27
+ `),qo(e,384)}catch(n){let r=n instanceof Error?n.message:String(n);process.stderr.write(`[auth] Failed to save credentials: ${r}
28
+ `)}}saveCredentials(e,t,n){this.writeSecure(this.credentialsPath(e,t),n)}loadCredentials(e,t){try{return JSON.parse(Zt(this.credentialsPath(e,t),"utf-8"))}catch{return null}}saveClient(e,t,n){this.writeSecure(this.clientPath(e,t),n)}loadClient(e,t){try{return JSON.parse(Zt(this.clientPath(e,t),"utf-8"))}catch{return null}}getActiveCredentials(){let e=this.getActiveProfile();if(!e)return{credentials:null,profile:null,env:null};let t=this.getDefaultEnv();return{credentials:this.loadCredentials(e,t),profile:e,env:t}}saveBasicAuth(e,t,n){this.writeSecure(this.basicAuthPath(e,t),n)}loadBasicAuth(e,t){try{return JSON.parse(Zt(this.basicAuthPath(e,t),"utf-8"))}catch{return null}}deleteBasicAuth(e,t){try{tt(this.basicAuthPath(e,t))}catch{}}resolveAuth(){let e=this.getActiveProfile();if(!e)return null;let t=this.getDefaultEnv(),n=this.loadBasicAuth(e,t);return n?{method:"basic",...n,profile:e,env:t}:this.loadCredentials(e,t)?{method:"oauth",profile:e,env:t}:null}listProfiles(){let e=[];try{for(let t of vr(this.profilesDir)){let n=Pe(this.profilesDir,t);try{for(let r of vr(n)){let s=Pe(n,r),a=xr(Pe(s,"credentials")),i=xr(Pe(s,"client.json")),l=xr(Pe(s,"basic-auth"));(a||i||l)&&e.push({profile:t,env:r})}}catch{}}}catch{}return e}deleteProfile(e,t){try{tt(this.credentialsPath(e,t))}catch{}if(this.getActiveProfile()===e){let n=this.readConfig();delete n.active_profile,this.writeConfig(n)}}deleteProfileFull(e,t){if(t){try{tt(this.credentialsPath(e,t))}catch{}try{tt(this.clientPath(e,t))}catch{}try{tt(this.basicAuthPath(e,t))}catch{}try{tt(this.profileConfigPath(e,t))}catch{}}else try{let n=Pe(this.profilesDir,e);for(let r of vr(n)){try{tt(Pe(n,r,"credentials"))}catch{}try{tt(Pe(n,r,"client.json"))}catch{}try{tt(Pe(n,r,"basic-auth"))}catch{}try{tt(Pe(n,r,"profile-config.json"))}catch{}}}catch{}}};var _r=N(re(),1),wr=8,br=7;function zo({onComplete:o}){let[e,t]=(0,Tt.useState)(0),[n,r]=(0,Tt.useState)(0),[s,a]=(0,Tt.useState)(!1),[i]=(0,Tt.useState)(()=>{let l=new ye,c=l.getActiveProfile(),f=l.getDefaultEnv(),d=c?l.loadCredentials(c,f):null,g=c?l.loadBasicAuth(c,f):null;return{authenticated:!!(d||g),user:g?.username??c??null}});return mt(()=>{t(l=>Math.min(wr,l+1))},e<wr?60:null),mt(()=>{r(l=>Math.min(br,l+1))},n<br?80:null),(0,Tt.useEffect)(()=>{e>=wr&&n>=br&&!s&&(a(!0),o?.())},[e,n,s,o]),(0,_r.jsx)(x,{flexDirection:"column",children:(0,_r.jsx)(_n,{size:"full",helmetVisibleRows:e,textVisibleRows:n,showMeta:s,user:i.user,authenticated:i.authenticated,version:ft})})}var rt=N(re(),1);function Go({entry:o}){return o.type==="input"?(0,rt.jsxs)(x,{children:[(0,rt.jsx)(u,{color:m.purple,children:"\u276F "}),(0,rt.jsx)(u,{children:o.text})]}):o.type==="error"?(0,rt.jsx)(x,{marginLeft:2,children:(0,rt.jsx)(u,{color:m.red,children:o.text})}):(0,rt.jsx)(x,{marginLeft:2,children:(0,rt.jsx)(u,{color:o.type==="info"?m.dimmed:void 0,children:o.text})})}var pt=N(ke(),1);var yr=N(ke(),1);var Ye=N(re(),1);function Jo({history:o,onSelect:e,onClose:t}){let[n,r]=(0,yr.useState)(""),[s,a]=(0,yr.useState)(0),i=n?o.search(n).slice(0,8):[];return $e((l,c)=>{if(c.escape){t();return}if(c.return){i.length>0&&i[s]?e(i[s]):t();return}if(c.upArrow){a(f=>Math.max(0,f-1));return}if(c.downArrow){a(f=>Math.min(i.length-1,f+1));return}if(c.backspace||c.delete){r(f=>f.slice(0,-1)),a(0);return}l&&!c.ctrl&&!c.meta&&(r(f=>f+l),a(0))}),(0,Ye.jsxs)(x,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,Ye.jsx)(u,{color:m.muted,bold:!0,children:"reverse search"}),(0,Ye.jsxs)(x,{gap:1,children:[(0,Ye.jsx)(u,{color:m.dimmed,children:"search:"}),(0,Ye.jsx)(u,{children:n}),(0,Ye.jsx)(u,{color:m.purple,children:"\u2588"})]}),i.length>0&&(0,Ye.jsx)(u,{children:" "}),i.map((l,c)=>(0,Ye.jsx)(x,{marginLeft:2,children:(0,Ye.jsxs)(u,{color:c===s?m.purple:m.dimmed,bold:c===s,children:[c===s?"\u25B8 ":" ",l]})},`${c}-${l}`))]})}var je=N(re(),1);function Xo({onSubmit:o,onEscape:e,history:t,placeholder:n="Type an objective or /command..."}){let[r,s]=(0,pt.useState)([]),[a,i]=(0,pt.useState)(0),[l,c]=(0,pt.useState)("none"),[f,d]=(0,pt.useState)(-1),g=(0,pt.useRef)(""),[E,h]=(0,pt.useState)(!0),{stdout:y}=dt(),_=y?.columns??80,w=r.join(""),I=(()=>{if(l!=="none"||r.length===0||w.startsWith("/"))return"";let B=t.getAll();for(let P=B.length-1;P>=0;P--)if(B[P].startsWith(w)&&B[P]!==w)return B[P].slice(w.length);return""})();$e((B,P)=>{if(E&&B&&h(!1),P.return){w.trim()&&(t.push(w.trim()),o(w.trim()),s([]),i(0),c("none"),d(-1),g.current="",h(!0));return}if(P.escape){l!=="none"?c("none"):r.length>0?(s([]),i(0),d(-1),g.current=""):e?.();return}if(P.tab){if(I){let R=w+I;s([...R]),i(R.length);return}return}if(P.ctrl&&B==="r"){c("search");return}if(P.ctrl&&B==="a"){i(0);return}if(P.ctrl&&B==="e"){i(r.length);return}if(P.ctrl&&B==="w"){if(a===0)return;let R=a-1;for(;R>0&&r[R]===" ";)R--;for(;R>0&&r[R-1]!==" ";)R--;let G=[...r.slice(0,R),...r.slice(a)];s(G),i(R);return}if(P.ctrl&&B==="u"){s([]),i(0),d(-1),c("none");return}if(P.meta&&B==="b"){let R=a-1;for(;R>0&&r[R]===" ";)R--;for(;R>0&&r[R-1]!==" ";)R--;i(Math.max(0,R));return}if(P.meta&&B==="f"){let R=a;for(;R<r.length&&r[R]!==" ";)R++;for(;R<r.length&&r[R]===" ";)R++;i(R);return}if(P.leftArrow){i(R=>Math.max(0,R-1));return}if(P.rightArrow){if(a>=r.length&&I){let R=w+I;s([...R]),i(R.length)}else i(R=>Math.min(r.length,R+1));return}if(P.upArrow){if(l==="none"){let R=t.getAll();if(R.length===0)return;if(f===-1){g.current=w,d(R.length-1);let G=R[R.length-1];s([...G]),i(G.length)}else if(f>0){let G=f-1;d(G);let Z=R[G];s([...Z]),i(Z.length)}}return}if(P.downArrow){if(l==="none"){let R=t.getAll();if(f===-1)return;if(f<R.length-1){let G=f+1;d(G);let Z=R[G];s([...Z]),i(Z.length)}else{d(-1);let G=g.current;s([...G]),i(G.length)}}return}if(P.backspace||P.delete){if(a>0){let R=[...r.slice(0,a-1),...r.slice(a)];s(R),i(a-1),d(-1)}return}if(B&&!P.ctrl&&!P.meta){let R=[...r.slice(0,a),...B,...r.slice(a)];s(R),i(a+B.length),d(-1)}},{isActive:l!=="search"});let z=B=>{s([...B]),i(B.length),c("none")},ce=()=>{c("none")},Y=(()=>{if(E&&r.length===0)return null;let B=a>=r.length,P=r.slice(0,a).join(""),R=B?" ":r[a],G=B?"":r.slice(a+1).join(""),Z="\u276F "+P+R+G+I,p=2,b=p+P.length,v=b+1,C=v+G.length,$=Z.length,U=Math.max(1,Math.ceil($/_)),H=[];for(let W=0;W<U;W++)H.push({start:W*_,end:Math.min((W+1)*_,$)});return{full:Z,p,b,c:v,a:C,lines:H}})();return(0,je.jsxs)(x,{flexDirection:"column",children:[l==="search"&&(0,je.jsx)(Jo,{history:t,onSelect:z,onClose:ce}),(0,je.jsx)(u,{color:m.muted,children:"\u2500".repeat(_)}),Y===null?(0,je.jsxs)(x,{children:[(0,je.jsx)(u,{color:m.purple,children:"\u276F "}),(0,je.jsx)(u,{color:m.dimmed,children:n})]}):(0,je.jsx)(x,{flexDirection:"column",children:Y.lines.map(({start:B,end:P},R)=>{let{full:G,p:Z,b:p,c:b,a:v}=Y,C=[];return P>0&&B<Z&&C.push((0,je.jsx)(u,{color:m.purple,children:G.slice(Math.max(B,0),Math.min(Z,P))},"p")),P>Z&&B<p&&C.push((0,je.jsx)(u,{children:G.slice(Math.max(Z,B),Math.min(p,P))},"b")),P>p&&B<b&&C.push((0,je.jsx)(u,{color:m.purple,inverse:!0,children:G.slice(Math.max(p,B),Math.min(b,P))},"c")),P>b&&B<v&&C.push((0,je.jsx)(u,{children:G.slice(Math.max(b,B),Math.min(v,P))},"a")),P>v&&C.push((0,je.jsx)(u,{color:m.dimmed,children:G.slice(Math.max(v,B),P)},"g")),(0,je.jsx)(x,{children:C},R)})})]})}var Se=N(ke(),1);var Qo=N(ke(),1);var yn=N(re(),1),Wi="#ffc580",Ki="#ffd9a8",Yo="#ffffff";function Zo({text:o,active:e=!0}){let[t,n]=(0,Qo.useState)(0),r=4;if(mt(()=>{n(a=>(a+1)%(o.length+r*2))},e?80:null),!e)return(0,yn.jsx)(u,{color:Yo,children:o});let s=o.split("").map((a,i)=>{let l=t-r,c=Math.abs(i-l-r/2),f;return c<=r/2?f=Wi:c<=r?f=Ki:f=Yo,(0,yn.jsx)(u,{color:f,children:a},i)});return(0,yn.jsx)(u,{children:s})}var Le=N(re(),1),qi={starting:m.cyan,running:m.purple,passed:m.green,failed:m.red,cancelled:m.dimmed,timed_out:m.yellow};function Sn({currentStep:o,maxSteps:e,elapsed:t,status:n}){let{stdout:r}=dt(),s=r?.columns??80,a=qi[n]??m.purple,i=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,Le.jsxs)(x,{flexDirection:"column",marginTop:1,children:[(0,Le.jsx)(u,{color:m.muted,children:"\u2500".repeat(Math.min(s,60))}),(0,Le.jsxs)(x,{children:[(0,Le.jsx)(u,{children:" "}),(0,Le.jsx)(u,{color:m.dimmed,children:"Steps "}),(0,Le.jsx)(u,{bold:!0,children:o}),(0,Le.jsxs)(u,{color:m.dimmed,children:["/",e]}),(0,Le.jsx)(u,{children:" "}),(0,Le.jsx)(u,{color:m.dimmed,children:"Elapsed "}),(0,Le.jsx)(u,{bold:!0,children:i}),(0,Le.jsx)(u,{children:" "}),(0,Le.jsx)(u,{color:m.dimmed,children:"Status "}),(0,Le.jsx)(u,{bold:!0,color:a,children:n})]})]})}var zi={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u26A1"};function es(o){return zi[o]??"\u25CF"}var ht=N(re(),1);function Sr({steps:o,flows:e,cmInitCounts:t,renderStep:n}){return(0,ht.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,ht.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",e?.length??o.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),o.map((r,s)=>(0,ht.jsxs)(x,{flexDirection:"column",marginTop:s>0?1:0,children:[(0,ht.jsxs)(u,{color:m.purple,children:["Flow ",s+1,": ",e?.[s]??r.objective]}),t&&t[s]!=null&&(0,ht.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",t[s]," checkpoints"]}),r.children&&r.children.length>0?r.children.map(a=>n(a,`f${s}-${a.index}`)):r.status==="pending"&&(0,ht.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},s))]})}var F=N(re(),1);function gt({step:o,indent:e=2}){let t=o.actionType?es(o.actionType):null,n=o.status==="running",r=o.status==="passed",s=o.status==="failed",a=o.status==="pending"||o.status==="stopped",{stdout:i}=dt(),l=i?.columns??80,c=Math.max(20,l-e-21),f=o.objective??"",d=f.length>c?f.slice(0,c-1)+"\u2026":f,g=(o.duration??0)*1e3,E=o.duration!=null?g<1e3?`${Math.round(g)}ms`:`${(g/1e3).toFixed(1)}s`:"";return(0,F.jsxs)(x,{flexDirection:"column",children:[(0,F.jsxs)(x,{marginLeft:e,children:[(0,F.jsx)(x,{width:4,children:(0,F.jsxs)(u,{color:m.muted,children:[String(o.index).padStart(2," ")," "]})}),(0,F.jsx)(x,{width:3,children:n?(0,F.jsx)(Co,{}):r?(0,F.jsx)(u,{color:m.green,bold:!0,children:"\u2713"}):s?(0,F.jsx)(u,{color:m.red,bold:!0,children:"\u2717"}):(0,F.jsx)(u,{color:m.muted,children:"\u25CB"})}),(0,F.jsx)(x,{flexGrow:1,children:n?(0,F.jsx)(Zo,{text:d,active:!0}):s?(0,F.jsx)(u,{color:m.red,children:d}):a?(0,F.jsx)(u,{color:m.dimmed,children:d}):(0,F.jsx)(u,{color:m.greenDim,children:d})}),(r||s)&&t?(0,F.jsx)(x,{width:3,marginLeft:1,children:(0,F.jsx)(u,{color:m.muted,children:t})}):(0,F.jsx)(x,{width:3,marginLeft:1}),(0,F.jsx)(x,{width:7,justifyContent:"flex-end",children:(0,F.jsx)(u,{color:m.dimmed,children:E})})]}),o.children&&o.children.length>0&&(0,F.jsx)(x,{flexDirection:"column",children:o.children.map((h,y)=>(0,F.jsx)(gt,{step:h,indent:e+2},`child-${y}`))})]})}function En({steps:o,bifurcated:e,flows:t,cmInitCounts:n,maxSteps:r=50,staticSteps:s=!1,onStepCommit:a}){let i=(0,Se.useRef)(new Set),l=(0,Se.useRef)(!1),c=(0,Se.useRef)(new Set),f=(0,Se.useRef)(!1),d=(0,Se.useRef)(new Set),g=(0,Se.useRef)(0);(0,Se.useEffect)(()=>{o.length===0&&g.current>0&&(i.current.clear(),l.current=!1,c.current.clear(),f.current=!1,d.current.clear()),g.current=o.length},[o.length]);let E=o.flatMap(p=>[p,...p.children??[]]),h=E.some(p=>p.status==="running"),y=E.some(p=>p.status==="failed"),_=E.length===0||E.every(p=>p.status==="pending"),w=E.filter(p=>p.status==="passed"||p.status==="failed").length,I;_?I="starting":h?I="running":y?I="failed":I="passed";let z=(0,Se.useRef)(null),[ce,Y]=(0,Se.useState)(0);(0,Se.useEffect)(()=>{E.length===0||_?(z.current=null,Y(0)):h&&z.current==null&&(z.current=Date.now())},[h,_,E.length]),(0,Se.useEffect)(()=>{if(!h)return;let p=setInterval(()=>{z.current!=null&&Y((Date.now()-z.current)/1e3)},500);return()=>clearInterval(p)},[h]);let B=(0,Se.useRef)(new Set),[P,R]=(0,Se.useState)([]),G=(0,Se.useRef)(!1);(0,Se.useEffect)(()=>{if(!s||e)return;let p=[];if(!e&&!G.current&&n&&n[0]!=null&&(G.current=!0,n[0]>0&&p.push({key:"cm_init_0",type:"cm_init",count:n[0]})),e){!B.current.has(-1)&&o.length>0&&(B.current.add(-1),p.push({key:"bif_header",type:"bifurcation_header",flowCount:t?.length??o.length}));for(let b=0;b<o.length;b++){let v=o[b],C=-(b+10);B.current.has(C)||(B.current.add(C),p.push({key:`flow_header_${b}`,type:"flow_header",flowIdx:b,label:t?.[b]??v.objective,cmCount:n?.[b]}));for(let $ of v.children??[])($.status==="passed"||$.status==="failed")&&!B.current.has($.index)&&(B.current.add($.index),p.push({key:`step_f${b}_${$.index}`,type:"step",step:{...$}}))}}else for(let b of o)(b.status==="passed"||b.status==="failed")&&!B.current.has(b.index)&&(B.current.add(b.index),p.push({key:`step_${b.index}`,type:"step",step:{...b,children:b.children?[...b.children]:void 0}}));p.length>0&&R(b=>[...b,...p])},[o,e,t,n,s]),(0,Se.useEffect)(()=>{if(!a)return;!e&&!f.current&&n&&n[0]!=null&&(f.current=!0,n[0]>0&&a((0,F.jsx)(x,{marginLeft:2,children:(0,F.jsxs)(u,{color:m.dimmed,children:["\u25A0 Generated task with ",n[0]," checkpoints"]})}))),e&&t&&!l.current&&(l.current=!0,a((0,F.jsx)(u,{color:"#b388ff",children:"\u2501\u2501 Bifurcated into "+t.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"})));let p=e?o.flatMap((b,v)=>{let C=b.children??[];return!c.current.has(v)&&C.length>0&&(c.current.add(v),a((0,F.jsx)(u,{color:"#b388ff",children:" Flow "+(v+1)+": "+(t?.[v]??"")})),n?.[v]!=null&&n[v]>0&&!d.current.has(v)&&(d.current.add(v),a((0,F.jsx)(x,{marginLeft:2,children:(0,F.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",n[v]," checkpoints"]})})))),n?.[v]!=null&&n[v]>0&&c.current.has(v)&&!d.current.has(v)&&(d.current.add(v),a((0,F.jsx)(x,{marginLeft:2,children:(0,F.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",n[v]," checkpoints"]})}))),C}):o.flatMap(b=>[b,...b.children??[]]);for(let b of p){let v=`${b.index}-${b.objective}`;i.current.has(v)||(b.status==="passed"||b.status==="failed"||b.status==="stopped")&&(i.current.add(v),a((0,F.jsx)(x,{marginLeft:2,children:(0,F.jsx)(gt,{step:b})})))}},[o,a,e,t,n]);let Z=[];if(a)if(e)for(let p of o){let v=(p.children??[]).filter(C=>{let $=`${C.index}-${C.objective}`;return!i.current.has($)});v.length>0&&Z.push({...p,children:v})}else for(let p of o){let b=`${p.index}-${p.objective}`;i.current.has(b)||Z.push(p)}else if(s){if(!e)for(let p of o)B.current.has(p.index)||Z.push(p)}if(!s){let p=a?Z:o;return(0,F.jsxs)(x,{flexDirection:"column",children:[e?a?p.length>0?(0,F.jsx)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:p.map((v,C)=>(0,F.jsx)(x,{flexDirection:"column",marginTop:C>0?1:0,children:v.children&&v.children.length>0?v.children.map($=>(0,F.jsx)(gt,{step:$},`f${C}-${$.index}`)):v.status==="pending"&&(0,F.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})},C))}):null:(0,F.jsx)(Sr,{steps:o,flows:t,cmInitCounts:n,renderStep:(v,C)=>(0,F.jsx)(gt,{step:v},C)}):(0,F.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&n&&n[0]!=null&&(0,F.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",n[0]," checkpoints"]}),p.map(v=>(0,F.jsx)(gt,{step:v},v.index))]}),h&&(0,F.jsx)(Sn,{currentStep:w,maxSteps:r,elapsed:ce,status:I})]})}return e?(0,F.jsxs)(x,{flexDirection:"column",children:[(0,F.jsx)(Sr,{steps:o,flows:t,cmInitCounts:n,renderStep:(p,b)=>(0,F.jsx)(gt,{step:p},b)}),h&&(0,F.jsx)(Sn,{currentStep:w,maxSteps:r,elapsed:ce,status:I})]}):(0,F.jsxs)(x,{flexDirection:"column",children:[(0,F.jsx)(jt,{items:P,children:p=>p.type==="cm_init"?(0,F.jsx)(x,{marginLeft:2,paddingLeft:1,children:(0,F.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",p.count," checkpoints"]})},p.key):p.type==="bifurcation_header"?(0,F.jsx)(x,{marginLeft:2,paddingLeft:1,children:(0,F.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",p.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},p.key):p.type==="flow_header"?(0,F.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,F.jsxs)(u,{color:m.purple,children:["Flow ",p.flowIdx+1,": ",p.label]}),p.cmCount!=null&&(0,F.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",p.cmCount," checkpoints"]})]},p.key):(0,F.jsx)(x,{marginLeft:2,paddingLeft:1,children:(0,F.jsx)(gt,{step:p.step})},p.key)}),Z.length>0&&(0,F.jsx)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:Z.map(p=>(0,F.jsx)(gt,{step:p},p.index))}),h&&(0,F.jsx)(Sn,{currentStep:w,maxSteps:r,elapsed:ce,status:I})]})}var Er=N(ke(),1);var Cn=N(re(),1),ts=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Rn({label:o,hasBifurcation:e=!1}){let[t,n]=(0,Er.useState)(0),[r,s]=(0,Er.useState)(0);mt(()=>{n(i=>(i+1)%ts.length)},80),mt(()=>{s(i=>(i+1)%4)},400);let a=o??(e?"Planning approach":"Analyzing objective");return(0,Cn.jsxs)(x,{marginLeft:1,children:[(0,Cn.jsxs)(u,{color:m.primary,children:[ts[t]," "]}),(0,Cn.jsxs)(u,{color:m.dim,children:[a,".".repeat(r+1)]})]})}function kn(o){if(!o.isRunning)return null;let e=o.bifurcationInfo;if(e&&!e.isSingleFlow){let t=o.steps.findIndex(r=>r.status==="running");return(t===-1?o.cmInitCounts.length===0:t>=o.cmInitCounts.length)?{label:t>0?`Planning flow ${t+1}`:void 0,hasBifurcation:!0}:null}return o.cmInitCounts.length>0||o.steps.some(t=>t.children?.length)?null:{hasBifurcation:!!e}}var Me=N(re(),1),Gi=64;function Ji(o){return o.split(`
29
+ `).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function en({status:o,summary:e,duration:t,steps:n,stepsPassed:r,stepsFailed:s,reason:a,creditsConsumed:i}){let l=o==="passed",c=l?m.green:m.red,f=l?"\u2713":"\u2717",d=o.toUpperCase(),g=r??(l?n:Math.max(0,n-1)),E=s??(l?0:1),h=E>0?`${n} steps (${g} passed, ${E} failed)`:`${n} steps`,y=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,_=Ji(e);return(0,Me.jsx)(x,{flexDirection:"column",marginTop:1,children:(0,Me.jsxs)(x,{borderStyle:"round",borderColor:c,flexDirection:"column",paddingX:2,paddingY:1,width:Gi+6,children:[(0,Me.jsxs)(x,{children:[(0,Me.jsxs)(u,{bold:!0,color:c,children:[f," ",d]}),(0,Me.jsxs)(u,{color:m.dimmed,children:[" ","\xB7 ",h," \xB7 ",y,typeof i=="number"&&i>0?` \xB7 ${parseFloat(i.toFixed(4))} credits`:""]})]}),_.length>0&&(0,Me.jsx)(x,{flexDirection:"column",marginTop:1,marginLeft:1,children:_.map((w,I)=>(0,Me.jsxs)(x,{marginBottom:I<_.length-1?1:0,children:[(0,Me.jsx)(u,{color:m.primary,children:"\u25CF "}),(0,Me.jsx)(x,{flexShrink:1,children:(0,Me.jsx)(u,{wrap:"wrap",children:w})})]},I))}),a&&!l&&(0,Me.jsx)(x,{marginTop:1,children:(0,Me.jsxs)(u,{color:m.red,wrap:"wrap",children:["Reason: ",a]})})]})})}var vt=N(re(),1);function Tn({steps:o,bifurcationInfo:e,perFlowMetadata:t}){return!e||e.isSingleFlow||!t||t.length<=1?null:(0,vt.jsx)(x,{flexDirection:"column",children:t.map((n,r)=>{let s=o[r],a=s?.children??[],i=a.filter(E=>E.status==="passed").length,l=a.filter(E=>E.status==="failed").length,c=i+l,f=a.reduce((E,h)=>E+(h.duration??0),0),d=s?.status==="failed"?"failed":"passed",g=e.flows[r]??s?.objective??`Flow ${r+1}`;return(0,vt.jsxs)(x,{flexDirection:"column",marginTop:r>0?1:0,children:[(0,vt.jsxs)(x,{marginLeft:1,children:[(0,vt.jsx)(u,{color:"#b388ff",bold:!0,children:"Flow "+(r+1)+": "}),(0,vt.jsx)(u,{color:"#b388ff",children:g})]}),(0,vt.jsx)(en,{status:d,summary:n?.summary??"",duration:f,steps:c,stepsPassed:i,stepsFailed:l,reason:n?.error_message??void 0,creditsConsumed:n?.credits_consumed??void 0})]},`flow-summary-${r}`)})})}var Ee=N(ke(),1);import{readFileSync as Xi,writeFileSync as ns,mkdirSync as rs}from"fs";import{dirname as os}from"path";var ss={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:Ge,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"action",setup_complete:!1},Ke=class{constructor(e=bo){this.path=e}load(){try{let e=Xi(this.path,"utf-8"),t=JSON.parse(e);return{...ss,...t}}catch{return{...ss}}}set(e,t){try{let n=this.load();n[e]=t,rs(os(this.path),{recursive:!0}),ns(this.path,JSON.stringify(n,null,2)+`
30
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);process.stderr.write(`[config] Failed to save config: ${r}
31
+ `)}}save(e){try{let n={...this.load(),...e};rs(os(this.path),{recursive:!0}),ns(this.path,JSON.stringify(n,null,2)+`
32
+ `)}catch(t){let n=t instanceof Error?t.message:String(t);process.stderr.write(`[config] Failed to save config: ${n}
33
+ `)}}};import{createServer as Aa}from"http";import{randomBytes as Ia}from"crypto";import{URL as Pa}from"url";import gs from"process";import{Buffer as vs}from"buffer";import xs from"path";import{fileURLToPath as ba}from"url";import{promisify as _a}from"util";import ws from"child_process";import ya,{constants as Sa}from"fs/promises";import cs from"process";import us,{constants as na}from"fs/promises";import ls from"process";import ta from"os";import Tr from"fs";import Zi from"fs";import is from"fs";var Cr;function Yi(){try{return is.statSync("/.dockerenv"),!0}catch{return!1}}function Qi(){try{return is.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Rr(){return Cr===void 0&&(Cr=Yi()||Qi()),Cr}var kr,ea=()=>{try{return Zi.statSync("/run/.containerenv"),!0}catch{return!1}};function At(){return kr===void 0&&(kr=ea()||Rr()),kr}var as=()=>{if(ls.platform!=="linux")return!1;if(ta.release().toLowerCase().includes("microsoft"))return!At();try{if(Tr.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!At()}catch{}return Tr.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Tr.existsSync("/run/WSL")?!At():!1},xt=ls.env.__IS_WSL_TEST__?as:as();var ra=(()=>{let o="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",n=!1;try{await us.access(t,na.F_OK),n=!0}catch{}if(!n)return o;let r=await us.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(r);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):o}})(),oa=async()=>`${await ra()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Ar=async()=>xt?oa():`${cs.env.SYSTEMROOT||cs.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function wt(o,e,t){let n=r=>Object.defineProperty(o,e,{value:r,enumerable:!0,writable:!0});return Object.defineProperty(o,e,{configurable:!0,enumerable:!0,get(){let r=t();return n(r),r},set(r){n(r)}}),o}import{promisify as ga}from"util";import Br from"process";import{execFile as va}from"child_process";import{promisify as sa}from"util";import ia from"process";import{execFile as aa}from"child_process";var la=sa(aa);async function Ir(){if(ia.platform!=="darwin")throw new Error("macOS only");let{stdout:o}=await la("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(o)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import ca from"process";import{promisify as ua}from"util";import{execFile as da,execFileSync as bu}from"child_process";var fa=ua(da);async function ds(o,{humanReadableOutput:e=!0,signal:t}={}){if(ca.platform!=="darwin")throw new Error("macOS only");let n=e?[]:["-ss"],r={};t&&(r.signal=t);let{stdout:s}=await fa("osascript",["-e",o,n],r);return s.trim()}async function Pr(o){return ds(`tell application "Finder" to set app_path to application file id "${o}" as string
34
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as ma}from"util";import{execFile as pa}from"child_process";var ha=ma(pa),An={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"}},Ru=new Map(Object.entries(An)),Or=class extends Error{};async function Dr(o=ha){let{stdout:e}=await o("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new Or(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:n}=t.groups,r=n.lastIndexOf("."),s=n.lastIndexOf("-"),a=r===-1?void 0:n.slice(0,r),i=s===-1?void 0:n.slice(0,s);return An[n]??An[a]??An[i]??{name:n,id:n}}var xa=ga(va),wa=o=>o.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function $r(){if(Br.platform==="darwin"){let o=await Ir();return{name:await Pr(o),id:o}}if(Br.platform==="linux"){let{stdout:o}=await xa("xdg-mime",["query","default","x-scheme-handler/http"]),e=o.trim();return{name:wa(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(Br.platform==="win32")return Dr();throw new Error("Only macOS, Linux, and Windows are supported")}var Ea=_a(ws.execFile),jr=xs.dirname(ba(import.meta.url)),fs=xs.join(jr,"xdg-open"),{platform:Ut,arch:ms}=gs;async function Ca(){let o=await Ar(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=vs.from(e,"utf16le").toString("base64"),{stdout:n}=await Ea(o,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),r=n.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[r]?{id:s[r]}:{}}var ps=async(o,e)=>{let t;for(let n of o)try{return await e(n)}catch(r){t=r}throw t},In=async o=>{if(o={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...o},Array.isArray(o.app))return ps(o.app,i=>In({...o,app:i}));let{name:e,arguments:t=[]}=o.app??{};if(t=[...t],Array.isArray(e))return ps(e,i=>In({...o,app:{name:i,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let i={"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"},c=xt?await Ca():await $r();if(c.id in i){let f=i[c.id];return e==="browserPrivate"&&t.push(l[f]),In({...o,app:{name:It[f],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let n,r=[],s={};if(Ut==="darwin")n="open",o.wait&&r.push("--wait-apps"),o.background&&r.push("--background"),o.newInstance&&r.push("--new"),e&&r.push("-a",e);else if(Ut==="win32"||xt&&!At()&&!e){n=await Ar(),r.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),xt||(s.windowsVerbatimArguments=!0);let i=["Start"];o.wait&&i.push("-Wait"),e?(i.push(`"\`"${e}\`""`),o.target&&t.push(o.target)):o.target&&i.push(`"${o.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),i.push("-ArgumentList",t.join(","))),o.target=vs.from(i.join(" "),"utf16le").toString("base64")}else{if(e)n=e;else{let i=!jr||jr==="/",l=!1;try{await ya.access(fs,Sa.X_OK),l=!0}catch{}n=gs.versions.electron??(Ut==="android"||i||!l)?"xdg-open":fs}t.length>0&&r.push(...t),o.wait||(s.stdio="ignore",s.detached=!0)}Ut==="darwin"&&t.length>0&&r.push("--args",...t),o.target&&r.push(o.target);let a=ws.spawn(n,r,s);return o.wait?new Promise((i,l)=>{a.once("error",l),a.once("close",c=>{if(!o.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}i(a)})}):(a.unref(),a)},Ra=(o,e)=>{if(typeof o!="string")throw new TypeError("Expected a `target`");return In({...e,target:o})};function hs(o){if(typeof o=="string"||Array.isArray(o))return o;let{[ms]:e}=o;if(!e)throw new Error(`${ms} is not supported`);return e}function Pn({[Ut]:o},{wsl:e}){if(e&&xt)return hs(e);if(!o)throw new Error(`${Ut} is not supported`);return hs(o)}var It={};wt(It,"chrome",()=>Pn({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"]}}));wt(It,"brave",()=>Pn({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"]}}));wt(It,"firefox",()=>Pn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));wt(It,"edge",()=>Pn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));wt(It,"browser",()=>"browser");wt(It,"browserPrivate",()=>"browserPrivate");var bs=Ra;import{createHash as ka,randomBytes as Ta}from"crypto";var qe=class{authBaseUrl;consentUrl;constructor(e="prod"){let t=ie(e);this.authBaseUrl=t.authBaseUrl,this.consentUrl=t.consentUrl}static generatePkce(){let e=Ta(96).toString("base64url").slice(0,128),t=ka("sha256").update(e).digest("base64url");return[e,t]}buildAuthorizationUrl(e,t,n,r){let s=new URLSearchParams({response_type:"code",client_id:e,redirect_uri:r,scope:Eo,code_challenge:t,code_challenge_method:"S256",state:n});return`${this.consentUrl}/oauth2?${s.toString()}`}async registerClient(e){let t=await fetch(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:So,redirect_uris:[e],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!t.ok)throw new Error(`DCR failed: ${t.status} ${await t.text()}`);return t.json()}async exchangeCode(e,t,n,r){let s=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:r,client_id:t,code_verifier:n})});if(!s.ok)throw new Error(`Token exchange failed: ${s.status}`);return s.json()}async refreshToken(e,t){let n=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:t})});if(!n.ok)throw new Error(`Token refresh failed: ${n.status}`);return n.json()}async revokeToken(e,t,n="access_token"){await fetch(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,token_type_hint:n,client_id:t})})}};var ot=class{profile;environment;creds;oauth;constructor(e="default",t="prod",n){this.profile=e,this.environment=t,this.creds=n??new ye,this.oauth=new qe(t)}async login(){let{server:e,port:t}=await this.startCallbackServer(),n=yo(t);try{let r=this.creds.loadClient(this.profile,this.environment);r||(r=await this.oauth.registerClient(n),this.creds.saveClient(this.profile,this.environment,r));let s=r.client_id,[a,i]=qe.generatePkce(),l=Ia(32).toString("hex"),c=this.oauth.buildAuthorizationUrl(s,i,l,n),f=await this.waitForCallback(e,t,c,l);if(!f)throw new Error("Login cancelled or timed out");let d=await this.oauth.exchangeCode(f,s,a,n),g={access_token:d.access_token,refresh_token:d.refresh_token,expires_at:Math.floor(Date.now()/1e3)+d.expires_in,scope:d.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,g),this.creds.setActiveProfile(this.profile),g}catch(r){throw e.close(),r}}startCallbackServer(){return new Promise((e,t)=>{let n=ar,r=()=>{let s=Aa();s.on("error",a=>{a.code==="EADDRINUSE"&&n<lr?(n++,r()):t(new Error(`Failed to start callback server: ${a.message}. Ports ${ar}-${lr} are all in use.`))}),s.listen(n,ir,()=>{e({server:s,port:n})})};r()})}waitForCallback(e,t,n,r){return new Promise(s=>{let a=!1,i=setTimeout(()=>l(null),12e4),l=c=>{a||(a=!0,clearTimeout(i),e.close(),s(c))};e.on("request",(c,f)=>{let d=new Pa(c.url??"/",`http://${ir}:${t}`);if(d.pathname!==_o){f.writeHead(404),f.end();return}let g=d.searchParams.get("state"),E=d.searchParams.get("code");if(d.searchParams.get("error")){f.writeHead(200,{"Content-Type":"text/html"}),f.end("<html><body><h1>Login Failed</h1><p>You can close this tab.</p></body></html>"),l(null);return}if(g!==r){f.writeHead(400,{"Content-Type":"text/html"}),f.end("<html><body><h1>Invalid State</h1></body></html>"),l(null);return}f.writeHead(200,{"Content-Type":"text/html"}),f.end("<html><body><h1>Login Successful!</h1><p>You can close this tab and return to the terminal.</p></body></html>"),l(E)}),bs(n).catch(c=>{let f=c instanceof Error?c.message:String(c);process.stderr.write(`[auth] Could not open browser: ${f}
35
+ Please open this URL manually: ${n}
36
+ `)})})}};var D=N(re(),1),_s=Ge;function ys({onComplete:o}){let[e]=(0,Ee.useState)(()=>new Ke),[t]=(0,Ee.useState)(()=>new ye),[n,r]=(0,Ee.useState)(process.env.KANE_DEV_MODE==="1"?"env":"auth"),[s,a]=(0,Ee.useState)(0),[i,l]=(0,Ee.useState)(""),[c,f]=(0,Ee.useState)("username"),[d,g]=(0,Ee.useState)(""),[E,h]=(0,Ee.useState)(null),[y,_]=(0,Ee.useState)(!1),[w,I]=(0,Ee.useState)([]),[z,ce]=(0,Ee.useState)([]),[Y,B]=(0,Ee.useState)(null),P=(0,Ee.useCallback)(b=>{a(0),l(""),h(null),r(b)},[]),R=(0,Ee.useCallback)(()=>{e.set("default_url",_s),e.set("setup_complete",!0),P("modes")},[e,P]),G=(0,Ee.useCallback)(async()=>{let{credentials:b,profile:v,env:C}=t.getActiveCredentials();if(!b||!v||!C)return null;let $=b.expires_at,U=Date.now()/1e3;if($-U<300){let H=t.loadClient(v,C);if(!H)return null;let Q=await new qe(C).refreshToken(b.refresh_token,H.client_id),le={access_token:Q.access_token,refresh_token:Q.refresh_token,expires_at:Math.floor(U)+Q.expires_in,scope:Q.scope};return t.saveCredentials(v,C,le),le.access_token}return b.access_token},[t]),Z=(0,Ee.useCallback)(async()=>{r("loading-projects");try{let b=t.resolveAuth();if(!b)throw new Error("No auth configured");let v=t.getDefaultEnv(),C=ie(v),$,U;if(b.method==="basic")$=b.username,U=b.access_key;else{let le=await G();if(!le)throw new Error("Could not get OAuth token");let de=await new Yt(C.controllerBaseUrl,le).getTmsCredentials();$=de.username,U=de.access_key}let Q=(await new et(C.tmsBaseUrl,$,U).listProjects()).map(le=>({id:le.project_id,label:`${le.name} (${le.project_id})`,isActive:le.name.toLowerCase().includes("kaneai")}));if(Q.length===0){h("No projects found."),R();return}I(Q),r("project")}catch(b){h(`Could not fetch projects: ${b instanceof Error?b.message:b}`),R()}},[t,G,P,R]),p=(0,Ee.useCallback)(async b=>{r("loading-folders");try{let v=t.resolveAuth();if(!v)throw new Error("No auth configured");let C=t.getDefaultEnv(),$=ie(C),U,H;if(v.method==="basic")U=v.username,H=v.access_key;else{let de=await G();if(!de)throw new Error("Could not get OAuth token");let ct=await new Yt($.controllerBaseUrl,de).getTmsCredentials();U=ct.username,H=ct.access_key}let W=new et($.tmsBaseUrl,U,H),Q=await W.listFolders(b),le=await W.getDefaultFolder(b).catch(()=>null);B(le);let Re=Q.map(de=>({id:de.id,label:`${de.name} (${de.id}) \xB7 ${de.test_cases_count} tests`,isActive:de.id===le}));if(Re.length===0){le&&e.set("folder_id",le),R();return}ce(Re),r("folder")}catch{R()}},[t,G,e,R]);return $e((b,v)=>{if(!y&&!(n==="loading-projects"||n==="loading-folders")){if(n==="modes"){v.return&&(r("done"),setTimeout(o,300));return}if(n==="env"||n==="auth"){if(v.upArrow)a($=>Math.max(0,$-1));else if(v.downArrow)a($=>Math.min(1,$+1));else if(v.return){if(n==="env"){let $=s===0?"prod":"stage";t.setDefaultEnv($),P("auth")}else if(n==="auth")if(s===0){_(!0);let $=t.getDefaultEnv(),U="default";t.setActiveProfile(U),new ot(U,$,t).login().then(()=>{_(!1),Z()}).catch(W=>{_(!1),h(`Login failed: ${W.message}`)})}else P("auth-basic"),f("username")}return}if(n==="auth-basic"){if(v.return)if(c==="username"){if(!i.trim()){h("Username is required");return}g(i.trim()),l(""),f("access_key"),h(null)}else{if(!i.trim()){h("Access key is required");return}let C="default",$=t.getDefaultEnv();t.setActiveProfile(C),t.saveBasicAuth(C,$,{username:d,access_key:i.trim()}),Z()}else v.backspace||v.delete?l(C=>C.slice(0,-1)):b&&!v.ctrl&&!v.meta&&l(C=>C+b);return}}},{isActive:n!=="project"&&n!=="folder"}),(0,D.jsx)(x,{flexDirection:"column",padding:1,children:(0,D.jsx)(vn,{title:"Kane CLI \u2014 First-time Setup",variant:n==="done"?"success":"default",children:(0,D.jsxs)(x,{flexDirection:"column",paddingY:1,children:[n==="env"&&(0,D.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,D.jsxs)(x,{children:[(0,D.jsx)(u,{color:m.purple,children:"?"}),(0,D.jsx)(u,{bold:!0,children:" Select environment"})]}),(0,D.jsxs)(x,{marginLeft:2,flexDirection:"column",children:[(0,D.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","prod"]}),(0,D.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","stage"]})]})]}),n==="auth"&&(0,D.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,D.jsxs)(x,{children:[(0,D.jsx)(u,{color:m.purple,children:"?"}),(0,D.jsx)(u,{bold:!0,children:" Which authentication method?"})]}),(0,D.jsxs)(x,{marginLeft:2,flexDirection:"column",children:[(0,D.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","OAuth (browser login)"]}),(0,D.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","Basic (username + access key)"]})]}),y&&(0,D.jsx)(x,{marginTop:1,marginLeft:2,children:(0,D.jsx)(u,{color:m.cyan,children:"\u280B Opening browser for login\u2026"})})]}),n==="auth-basic"&&(0,D.jsxs)(x,{flexDirection:"column",children:[(0,D.jsxs)(x,{marginBottom:c==="access_key"?0:1,children:[(0,D.jsx)(u,{color:c==="access_key"?m.statusPass:m.primary,children:c==="access_key"?"\u2713":"?"}),(0,D.jsx)(u,{bold:!0,children:" Username: "}),c==="username"?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(u,{color:m.base,children:i}),(0,D.jsx)(u,{color:m.primary,inverse:!0,children:" "})]}):(0,D.jsx)(u,{color:m.statusPass,children:d})]}),c==="access_key"&&(0,D.jsxs)(x,{marginBottom:1,children:[(0,D.jsx)(u,{color:m.primary,children:"?"}),(0,D.jsx)(u,{bold:!0,children:" Access Key: "}),(0,D.jsx)(u,{color:m.dim,children:"\u2022".repeat(i.length)}),(0,D.jsx)(u,{color:m.primary,inverse:!0,children:" "})]})]}),n==="loading-projects"&&(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.cyan,children:"\u280B Fetching projects\u2026"})}),n==="project"&&(0,D.jsx)(cr,{title:"Select project",items:w,itemNoun:"projects",onSelect:b=>{e.set("project_id",b.id),p(b.id)},onCancel:()=>{R()}}),n==="loading-folders"&&(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.cyan,children:"\u280B Fetching folders\u2026"})}),n==="folder"&&(0,D.jsx)(cr,{title:"Select folder",items:z,itemNoun:"folders",onSelect:b=>{e.set("folder_id",b.id),R()},onCancel:()=>{Y&&e.set("folder_id",Y),R()}}),n==="modes"&&(0,D.jsxs)(x,{flexDirection:"column",children:[(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.statusPass,bold:!0,children:"\u2713 Setup complete!"})}),(0,D.jsx)(x,{marginTop:1,children:(0,D.jsx)(xn,{label:"Profile",value:t.getActiveProfile()??"default"})}),(0,D.jsx)(xn,{label:"Environment",value:t.getDefaultEnv()}),(0,D.jsx)(xn,{label:"Default URL",value:_s}),(0,D.jsx)(x,{marginTop:1,flexDirection:"column",children:(0,D.jsx)(u,{bold:!0,color:m.primary,children:"Available modes:"})}),(0,D.jsxs)(x,{marginLeft:2,flexDirection:"column",marginTop:1,children:[(0,D.jsxs)(x,{children:[(0,D.jsx)(u,{bold:!0,color:m.base,children:"TUI "}),(0,D.jsx)(u,{color:m.dim,children:"Interactive menu + chat UI"})]}),(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.dim,children:" kane-cli"})}),(0,D.jsxs)(x,{marginTop:1,children:[(0,D.jsx)(u,{bold:!0,color:m.base,children:"CLI "}),(0,D.jsx)(u,{color:m.dim,children:"Headless single-run, JSON output"})]}),(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.dim,children:' kane-cli run "objective" --url <url>'})}),(0,D.jsxs)(x,{marginTop:1,children:[(0,D.jsx)(u,{bold:!0,color:m.base,children:"Agent "}),(0,D.jsx)(u,{color:m.dim,children:"Programmatic setup + run via CLI flags"})]}),(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.dim,children:" kane-cli login --username <u> --access-key <k>"})})]}),(0,D.jsxs)(x,{marginTop:1,children:[(0,D.jsx)(u,{color:m.dim,children:"Press "}),(0,D.jsx)(u,{bold:!0,color:m.primary,children:"Enter"}),(0,D.jsx)(u,{color:m.dim,children:" to launch TUI"})]})]}),n==="done"&&(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.statusPass,bold:!0,children:"Launching\u2026"})}),E&&(0,D.jsx)(x,{marginTop:1,children:(0,D.jsx)(u,{color:m.red,children:E})})]})})})}var st=N(ke(),1);var Ue=N(re(),1);function Oa(o,e){let t=[],r=Math.max(e-4,30);t.push({type:"title",text:o.title});for(let s=0;s<o.sections.length;s++){let a=o.sections[s];s>0&&t.push({type:"divider",text:"\u2500".repeat(r)}),a.label&&t.push({type:"header",text:a.label});let i=a.entries.length>0?Math.max(...a.entries.map(l=>l.key.length)):0;for(let l of a.entries){let c="\xB7".repeat(Math.max(2,i-l.key.length+3)),f=`${l.key} ${c} ${l.value}`;t.push({type:"entry",text:f,color:l.color})}}return t.push({type:"footer",text:"esc back"}),t}function Ss({data:o,width:e=60}){let t=Oa(o,e);return(0,Ue.jsx)(x,{flexDirection:"column",borderStyle:"round",borderColor:m.primary,paddingX:2,paddingY:1,children:t.map((n,r)=>{if(n.type==="title")return(0,Ue.jsx)(u,{color:m.primary,bold:!0,children:n.text},r);if(n.type==="header")return(0,Ue.jsx)(x,{marginTop:1,children:(0,Ue.jsx)(u,{color:m.dim,children:n.text})},r);if(n.type==="divider")return(0,Ue.jsx)(x,{marginTop:1,marginBottom:0,children:(0,Ue.jsx)(u,{color:m.ambient,children:n.text})},r);if(n.type==="footer")return(0,Ue.jsx)(x,{marginTop:1,children:(0,Ue.jsx)(u,{color:m.dim,children:n.text})},r);let s=n.text.match(/^(.+?) (·+) (.+)$/);return s?(0,Ue.jsxs)(u,{children:[(0,Ue.jsxs)(u,{color:m.secondary,children:[s[1]," "]}),(0,Ue.jsxs)(u,{color:m.ambient,children:[s[2]," "]}),(0,Ue.jsx)(u,{color:n.color??m.base,children:s[3]})]},r):(0,Ue.jsx)(u,{color:n.color??m.base,children:n.text},r)})})}var Oe=N(re(),1);function Es(o,e){let t=[];function n(r,s){for(let a of r)t.push({item:a,depth:s}),a.type==="submenu"&&a.children&&e.length>s&&e[s]===a.id&&n(a.children,s+1)}return n(o,0),t}function Cs({items:o,onRunSelected:e,renderLoginWizard:t,renderProfilesView:n,renderChromeProfilePicker:r,renderProjectPicker:s,renderFolderPicker:a,renderWindowSizePicker:i}){let[l,c]=(0,st.useState)({expandedPath:[],selectedIndex:0,inputValue:"",isEditing:!1,isSelecting:!1,feedback:null,activeView:null,infoData:null}),f=Es(o,l.expandedPath),d=f[l.selectedIndex]?.item,g=(0,st.useRef)(null),E=(0,st.useCallback)(y=>{c(_=>({..._,feedback:y})),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{c(_=>({..._,feedback:null})),g.current=null},4e3)},[]);(0,st.useEffect)(()=>()=>{g.current&&clearTimeout(g.current)},[]);let h=(0,st.useCallback)(()=>{c(y=>({...y,activeView:null,infoData:null}))},[]);return $e((y,_)=>{if(l.activeView==="infoView"){_.escape&&h();return}if(!(l.activeView==="loginWizard"||l.activeView==="profilesView"||l.activeView==="chromeProfilePicker"||l.activeView==="projectPicker"||l.activeView==="folderPicker"||l.activeView==="windowSizePicker")){if(l.isEditing){if(_.escape){c(w=>({...w,isEditing:!1,inputValue:""}));return}if(_.return){let w=l.inputValue.trim();if(d?.onValue&&w){let I=d.currentValue;d.onValue(w),E(I?`${d.label}: ${I} \u2192 ${w}`:`${d.label}: ${w}`)}c(I=>({...I,isEditing:!1,inputValue:""}));return}if(_.backspace||_.delete){c(w=>({...w,inputValue:w.inputValue.slice(0,-1)}));return}y&&!_.ctrl&&!_.meta&&c(w=>({...w,inputValue:w.inputValue+y}));return}if(l.isSelecting&&d?.options){let w=d.options;if(_.escape){c(I=>({...I,isSelecting:!1}));return}if(_.upArrow){c(I=>({...I,inputValue:String(Math.max(0,Number(I.inputValue||"0")-1))}));return}if(_.downArrow){c(I=>({...I,inputValue:String(Math.min(w.length-1,Number(I.inputValue||"0")+1))}));return}if(_.return){let I=Number(l.inputValue||"0"),z=w[I];if(z&&d.onValue){let ce=d.currentValue;d.onValue(z.value),E(ce?`${d.label}: ${ce} \u2192 ${z.label}`:`${d.label}: ${z.label}`)}c(ce=>({...ce,isSelecting:!1,inputValue:""}));return}return}if(_.upArrow){c(w=>({...w,selectedIndex:Math.max(0,w.selectedIndex-1)}));return}if(_.downArrow){c(w=>({...w,selectedIndex:Math.min(f.length-1,w.selectedIndex+1)}));return}if(_.escape){c(w=>{if(w.expandedPath.length===0)return w;let I=w.expandedPath.slice(0,-1),z=Es(o,I),ce=w.expandedPath[w.expandedPath.length-1],Y=z.findIndex(B=>B.item.id===ce);return{...w,expandedPath:I,selectedIndex:Y>=0?Y:0}});return}if(_.return&&d){if(d.id==="run-start"){e();return}if(d.type==="submenu"){let w=f[l.selectedIndex]?.depth??0;c(I=>({...I,expandedPath:[...I.expandedPath.slice(0,w),d.id],selectedIndex:I.selectedIndex+1}));return}if(d.onInfo){let w=d.onInfo();c(I=>({...I,activeView:"infoView",infoData:w}));return}if(d.onLoginWizard){d.onLoginWizard(),c(w=>({...w,activeView:"loginWizard"}));return}if(d.onProfilesView){d.onProfilesView(),c(w=>({...w,activeView:"profilesView"}));return}if(d.onChromeProfilePicker){d.onChromeProfilePicker(),c(w=>({...w,activeView:"chromeProfilePicker"}));return}if(d.onProjectPicker){d.onProjectPicker(),c(w=>({...w,activeView:"projectPicker"}));return}if(d.onFolderPicker){d.onFolderPicker(),c(w=>({...w,activeView:"folderPicker"}));return}if(d.onWindowSizePicker){d.onWindowSizePicker(),c(w=>({...w,activeView:"windowSizePicker"}));return}if(d.type==="action"){d.onAction?.(),d.suppressFeedback||E(`${d.label} done`);return}if(d.type==="select"&&d.options){let w=d.options.findIndex(I=>I.value===d.currentValue);c(I=>({...I,isSelecting:!0,inputValue:String(Math.max(0,w))}));return}if(d.type==="text-input"){c(w=>({...w,isEditing:!0,inputValue:d.currentValue??""}));return}}}}),(0,Oe.jsx)(x,{flexDirection:"column",paddingX:1,children:l.activeView==="infoView"&&l.infoData?(0,Oe.jsx)(Ss,{data:l.infoData}):l.activeView==="loginWizard"&&t?t(h):l.activeView==="profilesView"&&n?n(h):l.activeView==="chromeProfilePicker"&&r?r(h):l.activeView==="projectPicker"&&s?s(h):l.activeView==="folderPicker"&&a?a(h):l.activeView==="windowSizePicker"&&i?i(h):(0,Oe.jsxs)(Oe.Fragment,{children:[f.map(({item:y,depth:_},w)=>{let I=w===l.selectedIndex,z=" ".repeat(_),ce=I?"\u276F ":" ",Y=y.type==="submenu"?l.expandedPath.includes(y.id)?"\u25BC ":"\u25B6 ":" ",B=y.currentValue!=null?` [${y.currentValue}]`:"";if(I&&l.isSelecting&&y.options){let P=Number(l.inputValue||"0");return(0,Oe.jsxs)(x,{flexDirection:"column",children:[(0,Oe.jsxs)(u,{color:m.cyan,children:[z,ce,Y,y.label]}),y.options.map((R,G)=>(0,Oe.jsxs)(u,{color:G===P?m.cyan:void 0,children:[z," ",G===P?"\u276F ":" ",R.label]},R.value))]},y.id)}return I&&l.isEditing?(0,Oe.jsxs)(u,{color:m.cyan,children:[z,ce,Y,y.label,": ",l.inputValue,(0,Oe.jsx)(u,{color:m.dimmed,children:"\u2588"})]},y.id):(0,Oe.jsxs)(u,{color:I?m.cyan:void 0,dimColor:!I&&_>0,children:[z,ce,Y,y.label,(0,Oe.jsx)(u,{dimColor:!0,children:B})]},y.id)}),l.feedback&&(0,Oe.jsx)(x,{marginTop:1,children:(0,Oe.jsxs)(u,{color:m.green,children:["\u2713 ",l.feedback]})})]})})}var tn=N(ke(),1);var Te=N(re(),1),Lr=800,Ur=3840,Fr=600,Vr=2160;function Rs(o,e){if(!e)return"Enter a value";let t=Number(e);if(!Number.isInteger(t))return"Must be a whole number";if(o==="width"){if(t<Lr)return`Min ${Lr}`;if(t>Ur)return`Max ${Ur}`}else{if(t<Fr)return`Min ${Fr}`;if(t>Vr)return`Max ${Vr}`}return null}function ks({currentWidth:o,currentHeight:e,onSelect:t,onCancel:n}){let[r,s]=(0,tn.useState)("width"),[a,i]=(0,tn.useState)(String(o)),[l,c]=(0,tn.useState)(String(e)),[f,d]=(0,tn.useState)(null);$e((E,h)=>{if(h.escape){n();return}if(h.tab||h.rightArrow||h.leftArrow){s(y=>y==="width"?"height":"width"),d(null);return}if(h.return){let y=Rs("width",a);if(y){s("width"),d(`Width: ${y}`);return}let _=Rs("height",l);if(_){s("height"),d(`Height: ${_}`);return}t(Number(a),Number(l));return}if(h.backspace||h.delete){r==="width"?i(y=>y.slice(0,-1)):c(y=>y.slice(0,-1)),d(null);return}E&&/^\d$/.test(E)&&(r==="width"?i(y=>y+E):c(y=>y+E),d(null))});let g=(E,h,y)=>{let _=r===y,w=_?m.primary:m.secondary;return(0,Te.jsxs)(x,{flexDirection:"column",children:[(0,Te.jsxs)(u,{color:m.dim,children:[" ",E]}),(0,Te.jsx)(x,{borderStyle:"round",borderColor:w,paddingX:1,width:10,children:(0,Te.jsxs)(u,{color:_?m.base:m.dim,children:[h||" ",_?(0,Te.jsx)(u,{color:m.dimmed,children:"\u2588"}):""]})}),(0,Te.jsxs)(u,{color:m.dim,dimColor:!0,children:[" ",y==="width"?`${Lr}\u2013${Ur}`:`${Fr}\u2013${Vr}`]})]})};return(0,Te.jsxs)(x,{flexDirection:"column",paddingX:1,children:[(0,Te.jsx)(u,{color:m.primary,bold:!0,children:"Window Size"}),(0,Te.jsxs)(x,{marginTop:1,gap:1,children:[g("Width",a,"width"),(0,Te.jsx)(x,{alignItems:"center",marginTop:1,children:(0,Te.jsx)(u,{color:m.dim,children:"x"})}),g("Height",l,"height")]}),f&&(0,Te.jsx)(x,{marginTop:1,children:(0,Te.jsx)(u,{color:m.red,children:f})}),(0,Te.jsx)(x,{marginTop:1,children:(0,Te.jsx)(u,{color:m.dim,children:"Tab/arrows to switch Enter to save Esc to cancel"})})]})}import{randomUUID as Da}from"crypto";import{mkdirSync as Ba,writeFileSync as Ts,appendFileSync as $a,existsSync as As}from"fs";import{join as nn}from"path";var ja=nn(ve,"sessions"),Ft=class{sessionId;sessionDir;runs=[];_nextIndex=0;_started=!1;_testId=null;_testcaseId=null;_projectId=null;_uploadStatus="pending";_uploadAttempts=0;_uploadError=null;_firstObjective=null;_firstUrl=null;_auteurVariables={};_screenshotSas=null;_model="";_environment="";_profile=null;_startedAt="";_remoteLogger=null;_earlyLogBuffer=[];constructor(){this.sessionId=Da(),this.sessionDir=nn(ja,this.sessionId)}start(e){if(this._started)return;this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString(),Ba(this.sessionDir,{recursive:!0});let t={session_id:this.sessionId,started_at:this._startedAt,model:e.model,environment:e.environment,profile:e.profile,objectives:[],runs:[],status:"in_progress"};Ts(nn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
37
+ `),this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`),this._earlyLogBuffer.push({level:"info",event:"SESSION_START",message:"Session started",context:{session_id:this.sessionId}},{level:"info",event:"CONFIG",message:"Session config",context:{model:e.model,environment:e.environment,profile:e.profile}})}setRemoteLogger(e){this._remoteLogger=e;for(let t of this._earlyLogBuffer)e.log(t.level,t.event,t.message,t.context);this._earlyLogBuffer=[]}get hasRemoteLogger(){return this._remoteLogger!==null}setAuteurVariables(e){Object.assign(this._auteurVariables,e)}get auteurVariables(){return this._auteurVariables}setScreenshotSas(e){this._screenshotSas=e}get screenshotSas(){return this._screenshotSas}get screenshotBaseUrl(){return this._screenshotSas?`${this._screenshotSas.base_url}/${this._screenshotSas.container}`:""}get startedAt(){return this._startedAt||new Date().toISOString()}log(e,t,n,r){if(t===void 0){this._log(e);let i=e.indexOf(" "),l=i>0?e.slice(0,i):e,c=i>0?e.slice(i+1):"",f=/fail|error/i.test(e)?"error":"info";this._remoteLogger?.log(f,l,c||e);return}let s=e,a=n;this._log(`${t} ${a}`),this._remoteLogger?.log(s,t,a,r)}logStep(e,t,n){this._log(`${e} ${t}`);let r=this._nextIndex>0?this._nextIndex-1:0;this._remoteLogger?.logStep(r,e,t,n)}logCommand(e){this._log(`COMMAND ${e}`)}logRunStart(e,t,n){this._log(`RUN ${e} START objective="${t.slice(0,100)}" url=${n}`),this._remoteLogger?.setRunIndex(e),this._remoteLogger?.log("info","RUN_START",`Run ${e} started`,{run_index:e,objective:t,url:n})}logRunEnd(e,t,n,r){let s=(n??0).toFixed(1),a=(r??"").slice(0,100);this._log(`RUN ${e} END status=${t} duration=${s}s summary="${a}"`),this._remoteLogger?.log("info","RUN_END",`Run ${e} ended`,{run_index:e,status:t,duration:n??0,summary:r??""}),t!=="failed"&&t!=="error"&&this._remoteLogger?.discardSteps(e)}escalateRun(e){this._remoteLogger?.escalate(e)}logChromeLaunch(e,t){this._log(`CHROME LAUNCH port=${e} endpoint=${t}`),this._remoteLogger?.log("info","CHROME_LAUNCH","Chrome launched",{port:e,cdp_endpoint:t})}async finish(e="complete"){this._log(`SESSION END status=${e} total_runs=${this.runs.length}`),this._remoteLogger?.log("info","SESSION_END","Session ended",{status:e,total_runs:this.runs.length}),await this._remoteLogger?.shutdown();let t={session_id:this.sessionId,started_at:this._startedAt,ended_at:new Date().toISOString(),model:this._model,environment:this._environment,profile:this._profile,status:e,total_runs:this.runs.length,test_id:this._testId,testcase_id:this._testcaseId,commit_id:this.sessionId,project_id:this._projectId,upload_status:this._uploadStatus,upload_attempts:this._uploadAttempts,last_upload_attempt:this._uploadAttempts>0?new Date().toISOString():null,upload_error:this._uploadError,runs:this.runs.map(n=>({index:n.index,objective:n.objective,status:n.status,summary:n.summary,run_dir:n.run_dir}))};As(this.sessionDir)&&Ts(nn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
38
+ `)}nextRunIndex(){return this._nextIndex}addRunResult(e,t){this.runs.push(e),this._nextIndex+=t??1}getContext(){return{prior_runs:this.runs.map(e=>({index:e.index,objective:e.objective,summary:e.summary,status:e.status,memory:e.context.memory,variables:e.context.variables,pointer:e.context.pointer}))}}setTestId(e){this._testId=e}get testId(){return this._testId}setTestcaseId(e){this._testcaseId=e}get testcaseId(){return this._testcaseId}setProjectId(e){this._projectId=e}setFirstRun(e,t){this._firstObjective||(this._firstObjective=e,this._firstUrl=t)}get firstObjective(){return this._firstObjective}get firstUrl(){return this._firstUrl}getRunDirs(){let e=[];for(let t of this.runs)t.run_dirs&&t.run_dirs.length>0?e.push(...t.run_dirs):t.run_dir&&e.push(t.run_dir);return e}getRunObjectives(){let e=[];for(let t of this.runs)t.flow_objectives&&t.flow_objectives.length>0?e.push(...t.flow_objectives):e.push(t.objective);return e}getRunMetadata(){let e=[];for(let t of this.runs)if(t.perFlowMetadata&&t.perFlowMetadata.length>0)e.push(...t.perFlowMetadata);else{let n={resultCode:t.resultCode,reasonCode:t.reasonCode,errorMessage:t.status==="failed"?t.summary??null:null,summary:t.summary,oneLiner:t.oneLiner},r=t.run_dirs?.length??1;for(let s=0;s<r;s++)e.push(n)}return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e){if(!this._started||!As(this.sessionDir))return;let t=new Date().toISOString().slice(0,19).replace("T"," "),n=nn(this.sessionDir,"tui.log");$a(n,`[${t}] ${e}
39
+ `)}};import{dirname as La,join as Ua}from"path";function rn(o,e,t){let n=o.total_runs??1,r=o.run_dir,s,a;if(n>1&&r){let i=La(r);s=Array.from({length:n},(l,c)=>Ua(i,String(e+c))),t&&t.length===n&&(a=t)}return{allRunDirs:s,flowObjectives:a}}function on(o,e,t,n){return{index:t,objective:e,summary:o.summary,oneLiner:o.one_liner,status:o.status,resultCode:o.result_code,reasonCode:o.reason_code,perFlowMetadata:o.per_flow_metadata,context:o.context??{memory:{},variables:{},pointer:""},run_dir:o.run_dir,run_dirs:n.allRunDirs,flow_objectives:n.flowObjectives}}var De=N(ke(),1);async function On(o){let e=o.credentials.expires_at,t=o.thresholdSeconds??300;if(e-Date.now()/1e3>=t)return null;let n=o.creds.loadClient(o.profile,o.env);if(!n)return null;let s=await new qe(o.env).refreshToken(o.credentials.refresh_token,n.client_id),a=Math.floor(Date.now()/1e3)+s.expires_in;return o.creds.saveCredentials(o.profile,o.env,{access_token:s.access_token,refresh_token:s.refresh_token,expires_at:a,scope:s.scope}),{accessToken:s.access_token,refreshToken:s.refresh_token,expiresAt:a,scope:s.scope}}async function Dn(o,e,t){let n=o.loadCredentials(e,t),r=o.loadClient(e,t);if(n&&r){let a=new qe(t);await Promise.allSettled([a.revokeToken(n.access_token,r.client_id,"access_token"),a.revokeToken(n.refresh_token,r.client_id,"refresh_token")])}o.deleteProfileFull(e,t);let s=o.listProfiles();return s.length>0&&(o.setActiveProfile(s[0].profile),o.setDefaultEnv(s[0].env)),{profile:e,env:t,switchedTo:s.length>0?s[0]:void 0}}function Is(){let[o]=(0,De.useState)(()=>new ye),[e,t]=(0,De.useState)(()=>{let h=o.resolveAuth();if(!h)return!1;if(h.method==="basic")return!0;let{credentials:y}=o.getActiveCredentials();return y?y.expires_at>Date.now()/1e3:!1}),n=(0,De.useRef)(null),r=(0,De.useRef)(null),s=(0,De.useCallback)(()=>{let h=o.resolveAuth();return h?{method:h.method,profile:h.profile,env:h.env}:null},[o]),a=(0,De.useCallback)(async()=>{let{credentials:h,profile:y,env:_}=o.getActiveCredentials();if(!h||!y||!_)return null;let w=h.expires_at,I=Date.now()/1e3;if(w-I<300){if(r.current)return r.current;let z=(async()=>{try{let ce=await On({creds:o,profile:y,env:_,credentials:h});return ce?(t(!0),ce.accessToken):null}catch{return t(!1),null}finally{r.current=null}})();return r.current=z,z}return t(!0),h.access_token},[o]),i=(0,De.useCallback)(()=>{let h=o.resolveAuth();return!h||h.method!=="basic"?null:{username:h.username,access_key:h.access_key}},[o]),l=(0,De.useCallback)((h,y)=>{n.current?.revoke();let _=ie(h),w=i(),I=new Lt(_.controllerBaseUrl,a,w,y);return n.current=I,I},[i,a]),c=(0,De.useCallback)(()=>n.current,[]),f=(0,De.useCallback)(()=>{let h=i();if(h)return h;let y=n.current?.cached;return y?{username:y.username,access_key:y.access_key}:null},[i]),d=(0,De.useCallback)(async()=>{let h=n.current;return h?h.resolve():null},[]),g=(0,De.useCallback)(async(h="default")=>{let y=o.getDefaultEnv();await new ot(h,y,o).login(),t(!0)},[o]),E=(0,De.useCallback)(async()=>{let h=o.getActiveProfile();if(!h)return null;let y=o.getDefaultEnv(),_=await Dn(o,h,y);return t(!1),{profile:_.profile,env:_.env}},[o]);return{creds:o,tokenValid:e,setTokenValid:t,getToken:a,getBasicAuth:i,getAuthInfo:s,login:g,logout:E,initResolver:l,getResolver:c,getResolvedBasicAuth:f,resolveBasicAuth:d}}var it=N(ke(),1);import{spawn as Ps}from"child_process";import{existsSync as Fa}from"fs";import{createConnection as Va}from"net";import{homedir as sn,platform as Nr}from"os";import{join as an}from"path";var Os={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",an(sn(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",an(sn(),"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",an(sn(),"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",an(sn(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",an(sn(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function Na(){let o=Nr(),e=Os[o]??Os.linux;for(let t of e)if(Fa(t))return t;return o==="win32"?"chrome.exe":"google-chrome"}function Ma(o){let e=Nr(),t=[`--remote-debugging-port=${o.port}`,`--user-data-dir=${o.userDataDir}`,`--window-size=${o.width},${o.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 e==="linux"&&(t.push("--no-sandbox"),t.push("--disable-dev-shm-usage"),t.push("--password-store=basic")),e==="darwin"&&t.push("--use-mock-keychain"),o.headless&&t.push("--headless=new"),t}function Ha(o){return new Promise(e=>{let t=Va({port:o,host:"127.0.0.1"});t.setTimeout(1e3),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{t.destroy(),e(!1)})})}async function Wa(){for(let o=or;o<=sr;o++)if(!await Ha(o))return o;throw new Error(`All CDP ports ${or}-${sr} are in use. Close other Chrome instances.`)}async function Ka(o,e=15e3){let t=Date.now(),n=`http://127.0.0.1:${o}/json/version`;for(;Date.now()-t<e;){try{if((await fetch(n)).ok)return`http://127.0.0.1:${o}`}catch{}await new Promise(r=>setTimeout(r,200))}throw new Error(`Chrome CDP not ready after ${e}ms on port ${o}`)}async function Bn(o){let e=Nr(),t=await Wa(),n=Na(),r=Ma({port:t,...o});o.startUrl&&r.push(o.startUrl);let s=Ps(n,r,{stdio:"ignore",detached:!0,windowsHide:!0});s.unref();let a=await new Promise((i,l)=>{s.on("error",c=>{l(new Error(`Failed to launch Chrome: ${c.message}. Is Chrome installed at ${n}?`))}),s.on("close",c=>{c!==null&&c!==0&&l(new Error(`Chrome exited during startup with code ${c}`))}),Ka(t).then(i,l)});return{process:s,port:t,cdpEndpoint:a,kill(){try{if(s.pid)if(e==="win32")Ps("taskkill",["/pid",String(s.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-s.pid,"SIGKILL")}catch{s.kill("SIGKILL")}else s.kill("SIGKILL")}catch{}}}}var js=()=>!!process.env.KANE_DEV_MODE,bt=[],Ds=!1,Bs=null,Mr=null,Hr=null,$n=null;function jn(o){$n=o}function Qe(o,e){bt=bt.filter(t=>t.name!==o),bt.push({name:o,fn:e})}function Je(o,e){let t=bt.find(r=>r.name===o);if(!t)return;bt=bt.filter(r=>r.name!==o);let n=!0;try{t.fn()}catch(r){n=!1,process.stderr.write(`[exit-manager] cleanup(${o}) failed: ${r instanceof Error?r.message:String(r)}
40
+ `)}e&&n&&js()&&process.stderr.write(`[exit-manager] cleanup(${o}): ${e}
41
+ `)}function ne(o,e,t=!1){if(Ds){process.exit(Bs??o);return}if(Ds=!0,Bs=o,t&&$n)try{$n.log("error","CRASH",e),$n.shutdownSync()}catch{}let n=[...bt].reverse(),r=[];for(let s of n)try{s.fn(),r.push(s.name)}catch(a){process.stderr.write(`[exit-manager] cleanup(${s.name}) failed: ${a instanceof Error?a.message:String(a)}
42
+ `)}if(bt=[],js()&&(process.stderr.write(`[exit-manager] shutdown(${o}): ${e}
43
+ `),r.length>0&&process.stderr.write(`[exit-manager] cleaned up: ${r.join(", ")}
44
+ `)),t&&Hr){try{Hr()}catch{}process.stderr.write(`
45
+ Kane CLI crashed unexpectedly: ${e}
46
+ `+(r.length>0?`Resources cleaned up (${r.join(", ")}).
47
+ `:"")),process.exit(o);return}if(Mr&&!t){Mr();return}process.exit(o)}function Ls(o){Mr=o}function Us(o){Hr=o}var $s=!1;function Fs(){$s||($s=!0,process.on("SIGINT",()=>{ne(130,"Received SIGINT",!0)}),process.on("SIGTERM",()=>{ne(143,"Received SIGTERM",!0)}),process.on("uncaughtException",o=>{ne(1,`Uncaught exception: ${o.message}`,!0)}),process.on("unhandledRejection",o=>{ne(1,`Unhandled rejection: ${String(o)}`,!0)}))}import{mkdtempSync as qa,rmSync as za}from"fs";import{join as Ga}from"path";import{tmpdir as Ja}from"os";function Vs(){let[o]=(0,it.useState)(()=>new Ke),e=(0,it.useRef)(null),t=(0,it.useRef)(null),n=(0,it.useRef)(null),r=(0,it.useCallback)(async a=>{if(e.current)return e.current;if(n.current)return n.current;let i=(async()=>{let l=o.load(),c;if(l.chrome_profile_path)c=l.chrome_profile_path.replace("~",process.env.HOME??"~");else{let g=qa(Ga(Ja(),"kane-clean-"));t.current=g,c=g}let f=await Bn({userDataDir:c,width:l.window_size.width,height:l.window_size.height,startUrl:a??l.default_url??void 0});e.current=f;let d=t.current;return Qe("chrome",()=>{if(f.kill(),d)try{za(d,{recursive:!0,force:!0})}catch{}}),f})();n.current=i;try{return await i}finally{n.current=null}},[o]),s=(0,it.useCallback)(()=>{Je("chrome","Chrome killed"),e.current=null,t.current=null},[]);return{ensureChrome:r,killChrome:s}}var Ce=N(ke(),1);import{spawn as Ya,execSync as Qa}from"child_process";import{existsSync as Ln}from"fs";import{resolve as Be,dirname as Za}from"path";import{fileURLToPath as el}from"url";import{createInterface as Xa}from"readline";async function*Ns(o){let e=Xa({input:o,crlfDelay:1/0});for await(let t of e){let n=t.trim();if(n)try{let r=JSON.parse(n);r&&typeof r.type=="string"&&(yield r)}catch{}}}var at=Za(el(import.meta.url));function tl(){for(let o of["python3","python"])try{return Qa(`${o} --version`,{stdio:"ignore"}),o}catch{}return null}function nl(){let e=process.platform==="win32"?"v16-runner.exe":"v16-runner",t={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},n=`${process.platform}-${process.arch}`,r=t[n];if(r)for(let i of r){let l=[Be(at,"..","node_modules",i,"bin",e),Be(at,"..","..","node_modules",i,"bin",e),Be(at,"..","..","..","node_modules",i,"bin",e)];for(let c of l)if(Ln(c))return{cmd:c,args:[]}}let s=[Be(at,"bin",e),Be(at,"..","bin",e),Be(at,"..","..","..","..","v16-runner","dist",e),Be(at,"..","..","..","v16-runner","dist",e),Be(process.cwd(),"v16-runner","dist",e),Be(process.cwd(),"..","v16-runner","dist",e)];for(let i of s)if(Ln(i))return{cmd:i,args:[]};let a=[Be(at,"..","..","..","..","v16-runner"),Be(at,"..","..","..","v16-runner"),Be(process.cwd(),"v16-runner"),Be(process.cwd(),"..","v16-runner")];for(let i of a)if(Ln(Be(i,"main.py"))){for(let c of[Be(i,".venv","bin","python"),Be(i,"..","browser-agent",".venv","bin","python")])if(Ln(c))return{cmd:c,args:["main.py"],cwd:i};let l=tl();if(l)return{cmd:l,args:["main.py"],cwd:i}}return null}function Un(o,e){let t=nl();if(!t)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");let n={...process.env};e?.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8"),n.V16_SERVER_API_HOST=ie(e?.environment).v16ServerHost,o.username&&o.access_key&&(n.LT_USERNAME=o.username,n.LT_ACCESS_KEY=o.access_key);let r=Ya(t.cmd,t.args,{stdio:["pipe","pipe","pipe"],env:n,cwd:t.cwd});r.stdin.on("error",()=>{}),r.stdin.write(JSON.stringify(o)+`
48
+ `);let s=1e5,a="";r.stderr.on("data",d=>{a+=d.toString(),a.length>s&&(a=a.slice(-s))}),r.on("error",d=>{e?.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:d.message})});let i=null,l=null,c=new Promise(d=>{r.on("close",(g,E)=>{i=g,l=E?String(E):null,e?.log?.("info","RUNNER_EXIT","Runner exited",{code:g,signal:l??"none"}),d({code:g,signal:l})})}),f=Ns(r.stdout);return{child:r,events:f,sendUserResponse(d){let g=JSON.stringify({type:"user_response",answer:d});try{r.stdin.write(g+`
49
+ `)}catch{}},sendCancel(d){let g=JSON.stringify({type:"cancel",reason:d});try{r.stdin.write(g+`
50
+ `)}catch{}},cancel(){r.kill("SIGTERM")},get stderr(){return a},get exitCode(){return i},get exitSignal(){return l},exited:c}}function Wr(o){let e=o.indexOf(": ");return e>0&&e<15?o.slice(e+2):o}function Kr(o){return o.map(e=>{let t=e.children?Kr(e.children):e.children;return e.status==="running"?{...e,status:"stopped",phase:void 0,children:t}:t!==e.children?{...e,children:t}:e})}function Fn(o,e){let[t,n]=(0,Ce.useState)(!1),[r,s]=(0,Ce.useState)([]),[a,i]=(0,Ce.useState)(null),[l,c]=(0,Ce.useState)(null),[f,d]=(0,Ce.useState)(null),[g,E]=(0,Ce.useState)(null),[h,y]=(0,Ce.useState)([]),_=(0,Ce.useRef)(null),w=(0,Ce.useRef)(null),I=(0,Ce.useRef)(0),z=(0,Ce.useRef)(!1),ce=(0,Ce.useCallback)((P,R)=>{_.current&&(_.current.cancel(),_.current=null),s([]),i(null),c(null),d(null),E(null),y([]),n(!0),w.current=null,I.current=0;let G=Un(P,R);_.current=G,Qe("runner",()=>G.cancel()),(async()=>{z.current=!1;for await(let p of G.events){if(z.current)break;switch(p.type){case"run_start":if(w.current&&!w.current.isSingleFlow){let b=I.current;I.current++,s(v=>v.map((C,$)=>$===b?{...C,status:"running"}:C.status==="running"&&!C.children?.some(U=>U.status==="running")?{...C,status:C.children?.some(U=>U.status==="failed")?"failed":"passed"}:C))}break;case"bifurcation":{let b=p.flows??[],v=p.count??b.length,C={flows:b,isSingleFlow:p.is_single_flow??v<=1};E(C),w.current=C,I.current=0,s(b.map(($,U)=>({index:U+1,objective:$??`Flow ${U+1}`,status:"pending"})));break}case"step_start":{e?.("STEP_START",`Step ${p.index} started`,{index:p.index,objective:p.objective,child_id:p.child_id});let b=p.index,v=p.objective??`Step ${b}`,C=p.child_id,$=w.current&&!w.current.isSingleFlow;if(C)s(U=>{let H=U.findIndex(de=>de.status==="running"||de.children?.some(_t=>_t.status==="running"));if(H===-1)return U;let W=[...U],Q={...W[H]},Re=[...Q.children??[]].map(de=>de.status==="running"?{...de,status:"stopped",phase:void 0}:de);return Re.push({index:b,objective:v,status:"running"}),Q.children=Re,W[H]=Q,W});else if($){let U=Math.max(0,I.current-1);s(H=>{let W=[...H];if(U>=W.length)return H;let Q={...W[U]},Re=[...Q.children??[]].map(de=>de.status==="running"?{...de,status:"stopped",phase:void 0}:de);return Re.push({index:b,objective:v,status:"running"}),Q.children=Re,Q.status="running",W[U]=Q,W})}else s(U=>{let H=Kr(U);return H.some(Q=>Q.index===b)?H.map(Q=>Q.index===b?{...Q,status:"running",objective:v}:Q):[...H,{index:b,objective:v,status:"running"}]});break}case"step_event":{e?.("STEP_EVENT",`Step ${p.index} ${p.event}`,{index:p.index,phase:p.event,action_type:p.action_type,detail:p.detail,child_id:p.child_id});let b=p.child_id,v=w.current&&!w.current.isSingleFlow;if(p.event==="cm_init"&&p.checkpoint_count!=null){y(C=>[...C,p.checkpoint_count]);break}if(b)s(C=>C.map($=>{if(!$.children)return $;let U=$.children.map(H=>{if(H.index!==p.index)return H;let W={phase:p.event};return p.event==="reasoning"&&p.detail&&p.detail!=="reasoning"&&(W.objective=p.detail),p.action_type&&(W.actionType=p.action_type),{...H,...W}});return{...$,children:U}}));else if(v){let C=Math.max(0,I.current-1);s($=>{let U=[...$];if(C>=U.length)return $;let H={...U[C]},W=[...H.children??[]];if(!W.some(le=>le.index===p.index))W.push({index:p.index,objective:`Step ${p.index}`,status:"running",phase:p.event,actionType:p.action_type});else for(let le=0;le<W.length;le++){if(W[le].index!==p.index)continue;let Re={phase:p.event};p.event==="reasoning"&&p.detail&&p.detail!=="reasoning"&&(Re.objective=p.detail),p.action_type&&(Re.actionType=p.action_type),W[le]={...W[le],...Re}}return H.children=W,U[C]=H,U})}else s(C=>C.some(U=>U.index===p.index)?C.map(U=>{if(U.index!==p.index)return U;let H={phase:p.event};return p.event==="reasoning"&&p.detail&&p.detail!=="reasoning"&&(H.objective=p.detail),p.action_type&&(H.actionType=p.action_type),{...U,...H}}):[...Kr(C),{index:p.index,objective:`Step ${p.index}`,status:"running",phase:p.event,actionType:p.action_type}]);break}case"step_end":{e?.("STEP_END",`Step ${p.index} ${p.status}`,{index:p.index,status:p.status,duration:p.duration,summary:p.summary,child_id:p.child_id});let b=p.child_id,v=w.current&&!w.current.isSingleFlow;if(b)s(C=>C.map($=>{if(!$.children)return $;let U=$.children.map(H=>H.index===p.index?{...H,status:p.status,duration:p.duration,phase:void 0,objective:H.objective.startsWith("Step ")?Wr(p.summary||H.objective):H.objective}:H);return{...$,children:U}}));else if(v){let C=Math.max(0,I.current-1);s($=>{let U=[...$];if(C>=U.length)return $;let H={...U[C]},W=(H.children??[]).map(Q=>Q.index===p.index?{...Q,status:p.status,duration:p.duration,phase:void 0,objective:Q.objective.startsWith("Step ")?Wr(p.summary||Q.objective):Q.objective}:Q);return H.children=W,U[C]=H,U})}else s(C=>C.map($=>$.index===p.index?{...$,status:p.status,duration:p.duration,phase:void 0,objective:$.objective.startsWith("Step ")?Wr(p.summary||$.objective):$.objective}:$));if(!p.child_id){let $=w.current&&!w.current.isSingleFlow?Math.max(0,I.current-1):0;o?.(p.index,$)}break}case"child_agent_start":{let b=p.objective??"";s(v=>v.map(C=>C.status==="running"?{...C,objective:b,phase:`child: ${b.slice(0,50)}`}:C));break}case"child_agent_end":s(b=>b.map(v=>v.phase?.startsWith("child:")?{...v,phase:`child ${p.success?"done":"failed"}`}:v));break;case"ask_user":i(p.question??"");break;case"run_end":s(b=>b.map(v=>v.status==="running"?{...v,status:p.status,phase:void 0}:v)),c(p),n(!1),Je("runner","Run completed"),_.current=null;break;case"error":d(p.message??"Runner error"),s(b=>b.map(v=>v.status==="running"?{...v,status:"failed",phase:void 0}:v)),n(!1),Je("runner","Runner error"),_.current=null;break}}let Z=_.current;if(Z){let{code:p,signal:b}=await Z.exited,v=Z.stderr,C=[];p!==null&&p!==0&&C.push(`Runner exited with code ${p}`),b&&C.push(`Runner killed by signal ${b}`),v&&C.push(v),C.length>0&&d(C.join(`
51
+ `))}n(!1),Je("runner","Event stream ended"),_.current=null})().catch(Z=>{let p=_.current,b=[`Runner event loop error: ${Z}`];p&&(p.exitCode!==null&&p.exitCode!==0&&b.push(`Exit code: ${p.exitCode}`),p.exitSignal&&b.push(`Signal: ${p.exitSignal}`),p.stderr&&b.push(p.stderr)),d(b.join(`
52
+ `)),n(!1),Je("runner","Event loop error"),_.current=null})},[o,e]),Y=(0,Ce.useCallback)(P=>{_.current?.sendUserResponse(P),i(null)},[]),B=(0,Ce.useCallback)(()=>{let P=_.current;P&&(P.sendCancel("user"),n(!1),i(null),setTimeout(()=>{_.current===P&&(Je("runner","User cancelled run"),_.current=null)},5e3))},[]);return(0,Ce.useEffect)(()=>()=>{z.current=!0,Je("runner","Component unmounted"),_.current=null},[]),{isRunning:t,steps:r,askingUser:a,lastRunEnd:l,runError:f,bifurcationInfo:g,cmInitCounts:h,startRun:ce,sendAnswer:Y,cancelRun:B}}function ln(o){let e=o.flatMap(s=>[s,...s.children??[]]),t=e.filter(s=>s.status==="passed").length,n=e.filter(s=>s.status==="failed").length,r=e.filter(s=>s.status==="passed"||s.status==="failed").length;return{passed:t,failed:n,total:r}}var rl=null;function Ms(o){rl=o}import{readFileSync as ol,existsSync as sl}from"fs";function Vt(o){if(!sl(o))return null;try{return ol(o,"utf-8").trim()||null}catch{return null}}import{join as Ze}from"path";var ze=N(ke(),1);var He=N(re(),1);function Hs({message:o,code:e,remediation:t,docsUrl:n}){return(0,He.jsx)(vn,{title:"Error",variant:"error",children:(0,He.jsxs)(x,{flexDirection:"column",paddingY:1,children:[(0,He.jsxs)(u,{color:m.red,bold:!0,children:[" \u2717 ",o]}),e&&(0,He.jsxs)(x,{marginTop:0,marginLeft:5,children:[(0,He.jsx)(u,{color:m.muted,children:"Code: "}),(0,He.jsx)(u,{color:m.dimmed,children:e})]}),t&&(0,He.jsxs)(x,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,He.jsx)(u,{color:m.green,bold:!0,children:"Fix:"}),(0,He.jsxs)(u,{color:m.cyan,children:["$ ",t]})]}),n&&(0,He.jsxs)(x,{marginTop:1,marginLeft:5,children:[(0,He.jsx)(u,{color:m.muted,children:"Docs: "}),(0,He.jsx)(u,{color:m.cyan,underline:!0,children:n})]})]})})}var we=N(re(),1);function Ws({data:o,color:e}){let t=o.status==="passed"?"passed":"failed";return(0,we.jsx)(en,{status:t,summary:o.summary??"",duration:o.duration,steps:o.stepsTotal,stepsPassed:o.stepsPassed,stepsFailed:o.stepsFailed,reason:o.reason,creditsConsumed:o.creditsConsumed})}function Ks({config:o,spawnOpts:e,cancelRef:t,banner:n,onComplete:r,onStepEnd:s}){let{exit:a}=gn(),i=Fn(s),l=(0,ze.useRef)(!1),c=(0,ze.useRef)(!1),[f,d]=(0,ze.useState)("");(0,ze.useEffect)(()=>{l.current||(l.current=!0,i.startRun(o,e))},[o,e,i]),(0,ze.useEffect)(()=>{t&&(t.current=()=>i.cancelRun())},[t,i]);let g=(0,ze.useRef)(0);$e((y,_)=>{_.ctrl&&y==="c"&&(i.isRunning?(g.current++,g.current>=2?a():i.cancelRun()):a())}),$e((y,_)=>{i.askingUser&&(_.return?(i.sendAnswer(f),d("")):_.backspace||_.delete?d(w=>w.slice(0,-1)):y&&!_.ctrl&&!_.meta&&d(w=>w+y))},{isActive:!!i.askingUser}),(0,ze.useEffect)(()=>{if(!i.isRunning&&i.lastRunEnd&&!c.current){c.current=!0;let{passed:y,failed:_,total:w}=ln(i.steps),I=i.bifurcationInfo;r({lastRunEnd:i.lastRunEnd,stepsPassed:y,stepsFailed:_,stepsTotal:w,hadError:!1,bifurcationFlows:I&&!I.isSingleFlow?I.flows:null}),a()}},[i.isRunning,i.lastRunEnd,i.steps,r,a]),(0,ze.useEffect)(()=>{i.runError&&!i.isRunning&&!c.current&&(c.current=!0,r({lastRunEnd:null,stepsPassed:0,stepsFailed:0,stepsTotal:0,hadError:!0,bifurcationFlows:null}),a())},[i.runError,i.isRunning,r,a]);let E=i.lastRunEnd?(()=>{let{passed:y,failed:_,total:w}=ln(i.steps);return{status:i.lastRunEnd.status,duration:i.lastRunEnd.duration??0,summary:i.lastRunEnd.summary??"",stepsPassed:y,stepsFailed:_,stepsTotal:w,reason:i.lastRunEnd.reason,finalState:i.lastRunEnd.final_state,creditsConsumed:i.lastRunEnd.credits_consumed}})():null,h=(0,ze.useMemo)(()=>n?[{key:"banner",...n}]:[],[n]);return(0,we.jsxs)(x,{flexDirection:"column",children:[(0,we.jsx)(jt,{items:h,children:y=>(0,we.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,we.jsxs)(x,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,we.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,we.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,we.jsx)(u,{color:m.cyan,children:y.model}),(0,we.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,we.jsx)(u,{color:m.dimmed,children:y.auth})]}),y.status?.map((_,w)=>(0,we.jsx)(u,{color:m.dimmed,children:_},w))]},y.key)}),(()=>{let y=kn({isRunning:i.isRunning,bifurcationInfo:i.bifurcationInfo,steps:i.steps,cmInitCounts:i.cmInitCounts});return y?(0,we.jsx)(Rn,{label:y.label,hasBifurcation:y.hasBifurcation}):null})(),i.steps.length>0&&(0,we.jsx)(En,{steps:i.steps,bifurcated:!!i.bifurcationInfo&&!i.bifurcationInfo.isSingleFlow,flows:i.bifurcationInfo?.flows,cmInitCounts:i.cmInitCounts,staticSteps:!0}),i.askingUser&&(0,we.jsxs)(x,{flexDirection:"column",marginTop:1,children:[(0,we.jsxs)(u,{color:m.yellow,children:['Agent is asking: "',i.askingUser,'"']}),(0,we.jsxs)(u,{children:["> ",f,"\u2588"]})]}),i.runError&&(0,we.jsx)(Hs,{message:i.runError,code:"RUNNER_ERROR"}),E&&i.lastRunEnd&&(0,we.jsx)(Tn,{steps:i.steps,bifurcationInfo:i.bifurcationInfo,perFlowMetadata:i.lastRunEnd.per_flow_metadata??[]}),E&&(0,we.jsx)(en,{status:E.status==="passed"?"passed":"failed",summary:E.summary??"",duration:E.duration,steps:E.stepsTotal,stepsPassed:E.stepsPassed,stepsFailed:E.stepsFailed,reason:E.reason,creditsConsumed:E.creditsConsumed})]})}function qs(o,e,t){return`${o}/projects/${e}/test-cases/${t}`}function Nt(o,e,t,n){return`${qs(o,e,t)}/dashboard/share/${n}?type=summary&agentView=true&fqdn=summary-page`}function Vn(o,e,t){return`${qs(o,e,t)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{readFileSync as zs,readdirSync as il,existsSync as cn}from"fs";import{join as Mt}from"path";function Nn(o,e,t,n,r){try{let s=Mt(o,"runs",String(e),"run-test");if(!cn(s)){r("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:t,reason:"runsDir_not_found",path:s});return}let a=s;if(cn(Mt(s,"screenshots")))a=s;else{let h=il(s).filter(y=>cn(Mt(s,y,"screenshots")));if(h.length===0){r("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:t,reason:"no_screenshots_dir"});return}a=Mt(s,h[0])}let i=Mt(a,"screenshots",`step_${String(t).padStart(3,"0")}.png`);if(!cn(i)){r("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:t,reason:"screenshot_not_found",path:i});return}let l=Mt(a,"actions.ndjson");if(!cn(l)){r("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:t,reason:"ndjson_not_found"});return}let c=zs(l,"utf-8").trim().split(`
53
+ `),f=c[c.length-1];if(!f){r("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:t,reason:"ndjson_empty"});return}let g=JSON.parse(f).action_id;if(!g){r("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:t,reason:"no_action_id"});return}let E=zs(i);n.enqueue(g,E),r("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:t,action_id:g,size:E.length})}catch(s){r("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:t,error:s instanceof Error?s.message:String(s)})}}import al from"sharp";var Ht=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;log;constructor(e,t=3,n){this.sas=e,this.maxWorkers=t,this.log=n}updateSas(e){this.sas=e}enqueue(e,t){this.queue.push({operationId:e,buffer:t}),this.pump()}async drain(e=3e4){if(!(this.queue.length===0&&this.activeCount===0))return new Promise(t=>{this.drainResolvers.push(t),setTimeout(()=>{t()},e)})}pump(){for(;this.activeCount<this.maxWorkers&&this.queue.length>0;){let e=this.queue.shift();this.activeCount++,this.processJob(e).finally(()=>{if(this.activeCount--,this.pump(),this.queue.length===0&&this.activeCount===0){for(let t of this.drainResolvers)t();this.drainResolvers=[]}})}}async processJob(e){let t,n="image/webp";try{let i=await al(e.buffer).webp({quality:80}).toBuffer();t=new Uint8Array(i)}catch(i){t=new Uint8Array(e.buffer),n="image/png",this.log?.("warn","SCREENSHOT_CONVERT_FAILED","WebP conversion failed, using PNG",{operation_id:e.operationId,error:i instanceof Error?i.message:String(i)})}let r=n==="image/webp"?"webp":"png",s=`test_screenshots/untagged_screenshot/${e.operationId}.${r}`,a=`${this.sas.base_url}/${this.sas.container}/${s}?${this.sas.sas_token}`;for(let i=0;i<=this.maxRetries;i++)try{let l=await fetch(a,{method:"PUT",headers:{"Content-Type":n,"x-ms-blob-type":"BlockBlob"},body:t});if(l.ok)return;if(i<this.maxRetries){await this.backoff(i);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed after retries",{operation_id:e.operationId,status:l.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:e.operationId,error:"network",attempts:this.maxRetries+1})}}backoff(e){let t=e===0?1e3:3e3;return new Promise(n=>setTimeout(n,t))}isNearExpiry(){if(!this.sas.expiry)return!1;let e=new Date(this.sas.expiry).getTime();return Date.now()>e-5*6e4}};import{readdirSync as ll,readFileSync as Js,existsSync as Xs}from"fs";import{join as cl}from"path";function Gs(o,e){if(!Xs(o))return{};let t={},n;try{n=ll(o).filter(r=>r.endsWith(".json")).sort()}catch{return{}}for(let r of n)try{let s=Js(cl(o,r),"utf-8"),a=JSON.parse(s);if(a&&typeof a=="object"){for(let[i,l]of Object.entries(a))if(l&&typeof l=="object"&&"value"in l){let c=l;t[i]={value:c.value,secret:c.secret??!1,syntax:c.syntax??`{{${i}}}`}}}}catch{e?e("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:r}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${r}
54
+ `)}return t}function Ys(o){if(!Xs(o))throw new Error(`Variables file not found: ${o}`);let e=Js(o,"utf-8"),t=JSON.parse(e),n={};if(t&&typeof t=="object"){for(let[r,s]of Object.entries(t))if(s&&typeof s=="object"&&"value"in s){let a=s;n[r]={value:a.value,secret:a.secret??!1,syntax:a.syntax??`{{${r}}}`}}}return n}function Qs(o){let e;try{e=JSON.parse(o)}catch{throw new Error("Invalid --variables JSON")}let t={};if(e&&typeof e=="object"){for(let[n,r]of Object.entries(e))if(r&&typeof r=="object"&&"value"in r){let s=r;t[n]={value:s.value,secret:s.secret??!1,syntax:s.syntax??`{{${n}}}`}}}return t}function Zs(o,e,t){let n=Gs(o,t),r=Gs(e,t);return{...n,...r}}function ei(o,e){let t={},n={},r=e;for(let[s,a]of Object.entries(o))if(a.secret){let i=`secrets.user.${s}`;t[i]={value:a.value,secret:!0,syntax:`{{secrets.user.${s}}}`,type:"secret"},n[s]=i,r=r.replaceAll(`{{${s}}}`,`{{secrets.user.${s}}}`)}else{let i=`global.${s}`;t[i]={value:a.value,secret:!1,syntax:`{{global.${s}}}`,type:"global"},n[s]=i,r=r.replaceAll(`{{${s}}}`,`{{global.${s}}}`)}return{variables:t,objective:r,keyMap:n}}var Mn=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=Ro(e.username,e.accessKey),n=await fetch(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:t,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:e.secretKey,secretValue:e.secretValue,orgId:e.orgId,username:e.username,scope:"user",type:"user",accessKey:e.accessKey})});if(!n.ok)throw new Error(`Push secret failed: ${n.status} ${await n.text()}`)}static extractVariableKeys(e){let t=e.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),n=new Set;for(let r of t)n.add(r[1]);return[...n]}};var Hn=class extends ko{constructor(e,t,n){super(e,{username:t,accessKey:n})}async upsertVariable(e){let t=e.environmentId??0,n=await fetch(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:e.name,value:String(e.value),type:"variable",value_type:"string",is_persist:e.isPersist??!1,environment_id:t})});if(n.ok)return{id:(await n.json()).id??0};if(n.status!==409&&n.status!==422)return{id:0};if(!(await fetch(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(e.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(e.value),value_type:"string",type:"variable",environment_id:t})})).ok)return{id:0};let s=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${t}`,{method:"GET",headers:this.headers()});return s.ok?{id:(await s.json()).data?.id??0}:{id:0}}};function Wn(o){let e=Zs(o.globalDir,o.localDir,o.onLoadError),t=o.file?Ys(o.file):{},n=o.inline?Qs(o.inline):{},r={...e,...t,...n},s=Object.keys(r).length>0,{variables:a,objective:i}=s?ei(r,o.objective):{variables:{},objective:o.objective},l=Object.entries(r).filter(([,f])=>f.secret),c=Object.entries(r).filter(([,f])=>!f.secret);return{raw:r,auteur:a,auteurObjective:i,secretEntries:l,nonSecretEntries:c}}async function Kn(o){if(o.localMode)return{};let e=ie(o.env);if(o.variables.secretEntries.length>0){let n=new Mn(e.secretsBaseUrl);for(let[r,s]of o.variables.secretEntries)n.pushSecret({secretKey:r,secretValue:s.value,username:o.auth.username,accessKey:o.auth.access_key,orgId:o.orgId}).then(()=>o.log("info","SECRET_PUSH_OK","Secret pushed",{key:r})).catch(a=>o.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:r,error:String(a)}))}let t={};if(o.variables.nonSecretEntries.length>0){let n=new Hn(e.tmsBaseUrl,o.auth.username,o.auth.access_key);for(let[r,s]of o.variables.nonSecretEntries)try{let a=await n.upsertVariable({name:r,value:s.value});t[r]=a.id,o.log("info","VAR_PUSH_OK","Variable pushed",{name:r,id:a.id})}catch(a){o.log("error","VAR_PUSH_FAILED","Variable push failed",{name:r,error:String(a)})}}return t}function qn(o){let e={objective:o.objective,model:o.model,width:o.windowSize.width,height:o.windowSize.height,session_id:o.sessionId,run_index:o.runIndex,stream:!0,max_steps:o.maxSteps??30,headless:o.headless??!1};return o.url&&(e.url=o.url),o.chrome.wsEndpoint?e.ws_endpoint=o.chrome.wsEndpoint:o.chrome.cdpEndpoint&&(e.cdp_endpoint=o.chrome.cdpEndpoint),o.auth.basicAuth?(e.username=o.auth.basicAuth.username,e.access_key=o.auth.basicAuth.access_key):o.auth.token&&(e.auth={type:"bearer",token:o.auth.token}),o.disableAskUser&&(e.disable_ask_user=!0),o.enableTaskSkills&&(e.enable_task_skills=!0),o.variables&&Object.keys(o.variables).length>0&&(e.variables=o.variables),o.globalContext&&(e.global_context=o.globalContext),o.localContext&&(e.local_context=o.localContext),o.sessionContext&&(e.session_context=o.sessionContext),e}function un(o){let e=ie(o.env),{session:t,auth:n}=o,r=n.basicAuth?{username:n.basicAuth.username,accessKey:n.basicAuth.access_key}:n.token,s=n.resolvedCreds?.username??n.basicAuth?.username??"",a=n.resolvedCreds?.access_key??n.basicAuth?.access_key??"",i=n.resolvedCreds?.org_id??0,l=n.resolvedCreds?.user_id??0,c=[];for(let h of Object.keys(t.auteurVariables))h.startsWith("secrets.user.")&&c.push({key_name:h.replace("secrets.user.",""),scope:"user"});let d=t.getContext().prior_runs.map(h=>h.status),g=t.auteurVariables,E=Object.keys(g).length>0;return{controllerBaseUrl:e.controllerBaseUrl,tmsBaseUrl:e.tmsBaseUrl,auth:r,authResolver:n.resolver,sessionId:t.sessionId,sessionDir:t.sessionDir,testId:t.testId,commitId:t.sessionId,projectId:o.projectId,folderId:o.folderId,firstObjective:t.firstObjective??"KaneAI Test",firstUrl:t.firstUrl??"",runDirs:t.getRunDirs(),runObjectives:t.getRunObjectives(),runMetadata:t.getRunMetadata(),startedAt:t.startedAt,endedAt:new Date().toISOString(),totalSteps:o.totalSteps,totalDuration:o.totalDuration,runStatuses:d,orgId:i,userId:l,tmsUsername:s,tmsAccessKey:a,screenshotBaseUrl:t.screenshotBaseUrl,shareApiBaseUrl:e.shareApiBaseUrl,variables:E?g:void 0,variableIds:o.variableIds,secrets:c,codeExport:o.codeExport,onProgress:o.onProgress,log:o.log}}async function zn(o){try{let t=await new et(o.tmsBaseUrl,o.auth.username,o.auth.access_key).createAtmTest({objective:o.objective.slice(0,100),creation_mode:"KANECLI",playground_disabled:o.hasCustomProfile,testURL:o.url,project_id:o.projectId,folder_id:o.folderId,authoring_version:4});return o.log("info","ATM_CREATE_OK","Test created",{test_id:t}),t}catch(e){return o.log("error","ATM_CREATE_FAILED","Test creation failed",{error:e instanceof Error?e.message:String(e)}),null}}async function Gn(o){await new et(o.tmsBaseUrl,o.username,o.accessKey).submitFeedback({instruction_id:"",test_id:o.testId,feedback_type:o.feedbackType,mode:o.mode??"human",...o.details?{details:o.details}:{}}),o.log("info","FEEDBACK_SUBMITTED","Feedback submitted",{type:o.feedbackType})}var M=N(re(),1);function ti({localMode:o=!1,codeExport:e=!1,updatePromise:t}={}){gn();let[n]=(0,j.useState)(()=>new Ft),[r]=(0,j.useState)(()=>new Ke),s=(0,j.useRef)(0),a=(0,j.useCallback)(()=>`msg-${++s.current}`,[]),[i,l]=(0,j.useState)(!1),[c,f]=(0,j.useState)(null),[d,g]=(0,j.useState)(!1),[E,h]=(0,j.useState)(null),[y,_]=(0,j.useState)(!1),[w,I]=(0,j.useState)(0),[z,ce]=(0,j.useState)(!1),[Y,B]=(0,j.useState)(null),[P,R]=(0,j.useState)(null),G=(0,j.useRef)(null),[Z,p]=(0,j.useState)(null),[b,v]=(0,j.useState)(fr()),[C,$]=(0,j.useState)(null),[U,H]=(0,j.useState)(!1),W=(0,j.useRef)(null),Q=(0,j.useRef)(0),le=(0,j.useRef)(""),Re=(0,j.useRef)(null),de=(0,j.useRef)(null),_t=(0,j.useRef)({}),ct=(0,j.useRef)(0),[Dt,V]=(0,j.useState)([]),ee=(0,j.useCallback)(S=>{let A=`s-${++ct.current}`;V(k=>[...k,{id:A,content:S}])},[]),[se,pe]=(0,j.useState)(()=>new Ke().load().setup_complete),[Ae,We]=(0,j.useState)("menu"),[oe,ge]=(0,j.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),me=Vo(),T=Is(),Fe=Vs(),nt=(0,j.useCallback)((S,A)=>{let k=W.current;if(!k)return;let O=Q.current+A;Nn(n.sessionDir,O,S,k,(K,q,X,ae)=>n.log(K,q,X,ae))},[n]),Bt=(0,j.useCallback)((S,A,k)=>{n.logStep(S,A,k)},[n]),L=Fn(nt,Bt),[J,ut]=(0,j.useState)(()=>r.load()),[,Qn]=(0,j.useState)(0),yt=(0,j.useCallback)(()=>Qn(S=>S+1),[]),[be,St]=(0,j.useState)(null),mn=T.creds.getActiveProfile(),_e=T.creds.getDefaultEnv(),qt=(0,j.useCallback)((S,A)=>{let k=S?T.creds.loadProfileConfig(S,A):null;r.save({project_id:k?.project_id??null,project_name:k?.project_name??null,folder_id:k?.folder_id??null,folder_name:k?.folder_name??null}),ut(r.load())},[T.creds,r]);(0,j.useEffect)(()=>{y||(n.start({model:J.model,environment:_e,profile:mn}),_(!0))},[n,y,J.model,_e,mn]);let ao=(0,j.useCallback)(async S=>{let A=ie(S),k=T.getBasicAuth(),O=k?{username:k.username,accessKey:k.access_key}:await T.getToken().then(q=>q??"");if(!O)return;let K=new Yt(A.controllerBaseUrl,O);try{let q=await K.getScreenshotSas();n.setScreenshotSas(q),W.current=new Ht(q,3,(X,ae,ue,Ie)=>n.log(X,ae,ue,Ie)),n.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched")}catch(q){n.log("warn","SCREENSHOT_SAS_FAILED","Screenshot SAS fetch failed",{error:q instanceof Error?q.message:String(q)})}},[T,n]),zt=(0,j.useCallback)(async S=>{let A=S??T.creds.getDefaultEnv();$(null),W.current=null;let O=await T.initResolver(A,(K,q,X,ae)=>n.log(K,q,X,ae)).resolve(!0).catch(()=>null);return $(O),O&&(n.log("info","AUTH_RESET_OK","Auth reset resolved",{username:O.username,org_id:O.org_id,env:A}),await ao(A)),O},[T,n,ao]),lo=(0,j.useRef)(!1);(0,j.useEffect)(()=>{!i||lo.current||!y||(lo.current=!0,zt().then(S=>{if(S){if(n.log("info","BOOT_RESOLVE_OK","Boot auth resolved",{username:S.username,org_id:S.org_id}),!n.hasRemoteLogger){let A=Po({sessionId:n.sessionId,identity:{org_id:String(S.org_id??""),user_id:String(S.user_id??""),machine_id:Oo()},environment:_e,getToken:async()=>T.getToken()});n.setRemoteLogger(A),A.start(),Qe("remote-logger",()=>A.shutdownSync()),jn(A)}}else n.log("warn","BOOT_RESOLVE_FAILED","Boot auth failed \u2014 non-controller APIs may fail")}).catch(S=>{n.log("error","BOOT_RESOLVE_ERROR","Boot auth error",{error:S instanceof Error?S.message:String(S)})}))},[i,y,zt,n]);let Et=(0,j.useCallback)(async()=>{if(C)return n.log("info","TMS_CREDS_CACHED","Using cached TMS credentials",{username:C.username,org_id:C.org_id}),C;let S=await T.resolveBasicAuth();return S?(n.log("info","TMS_CREDS_OK","TMS credentials resolved",{username:S.username,org_id:S.org_id,user_id:S.user_id}),$(S)):n.log("warn","TMS_CREDS_FAILED","No TMS credentials resolved"),S},[T,C,n]),co=(0,j.useCallback)(async()=>{let S=await Et();if(!S)return n.log("warn","PROJECT_FAILED","No TMS credentials for project resolution"),null;let A=ie(_e),k=new et(A.tmsBaseUrl,S.username,S.access_key),O=T.creds.getActiveProfile(),K=T.creds.getDefaultEnv(),q=O?T.creds.loadProfileConfig(O,K):null,X=q?.project_id??J.project_id;if(X)n.log("info","PROJECT_CACHED","Using cached project",{project_id:X});else{n.log("info","PROJECT_FETCH","No project_id in config, fetching from TMS");try{n.log("info","PROJECT_LIST","Listing projects from TMS",{url:`${A.tmsBaseUrl}/v1/projects`});let ue=await k.listProjects((Ve,Gt,nr,rr)=>n.log(Ve,Gt,nr,rr));n.log("info","PROJECT_LIST_OK","Projects listed",{count:ue.length});let Ie=ue.find(Ve=>Ve.name==="KaneAI Generated");if(Ie)X=Ie.project_id,n.log("info","PROJECT_SELECTED","Using KaneAI Generated project",{project_id:X});else if(ue.length>0){let Ve=ue[0];X=Ve.project_id,n.log("info","PROJECT_SELECTED","Using first project",{name:Ve.name,project_id:X})}X&&r.set("project_id",X)}catch(ue){return n.log("error","PROJECT_LIST_FAILED","Project listing failed",{error:String(ue)}),null}}if(!X)return n.log("warn","PROJECT_NONE","No projects found"),null;let ae=q?.folder_id??J.folder_id;if(ae)n.log("info","FOLDER_CACHED","Using cached folder",{folder_id:ae});else try{n.log("info","FOLDER_FETCH","Fetching default folder",{project_id:X}),ae=await k.getDefaultFolder(X),n.log("info","FOLDER_OK","Default folder resolved",{folder_id:ae}),ae&&r.set("folder_id",ae)}catch(ue){return n.log("error","FOLDER_FAILED","Default folder fetch failed",{error:String(ue)}),null}return{projectId:X,folderId:ae??""}},[J.project_id,J.folder_id,Et,_e,r,n]),fe=(0,j.useCallback)(S=>{let A=a(),k={...S,id:A};ee((0,M.jsx)(Go,{entry:k}))},[a,ee]),uo=(0,j.useCallback)(async(S,A)=>{let k=n.nextRunIndex();Q.current=k,le.current=S,n.logRunStart(k,S,A??""),n.setFirstRun(S,A??"");let O=T.getResolvedBasicAuth(),K=O,q=null;if(!K&&(q=await T.getToken(),!q)){fe({type:"error",text:"Not authenticated. Run /login first."});return}let X={basicAuth:O??null,token:q,resolver:T.getResolver(),resolvedCreds:null};if(Re.current=X,k===0&&!o){n.log("info","ATM_CREATE_START","Creating test via ATM endpoint",{run_index:0});let Ne=await co(),Jt=ie(_e),Ct=K?{username:K.username,access_key:K.access_key}:await Et();if(Ct){let $t=await zn({tmsBaseUrl:Jt.tmsBaseUrl,auth:{username:Ct.username,access_key:Ct.access_key},objective:S,url:A??J.default_url??"",projectId:Ne?.projectId??J.project_id??"",folderId:Ne?.folderId??J.folder_id??"",hasCustomProfile:!!J.chrome_profile_path,log:(Ti,Ai,Ii,Pi)=>n.log(Ti,Ai,Ii,Pi)});$t&&(n.setTestId($t),Ne?.projectId&&n.setProjectId(Ne.projectId))}}let ae=null;if(oe.useCft)fe({type:"info",text:"CfT mode: Playwright will manage browser"});else if(oe.wsEndpoint)fe({type:"info",text:`WS endpoint: ${oe.wsEndpoint.slice(0,60)}...`});else if(oe.cdpEndpoint)fe({type:"info",text:`CDP endpoint: ${oe.cdpEndpoint}`});else{fe({type:"info",text:"Starting Chrome..."});try{ae=await Fe.ensureChrome(A)}catch(Ne){fe({type:"error",text:`Chrome failed: ${Ne instanceof Error?Ne.message:String(Ne)}`});return}n.logChromeLaunch(ae.port,ae.cdpEndpoint),fe({type:"info",text:`Chrome ready (port ${ae.port})`})}let ue=Wn({objective:S,globalDir:Ze(ve,"variables"),localDir:Ze(process.cwd(),".testmuai","variables")});n.setAuteurVariables(ue.auteur),de.current=ue;let Ie=K&&!o?await Kn({variables:ue,auth:K,orgId:String((await Et())?.org_id??""),env:_e,localMode:o,log:(Ne,Jt,Ct,$t)=>n.log(Ne,Jt,Ct,$t)}):{};_t.current=Ie;let Ve=Vt(Ze(ve,"global-memory.md")),Gt=Vt(Ze(process.cwd(),".testmuai","context.md")),nr=ae?{cdpEndpoint:ae.cdpEndpoint,instance:ae,tempDir:null}:oe.wsEndpoint?{wsEndpoint:oe.wsEndpoint,instance:null,tempDir:null}:oe.cdpEndpoint?{cdpEndpoint:oe.cdpEndpoint,instance:null,tempDir:null}:{instance:null,tempDir:null},rr=qn({objective:ue.auteurObjective,url:A,model:J.model,chrome:nr,auth:X,sessionId:n.sessionId,runIndex:k,windowSize:J.window_size,maxSteps:oe.maxSteps,headless:oe.headless,variables:Object.keys(ue.auteur).length>0?ue.auteur:void 0,globalContext:Ve??void 0,localContext:Gt??void 0,sessionContext:n.getContext()});A&&h(A),B(null),L.startRun(rr,{environment:_e,log:(Ne,Jt,Ct,$t)=>n.log(Ne,Jt,Ct,$t)}),I(Ne=>Ne+1)},[T,Fe,r,J,n,_e,L,fe,oe,co,Et]);(0,j.useEffect)(()=>{if(L.bifurcationInfo){let{flows:S,isSingleFlow:A}=L.bifurcationInfo;if(A&&S.length===1&&S[0])n.log("info","OBJECTIVE_REWRITTEN","Objective rewritten",{objective:S[0]}),fe({type:"info",text:`Objective: ${S[0]}`});else if(!A&&S.length>1){let k=[`Bifurcated into ${S.length} flows:`];S.forEach((O,K)=>k.push(` ${K+1}. ${O}`)),n.log("info","BIFURCATION","Objective bifurcated into flows",{flow_count:S.length}),fe({type:"info",text:k.join(`
55
+ `)})}}},[L.bifurcationInfo,n,fe]);let fo=j.default.useRef(null),mo=j.default.useRef(0),po=j.default.useRef(0);(0,j.useEffect)(()=>{if(L.lastRunEnd&&L.lastRunEnd!==fo.current){fo.current=L.lastRunEnd;let{status:S,duration:A,summary:k,reason:O,context:K}=L.lastRunEnd,{passed:q,failed:X,total:ae}=ln(L.steps);mo.current+=ae,po.current+=A??0,B({status:S,duration:A??0,summary:k??"",stepsPassed:q,stepsFailed:X,stepsTotal:ae,reason:O,finalState:L.lastRunEnd?.final_state,creditsConsumed:L.lastRunEnd?.credits_consumed}),n.logRunEnd(Q.current,S,A,k);let ue=L.bifurcationInfo,Ie=ue&&!ue.isSingleFlow?ue.flows:null,Ve=rn(L.lastRunEnd,Q.current,Ie),Gt=on(L.lastRunEnd,le.current,Q.current,Ve);n.addRunResult(Gt,L.lastRunEnd?.total_runs)}},[L.lastRunEnd,n,fe]);let Zn=(0,j.useRef)(null);(0,j.useEffect)(()=>{L.askingUser&&L.askingUser!==Zn.current&&(Zn.current=L.askingUser,ee((0,M.jsxs)(x,{children:[(0,M.jsx)(u,{color:"#ff9500",children:"? "}),(0,M.jsx)(u,{color:"#ff9500",children:"Agent asks: "}),(0,M.jsx)(u,{children:L.askingUser})]}))),L.askingUser||(Zn.current=null)},[L.askingUser,ee]);let ho=(0,j.useRef)(null);(0,j.useEffect)(()=>{if(Y&&!L.isRunning&&L.lastRunEnd){if(ho.current===L.lastRunEnd)return;ho.current=L.lastRunEnd;let S=L.bifurcationInfo&&!L.bifurcationInfo.isSingleFlow,A=L.lastRunEnd?.per_flow_metadata;S&&A&&A.length>1&&ee((0,M.jsx)(Tn,{steps:L.steps,bifurcationInfo:L.bifurcationInfo,perFlowMetadata:A})),ee((0,M.jsx)(Ws,{data:Y,color:Y.status==="passed"?"#4ade80":"#ef4444"})),B(null)}},[Y,L.isRunning,L.lastRunEnd,ee]),(0,j.useEffect)(()=>{if(L.runError&&!L.isRunning){let S=L.runError.trim();n.log("error","RUNNER_ERROR","Runner error occurred",{error:S}),n.escalateRun(n.nextRunIndex()-1);let k=S.split(`
42
56
  `).slice(-8).join(`
43
- `);re({type:"error",text:`Runner error:
44
- ${R}`})}},[B.runError,B.isRunning,re,n]);let Rt=(0,U.useCallback)(async()=>{n.log("EXIT_UPLOAD starting exit upload pipeline"),k(Zn()),X({status:"uploading"});let _=ce(E),T=$.getResolvedBasicAuth(),R;if(T)n.log("EXIT_UPLOAD using resolved basic auth for controller"),R={username:T.username,accessKey:T.access_key};else{let Ce=await $.getToken();if(!Ce)return n.log("EXIT_UPLOAD aborted: no auth available"),null;R=Ce}let O=y??await me();if(!O)return n.log("EXIT_UPLOAD aborted: no TMS credentials"),n.setUploadStatus("failed","Could not get TMS credentials"),null;let V=n.generateCommitId();n.log(`EXIT_UPLOAD config: testId=${n.testId} commitId=${V} projectId=${K.project_id} sessionDir=${n.sessionDir} runDirs=${JSON.stringify(n.getRunDirs())}`);let z=T?.username??O.username,se=T?.access_key??O.access_key,Ue=n.getContext().prior_runs,Se=n.getRunObjectives(),Pe=[];for(let[Ce]of Object.entries(n.auteurVariables))if(Ce.startsWith("secrets.user.")){let xe=Ce.replace("secrets.user.","");Pe.push({key_name:xe,scope:"user"})}F.current&&(n.log("SCREENSHOT_UPLOAD draining queue before pipeline"),await F.current.drain(),n.log("SCREENSHOT_UPLOAD queue drained"));let Ve=await new es({controllerBaseUrl:_.controllerBaseUrl,tmsBaseUrl:_.tmsBaseUrl,auth:R,authResolver:$.getResolver()??void 0,sessionId:n.sessionId,sessionDir:n.sessionDir,testId:n.testId,commitId:V,projectId:K.project_id,folderId:K.folder_id,firstObjective:n.firstObjective??"KaneAI Test",firstUrl:n.firstUrl??"",runDirs:n.getRunDirs(),runObjectives:Se,startedAt:n.startedAt,endedAt:new Date().toISOString(),totalSteps:ge.current,totalDuration:pe.current,runStatuses:Ue.map(Ce=>Ce.status),orgId:O.org_id,userId:O.user_id,tmsUsername:z,tmsAccessKey:se,screenshotBaseUrl:n.screenshotBaseUrl,shareApiBaseUrl:_.shareApiBaseUrl,testManagerUiUrl:_.testManagerUiUrl,variables:Object.keys(n.auteurVariables).length>0?n.auteurVariables:void 0,variableIds:{},secrets:Pe,codeExport:e,onProgress:(Ce,xe,lt)=>{n.log(`EXIT_PROGRESS step=${Ce} status=${xe}${lt?` detail=${lt}`:""}`),k(gt=>ts(gt,Ce,xe,lt))},log:Ce=>n.log(Ce)}).execute();return Ve.success?(n.log(`EXIT_UPLOAD success: testId=${Ve.testId} testcaseId=${Ve.testcaseId??"none"} shareId=${Ve.shareId??"none"}`),n.setUploadStatus("uploaded"),Ve.testId&&n.setTestId(Ve.testId),Ve.testcaseId&&n.setTestcaseId(Ve.testcaseId)):(n.log(`EXIT_UPLOAD failed: ${Ve.error}`),n.setUploadStatus("failed",Ve.error)),Ve},[$,E,n,K,y,me]),At=(0,U.useCallback)(()=>{n.finish("complete"),un(),Be.killChrome(),setTimeout(()=>r(),1500)},[n,Be,r]),rt=(0,U.useCallback)(async _=>{if(j(!1),_&&n.testId){n.log(`EXIT feedback=${_}, submitting...`);try{let T=ce(E),R=$.getResolvedBasicAuth();R&&(await new It(T.tmsBaseUrl,R.username,R.access_key).submitFeedback({instruction_id:"",test_id:n.testId,feedback_type:_,mode:"human"}),n.log("EXIT feedback submitted"))}catch(T){n.log(`EXIT feedback failed: ${T}`)}}else n.log("EXIT feedback skipped");At()},[E,$,n,At]),mt=(0,U.useCallback)(()=>{if(Q)return;let _=n.nextRunIndex()>0;if(n.log(`EXIT hasRuns=${_} localMode=${i}`),!_||i){n.log(`EXIT quick exit \u2014 ${_?"local mode":"no runs"}`),n.finish("complete"),un(),Be.killChrome(),r();return}n.log("EXIT starting upload pipeline..."),te(!0),Rt().then(T=>{let R=ce(E),O=K.project_id;if(T?.testcaseId&&O){let V=`${R.testManagerUiUrl}/projects/${O}/test-cases/${T.testcaseId}`,z=T.shareId?`${V}/dashboard/share/${T.shareId}`:void 0,se=`${V}/dashboard?type=summary&agentView=true&fqdn=summary-page`;X({status:"success",testUrl:z,testCaseLink:se,codeExportDir:T.codeExportDir}),Zs({shareableLink:z,testCaseLink:se,codeExportDir:T.codeExportDir})}else X({status:T?.success?"success":"failed",error:T?.error});j(!0)}).catch(T=>{n.log(`EXIT_UPLOAD exception: ${T}`),n.setUploadStatus("failed",String(T)),X({status:"failed",error:String(T)}),j(!0)})},[Q,n,Be,r,i,Rt,E,K]);(0,U.useEffect)(()=>{if(!Q)return;let _=300*1e3,T=setTimeout(()=>{n.setUploadStatus("failed","Upload timed out after 5m"),n.finish("complete"),un(),Be.killChrome(),process.exit(0)},_);return()=>clearTimeout(T)},[Q,n,Be]);let Mt=U.default.useRef(0),Oe=U.default.useRef(null),be=U.default.useRef(0);Ze((_,T)=>{if(T.ctrl&&_==="c"){if(Q){be.current+=1,be.current>=2&&(n.setUploadStatus("pending","Force exit by user"),n.finish("complete"),un(),Be.killChrome(),process.exit(0));return}if(B.isRunning){B.cancelRun(),re({type:"info",text:"Run cancelled."}),Mt.current++,Oe.current&&clearTimeout(Oe.current),Oe.current=setTimeout(()=>{Mt.current=0},2e3),Mt.current>=2&&mt();return}if(Vt==="chat"){St("menu");return}mt()}});let st=U.default.useMemo(()=>{let _=$.creds.getActiveProfile()??"none",T=$.creds.getDefaultEnv();return[{id:"run",label:"Run",type:"submenu",children:[{id:"run-start",label:"Start Run",type:"action"},{id:"run-config",label:"Run Config",type:"submenu",children:[{id:"run-headless",label:"Headless",type:"select",currentValue:fe.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:R=>{nt(O=>({...O,headless:R==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(fe.maxSteps),onValue:R=>{let O=parseInt(R,10);O>0&&nt(V=>({...V,maxSteps:O}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:fe.timeout?String(fe.timeout):"",placeholder:"0 = no timeout",onValue:R=>{let O=parseInt(R,10);nt(V=>({...V,timeout:isNaN(O)?0:O}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:fe.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:R=>{nt(O=>({...O,cdpEndpoint:R}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:fe.wsEndpoint,placeholder:"wss://...",onValue:R=>{nt(O=>({...O,wsEndpoint:R}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{$.logout().then(R=>{Et();let O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv();ie(O,V),ne().catch(()=>{}),re(R?{type:"info",text:`Logged out: ${R.profile} [${R.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{re({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let R=$.creds.getActiveProfile()??"none",O=$.creds.getDefaultEnv(),V=$.creds.loadBasicAuth(R,O),z=V?"basic":$.creds.loadCredentials(R,O)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:R},{key:"Environment",value:O}]},{label:"Authentication",entries:[{key:"Method",value:z},...V?[{key:"Username",value:V.username}]:[]]},{label:"Token",entries:[{key:"Status",value:$.tokenValid?"valid":"not logged in",color:$.tokenValid?m.statusPass:m.statusFail}]}]}}},{id:"profiles",label:"Profiles",type:"action",onProfilesView:()=>{}}]},{id:"config",label:"Config",type:"submenu",children:[{id:"config-show",label:"Show",type:"action",onInfo:()=>({title:"Show Config",sections:[{label:"General",entries:[{key:"Model",value:"v16-alpha"}]},{label:"Browser",entries:[{key:"Window",value:`${K.window_size.width}x${K.window_size.height}`},{key:"Chrome Profile",value:K.chrome_profile_path?K.chrome_profile_path.split("/").pop()??K.chrome_profile_path:"(temporary)"}]},{label:"Project",entries:[{key:"Project",value:K.project_name?`${K.project_name} (${K.project_id})`:K.project_id??"(none)"},{key:"Folder",value:K.folder_name?`${K.folder_name} (${K.folder_id})`:K.folder_id??"(none)"},{key:"Default URL",value:K.default_url??"(none)"}]}]})},{id:"config-chrome",label:"Chrome Profile",type:"action",onChromeProfilePicker:()=>{}},{id:"config-project",label:"Project",type:"action",onProjectPicker:()=>{}},{id:"config-folder",label:"Folder",type:"action",...K.project_id?{onFolderPicker:()=>{}}:{onInfo:()=>({title:"Folder",sections:[{entries:[{key:"Status",value:"Select a project first",color:m.dim}]}]})}},{id:"config-url",label:"Default URL",type:"text-input",currentValue:K.default_url??"",onValue:R=>{s.set("default_url",R)}},{id:"config-window",label:"Window Size",type:"text-input",currentValue:`${K.window_size.width}x${K.window_size.height}`,placeholder:"WIDTHxHEIGHT",onValue:R=>{let O=R.split("x").map(Number);O[0]&&O[1]&&s.set("window_size",{width:O[0],height:O[1]})}}]},{id:"help",label:"Help",type:"submenu",children:[{id:"help-paths",label:"File Paths",type:"action",onInfo:()=>({title:"File Paths",sections:[{label:"Variables",entries:[{key:"Global dir",value:`${De(_e,"variables")}/*.json`},{key:"Local dir",value:"{cwd}/.testmuai/variables/*.json"},{key:"Format",value:'{ "key": { "value": "...", "secret": false } }'},{key:"Usage",value:"{{key}} in objectives"}]},{label:"Context Files",entries:[{key:"Global",value:De(_e,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:De(_e,"tui-config.json")},{key:"Auth",value:De(_e,"config.json")},{key:"Sessions",value:`${De(_e,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${De(_e,"variables")}/*.json`},{key:"2. Local",value:"{cwd}/.testmuai/variables/*.json"},{key:"3. CLI",value:"--variables-file <path>"},{key:"4. Inline",value:`--variables '{"key": {"value": "..."}}"`}]},{label:"Format",entries:[{key:"Normal",value:'{ "username": { "value": "alice", "secret": false } }'},{key:"Secret",value:'{ "api_key": { "value": "sk-...", "secret": true } }'}]},{label:"Usage",entries:[{key:"Syntax",value:"{{key}} in objectives to reference variables"}]}]})},{id:"help-context",label:"Context Files",type:"action",onInfo:()=>({title:"Context Files",sections:[{entries:[{key:"Description",value:"Additional instructions for the agent"}]},{label:"Paths",entries:[{key:"Global",value:De(_e,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"CLI Overrides",entries:[{key:"Global",value:"--global-context <file>"},{key:"Local",value:"--local-context <file>"}]}]})}]},{id:"update",label:d?`Update (${d.current} \u2192 ${d.latest})`:"Update",type:"action",onAction:()=>{x||(S(!0),re({type:"info",text:"Checking for updates..."}),(async()=>{let{checkForUpdate:R}=await import("./version-check-KS7CP3M5.js"),O=await R();if(!O){re({type:"info",text:`Already on latest version (${Pt})`}),S(!1);return}re({type:"info",text:`Update available: ${O.current} \u2192 ${O.latest}. Installing...`});let{runSelfUpdate:V}=await import("./updater-H5HYMYRG.js"),z=await V();z.success?re({type:"info",text:`\u2713 Updated to ${z.toVersion}. Restart kane-cli to use the new version.`}):re({type:"error",text:`Update failed: ${z.error}`}),S(!1)})())}},{id:"exit",label:"Exit",type:"action",onAction:()=>{mt()}}]},[$,s,K,re,mt,fe,Et,d,x]),pt=(0,U.useCallback)(_=>{if(B.askingUser){de((0,H.jsxs)(v,{children:[(0,H.jsx)(u,{color:"#888888",children:"\u2192 "}),(0,H.jsx)(u,{color:"#888888",children:"You answered: "}),(0,H.jsx)(u,{children:_})]})),B.sendAnswer(_);return}if(n.logCommand(_),B.isRunning){re({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}de((0,H.jsxs)(v,{children:[(0,H.jsx)(u,{color:"#b388ff",children:"\u276F "}),(0,H.jsx)(u,{children:_})]}));let T=p??K.default_url;le(_,T||void 0)},[B,re,de,n,p,K,le]),_n="KaneAI CLI",ot=$.getAuthInfo(),ht=ot?ot.method==="basic"?"basic auth":"oauth":"not logged in";return zt?(0,H.jsxs)(v,{flexDirection:"column",children:[oe.length>0&&(0,H.jsx)(Xt,{items:oe,children:_=>(0,H.jsx)(v,{paddingX:1,children:_.content},_.id)}),!l&&(0,H.jsx)(ps,{onComplete:()=>{let _=$.creds.getActiveProfile(),T=$.creds.getDefaultEnv(),R=_?$.creds.loadCredentials(_,T):null,O=_?$.creds.loadBasicAuth(_,T):null,V=!!(R||O),z=O?.username??_??null;de((0,H.jsx)(An,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:Pt,authenticated:V,user:z})),c(!0),t&&t.then(se=>{se&&(h(se),re({type:"info",text:`Update available: ${se.current} \u2192 ${se.latest} \u2014 select Update from menu or run \`kane-cli update\``}))}).catch(()=>{})}}),l&&Vt==="menu"&&!Q&&(0,H.jsx)(v,{marginBottom:1,children:(0,H.jsxs)(v,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,H.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,H.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,H.jsx)(u,{color:"#ff9500",children:K.model}),(0,H.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,H.jsx)(u,{color:m.dimmed,children:ht}),(0,H.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,H.jsxs)(u,{color:m.dimmed,children:[Lt??"no profile","/",E]})]})}),l&&!Q&&(0,H.jsxs)(v,{flexDirection:"column",flexGrow:1,children:[Vt==="menu"&&(0,H.jsx)(H.Fragment,{children:(0,H.jsx)(Ks,{items:st,onRunSelected:()=>St("chat"),renderLoginWizard:_=>{let T=ve?.phase??"wizard";if(T==="project")return(0,H.jsx)(Yn,{resolver:$.getResolver(),currentProjectId:null,env:ve.env,onSelect:(R,O)=>{$.creds.saveProfileConfig(ve.profile,ve.env,{project_id:R,project_name:O}),at(V=>V?{...V,phase:"folder"}:null)},onCancel:()=>{ie(ve.profile,ve.env),at(null),_()}});if(T==="folder"){let R=$.creds.loadProfileConfig(ve.profile,ve.env);return(0,H.jsx)(Qn,{resolver:$.getResolver(),projectId:R?.project_id??"",currentFolderId:null,env:ve.env,onSelect:(O,V)=>{$.creds.saveProfileConfig(ve.profile,ve.env,{folder_id:O,folder_name:V}),ie(ve.profile,ve.env),at(null),_()},onCancel:async()=>{let O=$.creds.loadProfileConfig(ve.profile,ve.env);if(O?.project_id)try{let z=$.getResolver()?.cached;if(z){let se=ce(ve.env),Se=await new It(se.tmsBaseUrl,z.username,z.access_key).getDefaultFolder(O.project_id);Se&&$.creds.saveProfileConfig(ve.profile,ve.env,{folder_id:Se,folder_name:"Default"})}}catch{}ie(ve.profile,ve.env),at(null),_()}})}return(0,H.jsx)(Xr,{devMode:process.env.KANE_DEV_MODE==="1",profiles:$.creds.listProfiles(),onBasicLogin:(R,O,V,z)=>{$.creds.saveBasicAuth(R,O,{username:V,access_key:z}),$.creds.setActiveProfile(R),$.creds.setDefaultEnv(O),$.setTokenValid(!0),Et()},onOAuthLogin:async(R,O)=>{$.creds.setDefaultEnv(O),await $.login(R),Et()},onComplete:(R,O)=>{ne(O).then(()=>{at({phase:"project",profile:R,env:O})}).catch(()=>{at({phase:"project",profile:R,env:O})})},onCancel:()=>{at(null),_()}})},renderProfilesView:_=>(0,H.jsx)(Yr,{creds:$.creds,onSwitch:(T,R)=>{$.creds.setActiveProfile(T),$.creds.setDefaultEnv(R),ie(T,R),Et(),ne(R).catch(()=>{}),re({type:"info",text:`Switched to ${T} [${R}]`})},onCancel:_}),renderChromeProfilePicker:_=>(0,H.jsx)(Qr,{currentPath:K.chrome_profile_path,onSelect:T=>{s.set("chrome_profile_path",T),Ct(s.load())},onCancel:_}),renderProjectPicker:_=>(0,H.jsx)(Yn,{resolver:$.getResolver(),currentProjectId:K.project_id,env:E,onSelect:(T,R)=>{s.save({project_id:T,project_name:R});let O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv();O&&$.creds.saveProfileConfig(O,V,{project_id:T,project_name:R}),Ct(s.load()),_()},onCancel:_}),renderFolderPicker:_=>(0,H.jsx)(Qn,{resolver:$.getResolver(),projectId:K.project_id??"",currentFolderId:K.folder_id,env:E,onSelect:(T,R)=>{s.save({folder_id:T,folder_name:R});let O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv();O&&$.creds.saveProfileConfig(O,V,{folder_id:T,folder_name:R}),Ct(s.load()),_()},onCancel:_})})}),Vt==="chat"&&(0,H.jsxs)(H.Fragment,{children:[B.isRunning&&B.steps.length>0&&(0,H.jsx)(Pn,{steps:B.steps,bifurcated:!!B.bifurcationInfo&&!B.bifurcationInfo.isSingleFlow,flows:B.bifurcationInfo?.flows,cmInitCounts:B.cmInitCounts,onStepCommit:de},`run-${Z.current}`),(0,H.jsx)(xs,{onSubmit:pt,onEscape:()=>{!B.isRunning&&!B.askingUser&&St("menu")},history:q,placeholder:B.askingUser?"Type your answer...":B.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (esc = menu)"})]})]}),l&&Q&&A&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(ns,{steps:f,status:A.status,testUrl:A.testUrl,error:A.error}),A.status==="success"&&(0,H.jsx)(rs,{shareableLink:A.testUrl,testCaseLink:A.testCaseLink,codeExportDir:A.codeExportDir,autoExit:!1})]}),P&&(0,H.jsx)(ss,{onSubmit:rt}),l&&!Q&&(0,H.jsx)(os,{profile:Lt,environment:E,model:K.model,tokenValid:$.tokenValid,sessionId:n.sessionId,runCount:N,viewMode:Vt})]}):(0,H.jsx)(Fs,{onComplete:()=>{Ct(s.load()),sn(!0)}})}var So=G(yo(),1),{program:uf,createCommand:df,createArgument:ff,createOption:mf,CommanderError:pf,InvalidArgumentError:hf,InvalidOptionArgumentError:gf,Command:Co,Argument:xf,Option:Hn,Help:vf}=So.default;import{join as Qe}from"path";import{readFileSync as ko,readdirSync as Ra,existsSync as vn}from"fs";var Ro=G(We(),1);import{createInterface as ka}from"readline";function rn(i){process.stdout.write(JSON.stringify(i)+`
45
- `)}async function Eo(i,e,t){let r=Un(i,e);kn().then(h=>{h&&rn({type:"update_available",current:h.current,latest:h.latest,severity:h.severity})}).catch(()=>{});let n=ka({input:process.stdin});n.on("line",h=>{try{let x=JSON.parse(h);x.type==="user_response"?r.sendUserResponse(x.answer??""):x.type==="cancel"&&r.sendCancel(x.reason??"")}catch{}});let s=null,a=!1,o=0,l=null,c=0,d=!1;for await(let h of r.events)switch(h.type){case"run_start":d&&c++;break;case"step_start":{let x=h,S={step:x.index+1,status:"running",remark:x.objective??`Step ${x.index+1}`};x.child_id&&(S.child_id=x.child_id),rn(S);break}case"step_end":{let x=h;o++;let S={step:x.index+1,status:x.status==="passed"?"done":"failed",remark:x.summary??""};x.child_id&&(S.child_id=x.child_id),rn(S);let p=d?Math.max(0,c-1):0;t?.onStepEnd?.(x.index,p);break}case"bifurcation":{let x=h,S=x.flows??[],p=x.count??S.length;(x.is_single_flow??p<=1)||(l=S,d=!0,c=0),rn({type:"bifurcation",flows:S,count:p});break}case"ask_user":{let x=h;rn({type:"ask_user",question:x.question,step_index:x.step_index,...x.options?{options:x.options}:{}});break}case"run_end":{s=h;break}case"error":{a=!0,rn({type:"error",message:h.message});break}default:break}return n.close(),await r.exited,{lastRunEnd:s,stepsTotal:o,hadError:a,bifurcationFlows:l}}function Ao(i){let e=new Co;if(e.name("kane-cli").version(Pt),i[0]==="--help"||i[0]==="-h"||i[0]==="help"){(async()=>{let{HelpView:r}=await import("./HelpView-2ZFLX7JC.js"),{render:n}=await import("./build-MFETN2BY.js"),s=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=n(s.default.createElement(r));await a(),process.exit(0)})();return}e.command("login").action(async()=>{let r=new Ee,{LoginWizard:n}=await import("./LoginWizard-SSE5NJVU.js"),{render:s}=await import("./build-MFETN2BY.js"),a=await import("./react-QWOAB3TB.js");await new Promise(o=>{let{unmount:l}=s(a.default.createElement(n,{devMode:process.env.KANE_DEV_MODE==="1",profiles:r.listProfiles(),onBasicLogin:(c,d,h,x)=>{r.saveBasicAuth(c,d,{username:h,access_key:x}),r.setActiveProfile(c),r.setDefaultEnv(d),l(),o()},onOAuthLogin:async(c,d)=>{r.setDefaultEnv(d),await new bt(c,d,r).login(),l(),o()},onCancel:()=>{l(),o()}}))})}),e.command("logout").action(async()=>{let r=new Ee,n=r.getActiveProfile();if(!n){console.log("No active profile to logout");return}let s=r.getDefaultEnv(),a=r.loadCredentials(n,s),o=r.loadClient(n,s);if(a&&o){let c=new Ge(s);try{await c.revokeToken(a.access_token,o.client_id,"access_token")}catch{}try{await c.revokeToken(a.refresh_token,o.client_id,"refresh_token")}catch{}}r.deleteProfileFull(n,s);let l=r.listProfiles();l.length>0?(r.setActiveProfile(l[0].profile),r.setDefaultEnv(l[0].env),console.log(`Logged out ${n} [${s}]. Switched to ${l[0].profile} [${l[0].env}]`)):console.log(`Logged out ${n} [${s}]. No profiles remaining.`)}),e.command("whoami").option("--profile <name>","Profile name").action(async r=>{let n=new Ee,s=r.profile??n.getActiveProfile()??"default",a=n.getDefaultEnv(),o=n.loadCredentials(s,a),l=n.loadBasicAuth(s,a),c="none",d,h,x;if(l)c="basic",d=l.username;else if(o){c="oauth";let w=o.expires_at,N=Date.now()/1e3;h=w>N?"valid":"expired",x=new Date(w*1e3).toISOString().slice(0,10)}else h="missing";let{WhoamiView:S}=await import("./WhoamiView-2VBZBQF7.js"),{render:p}=await import("./build-MFETN2BY.js"),b=await import("./react-QWOAB3TB.js"),{waitUntilExit:g}=p(b.default.createElement(S,{profile:s,env:a,authenticated:c!=="none",authMethod:c,username:d,tokenStatus:h,expiresAt:x}));await g()}),e.command("config <action> [value]").action(async(r,n)=>{let s=new et,a=new Ee;if(r==="show"){let o=s.load(),l=a.getActiveProfile()??"default",c=a.getDefaultEnv(),d=a.loadBasicAuth(l,c),h=a.loadCredentials(l,c),x=d?`basic (${d.username})`:h?"oauth":"not configured",{ConfigView:S}=await import("./ConfigView-5R4G4OZ6.js"),{render:p}=await import("./build-MFETN2BY.js"),b=await import("./react-QWOAB3TB.js"),{waitUntilExit:g}=p(b.default.createElement(S,{model:o.model,authLabel:x,profile:l,env:c,defaultUrl:o.default_url,projectId:o.project_id,projectName:o.project_name,folderId:o.folder_id,windowSize:`${o.window_size.width}x${o.window_size.height}`,chromeProfile:o.chrome_profile_path,setupComplete:o.setup_complete}));await g()}else if(r==="set-url"&&n)s.set("default_url",n),console.log(`Default URL set to ${n}`);else if(r==="set-window"&&n){let o=n.split("x").map(Number);o[0]&&o[1]&&(s.set("window_size",{width:o[0],height:o[1]}),console.log(`Window size set to ${o[0]}x${o[1]}`))}else if(r==="chrome-profile"){let{ChromeProfilePicker:o}=await import("./ChromeProfilePicker-IRZUDC2R.js"),{render:l}=await import("./build-MFETN2BY.js"),c=await import("./react-QWOAB3TB.js");await new Promise(d=>{let{unmount:h}=l(c.default.createElement(o,{currentPath:s.load().chrome_profile_path,onSelect:x=>{s.set("chrome_profile_path",x),console.log(`Chrome profile set to ${x}`),h(),d()},onCancel:()=>{h(),d()}}))})}else if(r==="project"){let o=a.getDefaultEnv(),l=ce(o),c=a.loadBasicAuth(a.getActiveProfile()??"default",o);if(!c){console.log("Login first to browse projects");return}let{ProjectPicker:d}=await import("./ProjectPicker-AFQDF2VS.js"),{AuthResolver:h}=await import("./resolver-L3Z6FAOD.js"),{render:x}=await import("./build-MFETN2BY.js"),S=await import("./react-QWOAB3TB.js"),p=new h(l.controllerBaseUrl,async()=>null,c);await p.resolve(),await new Promise(b=>{let{unmount:g}=x(S.default.createElement(d,{resolver:p,currentProjectId:s.load().project_id,env:o,onSelect:(w,N)=>{s.set("project_id",w),s.set("project_name",N),console.log(`Project set to ${N} (${w})`),g(),b()},onCancel:()=>{g(),b()}}))})}else if(r==="folder"){let o=s.load();if(!o.project_id){console.log("Select a project first: kane-cli config project");return}let l=a.getDefaultEnv(),c=ce(l),d=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!d){console.log("Login first to browse folders");return}let{FolderPicker:h}=await import("./FolderPicker-G4C4RCP2.js"),{AuthResolver:x}=await import("./resolver-L3Z6FAOD.js"),{render:S}=await import("./build-MFETN2BY.js"),p=await import("./react-QWOAB3TB.js"),b=new x(c.controllerBaseUrl,async()=>null,d);await b.resolve(),await new Promise(g=>{let{unmount:w}=S(p.default.createElement(h,{resolver:b,projectId:o.project_id,currentFolderId:o.folder_id,env:l,onSelect:(N,W)=>{s.set("folder_id",N),s.set("folder_name",W),console.log(`Folder set to ${W} (${N})`),w(),g()},onCancel:()=>{w(),g()}}))})}else console.log("Usage: kane-cli config show|set-url|set-window|chrome-profile|project|folder")}),e.command("run").argument("<objective>","Test objective (use {{var}} to reference variables)").option("--url <url>","Target URL").option("--headless","Run Chrome in headless mode").option("--max-steps <n>","Maximum agent steps","30").option("--timeout <seconds>","Kill run after N seconds").option("--cdp-endpoint <url>","Connect to existing Chrome CDP endpoint").option("--ws-endpoint <url>","Connect via Playwright WebSocket (e.g. LambdaTest wss:// URL)").option("--global-context <file>",`Override global context markdown (default: ${Qe(_e,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new Hn("--model <name>","Model override").hideHelp()).option("--variables <json>",`Inline variables JSON, e.g. '{"user": {"value": "alice"}}'`).option("--variables-file <path>","Load variables from a JSON file").option("--session-context <json>","Session context JSON (prior runs)").addOption(new Hn("--cft","Use Playwright Chromium instead of managed Chrome").hideHelp()).option("--username <user>","Basic auth username (skip OAuth)").option("--access-key <key>","Basic auth access key (skip OAuth)").option("--env <name>","Environment (prod or stage)").option("--agent","Agent mode: plain NDJSON output, no colors/UI").option("--task-skills","Enable domain-specific task skills (experimental)").addOption(new Hn("--local","Skip TMS integration (no uploads, no variables/secrets push)").hideHelp()).option("--code-export","Generate code export after upload").addHelpText("after",`
57
+ `);fe({type:"error",text:`Runner error:
58
+ ${k}`})}},[L.runError,L.isRunning,fe,n]);let go=(0,j.useCallback)(async()=>{n.log("info","EXIT_UPLOAD_START","Starting exit upload pipeline"),v(fr()),p({status:"uploading"});let S=T.getResolvedBasicAuth(),A=null;if(!S&&(A=await T.getToken(),!A))return n.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no auth available"),null;let k=C??await Et();if(!k)return n.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no TMS credentials"),n.setUploadStatus("failed","Could not get TMS credentials"),null;n.log("info","EXIT_UPLOAD_CONFIG","Exit upload configuration",{test_id:n.testId,commit_id:n.sessionId,project_id:J.project_id,session_dir:n.sessionDir,run_dirs:n.getRunDirs()});let O={basicAuth:S??null,token:A,resolver:T.getResolver(),resolvedCreds:k};W.current&&(n.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot queue before pipeline"),await W.current.drain(),n.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot queue drained"));let K=un({session:n,env:_e,auth:O,variables:de.current??{raw:{},auteur:{},auteurObjective:"",secretEntries:[],nonSecretEntries:[]},variableIds:_t.current,projectId:J.project_id,folderId:J.folder_id,totalSteps:mo.current,totalDuration:po.current,codeExport:e,onProgress:(ae,ue,Ie)=>{n.log("info","EXIT_PROGRESS","Upload progress",{step:ae,status:ue,detail:Ie}),v(Ve=>Bo(Ve,ae,ue,Ie))},log:(ae,ue,Ie,Ve)=>n.log(ae,ue,Ie,Ve)}),X=await new Do(K).execute();return X.success?(n.log("info","EXIT_UPLOAD_OK","Exit upload succeeded",{test_id:X.testId,testcase_id:X.testcaseId??null,share_id:X.shareId??null}),n.setUploadStatus("uploaded"),X.testId&&n.setTestId(X.testId),X.testcaseId&&n.setTestcaseId(X.testcaseId)):(n.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:X.error}),n.setUploadStatus("failed",X.error)),X},[T,_e,n,J,C,Et]),vo=(0,j.useCallback)(async()=>{await n.finish("complete"),ne(0,"Session complete")},[n]),Ei=(0,j.useCallback)(async S=>{if(H(!1),S&&n.testId){n.log("info","EXIT_FEEDBACK_SUBMIT","Submitting session feedback",{choice:S});try{let A=ie(_e),k=T.getResolvedBasicAuth();k&&await Gn({tmsBaseUrl:A.tmsBaseUrl,username:k.username,accessKey:k.access_key,testId:n.testId,feedbackType:S,log:(O,K,q,X)=>n.log(O,K,q,X)})}catch(A){n.log("error","EXIT_FEEDBACK_FAILED","Feedback submission failed",{error:String(A)})}}else n.log("info","EXIT_FEEDBACK_SKIPPED","Feedback skipped");vo()},[_e,T,n,vo]),pn=(0,j.useCallback)(async()=>{if(z)return;let S=n.nextRunIndex()>0;if(n.log("info","EXIT_START","Exit initiated",{has_runs:S,local_mode:o}),!S||o){n.log("info","EXIT_QUICK","Quick exit",{reason:S?"local mode":"no runs"}),await n.finish("complete"),ne(0,S?"Local mode \u2014 quick exit":"No runs \u2014 quick exit");return}n.log("info","EXIT_UPLOAD_INIT","Starting upload pipeline on exit"),ce(!0),go().then(A=>{let k=ie(_e),O=J.project_id;if(A?.testcaseId&&O){let K=A.shareId?Nt(k.testManagerUiUrl,O,A.testcaseId,A.shareId):void 0,q=Vn(k.testManagerUiUrl,O,A.testcaseId);p({status:"success",testUrl:K,testCaseLink:q,codeExportDir:A.codeExportDir}),Ms({shareableLink:K,testCaseLink:q,codeExportDir:A.codeExportDir})}else p({status:A?.success?"success":"failed",error:A?.error});H(!0)}).catch(A=>{n.log("error","EXIT_UPLOAD_EXCEPTION","Exit upload threw exception",{error:String(A)}),n.setUploadStatus("failed",String(A)),p({status:"failed",error:String(A)}),H(!0)})},[z,n,o,go,_e,J]);(0,j.useEffect)(()=>{if(!z)return;let S=300*1e3,A=setTimeout(async()=>{n.setUploadStatus("failed","Upload timed out after 5m"),await n.finish("complete"),ne(0,"Upload timed out after 5m")},S);return()=>clearTimeout(A)},[z,n]);let er=j.default.useRef(0),tr=j.default.useRef(null),xo=j.default.useRef(0);$e((S,A)=>{if(A.ctrl&&S==="c"){if(z){xo.current+=1,xo.current>=2&&(n.setUploadStatus("pending","Force exit by user"),n.finish("complete"),ne(0,"Force exit by user"));return}if(L.isRunning){L.cancelRun(),fe({type:"info",text:"Run cancelled."}),er.current++,tr.current&&clearTimeout(tr.current),tr.current=setTimeout(()=>{er.current=0},2e3),er.current>=2&&pn();return}if(Ae==="chat"){We("menu");return}pn()}});let Ci=j.default.useMemo(()=>{let S=T.creds.getActiveProfile()??"none",A=T.creds.getDefaultEnv();return[{id:"run",label:"Run",type:"submenu",children:[{id:"run-start",label:"Start Run",type:"action"},{id:"run-config",label:"Run Config",type:"submenu",children:[{id:"run-headless",label:"Headless",type:"select",currentValue:oe.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:k=>{ge(O=>({...O,headless:k==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(oe.maxSteps),onValue:k=>{let O=parseInt(k,10);O>0&&ge(K=>({...K,maxSteps:O}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:oe.timeout?String(oe.timeout):"",placeholder:"0 = no timeout",onValue:k=>{let O=parseInt(k,10);ge(K=>({...K,timeout:isNaN(O)?0:O}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:oe.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:k=>{ge(O=>({...O,cdpEndpoint:k}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:oe.wsEndpoint,placeholder:"wss://...",onValue:k=>{ge(O=>({...O,wsEndpoint:k}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{T.logout().then(k=>{yt();let O=T.creds.getActiveProfile(),K=T.creds.getDefaultEnv();qt(O,K),zt().catch(()=>{}),fe(k?{type:"info",text:`Logged out: ${k.profile} [${k.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{fe({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let k=T.creds.getActiveProfile()??"none",O=T.creds.getDefaultEnv(),K=T.creds.loadBasicAuth(k,O),q=K?"basic":T.creds.loadCredentials(k,O)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:k},{key:"Environment",value:O}]},{label:"Authentication",entries:[{key:"Method",value:q},...K?[{key:"Username",value:K.username}]:[]]},{label:"Token",entries:[{key:"Status",value:T.tokenValid?"valid":"not logged in",color:T.tokenValid?m.statusPass:m.statusFail}]}]}}},{id:"balance",label:"Credit Balance",type:"action",suppressFeedback:!0,onAction:()=>{(async()=>{let k=T.creds.getActiveProfile()??"default",O=T.creds.getDefaultEnv(),K=ie(O);try{let q=T.getBasicAuth(),X=q?null:await T.getToken();if(!q&&!X){R({text:"Not authenticated. Run /login first.",color:m.red});return}let{ControllerClient:ae}=await import("./controller-client-7BIK5FYL.js"),Ie=await(q?new ae(K.controllerBaseUrl,{username:q.username,accessKey:q.access_key}):new ae(K.controllerBaseUrl,X)).getCreditBalance();R({text:`Credits \u2014 available: ${Ie.available_credits}, total: ${Ie.total_credits} (${k} / ${O})`,color:m.green})}catch(q){R({text:`Balance check failed: ${q instanceof Error?q.message:String(q)}`,color:m.red})}G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{R(null),G.current=null},5e3)})()}},{id:"profiles",label:"Profiles",type:"action",onProfilesView:()=>{}}]},{id:"config",label:"Config",type:"submenu",children:[{id:"config-show",label:"Show",type:"action",onInfo:()=>({title:"Show Config",sections:[{label:"General",entries:[{key:"Model",value:"v16-alpha"}]},{label:"Browser",entries:[{key:"Window",value:`${J.window_size.width}x${J.window_size.height}`},{key:"Chrome Profile",value:J.chrome_profile_path?J.chrome_profile_path.split("/").pop()??J.chrome_profile_path:"(temporary)"}]},{label:"Project",entries:[{key:"Project",value:J.project_name?`${J.project_name} (${J.project_id})`:J.project_id??"(none)"},{key:"Folder",value:J.folder_name?`${J.folder_name} (${J.folder_id})`:J.folder_id??"(none)"},{key:"Default URL",value:Ge}]}]})},{id:"config-chrome",label:"Chrome Profile",type:"action",onChromeProfilePicker:()=>{}},{id:"config-project",label:"Project",type:"action",onProjectPicker:()=>{}},{id:"config-folder",label:"Folder",type:"action",...J.project_id?{onFolderPicker:()=>{}}:{onInfo:()=>({title:"Folder",sections:[{entries:[{key:"Status",value:"Select a project first",color:m.dim}]}]})}},{id:"config-window",label:"Window Size",type:"action",currentValue:`${J.window_size.width}x${J.window_size.height}`,onWindowSizePicker:()=>{}}]},{id:"help",label:"Help",type:"submenu",children:[{id:"help-paths",label:"File Paths",type:"action",onInfo:()=>({title:"File Paths",sections:[{label:"Variables",entries:[{key:"Global dir",value:`${Ze(ve,"variables")}/*.json`},{key:"Local dir",value:"{cwd}/.testmuai/variables/*.json"},{key:"Format",value:'{ "key": { "value": "...", "secret": false } }'},{key:"Usage",value:"{{key}} in objectives"}]},{label:"Context Files",entries:[{key:"Global",value:Ze(ve,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:Ze(ve,"tui-config.json")},{key:"Auth",value:Ze(ve,"config.json")},{key:"Sessions",value:`${Ze(ve,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${Ze(ve,"variables")}/*.json`},{key:"2. Local",value:"{cwd}/.testmuai/variables/*.json"},{key:"3. CLI",value:"--variables-file <path>"},{key:"4. Inline",value:`--variables '{"key": {"value": "..."}}"`}]},{label:"Format",entries:[{key:"Normal",value:'{ "username": { "value": "alice", "secret": false } }'},{key:"Secret",value:'{ "api_key": { "value": "sk-...", "secret": true } }'}]},{label:"Usage",entries:[{key:"Syntax",value:"{{key}} in objectives to reference variables"}]}]})},{id:"help-context",label:"Context Files",type:"action",onInfo:()=>({title:"Context Files",sections:[{entries:[{key:"Description",value:"Additional instructions for the agent"}]},{label:"Paths",entries:[{key:"Global",value:Ze(ve,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"CLI Overrides",entries:[{key:"Global",value:"--global-context <file>"},{key:"Local",value:"--local-context <file>"}]}]})}]},{id:"update",label:c?`Update (${c.current} \u2192 ${c.latest})`:"Update",type:"action",onAction:()=>{d||(g(!0),fe({type:"info",text:"Checking for updates..."}),(async()=>{let{checkForUpdate:k}=await import("./version-check-SR6WBC6M.js"),O=await k();if(!O){fe({type:"info",text:`Already on latest version (${ft})`}),g(!1);return}fe({type:"info",text:`Update available: ${O.current} \u2192 ${O.latest}. Installing...`});let{runSelfUpdate:K}=await import("./updater-WVTXO7SS.js"),q=await K();q.success?fe({type:"info",text:`\u2713 Updated to ${q.toVersion}. Restart kane-cli to use the new version.`}):fe({type:"error",text:`Update failed: ${q.error}`}),g(!1)})())}},{id:"exit",label:"Exit",type:"action",onAction:()=>{pn()}}]},[T,r,J,fe,pn,oe,yt,c,d]),Ri=(0,j.useCallback)(S=>{if(L.askingUser){ee((0,M.jsxs)(x,{children:[(0,M.jsx)(u,{color:"#888888",children:"\u2192 "}),(0,M.jsx)(u,{color:"#888888",children:"You answered: "}),(0,M.jsx)(u,{children:S})]})),L.sendAnswer(S);return}if(n.logCommand(S),L.isRunning){fe({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}ee((0,M.jsxs)(x,{children:[(0,M.jsx)(u,{color:"#b388ff",children:"\u276F "}),(0,M.jsx)(u,{children:S})]})),uo(S,Ge)},[L,fe,ee,n,E,J,uo]),wo=T.getAuthInfo(),ki=wo?wo.method==="basic"?"basic auth":"oauth":"not logged in";return se?(0,M.jsxs)(x,{flexDirection:"column",children:[Dt.length>0&&(0,M.jsx)(jt,{items:Dt,children:S=>(0,M.jsx)(x,{paddingX:1,children:S.content},S.id)}),!i&&(0,M.jsx)(zo,{onComplete:()=>{let S=T.creds.getActiveProfile(),A=T.creds.getDefaultEnv(),k=S?T.creds.loadCredentials(S,A):null,O=S?T.creds.loadBasicAuth(S,A):null,K=!!(k||O),q=O?.username??S??null;ee((0,M.jsx)(_n,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:ft,authenticated:K,user:q})),l(!0),t&&t.then(X=>{X&&(f(X),fe({type:"info",text:`Update available: ${X.current} \u2192 ${X.latest} \u2014 select Update from menu or run \`kane-cli update\``}))}).catch(()=>{})}}),i&&Ae==="menu"&&!z&&(0,M.jsx)(x,{marginBottom:1,children:(0,M.jsxs)(x,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,M.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,M.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,M.jsx)(u,{color:"#ff9500",children:J.model}),(0,M.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,M.jsx)(u,{color:m.dimmed,children:ki}),(0,M.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,M.jsxs)(u,{color:m.dimmed,children:[mn??"no profile","/",_e]})]})}),i&&!z&&(0,M.jsxs)(x,{flexDirection:"column",flexGrow:1,children:[Ae==="menu"&&(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)(Cs,{items:Ci,onRunSelected:()=>We("chat"),renderLoginWizard:S=>{let A=be?.phase??"wizard";if(A==="project")return(0,M.jsx)(ur,{resolver:T.getResolver(),currentProjectId:null,env:be.env,onSelect:(k,O)=>{T.creds.saveProfileConfig(be.profile,be.env,{project_id:k,project_name:O}),St(K=>K?{...K,phase:"folder"}:null)},onCancel:()=>{qt(be.profile,be.env),St(null),S()}});if(A==="folder"){let k=T.creds.loadProfileConfig(be.profile,be.env);return(0,M.jsx)(dr,{resolver:T.getResolver(),projectId:k?.project_id??"",currentFolderId:null,env:be.env,onSelect:(O,K)=>{T.creds.saveProfileConfig(be.profile,be.env,{folder_id:O,folder_name:K}),qt(be.profile,be.env),St(null),S()},onCancel:async()=>{let O=T.creds.loadProfileConfig(be.profile,be.env);if(O?.project_id)try{let q=T.getResolver()?.cached;if(q){let X=ie(be.env),ue=await new et(X.tmsBaseUrl,q.username,q.access_key).getDefaultFolder(O.project_id);ue&&T.creds.saveProfileConfig(be.profile,be.env,{folder_id:ue,folder_name:"Default"})}}catch{}qt(be.profile,be.env),St(null),S()}})}return(0,M.jsx)(To,{devMode:process.env.KANE_DEV_MODE==="1",profiles:T.creds.listProfiles(),onBasicLogin:(k,O,K,q)=>{T.creds.saveBasicAuth(k,O,{username:K,access_key:q}),T.creds.setActiveProfile(k),T.creds.setDefaultEnv(O),T.setTokenValid(!0),yt()},onOAuthLogin:async(k,O)=>{T.creds.setDefaultEnv(O),await T.login(k),yt()},onComplete:(k,O)=>{zt(O).then(()=>{St({phase:"project",profile:k,env:O})}).catch(()=>{St({phase:"project",profile:k,env:O})})},onCancel:()=>{St(null),S()}})},renderProfilesView:S=>(0,M.jsx)(Ao,{creds:T.creds,onSwitch:(A,k)=>{T.creds.setActiveProfile(A),T.creds.setDefaultEnv(k),qt(A,k),yt(),zt(k).catch(()=>{}),fe({type:"info",text:`Switched to ${A} [${k}]`})},onCancel:S}),renderChromeProfilePicker:S=>(0,M.jsx)(Io,{currentPath:J.chrome_profile_path,onSelect:A=>{r.set("chrome_profile_path",A),ut(r.load())},onCancel:S}),renderProjectPicker:S=>(0,M.jsx)(ur,{resolver:T.getResolver(),currentProjectId:J.project_id,env:_e,onSelect:(A,k)=>{r.save({project_id:A,project_name:k});let O=T.creds.getActiveProfile(),K=T.creds.getDefaultEnv();O&&T.creds.saveProfileConfig(O,K,{project_id:A,project_name:k}),ut(r.load()),S()},onCancel:S}),renderFolderPicker:S=>(0,M.jsx)(dr,{resolver:T.getResolver(),projectId:J.project_id??"",currentFolderId:J.folder_id,env:_e,onSelect:(A,k)=>{r.save({folder_id:A,folder_name:k});let O=T.creds.getActiveProfile(),K=T.creds.getDefaultEnv();O&&T.creds.saveProfileConfig(O,K,{folder_id:A,folder_name:k}),ut(r.load()),S()},onCancel:S}),renderWindowSizePicker:S=>(0,M.jsx)(ks,{currentWidth:J.window_size.width,currentHeight:J.window_size.height,onSelect:(A,k)=>{r.set("window_size",{width:A,height:k}),ut(r.load()),S()},onCancel:S})}),P&&(0,M.jsx)(x,{paddingX:1,marginTop:1,children:(0,M.jsx)(u,{color:P.color,children:P.text})})]}),Ae==="chat"&&(0,M.jsxs)(M.Fragment,{children:[(()=>{let S=kn({isRunning:L.isRunning,bifurcationInfo:L.bifurcationInfo,steps:L.steps,cmInitCounts:L.cmInitCounts});return S?(0,M.jsx)(Rn,{label:S.label,hasBifurcation:S.hasBifurcation}):null})(),L.isRunning&&L.steps.length>0&&(0,M.jsx)(En,{steps:L.steps,bifurcated:!!L.bifurcationInfo&&!L.bifurcationInfo.isSingleFlow,flows:L.bifurcationInfo?.flows,cmInitCounts:L.cmInitCounts,onStepCommit:ee},`run-${Q.current}`),(0,M.jsx)(Xo,{onSubmit:Ri,onEscape:()=>{!L.isRunning&&!L.askingUser&&We("menu")},history:me,placeholder:L.askingUser?"Type your answer...":L.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (esc = menu)"})]})]}),i&&z&&Z&&(0,M.jsxs)(M.Fragment,{children:[(0,M.jsx)($o,{steps:b,status:Z.status,testUrl:Z.testUrl,error:Z.error}),Z.status==="success"&&(0,M.jsx)(jo,{shareableLink:Z.testUrl,testCaseLink:Z.testCaseLink,codeExportDir:Z.codeExportDir,autoExit:!1})]}),U&&(0,M.jsx)(Lo,{onSubmit:Ei}),i&&!z&&(0,M.jsx)(Uo,{profile:mn,environment:_e,model:J.model,tokenValid:T.tokenValid,sessionId:n.sessionId,runCount:w,viewMode:Ae})]}):(0,M.jsx)(ys,{onComplete:()=>{ut(r.load()),pe(!0)}})}var pi=N(mi(),1),{program:xp,createCommand:wp,createArgument:bp,createOption:_p,CommanderError:yp,InvalidArgumentError:Sp,InvalidOptionArgumentError:Ep,Command:hi,Argument:Cp,Option:Wt,Help:Rp}=pi.default;import{join as Ot}from"path";var wi=N(ke(),1);import{createInterface as Cl}from"readline";function Kt(o){process.stdout.write(JSON.stringify(o)+`
59
+ `)}async function gi(o,e,t){let n=Un(o,e);wn().then(d=>{d&&Kt({type:"update_available",current:d.current,latest:d.latest,severity:d.severity})}).catch(()=>{});let r=Cl({input:process.stdin});r.on("line",d=>{try{let g=JSON.parse(d);g.type==="user_response"?n.sendUserResponse(g.answer??""):g.type==="cancel"&&n.sendCancel(g.reason??"")}catch{}});let s=null,a=!1,i=0,l=null,c=0,f=!1;for await(let d of n.events)switch(d.type){case"run_start":f&&c++;break;case"step_start":{let g=d;t?.onStepLog?.("STEP_START",`Step ${g.index} started`,{index:g.index,objective:g.objective,child_id:g.child_id});let E={step:g.index+1,status:"running",remark:g.objective??`Step ${g.index+1}`};g.child_id&&(E.child_id=g.child_id),Kt(E);break}case"step_event":t?.onStepLog?.("STEP_EVENT",`Step ${d.index} ${d.event}`,{index:d.index,phase:d.event,action_type:d.action_type,detail:d.detail,child_id:d.child_id});break;case"step_end":{let g=d;t?.onStepLog?.("STEP_END",`Step ${g.index} ${g.status}`,{index:g.index,status:g.status,duration:g.duration,summary:g.summary,child_id:g.child_id}),i++;let E={step:g.index+1,status:g.status==="passed"?"done":"failed",remark:g.summary??""};g.child_id&&(E.child_id=g.child_id),Kt(E);let h=f?Math.max(0,c-1):0;t?.onStepEnd?.(g.index,h);break}case"bifurcation":{let g=d,E=g.flows??[],h=g.count??E.length;(g.is_single_flow??h<=1)||(l=E,f=!0,c=0),Kt({type:"bifurcation",flows:E,count:h});break}case"ask_user":{let g=d;Kt({type:"ask_user",question:g.question,step_index:g.step_index,...g.options?{options:g.options}:{}});break}case"run_end":{s=d;break}case"error":{a=!0,Kt({type:"error",message:d.message});break}default:break}return r.close(),await n.exited,{lastRunEnd:s,stepsTotal:i,hadError:a,bifurcationFlows:l}}var Pt=class extends Error{constructor(t,n){super(t);this.code=n;this.name="AuthError"}};async function vi(o){let{creds:e,env:t,usernameFlag:n,accessKeyFlag:r,log:s}=o,a=null,i=null;if(n&&r)a={username:n,access_key:r},s("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:n});else{let E=e.resolveAuth();E?.method==="basic"&&(a={username:E.username,access_key:E.access_key},s("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:E.username}))}if(!a){let{credentials:E,profile:h}=e.getActiveCredentials();if(!E)throw new Pt("Not authenticated \u2014 no credentials found","not_authenticated");if(i=E.access_token,E.expires_at-Date.now()/1e3<300)try{let _=await On({creds:e,profile:h,env:t,credentials:E});_&&(i=_.accessToken,s("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(_){let w=_ instanceof Error?_.message:String(_);throw s("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:w}),new Pt(`Token refresh failed: ${w}`,"refresh_failed")}}let l=ie(t),c=async()=>i,f=a?{username:a.username,access_key:a.access_key}:null,d=new Lt(l.controllerBaseUrl,c,f,s),g=await d.resolve();return g&&!a&&(a={username:g.username,access_key:g.access_key},s("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:g.username})),{basicAuth:a,token:i,resolver:d,resolvedCreds:g}}import{mkdtempSync as Rl,rmSync as kl}from"fs";import{join as Tl}from"path";import{tmpdir as Al}from"os";async function xi(o){if(o.cft)return{instance:null,tempDir:null};if(o.wsEndpoint)return{wsEndpoint:o.wsEndpoint,instance:null,tempDir:null};if(o.cdpEndpoint){let r=await fetch(`${o.cdpEndpoint}/json/version`);if(!r.ok)throw new Error(`CDP endpoint not reachable: ${o.cdpEndpoint} (${r.status})`);return{cdpEndpoint:o.cdpEndpoint,instance:null,tempDir:null}}let e,t=null;if(o.config.chrome_profile_path)e=o.config.chrome_profile_path.replace("~",process.env.HOME??"~");else{t=Rl(Tl(Al(),"kane-clean-")),e=t;let r=t;Qe("tempDir",()=>{try{kl(r,{recursive:!0,force:!0})}catch{}})}let n=await Bn({userDataDir:e,width:o.config.window_size.width,height:o.config.window_size.height,startUrl:o.startUrl,headless:o.headless});return{cdpEndpoint:n.cdpEndpoint,instance:n,tempDir:t}}function bi(o){let e=new hi;if(e.name("kane-cli").version(ft),o[0]==="--help"||o[0]==="-h"||o[0]==="help"){(async()=>{let{HelpView:n}=await import("./HelpView-WVCLJJMT.js"),{render:r}=await import("./build-MFETN2BY.js"),s=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=r(s.default.createElement(n));await a(),ne(0,"Help displayed")})();return}e.command("login").option("--oauth","Login via OAuth (opens browser)").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").addOption(new Wt("--env <name>","Environment (prod or stage)").default("prod").hideHelp()).option("--profile <name>","Profile name","default").option("--project-id <id>","Project ID (skip picker)").option("--folder-id <id>","Folder ID (skip picker)").addOption(new Wt("--model <name>","Model").default("v16-alpha").hideHelp()).option("--chrome-profile <path>","Chrome profile path").action(async n=>{let r=new ye,s=new Ke,a=n.env,i=n.profile;if(!process.stdin.isTTY||n.oauth||n.username){if(r.setDefaultEnv(a),n.oauth?(await new ot(i,a,r).login(),console.log(`Logged in as ${i} [${a}] via OAuth`)):n.username&&n.accessKey?(r.saveBasicAuth(i,a,{username:n.username,access_key:n.accessKey}),console.log(`Logged in as ${i} [${a}] via basic auth`)):(console.error("Provide --oauth, or --username and --access-key"),ne(1,"Missing --oauth or credentials for login")),r.setActiveProfile(i),s.set("model",n.model),n.chromeProfile&&s.set("chrome_profile_path",n.chromeProfile),n.projectId)s.set("project_id",n.projectId),console.log(`Project set to ${n.projectId}`);else try{let Y=r.resolveAuth();if(Y){let B=ie(a),P,R;if(Y.method==="basic")P=Y.username,R=Y.access_key;else{let v=r.getActiveCredentials(),C=r.loadClient(v.profile,v.env),U=await new qe(a).refreshToken(v.credentials.refresh_token,C.client_id),{ControllerClient:H}=await import("./controller-client-7BIK5FYL.js"),Q=await new H(B.controllerBaseUrl,U.access_token).getTmsCredentials();P=Q.username,R=Q.access_key}let{TmsClient:G}=await import("./tms-client-T4HO73MT.js"),b=(await new G(ie(a).tmsBaseUrl,P,R).listProjects()).find(v=>v.name.toLowerCase().includes("kaneai"));b&&(s.set("project_id",b.project_id),console.log(`Auto-selected project: ${b.name} (${b.project_id})`))}}catch(Y){console.warn(`Could not auto-select project: ${Y instanceof Error?Y.message:Y}`)}n.folderId&&(s.set("folder_id",n.folderId),console.log(`Folder set to ${n.folderId}`)),s.set("setup_complete",!0),console.log("Setup complete.");return}let{LoginWizard:l}=await import("./LoginWizard-ZGXMGBNJ.js"),{ProjectPicker:c}=await import("./ProjectPicker-3WKERA5V.js"),{FolderPicker:f}=await import("./FolderPicker-VVQBL3YD.js"),{AuthResolver:d}=await import("./resolver-QLDOAIXU.js"),{render:g}=await import("./build-MFETN2BY.js"),E=await import("./react-QWOAB3TB.js"),h=!1;if(await new Promise(Y=>{let{unmount:B}=g(E.default.createElement(l,{devMode:process.env.KANE_DEV_MODE==="1",profiles:r.listProfiles(),onBasicLogin:(P,R,G,Z)=>{r.saveBasicAuth(P,R,{username:G,access_key:Z}),r.setActiveProfile(P),r.setDefaultEnv(R),a=R,i=P},onOAuthLogin:async(P,R)=>{r.setDefaultEnv(R),await new ot(P,R,r).login(),a=R,i=P},onComplete:()=>{B(),Y()},onCancel:()=>{h=!0,B(),Y()}}))}),h)return;let y=ie(a),_=r.loadBasicAuth(i,a),w=_?null:r.loadCredentials(i,a),I=async()=>w?.access_token??null,z=new d(y.controllerBaseUrl,I,_);if(await z.resolve(),!z.cached){console.log("Could not resolve credentials for project setup.");return}let ce=null;await new Promise(Y=>{let{unmount:B}=g(E.default.createElement(c,{resolver:z,currentProjectId:s.load().project_id,env:a,onSelect:(P,R)=>{s.set("project_id",P),s.set("project_name",R),ce=P,console.log(`Project set to ${R} (${P})`),B(),Y()},onCancel:()=>{B(),Y()}}))}),ce&&(await new Promise(Y=>{let{unmount:B}=g(E.default.createElement(f,{resolver:z,projectId:ce,currentFolderId:s.load().folder_id,env:a,onSelect:(P,R)=>{s.set("folder_id",P),s.set("folder_name",R),console.log(`Folder set to ${R} (${P})`),B(),Y()},onCancel:()=>{B(),Y()}}))}),s.set("setup_complete",!0),ne(0,"Login setup complete"))}),e.command("logout").action(async()=>{let n=new ye,r=n.getActiveProfile();if(!r){console.log("No active profile to logout");return}let s=n.getDefaultEnv(),a=await Dn(n,r,s);a.switchedTo?console.log(`Logged out ${a.profile} [${a.env}]. Switched to ${a.switchedTo.profile} [${a.switchedTo.env}]`):console.log(`Logged out ${a.profile} [${a.env}]. No profiles remaining.`)}),e.command("whoami").option("--profile <name>","Profile name").action(async n=>{let r=new ye,s=n.profile??r.getActiveProfile()??"default",a=r.getDefaultEnv(),i=r.loadCredentials(s,a),l=r.loadBasicAuth(s,a),c="none",f,d,g;if(l)c="basic",f=l.username;else if(i){c="oauth";let w=i.expires_at,I=Date.now()/1e3;d=w>I?"valid":"expired",g=new Date(w*1e3).toISOString().slice(0,10)}else d="missing";let{WhoamiView:E}=await import("./WhoamiView-CY65SJE3.js"),{render:h}=await import("./build-MFETN2BY.js"),y=await import("./react-QWOAB3TB.js"),{waitUntilExit:_}=h(y.default.createElement(E,{profile:s,env:a,authenticated:c!=="none",authMethod:c,username:f,tokenStatus:d,expiresAt:g}));await _()}),e.command("config <action> [value]").action(async(n,r)=>{let s=new Ke,a=new ye;if(n==="show"){let i=s.load(),l=a.getActiveProfile()??"default",c=a.getDefaultEnv(),f=a.loadBasicAuth(l,c),d=a.loadCredentials(l,c),g=f?`basic (${f.username})`:d?"oauth":"not configured",{ConfigView:E}=await import("./ConfigView-MTU2VXM3.js"),{render:h}=await import("./build-MFETN2BY.js"),y=await import("./react-QWOAB3TB.js"),{waitUntilExit:_}=h(y.default.createElement(E,{model:i.model,authLabel:g,profile:l,env:c,defaultUrl:Ge,projectId:i.project_id,projectName:i.project_name,folderId:i.folder_id,windowSize:`${i.window_size.width}x${i.window_size.height}`,chromeProfile:i.chrome_profile_path,setupComplete:i.setup_complete}));await _()}else if(n==="set-window"&&r){let i=r.split("x").map(Number),[l,c]=i;!l||!c||!Number.isInteger(l)||!Number.isInteger(c)?console.error("Invalid format. Use: kane-cli config set-window WIDTHxHEIGHT"):l<800||l>3840?console.error(`Width must be between 800 and 3840 (got ${l})`):c<600||c>2160?console.error(`Height must be between 600 and 2160 (got ${c})`):(s.set("window_size",{width:l,height:c}),console.log(`Window size set to ${l}x${c}`))}else if(n==="chrome-profile"){if(r||!process.stdin.isTTY){r||(console.error("Usage: kane-cli config chrome-profile <path>"),ne(1,"Missing chrome-profile path")),s.set("chrome_profile_path",r),console.log(`Chrome profile set to ${r}`);return}let{ChromeProfilePicker:i}=await import("./ChromeProfilePicker-GFXYO62T.js"),{render:l}=await import("./build-MFETN2BY.js"),c=await import("./react-QWOAB3TB.js");await new Promise(f=>{let{unmount:d}=l(c.default.createElement(i,{currentPath:s.load().chrome_profile_path,onSelect:g=>{s.set("chrome_profile_path",g),console.log(`Chrome profile set to ${g}`),d(),f()},onCancel:()=>{d(),f()}}))})}else if(n==="project"){if(r||!process.stdin.isTTY){r||(console.error("Usage: kane-cli config project <project-id>"),ne(1,"Missing project ID")),s.set("project_id",r),console.log(`Project set to ${r}`);return}let i=a.getDefaultEnv(),l=ie(i),c=a.loadBasicAuth(a.getActiveProfile()??"default",i);if(!c){console.log("Login first to browse projects");return}let{ProjectPicker:f}=await import("./ProjectPicker-3WKERA5V.js"),{AuthResolver:d}=await import("./resolver-QLDOAIXU.js"),{render:g}=await import("./build-MFETN2BY.js"),E=await import("./react-QWOAB3TB.js"),h=new d(l.controllerBaseUrl,async()=>null,c);await h.resolve(),await new Promise(y=>{let{unmount:_}=g(E.default.createElement(f,{resolver:h,currentProjectId:s.load().project_id,env:i,onSelect:(w,I)=>{s.set("project_id",w),s.set("project_name",I),console.log(`Project set to ${I} (${w})`),_(),y()},onCancel:()=>{_(),y()}}))})}else if(n==="folder"){if(r||!process.stdin.isTTY){if(r||(console.error("Usage: kane-cli config folder <folder-id>"),ne(1,"Missing folder ID")),!s.load().project_id){console.log("Select a project first: kane-cli config project <id>");return}s.set("folder_id",r),console.log(`Folder set to ${r}`);return}let i=s.load();if(!i.project_id){console.log("Select a project first: kane-cli config project");return}let l=a.getDefaultEnv(),c=ie(l),f=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!f){console.log("Login first to browse folders");return}let{FolderPicker:d}=await import("./FolderPicker-VVQBL3YD.js"),{AuthResolver:g}=await import("./resolver-QLDOAIXU.js"),{render:E}=await import("./build-MFETN2BY.js"),h=await import("./react-QWOAB3TB.js"),y=new g(c.controllerBaseUrl,async()=>null,f);await y.resolve(),await new Promise(_=>{let{unmount:w}=E(h.default.createElement(d,{resolver:y,projectId:i.project_id,currentFolderId:i.folder_id,env:l,onSelect:(I,z)=>{s.set("folder_id",I),s.set("folder_name",z),console.log(`Folder set to ${z} (${I})`),w(),_()},onCancel:()=>{w(),_()}}))})}else console.log("Usage: kane-cli config show|set-window|chrome-profile|project|folder")}),e.command("run").argument("<objective>","Test objective (use {{var}} to reference variables)").option("--headless","Run Chrome in headless mode").option("--max-steps <n>","Maximum agent steps","30").option("--timeout <seconds>","Kill run after N seconds").option("--cdp-endpoint <url>","Connect to existing Chrome CDP endpoint").option("--ws-endpoint <url>","Connect via Playwright WebSocket (e.g. LambdaTest wss:// URL)").option("--global-context <file>",`Override global context markdown (default: ${Ot(ve,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new Wt("--model <name>","Model override").hideHelp()).option("--variables <json>",`Inline variables JSON, e.g. '{"user": {"value": "alice"}}'`).option("--variables-file <path>","Load variables from a JSON file").option("--session-context <json>","Session context JSON (prior runs)").addOption(new Wt("--cft","Use Playwright Chromium instead of managed Chrome").hideHelp()).option("--username <user>","Basic auth username (skip OAuth)").option("--access-key <key>","Basic auth access key (skip OAuth)").option("--env <name>","Environment (prod or stage)").option("--agent","Agent mode: plain NDJSON output, no colors/UI").option("--task-skills","Enable domain-specific task skills (experimental)").addOption(new Wt("--local","Skip TMS integration (no uploads, no variables/secrets push)").hideHelp()).option("--code-export","Generate code export after upload").addHelpText("after",`
46
60
  Variables:
47
61
  Variables are loaded in order (later wins):
48
- 1. Global: ${Qe(_e,"variables")}/*.json
62
+ 1. Global: ${Ot(ve,"variables")}/*.json
49
63
  2. Local: {cwd}/.testmuai/variables/*.json
50
64
  3. File: --variables-file <path>
51
65
  4. Inline: --variables '{"key": {"value": "...", "secret": false}}'
@@ -60,17 +74,16 @@ Variables:
60
74
 
61
75
  Context Files:
62
76
  Context files provide additional instructions to the agent.
63
- Global: ${Qe(_e,"global-memory.md")}
77
+ Global: ${Ot(ve,"global-memory.md")}
64
78
  Local: {cwd}/.testmuai/context.md
65
79
 
66
80
  Override with --global-context / --local-context flags.
67
- `).action(async(r,n)=>{let s=new Ee,o=new et().load();!o.setup_complete&&!(n.username&&n.accessKey)&&(console.error("First-time setup required. Run: kane-cli setup --auth-method <oauth|basic>"),process.exit(1));let l=`${s.getActiveProfile()??"no profile"}/${s.getDefaultEnv()}`,c=[],d=n.env??s.getDefaultEnv(),h,x=!1,S=n.username,p=n.accessKey;if(n.username&&n.accessKey)x=!0,c.push(`Using basic auth (${n.username})`);else{let E=s.resolveAuth();E?.method==="basic"&&(x=!0,S=E.username,p=E.access_key,c.push(`Using basic auth from config (${E.username})`))}if(!x){let{credentials:E,profile:ie}=s.getActiveCredentials();if(E||(console.error("Not authenticated. Run: kane-cli login"),process.exit(2)),h=E.access_token,E.expires_at-Date.now()/1e3<300){let ne=s.loadClient(ie,d);if(ne)try{let me=await new Ge(d).refreshToken(E.refresh_token,ne.client_id);h=me.access_token,s.saveCredentials(ie,d,{access_token:h,refresh_token:me.refresh_token,expires_at:Math.floor(Date.now()/1e3)+me.expires_in,scope:me.scope})}catch{console.error("Token refresh failed. Run: kane-cli login"),process.exit(2)}}}let b=async()=>h??null,g=x&&S&&p?{username:S,access_key:p}:null,w=null,N=[],W=E=>{w?w(E):N.push(E)},Q=new cn(ce(d).controllerBaseUrl,b,g,W),te=await Q.resolve();te&&(x||(x=!0,S=te.username,p=te.access_key,c.push(`Resolved basic auth (${te.username})`)));let L=n.url??o.default_url,M=Qe(_e,"variables"),A=Qe(process.cwd(),".testmuai","variables"),X=Ln(M,A,E=>console.error(E)),f=n.variablesFile?ro(n.variablesFile):{},k=n.variables?so(n.variables):{},y={...X,...f,...k},C;if(n.sessionContext)try{C=JSON.parse(n.sessionContext)}catch{console.error("Invalid --session-context JSON"),process.exit(2)}let P=n.globalContext??Qe(_e,"global-memory.md"),j=n.localContext??Qe(process.cwd(),".testmuai","context.md"),F=Zt(P),Z=Zt(j),Y,ue=null,oe=null;if(n.cft)c.push("CfT mode: Playwright will manage its own browser");else if(n.wsEndpoint)Y=n.wsEndpoint,c.push(`Playwright WS endpoint (${Y.slice(0,60)}...)`);else if(n.cdpEndpoint){try{let E=await fetch(`${n.cdpEndpoint}/json/version`);if(!E.ok)throw new Error(`CDP returned ${E.status}`)}catch{console.error(`CDP endpoint not reachable: ${n.cdpEndpoint}`),process.exit(2)}Y=n.cdpEndpoint,c.push(`CDP connected (${Y})`)}else{let E;if(o.chrome_profile_path)E=o.chrome_profile_path.replace("~",process.env.HOME??"~");else{let{mkdtempSync:ie}=await import("fs"),{tmpdir:J}=await import("os");oe=ie(Qe(J(),"kane-clean-")),E=oe}c.push("Starting Chrome...");try{ue=await Bn({userDataDir:E,width:o.window_size.width,height:o.window_size.height,headless:n.headless,startUrl:L})}catch(ie){console.error(`Chrome failed: ${ie instanceof Error?ie.message:ie}`),process.exit(2)}Y=ue.cdpEndpoint,c.push(`Chrome ready (${Y})`)}let Te=Object.keys(y).length>0,{variables:de,objective:zt,keyMap:sn}=Te?Mn(y,r):{variables:{},objective:r,keyMap:{}},Vt=te?String(te.org_id):"",St=Object.entries(y).filter(([,E])=>E.secret);if(!n.local&&St.length>0&&x&&S&&p){let E=ce(d),ie=new en(E.secretsBaseUrl);for(let[J,ne]of St)ie.pushSecret({secretKey:J,secretValue:ne.value,username:S,accessKey:p,orgId:Vt}).then(()=>console.error(`Secret pushed: ${J}`)).catch(ye=>console.error(`Secret push failed (${J}): ${ye}`))}let fe={},nt=Object.entries(y).filter(([,E])=>!E.secret);if(!n.local&&nt.length>0&&x&&S&&p){let E=ce(d),ie=new tn(E.tmsBaseUrl,S,p);for(let[J,ne]of nt)try{let ye=await ie.upsertVariable({name:J,value:ne.value});fe[J]=ye.id,console.error(`Variable pushed: ${J} (id=${ye.id})`)}catch(ye){console.error(`Variable push failed (${J}): ${ye}`)}}let q=new Qt;q.start({model:n.model??o.model,environment:d,profile:s.getActiveProfile()}),w=E=>q.log(E);for(let E of N)q.log(E);N.length=0;let $={objective:zt,...L?{url:L}:{},model:n.model??o.model,...n.wsEndpoint?{ws_endpoint:Y}:Y?{cdp_endpoint:Y}:{},width:o.window_size.width,height:o.window_size.height,session_id:q.sessionId,run_index:0,stream:!0,...x&&S&&p?{username:S,access_key:p}:h?{auth:{type:"bearer",token:h}}:{},headless:n.headless??!1,max_steps:parseInt(n.maxSteps,10),disable_ask_user:!process.stdin.isTTY,variables:Object.keys(de).length>0?de:void 0,global_context:F??void 0,local_context:Z??void 0,enable_task_skills:n.taskSkills??!1,session_context:C},Be=null;if(!n.local)try{let{ControllerClient:E}=await import("./controller-client-PS5GDXE3.js"),ie;if(x&&S&&p)ie={username:S,accessKey:p};else if(h)ie=h;else throw new Error("No auth available");let ne=await new E(ce(d).controllerBaseUrl,ie).getScreenshotSas();q.setScreenshotSas(ne),Be=new nn(ne,3),q.log(`SCREENSHOT_SAS fetched OK base_url=${ne.base_url} container=${ne.container} expiry=${ne.expiry}`)}catch(E){q.log(`SCREENSHOT_SAS failed: ${E instanceof Error?E.message:String(E)}`)}let bn=Be?(E,ie)=>{try{let J=ie,ne=Qe(q.sessionDir,"runs",String(J),"run-test");if(!vn(ne)){q.log(`SCREENSHOT_UPLOAD skip step=${E} reason=runsDir_not_found path=${ne}`);return}let ye=ne;if(vn(Qe(ne,"screenshots")))ye=ne;else{let ge=Ra(ne).filter(pe=>vn(Qe(ne,pe,"screenshots")));if(ge.length===0){q.log(`SCREENSHOT_UPLOAD skip step=${E} reason=no_screenshots_dir`);return}ye=Qe(ne,ge[0])}let me=Qe(ye,"screenshots",`step_${String(E).padStart(3,"0")}.png`),ze=Qe(ye,"actions.ndjson");if(!vn(me)){q.log(`SCREENSHOT_UPLOAD skip step=${E} reason=screenshot_not_found path=${me}`);return}if(!vn(ze)){q.log(`SCREENSHOT_UPLOAD skip step=${E} reason=ndjson_not_found path=${ze}`);return}let re=ko(ze,"utf-8").trim().split(`
68
- `),le=re[re.length-1];if(!le){q.log(`SCREENSHOT_UPLOAD skip step=${E} reason=ndjson_empty`);return}let je=JSON.parse(le);if(je.action_id){let ge=ko(me);Be.enqueue(je.action_id,ge),q.log(`SCREENSHOT_UPLOAD enqueued step=${E} action_id=${je.action_id} size=${ge.length}`)}else q.log(`SCREENSHOT_UPLOAD skip step=${E} reason=no_action_id`)}catch(J){q.log(`SCREENSHOT_UPLOAD error step=${E}: ${J instanceof Error?J.message:String(J)}`)}}:void 0;if(n.agent){let E=le=>{process.stdout.write(JSON.stringify(le)+`
69
- `)},ie=await Eo($,{environment:d},{onStepEnd:bn}),{lastRunEnd:J,stepsTotal:ne,hadError:ye,bifurcationFlows:me}=ie;if(J){let le=J.total_runs??1,je=J.run_dir,ge,pe;if(le>1&&je){let{dirname:ut,join:kt}=await import("path"),Rt=ut(je);ge=Array.from({length:le},(At,rt)=>kt(Rt,String(rt))),me&&me.length===le&&(pe=me)}q.addRunResult({index:0,objective:r,summary:J.summary,status:J.status,context:J.context??{memory:{},variables:{},pointer:""},run_dir:je,run_dirs:ge,flow_objectives:pe},J.total_runs)}if(ue&&ue.kill(),oe)try{let{rmSync:le}=await import("fs");le(oe,{recursive:!0,force:!0})}catch{}let ze;if(q.log(`DIRECT_UPLOAD agent_mode=true lastRunEnd=${!!J} opts.local=${!!n.local}`),J&&!n.local)try{let le=ce(d),je=te??await Q.resolve(),ge=je?.username||S,pe=je?.access_key||p;q.log(`DIRECT_UPLOAD tmsUsername=${ge} tmsAccessKey=${!!pe} resolvedCreds=${!!te} basicUsername=${!!S}`);let ut=ge&&pe?{username:ge,accessKey:pe}:h??"";if(ge&&pe){let{TmsClient:kt}=await import("./tms-client-QWVBCUUT.js"),{UploadPipeline:Rt}=await import("./pipeline-7NY333ZT.js"),At=new kt(le.tmsBaseUrl,ge,pe),rt=o.project_id,mt=o.folder_id,Mt=n.url??o.default_url,Oe=null;if(rt)try{Oe=await At.createAtmTest({objective:r.slice(0,100),creation_mode:"KANECLI",playground_disabled:!!o.chrome_profile_path,testURL:Mt??o.default_url??"",project_id:rt,folder_id:mt??"",authoring_version:4})}catch{}let be=q.generateCommitId(),st=x&&S?S:ge,pt=x&&p?p:pe;Be&&await Be.drain();let ot=await new Rt({controllerBaseUrl:le.controllerBaseUrl,tmsBaseUrl:le.tmsBaseUrl,auth:ut,authResolver:Q,sessionId:q.sessionId,sessionDir:q.sessionDir,testId:Oe,commitId:be,projectId:rt,folderId:mt,firstObjective:zt,firstUrl:n.url??o.default_url??"",runDirs:q.getRunDirs(),runObjectives:q.getRunObjectives(),startedAt:q.startedAt,endedAt:new Date().toISOString(),totalSteps:ne,totalDuration:J.duration??0,runStatuses:[J.status],orgId:je?.org_id??0,userId:je?.user_id??0,tmsUsername:st,tmsAccessKey:pt,screenshotBaseUrl:q.screenshotBaseUrl,shareApiBaseUrl:le.shareApiBaseUrl,variables:nt.length>0?Object.fromEntries(nt.map(([ht,_])=>[ht,_])):void 0,variableIds:fe,secrets:St.map(([ht])=>({key_name:ht,scope:"user"})),codeExport:!!n.codeExport,onProgress:()=>{},log:ht=>q.log(ht)}).execute();ot.success&&(ot.testcaseId&&q.setTestcaseId(ot.testcaseId),ot.testcaseId&&ot.shareId&&rt&&(ze=`${le.testManagerUiUrl}/projects/${rt}/test-cases/${ot.testcaseId}/dashboard/share/${ot.shareId}`))}}catch(le){q.log(`DIRECT_UPLOAD agent error: ${le instanceof Error?le.message:String(le)}`)}if(J){let le={...J};ze&&(le.test_url=ze),E(le)}q.finish("complete"),J||process.exit(ye?2:1);let re=J.reason??"";(re.includes("Cancel")||re.includes("Timeout"))&&process.exit(3),J.status==="passed"&&process.exit(0),process.exit(1)}let B=null,K=0,Ct=!1,Gt=null,Et={current:null},{waitUntilExit:ve}=yn(Ro.default.createElement(ao,{config:$,spawnOpts:{environment:d},cancelRef:Et,banner:{model:n.model??o.model,auth:l,status:c},onComplete:E=>{B=E.lastRunEnd,K=E.stepsTotal,Ct=E.hadError,Gt=E.bifurcationFlows},onStepEnd:bn}),{stdout:process.stderr,exitOnCtrlC:!1}),at;if(n.timeout){let E=parseInt(n.timeout,10)*1e3;at=setTimeout(()=>{console.error(`
70
- Timeout: ${n.timeout}s exceeded \u2014 cancelling...`),Et.current?.()},E)}if(await ve(),at&&clearTimeout(at),B){let E=B.total_runs??1,ie=B.run_dir,J,ne;if(E>1&&ie){let{dirname:ye,join:me}=await import("path"),ze=ye(ie);J=Array.from({length:E},(re,le)=>me(ze,String(le))),Gt&&Gt.length===E&&(ne=Gt)}q.addRunResult({index:0,objective:r,summary:B.summary,status:B.status,context:B.context??{memory:{},variables:{},pointer:""},run_dir:ie,run_dirs:J,flow_objectives:ne},B.total_runs)}if(ue&&ue.kill(),oe)try{let{rmSync:E}=await import("fs");E(oe,{recursive:!0,force:!0})}catch{}if(q.log(`DIRECT_UPLOAD ink_mode=true lastEvent=${!!B} opts.local=${!!n.local}`),B&&!n.local)try{let E=ce(d),ie=te??await Q.resolve(),J=ie?.username||S,ne=ie?.access_key||p,ye=ie?.org_id??0,me=ie?.user_id??0;q.log(`DIRECT_UPLOAD tmsUsername=${J} tmsAccessKey=${!!ne} resolvedCreds=${!!te} basicUsername=${!!S} projectId=${o.project_id}`);let ze=J&&ne?{username:J,accessKey:ne}:h??"";if(J&&ne){let{TmsClient:re}=await import("./tms-client-QWVBCUUT.js"),{UploadPipeline:le}=await import("./pipeline-7NY333ZT.js"),je=new re(E.tmsBaseUrl,J,ne),ge=null,pe=o.project_id,ut=o.folder_id,kt=n.url??o.default_url;if(pe)try{ge=await je.createAtmTest({objective:r.slice(0,100),creation_mode:"KANECLI",playground_disabled:!!o.chrome_profile_path,testURL:kt??o.default_url??"",project_id:pe,folder_id:ut,authoring_version:4})}catch(be){console.error(`Test creation failed: ${be}`)}let Rt=q.generateCommitId(),At=x&&S?S:J,rt=x&&p?p:ne;Be&&(q.log("SCREENSHOT_UPLOAD draining queue before pipeline"),await Be.drain(),q.log("SCREENSHOT_UPLOAD queue drained"));let mt=new le({controllerBaseUrl:E.controllerBaseUrl,tmsBaseUrl:E.tmsBaseUrl,auth:ze,authResolver:Q,sessionId:q.sessionId,sessionDir:q.sessionDir,testId:ge,commitId:Rt,projectId:pe,folderId:ut,firstObjective:zt,firstUrl:n.url??o.default_url??"",runDirs:q.getRunDirs(),runObjectives:q.getRunObjectives(),startedAt:new Date().toISOString(),endedAt:new Date().toISOString(),totalSteps:K,totalDuration:B.duration??0,runStatuses:[B.status],orgId:ye,userId:me,tmsUsername:At,tmsAccessKey:rt,screenshotBaseUrl:q.screenshotBaseUrl,shareApiBaseUrl:E.shareApiBaseUrl,variables:nt.length>0?Object.fromEntries(nt.map(([be,st])=>[be,st])):void 0,variableIds:fe,secrets:St.map(([be])=>({key_name:be,scope:"user"})),codeExport:!!n.codeExport,onProgress:()=>{},log:be=>q.log(be)}),{renderUploadProgress:Mt}=await import("./CliUploadProgress-QF57Z3FD.js"),Oe=await Mt(mt,be=>{if(be.testcaseId&&be.shareId&&pe)return`${E.testManagerUiUrl}/projects/${pe}/test-cases/${be.testcaseId}/dashboard/share/${be.shareId}`});if(Oe.success){Oe.testcaseId&&q.setTestcaseId(Oe.testcaseId);let be=Oe.testcaseId&&Oe.shareId&&pe?`${E.testManagerUiUrl}/projects/${pe}/test-cases/${Oe.testcaseId}/dashboard/share/${Oe.shareId}`:void 0,st=Oe.testcaseId&&pe?`${E.testManagerUiUrl}/projects/${pe}/test-cases/${Oe.testcaseId}/dashboard?type=summary&agentView=true&fqdn=summary-page`:void 0;if(be||st||Oe.codeExportDir){let{LinksBox:pt}=await import("./LinksBox-623NMFSA.js"),{render:_n}=await import("./build-MFETN2BY.js"),ot=await import("./react-QWOAB3TB.js"),{waitUntilExit:ht}=_n(ot.default.createElement(pt,{shareableLink:be,testCaseLink:st,codeExportDir:Oe.codeExportDir}),{stdout:process.stderr});await ht()}}if(ge){let{renderFeedbackPrompt:be}=await import("./CliFeedbackPrompt-RIIDDIY5.js"),st=await be();if(st)try{let{TmsClient:pt}=await import("./tms-client-QWVBCUUT.js");await new pt(E.tmsBaseUrl,At,rt).submitFeedback({instruction_id:"",test_id:ge,feedback_type:st,mode:"human"}),q.log(`FEEDBACK submitted type=${st}`)}catch(pt){q.log(`FEEDBACK failed: ${pt}`)}}}}catch(E){q.log(`DIRECT_UPLOAD ink error: ${E instanceof Error?E.stack??E.message:String(E)}`),console.error(`Upload failed: ${E}`)}q.finish("complete"),B||process.exit(Ct?2:1);let Lt=B.reason??"";(Lt.includes("Cancel")||Lt.includes("Timeout"))&&process.exit(3),B.status==="passed"&&process.exit(0),process.exit(1)}),e.command("profiles").action(async()=>{let r=new Ee,{ProfilesView:n}=await import("./ProfilesView-DBNO4RSU.js"),{render:s}=await import("./build-MFETN2BY.js"),a=await import("./react-QWOAB3TB.js");await new Promise(o=>{let{unmount:l}=s(a.default.createElement(n,{creds:r,onSwitch:(c,d)=>{r.setActiveProfile(c),r.setDefaultEnv(d),console.log(`Switched to ${c} [${d}]`)},onCancel:()=>{l(),o()}}))})}),e.command("setup").option("--auth-method <method>","Auth method: oauth or basic").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").option("--model <name>","Model","v16-alpha").option("--chrome-profile <path>","Chrome profile path").option("--project-id <id>","Project ID for testing mode").option("--default-url <url>","Default URL").option("--env <name>","Environment (prod or stage)").action(async r=>{let n=new et,s=new Ee;r.env&&(s.setDefaultEnv(r.env),console.log(`Environment set to ${r.env}`)),(!r.authMethod||!["oauth","basic"].includes(r.authMethod))&&(console.error("--auth-method is required: oauth or basic"),process.exit(1)),r.authMethod==="basic"&&(!r.username||!r.accessKey)&&(console.error("--username and --access-key are required for basic auth"),process.exit(1)),n.set("model",r.model);let a="default";s.setActiveProfile(a);let o=s.getDefaultEnv();if(r.authMethod==="basic"?(s.saveBasicAuth(a,o,{username:r.username,access_key:r.accessKey}),console.log(`Basic auth saved for ${a}/${o}`)):(await new bt(a,o,s).login(),console.log(`OAuth login complete for ${a}/${o}`)),r.chromeProfile&&n.set("chrome_profile_path",r.chromeProfile),r.projectId)n.set("project_id",r.projectId);else try{let l=s.resolveAuth();if(l){let c=s.getDefaultEnv(),d=ce(c),h,x;if(l.method==="basic")h=l.username,x=l.access_key;else{let w=new Ge(c),N=s.getActiveCredentials(),W=s.loadClient(N.profile,N.env),Q=await w.refreshToken(N.credentials.refresh_token,W.client_id),{ControllerClient:te}=await import("./controller-client-PS5GDXE3.js"),M=await new te(d.controllerBaseUrl,Q.access_token).getTmsCredentials();h=M.username,x=M.access_key}let{TmsClient:S}=await import("./tms-client-QWVBCUUT.js"),g=(await new S(d.tmsBaseUrl,h,x).listProjects()).find(w=>w.name.toLowerCase().includes("kaneai"));g&&(n.set("project_id",g.project_id),console.log(`Auto-selected project: ${g.name} (${g.project_id})`))}}catch(l){console.warn(`Could not auto-select project: ${l instanceof Error?l.message:l}`)}r.defaultUrl?n.set("default_url",r.defaultUrl):n.set("default_url","https://kaneai-playground.lambdatest.io"),n.set("setup_complete",!0),console.log("Setup complete.")}),e.command("feedback").requiredOption("--test-id <id>","Test ID").requiredOption("--feedback-type <type>","Feedback type: positive or negative").option("--details <text>","Feedback details (max 500 characters)").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").option("--env <name>","Environment (prod or stage)").action(async r=>{r.feedbackType!=="positive"&&r.feedbackType!=="negative"&&(console.error('Error: --feedback-type must be "positive" or "negative"'),process.exit(1)),r.details&&r.details.length>500&&(console.error("Error: --details must be 500 characters or fewer"),process.exit(1));let n=new Ee,s=r.env??n.getDefaultEnv(),a=ce(s),o=!1,l=r.username,c=r.accessKey,d;if(r.username&&r.accessKey)o=!0;else{let w=n.resolveAuth();w?.method==="basic"&&(o=!0,l=w.username,c=w.access_key)}if(!o){let{credentials:w}=n.getActiveCredentials();w||(console.error("Not authenticated. Run: kane-cli login"),process.exit(2)),d=w.access_token}let h=async()=>d??null,x=o&&l&&c?{username:l,access_key:c}:null,p=await new cn(a.controllerBaseUrl,h,x).resolve(),b=p?.username??l,g=p?.access_key??c;(!b||!g)&&(console.error(JSON.stringify({error:"Could not resolve TMS credentials"})),process.exit(1));try{let{TmsClient:w}=await import("./tms-client-QWVBCUUT.js"),W=await new w(a.tmsBaseUrl,b,g).submitFeedback({instruction_id:"",test_id:r.testId,feedback_type:r.feedbackType,details:r.details,mode:"agent"});console.log(JSON.stringify(W)),process.exit(0)}catch(w){console.error(JSON.stringify({error:w instanceof Error?w.message:String(w)})),process.exit(1)}}),e.command("help").action(()=>{e.help()}),e.command("update").description("Update kane-cli to the latest version").action(async()=>{let{checkForUpdate:r}=await import("./version-check-KS7CP3M5.js"),{runSelfUpdate:n}=await import("./updater-H5HYMYRG.js");console.log("Checking for updates...");let s=await r();if(!s){console.log(`Already on latest version (${Pt})`);return}console.log(`Update available: ${s.current} \u2192 ${s.latest}
71
- `),console.log("Updating @testmuai/kane-cli...");let a=await n(o=>{process.stdout.write(o)});a.success?(console.log(`
81
+ `).action(async(n,r)=>{try{let s=new ye,i=new Ke().load();!i.setup_complete&&!(r.username&&r.accessKey)&&(console.error("First-time setup required. Run: kane-cli login --oauth, or kane-cli login --username <user> --access-key <key>"),ne(1,"First-time setup required"));let l=`${s.getActiveProfile()??"no profile"}/${s.getDefaultEnv()}`,c=[],f=r.env??s.getDefaultEnv(),d=null,g=[],E=(V,ee,se,pe)=>{d?d(V,ee,se,pe):g.push([V,ee,se,pe])},h;try{h=await vi({creds:s,env:f,usernameFlag:r.username,accessKeyFlag:r.accessKey,log:E})}catch(V){throw V instanceof Pt&&(console.error(V.code==="not_authenticated"?"Not authenticated. Run: kane-cli login":"Token refresh failed. Run: kane-cli login"),ne(2,V.code==="not_authenticated"?"Not authenticated":"Token refresh failed")),V}let y=!!h.basicAuth,_=h.basicAuth?.username,w=h.basicAuth?.access_key,I=h.token,z=h.resolver,ce=h.resolvedCreds;h.basicAuth&&c.push(`Auth: ${h.basicAuth.username}`);let Y=Ge,B=Wn({objective:n,globalDir:Ot(ve,"variables"),localDir:Ot(process.cwd(),".testmuai","variables"),file:r.variablesFile,inline:r.variables,onLoadError:V=>console.error(V)}),P;if(r.sessionContext)try{P=JSON.parse(r.sessionContext)}catch{console.error("Invalid --session-context JSON"),ne(2,"Invalid --session-context JSON")}let R=r.globalContext??Ot(ve,"global-memory.md"),G=r.localContext??Ot(process.cwd(),".testmuai","context.md"),Z=Vt(R),p=Vt(G),b;try{b=await xi({config:i,startUrl:Y??void 0,headless:r.headless,cft:r.cft,wsEndpoint:r.wsEndpoint,cdpEndpoint:r.cdpEndpoint})}catch(V){console.error(`Chrome failed: ${V instanceof Error?V.message:V}`),ne(2,`Chrome failed: ${V instanceof Error?V.message:V}`)}b.instance&&Qe("chrome",()=>{b.instance.kill()}),r.cft?c.push("CfT mode: Playwright will manage its own browser"):r.wsEndpoint?c.push(`Playwright WS endpoint (${r.wsEndpoint.slice(0,60)}...)`):r.cdpEndpoint?c.push(`CDP connected (${r.cdpEndpoint})`):b.cdpEndpoint&&c.push(`Chrome ready (${b.cdpEndpoint})`);let v=new Ft;v.start({model:r.model??i.model,environment:f,profile:s.getActiveProfile()}),d=(V,ee,se,pe)=>v.log(V,ee,se,pe);for(let V of g)v.log(...V);if(g.length=0,h.resolvedCreds){let{createRemoteLogger:V}=await import("./logging-O5R56LPM.js"),{getMachineId:ee}=await import("./machine-id-DZN4MYOO.js"),se=V({sessionId:v.sessionId,identity:{org_id:String(h.resolvedCreds.org_id??""),user_id:String(h.resolvedCreds.user_id??""),machine_id:ee()},environment:f,getToken:async()=>h.token});v.setRemoteLogger(se),se.start(),Qe("remote-logger",()=>se.shutdownSync()),jn(se)}let C=h.basicAuth&&!r.local?await Kn({variables:B,auth:h.basicAuth,orgId:String(h.resolvedCreds?.org_id??""),env:f,localMode:!!r.local,log:(V,ee,se,pe)=>v.log(V,ee,se,pe)}):{};if(v.setAuteurVariables(B.auteur),v.setFirstRun(n,Ge),!r.local&&h.basicAuth&&i.project_id){let V=ie(f),ee=await zn({tmsBaseUrl:V.tmsBaseUrl,auth:h.basicAuth,objective:n,url:Ge,projectId:i.project_id,folderId:i.folder_id??"",hasCustomProfile:!!i.chrome_profile_path,log:(se,pe,Ae,We)=>v.log(se,pe,Ae,We)});ee&&v.setTestId(ee)}let $=qn({objective:B.auteurObjective,url:Y??void 0,model:r.model??i.model,chrome:b,auth:h,sessionId:v.sessionId,runIndex:0,windowSize:i.window_size,maxSteps:parseInt(r.maxSteps,10),headless:r.headless,disableAskUser:!process.stdin.isTTY,enableTaskSkills:r.taskSkills,variables:Object.keys(B.auteur).length>0?B.auteur:void 0,globalContext:Z??void 0,localContext:p??void 0,sessionContext:P}),U=null;if(!r.local)try{let{ControllerClient:V}=await import("./controller-client-7BIK5FYL.js"),ee;if(y&&_&&w)ee={username:_,accessKey:w};else if(I)ee=I;else throw new Error("No auth available");let pe=await new V(ie(f).controllerBaseUrl,ee).getScreenshotSas();v.setScreenshotSas(pe),U=new Ht(pe,3,(Ae,We,oe,ge)=>v.log(Ae,We,oe,ge)),v.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched",{base_url:pe.base_url,container:pe.container,expiry:pe.expiry})}catch(V){v.log("warn","SCREENSHOT_SAS_FAIL","Screenshot SAS token fetch failed",{error:V instanceof Error?V.message:String(V)})}let H=U?(V,ee)=>{Nn(v.sessionDir,ee,V,U,(se,pe,Ae,We)=>v.log(se,pe,Ae,We))}:void 0;if(!process.stdin.isTTY&&!r.agent&&(r.agent=!0),r.agent){let V=me=>{process.stdout.write(JSON.stringify(me)+`
82
+ `)},ee=await gi($,{environment:f,log:(me,T,Fe,nt)=>v.log(me,T,Fe,nt)},{onStepEnd:H,onStepLog:(me,T,Fe)=>v.logStep(me,T,Fe)}),{lastRunEnd:se,stepsTotal:pe,hadError:Ae,bifurcationFlows:We}=ee;if(Ae&&v.escalateRun(0),se){let me=rn(se,0,We);v.addRunResult(on(se,n,0,me),se.total_runs)}Je("chrome","Agent run completed");let oe;if(v.log("info","DIRECT_UPLOAD_START","Starting direct upload (agent mode)",{agent_mode:!0,last_run_end:!!se,local:!!r.local}),se&&!r.local)try{let me=ie(f),T=i.project_id;if(h.basicAuth){let{UploadPipeline:Fe}=await import("./pipeline-NXUVAHY5.js");U&&await U.drain();let nt=un({session:v,env:f,auth:h,variables:B,variableIds:C,projectId:T,folderId:i.folder_id,totalSteps:pe,totalDuration:se.duration??0,codeExport:!!r.codeExport,onProgress:()=>{},log:(J,ut,Qn,yt)=>v.log(J,ut,Qn,yt)}),L=await new Fe(nt).execute();L.success&&(L.testcaseId&&v.setTestcaseId(L.testcaseId),L.testcaseId&&L.shareId&&T&&(oe=Nt(me.testManagerUiUrl,T,L.testcaseId,L.shareId)))}}catch(me){v.log("error","DIRECT_UPLOAD_ERROR","Upload failed in agent mode",{error:me instanceof Error?me.message:String(me)})}if(se){let me={...se};oe&&(me.test_url=oe),V(me)}await v.finish("complete"),se||ne(Ae?2:1,"Agent run ended with no result");let ge=se.reason??"";(ge.includes("Cancel")||ge.includes("Timeout"))&&ne(3,`Agent run: ${ge}`),se.status==="passed"&&ne(0,"Agent run passed"),ne(1,"Agent run failed")}let W=null,Q=0,le=!1,Re=null,de={current:null},{waitUntilExit:_t}=hn(wi.default.createElement(Ks,{config:$,spawnOpts:{environment:f,log:(V,ee,se,pe)=>v.log(V,ee,se,pe)},cancelRef:de,banner:{model:r.model??i.model,auth:l,status:c},onComplete:V=>{W=V.lastRunEnd,Q=V.stepsTotal,le=V.hadError,Re=V.bifurcationFlows},onStepEnd:H}),{stdout:process.stderr,exitOnCtrlC:!1}),ct;if(r.timeout){let V=parseInt(r.timeout,10)*1e3;ct=setTimeout(()=>{console.error(`
83
+ Timeout: ${r.timeout}s exceeded \u2014 cancelling...`),de.current?.()},V)}if(await _t(),ct&&clearTimeout(ct),W){let V=rn(W,0,Re);v.addRunResult(on(W,n,0,V),W.total_runs)}if(Je("chrome","Ink run completed"),v.log("info","DIRECT_UPLOAD_START","Starting direct upload (ink mode)",{ink_mode:!0,last_event:!!W,local:!!r.local}),W&&!r.local)try{let V=ie(f),ee=i.project_id;if(h.basicAuth){let{UploadPipeline:se}=await import("./pipeline-NXUVAHY5.js");U&&(v.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot upload queue before pipeline"),await U.drain(),v.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot upload queue drained"));let pe=un({session:v,env:f,auth:h,variables:B,variableIds:C,projectId:i.project_id,folderId:i.folder_id,totalSteps:Q,totalDuration:W.duration??0,codeExport:!!r.codeExport,onProgress:()=>{},log:(ge,me,T,Fe)=>v.log(ge,me,T,Fe)}),Ae=new se(pe),{renderUploadProgress:We}=await import("./CliUploadProgress-DNE54O2E.js"),oe=await We(Ae,ge=>{if(ge.testcaseId&&ge.shareId&&ee)return Nt(V.testManagerUiUrl,ee,ge.testcaseId,ge.shareId)});if(oe.success){oe.testcaseId&&v.setTestcaseId(oe.testcaseId);let ge=oe.testcaseId&&oe.shareId&&ee?Nt(V.testManagerUiUrl,ee,oe.testcaseId,oe.shareId):void 0,me=oe.testcaseId&&ee?Vn(V.testManagerUiUrl,ee,oe.testcaseId):void 0;if(ge||me||oe.codeExportDir){let{LinksBox:T}=await import("./LinksBox-I4PYUQY7.js"),{render:Fe}=await import("./build-MFETN2BY.js"),nt=await import("./react-QWOAB3TB.js"),{waitUntilExit:Bt}=Fe(nt.default.createElement(T,{shareableLink:ge,testCaseLink:me,codeExportDir:oe.codeExportDir}),{stdout:process.stderr});await Bt()}}if(v.testId){let{renderFeedbackPrompt:ge}=await import("./CliFeedbackPrompt-F3ZTTEUY.js"),me=await ge();if(me)try{await Gn({tmsBaseUrl:V.tmsBaseUrl,username:h.basicAuth.username,accessKey:h.basicAuth.access_key,testId:v.testId,feedbackType:me,log:(T,Fe,nt,Bt)=>v.log(T,Fe,nt,Bt)})}catch(T){v.log("warn","FEEDBACK_FAILED","Feedback submission failed",{error:String(T)})}}}}catch(V){v.log("error","DIRECT_UPLOAD_FAILED","Direct upload failed (ink mode)",{error:V instanceof Error?V.stack??V.message:String(V)}),console.error(`Upload failed: ${V}`)}await v.finish("complete"),W||ne(le?2:1,"Run ended with no result");let Dt=W.reason??"";(Dt.includes("Cancel")||Dt.includes("Timeout"))&&ne(3,`Run: ${Dt}`),W.status==="passed"&&ne(0,"Run passed"),ne(1,"Run failed")}catch(s){ne(2,`CLI error: ${s instanceof Error?s.message:String(s)}`)}}),e.command("profiles [action] [name]").option("--env <name>","Environment for switch/delete").action(async(n,r,s)=>{let a=new ye;if(n==="list"||!n&&!process.stdin.isTTY){let f=a.listProfiles();if(f.length===0){console.log("No profiles configured. Run: kane-cli login");return}let d=a.getActiveProfile(),g=a.getDefaultEnv();for(let E of f){let h=E.profile===d&&E.env===g?" (active)":"";console.log(`${E.profile} [${E.env}]${h}`)}return}if(n==="switch"&&r){let f=s?.env??a.getDefaultEnv();a.setActiveProfile(r),a.setDefaultEnv(f),console.log(`Switched to ${r} [${f}]`);return}if(n==="delete"&&r){let f=s?.env??a.getDefaultEnv();a.deleteProfileFull(r,f),console.log(`Deleted profile ${r} [${f}]`);return}process.stdin.isTTY||(console.error("Usage: kane-cli profiles list|switch|delete <name> [--env <env>]"),ne(1,"Invalid profiles usage"));let{ProfilesView:i}=await import("./ProfilesView-AUJOUVYZ.js"),{render:l}=await import("./build-MFETN2BY.js"),c=await import("./react-QWOAB3TB.js");await new Promise(f=>{let{unmount:d}=l(c.default.createElement(i,{creds:a,onSwitch:(g,E)=>{a.setActiveProfile(g),a.setDefaultEnv(E),console.log(`Switched to ${g} [${E}]`)},onCancel:()=>{d(),f()}}))})}),e.command("feedback").requiredOption("--test-id <id>","Test ID").requiredOption("--feedback-type <type>","Feedback type: positive or negative").option("--details <text>","Feedback details (max 500 characters)").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").option("--env <name>","Environment (prod or stage)").action(async n=>{n.feedbackType!=="positive"&&n.feedbackType!=="negative"&&(console.error('Error: --feedback-type must be "positive" or "negative"'),ne(1,'Invalid --feedback-type (must be "positive" or "negative")')),n.details&&n.details.length>500&&(console.error("Error: --details must be 500 characters or fewer"),ne(1,"--details exceeds 500 character limit"));let r=new ye,s=n.env??r.getDefaultEnv(),a=ie(s),i=!1,l=n.username,c=n.accessKey,f;if(n.username&&n.accessKey)i=!0;else{let w=r.resolveAuth();w?.method==="basic"&&(i=!0,l=w.username,c=w.access_key)}if(!i){let{credentials:w}=r.getActiveCredentials();w||(console.error("Not authenticated. Run: kane-cli login"),ne(2,"Not authenticated for feedback")),f=w.access_token}let d=async()=>f??null,g=i&&l&&c?{username:l,access_key:c}:null,h=await new Lt(a.controllerBaseUrl,d,g).resolve(),y=h?.username??l,_=h?.access_key??c;(!y||!_)&&(console.error(JSON.stringify({error:"Could not resolve TMS credentials"})),ne(1,"Could not resolve TMS credentials for feedback"));try{let{TmsClient:w}=await import("./tms-client-T4HO73MT.js"),z=await new w(a.tmsBaseUrl,y,_).submitFeedback({instruction_id:"",test_id:n.testId,feedback_type:n.feedbackType,details:n.details,mode:"agent"});console.log(JSON.stringify(z)),ne(0,"Feedback submitted")}catch(w){console.error(JSON.stringify({error:w instanceof Error?w.message:String(w)})),ne(1,`Feedback failed: ${w instanceof Error?w.message:String(w)}`)}}),e.command("balance").description("Check credit balance").option("--profile <name>","Profile name").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").option("--env <name>","Environment (prod or stage)").action(async n=>{let r=new ye,s=n.profile??r.getActiveProfile()??"default",a=n.env??r.getDefaultEnv(),i=ie(a),l=r.loadBasicAuth(s,a),c=null;if(n.username&&n.accessKey)c={username:n.username,accessKey:n.accessKey};else if(l)c={username:l.username,accessKey:l.access_key};else{let f=r.loadCredentials(s,a);f||(console.error(`No credentials for profile "${s}" [${a}]. Run "kane-cli login" first.`),ne(2,`No credentials for profile "${s}" [${a}]`)),c=f.access_token}try{let{ControllerClient:f}=await import("./controller-client-7BIK5FYL.js"),g=await new f(i.controllerBaseUrl,c).getCreditBalance();console.log(`Available credits: ${g.available_credits}`),console.log(`Total credits: ${g.total_credits}`),ne(0,"Balance retrieved")}catch(f){console.error(`Error: ${f instanceof Error?f.message:String(f)}`),ne(1,`Balance check failed: ${f instanceof Error?f.message:String(f)}`)}}),e.command("help").action(()=>{e.help()}),e.command("update").description("Update kane-cli to the latest version").action(async()=>{let{checkForUpdate:n}=await import("./version-check-SR6WBC6M.js"),{runSelfUpdate:r}=await import("./updater-WVTXO7SS.js");console.log("Checking for updates...");let s=await n();if(!s){console.log(`Already on latest version (${ft})`);return}console.log(`Update available: ${s.current} \u2192 ${s.latest}
84
+ `),console.log("Updating @testmuai/kane-cli...");let a=await r(i=>{process.stdout.write(i)});a.success?(console.log(`
72
85
  \u2713 Updated to ${a.toVersion}`),console.log("\nRun `kane-cli changelog` to see what's new.")):console.error(`
73
- \u2717 Update failed: ${a.error}`)}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async r=>{let{fetchChangelog:n,formatChangelog:s}=await import("./changelog-XYK3P4RQ.js"),a=await n({all:r.all});console.log(s(a))}),e.parse(["node","kane-cli",...i])}var To=kn().catch(()=>null),Wn=Ut.argv.slice(2),Aa=Wn.includes("--dev"),Ta=Wn.includes("--local"),Oa=Wn.includes("--code-export"),Po=Wn.filter(i=>i!=="--dev"),Pa=new Set(["--local","--code-export"]),Ia=Po.some(i=>!Pa.has(i));Aa&&(Ut.env.KANE_DEV_MODE="1");if(Ia)To.then(i=>{i&&Ut.stderr.write(`
74
- Update available: ${i.current} \u2192 ${i.latest} \u2014 run \`kane-cli update\`
86
+ \u2717 Update failed: ${a.error}`)}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async n=>{let{fetchChangelog:r,formatChangelog:s}=await import("./changelog-CHSXQF3G.js"),a=await r({all:n.all});console.log(s(a))}),e.parse(["node","kane-cli",...o])}Fs();var _i=wn().catch(()=>null),Yn=fn.argv.slice(2),Il=Yn.includes("--dev"),Pl=Yn.includes("--local"),Ol=Yn.includes("--code-export"),Si=Yn.filter(o=>o!=="--dev"),Dl=new Set(["--local","--code-export"]),Bl=Si.some(o=>!Dl.has(o));Il&&(fn.env.KANE_DEV_MODE="1");if(Bl)_i.then(o=>{o&&fn.stderr.write(`
87
+ Update available: ${o.current} \u2192 ${o.latest} \u2014 run \`kane-cli update\`
75
88
 
76
- `)}),Ao(Po);else{Ut.on("SIGINT",()=>{Ut.exit(130)}),Ut.on("SIGTERM",async()=>{let{runExitCleanup:e}=await import("./exitCleanup-J3GVD6U2.js");e(),Ut.exit(143)});let{waitUntilExit:i}=yn(Oo.default.createElement(co,{localMode:Ta,codeExport:Oa,updatePromise:To}),{exitOnCtrlC:!1});i().then(()=>{Ut.exit(0)})}
89
+ `)}),bi(Si);else{let{waitUntilExit:o,unmount:e}=hn(yi.default.createElement(ti,{localMode:Pl,codeExport:Ol,updatePromise:_i}),{exitOnCtrlC:!1});Ls(()=>e()),Us(()=>{try{fn.stdin.setRawMode?.(!1)}catch{}fn.stdout.write("\x1B[?25h")}),o().then(()=>{ne(0,"TUI session ended")})}