@testmuai/kane-cli 0.2.9 → 0.2.10

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 (36) hide show
  1. package/dist/{ChromeProfilePicker-ZDIWVMLR.js → ChromeProfilePicker-VPCR7EPX.js} +1 -1
  2. package/dist/{CliFeedbackPrompt-V6X2IESW.js → CliFeedbackPrompt-CKWGADHU.js} +1 -1
  3. package/dist/{CliUploadProgress-BSXWFIP5.js → CliUploadProgress-ZVRZFMGT.js} +1 -1
  4. package/dist/{ConfigView-53QUJ3UT.js → ConfigView-XCWDFTNS.js} +1 -1
  5. package/dist/{FolderPicker-BHEDYLKA.js → FolderPicker-DN4OV6BI.js} +1 -1
  6. package/dist/{HelpView-ZR5EXR7F.js → HelpView-DOYUDPWZ.js} +1 -1
  7. package/dist/{LinksBox-6CLSLM2A.js → LinksBox-FR4WLNX4.js} +1 -1
  8. package/dist/{LoginWizard-NJA5AAYO.js → LoginWizard-NJ22OXIH.js} +1 -1
  9. package/dist/{ProfilesView-HEUHISRN.js → ProfilesView-ENBYW7PJ.js} +1 -1
  10. package/dist/{ProjectPicker-YZZUJDOQ.js → ProjectPicker-43LFS6S6.js} +1 -1
  11. package/dist/{WhoamiView-AXPRRGNG.js → WhoamiView-AP6NXPTL.js} +1 -1
  12. package/dist/{changelog-L2FNAYGV.js → changelog-DFV22SXX.js} +1 -1
  13. package/dist/{chunk-EOOULVWR.js → chunk-43D3E7EA.js} +1 -1
  14. package/dist/{chunk-RTOXLI4C.js → chunk-5PATFYIN.js} +1 -1
  15. package/dist/{chunk-56DFEK7K.js → chunk-5WXHT4JD.js} +1 -1
  16. package/dist/{chunk-4RVMT7O2.js → chunk-6REBTGNQ.js} +1 -1
  17. package/dist/chunk-75XK2HKS.js +2 -0
  18. package/dist/{chunk-QX4WHNRG.js → chunk-7E2QYCMX.js} +1 -1
  19. package/dist/{chunk-DGFG2WJH.js → chunk-7H6IY5KC.js} +1 -1
  20. package/dist/{chunk-C7FS7B4O.js → chunk-FBK6UISI.js} +1 -1
  21. package/dist/{chunk-4HQOC372.js → chunk-FK2AWXZN.js} +1 -1
  22. package/dist/{chunk-BTLH2ZWO.js → chunk-KJAVR2NX.js} +1 -1
  23. package/dist/{chunk-2ATFRKHW.js → chunk-OILYCYAD.js} +1 -1
  24. package/dist/{chunk-GIXIZJ6Y.js → chunk-PXIG2FKV.js} +1 -1
  25. package/dist/{chunk-RFGE6ULZ.js → chunk-SOUKF5VL.js} +1 -1
  26. package/dist/{chunk-CUBXICTI.js → chunk-UNQM5247.js} +1 -1
  27. package/dist/{chunk-TV6MHKZV.js → chunk-YSOCZU7T.js} +1 -1
  28. package/dist/{chunk-YLC6PSJZ.js → chunk-YTG6V347.js} +1 -1
  29. package/dist/index.js +45 -45
  30. package/dist/{logging-R5263ZJZ.js → logging-WJPMWUL5.js} +1 -1
  31. package/dist/login-flow-5WUX5JKU.js +2 -0
  32. package/dist/{pipeline-QHJGNZ7H.js → pipeline-ZSNZGJIH.js} +1 -1
  33. package/dist/{version-check-NUVM7TOP.js → version-check-AGBPWJQA.js} +1 -1
  34. package/package.json +5 -5
  35. package/dist/chunk-BXWE7UO7.js +0 -2
  36. package/dist/login-flow-J5AIWRWS.js +0 -2
package/dist/index.js CHANGED
@@ -1,64 +1,64 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
3
- import{a as Vr}from"./chunk-GIXIZJ6Y.js";import{a as Jo,d as Vn}from"./chunk-EOOULVWR.js";import{a as Xo}from"./chunk-4HQOC372.js";import{a as kt,b as No,c as Bn,d as qo,e as Br}from"./chunk-QX4WHNRG.js";import{a as zo}from"./chunk-DGFG2WJH.js";import{b as It}from"./chunk-2ATFRKHW.js";import{b as Pt}from"./chunk-BTLH2ZWO.js";import"./chunk-YLC6PSJZ.js";import{a as Ne,b as en,c as hn}from"./chunk-4RVMT7O2.js";import{a as ce}from"./chunk-CUBXICTI.js";import{a as mt}from"./chunk-PWGEMRBD.js";import{b as Wo}from"./chunk-56DFEK7K.js";import{a as Ko}from"./chunk-IFWLAQ3L.js";import{a as Go}from"./chunk-RFGE6ULZ.js";import{a as Ho}from"./chunk-L5Y2GUO6.js";import{a as Vo}from"./chunk-E47GFYXA.js";import{b as Zt}from"./chunk-TV6MHKZV.js";import{b as Lr}from"./chunk-C7FS7B4O.js";import{c as $r}from"./chunk-RTOXLI4C.js";import{a as Q}from"./chunk-HCBYKLMW.js";import{a as Qt,c as Se,d as Fo,h as ft,i as Dr,j as jr,t as v}from"./chunk-BXWE7UO7.js";import{a as S,b as f,c as gn,d as Xt,i as Oe,j as Yt,k as Tt}from"./chunk-C44QQJR4.js";import{a as Pe}from"./chunk-6YGTRKDT.js";import{a as at}from"./chunk-HFQ7T5KT.js";import{a as Uo,b as Mo}from"./chunk-DXKKUGFG.js";import{a as pn,c as Nt,e as N}from"./chunk-UR6MHSHU.js";var In=Nt(mo=>{"use strict";var hr=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}},fo=class extends hr{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};mo.CommanderError=hr;mo.InvalidArgumentError=fo});var vr=Nt(go=>{"use strict";var{InvalidArgumentError:Ia}=In(),po=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 Ia(`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 Pa(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}go.Argument=po;go.humanReadableArgName=Pa});var vo=Nt(Js=>{"use strict";var{humanReadableArgName:Oa}=vr(),ho=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,o)=>r.name().localeCompare(o.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),o=n.long&&e._findOption(n.long);!r&&!o?t.push(n):n.long&&!o?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(o=>!o.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=>Oa(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,o=2,a=2;function l(_,x){if(x){let C=`${_.padEnd(n+a)}${x}`;return t.wrap(C,r-o,n+a)}return _}function i(_){return _.join(`
4
- `).replace(/^/gm," ".repeat(o))}let c=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(c=c.concat([t.wrap(d,r,0),""]));let m=t.visibleArguments(e).map(_=>l(t.argumentTerm(_),t.argumentDescription(_)));m.length>0&&(c=c.concat(["Arguments:",i(m),""]));let g=t.visibleOptions(e).map(_=>l(t.optionTerm(_),t.optionDescription(_)));if(g.length>0&&(c=c.concat(["Options:",i(g),""])),this.showGlobalOptions){let _=t.visibleGlobalOptions(e).map(x=>l(t.optionTerm(x),t.optionDescription(x)));_.length>0&&(c=c.concat(["Global Options:",i(_),""]))}let p=t.visibleCommands(e).map(_=>l(t.subcommandTerm(_),t.subcommandDescription(_)));return p.length>0&&(c=c.concat(["Commands:",i(p),""])),c.join(`
3
+ import{a as Fr}from"./chunk-PXIG2FKV.js";import{a as Xo,d as Vn}from"./chunk-43D3E7EA.js";import{a as Yo}from"./chunk-FK2AWXZN.js";import{a as Tt,b as Uo,c as Bn,d as zo,e as Vr}from"./chunk-7E2QYCMX.js";import{a as Jo}from"./chunk-7H6IY5KC.js";import{b as kt}from"./chunk-OILYCYAD.js";import{b as It}from"./chunk-KJAVR2NX.js";import"./chunk-YTG6V347.js";import{a as He,b as nn,c as hn}from"./chunk-6REBTGNQ.js";import{a as ae}from"./chunk-UNQM5247.js";import{a as pt}from"./chunk-PWGEMRBD.js";import{b as Ko}from"./chunk-5WXHT4JD.js";import{a as Go}from"./chunk-IFWLAQ3L.js";import{a as qo}from"./chunk-SOUKF5VL.js";import{a as Wo}from"./chunk-L5Y2GUO6.js";import{a as Fo}from"./chunk-E47GFYXA.js";import{b as tn}from"./chunk-YSOCZU7T.js";import{b as $r}from"./chunk-FBK6UISI.js";import{c as Br}from"./chunk-5PATFYIN.js";import{a as Q}from"./chunk-HCBYKLMW.js";import{a as en,c as Ee,d as No,h as mt,i as jr,j as Lr,t as v}from"./chunk-75XK2HKS.js";import{a as y,b as f,c as gn,d as Qt,i as je,j as Zt,k as At}from"./chunk-C44QQJR4.js";import{a as De}from"./chunk-6YGTRKDT.js";import{a as lt}from"./chunk-HFQ7T5KT.js";import{a as Mo,b as Ho}from"./chunk-DXKKUGFG.js";import{a as pn,c as Mt,e as U}from"./chunk-UR6MHSHU.js";var In=Mt(po=>{"use strict";var vr=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}},mo=class extends vr{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};po.CommanderError=vr;po.InvalidArgumentError=mo});var _r=Mt(ho=>{"use strict";var{InvalidArgumentError:Ia}=In(),go=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 Ia(`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 Pa(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}ho.Argument=go;ho.humanReadableArgName=Pa});var _o=Mt(Js=>{"use strict";var{humanReadableArgName:Oa}=_r(),vo=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,o)=>r.name().localeCompare(o.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),o=n.long&&e._findOption(n.long);!r&&!o?t.push(n):n.long&&!o?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(o=>!o.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=>Oa(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,o=2,a=2;function l(_,b){if(b){let E=`${_.padEnd(n+a)}${b}`;return t.wrap(E,r-o,n+a)}return _}function i(_){return _.join(`
4
+ `).replace(/^/gm," ".repeat(o))}let c=[`Usage: ${t.commandUsage(e)}`,""],d=t.commandDescription(e);d.length>0&&(c=c.concat([t.wrap(d,r,0),""]));let m=t.visibleArguments(e).map(_=>l(t.argumentTerm(_),t.argumentDescription(_)));m.length>0&&(c=c.concat(["Arguments:",i(m),""]));let g=t.visibleOptions(e).map(_=>l(t.optionTerm(_),t.optionDescription(_)));if(g.length>0&&(c=c.concat(["Options:",i(g),""])),this.showGlobalOptions){let _=t.visibleGlobalOptions(e).map(b=>l(t.optionTerm(b),t.optionDescription(b)));_.length>0&&(c=c.concat(["Global Options:",i(_),""]))}let p=t.visibleCommands(e).map(_=>l(t.subcommandTerm(_),t.subcommandDescription(_)));return p.length>0&&(c=c.concat(["Commands:",i(p),""])),c.join(`
5
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 o=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${o}]+`);if(e.match(a))return e;let l=t-n;if(l<r)return e;let i=e.slice(0,n),c=e.slice(n).replace(`\r
6
6
  `,`
7
7
  `),d=" ".repeat(n),g="\\s\u200B",p=new RegExp(`
8
- |.{1,${l-1}}([${g}]|$)|[^${g}]+?([${g}]|$)`,"g"),_=c.match(p)||[];return i+_.map((x,C)=>x===`
9
- `?"":(C>0?d:"")+x.trimEnd()).join(`
10
- `)}};Js.Help=ho});var wo=Nt(xo=>{"use strict";var{InvalidArgumentError:Da}=In(),_o=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=La(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 Da(`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 ja(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},bo=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,o=r!==void 0?r:!1;return t.negate===(o===e)}};function ja(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function La(s){let e,t,n=s.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}}xo.Option=_o;xo.DualOptions=bo});var Ys=Nt(Xs=>{"use strict";function $a(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let n=0;n<=s.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<=s.length;r++){let o=1;s[r-1]===e[n-1]?o=0:o=1,t[r][n]=Math.min(t[r-1][n]+1,t[r][n-1]+1,t[r-1][n-1]+o),r>1&&n>1&&s[r-1]===e[n-2]&&s[r-2]===e[n-1]&&(t[r][n]=Math.min(t[r][n],t[r-2][n-2]+1))}return t[s.length][e.length]}function Ba(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(a=>a.slice(2)));let n=[],r=3,o=.4;return e.forEach(a=>{if(a.length<=1)return;let l=$a(s,a),i=Math.max(s.length,a.length);(i-l)/i>o&&(l<r?(r=l,n=[a]):l===r&&n.push(a))}),n.sort((a,l)=>a.localeCompare(l)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
8
+ |.{1,${l-1}}([${g}]|$)|[^${g}]+?([${g}]|$)`,"g"),_=c.match(p)||[];return i+_.map((b,E)=>b===`
9
+ `?"":(E>0?d:"")+b.trimEnd()).join(`
10
+ `)}};Js.Help=vo});var yo=Mt(wo=>{"use strict";var{InvalidArgumentError:Da}=In(),bo=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=La(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 Da(`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 ja(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},xo=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,o=r!==void 0?r:!1;return t.negate===(o===e)}};function ja(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function La(s){let e,t,n=s.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}}wo.Option=bo;wo.DualOptions=xo});var Ys=Mt(Xs=>{"use strict";function $a(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let n=0;n<=s.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<=s.length;r++){let o=1;s[r-1]===e[n-1]?o=0:o=1,t[r][n]=Math.min(t[r-1][n]+1,t[r][n-1]+1,t[r-1][n-1]+o),r>1&&n>1&&s[r-1]===e[n-2]&&s[r-2]===e[n-1]&&(t[r][n]=Math.min(t[r][n],t[r-2][n-2]+1))}return t[s.length][e.length]}function Ba(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(a=>a.slice(2)));let n=[],r=3,o=.4;return e.forEach(a=>{if(a.length<=1)return;let l=$a(s,a),i=Math.max(s.length,a.length);(i-l)/i>o&&(l<r?(r=l,n=[a]):l===r&&n.push(a))}),n.sort((a,l)=>a.localeCompare(l)),t&&(n=n.map(a=>`--${a}`)),n.length>1?`
11
11
  (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
12
- (Did you mean ${n[0]}?)`:""}Xs.suggestSimilar=Ba});var ni=Nt(ti=>{"use strict";var Va=pn("events").EventEmitter,yo=pn("child_process"),Et=pn("path"),So=pn("fs"),_e=pn("process"),{Argument:Fa,humanReadableArgName:Na}=vr(),{CommanderError:Eo}=In(),{Help:Ua}=vo(),{Option:Qs,DualOptions:Ma}=wo(),{suggestSimilar:Zs}=Ys(),Co=class s extends Va{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=>_e.stdout.write(t),writeErr:t=>_e.stderr.write(t),getOutHelpWidth:()=>_e.stdout.isTTY?_e.stdout.columns:void 0,getErrHelpWidth:()=>_e.stderr.isTTY?_e.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,o=n;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,a,l]=e.match(/([^ ]+) *(.*)/),i=this.createCommand(a);return r&&(i.description(r),i._executableHandler=!0),o.isDefault&&(this._defaultCommandName=i._name),i._hidden=!!(o.noHelp||o.hidden),i._executableFile=o.executableFile||null,l&&i.arguments(l),this._registerCommand(i),i.parent=this,i.copyInheritedSettings(this),r?this:i}createCommand(e){return new s(e)}createHelp(){return Object.assign(new Ua,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
12
+ (Did you mean ${n[0]}?)`:""}Xs.suggestSimilar=Ba});var ni=Mt(ti=>{"use strict";var Va=pn("events").EventEmitter,So=pn("child_process"),St=pn("path"),Eo=pn("fs"),xe=pn("process"),{Argument:Fa,humanReadableArgName:Na}=_r(),{CommanderError:Co}=In(),{Help:Ua}=_o(),{Option:Qs,DualOptions:Ma}=yo(),{suggestSimilar:Zs}=Ys(),Ro=class s extends Va{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,o=n;typeof r=="object"&&r!==null&&(o=r,r=null),o=o||{};let[,a,l]=e.match(/([^ ]+) *(.*)/),i=this.createCommand(a);return r&&(i.description(r),i._executableHandler=!0),o.isDefault&&(this._defaultCommandName=i._name),i._hidden=!!(o.noHelp||o.hidden),i._executableFile=o.executableFile||null,l&&i.arguments(l),this._registerCommand(i),i.parent=this,i.copyInheritedSettings(this),r?this:i}createCommand(e){return new s(e)}createHelp(){return Object.assign(new Ua,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
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 Fa(e,t)}argument(e,t,n,r){let o=this.createArgument(e,t);return typeof n=="function"?o.default(r).argParser(n):o.default(n),this.addArgument(o),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(/([^ ]+) *(.*)/),o=t??"display help for command",a=this.createCommand(n);return a.helpOption(!1),r&&a.arguments(r),o&&a.description(o),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 Eo(e,t,n)),_e.exit(e)}action(e){let t=n=>{let r=this.registeredArguments.length,o=n.slice(0,r);return this._storeOptionsAsProperties?o[r]=this:o[r]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new Qs(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let a=`${r} ${o.message}`;this.error(a,{exitCode:o.exitCode,code:o.code})}throw o}}_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("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' 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 o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(o,a,l)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let i=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,i,a):o!==null&&e.variadic&&(o=e._concatValue(o,i)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,l)};return this.on("option:"+t,o=>{let a=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let a=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,a,"env")}),this}_optionEx(e,t,n,r,o){if(typeof t=="object"&&t instanceof Qs)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(o).argParser(r);else if(r instanceof RegExp){let l=r;r=(i,c)=>{let d=l.exec(i);return d?d[0]:c},a.default(o).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){_e.versions?.electron&&(t.from="electron");let r=_e.execArgv??[];(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))&&(t.from="eval")}e===void 0&&(e=_e.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":_e.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 o(d,m){let g=Et.resolve(d,m);if(So.existsSync(g))return g;if(r.includes(Et.extname(m)))return;let p=r.find(_=>So.existsSync(`${g}${_}`));if(p)return`${g}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let d;try{d=So.realpathSync(this._scriptPath)}catch{d=this._scriptPath}l=Et.resolve(Et.dirname(d),l)}if(l){let d=o(l,a);if(!d&&!e._executableFile&&this._scriptPath){let m=Et.basename(this._scriptPath,Et.extname(this._scriptPath));m!==this._name&&(d=o(l,`${m}-${e._name}`))}a=d||a}n=r.includes(Et.extname(a));let i;_e.platform!=="win32"?n?(t.unshift(a),t=ei(_e.execArgv).concat(t),i=yo.spawn(_e.argv[0],t,{stdio:"inherit"})):i=yo.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=ei(_e.execArgv).concat(t),i=yo.spawn(_e.execPath,t,{stdio:"inherit"})),i.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{_e.on(m,()=>{i.killed===!1&&i.exitCode===null&&i.kill(m)})});let c=this._exitCallback;i.on("close",d=>{d=d??1,c?c(new Eo(d,"commander.executeSubCommandAsync","(close)")):_e.exit(d)}),i.on("error",d=>{if(d.code==="ENOENT"){let m=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",g=`'${a}' does not exist
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 Co(e,t,n)),xe.exit(e)}action(e){let t=n=>{let r=this.registeredArguments.length,o=n.slice(0,r);return this._storeOptionsAsProperties?o[r]=this:o[r]=this.opts(),o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new Qs(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let a=`${r} ${o.message}`;this.error(a,{exitCode:o.exitCode,code:o.code})}throw o}}_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("|"),o=t(e).join("|");throw new Error(`cannot add command '${o}' 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 o=e.long.replace(/^--no-/,"--");this._findOption(o)||this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(o,a,l)=>{o==null&&e.presetArg!==void 0&&(o=e.presetArg);let i=this.getOptionValue(n);o!==null&&e.parseArg?o=this._callParseArg(e,o,i,a):o!==null&&e.variadic&&(o=e._concatValue(o,i)),o==null&&(e.negate?o=!1:e.isBoolean()||e.optional?o=!0:o=""),this.setOptionValueWithSource(n,o,l)};return this.on("option:"+t,o=>{let a=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,o=>{let a=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,a,"env")}),this}_optionEx(e,t,n,r,o){if(typeof t=="object"&&t instanceof Qs)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(o).argParser(r);else if(r instanceof RegExp){let l=r;r=(i,c)=>{let d=l.exec(i);return d?d[0]:c},a.default(o).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 o(d,m){let g=St.resolve(d,m);if(Eo.existsSync(g))return g;if(r.includes(St.extname(m)))return;let p=r.find(_=>Eo.existsSync(`${g}${_}`));if(p)return`${g}${p}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,l=this._executableDir||"";if(this._scriptPath){let d;try{d=Eo.realpathSync(this._scriptPath)}catch{d=this._scriptPath}l=St.resolve(St.dirname(d),l)}if(l){let d=o(l,a);if(!d&&!e._executableFile&&this._scriptPath){let m=St.basename(this._scriptPath,St.extname(this._scriptPath));m!==this._name&&(d=o(l,`${m}-${e._name}`))}a=d||a}n=r.includes(St.extname(a));let i;xe.platform!=="win32"?n?(t.unshift(a),t=ei(xe.execArgv).concat(t),i=So.spawn(xe.argv[0],t,{stdio:"inherit"})):i=So.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=ei(xe.execArgv).concat(t),i=So.spawn(xe.execPath,t,{stdio:"inherit"})),i.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{xe.on(m,()=>{i.killed===!1&&i.exitCode===null&&i.kill(m)})});let c=this._exitCallback;i.on("close",d=>{d=d??1,c?c(new Co(d,"commander.executeSubCommandAsync","(close)")):xe.exit(d)}),i.on("error",d=>{if(d.code==="ENOENT"){let m=l?`searched for local subcommand relative to directory '${l}'`:"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
- - ${m}`;throw new Error(g)}else if(d.code==="EACCES")throw new Error(`'${a}' not executable`);if(!c)_e.exit(1);else{let m=new Eo(1,"commander.executeSubCommandAsync","(error)");m.nestedError=d,c(m)}}),this.runningCommand=i}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,r,"preSubcommand"),o=this._chainOrCall(o,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),o}_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,o)=>{let a=r;if(r!==null&&n.parseArg){let l=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,r,o,l)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let o=n.defaultValue;n.variadic?r<this.args.length?(o=this.args.slice(r),n.parseArg&&(o=o.reduce((a,l)=>e(n,l,a),n.defaultValue))):o===void 0&&(o=[]):r<this.args.length&&(o=this.args[r],n.parseArg&&(o=e(n,o,n.defaultValue))),t[r]=o}),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(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(a=>{r.push({hookedCommand:o,callback:a})})}),t==="postAction"&&r.reverse(),r.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{r=this._chainOrCall(r,()=>o(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])},o=`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(o,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(o))r(),this._processArguments(),this.parent.emit(o,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(o=>n.conflictsWith.includes(o.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,o=e.slice();function a(i){return i.length>1&&i[0]==="-"}let l=null;for(;o.length;){let i=o.shift();if(i==="--"){r===n&&r.push(i),r.push(...o);break}if(l&&!a(i)){this.emit(`option:${l.name()}`,i);continue}if(l=null,a(i)){let c=this._findOption(i);if(c){if(c.required){let d=o.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;o.length>0&&!a(o[0])&&(d=o.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(i.length>2&&i[0]==="-"&&i[1]!=="-"){let c=this._findOption(`-${i[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,i.slice(2)):(this.emit(`option:${c.name()}`),o.unshift(`-${i.slice(2)}`));continue}}if(/^--[^=]+=/.test(i)){let c=i.indexOf("="),d=this._findOption(i.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,i.slice(c+1));continue}}if(a(i)&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(i)){t.push(i),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&i===this._getHelpCommand().name()){t.push(i),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(i),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){r.push(i),o.length>0&&r.push(...o);break}r.push(i)}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}
18
+ - ${m}`;throw new Error(g)}else if(d.code==="EACCES")throw new Error(`'${a}' not executable`);if(!c)xe.exit(1);else{let m=new Co(1,"commander.executeSubCommandAsync","(error)");m.nestedError=d,c(m)}}),this.runningCommand=i}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);r||this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,r,"preSubcommand"),o=this._chainOrCall(o,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),o}_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,o)=>{let a=r;if(r!==null&&n.parseArg){let l=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;a=this._callParseArg(n,r,o,l)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let o=n.defaultValue;n.variadic?r<this.args.length?(o=this.args.slice(r),n.parseArg&&(o=o.reduce((a,l)=>e(n,l,a),n.defaultValue))):o===void 0&&(o=[]):r<this.args.length&&(o=this.args[r],n.parseArg&&(o=e(n,o,n.defaultValue))),t[r]=o}),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(o=>o._lifeCycleHooks[t]!==void 0).forEach(o=>{o._lifeCycleHooks[t].forEach(a=>{r.push({hookedCommand:o,callback:a})})}),t==="postAction"&&r.reverse(),r.forEach(o=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(o=>{r=this._chainOrCall(r,()=>o(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])},o=`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(o,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(o))r(),this._processArguments(),this.parent.emit(o,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(o=>n.conflictsWith.includes(o.attributeName()));r&&this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,o=e.slice();function a(i){return i.length>1&&i[0]==="-"}let l=null;for(;o.length;){let i=o.shift();if(i==="--"){r===n&&r.push(i),r.push(...o);break}if(l&&!a(i)){this.emit(`option:${l.name()}`,i);continue}if(l=null,a(i)){let c=this._findOption(i);if(c){if(c.required){let d=o.shift();d===void 0&&this.optionMissingArgument(c),this.emit(`option:${c.name()}`,d)}else if(c.optional){let d=null;o.length>0&&!a(o[0])&&(d=o.shift()),this.emit(`option:${c.name()}`,d)}else this.emit(`option:${c.name()}`);l=c.variadic?c:null;continue}}if(i.length>2&&i[0]==="-"&&i[1]!=="-"){let c=this._findOption(`-${i[1]}`);if(c){c.required||c.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${c.name()}`,i.slice(2)):(this.emit(`option:${c.name()}`),o.unshift(`-${i.slice(2)}`));continue}}if(/^--[^=]+=/.test(i)){let c=i.indexOf("="),d=this._findOption(i.slice(0,c));if(d&&(d.required||d.optional)){this.emit(`option:${d.name()}`,i.slice(c+1));continue}}if(a(i)&&(r=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(i)){t.push(i),o.length>0&&n.push(...o);break}else if(this._getHelpCommand()&&i===this._getHelpCommand().name()){t.push(i),o.length>0&&t.push(...o);break}else if(this._defaultCommandName){n.push(i),o.length>0&&n.push(...o);break}}if(this._passThroughOptions){r.push(i),o.length>0&&r.push(...o);break}r.push(i)}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 n=t||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in _e.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()}`,_e.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ma(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 l=a.attributeName(),i=this.getOptionValue(l),c=this.options.find(m=>m.negate&&l===m.attributeName()),d=this.options.find(m=>!m.negate&&l===m.attributeName());return c&&(c.presetArg===void 0&&i===!1||c.presetArg!==void 0&&i===c.presetArg)?c:d||a},r=a=>{let l=n(a),i=l.attributeName();return this.getOptionValueSource(i)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},o=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let a=o.createHelp().visibleOptions(o).filter(l=>l.long).map(l=>l.long);r=r.concat(a),o=o.parent}while(o&&!o._enablePositionalOptions);t=Zs(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",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(o=>{r.push(o.name()),o.alias()&&r.push(o.alias())}),t=Zs(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=>Na(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=Et.basename(e,Et.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(o=>o.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(o=>o.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=_e.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.
21
+ `),this.outputHelp({error:!0}));let n=t||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,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 Ma(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 l=a.attributeName(),i=this.getOptionValue(l),c=this.options.find(m=>m.negate&&l===m.attributeName()),d=this.options.find(m=>!m.negate&&l===m.attributeName());return c&&(c.presetArg===void 0&&i===!1||c.presetArg!==void 0&&i===c.presetArg)?c:d||a},r=a=>{let l=n(a),i=l.attributeName();return this.getOptionValueSource(i)==="env"?`environment variable '${l.envVar}'`:`option '${l.flags}'`},o=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let a=o.createHelp().visibleOptions(o).filter(l=>l.long).map(l=>l.long);r=r.concat(a),o=o.parent}while(o&&!o._enablePositionalOptions);t=Zs(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",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(o=>{r.push(o.name()),o.alias()&&r.push(o.alias())}),t=Zs(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=>Na(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=St.basename(e,St.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(o=>o.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(o=>o.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
23
  Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,o=>{let a;typeof t=="function"?a=t({error:o.error,command:o.command}):a=t,a&&o.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 ei(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?r=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],r=o[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}ti.Command=Co});var ii=Nt(nt=>{"use strict";var{Argument:ri}=vr(),{Command:Ro}=ni(),{CommanderError:Ha,InvalidArgumentError:oi}=In(),{Help:Wa}=vo(),{Option:si}=wo();nt.program=new Ro;nt.createCommand=s=>new Ro(s);nt.createOption=(s,e)=>new si(s,e);nt.createArgument=(s,e)=>new ri(s,e);nt.Command=Ro;nt.Option=si;nt.Argument=ri;nt.Help=Wa;nt.CommanderError=Ha;nt.InvalidArgumentError=oi;nt.InvalidOptionArgumentError=oi});var ko=N(Pe(),1);import Qe from"process";var L=N(Pe(),1);var pe=N(Q(),1);function Yo({profile:s,environment:e,model:t,tokenValid:n,sessionId:r,runCount:o,viewMode:a}){let{stdout:l}=Tt(),i=l?.columns??80,c=e==="stage";return(0,pe.jsxs)(S,{flexDirection:"column",children:[(0,pe.jsx)(f,{color:v.muted,children:"\u2500".repeat(i)}),(0,pe.jsx)(S,{paddingX:1,children:(0,pe.jsxs)(S,{gap:1,children:[(0,pe.jsx)(f,{color:v.dimmed,children:"Model:"}),(0,pe.jsx)(f,{color:v.dimmed,children:t}),(0,pe.jsx)(f,{color:v.muted,children:"|"}),(0,pe.jsx)(f,{color:v.dimmed,children:"Session:"}),(0,pe.jsx)(f,{color:v.dimmed,children:r.slice(-6)}),(0,pe.jsx)(f,{color:v.muted,children:"|"}),(0,pe.jsx)(f,{color:n?v.green:v.red,children:"\u25CF"}),(0,pe.jsx)(f,{color:v.dimmed,children:n?"authenticated":"not logged in"})]})}),(0,pe.jsx)(S,{paddingX:1,children:(0,pe.jsxs)(S,{gap:1,children:[(0,pe.jsx)(f,{color:v.dimmed,children:s??"no profile"}),(0,pe.jsx)(f,{color:v.muted,children:"|"}),c?(0,pe.jsx)(f,{color:v.yellow,bold:!0,children:"\u26A0 stage"}):(0,pe.jsx)(f,{color:v.green,children:e}),(0,pe.jsx)(f,{color:v.muted,children:"|"}),(0,pe.jsxs)(f,{color:v.dimmed,children:["runs: ",o]})]})}),(0,pe.jsx)(S,{paddingX:1,children:(0,pe.jsx)(f,{dimColor:!0,children:a==="chat"?"ctrl+c cancel/exit":"\u2191\u2193 navigate \u21B5 select esc back"})})]})}var Qo=N(Pe(),1);import{readFileSync as Ti,writeFileSync as ki,mkdirSync as Ii}from"fs";import{dirname as Pi,join as Oi}from"path";var Di=Oi(Se,"command-history.json"),ji=200,Fr=class{entries;filePath;max;constructor(e=Di,t=ji){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=Ti(this.filePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}_save(){try{Ii(Pi(this.filePath),{recursive:!0}),ki(this.filePath,JSON.stringify(this.entries)+`
25
- `)}catch{}}};function Fn(s){let e=(0,Qo.useRef)(null);return e.current||(e.current=new Fr(s)),e.current}var Mt=N(Pe(),1);var vn=[[[" "],[" "],[" "],[" "],["\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 ie=N(Q(),1),Nn="#af87d7",Nr="#875faf",Zo="#5b3a7a",Li="#ff9500",$i="#ea580c";var Ur="#666666",Bi="#555555",Ut=[[Nn,"\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"],[Nn,"\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"],[Nn,"\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"],[Nn,"\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"],[Nr,"\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"],[Nr,"\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"],[Nr,"\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"]],Mr=Ut.map(([,s])=>[...s]);function es({visibleRows:s=Ut.length}){let e=Math.min(s,Ut.length);return(0,ie.jsxs)(S,{flexDirection:"column",children:[Ut.slice(0,e).map(([t,n],r)=>{let o=Mr[r];return(0,ie.jsx)(f,{children:o.map((a,l)=>{if(a==="\u2588")return(0,ie.jsx)(f,{color:t,children:"\u2588"},l);let i=l>0&&o[l-1]==="\u2588",c=r>0&&l>0&&Mr[r-1][l-1]==="\u2588";return i||c?(0,ie.jsx)(f,{color:Zo,children:"\u2592"},l):(0,ie.jsx)(f,{children:" "},l)})},r)}),e>=Ut.length&&(0,ie.jsxs)(f,{children:[" ",Mr[Ut.length-1].map((t,n)=>t==="\u2588"?(0,ie.jsx)(f,{color:Zo,children:"\u2580"},n):(0,ie.jsx)(f,{children:" "},n))]})]})}function Vi({visibleRows:s=vn.length}){let e=Math.min(s,vn.length);return(0,ie.jsx)(S,{flexDirection:"column",children:vn.slice(0,e).map((t,n)=>(0,ie.jsx)(f,{children:t.map((r,o)=>{let a=r[0],l=r[1],i=r[2];return l?(0,ie.jsx)(f,{color:l,backgroundColor:i,children:a},o):(0,ie.jsx)(f,{children:a},o)})},n))})}function Un({size:s="compact",helmetVisibleRows:e=vn.length,textVisibleRows:t=Ut.length,showMeta:n=!1,user:r=null,authenticated:o=!1,version:a=""}){return s==="compact"?(0,ie.jsx)(es,{}):(0,ie.jsxs)(S,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,ie.jsx)(f,{color:Li,italic:!0,children:" Welcome to"}),(0,ie.jsx)(f,{children:" "}),(0,ie.jsxs)(S,{gap:2,children:[(0,ie.jsx)(Vi,{visibleRows:e}),(0,ie.jsxs)(S,{flexDirection:"column",children:[(0,ie.jsx)(es,{visibleRows:t}),(0,ie.jsx)(S,{justifyContent:"flex-end",width:73,children:(0,ie.jsx)(f,{color:$i,italic:!0,children:"Command-line interface"})})]})]}),n&&(0,ie.jsxs)(ie.Fragment,{children:[(0,ie.jsx)(f,{children:" "}),(0,ie.jsxs)(f,{children:[(0,ie.jsx)(f,{color:Ur,children:" Browser automation powered by AI. "}),(0,ie.jsx)(f,{color:Bi,children:`v${a}`})]}),(0,ie.jsx)(f,{children:" "}),(0,ie.jsx)(f,{children:(0,ie.jsx)(f,{color:Ur,children:" KaneCLI can navigate websites, fill forms, test web UI, and extract"})}),(0,ie.jsx)(f,{children:(0,ie.jsx)(f,{color:Ur,children:" data \u2014 right from your terminal."})}),(0,ie.jsx)(f,{children:" "})]})]})}var Kr=N(Q(),1),Hr=8,Wr=7;function ts({onComplete:s}){let[e,t]=(0,Mt.useState)(0),[n,r]=(0,Mt.useState)(0),[o,a]=(0,Mt.useState)(!1),[l]=(0,Mt.useState)(()=>{let i=new Ne,c=i.getActiveProfile(),d=i.getDefaultEnv(),m=c?i.loadCredentials(c,d):null,g=c?i.loadBasicAuth(c,d):null;return{authenticated:!!(m||g),user:g?.username??c??null}});return kt(()=>{t(i=>Math.min(Hr,i+1))},e<Hr?60:null),kt(()=>{r(i=>Math.min(Wr,i+1))},n<Wr?80:null),(0,Mt.useEffect)(()=>{e>=Hr&&n>=Wr&&!o&&(a(!0),s?.())},[e,n,o,s]),(0,Kr.jsx)(S,{flexDirection:"column",children:(0,Kr.jsx)(Un,{size:"full",helmetVisibleRows:e,textVisibleRows:n,showMeta:o,user:l.user,authenticated:l.authenticated,version:Qt})})}var vt=N(Q(),1);function ns({entry:s}){return s.type==="input"?(0,vt.jsxs)(S,{children:[(0,vt.jsx)(f,{color:v.purple,children:"\u276F "}),(0,vt.jsx)(f,{children:s.text})]}):s.type==="error"?(0,vt.jsx)(S,{marginLeft:2,children:(0,vt.jsx)(f,{color:v.red,children:s.text})}):(0,vt.jsx)(S,{marginLeft:2,children:(0,vt.jsx)(f,{color:s.type==="info"?v.dimmed:void 0,children:s.text})})}var _t=N(Pe(),1);var Gr=N(Pe(),1);var lt=N(Q(),1);function rs({history:s,onSelect:e,onClose:t}){let[n,r]=(0,Gr.useState)(""),[o,a]=(0,Gr.useState)(0),l=n?s.search(n).slice(0,8):[];return Oe((i,c)=>{if(c.escape){t();return}if(c.return){l.length>0&&l[o]?e(l[o]):t();return}if(c.upArrow){a(d=>Math.max(0,d-1));return}if(c.downArrow){a(d=>Math.min(l.length-1,d+1));return}if(c.backspace||c.delete){r(d=>d.slice(0,-1)),a(0);return}i&&!c.ctrl&&!c.meta&&(r(d=>d+i),a(0))}),(0,lt.jsxs)(S,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,lt.jsx)(f,{color:v.muted,bold:!0,children:"reverse search"}),(0,lt.jsxs)(S,{gap:1,children:[(0,lt.jsx)(f,{color:v.dimmed,children:"search:"}),(0,lt.jsx)(f,{children:n}),(0,lt.jsx)(f,{color:v.purple,children:"\u2588"})]}),l.length>0&&(0,lt.jsx)(f,{children:" "}),l.map((i,c)=>(0,lt.jsx)(S,{marginLeft:2,children:(0,lt.jsxs)(f,{color:c===o?v.purple:v.dimmed,bold:c===o,children:[c===o?"\u25B8 ":" ",i]})},`${c}-${i}`))]})}var Ot=N(Q(),1);function os({commands:s,selectedIndex:e}){return s.length===0?null:(0,Ot.jsx)(S,{flexDirection:"column",marginBottom:0,children:s.map((t,n)=>{let r=n===e;return(0,Ot.jsxs)(S,{children:[(0,Ot.jsx)(f,{color:r?v.primary:v.dimmed,children:r?"\u276F ":" "}),(0,Ot.jsxs)(f,{color:r?v.primary:void 0,bold:r,children:["/",t.name]}),t.args&&(0,Ot.jsxs)(f,{color:v.dimmed,children:[" ",t.args]}),(0,Ot.jsxs)(f,{color:v.dimmed,children:[" ",t.description]})]},t.name)})})}var $e=N(Q(),1);function Mn({onSubmit:s,onEscape:e,history:t,placeholder:n="Type an objective or /command...",commands:r}){let[o,a]=(0,_t.useState)([]),[l,i]=(0,_t.useState)(0),[c,d]=(0,_t.useState)("none"),[m,g]=(0,_t.useState)(-1),p=(0,_t.useRef)(""),[_,x]=(0,_t.useState)(!0),{stdout:C}=Tt(),T=C?.columns??80,[P,R]=(0,_t.useState)(0),O=o.join(""),te=(()=>{if(c!=="none"||o.length===0)return"";if(O.startsWith("/")&&r&&O.length>=2){let w=O.slice(1).toLowerCase(),h=r.find(b=>b.name.startsWith(w)&&b.name!==w);return h?`/${h.name}`.slice(O.length):""}if(O.startsWith("/"))return"";let u=t.getAll();for(let w=u.length-1;w>=0;w--)if(u[w].startsWith(O)&&u[w]!==O)return u[w].slice(O.length);return""})(),Z=(()=>{if(!r||!O.startsWith("/"))return[];let u=O.length>=2?O.slice(1).toLowerCase():"";return u&&r.some(w=>w.name===u)?[]:r.filter(w=>!u||w.name.startsWith(u))})(),ne=Z.length>0&&O.startsWith("/");Oe((u,w)=>{if(_&&u&&x(!1),w.return){if(ne&&Z[P]){let h=`/${Z[P].name}`;a([...h]),i(h.length),R(0);return}O.trim()&&(t.push(O.trim()),s(O.trim()),a([]),i(0),d("none"),g(-1),p.current="",x(!0),R(0));return}if(w.escape){c!=="none"?d("none"):o.length>0?(a([]),i(0),g(-1),p.current=""):e?.();return}if(w.tab){if(te){let h=O+te;a([...h]),i(h.length);return}return}if(w.ctrl&&u==="r"){d("search");return}if(w.ctrl&&u==="a"){i(0);return}if(w.ctrl&&u==="e"){i(o.length);return}if(w.ctrl&&u==="w"){if(l===0)return;let h=l-1;for(;h>0&&o[h]===" ";)h--;for(;h>0&&o[h-1]!==" ";)h--;let b=[...o.slice(0,h),...o.slice(l)];a(b),i(h);return}if(w.ctrl&&u==="u"){a([]),i(0),g(-1),d("none");return}if(w.meta&&u==="b"){let h=l-1;for(;h>0&&o[h]===" ";)h--;for(;h>0&&o[h-1]!==" ";)h--;i(Math.max(0,h));return}if(w.meta&&u==="f"){let h=l;for(;h<o.length&&o[h]!==" ";)h++;for(;h<o.length&&o[h]===" ";)h++;i(h);return}if(w.leftArrow){i(h=>Math.max(0,h-1));return}if(w.rightArrow){if(l>=o.length&&te){let h=O+te;a([...h]),i(h.length)}else i(h=>Math.min(o.length,h+1));return}if(w.upArrow){if(ne){R(h=>Math.max(0,h-1));return}if(c==="none"){let h=t.getAll();if(h.length===0)return;if(m===-1){p.current=O,g(h.length-1);let b=h[h.length-1];a([...b]),i(b.length)}else if(m>0){let b=m-1;g(b);let $=h[b];a([...$]),i($.length)}}return}if(w.downArrow){if(ne){R(h=>Math.min(Z.length-1,h+1));return}if(c==="none"){let h=t.getAll();if(m===-1)return;if(m<h.length-1){let b=m+1;g(b);let $=h[b];a([...$]),i($.length)}else{g(-1);let b=p.current;a([...b]),i(b.length)}}return}if(w.backspace||w.delete){if(l>0){let h=[...o.slice(0,l-1),...o.slice(l)];a(h),i(l-1),g(-1),R(0)}return}if(u&&!w.ctrl&&!w.meta){let h=[...o.slice(0,l),...u,...o.slice(l)];a(h),i(l+u.length),g(-1),R(0)}},{isActive:c!=="search"});let ve=u=>{a([...u]),i(u.length),d("none")},V=()=>{d("none")},F=(()=>{if(_&&o.length===0)return null;let u=l>=o.length,w=o.slice(0,l).join(""),h=u?" ":o[l],b=u?"":o.slice(l+1).join(""),$="\u276F "+w+h+b+te,z=2,q=z+w.length,re=q+1,ee=re+b.length,Te=$.length,je=Math.max(1,Math.ceil(Te/T)),Ce=[];for(let Le=0;Le<je;Le++)Ce.push({start:Le*T,end:Math.min((Le+1)*T,Te)});return{full:$,p:z,b:q,c:re,a:ee,lines:Ce}})();return(0,$e.jsxs)(S,{flexDirection:"column",children:[c==="search"&&(0,$e.jsx)(rs,{history:t,onSelect:ve,onClose:V}),ne&&(0,$e.jsx)(os,{commands:Z,selectedIndex:P}),(0,$e.jsx)(f,{color:v.muted,children:"\u2500".repeat(T)}),F===null?(0,$e.jsxs)(S,{children:[(0,$e.jsx)(f,{color:v.purple,children:"\u276F "}),(0,$e.jsx)(f,{color:v.dimmed,children:n})]}):(0,$e.jsx)(S,{flexDirection:"column",children:F.lines.map(({start:u,end:w},h)=>{let{full:b,p:$,b:z,c:q,a:re}=F,ee=[];return w>0&&u<$&&ee.push((0,$e.jsx)(f,{color:v.purple,children:b.slice(Math.max(u,0),Math.min($,w))},"p")),w>$&&u<z&&ee.push((0,$e.jsx)(f,{children:b.slice(Math.max($,u),Math.min(z,w))},"b")),w>z&&u<q&&ee.push((0,$e.jsx)(f,{color:v.purple,inverse:!0,children:b.slice(Math.max(z,u),Math.min(q,w))},"c")),w>q&&u<re&&ee.push((0,$e.jsx)(f,{children:b.slice(Math.max(q,u),Math.min(re,w))},"a")),w>re&&ee.push((0,$e.jsx)(f,{color:v.dimmed,children:b.slice(Math.max(re,u),w)},"g")),(0,$e.jsx)(S,{children:ee},h)})})]})}var Re=N(Pe(),1);var is=N(Pe(),1);var Hn=N(Q(),1),Fi="#ffc580",Ni="#ffd9a8",ss="#ffffff";function as({text:s,active:e=!0}){let[t,n]=(0,is.useState)(0),r=4;if(kt(()=>{n(a=>(a+1)%(s.length+r*2))},e?80:null),!e)return(0,Hn.jsx)(f,{color:ss,children:s});let o=s.split("").map((a,l)=>{let i=t-r,c=Math.abs(l-i-r/2),d;return c<=r/2?d=Fi:c<=r?d=Ni:d=ss,(0,Hn.jsx)(f,{color:d,children:a},l)});return(0,Hn.jsx)(f,{children:o})}var Ue=N(Q(),1),Ui={starting:v.cyan,running:v.purple,passed:v.green,failed:v.red,cancelled:v.dimmed,timed_out:v.yellow};function Wn({currentStep:s,maxSteps:e,elapsed:t,status:n}){let{stdout:r}=Tt(),o=r?.columns??80,a=Ui[n]??v.purple,l=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,Ue.jsxs)(S,{flexDirection:"column",marginTop:1,children:[(0,Ue.jsx)(f,{color:v.muted,children:"\u2500".repeat(Math.min(o,60))}),(0,Ue.jsxs)(S,{children:[(0,Ue.jsx)(f,{children:" "}),(0,Ue.jsx)(f,{color:v.dimmed,children:"Steps "}),(0,Ue.jsx)(f,{bold:!0,children:s}),(0,Ue.jsxs)(f,{color:v.dimmed,children:["/",e]}),(0,Ue.jsx)(f,{children:" "}),(0,Ue.jsx)(f,{color:v.dimmed,children:"Elapsed "}),(0,Ue.jsx)(f,{bold:!0,children:l}),(0,Ue.jsx)(f,{children:" "}),(0,Ue.jsx)(f,{color:v.dimmed,children:"Status "}),(0,Ue.jsx)(f,{bold:!0,color:a,children:n})]})]})}var Mi={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function ls(s){return Mi[s]??"\u25CF"}var Dt=N(Q(),1);function qr({steps:s,flows:e,cmInitCounts:t,renderStep:n}){return(0,Dt.jsxs)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,Dt.jsxs)(f,{color:v.dimmed,children:["\u2501\u2501 Bifurcated into ",e?.length??s.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),s.map((r,o)=>(0,Dt.jsxs)(S,{flexDirection:"column",marginTop:o>0?1:0,children:[(0,Dt.jsxs)(f,{color:v.purple,children:["Flow ",o+1,": ",e?.[o]??r.objective]}),t&&t[o]!=null&&(0,Dt.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",t[o]," checkpoints"]}),r.children&&r.children.length>0?r.children.map(a=>n(a,`f${o}-${a.index}`)):r.status==="pending"&&(0,Dt.jsx)(f,{color:v.dimmed,children:" \u25CB Waiting..."})]},o))]})}var B=N(Q(),1);function et({step:s,indent:e=2}){let t=s.actionType?ls(s.actionType):null,n=s.status==="running",r=s.status==="passed",o=s.status==="failed",a=s.status==="pending"||s.status==="stopped",{stdout:l}=Tt(),i=l?.columns??80,c=Math.max(20,i-e-21),d=s.objective??"",m=d.length>c?d.slice(0,c-1)+"\u2026":d,g=(s.duration??0)*1e3,p=s.duration!=null?g<1e3?`${Math.round(g)}ms`:`${(g/1e3).toFixed(1)}s`:"";return(0,B.jsxs)(S,{flexDirection:"column",children:[(0,B.jsxs)(S,{marginLeft:e,children:[(0,B.jsx)(S,{width:4,children:(0,B.jsxs)(f,{color:v.muted,children:[String(s.index).padStart(2," ")," "]})}),(0,B.jsx)(S,{width:3,children:n?(0,B.jsx)(No,{}):r?(0,B.jsx)(f,{color:v.green,bold:!0,children:"\u2713"}):o?(0,B.jsx)(f,{color:v.red,bold:!0,children:"\u2717"}):(0,B.jsx)(f,{color:v.muted,children:"\u25CB"})}),(0,B.jsx)(S,{flexGrow:1,children:n?(0,B.jsx)(as,{text:m,active:!0}):o?(0,B.jsx)(f,{color:v.red,children:m}):a?(0,B.jsx)(f,{color:v.dimmed,children:m}):(0,B.jsx)(f,{color:v.greenDim,children:m})}),(r||o)&&t?(0,B.jsx)(S,{width:3,marginLeft:1,children:(0,B.jsx)(f,{color:v.muted,children:t})}):(0,B.jsx)(S,{width:3,marginLeft:1}),(0,B.jsx)(S,{width:7,justifyContent:"flex-end",children:(0,B.jsx)(f,{color:v.dimmed,children:p})})]}),s.children&&s.children.length>0&&(0,B.jsx)(S,{flexDirection:"column",children:s.children.map((_,x)=>(0,B.jsx)(et,{step:_,indent:e+2},`child-${x}`))})]})}function Kn({steps:s,bifurcated:e,flows:t,cmInitCounts:n,maxSteps:r=50,staticSteps:o=!1,onStepCommit:a}){let l=(0,Re.useRef)(new Set),i=(0,Re.useRef)(!1),c=(0,Re.useRef)(new Set),d=(0,Re.useRef)(!1),m=(0,Re.useRef)(new Set),g=(0,Re.useRef)(0);(0,Re.useEffect)(()=>{s.length===0&&g.current>0&&(l.current.clear(),i.current=!1,c.current.clear(),d.current=!1,m.current.clear()),g.current=s.length},[s.length]);let p=s.flatMap(u=>[u,...u.children??[]]),_=p.some(u=>u.status==="running"),x=p.some(u=>u.status==="failed"),C=p.length===0||p.every(u=>u.status==="pending"),T=p.filter(u=>u.status==="passed"||u.status==="failed").length,P;C?P="starting":_?P="running":x?P="failed":P="passed";let R=(0,Re.useRef)(null),[O,te]=(0,Re.useState)(0);(0,Re.useEffect)(()=>{p.length===0||C?(R.current=null,te(0)):_&&R.current==null&&(R.current=Date.now())},[_,C,p.length]),(0,Re.useEffect)(()=>{if(!_)return;let u=setInterval(()=>{R.current!=null&&te((Date.now()-R.current)/1e3)},500);return()=>clearInterval(u)},[_]);let Z=(0,Re.useRef)(new Set),[ne,ve]=(0,Re.useState)([]),V=(0,Re.useRef)(!1);(0,Re.useEffect)(()=>{if(!o||e)return;let u=[];if(!e&&!V.current&&n&&n[0]!=null&&(V.current=!0,n[0]>0&&u.push({key:"cm_init_0",type:"cm_init",count:n[0]})),e){!Z.current.has(-1)&&s.length>0&&(Z.current.add(-1),u.push({key:"bif_header",type:"bifurcation_header",flowCount:t?.length??s.length}));for(let w=0;w<s.length;w++){let h=s[w],b=-(w+10);Z.current.has(b)||(Z.current.add(b),u.push({key:`flow_header_${w}`,type:"flow_header",flowIdx:w,label:t?.[w]??h.objective,cmCount:n?.[w]}));for(let $ of h.children??[])($.status==="passed"||$.status==="failed")&&!Z.current.has($.index)&&(Z.current.add($.index),u.push({key:`step_f${w}_${$.index}`,type:"step",step:{...$}}))}}else for(let w of s)(w.status==="passed"||w.status==="failed")&&!Z.current.has(w.index)&&(Z.current.add(w.index),u.push({key:`step_${w.index}`,type:"step",step:{...w,children:w.children?[...w.children]:void 0}}));u.length>0&&ve(w=>[...w,...u])},[s,e,t,n,o]),(0,Re.useEffect)(()=>{if(a)if(!e&&!d.current&&n&&n[0]!=null&&(d.current=!0,n[0]>0&&a((0,B.jsx)(S,{marginLeft:2,children:(0,B.jsxs)(f,{color:v.dimmed,children:["\u25A0 Generated task with ",n[0]," checkpoints"]})}))),e&&t&&!i.current&&(i.current=!0,a((0,B.jsx)(f,{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"}))),e){let u=s.flatMap((w,h)=>{let b=w.children??[];return!c.current.has(h)&&b.length>0&&(c.current.add(h),a((0,B.jsx)(f,{color:"#b388ff",children:" Flow "+(h+1)+": "+(t?.[h]??"")})),n?.[h]!=null&&n[h]>0&&!m.current.has(h)&&(m.current.add(h),a((0,B.jsx)(S,{marginLeft:2,children:(0,B.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",n[h]," checkpoints"]})})))),n?.[h]!=null&&n[h]>0&&c.current.has(h)&&!m.current.has(h)&&(m.current.add(h),a((0,B.jsx)(S,{marginLeft:2,children:(0,B.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",n[h]," checkpoints"]})}))),b});for(let w of u){let h=`${w.index}-${w.objective}`;l.current.has(h)||(w.status==="passed"||w.status==="failed"||w.status==="stopped")&&(l.current.add(h),a((0,B.jsx)(S,{marginLeft:2,children:(0,B.jsx)(et,{step:w})})))}}else for(let u of s){let w=`${u.index}-${u.objective}`,h=!!u.branchObjective;h&&!l.current.has(w)&&(l.current.add(w),a((0,B.jsx)(S,{marginLeft:2,children:(0,B.jsx)(et,{step:{...u,children:void 0}})})));for(let b of u.children??[]){let $=`child-${u.index}-${b.index}-${b.objective}`;l.current.has($)||(b.status==="passed"||b.status==="failed"||b.status==="stopped")&&(l.current.add($),a((0,B.jsx)(S,{marginLeft:4,children:(0,B.jsx)(et,{step:b})})))}!h&&!l.current.has(w)&&(u.status==="passed"||u.status==="failed"||u.status==="stopped")&&(l.current.add(w),a((0,B.jsx)(S,{marginLeft:2,children:(0,B.jsx)(et,{step:{...u,children:void 0}})})))}},[s,a,e,t,n]);let F=[];if(a)if(e)for(let u of s){let h=(u.children??[]).filter(b=>{let $=`${b.index}-${b.objective}`;return!l.current.has($)});h.length>0&&F.push({...u,children:h})}else for(let u of s){let w=`${u.index}-${u.objective}`,h=l.current.has(w),b=(u.children??[]).filter($=>{let z=`child-${u.index}-${$.index}-${$.objective}`;return!l.current.has(z)});h?b.length>0&&F.push({...u,children:b}):F.push({...u,children:b})}else if(o){if(!e)for(let u of s)Z.current.has(u.index)||F.push(u)}if(!o){let u=a?F:s;return(0,B.jsxs)(S,{flexDirection:"column",children:[e?a?u.length>0?(0,B.jsx)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:u.map((h,b)=>(0,B.jsx)(S,{flexDirection:"column",marginTop:b>0?1:0,children:h.children&&h.children.length>0?h.children.map($=>(0,B.jsx)(et,{step:$},`f${b}-${$.index}`)):h.status==="pending"&&(0,B.jsx)(f,{color:v.dimmed,children:" \u25CB Waiting..."})},b))}):null:(0,B.jsx)(qr,{steps:s,flows:t,cmInitCounts:n,renderStep:(h,b)=>(0,B.jsx)(et,{step:h},b)}):(0,B.jsxs)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&n&&n[0]!=null&&(0,B.jsxs)(f,{color:v.dimmed,children:["\u25AA Generated task with ",n[0]," checkpoints"]}),u.map(h=>{let b=`${h.index}-${h.objective}`;return a&&l.current.has(b)?(0,B.jsx)(S,{flexDirection:"column",children:(h.children??[]).map($=>(0,B.jsx)(S,{marginLeft:2,children:(0,B.jsx)(et,{step:$})},$.index))},`branch-children-${h.index}`):(0,B.jsx)(et,{step:h},h.index)})]}),_&&(0,B.jsx)(Wn,{currentStep:T,maxSteps:r,elapsed:O,status:P})]})}return e?(0,B.jsxs)(S,{flexDirection:"column",children:[(0,B.jsx)(qr,{steps:s,flows:t,cmInitCounts:n,renderStep:(u,w)=>(0,B.jsx)(et,{step:u},w)}),_&&(0,B.jsx)(Wn,{currentStep:T,maxSteps:r,elapsed:O,status:P})]}):(0,B.jsxs)(S,{flexDirection:"column",children:[(0,B.jsx)(Xt,{items:ne,children:u=>u.type==="cm_init"?(0,B.jsx)(S,{marginLeft:2,paddingLeft:1,children:(0,B.jsxs)(f,{color:v.dimmed,children:["\u25AA Generated task with ",u.count," checkpoints"]})},u.key):u.type==="bifurcation_header"?(0,B.jsx)(S,{marginLeft:2,paddingLeft:1,children:(0,B.jsxs)(f,{color:v.dimmed,children:["\u2501\u2501 Bifurcated into ",u.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},u.key):u.type==="flow_header"?(0,B.jsxs)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,B.jsxs)(f,{color:v.purple,children:["Flow ",u.flowIdx+1,": ",u.label]}),u.cmCount!=null&&(0,B.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",u.cmCount," checkpoints"]})]},u.key):(0,B.jsx)(S,{marginLeft:2,paddingLeft:1,children:(0,B.jsx)(et,{step:u.step})},u.key)}),F.length>0&&(0,B.jsx)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:F.map(u=>(0,B.jsx)(et,{step:u},u.index))}),_&&(0,B.jsx)(Wn,{currentStep:T,maxSteps:r,elapsed:O,status:P})]})}var zr=N(Pe(),1);var Gn=N(Q(),1),cs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function qn({label:s,hasBifurcation:e=!1}){let[t,n]=(0,zr.useState)(0),[r,o]=(0,zr.useState)(0);kt(()=>{n(l=>(l+1)%cs.length)},80),kt(()=>{o(l=>(l+1)%4)},400);let a=s??(e?"Planning approach":"Analyzing objective");return(0,Gn.jsxs)(S,{marginLeft:1,children:[(0,Gn.jsxs)(f,{color:v.primary,children:[cs[t]," "]}),(0,Gn.jsxs)(f,{color:v.dim,children:[a,".".repeat(r+1)]})]})}function zn(s){if(!s.isRunning)return null;let e=s.bifurcationInfo;if(e&&!e.isSingleFlow){let t=s.steps.findIndex(r=>r.status==="running");return(t===-1?s.cmInitCounts.length===0:t>=s.cmInitCounts.length)?{label:t>0?`Planning flow ${t+1}`:void 0,hasBifurcation:!0}:null}return s.cmInitCounts.length>0||s.steps.some(t=>t.children?.length)?null:{hasBifurcation:!!e}}var bt=N(Pe(),1);var Me=N(Q(),1);function Hi(s,e){let t=[],r=Math.max(e-4,30);t.push({type:"title",text:s.title});for(let o=0;o<s.sections.length;o++){let a=s.sections[o];o>0&&t.push({type:"divider",text:"\u2500".repeat(r)}),a.label&&t.push({type:"header",text:a.label});let l=a.entries.length>0?Math.max(...a.entries.map(i=>i.key.length)):0;for(let i of a.entries){let c="\xB7".repeat(Math.max(2,l-i.key.length+3)),d=`${i.key} ${c} ${i.value}`;t.push({type:"entry",text:d,color:i.color})}}return t.push({type:"footer",text:"esc back"}),t}function us({data:s,width:e=60}){let t=Hi(s,e);return(0,Me.jsx)(S,{flexDirection:"column",borderStyle:"round",borderColor:v.primary,paddingX:2,paddingY:1,children:t.map((n,r)=>{if(n.type==="title")return(0,Me.jsx)(f,{color:v.primary,bold:!0,children:n.text},r);if(n.type==="header")return(0,Me.jsx)(S,{marginTop:1,children:(0,Me.jsx)(f,{color:v.dim,children:n.text})},r);if(n.type==="divider")return(0,Me.jsx)(S,{marginTop:1,marginBottom:0,children:(0,Me.jsx)(f,{color:v.ambient,children:n.text})},r);if(n.type==="footer")return(0,Me.jsx)(S,{marginTop:1,children:(0,Me.jsx)(f,{color:v.dim,children:n.text})},r);let o=n.text.match(/^(.+?) (·+) (.+)$/);return o?(0,Me.jsxs)(f,{children:[(0,Me.jsxs)(f,{color:v.secondary,children:[o[1]," "]}),(0,Me.jsxs)(f,{color:v.ambient,children:[o[2]," "]}),(0,Me.jsx)(f,{color:n.color??v.base,children:o[3]})]},r):(0,Me.jsx)(f,{color:n.color??v.base,children:n.text},r)})})}var Be=N(Q(),1);function Jr(s,e){let t=[];function n(r,o){for(let a of r)t.push({item:a,depth:o}),a.type==="submenu"&&a.children&&e.length>o&&e[o]===a.id&&n(a.children,o+1)}return n(s,0),t}function Xr({items:s,onRunSelected:e,initialExpandedPath:t,onDismiss:n,renderLoginWizard:r,renderProfilesView:o,renderChromeProfilePicker:a,renderProjectPicker:l,renderFolderPicker:i,renderWindowSizePicker:c}){let[d,m]=(0,bt.useState)(()=>{let T=t??[],P=Jr(s,T),R=0;if(T.length>0){let O=P.findIndex(te=>te.item.id===T[0]);O>=0&&O+1<P.length&&(R=O+1)}return{expandedPath:T,selectedIndex:R,inputValue:"",isEditing:!1,isSelecting:!1,feedback:null,activeView:null,infoData:null}}),g=Jr(s,d.expandedPath),p=g[d.selectedIndex]?.item,_=(0,bt.useRef)(null),x=(0,bt.useCallback)(T=>{m(P=>({...P,feedback:T})),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{m(P=>({...P,feedback:null})),_.current=null},4e3)},[]);(0,bt.useEffect)(()=>()=>{_.current&&clearTimeout(_.current)},[]);let C=(0,bt.useCallback)(()=>{m(T=>({...T,activeView:null,infoData:null}))},[]);return Oe((T,P)=>{if(d.activeView==="infoView"){P.escape&&C();return}if(!(d.activeView==="loginWizard"||d.activeView==="profilesView"||d.activeView==="chromeProfilePicker"||d.activeView==="projectPicker"||d.activeView==="folderPicker"||d.activeView==="windowSizePicker")){if(d.isEditing){if(P.escape){m(R=>({...R,isEditing:!1,inputValue:""}));return}if(P.return){let R=d.inputValue.trim();if(p?.onValue&&R){let O=p.currentValue;p.onValue(R),x(O?`${p.label}: ${O} \u2192 ${R}`:`${p.label}: ${R}`)}m(O=>({...O,isEditing:!1,inputValue:""}));return}if(P.backspace||P.delete){m(R=>({...R,inputValue:R.inputValue.slice(0,-1)}));return}T&&!P.ctrl&&!P.meta&&m(R=>({...R,inputValue:R.inputValue+T}));return}if(d.isSelecting&&p?.options){let R=p.options;if(P.escape){m(O=>({...O,isSelecting:!1}));return}if(P.upArrow){m(O=>({...O,inputValue:String(Math.max(0,Number(O.inputValue||"0")-1))}));return}if(P.downArrow){m(O=>({...O,inputValue:String(Math.min(R.length-1,Number(O.inputValue||"0")+1))}));return}if(P.return){let O=Number(d.inputValue||"0"),te=R[O];if(te&&p.onValue){let Z=p.currentValue;p.onValue(te.value),x(Z?`${p.label}: ${Z} \u2192 ${te.label}`:`${p.label}: ${te.label}`)}m(Z=>({...Z,isSelecting:!1,inputValue:""}));return}return}if(P.upArrow){m(R=>({...R,selectedIndex:Math.max(0,R.selectedIndex-1)}));return}if(P.downArrow){m(R=>({...R,selectedIndex:Math.min(g.length-1,R.selectedIndex+1)}));return}if(P.escape){if(d.expandedPath.length===0){n?.();return}m(R=>{let O=R.expandedPath.slice(0,-1),te=Jr(s,O),Z=R.expandedPath[R.expandedPath.length-1],ne=te.findIndex(ve=>ve.item.id===Z);return{...R,expandedPath:O,selectedIndex:ne>=0?ne:0}});return}if(P.return&&p){if(p.id==="run-start"){e();return}if(p.type==="submenu"){let R=g[d.selectedIndex]?.depth??0;m(O=>({...O,expandedPath:[...O.expandedPath.slice(0,R),p.id],selectedIndex:O.selectedIndex+1}));return}if(p.onInfo){let R=p.onInfo();m(O=>({...O,activeView:"infoView",infoData:R}));return}if(p.onLoginWizard){p.onLoginWizard(),m(R=>({...R,activeView:"loginWizard"}));return}if(p.onProfilesView){p.onProfilesView(),m(R=>({...R,activeView:"profilesView"}));return}if(p.onChromeProfilePicker){p.onChromeProfilePicker(),m(R=>({...R,activeView:"chromeProfilePicker"}));return}if(p.onProjectPicker){p.onProjectPicker(),m(R=>({...R,activeView:"projectPicker"}));return}if(p.onFolderPicker){p.onFolderPicker(),m(R=>({...R,activeView:"folderPicker"}));return}if(p.onWindowSizePicker){p.onWindowSizePicker(),m(R=>({...R,activeView:"windowSizePicker"}));return}if(p.type==="action"){p.onAction?.(),p.suppressFeedback||x(`${p.label} done`);return}if(p.type==="select"&&p.options){let R=p.options.findIndex(O=>O.value===p.currentValue);m(O=>({...O,isSelecting:!0,inputValue:String(Math.max(0,R))}));return}if(p.type==="text-input"){m(R=>({...R,isEditing:!0,inputValue:p.currentValue??""}));return}}}}),(0,Be.jsx)(S,{flexDirection:"column",paddingX:1,children:d.activeView==="infoView"&&d.infoData?(0,Be.jsx)(us,{data:d.infoData}):d.activeView==="loginWizard"&&r?r(C):d.activeView==="profilesView"&&o?o(C):d.activeView==="chromeProfilePicker"&&a?a(C):d.activeView==="projectPicker"&&l?l(C):d.activeView==="folderPicker"&&i?i(C):d.activeView==="windowSizePicker"&&c?c(C):(0,Be.jsxs)(Be.Fragment,{children:[g.map(({item:T,depth:P},R)=>{let O=R===d.selectedIndex,te=" ".repeat(P),Z=O?"\u276F ":" ",ne=T.type==="submenu"?d.expandedPath.includes(T.id)?"\u25BC ":"\u25B6 ":" ",ve=T.currentValue!=null?` [${T.currentValue}]`:"";if(O&&d.isSelecting&&T.options){let V=Number(d.inputValue||"0");return(0,Be.jsxs)(S,{flexDirection:"column",children:[(0,Be.jsxs)(f,{color:v.cyan,children:[te,Z,ne,T.label]}),T.options.map((F,u)=>(0,Be.jsxs)(f,{color:u===V?v.cyan:void 0,children:[te," ",u===V?"\u276F ":" ",F.label]},F.value))]},T.id)}return O&&d.isEditing?(0,Be.jsxs)(f,{color:v.cyan,children:[te,Z,ne,T.label,": ",d.inputValue,(0,Be.jsx)(f,{color:v.dimmed,children:"\u2588"})]},T.id):(0,Be.jsxs)(f,{color:O?v.cyan:void 0,dimColor:!O&&P>0,children:[te,Z,ne,T.label,(0,Be.jsx)(f,{dimColor:!0,children:ve})]},T.id)}),d.feedback&&(0,Be.jsx)(S,{marginTop:1,children:(0,Be.jsxs)(f,{color:v.green,children:["\u2713 ",d.feedback]})})]})})}var _n=N(Pe(),1);var De=N(Q(),1),Yr=800,Qr=3840,Zr=600,eo=2160;function ds(s,e){if(!e)return"Enter a value";let t=Number(e);if(!Number.isInteger(t))return"Must be a whole number";if(s==="width"){if(t<Yr)return`Min ${Yr}`;if(t>Qr)return`Max ${Qr}`}else{if(t<Zr)return`Min ${Zr}`;if(t>eo)return`Max ${eo}`}return null}function to({currentWidth:s,currentHeight:e,onSelect:t,onCancel:n}){let[r,o]=(0,_n.useState)("width"),[a,l]=(0,_n.useState)(String(s)),[i,c]=(0,_n.useState)(String(e)),[d,m]=(0,_n.useState)(null);Oe((p,_)=>{if(_.escape){n();return}if(_.tab||_.rightArrow||_.leftArrow){o(x=>x==="width"?"height":"width"),m(null);return}if(_.return){let x=ds("width",a);if(x){o("width"),m(`Width: ${x}`);return}let C=ds("height",i);if(C){o("height"),m(`Height: ${C}`);return}t(Number(a),Number(i));return}if(_.backspace||_.delete){r==="width"?l(x=>x.slice(0,-1)):c(x=>x.slice(0,-1)),m(null);return}p&&/^\d$/.test(p)&&(r==="width"?l(x=>x+p):c(x=>x+p),m(null))});let g=(p,_,x)=>{let C=r===x,T=C?v.primary:v.secondary;return(0,De.jsxs)(S,{flexDirection:"column",children:[(0,De.jsxs)(f,{color:v.dim,children:[" ",p]}),(0,De.jsx)(S,{borderStyle:"round",borderColor:T,paddingX:1,width:10,children:(0,De.jsxs)(f,{color:C?v.base:v.dim,children:[_||" ",C?(0,De.jsx)(f,{color:v.dimmed,children:"\u2588"}):""]})}),(0,De.jsxs)(f,{color:v.dim,dimColor:!0,children:[" ",x==="width"?`${Yr}\u2013${Qr}`:`${Zr}\u2013${eo}`]})]})};return(0,De.jsxs)(S,{flexDirection:"column",paddingX:1,children:[(0,De.jsx)(f,{color:v.primary,bold:!0,children:"Window Size"}),(0,De.jsxs)(S,{marginTop:1,gap:1,children:[g("Width",a,"width"),(0,De.jsx)(S,{alignItems:"center",marginTop:1,children:(0,De.jsx)(f,{color:v.dim,children:"x"})}),g("Height",i,"height")]}),d&&(0,De.jsx)(S,{marginTop:1,children:(0,De.jsx)(f,{color:v.red,children:d})}),(0,De.jsx)(S,{marginTop:1,children:(0,De.jsx)(f,{color:v.dim,children:"Tab/arrows to switch Enter to save Esc to cancel"})})]})}import{randomUUID as Wi}from"crypto";import{mkdirSync as Ki,writeFileSync as fs,appendFileSync as Gi,existsSync as ms}from"fs";import{join as bn}from"path";var qi=bn(Se,"sessions"),xt=class{sessionId;sessionDir;runs=[];_flows=[];_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=Wi(),this.sessionDir=bn(qi,this.sessionId)}start(e){if(!this._started){this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString();try{Ki(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"};fs(bn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
26
- `)}catch{}this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`),this._earlyLogBuffer.push({level:"info",event:"SESSION_START",message:"Session started",context:{session_id:this.sessionId}},{level:"info",event:"CONFIG",message:"Session config",context:{model:e.model,environment:e.environment,profile:e.profile}})}}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 l=e.indexOf(" "),i=l>0?e.slice(0,l):e,c=l>0?e.slice(l+1):"",d=/fail|error/i.test(e)?"error":"info";this._remoteLogger?.log(d,i,c||e);return}let o=e,a=n;this._log(`${t} ${a}`),this._remoteLogger?.log(o,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 o=(n??0).toFixed(1),a=(r??"").slice(0,100);this._log(`RUN ${e} END status=${t} duration=${o}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}))};ms(this.sessionDir)&&fs(bn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
27
- `)}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}))}}addFlow(e){let t={...e,index:this._flows.length+1};return this._flows.push(t),t}getFlows(){return[...this._flows]}getFlow(e){return this._flows.find(t=>t.index===e)}clearFlows(){this._flows=[]}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 o=0;o<r;o++)e.push(n)}return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e){if(!(!this._started||!ms(this.sessionDir)))try{let t=new Date().toISOString().slice(0,19).replace("T"," "),n=bn(this.sessionDir,"tui.log");Gi(n,`[${t}] ${e}
28
- `)}catch{}}};import{dirname as zi,join as Ji}from"path";function xn(s,e,t){let n=s.total_runs??1,r=s.run_dir,o,a;if(n>1&&r){let l=zi(r);o=Array.from({length:n},(i,c)=>Ji(l,String(e+c))),t&&t.length===n&&(a=t)}return{allRunDirs:o,flowObjectives:a}}function wn(s,e,t,n){return{index:t,objective:e,summary:s.summary,oneLiner:s.one_liner,status:s.status,resultCode:s.result_code,reasonCode:s.reason_code,perFlowMetadata:s.per_flow_metadata,context:s.context??{memory:{},variables:{},pointer:""},run_dir:s.run_dir,run_dirs:n.allRunDirs,flow_objectives:n.flowObjectives}}import{readFileSync as Xi,writeFileSync as ps,mkdirSync as gs}from"fs";import{dirname as hs}from"path";var Jn={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:ft,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",code_export:{enabled:!1,language:"python",skip_validation:!0}},tt=class{constructor(e=Fo){this.path=e}load(){try{let e=Xi(this.path,"utf-8"),t=JSON.parse(e);return{...Jn,...t,code_export:{...Jn.code_export,...t.code_export??{}}}}catch{return{...Jn,code_export:{...Jn.code_export}}}}set(e,t){try{let n=this.load();n[e]=t,gs(hs(this.path),{recursive:!0}),ps(this.path,JSON.stringify(n,null,2)+`
24
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(r=>t.is(r))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function ei(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n="127.0.0.1",r="9229",o;return(o=e.match(/^(--inspect(-brk)?)$/))!==null?t=o[1]:(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=o[1],/^\d+$/.test(o[3])?r=o[3]:n=o[3]):(o=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=o[1],n=o[3],r=o[4]),t&&r!=="0"?`${t}=${n}:${parseInt(r)+1}`:e})}ti.Command=Ro});var ii=Mt(st=>{"use strict";var{Argument:ri}=_r(),{Command:Ao}=ni(),{CommanderError:Ha,InvalidArgumentError:oi}=In(),{Help:Wa}=_o(),{Option:si}=yo();st.program=new Ao;st.createCommand=s=>new Ao(s);st.createOption=(s,e)=>new si(s,e);st.createArgument=(s,e)=>new ri(s,e);st.Command=Ao;st.Option=si;st.Argument=ri;st.Help=Wa;st.CommanderError=Ha;st.InvalidArgumentError=oi;st.InvalidOptionArgumentError=oi});var Io=U(De(),1);import Ze from"process";var $=U(De(),1);var he=U(Q(),1);function Qo({profile:s,environment:e,model:t,tokenValid:n,sessionId:r,runCount:o,viewMode:a}){let{stdout:l}=At(),i=l?.columns??80,c=e==="stage";return(0,he.jsxs)(y,{flexDirection:"column",children:[(0,he.jsx)(f,{color:v.muted,children:"\u2500".repeat(i)}),(0,he.jsx)(y,{paddingX:1,children:(0,he.jsxs)(y,{gap:1,children:[(0,he.jsx)(f,{color:v.dimmed,children:"Model:"}),(0,he.jsx)(f,{color:v.dimmed,children:t}),(0,he.jsx)(f,{color:v.muted,children:"|"}),(0,he.jsx)(f,{color:v.dimmed,children:"Session:"}),(0,he.jsx)(f,{color:v.dimmed,children:r.slice(-6)}),(0,he.jsx)(f,{color:v.muted,children:"|"}),(0,he.jsx)(f,{color:n?v.green:v.red,children:"\u25CF"}),(0,he.jsx)(f,{color:v.dimmed,children:n?"authenticated":"not logged in"})]})}),(0,he.jsx)(y,{paddingX:1,children:(0,he.jsxs)(y,{gap:1,children:[(0,he.jsx)(f,{color:v.dimmed,children:s??"no profile"}),(0,he.jsx)(f,{color:v.muted,children:"|"}),c?(0,he.jsx)(f,{color:v.yellow,bold:!0,children:"\u26A0 stage"}):(0,he.jsx)(f,{color:v.green,children:e}),(0,he.jsx)(f,{color:v.muted,children:"|"}),(0,he.jsxs)(f,{color:v.dimmed,children:["runs: ",o]})]})}),(0,he.jsx)(y,{paddingX:1,children:(0,he.jsx)(f,{dimColor:!0,children:a==="chat"?"ctrl+c cancel/exit":"\u2191\u2193 navigate \u21B5 select esc back"})})]})}var Zo=U(De(),1);import{readFileSync as Ti,writeFileSync as ki,mkdirSync as Ii}from"fs";import{dirname as Pi,join as Oi}from"path";var Di=Oi(Ee,"command-history.json"),ji=200,Nr=class{entries;filePath;max;constructor(e=Di,t=ji){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=Ti(this.filePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}_save(){try{Ii(Pi(this.filePath),{recursive:!0}),ki(this.filePath,JSON.stringify(this.entries)+`
25
+ `)}catch{}}};function Fn(s){let e=(0,Zo.useRef)(null);return e.current||(e.current=new Nr(s)),e.current}var Wt=U(De(),1);var vn=[[[" "],[" "],[" "],[" "],["\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 se=U(Q(),1),Nn="#af87d7",Ur="#875faf",es="#5b3a7a",Li="#ff9500",$i="#ea580c";var Mr="#666666",Bi="#555555",Ht=[[Nn,"\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"],[Nn,"\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"],[Nn,"\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"],[Nn,"\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"],[Ur,"\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"],[Ur,"\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"],[Ur,"\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"]],Hr=Ht.map(([,s])=>[...s]);function ts({visibleRows:s=Ht.length}){let e=Math.min(s,Ht.length);return(0,se.jsxs)(y,{flexDirection:"column",children:[Ht.slice(0,e).map(([t,n],r)=>{let o=Hr[r];return(0,se.jsx)(f,{children:o.map((a,l)=>{if(a==="\u2588")return(0,se.jsx)(f,{color:t,children:"\u2588"},l);let i=l>0&&o[l-1]==="\u2588",c=r>0&&l>0&&Hr[r-1][l-1]==="\u2588";return i||c?(0,se.jsx)(f,{color:es,children:"\u2592"},l):(0,se.jsx)(f,{children:" "},l)})},r)}),e>=Ht.length&&(0,se.jsxs)(f,{children:[" ",Hr[Ht.length-1].map((t,n)=>t==="\u2588"?(0,se.jsx)(f,{color:es,children:"\u2580"},n):(0,se.jsx)(f,{children:" "},n))]})]})}function Vi({visibleRows:s=vn.length}){let e=Math.min(s,vn.length);return(0,se.jsx)(y,{flexDirection:"column",children:vn.slice(0,e).map((t,n)=>(0,se.jsx)(f,{children:t.map((r,o)=>{let a=r[0],l=r[1],i=r[2];return l?(0,se.jsx)(f,{color:l,backgroundColor:i,children:a},o):(0,se.jsx)(f,{children:a},o)})},n))})}function Un({size:s="compact",helmetVisibleRows:e=vn.length,textVisibleRows:t=Ht.length,showMeta:n=!1,user:r=null,authenticated:o=!1,version:a=""}){return s==="compact"?(0,se.jsx)(ts,{}):(0,se.jsxs)(y,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,se.jsx)(f,{color:Li,italic:!0,children:" Welcome to"}),(0,se.jsx)(f,{children:" "}),(0,se.jsxs)(y,{gap:2,children:[(0,se.jsx)(Vi,{visibleRows:e}),(0,se.jsxs)(y,{flexDirection:"column",children:[(0,se.jsx)(ts,{visibleRows:t}),(0,se.jsx)(y,{justifyContent:"flex-end",width:73,children:(0,se.jsx)(f,{color:$i,italic:!0,children:"Command-line interface"})})]})]}),n&&(0,se.jsxs)(se.Fragment,{children:[(0,se.jsx)(f,{children:" "}),(0,se.jsxs)(f,{children:[(0,se.jsx)(f,{color:Mr,children:" Browser automation powered by AI. "}),(0,se.jsx)(f,{color:Bi,children:`v${a}`})]}),(0,se.jsx)(f,{children:" "}),(0,se.jsx)(f,{children:(0,se.jsx)(f,{color:Mr,children:" KaneCLI can navigate websites, fill forms, test web UI, and extract"})}),(0,se.jsx)(f,{children:(0,se.jsx)(f,{color:Mr,children:" data \u2014 right from your terminal."})}),(0,se.jsx)(f,{children:" "})]})]})}var Gr=U(Q(),1),Wr=8,Kr=7;function ns({onComplete:s}){let[e,t]=(0,Wt.useState)(0),[n,r]=(0,Wt.useState)(0),[o,a]=(0,Wt.useState)(!1),[l]=(0,Wt.useState)(()=>{let i=new He,c=i.getActiveProfile(),d=i.getDefaultEnv(),m=c?i.loadCredentials(c,d):null,g=c?i.loadBasicAuth(c,d):null;return{authenticated:!!(m||g),user:g?.username??c??null}});return Tt(()=>{t(i=>Math.min(Wr,i+1))},e<Wr?60:null),Tt(()=>{r(i=>Math.min(Kr,i+1))},n<Kr?80:null),(0,Wt.useEffect)(()=>{e>=Wr&&n>=Kr&&!o&&(a(!0),s?.())},[e,n,o,s]),(0,Gr.jsx)(y,{flexDirection:"column",children:(0,Gr.jsx)(Un,{size:"full",helmetVisibleRows:e,textVisibleRows:n,showMeta:o,user:l.user,authenticated:l.authenticated,version:en})})}var ht=U(Q(),1);function rs({entry:s}){return s.type==="input"?(0,ht.jsxs)(y,{children:[(0,ht.jsx)(f,{color:v.purple,children:"\u276F "}),(0,ht.jsx)(f,{children:s.text})]}):s.type==="error"?(0,ht.jsx)(y,{marginLeft:2,children:(0,ht.jsx)(f,{color:v.red,children:s.text})}):(0,ht.jsx)(y,{marginLeft:2,children:(0,ht.jsx)(f,{color:s.type==="info"?v.dimmed:void 0,children:s.text})})}var vt=U(De(),1);var qr=U(De(),1);var ct=U(Q(),1);function os({history:s,onSelect:e,onClose:t}){let[n,r]=(0,qr.useState)(""),[o,a]=(0,qr.useState)(0),l=n?s.search(n).slice(0,8):[];return je((i,c)=>{if(c.escape){t();return}if(c.return){l.length>0&&l[o]?e(l[o]):t();return}if(c.upArrow){a(d=>Math.max(0,d-1));return}if(c.downArrow){a(d=>Math.min(l.length-1,d+1));return}if(c.backspace||c.delete){r(d=>d.slice(0,-1)),a(0);return}i&&!c.ctrl&&!c.meta&&(r(d=>d+i),a(0))}),(0,ct.jsxs)(y,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,ct.jsx)(f,{color:v.muted,bold:!0,children:"reverse search"}),(0,ct.jsxs)(y,{gap:1,children:[(0,ct.jsx)(f,{color:v.dimmed,children:"search:"}),(0,ct.jsx)(f,{children:n}),(0,ct.jsx)(f,{color:v.purple,children:"\u2588"})]}),l.length>0&&(0,ct.jsx)(f,{children:" "}),l.map((i,c)=>(0,ct.jsx)(y,{marginLeft:2,children:(0,ct.jsxs)(f,{color:c===o?v.purple:v.dimmed,bold:c===o,children:[c===o?"\u25B8 ":" ",i]})},`${c}-${i}`))]})}var Pt=U(Q(),1);function ss({commands:s,selectedIndex:e}){return s.length===0?null:(0,Pt.jsx)(y,{flexDirection:"column",marginBottom:0,children:s.map((t,n)=>{let r=n===e;return(0,Pt.jsxs)(y,{children:[(0,Pt.jsx)(f,{color:r?v.primary:v.dimmed,children:r?"\u276F ":" "}),(0,Pt.jsxs)(f,{color:r?v.primary:void 0,bold:r,children:["/",t.name]}),t.args&&(0,Pt.jsxs)(f,{color:v.dimmed,children:[" ",t.args]}),(0,Pt.jsxs)(f,{color:v.dimmed,children:[" ",t.description]})]},t.name)})})}var Be=U(Q(),1);function Mn({onSubmit:s,onEscape:e,history:t,placeholder:n="Type an objective or /command...",commands:r}){let[o,a]=(0,vt.useState)([]),[l,i]=(0,vt.useState)(0),[c,d]=(0,vt.useState)("none"),[m,g]=(0,vt.useState)(-1),p=(0,vt.useRef)(""),[_,b]=(0,vt.useState)(!0),{stdout:E}=At(),A=E?.columns??80,[P,C]=(0,vt.useState)(0),O=o.join(""),te=(()=>{if(c!=="none"||o.length===0)return"";if(O.startsWith("/")&&r&&O.length>=2){let x=O.slice(1).toLowerCase(),h=r.find(I=>I.name.startsWith(x)&&I.name!==x);return h?`/${h.name}`.slice(O.length):""}if(O.startsWith("/"))return"";let u=t.getAll();for(let x=u.length-1;x>=0;x--)if(u[x].startsWith(O)&&u[x]!==O)return u[x].slice(O.length);return""})(),Z=(()=>{if(!r||!O.startsWith("/"))return[];let u=O.length>=2?O.slice(1).toLowerCase():"";return u&&r.some(x=>x.name===u)?[]:r.filter(x=>!u||x.name.startsWith(u))})(),ne=Z.length>0&&O.startsWith("/");je((u,x)=>{if(_&&u&&b(!1),x.return){if(ne&&Z[P]){let h=`/${Z[P].name}`;a([...h]),i(h.length),C(0);return}O.trim()&&(t.push(O.trim()),s(O.trim()),a([]),i(0),d("none"),g(-1),p.current="",b(!0),C(0));return}if(x.escape){c!=="none"?d("none"):o.length>0?(a([]),i(0),g(-1),p.current=""):e?.();return}if(x.tab){if(te){let h=O+te;a([...h]),i(h.length);return}return}if(x.ctrl&&u==="r"){d("search");return}if(x.ctrl&&u==="a"){i(0);return}if(x.ctrl&&u==="e"){i(o.length);return}if(x.ctrl&&u==="w"){if(l===0)return;let h=l-1;for(;h>0&&o[h]===" ";)h--;for(;h>0&&o[h-1]!==" ";)h--;let I=[...o.slice(0,h),...o.slice(l)];a(I),i(h);return}if(x.ctrl&&u==="u"){a([]),i(0),g(-1),d("none");return}if(x.meta&&u==="b"){let h=l-1;for(;h>0&&o[h]===" ";)h--;for(;h>0&&o[h-1]!==" ";)h--;i(Math.max(0,h));return}if(x.meta&&u==="f"){let h=l;for(;h<o.length&&o[h]!==" ";)h++;for(;h<o.length&&o[h]===" ";)h++;i(h);return}if(x.leftArrow){i(h=>Math.max(0,h-1));return}if(x.rightArrow){if(l>=o.length&&te){let h=O+te;a([...h]),i(h.length)}else i(h=>Math.min(o.length,h+1));return}if(x.upArrow){if(ne){C(h=>Math.max(0,h-1));return}if(c==="none"){let h=t.getAll();if(h.length===0)return;if(m===-1){p.current=O,g(h.length-1);let I=h[h.length-1];a([...I]),i(I.length)}else if(m>0){let I=m-1;g(I);let B=h[I];a([...B]),i(B.length)}}return}if(x.downArrow){if(ne){C(h=>Math.min(Z.length-1,h+1));return}if(c==="none"){let h=t.getAll();if(m===-1)return;if(m<h.length-1){let I=m+1;g(I);let B=h[I];a([...B]),i(B.length)}else{g(-1);let I=p.current;a([...I]),i(I.length)}}return}if(x.backspace||x.delete){if(l>0){let h=[...o.slice(0,l-1),...o.slice(l)];a(h),i(l-1),g(-1),C(0)}return}if(u&&!x.ctrl&&!x.meta){let h=[...o.slice(0,l),...u,...o.slice(l)];a(h),i(l+u.length),g(-1),C(0)}},{isActive:c!=="search"});let _e=u=>{a([...u]),i(u.length),d("none")},F=()=>{d("none")},N=(()=>{if(_&&o.length===0)return null;let u=l>=o.length,x=o.slice(0,l).join(""),h=u?" ":o[l],I=u?"":o.slice(l+1).join(""),B="\u276F "+x+h+I+te,D=2,J=D+x.length,re=J+1,ee=re+I.length,Ie=B.length,me=Math.max(1,Math.ceil(Ie/A)),Re=[];for(let $e=0;$e<me;$e++)Re.push({start:$e*A,end:Math.min(($e+1)*A,Ie)});return{full:B,p:D,b:J,c:re,a:ee,lines:Re}})();return(0,Be.jsxs)(y,{flexDirection:"column",children:[c==="search"&&(0,Be.jsx)(os,{history:t,onSelect:_e,onClose:F}),ne&&(0,Be.jsx)(ss,{commands:Z,selectedIndex:P}),(0,Be.jsx)(f,{color:v.muted,children:"\u2500".repeat(A)}),N===null?(0,Be.jsxs)(y,{children:[(0,Be.jsx)(f,{color:v.purple,children:"\u276F "}),(0,Be.jsx)(f,{color:v.dimmed,children:n})]}):(0,Be.jsx)(y,{flexDirection:"column",children:N.lines.map(({start:u,end:x},h)=>{let{full:I,p:B,b:D,c:J,a:re}=N,ee=[];return x>0&&u<B&&ee.push((0,Be.jsx)(f,{color:v.purple,children:I.slice(Math.max(u,0),Math.min(B,x))},"p")),x>B&&u<D&&ee.push((0,Be.jsx)(f,{children:I.slice(Math.max(B,u),Math.min(D,x))},"b")),x>D&&u<J&&ee.push((0,Be.jsx)(f,{color:v.purple,inverse:!0,children:I.slice(Math.max(D,u),Math.min(J,x))},"c")),x>J&&u<re&&ee.push((0,Be.jsx)(f,{children:I.slice(Math.max(J,u),Math.min(re,x))},"a")),x>re&&ee.push((0,Be.jsx)(f,{color:v.dimmed,children:I.slice(Math.max(re,u),x)},"g")),(0,Be.jsx)(y,{children:ee},h)})})]})}var Te=U(De(),1);var as=U(De(),1);var Hn=U(Q(),1),Fi="#ffc580",Ni="#ffd9a8",is="#ffffff";function ls({text:s,active:e=!0}){let[t,n]=(0,as.useState)(0),r=4;if(Tt(()=>{n(a=>(a+1)%(s.length+r*2))},e?80:null),!e)return(0,Hn.jsx)(f,{color:is,children:s});let o=s.split("").map((a,l)=>{let i=t-r,c=Math.abs(l-i-r/2),d;return c<=r/2?d=Fi:c<=r?d=Ni:d=is,(0,Hn.jsx)(f,{color:d,children:a},l)});return(0,Hn.jsx)(f,{children:o})}var We=U(Q(),1),Ui={starting:v.cyan,running:v.purple,passed:v.green,failed:v.red,cancelled:v.dimmed,timed_out:v.yellow};function Wn({currentStep:s,maxSteps:e,elapsed:t,status:n}){let{stdout:r}=At(),o=r?.columns??80,a=Ui[n]??v.purple,l=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,We.jsxs)(y,{flexDirection:"column",marginTop:1,children:[(0,We.jsx)(f,{color:v.muted,children:"\u2500".repeat(Math.min(o,60))}),(0,We.jsxs)(y,{children:[(0,We.jsx)(f,{children:" "}),(0,We.jsx)(f,{color:v.dimmed,children:"Steps "}),(0,We.jsx)(f,{bold:!0,children:s}),(0,We.jsxs)(f,{color:v.dimmed,children:["/",e]}),(0,We.jsx)(f,{children:" "}),(0,We.jsx)(f,{color:v.dimmed,children:"Elapsed "}),(0,We.jsx)(f,{bold:!0,children:l}),(0,We.jsx)(f,{children:" "}),(0,We.jsx)(f,{color:v.dimmed,children:"Status "}),(0,We.jsx)(f,{bold:!0,color:a,children:n})]})]})}var Mi={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function cs(s){return Mi[s]??"\u25CF"}var Ot=U(Q(),1);function zr({steps:s,flows:e,cmInitCounts:t,renderStep:n}){return(0,Ot.jsxs)(y,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,Ot.jsxs)(f,{color:v.dimmed,children:["\u2501\u2501 Bifurcated into ",e?.length??s.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),s.map((r,o)=>(0,Ot.jsxs)(y,{flexDirection:"column",marginTop:o>0?1:0,children:[(0,Ot.jsxs)(f,{color:v.purple,children:["Flow ",o+1,": ",e?.[o]??r.objective]}),t&&t[o]!=null&&(0,Ot.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",t[o]," checkpoints"]}),r.children&&r.children.length>0?r.children.map(a=>n(a,`f${o}-${a.index}`)):r.status==="pending"&&(0,Ot.jsx)(f,{color:v.dimmed,children:" \u25CB Waiting..."})]},o))]})}var V=U(Q(),1);function rt({step:s,indent:e=2}){let t=s.actionType?cs(s.actionType):null,n=s.status==="running",r=s.status==="passed",o=s.status==="failed",a=s.status==="pending"||s.status==="stopped",{stdout:l}=At(),i=l?.columns??80,c=Math.max(20,i-e-21),d=s.objective??"",m=d.length>c?d.slice(0,c-1)+"\u2026":d,g=(s.duration??0)*1e3,p=s.duration!=null?g<1e3?`${Math.round(g)}ms`:`${(g/1e3).toFixed(1)}s`:"";return(0,V.jsxs)(y,{flexDirection:"column",children:[(0,V.jsxs)(y,{marginLeft:e,children:[(0,V.jsx)(y,{width:4,children:(0,V.jsxs)(f,{color:v.muted,children:[String(s.index).padStart(2," ")," "]})}),(0,V.jsx)(y,{width:3,children:n?(0,V.jsx)(Uo,{}):r?(0,V.jsx)(f,{color:v.green,bold:!0,children:"\u2713"}):o?(0,V.jsx)(f,{color:v.red,bold:!0,children:"\u2717"}):(0,V.jsx)(f,{color:v.muted,children:"\u25CB"})}),(0,V.jsx)(y,{flexGrow:1,children:n?(0,V.jsx)(ls,{text:m,active:!0}):o?(0,V.jsx)(f,{color:v.red,children:m}):a?(0,V.jsx)(f,{color:v.dimmed,children:m}):(0,V.jsx)(f,{color:v.greenDim,children:m})}),(r||o)&&t?(0,V.jsx)(y,{width:3,marginLeft:1,children:(0,V.jsx)(f,{color:v.muted,children:t})}):(0,V.jsx)(y,{width:3,marginLeft:1}),(0,V.jsx)(y,{width:7,justifyContent:"flex-end",children:(0,V.jsx)(f,{color:v.dimmed,children:p})})]}),s.children&&s.children.length>0&&(0,V.jsx)(y,{flexDirection:"column",children:s.children.map((_,b)=>(0,V.jsx)(rt,{step:_,indent:e+2},`child-${b}`))})]})}function Kn({steps:s,bifurcated:e,flows:t,cmInitCounts:n,maxSteps:r=50,staticSteps:o=!1,onStepCommit:a}){let l=(0,Te.useRef)(new Set),i=(0,Te.useRef)(!1),c=(0,Te.useRef)(new Set),d=(0,Te.useRef)(!1),m=(0,Te.useRef)(new Set),g=(0,Te.useRef)(0);(0,Te.useEffect)(()=>{s.length===0&&g.current>0&&(l.current.clear(),i.current=!1,c.current.clear(),d.current=!1,m.current.clear()),g.current=s.length},[s.length]);let p=s.flatMap(u=>[u,...u.children??[]]),_=p.some(u=>u.status==="running"),b=p.some(u=>u.status==="failed"),E=p.length===0||p.every(u=>u.status==="pending"),A=p.filter(u=>u.status==="passed"||u.status==="failed").length,P;E?P="starting":_?P="running":b?P="failed":P="passed";let C=(0,Te.useRef)(null),[O,te]=(0,Te.useState)(0);(0,Te.useEffect)(()=>{p.length===0||E?(C.current=null,te(0)):_&&C.current==null&&(C.current=Date.now())},[_,E,p.length]),(0,Te.useEffect)(()=>{if(!_)return;let u=setInterval(()=>{C.current!=null&&te((Date.now()-C.current)/1e3)},500);return()=>clearInterval(u)},[_]);let Z=(0,Te.useRef)(new Set),[ne,_e]=(0,Te.useState)([]),F=(0,Te.useRef)(!1);(0,Te.useEffect)(()=>{if(!o||e)return;let u=[];if(!e&&!F.current&&n&&n[0]!=null&&(F.current=!0,n[0]>0&&u.push({key:"cm_init_0",type:"cm_init",count:n[0]})),e){!Z.current.has(-1)&&s.length>0&&(Z.current.add(-1),u.push({key:"bif_header",type:"bifurcation_header",flowCount:t?.length??s.length}));for(let x=0;x<s.length;x++){let h=s[x],I=-(x+10);Z.current.has(I)||(Z.current.add(I),u.push({key:`flow_header_${x}`,type:"flow_header",flowIdx:x,label:t?.[x]??h.objective,cmCount:n?.[x]}));for(let B of h.children??[])(B.status==="passed"||B.status==="failed")&&!Z.current.has(B.index)&&(Z.current.add(B.index),u.push({key:`step_f${x}_${B.index}`,type:"step",step:{...B}}))}}else for(let x of s)(x.status==="passed"||x.status==="failed")&&!Z.current.has(x.index)&&(Z.current.add(x.index),u.push({key:`step_${x.index}`,type:"step",step:{...x,children:x.children?[...x.children]:void 0}}));u.length>0&&_e(x=>[...x,...u])},[s,e,t,n,o]),(0,Te.useEffect)(()=>{if(a)if(!e&&!d.current&&n&&n[0]!=null&&(d.current=!0,n[0]>0&&a((0,V.jsx)(y,{marginLeft:2,children:(0,V.jsxs)(f,{color:v.dimmed,children:["\u25A0 Generated task with ",n[0]," checkpoints"]})}))),e&&t&&!i.current&&(i.current=!0,a((0,V.jsx)(f,{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"}))),e){let u=s.flatMap((x,h)=>{let I=x.children??[];return!c.current.has(h)&&I.length>0&&(c.current.add(h),a((0,V.jsx)(f,{color:"#b388ff",children:" Flow "+(h+1)+": "+(t?.[h]??"")})),n?.[h]!=null&&n[h]>0&&!m.current.has(h)&&(m.current.add(h),a((0,V.jsx)(y,{marginLeft:2,children:(0,V.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",n[h]," checkpoints"]})})))),n?.[h]!=null&&n[h]>0&&c.current.has(h)&&!m.current.has(h)&&(m.current.add(h),a((0,V.jsx)(y,{marginLeft:2,children:(0,V.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",n[h]," checkpoints"]})}))),I});for(let x of u){let h=`${x.index}-${x.objective}`;l.current.has(h)||(x.status==="passed"||x.status==="failed"||x.status==="stopped")&&(l.current.add(h),a((0,V.jsx)(y,{marginLeft:2,children:(0,V.jsx)(rt,{step:x})})))}}else for(let u of s){let x=`${u.index}-${u.objective}`,h=!!u.branchObjective;h&&!l.current.has(x)&&(l.current.add(x),a((0,V.jsx)(y,{marginLeft:2,children:(0,V.jsx)(rt,{step:{...u,children:void 0}})})));for(let I of u.children??[]){let B=`child-${u.index}-${I.index}-${I.objective}`;l.current.has(B)||(I.status==="passed"||I.status==="failed"||I.status==="stopped")&&(l.current.add(B),a((0,V.jsx)(y,{marginLeft:4,children:(0,V.jsx)(rt,{step:I})})))}!h&&!l.current.has(x)&&(u.status==="passed"||u.status==="failed"||u.status==="stopped")&&(l.current.add(x),a((0,V.jsx)(y,{marginLeft:2,children:(0,V.jsx)(rt,{step:{...u,children:void 0}})})))}},[s,a,e,t,n]);let N=[];if(a)if(e)for(let u of s){let h=(u.children??[]).filter(I=>{let B=`${I.index}-${I.objective}`;return!l.current.has(B)});h.length>0&&N.push({...u,children:h})}else for(let u of s){let x=`${u.index}-${u.objective}`,h=l.current.has(x),I=(u.children??[]).filter(B=>{let D=`child-${u.index}-${B.index}-${B.objective}`;return!l.current.has(D)});h?I.length>0&&N.push({...u,children:I}):N.push({...u,children:I})}else if(o){if(!e)for(let u of s)Z.current.has(u.index)||N.push(u)}if(!o){let u=a?N:s;return(0,V.jsxs)(y,{flexDirection:"column",children:[e?a?u.length>0?(0,V.jsx)(y,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:u.map((h,I)=>(0,V.jsx)(y,{flexDirection:"column",marginTop:I>0?1:0,children:h.children&&h.children.length>0?h.children.map(B=>(0,V.jsx)(rt,{step:B},`f${I}-${B.index}`)):h.status==="pending"&&(0,V.jsx)(f,{color:v.dimmed,children:" \u25CB Waiting..."})},I))}):null:(0,V.jsx)(zr,{steps:s,flows:t,cmInitCounts:n,renderStep:(h,I)=>(0,V.jsx)(rt,{step:h},I)}):(0,V.jsxs)(y,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&n&&n[0]!=null&&(0,V.jsxs)(f,{color:v.dimmed,children:["\u25AA Generated task with ",n[0]," checkpoints"]}),u.map(h=>{let I=`${h.index}-${h.objective}`;return a&&l.current.has(I)?(0,V.jsx)(y,{flexDirection:"column",children:(h.children??[]).map(B=>(0,V.jsx)(y,{marginLeft:2,children:(0,V.jsx)(rt,{step:B})},B.index))},`branch-children-${h.index}`):(0,V.jsx)(rt,{step:h},h.index)})]}),_&&(0,V.jsx)(Wn,{currentStep:A,maxSteps:r,elapsed:O,status:P})]})}return e?(0,V.jsxs)(y,{flexDirection:"column",children:[(0,V.jsx)(zr,{steps:s,flows:t,cmInitCounts:n,renderStep:(u,x)=>(0,V.jsx)(rt,{step:u},x)}),_&&(0,V.jsx)(Wn,{currentStep:A,maxSteps:r,elapsed:O,status:P})]}):(0,V.jsxs)(y,{flexDirection:"column",children:[(0,V.jsx)(Qt,{items:ne,children:u=>u.type==="cm_init"?(0,V.jsx)(y,{marginLeft:2,paddingLeft:1,children:(0,V.jsxs)(f,{color:v.dimmed,children:["\u25AA Generated task with ",u.count," checkpoints"]})},u.key):u.type==="bifurcation_header"?(0,V.jsx)(y,{marginLeft:2,paddingLeft:1,children:(0,V.jsxs)(f,{color:v.dimmed,children:["\u2501\u2501 Bifurcated into ",u.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},u.key):u.type==="flow_header"?(0,V.jsxs)(y,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,V.jsxs)(f,{color:v.purple,children:["Flow ",u.flowIdx+1,": ",u.label]}),u.cmCount!=null&&(0,V.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",u.cmCount," checkpoints"]})]},u.key):(0,V.jsx)(y,{marginLeft:2,paddingLeft:1,children:(0,V.jsx)(rt,{step:u.step})},u.key)}),N.length>0&&(0,V.jsx)(y,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:N.map(u=>(0,V.jsx)(rt,{step:u},u.index))}),_&&(0,V.jsx)(Wn,{currentStep:A,maxSteps:r,elapsed:O,status:P})]})}var Jr=U(De(),1);var Gn=U(Q(),1),us=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function qn({label:s,hasBifurcation:e=!1}){let[t,n]=(0,Jr.useState)(0),[r,o]=(0,Jr.useState)(0);Tt(()=>{n(l=>(l+1)%us.length)},80),Tt(()=>{o(l=>(l+1)%4)},400);let a=s??(e?"Planning approach":"Analyzing objective");return(0,Gn.jsxs)(y,{marginLeft:1,children:[(0,Gn.jsxs)(f,{color:v.primary,children:[us[t]," "]}),(0,Gn.jsxs)(f,{color:v.dim,children:[a,".".repeat(r+1)]})]})}function zn(s){if(!s.isRunning)return null;let e=s.bifurcationInfo;if(e&&!e.isSingleFlow){let t=s.steps.findIndex(r=>r.status==="running");return(t===-1?s.cmInitCounts.length===0:t>=s.cmInitCounts.length)?{label:t>0?`Planning flow ${t+1}`:void 0,hasBifurcation:!0}:null}return s.cmInitCounts.length>0||s.steps.some(t=>t.children?.length)?null:{hasBifurcation:!!e}}var _t=U(De(),1);var Ke=U(Q(),1);function Hi(s,e){let t=[],r=Math.max(e-4,30);t.push({type:"title",text:s.title});for(let o=0;o<s.sections.length;o++){let a=s.sections[o];o>0&&t.push({type:"divider",text:"\u2500".repeat(r)}),a.label&&t.push({type:"header",text:a.label});let l=a.entries.length>0?Math.max(...a.entries.map(i=>i.key.length)):0;for(let i of a.entries){let c="\xB7".repeat(Math.max(2,l-i.key.length+3)),d=`${i.key} ${c} ${i.value}`;t.push({type:"entry",text:d,color:i.color})}}return t.push({type:"footer",text:"esc back"}),t}function ds({data:s,width:e=60}){let t=Hi(s,e);return(0,Ke.jsx)(y,{flexDirection:"column",borderStyle:"round",borderColor:v.primary,paddingX:2,paddingY:1,children:t.map((n,r)=>{if(n.type==="title")return(0,Ke.jsx)(f,{color:v.primary,bold:!0,children:n.text},r);if(n.type==="header")return(0,Ke.jsx)(y,{marginTop:1,children:(0,Ke.jsx)(f,{color:v.dim,children:n.text})},r);if(n.type==="divider")return(0,Ke.jsx)(y,{marginTop:1,marginBottom:0,children:(0,Ke.jsx)(f,{color:v.ambient,children:n.text})},r);if(n.type==="footer")return(0,Ke.jsx)(y,{marginTop:1,children:(0,Ke.jsx)(f,{color:v.dim,children:n.text})},r);let o=n.text.match(/^(.+?) (·+) (.+)$/);return o?(0,Ke.jsxs)(f,{children:[(0,Ke.jsxs)(f,{color:v.secondary,children:[o[1]," "]}),(0,Ke.jsxs)(f,{color:v.ambient,children:[o[2]," "]}),(0,Ke.jsx)(f,{color:n.color??v.base,children:o[3]})]},r):(0,Ke.jsx)(f,{color:n.color??v.base,children:n.text},r)})})}var Ve=U(Q(),1);function Xr(s,e){let t=[];function n(r,o){for(let a of r)t.push({item:a,depth:o}),a.type==="submenu"&&a.children&&e.length>o&&e[o]===a.id&&n(a.children,o+1)}return n(s,0),t}function Yr({items:s,onRunSelected:e,initialExpandedPath:t,onDismiss:n,renderLoginWizard:r,renderProfilesView:o,renderChromeProfilePicker:a,renderProjectPicker:l,renderFolderPicker:i,renderWindowSizePicker:c}){let[d,m]=(0,_t.useState)(()=>{let A=t??[],P=Xr(s,A),C=0;if(A.length>0){let O=P.findIndex(te=>te.item.id===A[0]);O>=0&&O+1<P.length&&(C=O+1)}return{expandedPath:A,selectedIndex:C,inputValue:"",isEditing:!1,isSelecting:!1,feedback:null,activeView:null,infoData:null}}),g=Xr(s,d.expandedPath),p=g[d.selectedIndex]?.item,_=(0,_t.useRef)(null),b=(0,_t.useCallback)(A=>{m(P=>({...P,feedback:A})),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>{m(P=>({...P,feedback:null})),_.current=null},4e3)},[]);(0,_t.useEffect)(()=>()=>{_.current&&clearTimeout(_.current)},[]);let E=(0,_t.useCallback)(()=>{m(A=>({...A,activeView:null,infoData:null}))},[]);return je((A,P)=>{if(d.activeView==="infoView"){P.escape&&E();return}if(!(d.activeView==="loginWizard"||d.activeView==="profilesView"||d.activeView==="chromeProfilePicker"||d.activeView==="projectPicker"||d.activeView==="folderPicker"||d.activeView==="windowSizePicker")){if(d.isEditing){if(P.escape){m(C=>({...C,isEditing:!1,inputValue:""}));return}if(P.return){let C=d.inputValue.trim();if(p?.onValue&&C){let O=p.currentValue;p.onValue(C),b(O?`${p.label}: ${O} \u2192 ${C}`:`${p.label}: ${C}`)}m(O=>({...O,isEditing:!1,inputValue:""}));return}if(P.backspace||P.delete){m(C=>({...C,inputValue:C.inputValue.slice(0,-1)}));return}A&&!P.ctrl&&!P.meta&&m(C=>({...C,inputValue:C.inputValue+A}));return}if(d.isSelecting&&p?.options){let C=p.options;if(P.escape){m(O=>({...O,isSelecting:!1}));return}if(P.upArrow){m(O=>({...O,inputValue:String(Math.max(0,Number(O.inputValue||"0")-1))}));return}if(P.downArrow){m(O=>({...O,inputValue:String(Math.min(C.length-1,Number(O.inputValue||"0")+1))}));return}if(P.return){let O=Number(d.inputValue||"0"),te=C[O];if(te&&p.onValue){let Z=p.currentValue;p.onValue(te.value),b(Z?`${p.label}: ${Z} \u2192 ${te.label}`:`${p.label}: ${te.label}`)}m(Z=>({...Z,isSelecting:!1,inputValue:""}));return}return}if(P.upArrow){m(C=>({...C,selectedIndex:Math.max(0,C.selectedIndex-1)}));return}if(P.downArrow){m(C=>({...C,selectedIndex:Math.min(g.length-1,C.selectedIndex+1)}));return}if(P.escape){if(d.expandedPath.length===0){n?.();return}m(C=>{let O=C.expandedPath.slice(0,-1),te=Xr(s,O),Z=C.expandedPath[C.expandedPath.length-1],ne=te.findIndex(_e=>_e.item.id===Z);return{...C,expandedPath:O,selectedIndex:ne>=0?ne:0}});return}if(P.return&&p){if(p.id==="run-start"){e();return}if(p.type==="submenu"){let C=g[d.selectedIndex]?.depth??0;m(O=>({...O,expandedPath:[...O.expandedPath.slice(0,C),p.id],selectedIndex:O.selectedIndex+1}));return}if(p.onInfo){let C=p.onInfo();m(O=>({...O,activeView:"infoView",infoData:C}));return}if(p.onLoginWizard){p.onLoginWizard(),m(C=>({...C,activeView:"loginWizard"}));return}if(p.onProfilesView){p.onProfilesView(),m(C=>({...C,activeView:"profilesView"}));return}if(p.onChromeProfilePicker){p.onChromeProfilePicker(),m(C=>({...C,activeView:"chromeProfilePicker"}));return}if(p.onProjectPicker){p.onProjectPicker(),m(C=>({...C,activeView:"projectPicker"}));return}if(p.onFolderPicker){p.onFolderPicker(),m(C=>({...C,activeView:"folderPicker"}));return}if(p.onWindowSizePicker){p.onWindowSizePicker(),m(C=>({...C,activeView:"windowSizePicker"}));return}if(p.type==="action"){p.onAction?.(),p.suppressFeedback||b(`${p.label} done`);return}if(p.type==="select"&&p.options){let C=p.options.findIndex(O=>O.value===p.currentValue);m(O=>({...O,isSelecting:!0,inputValue:String(Math.max(0,C))}));return}if(p.type==="text-input"){m(C=>({...C,isEditing:!0,inputValue:p.currentValue??""}));return}}}}),(0,Ve.jsx)(y,{flexDirection:"column",paddingX:1,children:d.activeView==="infoView"&&d.infoData?(0,Ve.jsx)(ds,{data:d.infoData}):d.activeView==="loginWizard"&&r?r(E):d.activeView==="profilesView"&&o?o(E):d.activeView==="chromeProfilePicker"&&a?a(E):d.activeView==="projectPicker"&&l?l(E):d.activeView==="folderPicker"&&i?i(E):d.activeView==="windowSizePicker"&&c?c(E):(0,Ve.jsxs)(Ve.Fragment,{children:[g.map(({item:A,depth:P},C)=>{let O=C===d.selectedIndex,te=" ".repeat(P),Z=O?"\u276F ":" ",ne=A.type==="submenu"?d.expandedPath.includes(A.id)?"\u25BC ":"\u25B6 ":" ",_e=A.currentValue!=null?` [${A.currentValue}]`:"";if(O&&d.isSelecting&&A.options){let F=Number(d.inputValue||"0");return(0,Ve.jsxs)(y,{flexDirection:"column",children:[(0,Ve.jsxs)(f,{color:v.cyan,children:[te,Z,ne,A.label]}),A.options.map((N,u)=>(0,Ve.jsxs)(f,{color:u===F?v.cyan:void 0,children:[te," ",u===F?"\u276F ":" ",N.label]},N.value))]},A.id)}return O&&d.isEditing?(0,Ve.jsxs)(f,{color:v.cyan,children:[te,Z,ne,A.label,": ",d.inputValue,(0,Ve.jsx)(f,{color:v.dimmed,children:"\u2588"})]},A.id):(0,Ve.jsxs)(f,{color:O?v.cyan:void 0,dimColor:!O&&P>0,children:[te,Z,ne,A.label,(0,Ve.jsx)(f,{dimColor:!0,children:_e})]},A.id)}),d.feedback&&(0,Ve.jsx)(y,{marginTop:1,children:(0,Ve.jsxs)(f,{color:v.green,children:["\u2713 ",d.feedback]})})]})})}var _n=U(De(),1);var Le=U(Q(),1),Qr=800,Zr=3840,eo=600,to=2160;function fs(s,e){if(!e)return"Enter a value";let t=Number(e);if(!Number.isInteger(t))return"Must be a whole number";if(s==="width"){if(t<Qr)return`Min ${Qr}`;if(t>Zr)return`Max ${Zr}`}else{if(t<eo)return`Min ${eo}`;if(t>to)return`Max ${to}`}return null}function no({currentWidth:s,currentHeight:e,onSelect:t,onCancel:n}){let[r,o]=(0,_n.useState)("width"),[a,l]=(0,_n.useState)(String(s)),[i,c]=(0,_n.useState)(String(e)),[d,m]=(0,_n.useState)(null);je((p,_)=>{if(_.escape){n();return}if(_.tab||_.rightArrow||_.leftArrow){o(b=>b==="width"?"height":"width"),m(null);return}if(_.return){let b=fs("width",a);if(b){o("width"),m(`Width: ${b}`);return}let E=fs("height",i);if(E){o("height"),m(`Height: ${E}`);return}t(Number(a),Number(i));return}if(_.backspace||_.delete){r==="width"?l(b=>b.slice(0,-1)):c(b=>b.slice(0,-1)),m(null);return}p&&/^\d$/.test(p)&&(r==="width"?l(b=>b+p):c(b=>b+p),m(null))});let g=(p,_,b)=>{let E=r===b,A=E?v.primary:v.secondary;return(0,Le.jsxs)(y,{flexDirection:"column",children:[(0,Le.jsxs)(f,{color:v.dim,children:[" ",p]}),(0,Le.jsx)(y,{borderStyle:"round",borderColor:A,paddingX:1,width:10,children:(0,Le.jsxs)(f,{color:E?v.base:v.dim,children:[_||" ",E?(0,Le.jsx)(f,{color:v.dimmed,children:"\u2588"}):""]})}),(0,Le.jsxs)(f,{color:v.dim,dimColor:!0,children:[" ",b==="width"?`${Qr}\u2013${Zr}`:`${eo}\u2013${to}`]})]})};return(0,Le.jsxs)(y,{flexDirection:"column",paddingX:1,children:[(0,Le.jsx)(f,{color:v.primary,bold:!0,children:"Window Size"}),(0,Le.jsxs)(y,{marginTop:1,gap:1,children:[g("Width",a,"width"),(0,Le.jsx)(y,{alignItems:"center",marginTop:1,children:(0,Le.jsx)(f,{color:v.dim,children:"x"})}),g("Height",i,"height")]}),d&&(0,Le.jsx)(y,{marginTop:1,children:(0,Le.jsx)(f,{color:v.red,children:d})}),(0,Le.jsx)(y,{marginTop:1,children:(0,Le.jsx)(f,{color:v.dim,children:"Tab/arrows to switch Enter to save Esc to cancel"})})]})}import{randomUUID as Wi}from"crypto";import{mkdirSync as Ki,writeFileSync as ms,appendFileSync as Gi,existsSync as ps}from"fs";import{join as bn}from"path";var qi=bn(Ee,"sessions"),bt=class{sessionId;sessionDir;runs=[];_flows=[];_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=Wi(),this.sessionDir=bn(qi,this.sessionId)}start(e){if(!this._started){this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString();try{Ki(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"};ms(bn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
26
+ `)}catch{}this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`),this._earlyLogBuffer.push({level:"info",event:"SESSION_START",message:"Session started",context:{session_id:this.sessionId}},{level:"info",event:"CONFIG",message:"Session config",context:{model:e.model,environment:e.environment,profile:e.profile}})}}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 l=e.indexOf(" "),i=l>0?e.slice(0,l):e,c=l>0?e.slice(l+1):"",d=/fail|error/i.test(e)?"error":"info";this._remoteLogger?.log(d,i,c||e);return}let o=e,a=n;this._log(`${t} ${a}`),this._remoteLogger?.log(o,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 o=(n??0).toFixed(1),a=(r??"").slice(0,100);this._log(`RUN ${e} END status=${t} duration=${o}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}))};ps(this.sessionDir)&&ms(bn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
27
+ `)}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}))}}addFlow(e){let t={...e,index:this._flows.length+1};return this._flows.push(t),t}getFlows(){return[...this._flows]}getFlow(e){return this._flows.find(t=>t.index===e)}clearFlows(){this._flows=[]}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 o=0;o<r;o++)e.push(n)}return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e){if(!(!this._started||!ps(this.sessionDir)))try{let t=new Date().toISOString().slice(0,19).replace("T"," "),n=bn(this.sessionDir,"tui.log");Gi(n,`[${t}] ${e}
28
+ `)}catch{}}};import{dirname as zi,join as Ji}from"path";function xn(s,e,t){let n=s.total_runs??1,r=s.run_dir,o,a;if(n>1&&r){let l=zi(r);o=Array.from({length:n},(i,c)=>Ji(l,String(e+c))),t&&t.length===n&&(a=t)}return{allRunDirs:o,flowObjectives:a}}function wn(s,e,t,n){return{index:t,objective:e,summary:s.summary,oneLiner:s.one_liner,status:s.status,resultCode:s.result_code,reasonCode:s.reason_code,perFlowMetadata:s.per_flow_metadata,context:s.context??{memory:{},variables:{},pointer:""},run_dir:s.run_dir,run_dirs:n.allRunDirs,flow_objectives:n.flowObjectives}}import{readFileSync as Xi,writeFileSync as gs,mkdirSync as hs}from"fs";import{dirname as vs}from"path";var Jn={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:mt,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"testing",code_export:{enabled:!1,language:"python",skip_validation:!0}},ot=class{constructor(e=No){this.path=e}load(){try{let e=Xi(this.path,"utf-8"),t=JSON.parse(e);return{...Jn,...t,code_export:{...Jn.code_export,...t.code_export??{}}}}catch{return{...Jn,code_export:{...Jn.code_export}}}}set(e,t){try{let n=this.load();n[e]=t,hs(vs(this.path),{recursive:!0}),gs(this.path,JSON.stringify(n,null,2)+`
29
29
  `)}catch(n){let r=n instanceof Error?n.message:String(n);process.stderr.write(`[config] Failed to save config: ${r}
30
- `)}}save(e){try{let n={...this.load(),...e};gs(hs(this.path),{recursive:!0}),ps(this.path,JSON.stringify(n,null,2)+`
30
+ `)}}save(e){try{let n={...this.load(),...e};hs(vs(this.path),{recursive:!0}),gs(this.path,JSON.stringify(n,null,2)+`
31
31
  `)}catch(t){let n=t instanceof Error?t.message:String(t);process.stderr.write(`[config] Failed to save config: ${n}
32
- `)}}};var Ve=N(Pe(),1);async function Xn(s){let e=s.credentials.expires_at,t=s.thresholdSeconds??300;if(e-Date.now()/1e3>=t)return null;let n=s.creds.loadClient(s.profile,s.env);if(!n)return null;let o=await new en(s.env).refreshToken(s.credentials.refresh_token,n.client_id),a=Math.floor(Date.now()/1e3)+o.expires_in;return s.creds.saveCredentials(s.profile,s.env,{access_token:o.access_token,refresh_token:o.refresh_token,expires_at:a,scope:o.scope}),{accessToken:o.access_token,refreshToken:o.refresh_token,expiresAt:a,scope:o.scope}}async function Yn(s,e,t){let n=s.loadCredentials(e,t),r=s.loadClient(e,t);if(n&&r){let a=new en(t);await Promise.allSettled([a.revokeToken(n.access_token,r.client_id,"access_token"),a.revokeToken(n.refresh_token,r.client_id,"refresh_token")])}s.deleteProfileFull(e,t);let o=s.listProfiles();return o.length>0&&(s.setActiveProfile(o[0].profile),s.setDefaultEnv(o[0].env)),{profile:e,env:t,switchedTo:o.length>0?o[0]:void 0}}function vs(){let[s]=(0,Ve.useState)(()=>new Ne),[e,t]=(0,Ve.useState)(()=>{let _=s.resolveAuth();if(!_)return!1;if(_.method==="basic")return!0;let{credentials:x}=s.getActiveCredentials();return x?x.expires_at>Date.now()/1e3:!1}),n=(0,Ve.useRef)(null),r=(0,Ve.useRef)(null),o=(0,Ve.useCallback)(()=>{let _=s.resolveAuth();return _?{method:_.method,profile:_.profile,env:_.env}:null},[s]),a=(0,Ve.useCallback)(async()=>{let{credentials:_,profile:x,env:C}=s.getActiveCredentials();if(!_||!x||!C)return null;let T=_.expires_at,P=Date.now()/1e3;if(T-P<300){if(r.current)return r.current;let R=(async()=>{try{let O=await Xn({creds:s,profile:x,env:C,credentials:_});return O?(t(!0),O.accessToken):null}catch{return t(!1),null}finally{r.current=null}})();return r.current=R,R}return t(!0),_.access_token},[s]),l=(0,Ve.useCallback)(()=>{let _=s.resolveAuth();return!_||_.method!=="basic"?null:{username:_.username,access_key:_.access_key}},[s]),i=(0,Ve.useCallback)((_,x)=>{n.current?.revoke();let C=ce(_),T=l(),P=new mt(C.controllerBaseUrl,a,T,x);return n.current=P,P},[l,a]),c=(0,Ve.useCallback)(()=>n.current,[]),d=(0,Ve.useCallback)(()=>{let _=l();if(_)return _;let x=n.current?.cached;return x?{username:x.username,access_key:x.access_key}:null},[l]),m=(0,Ve.useCallback)(async()=>{let _=n.current;return _?_.resolve():null},[]),g=(0,Ve.useCallback)(async(_="default")=>{let x=s.getDefaultEnv();await new hn(_,x,s).login(),s.setActiveProfile(_),t(!0)},[s]),p=(0,Ve.useCallback)(async()=>{let _=s.getActiveProfile();if(!_)return null;let x=s.getDefaultEnv(),C=await Yn(s,_,x);return t(!1),{profile:C.profile,env:C.env}},[s]);return{creds:s,tokenValid:e,setTokenValid:t,getToken:a,getBasicAuth:l,getAuthInfo:o,login:g,logout:p,initResolver:i,getResolver:c,getResolvedBasicAuth:d,resolveBasicAuth:m}}var wt=N(Pe(),1);import{spawn as Es,spawnSync as Yi}from"child_process";import{existsSync as io}from"fs";import{createConnection as Qi}from"net";import{homedir as Sn,platform as Cn}from"os";import{join as En}from"path";var ws=()=>!!process.env.KANE_DEV_MODE,jt=[],_s=!1,bs=null,no=null,ro=null,yn=null;function Qn(s){yn=s}function ys(){return yn}function Xe(s,e){jt=jt.filter(t=>t.name!==s),jt.push({name:s,fn:e})}function He(s,e){let t=jt.find(r=>r.name===s);if(!t)return;jt=jt.filter(r=>r.name!==s);let n=!0;try{t.fn()}catch(r){n=!1,process.stderr.write(`[exit-manager] cleanup(${s}) failed: ${r instanceof Error?r.message:String(r)}
33
- `)}e&&n&&ws()&&process.stderr.write(`[exit-manager] cleanup(${s}): ${e}
34
- `)}function X(s,e,t=!1){if(_s){process.exit(bs??s);return}if(_s=!0,bs=s,t&&yn)try{yn.log("error","CRASH",e),yn.shutdownSync()}catch{}let n=[...jt].reverse(),r=[];for(let o of n)try{o.fn(),r.push(o.name)}catch(a){process.stderr.write(`[exit-manager] cleanup(${o.name}) failed: ${a instanceof Error?a.message:String(a)}
35
- `)}if(jt=[],ws()&&(process.stderr.write(`[exit-manager] shutdown(${s}): ${e}
32
+ `)}}};var Fe=U(De(),1);async function Xn(s){let e=s.credentials.expires_at,t=s.thresholdSeconds??300;if(e-Date.now()/1e3>=t)return null;let n=s.creds.loadClient(s.profile,s.env);if(!n)return null;let o=await new nn(s.env).refreshToken(s.credentials.refresh_token,n.client_id),a=Math.floor(Date.now()/1e3)+o.expires_in;return s.creds.saveCredentials(s.profile,s.env,{access_token:o.access_token,refresh_token:o.refresh_token,expires_at:a,scope:o.scope}),{accessToken:o.access_token,refreshToken:o.refresh_token,expiresAt:a,scope:o.scope}}async function Yn(s,e,t){let n=s.loadCredentials(e,t),r=s.loadClient(e,t);if(n&&r){let a=new nn(t);await Promise.allSettled([a.revokeToken(n.access_token,r.client_id,"access_token"),a.revokeToken(n.refresh_token,r.client_id,"refresh_token")])}s.deleteProfileFull(e,t);let o=s.listProfiles();return o.length>0&&(s.setActiveProfile(o[0].profile),s.setDefaultEnv(o[0].env)),{profile:e,env:t,switchedTo:o.length>0?o[0]:void 0}}function _s(){let[s]=(0,Fe.useState)(()=>new He),[e,t]=(0,Fe.useState)(()=>{let _=s.resolveAuth();if(!_)return!1;if(_.method==="basic")return!0;let{credentials:b}=s.getActiveCredentials();return b?b.expires_at>Date.now()/1e3:!1}),n=(0,Fe.useRef)(null),r=(0,Fe.useRef)(null),o=(0,Fe.useCallback)(()=>{let _=s.resolveAuth();return _?{method:_.method,profile:_.profile,env:_.env}:null},[s]),a=(0,Fe.useCallback)(async()=>{let{credentials:_,profile:b,env:E}=s.getActiveCredentials();if(!_||!b||!E)return null;let A=_.expires_at,P=Date.now()/1e3;if(A-P<300){if(r.current)return r.current;let C=(async()=>{try{let O=await Xn({creds:s,profile:b,env:E,credentials:_});return O?(t(!0),O.accessToken):null}catch{return t(!1),null}finally{r.current=null}})();return r.current=C,C}return t(!0),_.access_token},[s]),l=(0,Fe.useCallback)(()=>{let _=s.resolveAuth();return!_||_.method!=="basic"?null:{username:_.username,access_key:_.access_key}},[s]),i=(0,Fe.useCallback)((_,b)=>{n.current?.revoke();let E=ae(_),A=l(),P=new pt(E.controllerBaseUrl,a,A,b);return n.current=P,P},[l,a]),c=(0,Fe.useCallback)(()=>n.current,[]),d=(0,Fe.useCallback)(()=>{let _=l();if(_)return _;let b=n.current?.cached;return b?{username:b.username,access_key:b.access_key}:null},[l]),m=(0,Fe.useCallback)(async()=>{let _=n.current;return _?_.resolve():null},[]),g=(0,Fe.useCallback)(async(_="default")=>{let b=s.getDefaultEnv();await new hn(_,b,s).login(),s.setActiveProfile(_),t(!0)},[s]),p=(0,Fe.useCallback)(async()=>{let _=s.getActiveProfile();if(!_)return null;let b=s.getDefaultEnv(),E=await Yn(s,_,b);return t(!1),{profile:E.profile,env:E.env}},[s]);return{creds:s,tokenValid:e,setTokenValid:t,getToken:a,getBasicAuth:l,getAuthInfo:o,login:g,logout:p,initResolver:i,getResolver:c,getResolvedBasicAuth:d,resolveBasicAuth:m}}var xt=U(De(),1);import{spawn as Cs,spawnSync as Yi}from"child_process";import{existsSync as ao}from"fs";import{createConnection as Qi}from"net";import{homedir as Sn,platform as Cn}from"os";import{join as En}from"path";var ys=()=>!!process.env.KANE_DEV_MODE,Dt=[],bs=!1,xs=null,ro=null,oo=null,yn=null;function Qn(s){yn=s}function Ss(){return yn}function Ge(s,e){Dt=Dt.filter(t=>t.name!==s),Dt.push({name:s,fn:e})}function qe(s,e){let t=Dt.find(r=>r.name===s);if(!t)return;Dt=Dt.filter(r=>r.name!==s);let n=!0;try{t.fn()}catch(r){n=!1,process.stderr.write(`[exit-manager] cleanup(${s}) failed: ${r instanceof Error?r.message:String(r)}
33
+ `)}e&&n&&ys()&&process.stderr.write(`[exit-manager] cleanup(${s}): ${e}
34
+ `)}function X(s,e,t=!1){if(bs){process.exit(xs??s);return}if(bs=!0,xs=s,t&&yn)try{yn.log("error","CRASH",e),yn.shutdownSync()}catch{}let n=[...Dt].reverse(),r=[];for(let o of n)try{o.fn(),r.push(o.name)}catch(a){process.stderr.write(`[exit-manager] cleanup(${o.name}) failed: ${a instanceof Error?a.message:String(a)}
35
+ `)}if(Dt=[],ys()&&(process.stderr.write(`[exit-manager] shutdown(${s}): ${e}
36
36
  `),r.length>0&&process.stderr.write(`[exit-manager] cleaned up: ${r.join(", ")}
37
- `)),t&&ro){try{ro()}catch{}process.stderr.write(`
37
+ `)),t&&oo){try{oo()}catch{}process.stderr.write(`
38
38
  Kane CLI crashed unexpectedly: ${e}
39
39
  `+(r.length>0?`Resources cleaned up (${r.join(", ")}).
40
- `:"")),process.exit(s);return}if(no&&!t){no();return}process.exit(s)}function oo(s){no=s}function so(s){ro=s}var xs=!1;function Ss(){xs||(xs=!0,process.on("SIGINT",()=>{X(130,"Received SIGINT",!0)}),process.on("SIGTERM",()=>{X(143,"Received SIGTERM",!0)}),process.on("uncaughtException",s=>{X(1,`Uncaught exception: ${s.message}`,!0)}),process.on("unhandledRejection",s=>{X(1,`Unhandled rejection: ${String(s)}`,!0)}))}var Zi=new Set(["1","true","yes"]),tn=class extends Error{constructor(e){super(e),this.name="ChromeNotFoundError"}};function er(s){return s instanceof tn?s.message:`Chrome failed: ${s instanceof Error?s.message:String(s)}`}var Zn={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",En(Sn(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",En(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",En(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",En(Sn(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",En(Sn(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function ea(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let s=Cn(),e=Zn[s]??Zn.linux;for(let t of e)if(io(t))return t;return s==="win32"?"chrome.exe":"google-chrome"}function ta(){if(process.env.KANE_CLI_CHROME_PATH)return io(process.env.KANE_CLI_CHROME_PATH);let s=Cn();if((Zn[s]??Zn.linux).some(r=>io(r)))return!0;let t=s==="win32"?"chrome.exe":"google-chrome",n=s==="win32"?"where":"which";try{return Yi(n,[t],{stdio:"ignore"}).status===0}catch{return!1}}function na(){let s=Cn();return s==="darwin"?["Google Chrome is required but was not found at any standard path.","","Install via Homebrew (recommended):"," brew install --cask google-chrome","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
40
+ `:"")),process.exit(s);return}if(ro&&!t){ro();return}process.exit(s)}function so(s){ro=s}function io(s){oo=s}var ws=!1;function Es(){ws||(ws=!0,process.on("SIGINT",()=>{X(130,"Received SIGINT",!0)}),process.on("SIGTERM",()=>{X(143,"Received SIGTERM",!0)}),process.on("uncaughtException",s=>{X(1,`Uncaught exception: ${s.message}`,!0)}),process.on("unhandledRejection",s=>{X(1,`Unhandled rejection: ${String(s)}`,!0)}))}var Zi=new Set(["1","true","yes"]),rn=class extends Error{constructor(e){super(e),this.name="ChromeNotFoundError"}};function er(s){return s instanceof rn?s.message:`Chrome failed: ${s instanceof Error?s.message:String(s)}`}var Zn={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",En(Sn(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",En(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",En(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",En(Sn(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",En(Sn(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function ea(){if(process.env.KANE_CLI_CHROME_PATH)return process.env.KANE_CLI_CHROME_PATH;let s=Cn(),e=Zn[s]??Zn.linux;for(let t of e)if(ao(t))return t;return s==="win32"?"chrome.exe":"google-chrome"}function ta(){if(process.env.KANE_CLI_CHROME_PATH)return ao(process.env.KANE_CLI_CHROME_PATH);let s=Cn();if((Zn[s]??Zn.linux).some(r=>ao(r)))return!0;let t=s==="win32"?"chrome.exe":"google-chrome",n=s==="win32"?"where":"which";try{return Yi(n,[t],{stdio:"ignore"}).status===0}catch{return!1}}function na(){let s=Cn();return s==="darwin"?["Google Chrome is required but was not found at any standard path.","","Install via Homebrew (recommended):"," brew install --cask google-chrome","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
41
41
  `):s==="linux"?["Google Chrome is required but was not found at /usr/bin/google-chrome.","(amd64 / x86_64 only \u2014 Google does not ship Chrome for Linux ARM.)","","Debian / Ubuntu (any version):"," wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb"," sudo apt install -y ./google-chrome-stable_current_amd64.deb","","Fedora / RHEL / AlmaLinux / Rocky:"," sudo dnf install -y https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm","","Then re-run your command. Set KANE_CLI_CHROME_PATH=/path/to/chrome","to point at a non-standard install."].join(`
42
42
  `):s==="win32"?["Google Chrome is required but was not found in Program Files or AppData.","","Install via winget (Windows 10 1809+):"," winget install --id Google.Chrome -e --silent","","Or download:"," https://www.google.com/chrome/","","Then re-run your command. Set KANE_CLI_CHROME_PATH=C:\\path\\to\\chrome.exe","to point at a non-standard install."].join(`
43
43
  `):["Google Chrome is required.","Install from https://www.google.com/chrome/","(Note: no official Chrome builds for BSD or Alpine/musl Linux.)"].join(`
44
- `)}function ra(s){let e=Cn(),t=[`--remote-debugging-port=${s.port}`,`--user-data-dir=${s.userDataDir}`,`--window-size=${s.width},${s.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"),s.headless&&t.push("--headless=new"),t}function oa(s){return new Promise(e=>{let t=Qi({port:s,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 sa(){for(let s=Dr;s<=jr;s++)if(!await oa(s))return s;throw new Error(`All CDP ports ${Dr}-${jr} are in use. Close other Chrome instances.`)}async function ia(s,e=15e3){let t=Date.now(),n=`http://127.0.0.1:${s}/json/version`;for(;Date.now()-t<e;){try{if((await fetch(n)).ok)return`http://127.0.0.1:${s}`}catch{}await new Promise(r=>setTimeout(r,200))}throw new Error(`Chrome CDP not ready after ${e}ms on port ${s}`)}async function tr(s){let e=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(e!=null&&Zi.has(e.toLowerCase()))&&!ta())throw ys()?.log("error","CHROME_NOT_FOUND","Startup gate: Chrome unavailable at standard system paths",{platform:process.platform,kane_cli_chrome_path:process.env.KANE_CLI_CHROME_PATH??null,skip_browser_download:process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD??null}),new tn(na());let n=Cn(),r=await sa(),o=ea(),a=ra({port:r,...s});s.startUrl&&a.push(s.startUrl);let l=Es(o,a,{stdio:"ignore",detached:!0,windowsHide:!0});l.unref();let i=await new Promise((c,d)=>{l.on("error",m=>{d(new Error(`Failed to launch Chrome: ${m.message}. Is Chrome installed at ${o}?`))}),l.on("close",m=>{m!==null&&m!==0&&d(new Error(`Chrome exited during startup with code ${m}`))}),ia(r).then(c,d)});return{process:l,port:r,cdpEndpoint:i,kill(){try{if(l.pid)if(n==="win32")Es("taskkill",["/pid",String(l.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-l.pid,"SIGKILL")}catch{l.kill("SIGKILL")}else l.kill("SIGKILL")}catch{}}}}import{mkdtempSync as aa,rmSync as la}from"fs";import{join as ca}from"path";import{tmpdir as ua}from"os";function Cs(){let[s]=(0,wt.useState)(()=>new tt),e=(0,wt.useRef)(null),t=(0,wt.useRef)(null),n=(0,wt.useRef)(null),r=(0,wt.useCallback)(async a=>{if(e.current)return e.current;if(n.current)return n.current;let l=(async()=>{let i=s.load(),c;if(i.chrome_profile_path)c=i.chrome_profile_path.replace("~",process.env.HOME??"~");else{t.current&&(He("tempDir","Previous temp dir removed before retry"),t.current=null);let m=aa(ca(ua(),"kane-clean-"));t.current=m,c=m,Xe("tempDir",()=>{try{la(m,{recursive:!0,force:!0})}catch{}})}let d=await tr({userDataDir:c,width:i.window_size.width,height:i.window_size.height,startUrl:a??i.default_url??void 0});return e.current=d,Xe("chrome",()=>{d.kill()}),d})();n.current=l;try{return await l}finally{n.current=null}},[s]),o=(0,wt.useCallback)(()=>{He("chrome","Chrome killed"),He("tempDir","Temp dir removed"),e.current=null,t.current=null},[]);return{ensureChrome:r,killChrome:o}}import{spawn as va}from"child_process";import{spawn as fa,execSync as ma}from"child_process";import{existsSync as nr}from"fs";import{resolve as Fe,dirname as pa}from"path";import{fileURLToPath as ga}from"url";import{createInterface as da}from"readline";async function*Rs(s){let e=da({input:s,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{}}}function As(s){return s==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS"]}}var yt=pa(ga(import.meta.url));function ha(){for(let s of["python3","python"])try{return ma(`${s} --version`,{stdio:"ignore"}),s}catch{}return null}function ao(){let e=process.platform==="win32"?"v16-runner.exe":"v16-runner",t={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},n=`${process.platform}-${process.arch}`,r=t[n];if(r)for(let l of r){let i=[Fe(yt,"..","node_modules",l,"bin",e),Fe(yt,"..","..","node_modules",l,"bin",e),Fe(yt,"..","..","..","node_modules",l,"bin",e)];for(let c of i)if(nr(c))return{cmd:c,args:[]}}let o=[Fe(yt,"bin",e),Fe(yt,"..","bin",e),Fe(yt,"..","..","..","..","v16-runner","dist",e),Fe(yt,"..","..","..","v16-runner","dist",e),Fe(process.cwd(),"v16-runner","dist",e),Fe(process.cwd(),"..","v16-runner","dist",e)];for(let l of o)if(nr(l))return{cmd:l,args:[]};let a=[Fe(yt,"..","..","..","..","v16-runner"),Fe(yt,"..","..","..","v16-runner"),Fe(process.cwd(),"v16-runner"),Fe(process.cwd(),"..","v16-runner")];for(let l of a)if(nr(Fe(l,"main.py"))){for(let c of[Fe(l,".venv","bin","python"),Fe(l,"..","browser-agent",".venv","bin","python")])if(nr(c))return{cmd:c,args:["main.py"],cwd:l};let i=ha();if(i)return{cmd:i,args:["main.py"],cwd:l}}return null}function rr(s,e){let t=ao();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=ce(e?.environment).v16ServerHost,s.username&&s.access_key&&(n.LT_USERNAME=s.username,n.LT_ACCESS_KEY=s.access_key);let r=As(e?.mode??"testing");Object.assign(n,r.set);for(let g of r.unset)delete n[g];let o=fa(t.cmd,t.args,{stdio:["pipe","pipe","pipe"],env:n,cwd:t.cwd});o.stdin.on("error",()=>{}),o.stdin.write(JSON.stringify(s)+`
45
- `);let a=1e5,l="";o.stderr.on("data",g=>{l+=g.toString(),l.length>a&&(l=l.slice(-a))}),o.on("error",g=>{e?.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:g.message})});let i=null,c=null,d=new Promise(g=>{o.on("close",(p,_)=>{i=p,c=_?String(_):null,e?.log?.("info","RUNNER_EXIT","Runner exited",{code:p,signal:c??"none"}),g({code:p,signal:c})})}),m=Rs(o.stdout);return{child:o,events:m,sendUserResponse(g){let p=JSON.stringify({type:"user_response",answer:g});try{o.stdin.write(p+`
44
+ `)}function ra(s){let e=Cn(),t=[`--remote-debugging-port=${s.port}`,`--user-data-dir=${s.userDataDir}`,`--window-size=${s.width},${s.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"),s.headless&&t.push("--headless=new"),t}function oa(s){return new Promise(e=>{let t=Qi({port:s,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 sa(){for(let s=jr;s<=Lr;s++)if(!await oa(s))return s;throw new Error(`All CDP ports ${jr}-${Lr} are in use. Close other Chrome instances.`)}async function ia(s,e=15e3){let t=Date.now(),n=`http://127.0.0.1:${s}/json/version`;for(;Date.now()-t<e;){try{if((await fetch(n)).ok)return`http://127.0.0.1:${s}`}catch{}await new Promise(r=>setTimeout(r,200))}throw new Error(`Chrome CDP not ready after ${e}ms on port ${s}`)}async function tr(s){let e=process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD;if(!(e!=null&&Zi.has(e.toLowerCase()))&&!ta())throw Ss()?.log("error","CHROME_NOT_FOUND","Startup gate: Chrome unavailable at standard system paths",{platform:process.platform,kane_cli_chrome_path:process.env.KANE_CLI_CHROME_PATH??null,skip_browser_download:process.env.KANE_CLI_SKIP_BROWSER_DOWNLOAD??null}),new rn(na());let n=Cn(),r=await sa(),o=ea(),a=ra({port:r,...s});s.startUrl&&a.push(s.startUrl);let l=Cs(o,a,{stdio:"ignore",detached:!0,windowsHide:!0});l.unref();let i=await new Promise((c,d)=>{l.on("error",m=>{d(new Error(`Failed to launch Chrome: ${m.message}. Is Chrome installed at ${o}?`))}),l.on("close",m=>{m!==null&&m!==0&&d(new Error(`Chrome exited during startup with code ${m}`))}),ia(r).then(c,d)});return{process:l,port:r,cdpEndpoint:i,kill(){try{if(l.pid)if(n==="win32")Cs("taskkill",["/pid",String(l.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-l.pid,"SIGKILL")}catch{l.kill("SIGKILL")}else l.kill("SIGKILL")}catch{}}}}import{mkdtempSync as aa,rmSync as la}from"fs";import{join as ca}from"path";import{tmpdir as ua}from"os";function Rs(){let[s]=(0,xt.useState)(()=>new ot),e=(0,xt.useRef)(null),t=(0,xt.useRef)(null),n=(0,xt.useRef)(null),r=(0,xt.useCallback)(async a=>{if(e.current)return e.current;if(n.current)return n.current;let l=(async()=>{let i=s.load(),c;if(i.chrome_profile_path)c=i.chrome_profile_path.replace("~",process.env.HOME??"~");else{t.current&&(qe("tempDir","Previous temp dir removed before retry"),t.current=null);let m=aa(ca(ua(),"kane-clean-"));t.current=m,c=m,Ge("tempDir",()=>{try{la(m,{recursive:!0,force:!0})}catch{}})}let d=await tr({userDataDir:c,width:i.window_size.width,height:i.window_size.height,startUrl:a??i.default_url??void 0});return e.current=d,Ge("chrome",()=>{d.kill()}),d})();n.current=l;try{return await l}finally{n.current=null}},[s]),o=(0,xt.useCallback)(()=>{qe("chrome","Chrome killed"),qe("tempDir","Temp dir removed"),e.current=null,t.current=null},[]);return{ensureChrome:r,killChrome:o}}import{spawn as va}from"child_process";import{spawn as fa,execSync as ma}from"child_process";import{existsSync as nr}from"fs";import{resolve as Ne,dirname as pa}from"path";import{fileURLToPath as ga}from"url";import{createInterface as da}from"readline";async function*As(s){let e=da({input:s,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{}}}function Ts(s){return s==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS"]}}var wt=pa(ga(import.meta.url));function ha(){for(let s of["python3","python"])try{return ma(`${s} --version`,{stdio:"ignore"}),s}catch{}return null}function lo(){let e=process.platform==="win32"?"v16-runner.exe":"v16-runner",t={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},n=`${process.platform}-${process.arch}`,r=t[n];if(r)for(let l of r){let i=[Ne(wt,"..","node_modules",l,"bin",e),Ne(wt,"..","..","node_modules",l,"bin",e),Ne(wt,"..","..","..","node_modules",l,"bin",e)];for(let c of i)if(nr(c))return{cmd:c,args:[]}}let o=[Ne(wt,"bin",e),Ne(wt,"..","bin",e),Ne(wt,"..","..","..","..","v16-runner","dist",e),Ne(wt,"..","..","..","v16-runner","dist",e),Ne(process.cwd(),"v16-runner","dist",e),Ne(process.cwd(),"..","v16-runner","dist",e)];for(let l of o)if(nr(l))return{cmd:l,args:[]};let a=[Ne(wt,"..","..","..","..","v16-runner"),Ne(wt,"..","..","..","v16-runner"),Ne(process.cwd(),"v16-runner"),Ne(process.cwd(),"..","v16-runner")];for(let l of a)if(nr(Ne(l,"main.py"))){for(let c of[Ne(l,".venv","bin","python"),Ne(l,"..","browser-agent",".venv","bin","python")])if(nr(c))return{cmd:c,args:["main.py"],cwd:l};let i=ha();if(i)return{cmd:i,args:["main.py"],cwd:l}}return null}function rr(s,e){let t=lo();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=ae(e?.environment).v16ServerHost,s.username&&s.access_key&&(n.LT_USERNAME=s.username,n.LT_ACCESS_KEY=s.access_key);let r=Ts(e?.mode??"testing");Object.assign(n,r.set);for(let g of r.unset)delete n[g];let o=fa(t.cmd,t.args,{stdio:["pipe","pipe","pipe"],env:n,cwd:t.cwd});o.stdin.on("error",()=>{}),o.stdin.write(JSON.stringify(s)+`
45
+ `);let a=1e5,l="";o.stderr.on("data",g=>{l+=g.toString(),l.length>a&&(l=l.slice(-a))}),o.on("error",g=>{e?.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:g.message})});let i=null,c=null,d=new Promise(g=>{o.on("close",(p,_)=>{i=p,c=_?String(_):null,e?.log?.("info","RUNNER_EXIT","Runner exited",{code:p,signal:c??"none"}),g({code:p,signal:c})})}),m=As(o.stdout);return{child:o,events:m,sendUserResponse(g){let p=JSON.stringify({type:"user_response",answer:g});try{o.stdin.write(p+`
46
46
  `)}catch{}},sendCancel(g){let p=JSON.stringify({type:"cancel",reason:g});try{o.stdin.write(p+`
47
- `)}catch{}},cancel(){o.kill("SIGTERM")},get stderr(){return l},get exitCode(){return i},get exitSignal(){return c},exited:d}}async function Ts(s,e,t=100){let n=`${s.replace(/\/+$/,"")}/json/version`,r=await fetch(n);if(!r.ok)throw new Error(`CDP /json/version returned ${r.status}`);let o=await r.json();if(!o.webSocketDebuggerUrl)throw new Error("CDP /json/version missing webSocketDebuggerUrl");let a=new Vo(o.webSocketDebuggerUrl);await new Promise((P,R)=>{a.once("open",P),a.once("error",R)});let l=1,i=new Map;a.on("message",P=>{let R;try{R=JSON.parse(P.toString())}catch{return}if(R.id==null)return;let O=i.get(R.id);O&&(i.delete(R.id),R.error?O.reject(new Error(R.error.message)):O.resolve(R.result))});function c(P,R){let O=l++;return new Promise((te,Z)=>{i.set(O,{resolve:ne=>te(ne),reject:Z}),a.send(JSON.stringify({id:O,method:P,params:R}))})}let m=(await c("Target.getTargets")).targetInfos.find(P=>P.type==="page");if(!m)throw a.close(),new Error("CDP: no page target found");let p=(await c("Browser.getWindowForTarget",{targetId:m.targetId})).windowId,_="",x=!1,C=null;async function T(){if(!x){try{let R=(await c("Browser.getWindowBounds",{windowId:p})).bounds,O=`${R.left}:${R.top}:${R.width}:${R.height}`;O!==_&&(_=O,e({left:R.left,top:R.top,width:R.width,height:R.height}))}catch{x=!0,a.close();return}x||(C=setTimeout(T,t))}}return T(),{stop(){if(!x){x=!0,C&&clearTimeout(C);try{a.close()}catch{}}}}}var _a=new Set(["1","true","yes"]);function ks(s){if(s?.headless)return null;let e=process.env.KANE_CLI_DISABLE_MARKER;if(e!=null&&_a.has(e.toLowerCase()))return null;let t=ao();if(!t)return null;let n=[...t.args,"overlay"];s?.text&&n.push(s.text);let r;try{r=va(t.cmd,n,{cwd:t.cwd,stdio:["pipe","ignore","ignore"],detached:!1,windowsHide:!0})}catch{return null}function o(i){if(!(!r.stdin||r.stdin.destroyed))try{r.stdin.write(JSON.stringify(i)+`
48
- `)}catch{}}let a=null;s?.cdpEndpoint&&Ts(s.cdpEndpoint,i=>{o({type:"bounds",...i})}).then(i=>{a=i.stop}).catch(()=>{});let l=!1;return{setRunActive(i){l||o({type:"run_active",active:i})},kill(){if(!l){l=!0,a?.();try{r.stdin?.end()}catch{}try{r.kill("SIGTERM")}catch{}}}}}var Ae=N(Pe(),1);function lo(s){let e=s.indexOf(": ");return e>0&&e<15?s.slice(e+2):s}function co(s){return s.map(e=>{let t=e.children?co(e.children):e.children;return e.status==="running"?{...e,status:"stopped",phase:void 0,children:t}:t!==e.children?{...e,children:t}:e})}function or(s,e){let[t,n]=(0,Ae.useState)(!1),[r,o]=(0,Ae.useState)([]),[a,l]=(0,Ae.useState)(null),[i,c]=(0,Ae.useState)(null),[d,m]=(0,Ae.useState)(null),[g,p]=(0,Ae.useState)(null),[_,x]=(0,Ae.useState)([]),C=(0,Ae.useRef)(null),T=(0,Ae.useRef)(null),P=(0,Ae.useRef)(0),R=(0,Ae.useRef)(!1),O=(0,Ae.useCallback)((ne,ve)=>{C.current&&(C.current.cancel(),C.current=null),o([]),l(null),c(null),m(null),p(null),x([]),n(!0),T.current=null,P.current=0;let V;try{V=rr(ne,ve)}catch(F){m(F instanceof Error?F.message:String(F)),n(!1);return}C.current=V,Xe("runner",()=>V.cancel()),(async()=>{R.current=!1;for await(let u of V.events){if(R.current)break;switch(u.type){case"run_start":if(T.current&&!T.current.isSingleFlow){let w=P.current;P.current++,o(h=>h.map((b,$)=>$===w?{...b,status:"running"}:b.status==="running"&&!b.children?.some(z=>z.status==="running")?{...b,status:b.children?.some(z=>z.status==="failed")?"failed":"passed"}:b))}break;case"bifurcation":{let w=u.flows??[],h=u.count??w.length,b={flows:w,isSingleFlow:u.is_single_flow??h<=1};p(b),T.current=b,P.current=0,o(w.map(($,z)=>({index:z+1,objective:$??`Flow ${z+1}`,status:"pending"})));break}case"step_start":{e?.("STEP_START",`Step ${u.index} started`,{index:u.index,objective:u.objective,child_id:u.child_id});let w=u.index,h=u.objective??`Step ${w}`,b=u.child_id,$=T.current&&!T.current.isSingleFlow;if(b)o(z=>{let q=z.findIndex(Ce=>Ce.status==="running"||Ce.children?.some(Le=>Le.status==="running"));if(q===-1)return z;let re=[...z],ee={...re[q]},je=[...ee.children??[]].map(Ce=>Ce.status==="running"?{...Ce,status:"stopped",phase:void 0}:Ce);return je.push({index:w,objective:h,status:"running"}),ee.children=je,re[q]=ee,re});else if($){let z=Math.max(0,P.current-1);o(q=>{let re=[...q];if(z>=re.length)return q;let ee={...re[z]},je=[...ee.children??[]].map(Ce=>Ce.status==="running"?{...Ce,status:"stopped",phase:void 0}:Ce);return je.push({index:w,objective:h,status:"running"}),ee.children=je,ee.status="running",re[z]=ee,re})}else o(z=>{let q=co(z);return q.some(ee=>ee.index===w)?q.map(ee=>ee.index===w?{...ee,status:"running",objective:h}:ee):[...q,{index:w,objective:h,status:"running"}]});break}case"step_event":{e?.("STEP_EVENT",`Step ${u.index} ${u.event}`,{index:u.index,phase:u.event,action_type:u.action_type,detail:u.detail,child_id:u.child_id});let w=u.child_id,h=T.current&&!T.current.isSingleFlow;if(u.event==="cm_init"&&u.checkpoint_count!=null){x(b=>[...b,u.checkpoint_count]);break}if(w)o(b=>b.map($=>{if(!$.children)return $;let z=$.children.map(q=>{if(q.index!==u.index)return q;let re={phase:u.event};return u.event==="reasoning"&&u.detail&&u.detail!=="reasoning"&&(re.objective=u.detail),u.action_type&&(re.actionType=u.action_type),{...q,...re}});return{...$,children:z}}));else if(h){let b=Math.max(0,P.current-1);o($=>{let z=[...$];if(b>=z.length)return $;let q={...z[b]},re=[...q.children??[]];if(!re.some(Te=>Te.index===u.index))re.push({index:u.index,objective:`Step ${u.index}`,status:"running",phase:u.event,actionType:u.action_type});else for(let Te=0;Te<re.length;Te++){if(re[Te].index!==u.index)continue;let je={phase:u.event};u.event==="reasoning"&&u.detail&&u.detail!=="reasoning"&&(je.objective=u.detail),u.action_type&&(je.actionType=u.action_type),re[Te]={...re[Te],...je}}return q.children=re,z[b]=q,z})}else o(b=>b.some(z=>z.index===u.index)?b.map(z=>{if(z.index!==u.index)return z;let q={phase:u.event};return u.event==="reasoning"&&u.detail&&u.detail!=="reasoning"&&(q.objective=u.detail),u.action_type&&(q.actionType=u.action_type),{...z,...q}}):[...co(b),{index:u.index,objective:`Step ${u.index}`,status:"running",phase:u.event,actionType:u.action_type}]);break}case"step_end":{e?.("STEP_END",`Step ${u.index} ${u.status}`,{index:u.index,status:u.status,duration:u.duration,summary:u.summary,child_id:u.child_id});let w=u.child_id,h=T.current&&!T.current.isSingleFlow;if(w)o(b=>b.map($=>{if(!$.children)return $;let z=$.children.map(q=>q.index===u.index?{...q,status:u.status,duration:u.duration,phase:void 0,objective:q.objective.startsWith("Step ")?lo(u.summary||q.objective):q.objective}:q);return{...$,children:z}}));else if(h){let b=Math.max(0,P.current-1);o($=>{let z=[...$];if(b>=z.length)return $;let q={...z[b]},re=(q.children??[]).map(ee=>ee.index===u.index?{...ee,status:u.status,duration:u.duration,phase:void 0,objective:ee.objective.startsWith("Step ")?lo(u.summary||ee.objective):ee.objective}:ee);return q.children=re,z[b]=q,z})}else o(b=>b.map($=>$.index===u.index?{...$,status:u.status,duration:u.duration,phase:void 0,objective:$.objective.startsWith("Step ")?lo(u.summary||$.objective):$.objective}:$));{let $=T.current&&!T.current.isSingleFlow?Math.max(0,P.current-1):0;s?.(u.index,$,u.child_id)}break}case"child_agent_start":{let w=u.objective??"";o(h=>h.map(b=>b.status==="running"?{...b,objective:`${w} (branch)`,phase:`child: ${w.slice(0,50)}`,branchObjective:w}:b));break}case"child_agent_end":o(w=>w.map(h=>h.phase?.startsWith("child:")?{...h,phase:`child ${u.success?"done":"failed"}`}:h));break;case"ask_user":l(u.question??"");break;case"run_end":o(w=>w.map(h=>h.status==="running"?{...h,status:u.status,phase:void 0}:h)),c(u),n(!1),He("runner","Run completed"),C.current=null;break;case"error":m(u.message??"Runner error"),o(w=>w.map(h=>h.status==="running"?{...h,status:"failed",phase:void 0}:h)),n(!1),He("runner","Runner error"),C.current=null;break}}let F=C.current;if(F){let{code:u,signal:w}=await F.exited,h=F.stderr,b=[];u!==null&&u!==0&&b.push(`Runner exited with code ${u}`),w&&b.push(`Runner killed by signal ${w}`),h&&b.push(h),b.length>0&&m(b.join(`
49
- `))}n(!1),He("runner","Event stream ended"),C.current=null})().catch(F=>{let u=C.current,w=[`Runner event loop error: ${F}`];u&&(u.exitCode!==null&&u.exitCode!==0&&w.push(`Exit code: ${u.exitCode}`),u.exitSignal&&w.push(`Signal: ${u.exitSignal}`),u.stderr&&w.push(u.stderr)),m(w.join(`
50
- `)),n(!1),He("runner","Event loop error"),C.current=null})},[s,e]),te=(0,Ae.useCallback)(ne=>{C.current?.sendUserResponse(ne),l(null)},[]),Z=(0,Ae.useCallback)(()=>{let ne=C.current;ne&&(ne.sendCancel("user"),n(!1),l(null),setTimeout(()=>{C.current===ne&&(He("runner","User cancelled run"),C.current=null)},5e3))},[]);return(0,Ae.useEffect)(()=>()=>{R.current=!0,He("runner","Component unmounted"),C.current=null},[]),{isRunning:t,steps:r,askingUser:a,lastRunEnd:i,runError:d,bifurcationInfo:g,cmInitCounts:_,startRun:O,sendAnswer:te,cancelRun:Z}}function Rn(s){let e=s.flatMap(o=>[o,...o.children??[]]),t=e.filter(o=>o.status==="passed").length,n=e.filter(o=>o.status==="failed").length,r=e.filter(o=>o.status==="passed"||o.status==="failed").length;return{passed:t,failed:n,total:r}}async function nn(s,e,t,n){let r=s.loadBasicAuth(e,t),o=s.loadCredentials(e,t);if(!r&&!o)return n("info","STARTUP_GATE_NO_CREDS","Profile has no credentials",{profile:e,env:t}),{status:"needs_login",profile:e,env:t};let a=ce(t),l=async()=>s.loadCredentials(e,t)?.access_token??null,i=new mt(a.controllerBaseUrl,l,r,n);n("info","STARTUP_GATE_VALIDATE","Validating credentials with controller",{profile:e,env:t,method:r?"basic":"oauth"});let c=await i.resolve(!0);if(c)return n("info","STARTUP_GATE_VALID","Credentials validated",{profile:e,env:t,username:c.username,org_id:c.org_id}),{status:"authenticated",result:{profile:e,env:t,credentials:o,basicAuth:r,tmsCreds:c,resolver:i}};if(!r&&o){let d=o.refresh_token,g=s.loadClient(e,t)?.client_id;if(d&&g){n("info","STARTUP_GATE_REFRESH","Attempting token refresh",{profile:e,env:t});try{let _=await new en(t).refreshToken(d,g);if(_.access_token){s.saveCredentials(e,t,{...o,..._,expires_at:Date.now()/1e3+(_.expires_in??3600)});let C=await i.resolve(!0);if(C)return n("info","STARTUP_GATE_REFRESH_OK","Token refreshed and validated",{profile:e,env:t,username:C.username}),{status:"authenticated",result:{profile:e,env:t,credentials:{...o,..._},basicAuth:null,tmsCreds:C,resolver:i}}}n("warn","STARTUP_GATE_REFRESH_INVALID","Refreshed token still invalid",{profile:e,env:t})}catch(p){n("warn","STARTUP_GATE_REFRESH_FAILED","Token refresh failed",{profile:e,env:t,error:p instanceof Error?p.message:String(p)})}}else n("info","STARTUP_GATE_NO_REFRESH","No refresh_token or client_id \u2014 login required",{profile:e,env:t})}return n("info","STARTUP_GATE_INVALID","Credentials invalid \u2014 login required",{profile:e,env:t}),{status:"needs_login",profile:e,env:t}}async function sr(s,e){let t=s.listProfiles();if(e("info","STARTUP_GATE_START","Auth startup gate",{profile_count:t.length}),t.length===0)return e("info","STARTUP_GATE_NONE","No profiles found \u2014 login required"),{status:"needs_login"};if(t.length>1){let o=s.getActiveProfile(),a=s.getDefaultEnv();if(o&&t.some(i=>i.profile===o&&i.env===a)){e("info","STARTUP_GATE_TRY_ACTIVE","Multiple profiles \u2014 trying active first",{activeProfile:o,activeEnv:a});let i=await nn(s,o,a,e);if(i.status==="authenticated")return i;e("info","STARTUP_GATE_ACTIVE_FAILED","Active profile invalid \u2014 showing picker",{activeProfile:o,activeEnv:a})}return e("info","STARTUP_GATE_MULTI","Multiple profiles \u2014 picker required",{profiles:t.map(l=>`${l.profile}/${l.env}`)}),{status:"needs_pick",profiles:t}}let{profile:n,env:r}=t[0];return s.setActiveProfile(n),s.setDefaultEnv(r),nn(s,n,r,e)}var ir=[{name:"run",description:"Execute a test run",args:'"objective"'},{name:"login",description:"OAuth login",args:"[--profile name]"},{name:"logout",description:"Logout & revoke tokens",args:"[--profile name]"},{name:"whoami",description:"Show profile info",args:"[--profile name]"},{name:"balance",description:"Show credit balance"},{name:"profiles",description:"Manage profiles",args:"list|switch|delete"},{name:"config",description:"Manage configuration",args:"show|set-window|set-mode|chrome-profile|project|folder"},{name:"new",description:"Start a fresh session (uploads current first)"},{name:"summary",description:"View detailed run summaries",args:"[index]"},{name:"cancel",description:"Abort current run"},{name:"help",description:"Show command reference"},{name:"clear",description:"Clear chat history"},{name:"exit",description:"Quit kane-cli"}];function Is(s){let e=s.trim();if(!e.startsWith("/"))return null;let n=e.slice(1).match(/(?:[^\s"]+|"[^"]*")+/g)??[];if(n.length===0)return null;let r=n[0],o={},a=1;for(;a<n.length;){let l=n[a];if(l.startsWith("--")){let i=l.slice(2),c=n[a+1];c&&!c.startsWith("--")?(o[i]=c.replace(/^"|"$/g,""),a+=2):(o[i]=void 0,a++)}else{let i=l.replace(/^"|"$/g,"");r==="run"?o.objective=i:r==="config"?o.action?o.value=i:o.action=i:r==="profiles"?o.action=i:r==="summary"&&(o.index=i),a++}}return{command:r,args:o,raw:e}}var Au=[{name:"Testing",commands:ir.filter(s=>["run","cancel"].includes(s.name))},{name:"Auth",commands:ir.filter(s=>["login","logout","whoami","balance","profiles"].includes(s.name))},{name:"Settings",commands:ir.filter(s=>["config"].includes(s.name))},{name:"Session",commands:ir.filter(s=>["new","summary","help","clear","exit"].includes(s.name))}];var Ps=[{name:"auth",description:"Login, logout, profiles"},{name:"config",description:"View/change settings"},{name:"help",description:"Command reference"},{name:"new",description:"Start a fresh session"},{name:"summary",description:"View run summaries",args:"[index]"},{name:"cancel",description:"Abort current run"},{name:"exit",description:"Quit kane-cli"}];var We=N(Q(),1),ba=64;function xa(s){return s.split(`
51
- `).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function rn({status:s,summary:e,duration:t,steps:n,stepsPassed:r,stepsFailed:o,reason:a,creditsConsumed:l}){let i=s==="passed",c=i?v.green:v.red,d=i?"\u2713":"\u2717",m=s.toUpperCase(),g=r??(i?n:Math.max(0,n-1)),p=o??(i?0:1),_=p>0?`${n} steps (${g} passed, ${p} failed)`:`${n} steps`,x=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,C=xa(e);return(0,We.jsx)(S,{flexDirection:"column",marginTop:1,children:(0,We.jsxs)(S,{borderStyle:"round",borderColor:c,flexDirection:"column",paddingX:2,paddingY:1,width:ba+6,children:[(0,We.jsxs)(S,{flexDirection:"column",children:[(0,We.jsxs)(f,{bold:!0,color:c,children:[d," ",m]}),(0,We.jsxs)(f,{color:v.dimmed,wrap:"wrap",children:[_," \xB7 ",x,typeof l=="number"&&l>0?` \xB7 ${parseFloat(l.toFixed(4))} credits`:""]})]}),C.length>0&&(0,We.jsx)(S,{flexDirection:"column",marginTop:1,marginLeft:1,children:C.map((T,P)=>(0,We.jsxs)(S,{marginBottom:P<C.length-1?1:0,children:[(0,We.jsx)(f,{color:v.primary,children:"\u25CF "}),(0,We.jsx)(S,{flexShrink:1,children:(0,We.jsx)(f,{wrap:"wrap",children:T})})]},P))}),a&&!i&&(0,We.jsx)(S,{marginTop:1,children:(0,We.jsxs)(f,{color:v.red,wrap:"wrap",children:["Reason: ",a]})})]})})}var Lt=N(Q(),1);function uo({flows:s,filterIndex:e}){let t=e!==void 0?s.filter(n=>n.index===e):s;return t.length===0?null:(0,Lt.jsx)(S,{flexDirection:"column",children:t.map(n=>(0,Lt.jsxs)(S,{flexDirection:"column",marginTop:1,children:[(0,Lt.jsxs)(S,{marginLeft:1,children:[(0,Lt.jsx)(f,{color:"#b388ff",bold:!0,children:"Flow "+n.index+": "}),(0,Lt.jsx)(f,{color:"#b388ff",children:n.objective})]}),(0,Lt.jsx)(rn,{status:n.status==="error"?"failed":n.status,summary:n.summary,duration:n.duration,steps:n.steps,stepsPassed:n.stepsPassed,stepsFailed:n.stepsFailed,reason:n.reason,creditsConsumed:n.creditsConsumed})]},n.index))})}var wa=null;function Os(s){wa=s}import{readFileSync as ya,existsSync as Sa}from"fs";function on(s){if(!Sa(s))return null;try{return ya(s,"utf-8").trim()||null}catch{return null}}import{join as ct}from"path";var ar=N(Q(),1);function Ds({status:s,steps:e,duration:t,creditsConsumed:n,reason:r}){let o=s==="passed",a=o?v.green:v.red,l=o?"\u2713":"\u2717",i=o?"Passed":"Failed",c=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,d=typeof n=="number"&&n>0?` \xB7 ${n.toFixed(4)} credits`:"",m=!o&&r?` \xB7 ${r}`:"";return(0,ar.jsxs)(S,{children:[(0,ar.jsxs)(f,{bold:!0,color:a,children:[l," ",i]}),(0,ar.jsxs)(f,{color:v.dimmed,children:[" ","\xB7 ",e," steps \xB7 ",c,d,m]})]})}var Ls=N(Q(),1);function js(){return(0,Ls.jsx)(f,{color:v.dimmed,children:"Continue below \xB7 /new fresh session \xB7 /summary view details \xB7 Ctrl+C exit"})}function $s(s,e,t){return`${s}/projects/${e}/test-cases/${t}`}function Ht(s,e,t,n){return`${$s(s,e,t)}/dashboard/share/${n}?type=summary&agentView=true&fqdn=summary-page`}function An(s,e,t){return`${$s(s,e,t)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{readFileSync as Bs,readdirSync as Vs,existsSync as Wt}from"fs";import{join as St}from"path";function lr(s,e,t,n,r,o){try{let a=St(s,"runs",String(e),"run-test");if(!Wt(a)){r("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:t,reason:"runsDir_not_found",path:a});return}let l=a;if(o){let x=St(a,`child-${o}`);if(!Wt(x)){r("warn","SCREENSHOT_SKIP","Child dir not found",{step_index:t,child_id:o,reason:"child_dir_not_found",path:x});return}let C=Vs(x).filter(T=>Wt(St(x,T,"screenshots")));if(C.length===0){r("warn","SCREENSHOT_SKIP","No screenshots dir under child",{step_index:t,child_id:o,reason:"no_child_screenshots_dir"});return}l=St(x,C[0])}else if(!Wt(St(a,"screenshots"))){let x=Vs(a).filter(C=>Wt(St(a,C,"screenshots")));if(x.length===0){r("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:t,reason:"no_screenshots_dir"});return}l=St(a,x[0])}let i=St(l,"screenshots",`step_${String(t).padStart(3,"0")}.png`);if(!Wt(i)){r("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:t,child_id:o,reason:"screenshot_not_found",path:i});return}let c=St(a,"actions.ndjson");if(!Wt(c)){r("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:t,reason:"ndjson_not_found"});return}let d=Bs(c,"utf-8").trim().split(`
52
- `),m=d[d.length-1];if(!m){r("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:t,reason:"ndjson_empty"});return}let p=JSON.parse(m).action_id;if(!p){r("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:t,reason:"no_action_id"});return}let _=Bs(i);n.enqueue(p,_),r("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:t,child_id:o,action_id:p,size:_.length})}catch(a){r("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:t,error:a instanceof Error?a.message:String(a)})}}import Ea from"sharp";var sn=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 l=await Ea(e.buffer).webp({quality:80}).toBuffer();t=new Uint8Array(l)}catch(l){t=new Uint8Array(e.buffer),n="image/png",this.log?.("warn","SCREENSHOT_CONVERT_FAILED","WebP conversion failed, using PNG",{operation_id:e.operationId,error:l instanceof Error?l.message:String(l)})}let r=n==="image/webp"?"webp":"png",o=`test_screenshots/untagged_screenshot/${e.operationId}.${r}`,a=`${this.sas.base_url}/${this.sas.container}/${o}?${this.sas.sas_token}`;for(let l=0;l<=this.maxRetries;l++)try{let i=await fetch(a,{method:"PUT",headers:{"Content-Type":n,"x-ms-blob-type":"BlockBlob"},body:t});if(i.ok)return;if(l<this.maxRetries){await this.backoff(l);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed after retries",{operation_id:e.operationId,status:i.status,attempts:this.maxRetries+1})}catch{if(l<this.maxRetries){await this.backoff(l);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 Ca,readFileSync as Ns,existsSync as Us}from"fs";import{join as Ra}from"path";function Fs(s,e){if(!Us(s))return{};let t={},n;try{n=Ca(s).filter(r=>r.endsWith(".json")).sort()}catch{return{}}for(let r of n)try{let o=Ns(Ra(s,r),"utf-8"),a=JSON.parse(o);if(a&&typeof a=="object"){for(let[l,i]of Object.entries(a))if(i&&typeof i=="object"&&"value"in i){let c=i;t[l]={value:c.value,secret:c.secret??!1,syntax:c.syntax??`{{${l}}}`}}}}catch{e?e("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:r}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${r}
53
- `)}return t}function Ms(s){if(!Us(s))throw new Error(`Variables file not found: ${s}`);let e=Ns(s,"utf-8"),t=JSON.parse(e),n={};if(t&&typeof t=="object"){for(let[r,o]of Object.entries(t))if(o&&typeof o=="object"&&"value"in o){let a=o;n[r]={value:a.value,secret:a.secret??!1,syntax:a.syntax??`{{${r}}}`}}}return n}function Hs(s){let e;try{e=JSON.parse(s)}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 o=r;t[n]={value:o.value,secret:o.secret??!1,syntax:o.syntax??`{{${n}}}`}}}return t}function Ws(s,e,t){let n=Fs(s,t),r=Fs(e,t);return{...n,...r}}function Ks(s,e){let t={},n={},r=e;for(let[o,a]of Object.entries(s))if(a.secret){let l=`secrets.user.${o}`;t[l]={value:a.value,secret:!0,syntax:`{{secrets.user.${o}}}`,type:"secret"},n[o]=l,r=r.replaceAll(`{{${o}}}`,`{{secrets.user.${o}}}`)}else{let l=`global.${o}`;t[l]={value:a.value,secret:!1,syntax:`{{global.${o}}}`,type:"global"},n[o]=l,r=r.replaceAll(`{{${o}}}`,`{{global.${o}}}`)}return{variables:t,objective:r,keyMap:n}}var cr=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=Uo(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 ur=class extends Mo{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 o=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${t}`,{method:"GET",headers:this.headers()});return o.ok?{id:(await o.json()).data?.id??0}:{id:0}}};function dr(s){let e=Ws(s.globalDir,s.localDir,s.onLoadError),t=s.file?Ms(s.file):{},n=s.inline?Hs(s.inline):{},r={...e,...t,...n},o=Object.keys(r).length>0,{variables:a,objective:l}=o?Ks(r,s.objective):{variables:{},objective:s.objective},i=Object.entries(r).filter(([,d])=>d.secret),c=Object.entries(r).filter(([,d])=>!d.secret);return{raw:r,auteur:a,auteurObjective:l,secretEntries:i,nonSecretEntries:c}}async function fr(s){if(s.localMode)return{};let e=ce(s.env);if(s.variables.secretEntries.length>0){let n=new cr(e.secretsBaseUrl);for(let[r,o]of s.variables.secretEntries)n.pushSecret({secretKey:r,secretValue:o.value,username:s.auth.username,accessKey:s.auth.access_key,orgId:s.orgId}).then(()=>s.log("info","SECRET_PUSH_OK","Secret pushed",{key:r})).catch(a=>s.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:r,error:String(a)}))}let t={};if(s.variables.nonSecretEntries.length>0){let n=new ur(e.tmsBaseUrl,s.auth.username,s.auth.access_key);for(let[r,o]of s.variables.nonSecretEntries)try{let a=await n.upsertVariable({name:r,value:o.value});t[r]=a.id,s.log("info","VAR_PUSH_OK","Variable pushed",{name:r,id:a.id})}catch(a){s.log("error","VAR_PUSH_FAILED","Variable push failed",{name:r,error:String(a)})}}return t}function mr(s){let e={objective:s.objective,model:s.model,width:s.windowSize.width,height:s.windowSize.height,session_id:s.sessionId,run_index:s.runIndex,stream:!0,max_steps:s.maxSteps??30,headless:s.headless??!1};return s.url&&(e.url=s.url),s.chrome.wsEndpoint?e.ws_endpoint=s.chrome.wsEndpoint:s.chrome.cdpEndpoint&&(e.cdp_endpoint=s.chrome.cdpEndpoint),s.auth.basicAuth?(e.username=s.auth.basicAuth.username,e.access_key=s.auth.basicAuth.access_key):s.auth.token&&(e.auth={type:"bearer",token:s.auth.token}),s.disableAskUser&&(e.disable_ask_user=!0),s.enableTaskSkills&&(e.enable_task_skills=!0),s.variables&&Object.keys(s.variables).length>0&&(e.variables=s.variables),s.globalContext&&(e.global_context=s.globalContext),s.localContext&&(e.local_context=s.localContext),s.sessionContext&&(e.session_context=s.sessionContext),e}function Tn(s){let e=ce(s.env),{session:t,auth:n}=s,r=n.basicAuth?{username:n.basicAuth.username,accessKey:n.basicAuth.access_key}:n.token,o=n.resolvedCreds?.username??n.basicAuth?.username??"",a=n.resolvedCreds?.access_key??n.basicAuth?.access_key??"",l=n.resolvedCreds?.org_id??0,i=n.resolvedCreds?.user_id??0,c=[];for(let _ of Object.keys(t.auteurVariables))_.startsWith("secrets.user.")&&c.push({key_name:_.replace("secrets.user.",""),scope:"user"});let m=t.getContext().prior_runs.map(_=>_.status),g=t.auteurVariables,p=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:s.projectId,folderId:s.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:s.totalSteps,totalDuration:s.totalDuration,runStatuses:m,orgId:l,userId:i,tmsUsername:o,tmsAccessKey:a,screenshotBaseUrl:t.screenshotBaseUrl,shareApiBaseUrl:e.shareApiBaseUrl,variables:p?g:void 0,variableIds:s.variableIds,secrets:c,codeExport:s.codeExport,onProgress:s.onProgress,log:s.log}}var Gs=["python"];function Aa(s){if(s!==void 0){if(!Gs.includes(s))throw new Error(`--code-language must be one of: ${Gs.join(", ")} (got "${s}")`);return s}}function kn(s,e){let t=Aa(s.codeLanguage);return{enabled:s.codeExport??e.enabled,language:t??e.language,skipValidation:s.skipCodeValidation??e.skip_validation}}async function pr(s){try{let t=await new at(s.tmsBaseUrl,s.auth.username,s.auth.access_key).createAtmTest({objective:s.objective.slice(0,100),creation_mode:"KANECLI",playground_disabled:s.hasCustomProfile,testURL:s.url,project_id:s.projectId,folder_id:s.folderId,authoring_version:4});return s.log("info","ATM_CREATE_OK","Test created",{test_id:t}),t}catch(e){return s.log("error","ATM_CREATE_FAILED","Test creation failed",{error:e instanceof Error?e.message:String(e)}),null}}async function gr(s){await new at(s.tmsBaseUrl,s.username,s.accessKey).submitFeedback({instruction_id:"",test_id:s.testId,feedback_type:s.feedbackType,mode:s.mode??"human",...s.details?{details:s.details}:{}}),s.log("info","FEEDBACK_SUBMITTED","Feedback submitted",{type:s.feedbackType})}var D=N(Q(),1);function qs({localMode:s=!1,codeExport:e,codeLanguage:t,skipCodeValidation:n,updatePromise:r}={}){Yt();let o=(0,L.useRef)(new xt),[a,l]=(0,L.useState)(0),i=o.current,[c]=(0,L.useState)(()=>new tt),d=(0,L.useRef)(0),m=(0,L.useCallback)(()=>`msg-${++d.current}`,[]),[g,p]=(0,L.useState)(!1),[_,x]=(0,L.useState)(null),[C,T]=(0,L.useState)(!1),[P,R]=(0,L.useState)(0),[O,te]=(0,L.useState)(!1),[Z,ne]=(0,L.useState)(null),[ve,V]=(0,L.useState)(null),F=(0,L.useRef)(null),[u,w]=(0,L.useState)(null),[h,b]=(0,L.useState)(Bn()),[$,z]=(0,L.useState)(null),[q,re]=(0,L.useState)([]),[ee,Te]=(0,L.useState)(!1),[je,Ce]=(0,L.useState)(!1),Le=(0,L.useRef)(null),rt=(0,L.useRef)(0),pt=(0,L.useRef)(""),cn=(0,L.useRef)(null),U=(0,L.useRef)(null),oe=(0,L.useRef)({}),se=(0,L.useRef)(null),me=(0,L.useRef)(0),[Ge,ot]=(0,L.useState)([]),ae=(0,L.useCallback)(E=>{let A=`s-${++me.current}`;ot(y=>[...y,{id:A,content:E}])},[]),[ge,le]=(0,L.useState)("booting"),[Ie,qe]=(0,L.useState)([]),[gt,Ct]=(0,L.useState)(!1),[ut,wr]=(0,L.useState)(!1),[zt,yr]=(0,L.useState)("chat"),[Bt,un]=(0,L.useState)(null),[we,dn]=(0,L.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),xi=Fn(),k=vs(),On=Cs(),wi=(0,L.useCallback)((E,A,y)=>{let I=Le.current;if(!I)return;let j=rt.current+A;lr(i.sessionDir,j,E,I,(K,G,J,Y)=>i.log(K,G,J,Y),y)},[i]),yi=(0,L.useCallback)((E,A,y)=>{i.logStep(E,A,y)},[i]),M=or(wi,yi),[H,Ze]=(0,L.useState)(()=>c.load()),[,Si]=(0,L.useState)(0),ze=(0,L.useCallback)(()=>Si(E=>E+1),[]),[W,ye]=(0,L.useState)(null),Jt=k.creds.getActiveProfile(),fe=k.creds.getDefaultEnv(),Je=(0,L.useCallback)((E,A)=>{let y=E?k.creds.loadProfileConfig(E,A):null;c.save({project_id:y?.project_id??null,project_name:y?.project_name??null,folder_id:y?.folder_id??null,folder_name:y?.folder_name??null}),Ze(c.load())},[k.creds,c]);(0,L.useEffect)(()=>{C||(i.start({model:H.model,environment:fe,profile:Jt}),T(!0))},[i,C,H.model,fe,Jt]);let Io=(0,L.useCallback)(async E=>{let A=ce(E),y=k.getBasicAuth(),I=y?{username:y.username,accessKey:y.access_key}:await k.getToken().then(K=>K??"");if(!I)return;let j=new Ho(A.controllerBaseUrl,I);try{let K=await j.getScreenshotSas();i.setScreenshotSas(K),Le.current=new sn(K,3,(G,J,Y,de)=>i.log(G,J,Y,de)),i.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched")}catch(K){i.log("warn","SCREENSHOT_SAS_FAILED","Screenshot SAS fetch failed",{error:K instanceof Error?K.message:String(K)})}},[k,i]),Rt=(0,L.useCallback)(async E=>{let A=E??k.creds.getDefaultEnv();z(null),Le.current=null;let I=await k.initResolver(A,(j,K,G,J)=>i.log(j,K,G,J)).resolve(!0).catch(()=>null);return z(I),I&&(i.log("info","AUTH_RESET_OK","Auth reset resolved",{username:I.username,org_id:I.org_id,env:A}),await Io(A)),I},[k,i,Io]),Po=(0,L.useRef)(!1);(0,L.useEffect)(()=>{!g||Po.current||!C||(Po.current=!0,Rt().then(E=>{if(E){if(i.log("info","BOOT_RESOLVE_OK","Boot auth resolved",{username:E.username,org_id:E.org_id}),!i.hasRemoteLogger){let A=Wo({sessionId:i.sessionId,identity:{org_id:String(E.org_id??""),user_id:String(E.user_id??""),machine_id:Ko()},environment:fe,getToken:async()=>k.getToken()});i.setRemoteLogger(A),A.start(),Xe("remote-logger",()=>A.shutdownSync()),Qn(A)}}else i.log("warn","BOOT_RESOLVE_FAILED","Boot auth failed \u2014 non-controller APIs may fail")}).catch(E=>{i.log("error","BOOT_RESOLVE_ERROR","Boot auth error",{error:E instanceof Error?E.message:String(E)})}))},[g,C,Rt,i]);let Vt=(0,L.useCallback)(async()=>{if($)return i.log("info","TMS_CREDS_CACHED","Using cached TMS credentials",{username:$.username,org_id:$.org_id}),$;let E=await k.resolveBasicAuth();return E?(i.log("info","TMS_CREDS_OK","TMS credentials resolved",{username:E.username,org_id:E.org_id,user_id:E.user_id}),z(E)):i.log("warn","TMS_CREDS_FAILED","No TMS credentials resolved"),E},[k,$,i]),Oo=(0,L.useCallback)(async()=>{let E=await Vt();if(!E)return i.log("warn","PROJECT_FAILED","No TMS credentials for project resolution"),null;let A=ce(fe),y=new at(A.tmsBaseUrl,E.username,E.access_key),I=k.creds.getActiveProfile(),j=k.creds.getDefaultEnv(),K=I?k.creds.loadProfileConfig(I,j):null,G=K?.project_id??H.project_id;if(G)i.log("info","PROJECT_CACHED","Using cached project",{project_id:G});else{i.log("info","PROJECT_FETCH","No project_id in config, fetching from TMS");try{i.log("info","PROJECT_LIST","Listing projects from TMS",{url:`${A.tmsBaseUrl}/v1/projects`});let Y=await y.listProjects((be,fn,At,dt)=>i.log(be,fn,At,dt));i.log("info","PROJECT_LIST_OK","Projects listed",{count:Y.length});let de=Y.find(be=>be.name==="KaneAI Generated");if(de)G=de.project_id,i.log("info","PROJECT_SELECTED","Using KaneAI Generated project",{project_id:G});else if(Y.length>0){let be=Y[0];G=be.project_id,i.log("info","PROJECT_SELECTED","Using first project",{name:be.name,project_id:G})}G&&c.set("project_id",G)}catch(Y){return i.log("error","PROJECT_LIST_FAILED","Project listing failed",{error:String(Y)}),null}}if(!G)return i.log("warn","PROJECT_NONE","No projects found"),null;let J=K?.folder_id??H.folder_id;if(J)i.log("info","FOLDER_CACHED","Using cached folder",{folder_id:J});else try{i.log("info","FOLDER_FETCH","Fetching default folder",{project_id:G}),J=await y.getDefaultFolder(G),i.log("info","FOLDER_OK","Default folder resolved",{folder_id:J}),J&&c.set("folder_id",J)}catch(Y){return i.log("error","FOLDER_FAILED","Default folder fetch failed",{error:String(Y)}),null}return{projectId:G,folderId:J??""}},[H.project_id,H.folder_id,Vt,fe,c,i]),ue=(0,L.useCallback)(E=>{let A=m(),y={...E,id:A};ae((0,D.jsx)(ns,{entry:y}))},[m,ae]),Do=(0,L.useCallback)(async(E,A)=>{let y=i.nextRunIndex();rt.current=y,pt.current=E,i.logRunStart(y,E,A??""),i.setFirstRun(E,A??"");let I=k.getResolvedBasicAuth(),j=I,K=null;if(!j&&(K=await k.getToken(),!K)){ue({type:"error",text:"Not authenticated. Run /login first."});return}let G={basicAuth:I??null,token:K,resolver:k.getResolver(),resolvedCreds:null};if(cn.current=G,y===0&&!s){i.log("info","ATM_CREATE_START","Creating test via ATM endpoint",{run_index:0});let ke=await Oo(),st=ce(fe),it=j?{username:j.username,access_key:j.access_key}:await Vt();if(it){let ht=await pr({tmsBaseUrl:st.tmsBaseUrl,auth:{username:it.username,access_key:it.access_key},objective:E,url:A??H.default_url??"",projectId:ke?.projectId??H.project_id??"",folderId:ke?.folderId??H.folder_id??"",hasCustomProfile:!!H.chrome_profile_path,log:($n,Ir,Pr,Or)=>i.log($n,Ir,Pr,Or)});ht&&(i.setTestId(ht),ke?.projectId&&i.setProjectId(ke.projectId))}}let J=null;if(we.useCft)ue({type:"info",text:"CfT mode: Playwright will manage browser"});else if(we.wsEndpoint)ue({type:"info",text:`WS endpoint: ${we.wsEndpoint.slice(0,60)}...`});else if(we.cdpEndpoint)ue({type:"info",text:`CDP endpoint: ${we.cdpEndpoint}`});else{ue({type:"info",text:"Starting Chrome..."});try{J=await On.ensureChrome(A)}catch(st){ue({type:"error",text:er(st)});return}i.logChromeLaunch(J.port,J.cdpEndpoint),ue({type:"info",text:`Chrome ready (port ${J.port})`});let ke=ks({headless:we.headless,cdpEndpoint:J.cdpEndpoint});ke&&(se.current=ke,Xe("marker-overlay",()=>ke.kill()))}let Y=dr({objective:E,globalDir:ct(Se,"variables"),localDir:ct(process.cwd(),".testmuai","variables")});i.setAuteurVariables(Y.auteur),U.current=Y;let de=j&&!s?await fr({variables:Y,auth:j,orgId:String((await Vt())?.org_id??""),env:fe,localMode:s,log:(ke,st,it,ht)=>i.log(ke,st,it,ht)}):{};oe.current=de;let be=on(ct(Se,"global-memory.md")),fn=on(ct(process.cwd(),".testmuai","context.md")),At=J?{cdpEndpoint:J.cdpEndpoint,instance:J,tempDir:null}:we.wsEndpoint?{wsEndpoint:we.wsEndpoint,instance:null,tempDir:null}:we.cdpEndpoint?{cdpEndpoint:we.cdpEndpoint,instance:null,tempDir:null}:{instance:null,tempDir:null},dt=mr({objective:Y.auteurObjective,url:A,model:H.model,chrome:At,auth:G,sessionId:i.sessionId,runIndex:y,windowSize:H.window_size,maxSteps:we.maxSteps,headless:we.headless,variables:Object.keys(Y.auteur).length>0?Y.auteur:void 0,globalContext:be??void 0,localContext:fn??void 0,sessionContext:i.getContext()});A&&x(A),ne(null),M.startRun(dt,{environment:fe,mode:H.mode,log:(ke,st,it,ht)=>i.log(ke,st,it,ht)}),R(ke=>ke+1)},[k,On,c,H,i,fe,M,ue,we,Oo,Vt]),Sr=(0,L.useRef)(null);(0,L.useEffect)(()=>{if(M.bifurcationInfo&&M.bifurcationInfo!==Sr.current){Sr.current=M.bifurcationInfo;let{flows:E,isSingleFlow:A}=M.bifurcationInfo;if(A&&E.length===1&&E[0])i.log("info","OBJECTIVE_REWRITTEN","Objective rewritten",{objective:E[0]}),ue({type:"info",text:`Objective: ${E[0]}`});else if(!A&&E.length>1){let y=[`Bifurcated into ${E.length} flows:`];E.forEach((I,j)=>y.push(` ${j+1}. ${I}`)),i.log("info","BIFURCATION","Objective bifurcated into flows",{flow_count:E.length}),ue({type:"info",text:y.join(`
54
- `)})}}},[M.bifurcationInfo,i,ue]);let Er=L.default.useRef(null),Cr=L.default.useRef(0),Rr=L.default.useRef(0);(0,L.useEffect)(()=>{if(M.lastRunEnd&&M.lastRunEnd!==Er.current){Er.current=M.lastRunEnd;let{status:E,duration:A,summary:y,reason:I,context:j}=M.lastRunEnd,{passed:K,failed:G,total:J}=Rn(M.steps);Cr.current+=J,Rr.current+=A??0,ne({status:E,duration:A??0,summary:y??"",stepsPassed:K,stepsFailed:G,stepsTotal:J,reason:I,finalState:M.lastRunEnd?.final_state,creditsConsumed:M.lastRunEnd?.credits_consumed}),i.logRunEnd(rt.current,E,A,y);let Y=M.bifurcationInfo,de=Y&&!Y.isSingleFlow?Y.flows:null,be=xn(M.lastRunEnd,rt.current,de),fn=wn(M.lastRunEnd,pt.current,rt.current,be);i.addRunResult(fn,M.lastRunEnd?.total_runs);let At=M.lastRunEnd?.per_flow_metadata;if(Y&&!Y.isSingleFlow&&At&&At.length>1)for(let dt=0;dt<At.length;dt++){let ke=At[dt],st=M.steps[dt],it=st?.children??[],ht=it.filter(mn=>mn.status==="passed").length,$n=it.filter(mn=>mn.status==="failed").length,Ir=it.reduce((mn,Ai)=>mn+(Ai.duration??0),0),Pr=st?.status==="failed"?"failed":"passed",Or=Y.flows[dt]??st?.objective??pt.current;i.addFlow({runIndex:rt.current,flowId:Y.flows[dt],objective:Or,status:Pr,summary:ke.summary??"",duration:Ir,steps:ht+$n,stepsPassed:ht,stepsFailed:$n,reason:ke.error_message??void 0,creditsConsumed:ke.credits_consumed??void 0})}else i.addFlow({runIndex:rt.current,objective:pt.current,status:E,summary:y??"",duration:A??0,steps:J,stepsPassed:K,stepsFailed:G,reason:I,creditsConsumed:M.lastRunEnd?.credits_consumed})}},[M.lastRunEnd,i,ue]);let Dn=(0,L.useRef)(null);(0,L.useEffect)(()=>{M.askingUser&&M.askingUser!==Dn.current&&(Dn.current=M.askingUser,ae((0,D.jsxs)(S,{children:[(0,D.jsx)(f,{color:"#ff9500",children:"? "}),(0,D.jsx)(f,{color:"#ff9500",children:"Agent asks: "}),(0,D.jsx)(f,{children:M.askingUser})]}))),M.askingUser||(Dn.current=null)},[M.askingUser,ae]);let Ar=(0,L.useRef)(null);(0,L.useEffect)(()=>{if(Z&&!M.isRunning&&M.lastRunEnd){if(Ar.current===M.lastRunEnd)return;Ar.current=M.lastRunEnd,ae((0,D.jsxs)(S,{flexDirection:"column",children:[(0,D.jsx)(Ds,{status:Z.status,steps:Z.stepsTotal,duration:Z.duration,creditsConsumed:Z.creditsConsumed,reason:Z.reason}),(0,D.jsx)(js,{})]})),ne(null)}},[Z,M.isRunning,M.lastRunEnd,ae]),(0,L.useEffect)(()=>{se.current?.setRunActive(M.isRunning)},[M.isRunning]),(0,L.useEffect)(()=>{if(M.runError&&!M.isRunning){let E=M.runError.trim();i.log("error","RUNNER_ERROR","Runner error occurred",{error:E}),i.escalateRun(i.nextRunIndex()-1);let y=E.split(`
47
+ `)}catch{}},cancel(){o.kill("SIGTERM")},get stderr(){return l},get exitCode(){return i},get exitSignal(){return c},exited:d}}async function ks(s,e,t=100){let n=`${s.replace(/\/+$/,"")}/json/version`,r=await fetch(n);if(!r.ok)throw new Error(`CDP /json/version returned ${r.status}`);let o=await r.json();if(!o.webSocketDebuggerUrl)throw new Error("CDP /json/version missing webSocketDebuggerUrl");let a=new Fo(o.webSocketDebuggerUrl);await new Promise((P,C)=>{a.once("open",P),a.once("error",C)});let l=1,i=new Map;a.on("message",P=>{let C;try{C=JSON.parse(P.toString())}catch{return}if(C.id==null)return;let O=i.get(C.id);O&&(i.delete(C.id),C.error?O.reject(new Error(C.error.message)):O.resolve(C.result))});function c(P,C){let O=l++;return new Promise((te,Z)=>{i.set(O,{resolve:ne=>te(ne),reject:Z}),a.send(JSON.stringify({id:O,method:P,params:C}))})}let m=(await c("Target.getTargets")).targetInfos.find(P=>P.type==="page");if(!m)throw a.close(),new Error("CDP: no page target found");let p=(await c("Browser.getWindowForTarget",{targetId:m.targetId})).windowId,_="",b=!1,E=null;async function A(){if(!b){try{let C=(await c("Browser.getWindowBounds",{windowId:p})).bounds,O=`${C.left}:${C.top}:${C.width}:${C.height}`;O!==_&&(_=O,e({left:C.left,top:C.top,width:C.width,height:C.height}))}catch{b=!0,a.close();return}b||(E=setTimeout(A,t))}}return A(),{stop(){if(!b){b=!0,E&&clearTimeout(E);try{a.close()}catch{}}}}}var _a=new Set(["1","true","yes"]);function or(s){if(s?.headless)return null;let e=process.env.KANE_CLI_DISABLE_MARKER;if(e!=null&&_a.has(e.toLowerCase()))return null;let t=lo();if(!t)return null;let n=[...t.args,"overlay"];s?.text&&n.push(s.text);let r;try{r=va(t.cmd,n,{cwd:t.cwd,stdio:["pipe","ignore","ignore"],detached:!1,windowsHide:!0})}catch{return null}function o(i){if(!(!r.stdin||r.stdin.destroyed))try{r.stdin.write(JSON.stringify(i)+`
48
+ `)}catch{}}let a=null;s?.cdpEndpoint&&ks(s.cdpEndpoint,i=>{o({type:"bounds",...i})}).then(i=>{a=i.stop}).catch(()=>{});let l=!1;return{setRunActive(i){l||o({type:"run_active",active:i})},kill(){if(!l){l=!0,a?.();try{r.stdin?.end()}catch{}try{r.kill("SIGTERM")}catch{}}}}}var ke=U(De(),1);function co(s){let e=s.indexOf(": ");return e>0&&e<15?s.slice(e+2):s}function uo(s){return s.map(e=>{let t=e.children?uo(e.children):e.children;return e.status==="running"?{...e,status:"stopped",phase:void 0,children:t}:t!==e.children?{...e,children:t}:e})}function sr(s,e){let[t,n]=(0,ke.useState)(!1),[r,o]=(0,ke.useState)([]),[a,l]=(0,ke.useState)(null),[i,c]=(0,ke.useState)(null),[d,m]=(0,ke.useState)(null),[g,p]=(0,ke.useState)(null),[_,b]=(0,ke.useState)([]),E=(0,ke.useRef)(null),A=(0,ke.useRef)(null),P=(0,ke.useRef)(0),C=(0,ke.useRef)(!1),O=(0,ke.useCallback)((ne,_e)=>{E.current&&(E.current.cancel(),E.current=null),o([]),l(null),c(null),m(null),p(null),b([]),n(!0),A.current=null,P.current=0;let F;try{F=rr(ne,_e)}catch(N){m(N instanceof Error?N.message:String(N)),n(!1);return}E.current=F,Ge("runner",()=>F.cancel()),(async()=>{C.current=!1;for await(let u of F.events){if(C.current)break;switch(u.type){case"run_start":if(A.current&&!A.current.isSingleFlow){let x=P.current;P.current++,o(h=>h.map((I,B)=>B===x?{...I,status:"running"}:I.status==="running"&&!I.children?.some(D=>D.status==="running")?{...I,status:I.children?.some(D=>D.status==="failed")?"failed":"passed"}:I))}break;case"bifurcation":{let x=u.flows??[],h=u.count??x.length,I={flows:x,isSingleFlow:u.is_single_flow??h<=1};p(I),A.current=I,P.current=0,o(x.map((B,D)=>({index:D+1,objective:B??`Flow ${D+1}`,status:"pending"})));break}case"step_start":{e?.("STEP_START",`Step ${u.index} started`,{index:u.index,objective:u.objective,child_id:u.child_id});let x=u.index,h=u.objective??`Step ${x}`,I=u.child_id,B=A.current&&!A.current.isSingleFlow;if(I)o(D=>{let J=D.findIndex(Re=>Re.status==="running"||Re.children?.some($e=>$e.status==="running"));if(J===-1)return D;let re=[...D],ee={...re[J]},me=[...ee.children??[]].map(Re=>Re.status==="running"?{...Re,status:"stopped",phase:void 0}:Re);return me.push({index:x,objective:h,status:"running"}),ee.children=me,re[J]=ee,re});else if(B){let D=Math.max(0,P.current-1);o(J=>{let re=[...J];if(D>=re.length)return J;let ee={...re[D]},me=[...ee.children??[]].map(Re=>Re.status==="running"?{...Re,status:"stopped",phase:void 0}:Re);return me.push({index:x,objective:h,status:"running"}),ee.children=me,ee.status="running",re[D]=ee,re})}else o(D=>{let J=uo(D);return J.some(ee=>ee.index===x)?J.map(ee=>ee.index===x?{...ee,status:"running",objective:h}:ee):[...J,{index:x,objective:h,status:"running"}]});break}case"step_event":{e?.("STEP_EVENT",`Step ${u.index} ${u.event}`,{index:u.index,phase:u.event,action_type:u.action_type,detail:u.detail,child_id:u.child_id});let x=u.child_id,h=A.current&&!A.current.isSingleFlow;if(u.event==="cm_init"&&u.checkpoint_count!=null){b(I=>[...I,u.checkpoint_count]);break}if(x)o(I=>I.map(B=>{if(!B.children)return B;let D=B.children.map(J=>{if(J.index!==u.index)return J;let re={phase:u.event};return u.event==="reasoning"&&u.detail&&u.detail!=="reasoning"&&(re.objective=u.detail),u.action_type&&(re.actionType=u.action_type),{...J,...re}});return{...B,children:D}}));else if(h){let I=Math.max(0,P.current-1);o(B=>{let D=[...B];if(I>=D.length)return B;let J={...D[I]},re=[...J.children??[]];if(!re.some(Ie=>Ie.index===u.index))re.push({index:u.index,objective:`Step ${u.index}`,status:"running",phase:u.event,actionType:u.action_type});else for(let Ie=0;Ie<re.length;Ie++){if(re[Ie].index!==u.index)continue;let me={phase:u.event};u.event==="reasoning"&&u.detail&&u.detail!=="reasoning"&&(me.objective=u.detail),u.action_type&&(me.actionType=u.action_type),re[Ie]={...re[Ie],...me}}return J.children=re,D[I]=J,D})}else o(I=>I.some(D=>D.index===u.index)?I.map(D=>{if(D.index!==u.index)return D;let J={phase:u.event};return u.event==="reasoning"&&u.detail&&u.detail!=="reasoning"&&(J.objective=u.detail),u.action_type&&(J.actionType=u.action_type),{...D,...J}}):[...uo(I),{index:u.index,objective:`Step ${u.index}`,status:"running",phase:u.event,actionType:u.action_type}]);break}case"step_end":{e?.("STEP_END",`Step ${u.index} ${u.status}`,{index:u.index,status:u.status,duration:u.duration,summary:u.summary,child_id:u.child_id});let x=u.child_id,h=A.current&&!A.current.isSingleFlow;if(x)o(I=>I.map(B=>{if(!B.children)return B;let D=B.children.map(J=>J.index===u.index?{...J,status:u.status,duration:u.duration,phase:void 0,objective:J.objective.startsWith("Step ")?co(u.summary||J.objective):J.objective}:J);return{...B,children:D}}));else if(h){let I=Math.max(0,P.current-1);o(B=>{let D=[...B];if(I>=D.length)return B;let J={...D[I]},re=(J.children??[]).map(ee=>ee.index===u.index?{...ee,status:u.status,duration:u.duration,phase:void 0,objective:ee.objective.startsWith("Step ")?co(u.summary||ee.objective):ee.objective}:ee);return J.children=re,D[I]=J,D})}else o(I=>I.map(B=>B.index===u.index?{...B,status:u.status,duration:u.duration,phase:void 0,objective:B.objective.startsWith("Step ")?co(u.summary||B.objective):B.objective}:B));{let B=A.current&&!A.current.isSingleFlow?Math.max(0,P.current-1):0;s?.(u.index,B,u.child_id)}break}case"child_agent_start":{let x=u.objective??"";o(h=>h.map(I=>I.status==="running"?{...I,objective:`${x} (branch)`,phase:`child: ${x.slice(0,50)}`,branchObjective:x}:I));break}case"child_agent_end":o(x=>x.map(h=>h.phase?.startsWith("child:")?{...h,phase:`child ${u.success?"done":"failed"}`}:h));break;case"ask_user":l(u.question??"");break;case"run_end":o(x=>x.map(h=>h.status==="running"?{...h,status:u.status,phase:void 0}:h)),c(u),n(!1),qe("runner","Run completed"),E.current=null;break;case"error":m(u.message??"Runner error"),o(x=>x.map(h=>h.status==="running"?{...h,status:"failed",phase:void 0}:h)),n(!1),qe("runner","Runner error"),E.current=null;break}}let N=E.current;if(N){let{code:u,signal:x}=await N.exited,h=N.stderr,I=[];u!==null&&u!==0&&I.push(`Runner exited with code ${u}`),x&&I.push(`Runner killed by signal ${x}`),h&&I.push(h),I.length>0&&m(I.join(`
49
+ `))}n(!1),qe("runner","Event stream ended"),E.current=null})().catch(N=>{let u=E.current,x=[`Runner event loop error: ${N}`];u&&(u.exitCode!==null&&u.exitCode!==0&&x.push(`Exit code: ${u.exitCode}`),u.exitSignal&&x.push(`Signal: ${u.exitSignal}`),u.stderr&&x.push(u.stderr)),m(x.join(`
50
+ `)),n(!1),qe("runner","Event loop error"),E.current=null})},[s,e]),te=(0,ke.useCallback)(ne=>{E.current?.sendUserResponse(ne),l(null)},[]),Z=(0,ke.useCallback)(()=>{let ne=E.current;ne&&(ne.sendCancel("user"),n(!1),l(null),setTimeout(()=>{E.current===ne&&(qe("runner","User cancelled run"),E.current=null)},5e3))},[]);return(0,ke.useEffect)(()=>()=>{C.current=!0,qe("runner","Component unmounted"),E.current=null},[]),{isRunning:t,steps:r,askingUser:a,lastRunEnd:i,runError:d,bifurcationInfo:g,cmInitCounts:_,startRun:O,sendAnswer:te,cancelRun:Z}}function Rn(s){let e=s.flatMap(o=>[o,...o.children??[]]),t=e.filter(o=>o.status==="passed").length,n=e.filter(o=>o.status==="failed").length,r=e.filter(o=>o.status==="passed"||o.status==="failed").length;return{passed:t,failed:n,total:r}}async function on(s,e,t,n){let r=s.loadBasicAuth(e,t),o=s.loadCredentials(e,t);if(!r&&!o)return n("info","STARTUP_GATE_NO_CREDS","Profile has no credentials",{profile:e,env:t}),{status:"needs_login",profile:e,env:t};let a=ae(t),l=async()=>s.loadCredentials(e,t)?.access_token??null,i=new pt(a.controllerBaseUrl,l,r,n);n("info","STARTUP_GATE_VALIDATE","Validating credentials with controller",{profile:e,env:t,method:r?"basic":"oauth"});let c=await i.resolve(!0);if(c)return n("info","STARTUP_GATE_VALID","Credentials validated",{profile:e,env:t,username:c.username,org_id:c.org_id}),{status:"authenticated",result:{profile:e,env:t,credentials:o,basicAuth:r,tmsCreds:c,resolver:i}};if(!r&&o){let d=o.refresh_token,g=s.loadClient(e,t)?.client_id;if(d&&g){n("info","STARTUP_GATE_REFRESH","Attempting token refresh",{profile:e,env:t});try{let _=await new nn(t).refreshToken(d,g);if(_.access_token){s.saveCredentials(e,t,{...o,..._,expires_at:Date.now()/1e3+(_.expires_in??3600)});let E=await i.resolve(!0);if(E)return n("info","STARTUP_GATE_REFRESH_OK","Token refreshed and validated",{profile:e,env:t,username:E.username}),{status:"authenticated",result:{profile:e,env:t,credentials:{...o,..._},basicAuth:null,tmsCreds:E,resolver:i}}}n("warn","STARTUP_GATE_REFRESH_INVALID","Refreshed token still invalid",{profile:e,env:t})}catch(p){n("warn","STARTUP_GATE_REFRESH_FAILED","Token refresh failed",{profile:e,env:t,error:p instanceof Error?p.message:String(p)})}}else n("info","STARTUP_GATE_NO_REFRESH","No refresh_token or client_id \u2014 login required",{profile:e,env:t})}return n("info","STARTUP_GATE_INVALID","Credentials invalid \u2014 login required",{profile:e,env:t}),{status:"needs_login",profile:e,env:t}}async function ir(s,e){let t=s.listProfiles();if(e("info","STARTUP_GATE_START","Auth startup gate",{profile_count:t.length}),t.length===0)return e("info","STARTUP_GATE_NONE","No profiles found \u2014 login required"),{status:"needs_login"};if(t.length>1){let o=s.getActiveProfile(),a=s.getDefaultEnv();if(o&&t.some(i=>i.profile===o&&i.env===a)){e("info","STARTUP_GATE_TRY_ACTIVE","Multiple profiles \u2014 trying active first",{activeProfile:o,activeEnv:a});let i=await on(s,o,a,e);if(i.status==="authenticated")return i;e("info","STARTUP_GATE_ACTIVE_FAILED","Active profile invalid \u2014 showing picker",{activeProfile:o,activeEnv:a})}return e("info","STARTUP_GATE_MULTI","Multiple profiles \u2014 picker required",{profiles:t.map(l=>`${l.profile}/${l.env}`)}),{status:"needs_pick",profiles:t}}let{profile:n,env:r}=t[0];return s.setActiveProfile(n),s.setDefaultEnv(r),on(s,n,r,e)}var ar=[{name:"run",description:"Execute a test run",args:'"objective"'},{name:"login",description:"OAuth login",args:"[--profile name]"},{name:"logout",description:"Logout & revoke tokens",args:"[--profile name]"},{name:"whoami",description:"Show profile info",args:"[--profile name]"},{name:"balance",description:"Show credit balance"},{name:"profiles",description:"Manage profiles",args:"list|switch|delete"},{name:"config",description:"Manage configuration",args:"show|set-window|set-mode|chrome-profile|project|folder"},{name:"new",description:"Start a fresh session (uploads current first)"},{name:"summary",description:"View detailed run summaries",args:"[index]"},{name:"cancel",description:"Abort current run"},{name:"help",description:"Show command reference"},{name:"clear",description:"Clear chat history"},{name:"exit",description:"Quit kane-cli"}];function Is(s){let e=s.trim();if(!e.startsWith("/"))return null;let n=e.slice(1).match(/(?:[^\s"]+|"[^"]*")+/g)??[];if(n.length===0)return null;let r=n[0],o={},a=1;for(;a<n.length;){let l=n[a];if(l.startsWith("--")){let i=l.slice(2),c=n[a+1];c&&!c.startsWith("--")?(o[i]=c.replace(/^"|"$/g,""),a+=2):(o[i]=void 0,a++)}else{let i=l.replace(/^"|"$/g,"");r==="run"?o.objective=i:r==="config"?o.action?o.value=i:o.action=i:r==="profiles"?o.action=i:r==="summary"&&(o.index=i),a++}}return{command:r,args:o,raw:e}}var Au=[{name:"Testing",commands:ar.filter(s=>["run","cancel"].includes(s.name))},{name:"Auth",commands:ar.filter(s=>["login","logout","whoami","balance","profiles"].includes(s.name))},{name:"Settings",commands:ar.filter(s=>["config"].includes(s.name))},{name:"Session",commands:ar.filter(s=>["new","summary","help","clear","exit"].includes(s.name))}];var Ps=[{name:"auth",description:"Login, logout, profiles"},{name:"config",description:"View/change settings"},{name:"help",description:"Command reference"},{name:"new",description:"Start a fresh session"},{name:"summary",description:"View run summaries",args:"[index]"},{name:"cancel",description:"Abort current run"},{name:"exit",description:"Quit kane-cli"}];var ze=U(Q(),1),ba=64;function xa(s){return s.split(`
51
+ `).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function sn({status:s,summary:e,duration:t,steps:n,stepsPassed:r,stepsFailed:o,reason:a,creditsConsumed:l}){let i=s==="passed",c=i?v.green:v.red,d=i?"\u2713":"\u2717",m=s.toUpperCase(),g=r??(i?n:Math.max(0,n-1)),p=o??(i?0:1),_=p>0?`${n} steps (${g} passed, ${p} failed)`:`${n} steps`,b=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,E=xa(e);return(0,ze.jsx)(y,{flexDirection:"column",marginTop:1,children:(0,ze.jsxs)(y,{borderStyle:"round",borderColor:c,flexDirection:"column",paddingX:2,paddingY:1,width:ba+6,children:[(0,ze.jsxs)(y,{flexDirection:"column",children:[(0,ze.jsxs)(f,{bold:!0,color:c,children:[d," ",m]}),(0,ze.jsxs)(f,{color:v.dimmed,wrap:"wrap",children:[_," \xB7 ",b,typeof l=="number"&&l>0?` \xB7 ${parseFloat(l.toFixed(4))} credits`:""]})]}),E.length>0&&(0,ze.jsx)(y,{flexDirection:"column",marginTop:1,marginLeft:1,children:E.map((A,P)=>(0,ze.jsxs)(y,{marginBottom:P<E.length-1?1:0,children:[(0,ze.jsx)(f,{color:v.primary,children:"\u25CF "}),(0,ze.jsx)(y,{flexShrink:1,children:(0,ze.jsx)(f,{wrap:"wrap",children:A})})]},P))}),a&&!i&&(0,ze.jsx)(y,{marginTop:1,children:(0,ze.jsxs)(f,{color:v.red,wrap:"wrap",children:["Reason: ",a]})})]})})}var jt=U(Q(),1);function fo({flows:s,filterIndex:e}){let t=e!==void 0?s.filter(n=>n.index===e):s;return t.length===0?null:(0,jt.jsx)(y,{flexDirection:"column",children:t.map(n=>(0,jt.jsxs)(y,{flexDirection:"column",marginTop:1,children:[(0,jt.jsxs)(y,{marginLeft:1,children:[(0,jt.jsx)(f,{color:"#b388ff",bold:!0,children:"Flow "+n.index+": "}),(0,jt.jsx)(f,{color:"#b388ff",children:n.objective})]}),(0,jt.jsx)(sn,{status:n.status==="error"?"failed":n.status,summary:n.summary,duration:n.duration,steps:n.steps,stepsPassed:n.stepsPassed,stepsFailed:n.stepsFailed,reason:n.reason,creditsConsumed:n.creditsConsumed})]},n.index))})}var wa=null;function Os(s){wa=s}import{readFileSync as ya,existsSync as Sa}from"fs";function an(s){if(!Sa(s))return null;try{return ya(s,"utf-8").trim()||null}catch{return null}}import{join as ut}from"path";var lr=U(Q(),1);function Ds({status:s,steps:e,duration:t,creditsConsumed:n,reason:r}){let o=s==="passed",a=o?v.green:v.red,l=o?"\u2713":"\u2717",i=o?"Passed":"Failed",c=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,d=typeof n=="number"&&n>0?` \xB7 ${n.toFixed(4)} credits`:"",m=!o&&r?` \xB7 ${r}`:"";return(0,lr.jsxs)(y,{children:[(0,lr.jsxs)(f,{bold:!0,color:a,children:[l," ",i]}),(0,lr.jsxs)(f,{color:v.dimmed,children:[" ","\xB7 ",e," steps \xB7 ",c,d,m]})]})}var Ls=U(Q(),1);function js(){return(0,Ls.jsx)(f,{color:v.dimmed,children:"Continue below \xB7 /new fresh session \xB7 /summary view details \xB7 Ctrl+C exit"})}function $s(s,e,t){return`${s}/projects/${e}/test-cases/${t}`}function Kt(s,e,t,n){return`${$s(s,e,t)}/dashboard/share/${n}?type=summary&agentView=true&fqdn=summary-page`}function An(s,e,t){return`${$s(s,e,t)}/dashboard?type=summary&agentView=true&fqdn=summary-page`}import{readFileSync as Bs,readdirSync as Vs,existsSync as Gt}from"fs";import{join as yt}from"path";function cr(s,e,t,n,r,o){try{let a=yt(s,"runs",String(e),"run-test");if(!Gt(a)){r("warn","SCREENSHOT_SKIP","Runs dir not found",{step_index:t,reason:"runsDir_not_found",path:a});return}let l=a;if(o){let b=yt(a,`child-${o}`);if(!Gt(b)){r("warn","SCREENSHOT_SKIP","Child dir not found",{step_index:t,child_id:o,reason:"child_dir_not_found",path:b});return}let E=Vs(b).filter(A=>Gt(yt(b,A,"screenshots")));if(E.length===0){r("warn","SCREENSHOT_SKIP","No screenshots dir under child",{step_index:t,child_id:o,reason:"no_child_screenshots_dir"});return}l=yt(b,E[0])}else if(!Gt(yt(a,"screenshots"))){let b=Vs(a).filter(E=>Gt(yt(a,E,"screenshots")));if(b.length===0){r("warn","SCREENSHOT_SKIP","No screenshots dir found",{step_index:t,reason:"no_screenshots_dir"});return}l=yt(a,b[0])}let i=yt(l,"screenshots",`step_${String(t).padStart(3,"0")}.png`);if(!Gt(i)){r("warn","SCREENSHOT_SKIP","Screenshot not found",{step_index:t,child_id:o,reason:"screenshot_not_found",path:i});return}let c=yt(a,"actions.ndjson");if(!Gt(c)){r("warn","SCREENSHOT_SKIP","NDJSON not found",{step_index:t,reason:"ndjson_not_found"});return}let d=Bs(c,"utf-8").trim().split(`
52
+ `),m=d[d.length-1];if(!m){r("warn","SCREENSHOT_SKIP","NDJSON empty",{step_index:t,reason:"ndjson_empty"});return}let p=JSON.parse(m).action_id;if(!p){r("warn","SCREENSHOT_SKIP","No action_id in NDJSON",{step_index:t,reason:"no_action_id"});return}let _=Bs(i);n.enqueue(p,_),r("info","SCREENSHOT_ENQUEUED","Screenshot enqueued",{step_index:t,child_id:o,action_id:p,size:_.length})}catch(a){r("error","SCREENSHOT_DISPATCH_ERROR","Screenshot dispatch error",{step_index:t,error:a instanceof Error?a.message:String(a)})}}import Ea from"sharp";var ln=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 l=await Ea(e.buffer).webp({quality:80}).toBuffer();t=new Uint8Array(l)}catch(l){t=new Uint8Array(e.buffer),n="image/png",this.log?.("warn","SCREENSHOT_CONVERT_FAILED","WebP conversion failed, using PNG",{operation_id:e.operationId,error:l instanceof Error?l.message:String(l)})}let r=n==="image/webp"?"webp":"png",o=`test_screenshots/untagged_screenshot/${e.operationId}.${r}`,a=`${this.sas.base_url}/${this.sas.container}/${o}?${this.sas.sas_token}`;for(let l=0;l<=this.maxRetries;l++)try{let i=await fetch(a,{method:"PUT",headers:{"Content-Type":n,"x-ms-blob-type":"BlockBlob"},body:t});if(i.ok)return;if(l<this.maxRetries){await this.backoff(l);continue}this.log?.("warn","SCREENSHOT_UPLOAD_FAILED","Screenshot upload failed after retries",{operation_id:e.operationId,status:i.status,attempts:this.maxRetries+1})}catch{if(l<this.maxRetries){await this.backoff(l);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 Ca,readFileSync as Ns,existsSync as Us}from"fs";import{join as Ra}from"path";function Fs(s,e){if(!Us(s))return{};let t={},n;try{n=Ca(s).filter(r=>r.endsWith(".json")).sort()}catch{return{}}for(let r of n)try{let o=Ns(Ra(s,r),"utf-8"),a=JSON.parse(o);if(a&&typeof a=="object"){for(let[l,i]of Object.entries(a))if(i&&typeof i=="object"&&"value"in i){let c=i;t[l]={value:c.value,secret:c.secret??!1,syntax:c.syntax??`{{${l}}}`}}}}catch{e?e("warn","VARIABLE_PARSE_FAILED","Skipping invalid variables file",{file:r}):process.stderr.write(`[variables] Warning: skipping invalid variables file: ${r}
53
+ `)}return t}function Ms(s){if(!Us(s))throw new Error(`Variables file not found: ${s}`);let e=Ns(s,"utf-8"),t=JSON.parse(e),n={};if(t&&typeof t=="object"){for(let[r,o]of Object.entries(t))if(o&&typeof o=="object"&&"value"in o){let a=o;n[r]={value:a.value,secret:a.secret??!1,syntax:a.syntax??`{{${r}}}`}}}return n}function Hs(s){let e;try{e=JSON.parse(s)}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 o=r;t[n]={value:o.value,secret:o.secret??!1,syntax:o.syntax??`{{${n}}}`}}}return t}function Ws(s,e,t){let n=Fs(s,t),r=Fs(e,t);return{...n,...r}}function Ks(s,e){let t={},n={},r=e;for(let[o,a]of Object.entries(s))if(a.secret){let l=`secrets.user.${o}`;t[l]={value:a.value,secret:!0,syntax:`{{secrets.user.${o}}}`,type:"secret"},n[o]=l,r=r.replaceAll(`{{${o}}}`,`{{secrets.user.${o}}}`)}else{let l=`global.${o}`;t[l]={value:a.value,secret:!1,syntax:`{{global.${o}}}`,type:"global"},n[o]=l,r=r.replaceAll(`{{${o}}}`,`{{global.${o}}}`)}return{variables:t,objective:r,keyMap:n}}var ur=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=Mo(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 dr=class extends Ho{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 o=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${t}`,{method:"GET",headers:this.headers()});return o.ok?{id:(await o.json()).data?.id??0}:{id:0}}};function fr(s){let e=Ws(s.globalDir,s.localDir,s.onLoadError),t=s.file?Ms(s.file):{},n=s.inline?Hs(s.inline):{},r={...e,...t,...n},o=Object.keys(r).length>0,{variables:a,objective:l}=o?Ks(r,s.objective):{variables:{},objective:s.objective},i=Object.entries(r).filter(([,d])=>d.secret),c=Object.entries(r).filter(([,d])=>!d.secret);return{raw:r,auteur:a,auteurObjective:l,secretEntries:i,nonSecretEntries:c}}async function mr(s){if(s.localMode)return{};let e=ae(s.env);if(s.variables.secretEntries.length>0){let n=new ur(e.secretsBaseUrl);for(let[r,o]of s.variables.secretEntries)n.pushSecret({secretKey:r,secretValue:o.value,username:s.auth.username,accessKey:s.auth.access_key,orgId:s.orgId}).then(()=>s.log("info","SECRET_PUSH_OK","Secret pushed",{key:r})).catch(a=>s.log("error","SECRET_PUSH_FAILED","Secret push failed",{key:r,error:String(a)}))}let t={};if(s.variables.nonSecretEntries.length>0){let n=new dr(e.tmsBaseUrl,s.auth.username,s.auth.access_key);for(let[r,o]of s.variables.nonSecretEntries)try{let a=await n.upsertVariable({name:r,value:o.value});t[r]=a.id,s.log("info","VAR_PUSH_OK","Variable pushed",{name:r,id:a.id})}catch(a){s.log("error","VAR_PUSH_FAILED","Variable push failed",{name:r,error:String(a)})}}return t}function pr(s){let e={objective:s.objective,model:s.model,width:s.windowSize.width,height:s.windowSize.height,session_id:s.sessionId,run_index:s.runIndex,stream:!0,max_steps:s.maxSteps??30,headless:s.headless??!1};return s.url&&(e.url=s.url),s.chrome.wsEndpoint?e.ws_endpoint=s.chrome.wsEndpoint:s.chrome.cdpEndpoint&&(e.cdp_endpoint=s.chrome.cdpEndpoint),s.auth.basicAuth?(e.username=s.auth.basicAuth.username,e.access_key=s.auth.basicAuth.access_key):s.auth.token&&(e.auth={type:"bearer",token:s.auth.token}),s.disableAskUser&&(e.disable_ask_user=!0),s.enableTaskSkills&&(e.enable_task_skills=!0),s.variables&&Object.keys(s.variables).length>0&&(e.variables=s.variables),s.globalContext&&(e.global_context=s.globalContext),s.localContext&&(e.local_context=s.localContext),s.sessionContext&&(e.session_context=s.sessionContext),e}function Tn(s){let e=ae(s.env),{session:t,auth:n}=s,r=n.basicAuth?{username:n.basicAuth.username,accessKey:n.basicAuth.access_key}:n.token,o=n.resolvedCreds?.username??n.basicAuth?.username??"",a=n.resolvedCreds?.access_key??n.basicAuth?.access_key??"",l=n.resolvedCreds?.org_id??0,i=n.resolvedCreds?.user_id??0,c=[];for(let _ of Object.keys(t.auteurVariables))_.startsWith("secrets.user.")&&c.push({key_name:_.replace("secrets.user.",""),scope:"user"});let m=t.getContext().prior_runs.map(_=>_.status),g=t.auteurVariables,p=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:s.projectId,folderId:s.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:s.totalSteps,totalDuration:s.totalDuration,runStatuses:m,orgId:l,userId:i,tmsUsername:o,tmsAccessKey:a,screenshotBaseUrl:t.screenshotBaseUrl,shareApiBaseUrl:e.shareApiBaseUrl,variables:p?g:void 0,variableIds:s.variableIds,secrets:c,codeExport:s.codeExport,onProgress:s.onProgress,log:s.log}}var Gs=["python"];function Aa(s){if(s!==void 0){if(!Gs.includes(s))throw new Error(`--code-language must be one of: ${Gs.join(", ")} (got "${s}")`);return s}}function kn(s,e){let t=Aa(s.codeLanguage);return{enabled:s.codeExport??e.enabled,language:t??e.language,skipValidation:s.skipCodeValidation??e.skip_validation}}async function gr(s){try{let t=await new lt(s.tmsBaseUrl,s.auth.username,s.auth.access_key).createAtmTest({objective:s.objective.slice(0,100),creation_mode:"KANECLI",playground_disabled:s.hasCustomProfile,testURL:s.url,project_id:s.projectId,folder_id:s.folderId,authoring_version:4});return s.log("info","ATM_CREATE_OK","Test created",{test_id:t}),t}catch(e){return s.log("error","ATM_CREATE_FAILED","Test creation failed",{error:e instanceof Error?e.message:String(e)}),null}}async function hr(s){await new lt(s.tmsBaseUrl,s.username,s.accessKey).submitFeedback({instruction_id:"",test_id:s.testId,feedback_type:s.feedbackType,mode:s.mode??"human",...s.details?{details:s.details}:{}}),s.log("info","FEEDBACK_SUBMITTED","Feedback submitted",{type:s.feedbackType})}var j=U(Q(),1);function qs({localMode:s=!1,codeExport:e,codeLanguage:t,skipCodeValidation:n,updatePromise:r}={}){Zt();let o=(0,$.useRef)(new bt),[a,l]=(0,$.useState)(0),i=o.current,[c]=(0,$.useState)(()=>new ot),d=(0,$.useRef)(0),m=(0,$.useCallback)(()=>`msg-${++d.current}`,[]),[g,p]=(0,$.useState)(!1),[_,b]=(0,$.useState)(null),[E,A]=(0,$.useState)(!1),[P,C]=(0,$.useState)(0),[O,te]=(0,$.useState)(!1),[Z,ne]=(0,$.useState)(null),[_e,F]=(0,$.useState)(null),N=(0,$.useRef)(null),[u,x]=(0,$.useState)(null),[h,I]=(0,$.useState)(Bn()),[B,D]=(0,$.useState)(null),[J,re]=(0,$.useState)([]),[ee,Ie]=(0,$.useState)(!1),[me,Re]=(0,$.useState)(!1),$e=(0,$.useRef)(null),et=(0,$.useRef)(0),Et=(0,$.useRef)(""),yr=(0,$.useRef)(null),$t=(0,$.useRef)(null),Bt=(0,$.useRef)({}),M=(0,$.useRef)(null),ie=(0,$.useRef)(0),[oe,ge]=(0,$.useState)([]),ue=(0,$.useCallback)(S=>{let R=`s-${++ie.current}`;ge(w=>[...w,{id:R,content:S}])},[]),[Ue,ce]=(0,$.useState)("booting"),[Ae,de]=(0,$.useState)([]),[Oe,Me]=(0,$.useState)(!1),[dt,Xt]=(0,$.useState)(!1),[tt,Sr]=(0,$.useState)("chat"),[Vt,Ft]=(0,$.useState)(null),[be,dn]=(0,$.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),xi=Fn(),T=_s(),On=Rs(),wi=(0,$.useCallback)((S,R,w)=>{let k=$e.current;if(!k)return;let L=et.current+R;cr(i.sessionDir,L,S,k,(G,q,z,Y)=>i.log(G,q,z,Y),w)},[i]),yi=(0,$.useCallback)((S,R,w)=>{i.logStep(S,R,w)},[i]),H=sr(wi,yi),[W,nt]=(0,$.useState)(()=>c.load()),[,Si]=(0,$.useState)(0),Xe=(0,$.useCallback)(()=>Si(S=>S+1),[]),[K,Se]=(0,$.useState)(null),Yt=T.creds.getActiveProfile(),pe=T.creds.getDefaultEnv(),Ye=(0,$.useCallback)((S,R)=>{let w=S?T.creds.loadProfileConfig(S,R):null;c.save({project_id:w?.project_id??null,project_name:w?.project_name??null,folder_id:w?.folder_id??null,folder_name:w?.folder_name??null}),nt(c.load())},[T.creds,c]);(0,$.useEffect)(()=>{E||(i.start({model:W.model,environment:pe,profile:Yt}),A(!0))},[i,E,W.model,pe,Yt]);let Po=(0,$.useCallback)(async S=>{let R=ae(S),w=T.getBasicAuth(),k=w?{username:w.username,accessKey:w.access_key}:await T.getToken().then(G=>G??"");if(!k)return;let L=new Wo(R.controllerBaseUrl,k);try{let G=await L.getScreenshotSas();i.setScreenshotSas(G),$e.current=new ln(G,3,(q,z,Y,fe)=>i.log(q,z,Y,fe)),i.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched")}catch(G){i.log("warn","SCREENSHOT_SAS_FAILED","Screenshot SAS fetch failed",{error:G instanceof Error?G.message:String(G)})}},[T,i]),Ct=(0,$.useCallback)(async S=>{let R=S??T.creds.getDefaultEnv();D(null),$e.current=null;let k=await T.initResolver(R,(L,G,q,z)=>i.log(L,G,q,z)).resolve(!0).catch(()=>null);return D(k),k&&(i.log("info","AUTH_RESET_OK","Auth reset resolved",{username:k.username,org_id:k.org_id,env:R}),await Po(R)),k},[T,i,Po]),Oo=(0,$.useRef)(!1);(0,$.useEffect)(()=>{!g||Oo.current||!E||(Oo.current=!0,Ct().then(S=>{if(S){if(i.log("info","BOOT_RESOLVE_OK","Boot auth resolved",{username:S.username,org_id:S.org_id}),!i.hasRemoteLogger){let R=Ko({sessionId:i.sessionId,identity:{org_id:String(S.org_id??""),user_id:String(S.user_id??""),machine_id:Go()},environment:pe,getToken:async()=>T.getToken()});i.setRemoteLogger(R),R.start(),Ge("remote-logger",()=>R.shutdownSync()),Qn(R)}}else i.log("warn","BOOT_RESOLVE_FAILED","Boot auth failed \u2014 non-controller APIs may fail")}).catch(S=>{i.log("error","BOOT_RESOLVE_ERROR","Boot auth error",{error:S instanceof Error?S.message:String(S)})}))},[g,E,Ct,i]);let Nt=(0,$.useCallback)(async()=>{if(B)return i.log("info","TMS_CREDS_CACHED","Using cached TMS credentials",{username:B.username,org_id:B.org_id}),B;let S=await T.resolveBasicAuth();return S?(i.log("info","TMS_CREDS_OK","TMS credentials resolved",{username:S.username,org_id:S.org_id,user_id:S.user_id}),D(S)):i.log("warn","TMS_CREDS_FAILED","No TMS credentials resolved"),S},[T,B,i]),Do=(0,$.useCallback)(async()=>{let S=await Nt();if(!S)return i.log("warn","PROJECT_FAILED","No TMS credentials for project resolution"),null;let R=ae(pe),w=new lt(R.tmsBaseUrl,S.username,S.access_key),k=T.creds.getActiveProfile(),L=T.creds.getDefaultEnv(),G=k?T.creds.loadProfileConfig(k,L):null,q=G?.project_id??W.project_id;if(q)i.log("info","PROJECT_CACHED","Using cached project",{project_id:q});else{i.log("info","PROJECT_FETCH","No project_id in config, fetching from TMS");try{i.log("info","PROJECT_LIST","Listing projects from TMS",{url:`${R.tmsBaseUrl}/v1/projects`});let Y=await w.listProjects((we,fn,Rt,ft)=>i.log(we,fn,Rt,ft));i.log("info","PROJECT_LIST_OK","Projects listed",{count:Y.length});let fe=Y.find(we=>we.name==="KaneAI Generated");if(fe)q=fe.project_id,i.log("info","PROJECT_SELECTED","Using KaneAI Generated project",{project_id:q});else if(Y.length>0){let we=Y[0];q=we.project_id,i.log("info","PROJECT_SELECTED","Using first project",{name:we.name,project_id:q})}q&&c.set("project_id",q)}catch(Y){return i.log("error","PROJECT_LIST_FAILED","Project listing failed",{error:String(Y)}),null}}if(!q)return i.log("warn","PROJECT_NONE","No projects found"),null;let z=G?.folder_id??W.folder_id;if(z)i.log("info","FOLDER_CACHED","Using cached folder",{folder_id:z});else try{i.log("info","FOLDER_FETCH","Fetching default folder",{project_id:q}),z=await w.getDefaultFolder(q),i.log("info","FOLDER_OK","Default folder resolved",{folder_id:z}),z&&c.set("folder_id",z)}catch(Y){return i.log("error","FOLDER_FAILED","Default folder fetch failed",{error:String(Y)}),null}return{projectId:q,folderId:z??""}},[W.project_id,W.folder_id,Nt,pe,c,i]),le=(0,$.useCallback)(S=>{let R=m(),w={...S,id:R};ue((0,j.jsx)(rs,{entry:w}))},[m,ue]),jo=(0,$.useCallback)(async(S,R)=>{let w=i.nextRunIndex();et.current=w,Et.current=S,i.logRunStart(w,S,R??""),i.setFirstRun(S,R??"");let k=T.getResolvedBasicAuth(),L=k,G=null;if(!L&&(G=await T.getToken(),!G)){le({type:"error",text:"Not authenticated. Run /login first."});return}let q={basicAuth:k??null,token:G,resolver:T.getResolver(),resolvedCreds:null};if(yr.current=q,w===0&&!s){i.log("info","ATM_CREATE_START","Creating test via ATM endpoint",{run_index:0});let Pe=await Do(),it=ae(pe),at=L?{username:L.username,access_key:L.access_key}:await Nt();if(at){let gt=await gr({tmsBaseUrl:it.tmsBaseUrl,auth:{username:at.username,access_key:at.access_key},objective:S,url:R??W.default_url??"",projectId:Pe?.projectId??W.project_id??"",folderId:Pe?.folderId??W.folder_id??"",hasCustomProfile:!!W.chrome_profile_path,log:($n,Pr,Or,Dr)=>i.log($n,Pr,Or,Dr)});gt&&(i.setTestId(gt),Pe?.projectId&&i.setProjectId(Pe.projectId))}}let z=null;if(be.useCft)le({type:"info",text:"CfT mode: Playwright will manage browser"});else if(be.wsEndpoint)le({type:"info",text:`WS endpoint: ${be.wsEndpoint.slice(0,60)}...`});else if(be.cdpEndpoint)le({type:"info",text:`CDP endpoint: ${be.cdpEndpoint}`});else{le({type:"info",text:"Starting Chrome..."});try{z=await On.ensureChrome(R)}catch(it){le({type:"error",text:er(it)});return}i.logChromeLaunch(z.port,z.cdpEndpoint),le({type:"info",text:`Chrome ready (port ${z.port})`});let Pe=or({headless:be.headless,cdpEndpoint:z.cdpEndpoint});Pe&&(M.current=Pe,Ge("marker-overlay",()=>Pe.kill()))}let Y=fr({objective:S,globalDir:ut(Ee,"variables"),localDir:ut(process.cwd(),".testmuai","variables")});i.setAuteurVariables(Y.auteur),$t.current=Y;let fe=L&&!s?await mr({variables:Y,auth:L,orgId:String((await Nt())?.org_id??""),env:pe,localMode:s,log:(Pe,it,at,gt)=>i.log(Pe,it,at,gt)}):{};Bt.current=fe;let we=an(ut(Ee,"global-memory.md")),fn=an(ut(process.cwd(),".testmuai","context.md")),Rt=z?{cdpEndpoint:z.cdpEndpoint,instance:z,tempDir:null}:be.wsEndpoint?{wsEndpoint:be.wsEndpoint,instance:null,tempDir:null}:be.cdpEndpoint?{cdpEndpoint:be.cdpEndpoint,instance:null,tempDir:null}:{instance:null,tempDir:null},ft=pr({objective:Y.auteurObjective,url:R,model:W.model,chrome:Rt,auth:q,sessionId:i.sessionId,runIndex:w,windowSize:W.window_size,maxSteps:be.maxSteps,headless:be.headless,variables:Object.keys(Y.auteur).length>0?Y.auteur:void 0,globalContext:we??void 0,localContext:fn??void 0,sessionContext:i.getContext()});R&&b(R),ne(null),H.startRun(ft,{environment:pe,mode:W.mode,log:(Pe,it,at,gt)=>i.log(Pe,it,at,gt)}),C(Pe=>Pe+1)},[T,On,c,W,i,pe,H,le,be,Do,Nt]),Er=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(H.bifurcationInfo&&H.bifurcationInfo!==Er.current){Er.current=H.bifurcationInfo;let{flows:S,isSingleFlow:R}=H.bifurcationInfo;if(R&&S.length===1&&S[0])i.log("info","OBJECTIVE_REWRITTEN","Objective rewritten",{objective:S[0]}),le({type:"info",text:`Objective: ${S[0]}`});else if(!R&&S.length>1){let w=[`Bifurcated into ${S.length} flows:`];S.forEach((k,L)=>w.push(` ${L+1}. ${k}`)),i.log("info","BIFURCATION","Objective bifurcated into flows",{flow_count:S.length}),le({type:"info",text:w.join(`
54
+ `)})}}},[H.bifurcationInfo,i,le]);let Cr=$.default.useRef(null),Rr=$.default.useRef(0),Ar=$.default.useRef(0);(0,$.useEffect)(()=>{if(H.lastRunEnd&&H.lastRunEnd!==Cr.current){Cr.current=H.lastRunEnd;let{status:S,duration:R,summary:w,reason:k,context:L}=H.lastRunEnd,{passed:G,failed:q,total:z}=Rn(H.steps);Rr.current+=z,Ar.current+=R??0,ne({status:S,duration:R??0,summary:w??"",stepsPassed:G,stepsFailed:q,stepsTotal:z,reason:k,finalState:H.lastRunEnd?.final_state,creditsConsumed:H.lastRunEnd?.credits_consumed}),i.logRunEnd(et.current,S,R,w);let Y=H.bifurcationInfo,fe=Y&&!Y.isSingleFlow?Y.flows:null,we=xn(H.lastRunEnd,et.current,fe),fn=wn(H.lastRunEnd,Et.current,et.current,we);i.addRunResult(fn,H.lastRunEnd?.total_runs);let Rt=H.lastRunEnd?.per_flow_metadata;if(Y&&!Y.isSingleFlow&&Rt&&Rt.length>1)for(let ft=0;ft<Rt.length;ft++){let Pe=Rt[ft],it=H.steps[ft],at=it?.children??[],gt=at.filter(mn=>mn.status==="passed").length,$n=at.filter(mn=>mn.status==="failed").length,Pr=at.reduce((mn,Ai)=>mn+(Ai.duration??0),0),Or=it?.status==="failed"?"failed":"passed",Dr=Y.flows[ft]??it?.objective??Et.current;i.addFlow({runIndex:et.current,flowId:Y.flows[ft],objective:Dr,status:Or,summary:Pe.summary??"",duration:Pr,steps:gt+$n,stepsPassed:gt,stepsFailed:$n,reason:Pe.error_message??void 0,creditsConsumed:Pe.credits_consumed??void 0})}else i.addFlow({runIndex:et.current,objective:Et.current,status:S,summary:w??"",duration:R??0,steps:z,stepsPassed:G,stepsFailed:q,reason:k,creditsConsumed:H.lastRunEnd?.credits_consumed})}},[H.lastRunEnd,i,le]);let Dn=(0,$.useRef)(null);(0,$.useEffect)(()=>{H.askingUser&&H.askingUser!==Dn.current&&(Dn.current=H.askingUser,ue((0,j.jsxs)(y,{children:[(0,j.jsx)(f,{color:"#ff9500",children:"? "}),(0,j.jsx)(f,{color:"#ff9500",children:"Agent asks: "}),(0,j.jsx)(f,{children:H.askingUser})]}))),H.askingUser||(Dn.current=null)},[H.askingUser,ue]);let Tr=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(Z&&!H.isRunning&&H.lastRunEnd){if(Tr.current===H.lastRunEnd)return;Tr.current=H.lastRunEnd,ue((0,j.jsxs)(y,{flexDirection:"column",children:[(0,j.jsx)(Ds,{status:Z.status,steps:Z.stepsTotal,duration:Z.duration,creditsConsumed:Z.creditsConsumed,reason:Z.reason}),(0,j.jsx)(js,{})]})),ne(null)}},[Z,H.isRunning,H.lastRunEnd,ue]),(0,$.useEffect)(()=>{M.current?.setRunActive(H.isRunning)},[H.isRunning]),(0,$.useEffect)(()=>{if(H.runError&&!H.isRunning){let S=H.runError.trim();i.log("error","RUNNER_ERROR","Runner error occurred",{error:S}),i.escalateRun(i.nextRunIndex()-1);let w=S.split(`
55
55
  `).slice(-8).join(`
56
- `);ue({type:"error",text:`Runner error:
57
- ${y}`})}},[M.runError,M.isRunning,ue,i]);let jn=(0,L.useCallback)(async()=>{i.log("info","EXIT_UPLOAD_START","Starting exit upload pipeline"),b(Bn()),w({status:"uploading"});let E=k.getResolvedBasicAuth(),A=null;if(!E&&(A=await k.getToken(),!A))return i.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no auth available"),null;let y=$??await Vt();if(!y)return i.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no TMS credentials"),i.setUploadStatus("failed","Could not get TMS credentials"),null;i.log("info","EXIT_UPLOAD_CONFIG","Exit upload configuration",{test_id:i.testId,commit_id:i.sessionId,project_id:H.project_id,session_dir:i.sessionDir,run_dirs:i.getRunDirs()});let I={basicAuth:E??null,token:A,resolver:k.getResolver(),resolvedCreds:y};Le.current&&(i.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot queue before pipeline"),await Le.current.drain(),i.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot queue drained"));let j=Tn({session:i,env:fe,auth:I,variables:U.current??{raw:{},auteur:{},auteurObjective:"",secretEntries:[],nonSecretEntries:[]},variableIds:oe.current,projectId:H.project_id,folderId:H.folder_id,totalSteps:Cr.current,totalDuration:Rr.current,codeExport:kn({codeExport:e,codeLanguage:t,skipCodeValidation:n},H.code_export),onProgress:(J,Y,de)=>{i.log("info","EXIT_PROGRESS","Upload progress",{step:J,status:Y,detail:de}),b(be=>qo(be,J,Y,de))},log:(J,Y,de,be)=>i.log(J,Y,de,be)}),G=await new Go(j).execute();if(G.success){i.log("info","EXIT_UPLOAD_OK","Exit upload succeeded",{test_id:G.testId,testcase_id:G.testcaseId??null,share_id:G.shareId??null}),i.setUploadStatus("uploaded"),G.testId&&i.setTestId(G.testId),G.testcaseId&&i.setTestcaseId(G.testcaseId);let J=ce(fe),Y=H.project_id,de=G.testcaseId&&G.shareId&&Y?Ht(J.testManagerUiUrl,Y,G.testcaseId,G.shareId):void 0,be=G.testcaseId&&Y?An(J.testManagerUiUrl,Y,G.testcaseId):void 0;w({status:"success",testUrl:de,testCaseLink:be,codeExportDir:G.codeExportDir}),Os({shareableLink:de,testCaseLink:be,codeExportDir:G.codeExportDir})}else i.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:G.error}),i.setUploadStatus("failed",G.error),w({status:"failed",error:G.error});return G},[k,fe,i,H,$,Vt]),jo=(0,L.useCallback)(async()=>{if(!(i.nextRunIndex()>0)){ue({type:"info",text:"No runs in current session."});return}if(M.isRunning){ue({type:"error",text:"Cannot reset while a run is in progress. Cancel the run first."});return}i.log("info","SESSION_RESET_START","Starting session reset via /new"),Te(!0);let A=i.getFlows();A.length>0&&ae((0,D.jsx)(uo,{flows:A}));let y=null;if(!s)try{y=await jn()??null}catch(j){i.log("error","SESSION_RESET_UPLOAD_FAILED","Upload failed during /new",{error:String(j)}),ue({type:"error",text:"Upload failed \u2014 session data saved locally."})}if(y?.success&&y.testcaseId){let j=ce(fe),K=H.project_id;ae((0,D.jsx)(Vr,{shareableLink:y.shareId&&K?Ht(j.testManagerUiUrl,K,y.testcaseId,y.shareId):void 0,testCaseLink:K?An(j.testManagerUiUrl,K,y.testcaseId):void 0,codeExportDir:y.codeExportDir,autoExit:!1}))}i.testId&&re(j=>[...j,{testId:i.testId,runCount:P}]),On.killChrome(),await i.finish("complete");let I=new xt;I.start({model:H.model,environment:fe,profile:Jt??null}),o.current=I,l(j=>j+1),i.log("info","SESSION_RESET_COMPLETE","Session reset complete",{new_session_id:I.sessionId}),R(0),Cr.current=0,Rr.current=0,rt.current=0,pt.current="",U.current=null,oe.current={},Le.current=null,Ln.current=0,kr.current=0,Dn.current=null,Ar.current=null,Er.current=null,Sr.current=null,ne(null),x(null),w(null),b(Bn()),Te(!1),ae((0,D.jsxs)(S,{flexDirection:"column",marginY:1,children:[(0,D.jsx)(f,{color:v.dimmed,children:"\u2500".repeat(44)}),(0,D.jsx)(f,{color:v.green,bold:!0,children:"New session started"})]}))},[i,M,ue,ae,s,jn,On,P,H,fe,Jt,a]),Lo=(0,L.useCallback)(async()=>{await i.finish("complete"),X(0,"Session complete")},[i]),Ei=(0,L.useCallback)(async E=>{Ce(!1);let A=i.testId??(q.length>0?q[q.length-1].testId:null);if(E&&A){i.log("info","EXIT_FEEDBACK_SUBMIT","Submitting session feedback",{choice:E});try{let y=ce(fe),I=k.getResolvedBasicAuth();I&&await gr({tmsBaseUrl:y.tmsBaseUrl,username:I.username,accessKey:I.access_key,testId:A,feedbackType:E,log:(j,K,G,J)=>i.log(j,K,G,J)})}catch(y){i.log("error","EXIT_FEEDBACK_FAILED","Feedback submission failed",{error:String(y)})}}else i.log("info","EXIT_FEEDBACK_SKIPPED","Feedback skipped");Lo()},[fe,k,i,Lo,q]),Ft=(0,L.useCallback)(async()=>{if(O)return;if(i.log("info","EXIT_START","TUI exit initiated"),i.nextRunIndex()>0&&!s){i.log("info","EXIT_WITH_ACTIVE_SESSION","Exit with active session \u2014 uploading first"),te(!0);try{await jn()}catch(y){i.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:String(y)})}i.testId&&re(y=>[...y,{testId:i.testId,runCount:P}]),await i.finish("complete")}if(!(i.testId??(q.length>0?q[q.length-1].testId:null))||s){await i.finish("complete"),X(0,"No test ID \u2014 quick exit");return}te(!0),Ce(!0)},[O,i,s,jn,P,q]);(0,L.useEffect)(()=>{if(!O)return;let E=300*1e3,A=setTimeout(async()=>{i.setUploadStatus("failed","Upload timed out after 5m"),await i.finish("complete"),X(0,"Upload timed out after 5m")},E);return()=>clearTimeout(A)},[O,i]);let Ln=L.default.useRef(0),Tr=L.default.useRef(null),kr=L.default.useRef(0);Oe((E,A)=>{if(A.ctrl&&E==="c"){if(O){kr.current+=1,kr.current>=2&&(i.setUploadStatus("pending","Force exit by user"),i.finish("complete"),X(0,"Force exit by user"));return}if(M.isRunning){M.cancelRun(),ue({type:"info",text:"Run cancelled."}),Ln.current++,Tr.current&&clearTimeout(Tr.current),Tr.current=setTimeout(()=>{Ln.current=0},2e3),Ln.current>=2&&Ft();return}Ft()}});let $o=L.default.useMemo(()=>{let E=k.creds.getActiveProfile()??"none",A=k.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:we.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:y=>{dn(I=>({...I,headless:y==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(we.maxSteps),onValue:y=>{let I=parseInt(y,10);I>0&&dn(j=>({...j,maxSteps:I}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:we.timeout?String(we.timeout):"",placeholder:"0 = no timeout",onValue:y=>{let I=parseInt(y,10);dn(j=>({...j,timeout:isNaN(I)?0:I}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:we.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:y=>{dn(I=>({...I,cdpEndpoint:y}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:we.wsEndpoint,placeholder:"wss://...",onValue:y=>{dn(I=>({...I,wsEndpoint:y}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{k.logout().then(y=>{ze();let I=k.creds.getActiveProfile(),j=k.creds.getDefaultEnv();Je(I,j),Rt().catch(()=>{}),ue(y?{type:"info",text:`Logged out: ${y.profile} [${y.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{ue({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let y=k.creds.getActiveProfile()??"none",I=k.creds.getDefaultEnv(),j=k.creds.loadBasicAuth(y,I),K=j?"basic":k.creds.loadCredentials(y,I)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:y},{key:"Environment",value:I}]},{label:"Authentication",entries:[{key:"Method",value:K},...j?[{key:"Username",value:j.username}]:[]]},{label:"Token",entries:[{key:"Status",value:k.tokenValid?"valid":"not logged in",color:k.tokenValid?v.statusPass:v.statusFail}]}]}}},{id:"balance",label:"Credit Balance",type:"action",suppressFeedback:!0,onAction:()=>{(async()=>{let y=k.creds.getActiveProfile()??"default",I=k.creds.getDefaultEnv(),j=ce(I);try{let K=k.getBasicAuth(),G=K?null:await k.getToken();if(!K&&!G){V({text:"Not authenticated. Run /login first.",color:v.red});return}let{ControllerClient:J}=await import("./controller-client-7BIK5FYL.js"),de=await(K?new J(j.controllerBaseUrl,{username:K.username,accessKey:K.access_key}):new J(j.controllerBaseUrl,G)).getCreditBalance();V({text:`Credits \u2014 available: ${de.available_credits}, total: ${de.total_credits} (${y} / ${I})`,color:v.green})}catch(K){V({text:`Balance check failed: ${K instanceof Error?K.message:String(K)}`,color:v.red})}F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{V(null),F.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"},{key:"Mode",value:H.mode}]},{label:"Browser",entries:[{key:"Window",value:`${H.window_size.width}x${H.window_size.height}`},{key:"Chrome Profile",value:H.chrome_profile_path?H.chrome_profile_path.split("/").pop()??H.chrome_profile_path:"(temporary)"}]},{label:"Project",entries:[{key:"Project",value:H.project_name?`${H.project_name} (${H.project_id})`:H.project_id??"(none)"},{key:"Folder",value:H.folder_name?`${H.folder_name} (${H.folder_id})`:H.folder_id??"(none)"},{key:"Default URL",value:ft}]},{label:"Code Export",entries:[{key:"Enabled",value:H.code_export.enabled?"yes":"no"},{key:"Skip Validation",value:H.code_export.skip_validation?"yes":"no"}]}]})},{id:"config-chrome",label:"Chrome Profile",type:"action",onChromeProfilePicker:()=>{}},{id:"config-project",label:"Project",type:"action",onProjectPicker:()=>{}},{id:"config-folder",label:"Folder",type:"action",...H.project_id?{onFolderPicker:()=>{}}:{onInfo:()=>({title:"Folder",sections:[{entries:[{key:"Status",value:"Select a project first",color:v.dim}]}]})}},{id:"config-window",label:"Window Size",type:"action",currentValue:`${H.window_size.width}x${H.window_size.height}`,onWindowSizePicker:()=>{}},{id:"config-mode",label:"Mode",type:"select",currentValue:H.mode,options:[{label:"testing",value:"testing"},{label:"action",value:"action"}],onValue:y=>{(y==="action"||y==="testing")&&(c.set("mode",y),Ze(c.load()))}},{id:"config-code-export",label:"Code Export",type:"submenu",currentValue:H.code_export.enabled?"enabled":"disabled",children:[{id:"config-code-export-enabled",label:"Enabled",type:"select",currentValue:H.code_export.enabled?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:y=>{c.set("code_export",{...H.code_export,enabled:y==="on"}),Ze(c.load())}},{id:"config-code-export-skip-validation",label:"Skip Validation",type:"select",currentValue:H.code_export.skip_validation?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:y=>{c.set("code_export",{...H.code_export,skip_validation:y==="on"}),Ze(c.load())}}]}]},{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:`${ct(Se,"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:ct(Se,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:ct(Se,"tui-config.json")},{key:"Auth",value:ct(Se,"config.json")},{key:"Sessions",value:`${ct(Se,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${ct(Se,"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:ct(Se,"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:"exit",label:"Exit",type:"action",onAction:()=>{Ft()}}]},[k,c,H,ue,Ft,we,ze]),Ci=(0,L.useCallback)(E=>{if(M.askingUser){ae((0,D.jsxs)(S,{children:[(0,D.jsx)(f,{color:"#888888",children:"\u2192 "}),(0,D.jsx)(f,{color:"#888888",children:"You answered: "}),(0,D.jsx)(f,{children:E})]})),M.sendAnswer(E);return}if(i.logCommand(E),M.isRunning){ue({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}let A=Is(E);if(A)switch(A.command){case"login":case"logout":case"whoami":case"profiles":case"balance":case"auth":un("auth");return;case"config":un("config");return;case"help":un("help");return;case"update":{(async()=>{let{getUpdateCommand:y}=await import("./version-check-NUVM7TOP.js");ue({type:"info",text:`To update kane-cli, run: ${y()}`})})();return}case"summary":{let y=i.getFlows();if(y.length===0){ue({type:"info",text:"No runs yet in this session."});return}let I=A.args.index?parseInt(A.args.index,10):void 0;if(I!==void 0&&!i.getFlow(I)){ue({type:"error",text:`No flow at index ${I}. ${y.length} flow${y.length===1?"":"s"} available. Use /summary to see all.`});return}ae((0,D.jsx)(uo,{flows:y,filterIndex:I}));return}case"new":jo();return;case"cancel":M.cancelRun(),ue({type:"info",text:"Run cancelled."});return;case"clear":return;case"exit":Ft();return;default:ue({type:"error",text:`Unknown command: /${A.command}`});return}if(E.trim().toLowerCase()==="exit"){Ft();return}ae((0,D.jsxs)(S,{children:[(0,D.jsx)(f,{color:"#b388ff",children:"\u276F "}),(0,D.jsx)(f,{children:E})]})),Do(E,ft)},[M,ue,ae,i,Do,Ft,jo]),Bo=k.getAuthInfo(),Ri=Bo?Bo.method==="basic"?"basic auth":"oauth":"not logged in";return(0,D.jsxs)(S,{flexDirection:"column",children:[Ge.length>0&&(0,D.jsx)(Xt,{items:Ge,children:E=>(0,D.jsx)(S,{paddingX:1,children:E.content},E.id)}),!g&&!ut&&(0,D.jsx)(ts,{onComplete:()=>{let E=k.creds.getActiveProfile(),A=k.creds.getDefaultEnv(),y=E?k.creds.loadCredentials(E,A):null,I=E?k.creds.loadBasicAuth(E,A):null,j=!!(y||I),K=I?.username??E??null;ae((0,D.jsx)(Un,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:Qt,authenticated:j,user:K})),wr(!0);let G=(J,Y,de,be)=>{i.log(J,Y,de,be)};sr(k.creds,G).then(J=>{if(J.status==="authenticated"){let{profile:Y,env:de,tmsCreds:be}=J.result;k.creds.setActiveProfile(Y),k.creds.setDefaultEnv(de),ze(),z(be),le("ready"),p(!0)}else J.status==="needs_pick"?(qe(J.profiles),le("pick")):le("login")}).catch(J=>{i.log("error","STARTUP_GATE_ERROR","Auth gate failed",{error:String(J)}),le("login")}),r&&r.then(async J=>{if(J){let{getUpdateCommand:Y}=await import("./version-check-NUVM7TOP.js");ue({type:"info",text:`Update available: ${J.current} \u2192 ${J.latest} \u2014 run \`${Y()}\` to update`})}}).catch(()=>{})}}),!g&&ge==="booting"&&ut&&(0,D.jsx)(S,{paddingX:1,children:(0,D.jsx)(f,{color:"yellow",children:"Checking authentication..."})}),!g&&ge==="pick"&&(0,D.jsx)(Ta,{profiles:Ie,onCancel:()=>le("login"),onSelect:async(E,A)=>{k.creds.setActiveProfile(E),k.creds.setDefaultEnv(A),ze(),Ct(!0);let y=(I,j,K,G)=>{i.log(I,j,K,G)};try{let I=await nn(k.creds,E,A,y);Ct(!1),I.status==="authenticated"?(Je(E,A),le("ready"),p(!0)):le("login")}catch{Ct(!1),le("login")}},validating:gt}),!g&&ge==="login"&&!W&&(0,D.jsx)(Zt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:k.creds.listProfiles(),onBasicLogin:(E,A,y,I)=>{k.creds.saveBasicAuth(E,A,{username:y,access_key:I}),k.creds.setActiveProfile(E),k.creds.setDefaultEnv(A),k.setTokenValid(!0),ze()},onOAuthLogin:async(E,A)=>{k.creds.setDefaultEnv(A),await k.login(E),ze()},onComplete:(E,A)=>{Rt(A).then(()=>{ze(),ye({phase:"project",profile:E,env:A})}).catch(()=>{ye({phase:"project",profile:E,env:A})})},onCancel:()=>{X(0,"Login cancelled at startup")}}),!g&&ge==="login"&&W?.phase==="project"&&(0,D.jsx)(It,{resolver:k.getResolver(),currentProjectId:null,env:W.env,onSelect:(E,A)=>{k.creds.saveProfileConfig(W.profile,W.env,{project_id:E,project_name:A}),ye({...W,phase:"folder"})},onCancel:()=>{Je(W.profile,W.env),ye(null),le("ready"),p(!0)}}),!g&&ge==="login"&&W?.phase==="folder"&&(0,D.jsx)(Pt,{resolver:k.getResolver(),projectId:k.creds.loadProfileConfig(W.profile,W.env)?.project_id??"",currentFolderId:null,env:W.env,onSelect:(E,A)=>{k.creds.saveProfileConfig(W.profile,W.env,{folder_id:E,folder_name:A}),Je(W.profile,W.env),ye(null),le("ready"),p(!0)},onCancel:async()=>{let E=k.creds.loadProfileConfig(W.profile,W.env);if(E?.project_id)try{let y=k.getResolver()?.cached;if(y){let I=ce(W.env),K=await new at(I.tmsBaseUrl,y.username,y.access_key).getDefaultFolder(E.project_id);K&&k.creds.saveProfileConfig(W.profile,W.env,{folder_id:K,folder_name:"Default"})}}catch{}Je(W.profile,W.env),ye(null),le("ready"),p(!0)}}),g&&zt==="menu"&&!O&&(0,D.jsx)(S,{marginBottom:1,children:(0,D.jsxs)(S,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,D.jsx)(f,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,D.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,D.jsx)(f,{color:"#ff9500",children:H.model}),(0,D.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,D.jsx)(f,{color:v.dimmed,children:Ri}),(0,D.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,D.jsxs)(f,{color:v.dimmed,children:[Jt??"no profile","/",fe]})]})}),g&&!O&&(0,D.jsxs)(S,{flexDirection:"column",flexGrow:1,children:[zt==="menu"&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(Xr,{items:$o,onRunSelected:()=>yr("chat"),renderLoginWizard:E=>{let A=W?.phase??"wizard";if(A==="project")return(0,D.jsx)(It,{resolver:k.getResolver(),currentProjectId:null,env:W.env,onSelect:(y,I)=>{k.creds.saveProfileConfig(W.profile,W.env,{project_id:y,project_name:I}),ye(j=>j?{...j,phase:"folder"}:null)},onCancel:()=>{Je(W.profile,W.env),ye(null),E()}});if(A==="folder"){let y=k.creds.loadProfileConfig(W.profile,W.env);return(0,D.jsx)(Pt,{resolver:k.getResolver(),projectId:y?.project_id??"",currentFolderId:null,env:W.env,onSelect:(I,j)=>{k.creds.saveProfileConfig(W.profile,W.env,{folder_id:I,folder_name:j}),Je(W.profile,W.env),ye(null),E()},onCancel:async()=>{let I=k.creds.loadProfileConfig(W.profile,W.env);if(I?.project_id)try{let K=k.getResolver()?.cached;if(K){let G=ce(W.env),Y=await new at(G.tmsBaseUrl,K.username,K.access_key).getDefaultFolder(I.project_id);Y&&k.creds.saveProfileConfig(W.profile,W.env,{folder_id:Y,folder_name:"Default"})}}catch{}Je(W.profile,W.env),ye(null),E()}})}return(0,D.jsx)(Zt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:k.creds.listProfiles(),onBasicLogin:(y,I,j,K)=>{k.creds.saveBasicAuth(y,I,{username:j,access_key:K}),k.creds.setActiveProfile(y),k.creds.setDefaultEnv(I),k.setTokenValid(!0),ze()},onOAuthLogin:async(y,I)=>{k.creds.setDefaultEnv(I),await k.login(y),ze()},onComplete:(y,I)=>{Rt(I).then(()=>{ye({phase:"project",profile:y,env:I})}).catch(()=>{ye({phase:"project",profile:y,env:I})})},onCancel:()=>{ye(null),E()}})},renderProfilesView:E=>(0,D.jsx)(Lr,{creds:k.creds,onSwitch:(A,y)=>{k.creds.setActiveProfile(A),k.creds.setDefaultEnv(y),Je(A,y),ze(),Rt(y).catch(()=>{}),ue({type:"info",text:`Switched to ${A} [${y}]`})},onCancel:E}),renderChromeProfilePicker:E=>(0,D.jsx)($r,{currentPath:H.chrome_profile_path,onSelect:A=>{c.set("chrome_profile_path",A),Ze(c.load())},onCancel:E}),renderProjectPicker:E=>(0,D.jsx)(It,{resolver:k.getResolver(),currentProjectId:H.project_id,env:fe,onSelect:(A,y)=>{c.save({project_id:A,project_name:y});let I=k.creds.getActiveProfile(),j=k.creds.getDefaultEnv();I&&k.creds.saveProfileConfig(I,j,{project_id:A,project_name:y}),Ze(c.load()),E()},onCancel:E}),renderFolderPicker:E=>(0,D.jsx)(Pt,{resolver:k.getResolver(),projectId:H.project_id??"",currentFolderId:H.folder_id,env:fe,onSelect:(A,y)=>{c.save({folder_id:A,folder_name:y});let I=k.creds.getActiveProfile(),j=k.creds.getDefaultEnv();I&&k.creds.saveProfileConfig(I,j,{folder_id:A,folder_name:y}),Ze(c.load()),E()},onCancel:E}),renderWindowSizePicker:E=>(0,D.jsx)(to,{currentWidth:H.window_size.width,currentHeight:H.window_size.height,onSelect:(A,y)=>{c.set("window_size",{width:A,height:y}),Ze(c.load()),E()},onCancel:E})}),ve&&(0,D.jsx)(S,{paddingX:1,marginTop:1,children:(0,D.jsx)(f,{color:ve.color,children:ve.text})})]}),zt==="chat"&&(0,D.jsxs)(D.Fragment,{children:[(()=>{let E=zn({isRunning:M.isRunning,bifurcationInfo:M.bifurcationInfo,steps:M.steps,cmInitCounts:M.cmInitCounts});return E?(0,D.jsx)(qn,{label:E.label,hasBifurcation:E.hasBifurcation}):null})(),M.isRunning&&M.steps.length>0&&(0,D.jsx)(Kn,{steps:M.steps,bifurcated:!!M.bifurcationInfo&&!M.bifurcationInfo.isSingleFlow,flows:M.bifurcationInfo?.flows,cmInitCounts:M.cmInitCounts,onStepCommit:ae},`run-${rt.current}`),Bt&&!M.isRunning&&(()=>{let E=$o.find(A=>A.id===Bt);return E?.children?(0,D.jsx)(Xr,{items:E.children,onRunSelected:()=>un(null),onDismiss:()=>un(null),renderLoginWizard:A=>{let y=W?.phase??"wizard";if(y==="project")return(0,D.jsx)(It,{resolver:k.getResolver(),currentProjectId:null,env:W.env,onSelect:(I,j)=>{k.creds.saveProfileConfig(W.profile,W.env,{project_id:I,project_name:j}),ye(K=>K?{...K,phase:"folder"}:null)},onCancel:()=>{Je(W.profile,W.env),ye(null),A()}});if(y==="folder"){let I=k.creds.loadProfileConfig(W.profile,W.env);return(0,D.jsx)(Pt,{resolver:k.getResolver(),projectId:I?.project_id??"",currentFolderId:null,env:W.env,onSelect:(j,K)=>{k.creds.saveProfileConfig(W.profile,W.env,{folder_id:j,folder_name:K}),Je(W.profile,W.env),ye(null),A()},onCancel:async()=>{let j=k.creds.loadProfileConfig(W.profile,W.env);if(j?.project_id)try{let G=k.getResolver()?.cached;if(G){let J=ce(W.env),de=await new at(J.tmsBaseUrl,G.username,G.access_key).getDefaultFolder(j.project_id);de&&k.creds.saveProfileConfig(W.profile,W.env,{folder_id:de,folder_name:"Default"})}}catch{}Je(W.profile,W.env),ye(null),A()}})}return(0,D.jsx)(Zt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:k.creds.listProfiles(),onBasicLogin:(I,j,K,G)=>{k.creds.saveBasicAuth(I,j,{username:K,access_key:G}),k.creds.setActiveProfile(I),k.creds.setDefaultEnv(j),k.setTokenValid(!0),ze()},onOAuthLogin:async(I,j)=>{k.creds.setDefaultEnv(j),await k.login(I),ze()},onComplete:(I,j)=>{Rt(j).then(()=>{ye({phase:"project",profile:I,env:j})}).catch(()=>{ye({phase:"project",profile:I,env:j})})},onCancel:()=>{ye(null),A()}})},renderProfilesView:A=>(0,D.jsx)(Lr,{creds:k.creds,onSwitch:(y,I)=>{k.creds.setActiveProfile(y),k.creds.setDefaultEnv(I),Je(y,I),ze(),Rt(I).catch(()=>{}),ue({type:"info",text:`Switched to ${y} [${I}]`}),A()},onCancel:A}),renderChromeProfilePicker:A=>(0,D.jsx)($r,{currentPath:H.chrome_profile_path,onSelect:y=>{c.save({chrome_profile_path:y}),Ze(c.load()),A()},onCancel:A}),renderProjectPicker:A=>(0,D.jsx)(It,{resolver:k.getResolver(),currentProjectId:H.project_id,env:fe,onSelect:(y,I)=>{c.save({project_id:y,project_name:I});let j=k.creds.getActiveProfile();j&&k.creds.saveProfileConfig(j,fe,{project_id:y,project_name:I}),Ze(c.load()),A()},onCancel:A}),renderFolderPicker:A=>(0,D.jsx)(Pt,{resolver:k.getResolver(),projectId:H.project_id??"",currentFolderId:H.folder_id,env:fe,onSelect:(y,I)=>{c.save({folder_id:y,folder_name:I});let j=k.creds.getActiveProfile();j&&k.creds.saveProfileConfig(j,fe,{folder_id:y,folder_name:I}),Ze(c.load()),A()},onCancel:A}),renderWindowSizePicker:A=>(0,D.jsx)(to,{currentWidth:H.window_size.width,currentHeight:H.window_size.height,onSelect:(y,I)=>{c.set("window_size",{width:y,height:I}),Ze(c.load()),A()},onCancel:A})},Bt):null})(),Bt&&ve&&(0,D.jsx)(S,{paddingX:1,marginTop:1,children:(0,D.jsx)(f,{color:ve.color,children:ve.text})}),!Bt&&(0,D.jsx)(Mn,{onSubmit:Ci,onEscape:void 0,history:xi,commands:Ps,placeholder:M.askingUser?"Type your answer...":M.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (/ = commands)"})]})]}),g&&O&&u&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(Br,{steps:h,status:u.status,testUrl:u.testUrl,error:u.error}),u.status==="success"&&(0,D.jsx)(Vr,{shareableLink:u.testUrl,testCaseLink:u.testCaseLink,codeExportDir:u.codeExportDir,autoExit:!1})]}),je&&(0,D.jsx)(zo,{onSubmit:Ei}),ee&&u&&(0,D.jsx)(Br,{steps:h,status:u.status,error:u.error}),g&&!O&&(0,D.jsx)(Yo,{profile:Jt,environment:fe,model:H.model,tokenValid:k.tokenValid,sessionId:i.sessionId,runCount:P,viewMode:zt})]})}function Ta({profiles:s,onSelect:e,onCancel:t,validating:n}){let[r,o]=(0,L.useState)(0);return Oe((a,l)=>{if(!n){if(l.escape){t();return}if(l.upArrow&&r>0&&o(i=>i-1),l.downArrow&&r<s.length-1&&o(i=>i+1),l.return){let i=s[r];e(i.profile,i.env)}}}),(0,D.jsxs)(S,{flexDirection:"column",paddingX:1,children:[(0,D.jsx)(f,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,D.jsx)(S,{marginTop:1,flexDirection:"column",children:s.map((a,l)=>(0,D.jsxs)(f,{children:[l===r?"\u276F ":" ",(0,D.jsx)(f,{color:l===r?"#ff9500":"white",bold:l===r,children:a.profile}),(0,D.jsxs)(f,{color:"gray",children:[" [",a.env,"]"]})]},`${a.profile}-${a.env}`))}),n&&(0,D.jsx)(S,{marginTop:1,children:(0,D.jsx)(f,{color:"yellow",children:"Validating credentials..."})}),!n&&(0,D.jsx)(S,{marginTop:1,children:(0,D.jsx)(f,{color:"gray",children:"Esc = new login"})})]})}var xe=N(Pe(),1);var he=N(Q(),1);function zs({resultRef:s}){let{exit:e}=Yt(),t=(0,xe.useRef)(new Ne),n=(0,xe.useRef)(new tt),r=(0,xe.useRef)(new xt),o=t.current,a=n.current,l=r.current,i=Fn(),[c,d]=(0,xe.useState)("gate"),[m,g]=(0,xe.useState)(null),[p,_]=(0,xe.useState)(null),[x,C]=(0,xe.useState)(null),[T,P]=(0,xe.useState)(null),R=(0,xe.useCallback)((V,F,u,w)=>l.log(V,F,u,w),[l]),O=(0,xe.useCallback)((V,F)=>{let u=V?o.loadProfileConfig(V,F):null;a.save({project_id:u?.project_id??null,project_name:u?.project_name??null,folder_id:u?.folder_id??null,folder_name:u?.folder_name??null})},[o,a]);Oe((V,F)=>{F.ctrl&&V==="c"&&X(0,"Ctrl+C exit")});let te=(0,xe.useRef)(!1);xe.default.useEffect(()=>{te.current||(te.current=!0,sr(o,R).then(V=>{g(V),V.status==="authenticated"?(O(V.result.profile,V.result.env),d("input")):V.status==="needs_pick"?d("pick"):(_(V.profile??null),C(V.env??null),d("login"))}).catch(V=>{P(`Auth check failed: ${V instanceof Error?V.message:String(V)}`)}))},[o,R]);let Z=(0,xe.useCallback)(V=>{s.current={objective:V},e()},[s,e]),ne=(0,xe.useCallback)(async(V,F)=>{o.setActiveProfile(V),o.setDefaultEnv(F),(await nn(o,V,F,R)).status==="authenticated"?(O(V,F),d("input")):(_(V),C(F),d("login"))},[o,R,O]),ve=(0,xe.useCallback)(()=>{let V=o.getActiveProfile(),F=o.getDefaultEnv();if(!V)return null;let u=ce(F),w=o.loadBasicAuth(V,F);return new mt(u.controllerBaseUrl,async()=>o.loadCredentials(V,F)?.access_token??null,w,R)},[o,R]);if(c==="gate")return(0,he.jsx)(S,{paddingX:1,children:(0,he.jsx)(f,{color:"yellow",children:"Checking authentication..."})});if(T)return(0,he.jsxs)(S,{flexDirection:"column",paddingX:1,children:[(0,he.jsx)(f,{color:"red",children:T}),(0,he.jsx)(f,{color:"gray",children:"Press Ctrl+C to exit."})]});if(c==="pick"&&m?.status==="needs_pick")return(0,he.jsx)(ka,{profiles:m.profiles,onSelect:ne});if(c==="login"||c==="login-project"||c==="login-folder"){if(c==="login-project")return(0,he.jsx)(It,{resolver:ve(),currentProjectId:null,env:x??"prod",onSelect:(V,F)=>{let u=p??o.getActiveProfile()??"default",w=x??o.getDefaultEnv();o.saveProfileConfig(u,w,{project_id:V,project_name:F}),d("login-folder")},onCancel:()=>{let V=p??o.getActiveProfile()??"default",F=x??o.getDefaultEnv();O(V,F),d("input")}});if(c==="login-folder"){let V=p??o.getActiveProfile()??"default",F=x??o.getDefaultEnv(),u=o.loadProfileConfig(V,F);return(0,he.jsx)(Pt,{resolver:ve(),projectId:u?.project_id??"",currentFolderId:null,env:F,onSelect:(w,h)=>{o.saveProfileConfig(V,F,{folder_id:w,folder_name:h}),O(V,F),d("input")},onCancel:async()=>{if(u?.project_id)try{let w=ce(F),h=o.loadBasicAuth(V,F);if(h){let $=await new at(w.tmsBaseUrl,h.username,h.access_key).getDefaultFolder(u.project_id);$&&o.saveProfileConfig(V,F,{folder_id:$,folder_name:"Default"})}}catch{}O(V,F),d("input")}})}return(0,he.jsx)(Zt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:(V,F,u,w)=>{o.saveBasicAuth(V,F,{username:u,access_key:w}),o.setActiveProfile(V),o.setDefaultEnv(F)},onOAuthLogin:async(V,F)=>{let{LoginFlow:u}=await import("./login-flow-J5AIWRWS.js");o.setDefaultEnv(F),o.setActiveProfile(V),await new u(V,F,o).login()},onComplete:(V,F)=>{_(V),C(F),o.setActiveProfile(V),o.setDefaultEnv(F),d("login-project")},onCancel:()=>{X(0,"Login cancelled")}})}return c==="input"?(0,he.jsx)(Mn,{onSubmit:Z,onEscape:()=>X(0,"User pressed Escape"),history:i,placeholder:"Type an objective..."}):(0,he.jsx)(he.Fragment,{})}function ka({profiles:s,onSelect:e}){let[t,n]=(0,xe.useState)(0),[r,o]=(0,xe.useState)(!1);return Oe((a,l)=>{if(!r){if(l.escape){X(0,"Profile picker cancelled");return}if(l.upArrow&&t>0&&n(i=>i-1),l.downArrow&&t<s.length-1&&n(i=>i+1),l.return){o(!0);let i=s[t];e(i.profile,i.env).catch(()=>o(!1))}}}),(0,he.jsxs)(S,{flexDirection:"column",paddingX:1,children:[(0,he.jsx)(f,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,he.jsx)(S,{marginTop:1,flexDirection:"column",children:s.map((a,l)=>(0,he.jsxs)(f,{children:[l===t?"\u276F ":" ",(0,he.jsx)(f,{color:l===t?"#ff9500":"white",bold:l===t,children:a.profile}),(0,he.jsxs)(f,{color:"gray",children:[" [",a.env,"]"]})]},`${a.profile}-${a.env}`))}),r&&(0,he.jsx)(S,{marginTop:1,children:(0,he.jsx)(f,{color:"yellow",children:"Validating credentials..."})})]})}var ai=N(ii(),1),{program:Mf,createCommand:Hf,createArgument:Wf,createOption:Kf,CommanderError:Gf,InvalidArgumentError:qf,InvalidOptionArgumentError:zf,Command:li,Argument:Jf,Option:an,Help:Xf}=ai.default;import{join as Gt}from"path";var pi=N(Pe(),1);var Ye=N(Pe(),1);var $t=N(Q(),1);function ci({steps:s,bifurcationInfo:e,perFlowMetadata:t}){return!e||e.isSingleFlow||!t||t.length<=1?null:(0,$t.jsx)(S,{flexDirection:"column",children:t.map((n,r)=>{let o=s[r],a=o?.children??[],l=a.filter(p=>p.status==="passed").length,i=a.filter(p=>p.status==="failed").length,c=l+i,d=a.reduce((p,_)=>p+(_.duration??0),0),m=o?.status==="failed"?"failed":"passed",g=e.flows[r]??o?.objective??`Flow ${r+1}`;return(0,$t.jsxs)(S,{flexDirection:"column",marginTop:r>0?1:0,children:[(0,$t.jsxs)(S,{marginLeft:1,children:[(0,$t.jsx)(f,{color:"#b388ff",bold:!0,children:"Flow "+(r+1)+": "}),(0,$t.jsx)(f,{color:"#b388ff",children:g})]}),(0,$t.jsx)(rn,{status:m,summary:n?.summary??"",duration:d,steps:c,stepsPassed:l,stepsFailed:i,reason:n?.error_message??void 0,creditsConsumed:n?.credits_consumed??void 0})]},`flow-summary-${r}`)})})}var Ke=N(Q(),1);function ui({message:s,code:e,remediation:t,docsUrl:n}){return(0,Ke.jsx)(Xo,{title:"Error",variant:"error",children:(0,Ke.jsxs)(S,{flexDirection:"column",paddingY:1,children:[(0,Ke.jsxs)(f,{color:v.red,bold:!0,children:[" \u2717 ",s]}),e&&(0,Ke.jsxs)(S,{marginTop:0,marginLeft:5,children:[(0,Ke.jsx)(f,{color:v.muted,children:"Code: "}),(0,Ke.jsx)(f,{color:v.dimmed,children:e})]}),t&&(0,Ke.jsxs)(S,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,Ke.jsx)(f,{color:v.green,bold:!0,children:"Fix:"}),(0,Ke.jsxs)(f,{color:v.cyan,children:["$ ",t]})]}),n&&(0,Ke.jsxs)(S,{marginTop:1,marginLeft:5,children:[(0,Ke.jsx)(f,{color:v.muted,children:"Docs: "}),(0,Ke.jsx)(f,{color:v.cyan,underline:!0,children:n})]})]})})}var Ee=N(Q(),1);function di({config:s,spawnOpts:e,cancelRef:t,banner:n,onComplete:r,onStepEnd:o}){let{exit:a}=Yt(),l=or(o),i=(0,Ye.useRef)(!1),c=(0,Ye.useRef)(!1),[d,m]=(0,Ye.useState)("");(0,Ye.useEffect)(()=>{i.current||(i.current=!0,l.startRun(s,e))},[s,e,l]),(0,Ye.useEffect)(()=>{t&&(t.current=()=>l.cancelRun())},[t,l]);let g=(0,Ye.useRef)(0);Oe((x,C)=>{C.ctrl&&x==="c"&&(l.isRunning?(g.current++,g.current>=2?a():l.cancelRun()):a())}),Oe((x,C)=>{l.askingUser&&(C.return?(l.sendAnswer(d),m("")):C.backspace||C.delete?m(T=>T.slice(0,-1)):x&&!C.ctrl&&!C.meta&&m(T=>T+x))},{isActive:!!l.askingUser}),(0,Ye.useEffect)(()=>{if(!l.isRunning&&l.lastRunEnd&&!c.current){c.current=!0;let{passed:x,failed:C,total:T}=Rn(l.steps),P=l.bifurcationInfo;r({lastRunEnd:l.lastRunEnd,stepsPassed:x,stepsFailed:C,stepsTotal:T,hadError:!1,bifurcationFlows:P&&!P.isSingleFlow?P.flows:null}),a()}},[l.isRunning,l.lastRunEnd,l.steps,r,a]),(0,Ye.useEffect)(()=>{l.runError&&!l.isRunning&&!c.current&&(c.current=!0,r({lastRunEnd:null,stepsPassed:0,stepsFailed:0,stepsTotal:0,hadError:!0,bifurcationFlows:null}),a())},[l.runError,l.isRunning,r,a]);let p=l.lastRunEnd?(()=>{let{passed:x,failed:C,total:T}=Rn(l.steps);return{status:l.lastRunEnd.status,duration:l.lastRunEnd.duration??0,summary:l.lastRunEnd.summary??"",stepsPassed:x,stepsFailed:C,stepsTotal:T,reason:l.lastRunEnd.reason,finalState:l.lastRunEnd.final_state,creditsConsumed:l.lastRunEnd.credits_consumed}})():null,_=(0,Ye.useMemo)(()=>n?[{key:"banner",...n}]:[],[n]);return(0,Ee.jsxs)(S,{flexDirection:"column",children:[(0,Ee.jsx)(Xt,{items:_,children:x=>(0,Ee.jsxs)(S,{flexDirection:"column",marginBottom:1,children:[(0,Ee.jsxs)(S,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,Ee.jsx)(f,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,Ee.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,Ee.jsx)(f,{color:v.cyan,children:x.model}),(0,Ee.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,Ee.jsx)(f,{color:v.dimmed,children:x.auth})]}),x.status?.map((C,T)=>(0,Ee.jsx)(f,{color:v.dimmed,children:C},T))]},x.key)}),(()=>{let x=zn({isRunning:l.isRunning,bifurcationInfo:l.bifurcationInfo,steps:l.steps,cmInitCounts:l.cmInitCounts});return x?(0,Ee.jsx)(qn,{label:x.label,hasBifurcation:x.hasBifurcation}):null})(),l.steps.length>0&&(0,Ee.jsx)(Kn,{steps:l.steps,bifurcated:!!l.bifurcationInfo&&!l.bifurcationInfo.isSingleFlow,flows:l.bifurcationInfo?.flows,cmInitCounts:l.cmInitCounts,staticSteps:!0}),l.askingUser&&(0,Ee.jsxs)(S,{flexDirection:"column",marginTop:1,children:[(0,Ee.jsxs)(f,{color:v.yellow,children:['Agent is asking: "',l.askingUser,'"']}),(0,Ee.jsxs)(f,{children:["> ",d,"\u2588"]})]}),l.runError&&(0,Ee.jsx)(ui,{message:l.runError,code:"RUNNER_ERROR"}),p&&l.lastRunEnd&&(0,Ee.jsx)(ci,{steps:l.steps,bifurcationInfo:l.bifurcationInfo,perFlowMetadata:l.lastRunEnd.per_flow_metadata??[]}),p&&(0,Ee.jsx)(rn,{status:p.status==="passed"?"passed":"failed",summary:p.summary??"",duration:p.duration,steps:p.stepsTotal,stepsPassed:p.stepsPassed,stepsFailed:p.stepsFailed,reason:p.reason,creditsConsumed:p.creditsConsumed})]})}import{createInterface as Ka}from"readline";function ln(s){process.stdout.write(JSON.stringify(s)+`
58
- `)}async function fi(s,e,t){let n=rr(s,e);Vn().then(m=>{m&&ln({type:"update_available",current:m.current,latest:m.latest,severity:m.severity})}).catch(()=>{});let r=Ka({input:process.stdin});r.on("line",m=>{try{let g=JSON.parse(m);g.type==="user_response"?n.sendUserResponse(g.answer??""):g.type==="cancel"&&n.sendCancel(g.reason??"")}catch{}});let o=null,a=!1,l=0,i=null,c=0,d=!1;for await(let m of n.events)switch(m.type){case"run_start":d&&c++;break;case"step_start":{let g=m;t?.onStepLog?.("STEP_START",`Step ${g.index} started`,{index:g.index,objective:g.objective,child_id:g.child_id});let p={step:g.index+1,status:"running",remark:g.objective??`Step ${g.index+1}`};g.child_id&&(p.child_id=g.child_id),ln(p);break}case"step_event":t?.onStepLog?.("STEP_EVENT",`Step ${m.index} ${m.event}`,{index:m.index,phase:m.event,action_type:m.action_type,detail:m.detail,child_id:m.child_id});break;case"step_end":{let g=m;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}),l++;let p={step:g.index+1,status:g.status==="passed"?"done":"failed",remark:g.summary??""};g.child_id&&(p.child_id=g.child_id),ln(p);let _=d?Math.max(0,c-1):0;t?.onStepEnd?.(g.index,_);break}case"bifurcation":{let g=m,p=g.flows??[],_=g.count??p.length;(g.is_single_flow??_<=1)||(i=p,d=!0,c=0),ln({type:"bifurcation",flows:p,count:_});break}case"ask_user":{let g=m;ln({type:"ask_user",question:g.question,step_index:g.step_index,...g.options?{options:g.options}:{}});break}case"run_end":{o=m;break}case"error":{a=!0,ln({type:"error",message:m.message});break}default:break}return r.close(),await n.exited,{lastRunEnd:o,stepsTotal:l,hadError:a,bifurcationFlows:i}}var Kt=class extends Error{constructor(t,n){super(t);this.code=n;this.name="AuthError"}};async function _r(s){let{creds:e,env:t,usernameFlag:n,accessKeyFlag:r,log:o}=s,a=null,l=null;if(n&&r)a={username:n,access_key:r},o("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:n});else{let p=e.resolveAuth();p?.method==="basic"&&(a={username:p.username,access_key:p.access_key},o("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:p.username}))}if(!a){let{credentials:p,profile:_}=e.getActiveCredentials();if(!p)throw new Kt("Not authenticated \u2014 no credentials found","not_authenticated");if(l=p.access_token,p.expires_at-Date.now()/1e3<300)try{let C=await Xn({creds:e,profile:_,env:t,credentials:p});C&&(l=C.accessToken,o("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(C){let T=C instanceof Error?C.message:String(C);throw o("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:T}),new Kt(`Token refresh failed: ${T}`,"refresh_failed")}}let i=ce(t),c=async()=>l,d=a?{username:a.username,access_key:a.access_key}:null,m=new mt(i.controllerBaseUrl,c,d,o),g=await m.resolve();return g&&!a&&(a={username:g.username,access_key:g.access_key},o("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:g.username})),{basicAuth:a,token:l,resolver:m,resolvedCreds:g}}import{mkdtempSync as Ga,rmSync as qa}from"fs";import{join as za}from"path";import{tmpdir as Ja}from"os";async function mi(s){if(s.cft)return{instance:null,tempDir:null};if(s.wsEndpoint)return{wsEndpoint:s.wsEndpoint,instance:null,tempDir:null};if(s.cdpEndpoint){let r=await fetch(`${s.cdpEndpoint}/json/version`);if(!r.ok)throw new Error(`CDP endpoint not reachable: ${s.cdpEndpoint} (${r.status})`);return{cdpEndpoint:s.cdpEndpoint,instance:null,tempDir:null}}let e,t=null;if(s.config.chrome_profile_path)e=s.config.chrome_profile_path.replace("~",process.env.HOME??"~");else{t=Ga(za(Ja(),"kane-clean-")),e=t;let r=t;Xe("tempDir",()=>{try{qa(r,{recursive:!0,force:!0})}catch{}})}let n=await tr({userDataDir:e,width:s.config.window_size.width,height:s.config.window_size.height,startUrl:s.startUrl,headless:s.headless});return{cdpEndpoint:n.cdpEndpoint,instance:n,tempDir:t}}function Pn(s){let e=new li;if(e.name("kane-cli").version(Qt),s[0]==="--help"||s[0]==="-h"||s[0]==="help"){(async()=>{let{HelpView:n}=await import("./HelpView-ZR5EXR7F.js"),{render:r}=await import("./build-JIKYOZUH.js"),o=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=r(o.default.createElement(n));await a(),X(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 an("--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 an("--model <name>","Model").default("v16-alpha").hideHelp()).option("--chrome-profile <path>","Chrome profile path").action(async n=>{let r=new Ne,o=new tt,a=n.env,l=n.profile;if(!process.stdin.isTTY||n.oauth||n.username){if(r.setDefaultEnv(a),n.oauth?(await new hn(l,a,r).login(),console.log(`Logged in as ${l} [${a}] via OAuth`)):n.username&&n.accessKey?(r.saveBasicAuth(l,a,{username:n.username,access_key:n.accessKey}),console.log(`Logged in as ${l} [${a}] via basic auth`)):(console.error("Provide --oauth, or --username and --access-key"),X(1,"Missing --oauth or credentials for login")),r.setActiveProfile(l),o.set("model",n.model),n.chromeProfile&&o.set("chrome_profile_path",n.chromeProfile),n.projectId)o.set("project_id",n.projectId),console.log(`Project set to ${n.projectId}`);else try{let T=await _r({creds:r,env:a,log:()=>{}});if(T.resolvedCreds){let{TmsClient:P}=await import("./tms-client-VH42IFUF.js"),te=(await new P(ce(a).tmsBaseUrl,T.resolvedCreds.username,T.resolvedCreds.access_key).listProjects()).find(Z=>Z.name.toLowerCase().includes("kaneai"));te&&(o.set("project_id",te.project_id),console.log(`Auto-selected project: ${te.name} (${te.project_id})`))}}catch(C){console.warn(`Could not auto-select project: ${C instanceof Error?C.message:C}`)}n.folderId&&(o.set("folder_id",n.folderId),console.log(`Folder set to ${n.folderId}`)),console.log("Setup complete.");return}let{LoginWizard:i}=await import("./LoginWizard-NJA5AAYO.js"),{ProjectPicker:c}=await import("./ProjectPicker-YZZUJDOQ.js"),{FolderPicker:d}=await import("./FolderPicker-BHEDYLKA.js"),{render:m}=await import("./build-JIKYOZUH.js"),g=await import("./react-QWOAB3TB.js"),p=!1;if(await new Promise(C=>{let{unmount:T}=m(g.default.createElement(i,{devMode:process.env.KANE_DEV_MODE==="1",profiles:r.listProfiles(),onBasicLogin:(P,R,O,te)=>{r.saveBasicAuth(P,R,{username:O,access_key:te}),r.setActiveProfile(P),r.setDefaultEnv(R),a=R,l=P},onOAuthLogin:async(P,R)=>{r.setDefaultEnv(R),await new hn(P,R,r).login(),a=R,l=P},onComplete:()=>{T(),C()},onCancel:()=>{p=!0,T(),C()}}))}),p)return;let _;try{_=(await _r({creds:r,env:a,log:()=>{}})).resolver}catch{console.log("Could not resolve credentials for project setup. Run: kane-cli login");return}if(!_.cached){console.log("Could not resolve credentials for project setup. Run: kane-cli login");return}let x=null;await new Promise(C=>{let{unmount:T}=m(g.default.createElement(c,{resolver:_,currentProjectId:o.load().project_id,env:a,onSelect:(P,R)=>{o.set("project_id",P),o.set("project_name",R),x=P,console.log(`Project set to ${R} (${P})`),T(),C()},onCancel:()=>{T(),C()}}))}),x&&(await new Promise(C=>{let{unmount:T}=m(g.default.createElement(d,{resolver:_,projectId:x,currentFolderId:o.load().folder_id,env:a,onSelect:(P,R)=>{o.set("folder_id",P),o.set("folder_name",R),console.log(`Folder set to ${R} (${P})`),T(),C()},onCancel:()=>{T(),C()}}))}),X(0,"Login setup complete"))}),e.command("logout").action(async()=>{let n=new Ne,r=n.getActiveProfile();if(!r){console.log("No active profile to logout");return}let o=n.getDefaultEnv(),a=await Yn(n,r,o);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 Ne,o=n.profile??r.getActiveProfile()??"default",a=r.getDefaultEnv(),l=r.loadCredentials(o,a),i=r.loadBasicAuth(o,a),c="none",d,m,g;if(i)c="basic",d=i.username;else if(l){c="oauth";let T=l.expires_at,P=Date.now()/1e3;m=T>P?"valid":"expired",g=new Date(T*1e3).toISOString().slice(0,10)}else m="missing";let{WhoamiView:p}=await import("./WhoamiView-AXPRRGNG.js"),{render:_}=await import("./build-JIKYOZUH.js"),x=await import("./react-QWOAB3TB.js"),{waitUntilExit:C}=_(x.default.createElement(p,{profile:o,env:a,authenticated:c!=="none",authMethod:c,username:d,tokenStatus:m,expiresAt:g}));await C()}),e.command("config <action> [value]").action(async(n,r)=>{let o=new tt,a=new Ne;if(n==="show"){let l=o.load(),i=a.getActiveProfile()??"default",c=a.getDefaultEnv(),d=a.loadBasicAuth(i,c),m=a.loadCredentials(i,c),g=d?`basic (${d.username})`:m?"oauth":"not configured",{ConfigView:p}=await import("./ConfigView-53QUJ3UT.js"),{render:_}=await import("./build-JIKYOZUH.js"),x=await import("./react-QWOAB3TB.js"),{waitUntilExit:C}=_(x.default.createElement(p,{model:l.model,mode:l.mode,authLabel:g,profile:i,env:c,defaultUrl:ft,projectId:l.project_id,projectName:l.project_name,folderId:l.folder_id,windowSize:`${l.window_size.width}x${l.window_size.height}`,chromeProfile:l.chrome_profile_path}));await C()}else if(n==="set-window"&&r){let l=r.split("x").map(Number),[i,c]=l;!i||!c||!Number.isInteger(i)||!Number.isInteger(c)?console.error("Invalid format. Use: kane-cli config set-window WIDTHxHEIGHT"):i<800||i>3840?console.error(`Width must be between 800 and 3840 (got ${i})`):c<600||c>2160?console.error(`Height must be between 600 and 2160 (got ${c})`):(o.set("window_size",{width:i,height:c}),console.log(`Window size set to ${i}x${c}`))}else if(n==="set-mode"){if(r!=="action"&&r!=="testing"){console.error("Mode must be 'action' or 'testing'."),X(1,"Invalid mode");return}o.set("mode",r),console.log(`Mode set to ${r}`)}else if(n==="chrome-profile"){if(r||!process.stdin.isTTY){r||(console.error("Usage: kane-cli config chrome-profile <path>"),X(1,"Missing chrome-profile path")),o.set("chrome_profile_path",r),console.log(`Chrome profile set to ${r}`);return}let{ChromeProfilePicker:l}=await import("./ChromeProfilePicker-ZDIWVMLR.js"),{render:i}=await import("./build-JIKYOZUH.js"),c=await import("./react-QWOAB3TB.js");await new Promise(d=>{let{unmount:m}=i(c.default.createElement(l,{currentPath:o.load().chrome_profile_path,onSelect:g=>{o.set("chrome_profile_path",g),console.log(`Chrome profile set to ${g}`),m(),d()},onCancel:()=>{m(),d()}}))})}else if(n==="project"){if(r||!process.stdin.isTTY){r||(console.error("Usage: kane-cli config project <project-id>"),X(1,"Missing project ID")),o.set("project_id",r),console.log(`Project set to ${r}`);return}let l=a.getDefaultEnv(),i=ce(l),c=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!c){console.log("Login first to browse projects");return}let{ProjectPicker:d}=await import("./ProjectPicker-YZZUJDOQ.js"),{AuthResolver:m}=await import("./resolver-QLDOAIXU.js"),{render:g}=await import("./build-JIKYOZUH.js"),p=await import("./react-QWOAB3TB.js"),_=new m(i.controllerBaseUrl,async()=>null,c);await _.resolve(),await new Promise(x=>{let{unmount:C}=g(p.default.createElement(d,{resolver:_,currentProjectId:o.load().project_id,env:l,onSelect:(T,P)=>{o.set("project_id",T),o.set("project_name",P),console.log(`Project set to ${P} (${T})`),C(),x()},onCancel:()=>{C(),x()}}))})}else if(n==="folder"){if(r||!process.stdin.isTTY){if(r||(console.error("Usage: kane-cli config folder <folder-id>"),X(1,"Missing folder ID")),!o.load().project_id){console.log("Select a project first: kane-cli config project <id>");return}o.set("folder_id",r),console.log(`Folder set to ${r}`);return}let l=o.load();if(!l.project_id){console.log("Select a project first: kane-cli config project");return}let i=a.getDefaultEnv(),c=ce(i),d=a.loadBasicAuth(a.getActiveProfile()??"default",i);if(!d){console.log("Login first to browse folders");return}let{FolderPicker:m}=await import("./FolderPicker-BHEDYLKA.js"),{AuthResolver:g}=await import("./resolver-QLDOAIXU.js"),{render:p}=await import("./build-JIKYOZUH.js"),_=await import("./react-QWOAB3TB.js"),x=new g(c.controllerBaseUrl,async()=>null,d);await x.resolve(),await new Promise(C=>{let{unmount:T}=p(_.default.createElement(m,{resolver:x,projectId:l.project_id,currentFolderId:l.folder_id,env:i,onSelect:(P,R)=>{o.set("folder_id",P),o.set("folder_name",R),console.log(`Folder set to ${R} (${P})`),T(),C()},onCancel:()=>{T(),C()}}))})}else console.log("Usage: kane-cli config show|set-window|set-mode|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: ${Gt(Se,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new an("--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 an("--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("--mode <name>","Run mode: 'action' (strict \u2014 hard-stop on auth/blocked/error) or 'testing' (lenient \u2014 fall through). Overrides config; default: testing.").option("--agent","Agent mode: plain NDJSON output, no colors/UI").option("--task-skills","Enable domain-specific task skills (experimental)").addOption(new an("--local","Skip TMS integration (no uploads, no variables/secrets push)").hideHelp()).option("--code-export","Generate code export after upload").option("--code-language <lang>","Code export language: python (only python supported for now)").option("--skip-code-validation","Skip post-codegen worker-side validation").option("--no-skip-code-validation","Force post-codegen worker-side validation").addHelpText("after",`
56
+ `);le({type:"error",text:`Runner error:
57
+ ${w}`})}},[H.runError,H.isRunning,le,i]);let jn=(0,$.useCallback)(async()=>{i.log("info","EXIT_UPLOAD_START","Starting exit upload pipeline"),I(Bn()),x({status:"uploading"});let S=T.getResolvedBasicAuth(),R=null;if(!S&&(R=await T.getToken(),!R))return i.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no auth available"),null;let w=B??await Nt();if(!w)return i.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no TMS credentials"),i.setUploadStatus("failed","Could not get TMS credentials"),null;i.log("info","EXIT_UPLOAD_CONFIG","Exit upload configuration",{test_id:i.testId,commit_id:i.sessionId,project_id:W.project_id,session_dir:i.sessionDir,run_dirs:i.getRunDirs()});let k={basicAuth:S??null,token:R,resolver:T.getResolver(),resolvedCreds:w};$e.current&&(i.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot queue before pipeline"),await $e.current.drain(),i.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot queue drained"));let L=Tn({session:i,env:pe,auth:k,variables:$t.current??{raw:{},auteur:{},auteurObjective:"",secretEntries:[],nonSecretEntries:[]},variableIds:Bt.current,projectId:W.project_id,folderId:W.folder_id,totalSteps:Rr.current,totalDuration:Ar.current,codeExport:kn({codeExport:e,codeLanguage:t,skipCodeValidation:n},W.code_export),onProgress:(z,Y,fe)=>{i.log("info","EXIT_PROGRESS","Upload progress",{step:z,status:Y,detail:fe}),I(we=>zo(we,z,Y,fe))},log:(z,Y,fe,we)=>i.log(z,Y,fe,we)}),q=await new qo(L).execute();if(q.success){i.log("info","EXIT_UPLOAD_OK","Exit upload succeeded",{test_id:q.testId,testcase_id:q.testcaseId??null,share_id:q.shareId??null}),i.setUploadStatus("uploaded"),q.testId&&i.setTestId(q.testId),q.testcaseId&&i.setTestcaseId(q.testcaseId);let z=ae(pe),Y=W.project_id,fe=q.testcaseId&&q.shareId&&Y?Kt(z.testManagerUiUrl,Y,q.testcaseId,q.shareId):void 0,we=q.testcaseId&&Y?An(z.testManagerUiUrl,Y,q.testcaseId):void 0;x({status:"success",testUrl:fe,testCaseLink:we,codeExportDir:q.codeExportDir}),Os({shareableLink:fe,testCaseLink:we,codeExportDir:q.codeExportDir})}else i.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:q.error}),i.setUploadStatus("failed",q.error),x({status:"failed",error:q.error});return q},[T,pe,i,W,B,Nt]),Lo=(0,$.useCallback)(async()=>{if(!(i.nextRunIndex()>0)){le({type:"info",text:"No runs in current session."});return}if(H.isRunning){le({type:"error",text:"Cannot reset while a run is in progress. Cancel the run first."});return}i.log("info","SESSION_RESET_START","Starting session reset via /new"),Ie(!0);let R=i.getFlows();R.length>0&&ue((0,j.jsx)(fo,{flows:R}));let w=null;if(!s)try{w=await jn()??null}catch(L){i.log("error","SESSION_RESET_UPLOAD_FAILED","Upload failed during /new",{error:String(L)}),le({type:"error",text:"Upload failed \u2014 session data saved locally."})}if(w?.success&&w.testcaseId){let L=ae(pe),G=W.project_id;ue((0,j.jsx)(Fr,{shareableLink:w.shareId&&G?Kt(L.testManagerUiUrl,G,w.testcaseId,w.shareId):void 0,testCaseLink:G?An(L.testManagerUiUrl,G,w.testcaseId):void 0,codeExportDir:w.codeExportDir,autoExit:!1}))}i.testId&&re(L=>[...L,{testId:i.testId,runCount:P}]),On.killChrome(),await i.finish("complete");let k=new bt;k.start({model:W.model,environment:pe,profile:Yt??null}),o.current=k,l(L=>L+1),i.log("info","SESSION_RESET_COMPLETE","Session reset complete",{new_session_id:k.sessionId}),C(0),Rr.current=0,Ar.current=0,et.current=0,Et.current="",$t.current=null,Bt.current={},$e.current=null,Ln.current=0,Ir.current=0,Dn.current=null,Tr.current=null,Cr.current=null,Er.current=null,ne(null),b(null),x(null),I(Bn()),Ie(!1),ue((0,j.jsxs)(y,{flexDirection:"column",marginY:1,children:[(0,j.jsx)(f,{color:v.dimmed,children:"\u2500".repeat(44)}),(0,j.jsx)(f,{color:v.green,bold:!0,children:"New session started"})]}))},[i,H,le,ue,s,jn,On,P,W,pe,Yt,a]),$o=(0,$.useCallback)(async()=>{await i.finish("complete"),X(0,"Session complete")},[i]),Ei=(0,$.useCallback)(async S=>{Re(!1);let R=i.testId??(J.length>0?J[J.length-1].testId:null);if(S&&R){i.log("info","EXIT_FEEDBACK_SUBMIT","Submitting session feedback",{choice:S});try{let w=ae(pe),k=T.getResolvedBasicAuth();k&&await hr({tmsBaseUrl:w.tmsBaseUrl,username:k.username,accessKey:k.access_key,testId:R,feedbackType:S,log:(L,G,q,z)=>i.log(L,G,q,z)})}catch(w){i.log("error","EXIT_FEEDBACK_FAILED","Feedback submission failed",{error:String(w)})}}else i.log("info","EXIT_FEEDBACK_SKIPPED","Feedback skipped");$o()},[pe,T,i,$o,J]),Ut=(0,$.useCallback)(async()=>{if(O)return;if(i.log("info","EXIT_START","TUI exit initiated"),i.nextRunIndex()>0&&!s){i.log("info","EXIT_WITH_ACTIVE_SESSION","Exit with active session \u2014 uploading first"),te(!0);try{await jn()}catch(w){i.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:String(w)})}i.testId&&re(w=>[...w,{testId:i.testId,runCount:P}]),await i.finish("complete")}if(!(i.testId??(J.length>0?J[J.length-1].testId:null))||s){await i.finish("complete"),X(0,"No test ID \u2014 quick exit");return}te(!0),Re(!0)},[O,i,s,jn,P,J]);(0,$.useEffect)(()=>{if(!O)return;let S=300*1e3,R=setTimeout(async()=>{i.setUploadStatus("failed","Upload timed out after 5m"),await i.finish("complete"),X(0,"Upload timed out after 5m")},S);return()=>clearTimeout(R)},[O,i]);let Ln=$.default.useRef(0),kr=$.default.useRef(null),Ir=$.default.useRef(0);je((S,R)=>{if(R.ctrl&&S==="c"){if(O){Ir.current+=1,Ir.current>=2&&(i.setUploadStatus("pending","Force exit by user"),i.finish("complete"),X(0,"Force exit by user"));return}if(H.isRunning){H.cancelRun(),le({type:"info",text:"Run cancelled."}),Ln.current++,kr.current&&clearTimeout(kr.current),kr.current=setTimeout(()=>{Ln.current=0},2e3),Ln.current>=2&&Ut();return}Ut()}});let Bo=$.default.useMemo(()=>{let S=T.creds.getActiveProfile()??"none",R=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:be.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:w=>{dn(k=>({...k,headless:w==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(be.maxSteps),onValue:w=>{let k=parseInt(w,10);k>0&&dn(L=>({...L,maxSteps:k}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:be.timeout?String(be.timeout):"",placeholder:"0 = no timeout",onValue:w=>{let k=parseInt(w,10);dn(L=>({...L,timeout:isNaN(k)?0:k}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:be.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:w=>{dn(k=>({...k,cdpEndpoint:w}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:be.wsEndpoint,placeholder:"wss://...",onValue:w=>{dn(k=>({...k,wsEndpoint:w}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{T.logout().then(w=>{Xe();let k=T.creds.getActiveProfile(),L=T.creds.getDefaultEnv();Ye(k,L),Ct().catch(()=>{}),le(w?{type:"info",text:`Logged out: ${w.profile} [${w.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{le({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let w=T.creds.getActiveProfile()??"none",k=T.creds.getDefaultEnv(),L=T.creds.loadBasicAuth(w,k),G=L?"basic":T.creds.loadCredentials(w,k)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:w},{key:"Environment",value:k}]},{label:"Authentication",entries:[{key:"Method",value:G},...L?[{key:"Username",value:L.username}]:[]]},{label:"Token",entries:[{key:"Status",value:T.tokenValid?"valid":"not logged in",color:T.tokenValid?v.statusPass:v.statusFail}]}]}}},{id:"balance",label:"Credit Balance",type:"action",suppressFeedback:!0,onAction:()=>{(async()=>{let w=T.creds.getActiveProfile()??"default",k=T.creds.getDefaultEnv(),L=ae(k);try{let G=T.getBasicAuth(),q=G?null:await T.getToken();if(!G&&!q){F({text:"Not authenticated. Run /login first.",color:v.red});return}let{ControllerClient:z}=await import("./controller-client-7BIK5FYL.js"),fe=await(G?new z(L.controllerBaseUrl,{username:G.username,accessKey:G.access_key}):new z(L.controllerBaseUrl,q)).getCreditBalance();F({text:`Credits \u2014 available: ${fe.available_credits}, total: ${fe.total_credits} (${w} / ${k})`,color:v.green})}catch(G){F({text:`Balance check failed: ${G instanceof Error?G.message:String(G)}`,color:v.red})}N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{F(null),N.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"},{key:"Mode",value:W.mode}]},{label:"Browser",entries:[{key:"Window",value:`${W.window_size.width}x${W.window_size.height}`},{key:"Chrome Profile",value:W.chrome_profile_path?W.chrome_profile_path.split("/").pop()??W.chrome_profile_path:"(temporary)"}]},{label:"Project",entries:[{key:"Project",value:W.project_name?`${W.project_name} (${W.project_id})`:W.project_id??"(none)"},{key:"Folder",value:W.folder_name?`${W.folder_name} (${W.folder_id})`:W.folder_id??"(none)"},{key:"Default URL",value:mt}]},{label:"Code Export",entries:[{key:"Enabled",value:W.code_export.enabled?"yes":"no"},{key:"Skip Validation",value:W.code_export.skip_validation?"yes":"no"}]}]})},{id:"config-chrome",label:"Chrome Profile",type:"action",onChromeProfilePicker:()=>{}},{id:"config-project",label:"Project",type:"action",onProjectPicker:()=>{}},{id:"config-folder",label:"Folder",type:"action",...W.project_id?{onFolderPicker:()=>{}}:{onInfo:()=>({title:"Folder",sections:[{entries:[{key:"Status",value:"Select a project first",color:v.dim}]}]})}},{id:"config-window",label:"Window Size",type:"action",currentValue:`${W.window_size.width}x${W.window_size.height}`,onWindowSizePicker:()=>{}},{id:"config-mode",label:"Mode",type:"select",currentValue:W.mode,options:[{label:"testing",value:"testing"},{label:"action",value:"action"}],onValue:w=>{(w==="action"||w==="testing")&&(c.set("mode",w),nt(c.load()))}},{id:"config-code-export",label:"Code Export",type:"submenu",currentValue:W.code_export.enabled?"enabled":"disabled",children:[{id:"config-code-export-enabled",label:"Enabled",type:"select",currentValue:W.code_export.enabled?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:w=>{c.set("code_export",{...W.code_export,enabled:w==="on"}),nt(c.load())}},{id:"config-code-export-skip-validation",label:"Skip Validation",type:"select",currentValue:W.code_export.skip_validation?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:w=>{c.set("code_export",{...W.code_export,skip_validation:w==="on"}),nt(c.load())}}]}]},{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:`${ut(Ee,"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:ut(Ee,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:ut(Ee,"tui-config.json")},{key:"Auth",value:ut(Ee,"config.json")},{key:"Sessions",value:`${ut(Ee,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${ut(Ee,"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:ut(Ee,"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:"exit",label:"Exit",type:"action",onAction:()=>{Ut()}}]},[T,c,W,le,Ut,be,Xe]),Ci=(0,$.useCallback)(S=>{if(H.askingUser){ue((0,j.jsxs)(y,{children:[(0,j.jsx)(f,{color:"#888888",children:"\u2192 "}),(0,j.jsx)(f,{color:"#888888",children:"You answered: "}),(0,j.jsx)(f,{children:S})]})),H.sendAnswer(S);return}if(i.logCommand(S),H.isRunning){le({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}let R=Is(S);if(R)switch(R.command){case"login":case"logout":case"whoami":case"profiles":case"balance":case"auth":Ft("auth");return;case"config":Ft("config");return;case"help":Ft("help");return;case"update":{(async()=>{let{getUpdateCommand:w}=await import("./version-check-AGBPWJQA.js");le({type:"info",text:`To update kane-cli, run: ${w()}`})})();return}case"summary":{let w=i.getFlows();if(w.length===0){le({type:"info",text:"No runs yet in this session."});return}let k=R.args.index?parseInt(R.args.index,10):void 0;if(k!==void 0&&!i.getFlow(k)){le({type:"error",text:`No flow at index ${k}. ${w.length} flow${w.length===1?"":"s"} available. Use /summary to see all.`});return}ue((0,j.jsx)(fo,{flows:w,filterIndex:k}));return}case"new":Lo();return;case"cancel":H.cancelRun(),le({type:"info",text:"Run cancelled."});return;case"clear":return;case"exit":Ut();return;default:le({type:"error",text:`Unknown command: /${R.command}`});return}if(S.trim().toLowerCase()==="exit"){Ut();return}ue((0,j.jsxs)(y,{children:[(0,j.jsx)(f,{color:"#b388ff",children:"\u276F "}),(0,j.jsx)(f,{children:S})]})),jo(S,mt)},[H,le,ue,i,jo,Ut,Lo]),Vo=T.getAuthInfo(),Ri=Vo?Vo.method==="basic"?"basic auth":"oauth":"not logged in";return(0,j.jsxs)(y,{flexDirection:"column",children:[oe.length>0&&(0,j.jsx)(Qt,{items:oe,children:S=>(0,j.jsx)(y,{paddingX:1,children:S.content},S.id)}),!g&&!dt&&(0,j.jsx)(ns,{onComplete:()=>{let S=T.creds.getActiveProfile(),R=T.creds.getDefaultEnv(),w=S?T.creds.loadCredentials(S,R):null,k=S?T.creds.loadBasicAuth(S,R):null,L=!!(w||k),G=k?.username??S??null;ue((0,j.jsx)(Un,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:en,authenticated:L,user:G})),Xt(!0);let q=(z,Y,fe,we)=>{i.log(z,Y,fe,we)};ir(T.creds,q).then(z=>{if(z.status==="authenticated"){let{profile:Y,env:fe,tmsCreds:we}=z.result;T.creds.setActiveProfile(Y),T.creds.setDefaultEnv(fe),Xe(),D(we),ce("ready"),p(!0)}else z.status==="needs_pick"?(de(z.profiles),ce("pick")):ce("login")}).catch(z=>{i.log("error","STARTUP_GATE_ERROR","Auth gate failed",{error:String(z)}),ce("login")}),r&&r.then(async z=>{if(z){let{getUpdateCommand:Y}=await import("./version-check-AGBPWJQA.js");le({type:"info",text:`Update available: ${z.current} \u2192 ${z.latest} \u2014 run \`${Y()}\` to update`})}}).catch(()=>{})}}),!g&&Ue==="booting"&&dt&&(0,j.jsx)(y,{paddingX:1,children:(0,j.jsx)(f,{color:"yellow",children:"Checking authentication..."})}),!g&&Ue==="pick"&&(0,j.jsx)(Ta,{profiles:Ae,onCancel:()=>ce("login"),onSelect:async(S,R)=>{T.creds.setActiveProfile(S),T.creds.setDefaultEnv(R),Xe(),Me(!0);let w=(k,L,G,q)=>{i.log(k,L,G,q)};try{let k=await on(T.creds,S,R,w);Me(!1),k.status==="authenticated"?(Ye(S,R),ce("ready"),p(!0)):ce("login")}catch{Me(!1),ce("login")}},validating:Oe}),!g&&Ue==="login"&&!K&&(0,j.jsx)(tn,{devMode:process.env.KANE_DEV_MODE==="1",profiles:T.creds.listProfiles(),onBasicLogin:(S,R,w,k)=>{T.creds.saveBasicAuth(S,R,{username:w,access_key:k}),T.creds.setActiveProfile(S),T.creds.setDefaultEnv(R),T.setTokenValid(!0),Xe()},onOAuthLogin:async(S,R)=>{T.creds.setDefaultEnv(R),await T.login(S),Xe()},onComplete:(S,R)=>{Ct(R).then(()=>{Xe(),Se({phase:"project",profile:S,env:R})}).catch(()=>{Se({phase:"project",profile:S,env:R})})},onCancel:()=>{X(0,"Login cancelled at startup")}}),!g&&Ue==="login"&&K?.phase==="project"&&(0,j.jsx)(kt,{resolver:T.getResolver(),currentProjectId:null,env:K.env,onSelect:(S,R)=>{T.creds.saveProfileConfig(K.profile,K.env,{project_id:S,project_name:R}),Se({...K,phase:"folder"})},onCancel:()=>{Ye(K.profile,K.env),Se(null),ce("ready"),p(!0)}}),!g&&Ue==="login"&&K?.phase==="folder"&&(0,j.jsx)(It,{resolver:T.getResolver(),projectId:T.creds.loadProfileConfig(K.profile,K.env)?.project_id??"",currentFolderId:null,env:K.env,onSelect:(S,R)=>{T.creds.saveProfileConfig(K.profile,K.env,{folder_id:S,folder_name:R}),Ye(K.profile,K.env),Se(null),ce("ready"),p(!0)},onCancel:async()=>{let S=T.creds.loadProfileConfig(K.profile,K.env);if(S?.project_id)try{let w=T.getResolver()?.cached;if(w){let k=ae(K.env),G=await new lt(k.tmsBaseUrl,w.username,w.access_key).getDefaultFolder(S.project_id);G&&T.creds.saveProfileConfig(K.profile,K.env,{folder_id:G,folder_name:"Default"})}}catch{}Ye(K.profile,K.env),Se(null),ce("ready"),p(!0)}}),g&&tt==="menu"&&!O&&(0,j.jsx)(y,{marginBottom:1,children:(0,j.jsxs)(y,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,j.jsx)(f,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,j.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,j.jsx)(f,{color:"#ff9500",children:W.model}),(0,j.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,j.jsx)(f,{color:v.dimmed,children:Ri}),(0,j.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,j.jsxs)(f,{color:v.dimmed,children:[Yt??"no profile","/",pe]})]})}),g&&!O&&(0,j.jsxs)(y,{flexDirection:"column",flexGrow:1,children:[tt==="menu"&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(Yr,{items:Bo,onRunSelected:()=>Sr("chat"),renderLoginWizard:S=>{let R=K?.phase??"wizard";if(R==="project")return(0,j.jsx)(kt,{resolver:T.getResolver(),currentProjectId:null,env:K.env,onSelect:(w,k)=>{T.creds.saveProfileConfig(K.profile,K.env,{project_id:w,project_name:k}),Se(L=>L?{...L,phase:"folder"}:null)},onCancel:()=>{Ye(K.profile,K.env),Se(null),S()}});if(R==="folder"){let w=T.creds.loadProfileConfig(K.profile,K.env);return(0,j.jsx)(It,{resolver:T.getResolver(),projectId:w?.project_id??"",currentFolderId:null,env:K.env,onSelect:(k,L)=>{T.creds.saveProfileConfig(K.profile,K.env,{folder_id:k,folder_name:L}),Ye(K.profile,K.env),Se(null),S()},onCancel:async()=>{let k=T.creds.loadProfileConfig(K.profile,K.env);if(k?.project_id)try{let G=T.getResolver()?.cached;if(G){let q=ae(K.env),Y=await new lt(q.tmsBaseUrl,G.username,G.access_key).getDefaultFolder(k.project_id);Y&&T.creds.saveProfileConfig(K.profile,K.env,{folder_id:Y,folder_name:"Default"})}}catch{}Ye(K.profile,K.env),Se(null),S()}})}return(0,j.jsx)(tn,{devMode:process.env.KANE_DEV_MODE==="1",profiles:T.creds.listProfiles(),onBasicLogin:(w,k,L,G)=>{T.creds.saveBasicAuth(w,k,{username:L,access_key:G}),T.creds.setActiveProfile(w),T.creds.setDefaultEnv(k),T.setTokenValid(!0),Xe()},onOAuthLogin:async(w,k)=>{T.creds.setDefaultEnv(k),await T.login(w),Xe()},onComplete:(w,k)=>{Ct(k).then(()=>{Se({phase:"project",profile:w,env:k})}).catch(()=>{Se({phase:"project",profile:w,env:k})})},onCancel:()=>{Se(null),S()}})},renderProfilesView:S=>(0,j.jsx)($r,{creds:T.creds,onSwitch:(R,w)=>{T.creds.setActiveProfile(R),T.creds.setDefaultEnv(w),Ye(R,w),Xe(),Ct(w).catch(()=>{}),le({type:"info",text:`Switched to ${R} [${w}]`})},onCancel:S}),renderChromeProfilePicker:S=>(0,j.jsx)(Br,{currentPath:W.chrome_profile_path,onSelect:R=>{c.set("chrome_profile_path",R),nt(c.load())},onCancel:S}),renderProjectPicker:S=>(0,j.jsx)(kt,{resolver:T.getResolver(),currentProjectId:W.project_id,env:pe,onSelect:(R,w)=>{c.save({project_id:R,project_name:w});let k=T.creds.getActiveProfile(),L=T.creds.getDefaultEnv();k&&T.creds.saveProfileConfig(k,L,{project_id:R,project_name:w}),nt(c.load()),S()},onCancel:S}),renderFolderPicker:S=>(0,j.jsx)(It,{resolver:T.getResolver(),projectId:W.project_id??"",currentFolderId:W.folder_id,env:pe,onSelect:(R,w)=>{c.save({folder_id:R,folder_name:w});let k=T.creds.getActiveProfile(),L=T.creds.getDefaultEnv();k&&T.creds.saveProfileConfig(k,L,{folder_id:R,folder_name:w}),nt(c.load()),S()},onCancel:S}),renderWindowSizePicker:S=>(0,j.jsx)(no,{currentWidth:W.window_size.width,currentHeight:W.window_size.height,onSelect:(R,w)=>{c.set("window_size",{width:R,height:w}),nt(c.load()),S()},onCancel:S})}),_e&&(0,j.jsx)(y,{paddingX:1,marginTop:1,children:(0,j.jsx)(f,{color:_e.color,children:_e.text})})]}),tt==="chat"&&(0,j.jsxs)(j.Fragment,{children:[(()=>{let S=zn({isRunning:H.isRunning,bifurcationInfo:H.bifurcationInfo,steps:H.steps,cmInitCounts:H.cmInitCounts});return S?(0,j.jsx)(qn,{label:S.label,hasBifurcation:S.hasBifurcation}):null})(),H.isRunning&&H.steps.length>0&&(0,j.jsx)(Kn,{steps:H.steps,bifurcated:!!H.bifurcationInfo&&!H.bifurcationInfo.isSingleFlow,flows:H.bifurcationInfo?.flows,cmInitCounts:H.cmInitCounts,onStepCommit:ue},`run-${et.current}`),Vt&&!H.isRunning&&(()=>{let S=Bo.find(R=>R.id===Vt);return S?.children?(0,j.jsx)(Yr,{items:S.children,onRunSelected:()=>Ft(null),onDismiss:()=>Ft(null),renderLoginWizard:R=>{let w=K?.phase??"wizard";if(w==="project")return(0,j.jsx)(kt,{resolver:T.getResolver(),currentProjectId:null,env:K.env,onSelect:(k,L)=>{T.creds.saveProfileConfig(K.profile,K.env,{project_id:k,project_name:L}),Se(G=>G?{...G,phase:"folder"}:null)},onCancel:()=>{Ye(K.profile,K.env),Se(null),R()}});if(w==="folder"){let k=T.creds.loadProfileConfig(K.profile,K.env);return(0,j.jsx)(It,{resolver:T.getResolver(),projectId:k?.project_id??"",currentFolderId:null,env:K.env,onSelect:(L,G)=>{T.creds.saveProfileConfig(K.profile,K.env,{folder_id:L,folder_name:G}),Ye(K.profile,K.env),Se(null),R()},onCancel:async()=>{let L=T.creds.loadProfileConfig(K.profile,K.env);if(L?.project_id)try{let q=T.getResolver()?.cached;if(q){let z=ae(K.env),fe=await new lt(z.tmsBaseUrl,q.username,q.access_key).getDefaultFolder(L.project_id);fe&&T.creds.saveProfileConfig(K.profile,K.env,{folder_id:fe,folder_name:"Default"})}}catch{}Ye(K.profile,K.env),Se(null),R()}})}return(0,j.jsx)(tn,{devMode:process.env.KANE_DEV_MODE==="1",profiles:T.creds.listProfiles(),onBasicLogin:(k,L,G,q)=>{T.creds.saveBasicAuth(k,L,{username:G,access_key:q}),T.creds.setActiveProfile(k),T.creds.setDefaultEnv(L),T.setTokenValid(!0),Xe()},onOAuthLogin:async(k,L)=>{T.creds.setDefaultEnv(L),await T.login(k),Xe()},onComplete:(k,L)=>{Ct(L).then(()=>{Se({phase:"project",profile:k,env:L})}).catch(()=>{Se({phase:"project",profile:k,env:L})})},onCancel:()=>{Se(null),R()}})},renderProfilesView:R=>(0,j.jsx)($r,{creds:T.creds,onSwitch:(w,k)=>{T.creds.setActiveProfile(w),T.creds.setDefaultEnv(k),Ye(w,k),Xe(),Ct(k).catch(()=>{}),le({type:"info",text:`Switched to ${w} [${k}]`}),R()},onCancel:R}),renderChromeProfilePicker:R=>(0,j.jsx)(Br,{currentPath:W.chrome_profile_path,onSelect:w=>{c.save({chrome_profile_path:w}),nt(c.load()),R()},onCancel:R}),renderProjectPicker:R=>(0,j.jsx)(kt,{resolver:T.getResolver(),currentProjectId:W.project_id,env:pe,onSelect:(w,k)=>{c.save({project_id:w,project_name:k});let L=T.creds.getActiveProfile();L&&T.creds.saveProfileConfig(L,pe,{project_id:w,project_name:k}),nt(c.load()),R()},onCancel:R}),renderFolderPicker:R=>(0,j.jsx)(It,{resolver:T.getResolver(),projectId:W.project_id??"",currentFolderId:W.folder_id,env:pe,onSelect:(w,k)=>{c.save({folder_id:w,folder_name:k});let L=T.creds.getActiveProfile();L&&T.creds.saveProfileConfig(L,pe,{folder_id:w,folder_name:k}),nt(c.load()),R()},onCancel:R}),renderWindowSizePicker:R=>(0,j.jsx)(no,{currentWidth:W.window_size.width,currentHeight:W.window_size.height,onSelect:(w,k)=>{c.set("window_size",{width:w,height:k}),nt(c.load()),R()},onCancel:R})},Vt):null})(),Vt&&_e&&(0,j.jsx)(y,{paddingX:1,marginTop:1,children:(0,j.jsx)(f,{color:_e.color,children:_e.text})}),!Vt&&(0,j.jsx)(Mn,{onSubmit:Ci,onEscape:void 0,history:xi,commands:Ps,placeholder:H.askingUser?"Type your answer...":H.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (/ = commands)"})]})]}),g&&O&&u&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(Vr,{steps:h,status:u.status,testUrl:u.testUrl,error:u.error}),u.status==="success"&&(0,j.jsx)(Fr,{shareableLink:u.testUrl,testCaseLink:u.testCaseLink,codeExportDir:u.codeExportDir,autoExit:!1})]}),me&&(0,j.jsx)(Jo,{onSubmit:Ei}),ee&&u&&(0,j.jsx)(Vr,{steps:h,status:u.status,error:u.error}),g&&!O&&(0,j.jsx)(Qo,{profile:Yt,environment:pe,model:W.model,tokenValid:T.tokenValid,sessionId:i.sessionId,runCount:P,viewMode:tt})]})}function Ta({profiles:s,onSelect:e,onCancel:t,validating:n}){let[r,o]=(0,$.useState)(0);return je((a,l)=>{if(!n){if(l.escape){t();return}if(l.upArrow&&r>0&&o(i=>i-1),l.downArrow&&r<s.length-1&&o(i=>i+1),l.return){let i=s[r];e(i.profile,i.env)}}}),(0,j.jsxs)(y,{flexDirection:"column",paddingX:1,children:[(0,j.jsx)(f,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,j.jsx)(y,{marginTop:1,flexDirection:"column",children:s.map((a,l)=>(0,j.jsxs)(f,{children:[l===r?"\u276F ":" ",(0,j.jsx)(f,{color:l===r?"#ff9500":"white",bold:l===r,children:a.profile}),(0,j.jsxs)(f,{color:"gray",children:[" [",a.env,"]"]})]},`${a.profile}-${a.env}`))}),n&&(0,j.jsx)(y,{marginTop:1,children:(0,j.jsx)(f,{color:"yellow",children:"Validating credentials..."})}),!n&&(0,j.jsx)(y,{marginTop:1,children:(0,j.jsx)(f,{color:"gray",children:"Esc = new login"})})]})}var ye=U(De(),1);var ve=U(Q(),1);function zs({resultRef:s}){let{exit:e}=Zt(),t=(0,ye.useRef)(new He),n=(0,ye.useRef)(new ot),r=(0,ye.useRef)(new bt),o=t.current,a=n.current,l=r.current,i=Fn(),[c,d]=(0,ye.useState)("gate"),[m,g]=(0,ye.useState)(null),[p,_]=(0,ye.useState)(null),[b,E]=(0,ye.useState)(null),[A,P]=(0,ye.useState)(null),C=(0,ye.useCallback)((F,N,u,x)=>l.log(F,N,u,x),[l]),O=(0,ye.useCallback)((F,N)=>{let u=F?o.loadProfileConfig(F,N):null;a.save({project_id:u?.project_id??null,project_name:u?.project_name??null,folder_id:u?.folder_id??null,folder_name:u?.folder_name??null})},[o,a]);je((F,N)=>{N.ctrl&&F==="c"&&X(0,"Ctrl+C exit")});let te=(0,ye.useRef)(!1);ye.default.useEffect(()=>{te.current||(te.current=!0,ir(o,C).then(F=>{g(F),F.status==="authenticated"?(O(F.result.profile,F.result.env),d("input")):F.status==="needs_pick"?d("pick"):(_(F.profile??null),E(F.env??null),d("login"))}).catch(F=>{P(`Auth check failed: ${F instanceof Error?F.message:String(F)}`)}))},[o,C]);let Z=(0,ye.useCallback)(F=>{s.current={objective:F},e()},[s,e]),ne=(0,ye.useCallback)(async(F,N)=>{o.setActiveProfile(F),o.setDefaultEnv(N),(await on(o,F,N,C)).status==="authenticated"?(O(F,N),d("input")):(_(F),E(N),d("login"))},[o,C,O]),_e=(0,ye.useCallback)(()=>{let F=o.getActiveProfile(),N=o.getDefaultEnv();if(!F)return null;let u=ae(N),x=o.loadBasicAuth(F,N);return new pt(u.controllerBaseUrl,async()=>o.loadCredentials(F,N)?.access_token??null,x,C)},[o,C]);if(c==="gate")return(0,ve.jsx)(y,{paddingX:1,children:(0,ve.jsx)(f,{color:"yellow",children:"Checking authentication..."})});if(A)return(0,ve.jsxs)(y,{flexDirection:"column",paddingX:1,children:[(0,ve.jsx)(f,{color:"red",children:A}),(0,ve.jsx)(f,{color:"gray",children:"Press Ctrl+C to exit."})]});if(c==="pick"&&m?.status==="needs_pick")return(0,ve.jsx)(ka,{profiles:m.profiles,onSelect:ne});if(c==="login"||c==="login-project"||c==="login-folder"){if(c==="login-project")return(0,ve.jsx)(kt,{resolver:_e(),currentProjectId:null,env:b??"prod",onSelect:(F,N)=>{let u=p??o.getActiveProfile()??"default",x=b??o.getDefaultEnv();o.saveProfileConfig(u,x,{project_id:F,project_name:N}),d("login-folder")},onCancel:()=>{let F=p??o.getActiveProfile()??"default",N=b??o.getDefaultEnv();O(F,N),d("input")}});if(c==="login-folder"){let F=p??o.getActiveProfile()??"default",N=b??o.getDefaultEnv(),u=o.loadProfileConfig(F,N);return(0,ve.jsx)(It,{resolver:_e(),projectId:u?.project_id??"",currentFolderId:null,env:N,onSelect:(x,h)=>{o.saveProfileConfig(F,N,{folder_id:x,folder_name:h}),O(F,N),d("input")},onCancel:async()=>{if(u?.project_id)try{let x=ae(N),h=o.loadBasicAuth(F,N);if(h){let B=await new lt(x.tmsBaseUrl,h.username,h.access_key).getDefaultFolder(u.project_id);B&&o.saveProfileConfig(F,N,{folder_id:B,folder_name:"Default"})}}catch{}O(F,N),d("input")}})}return(0,ve.jsx)(tn,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:(F,N,u,x)=>{o.saveBasicAuth(F,N,{username:u,access_key:x}),o.setActiveProfile(F),o.setDefaultEnv(N)},onOAuthLogin:async(F,N)=>{let{LoginFlow:u}=await import("./login-flow-5WUX5JKU.js");o.setDefaultEnv(N),o.setActiveProfile(F),await new u(F,N,o).login()},onComplete:(F,N)=>{_(F),E(N),o.setActiveProfile(F),o.setDefaultEnv(N),d("login-project")},onCancel:()=>{X(0,"Login cancelled")}})}return c==="input"?(0,ve.jsx)(Mn,{onSubmit:Z,onEscape:()=>X(0,"User pressed Escape"),history:i,placeholder:"Type an objective..."}):(0,ve.jsx)(ve.Fragment,{})}function ka({profiles:s,onSelect:e}){let[t,n]=(0,ye.useState)(0),[r,o]=(0,ye.useState)(!1);return je((a,l)=>{if(!r){if(l.escape){X(0,"Profile picker cancelled");return}if(l.upArrow&&t>0&&n(i=>i-1),l.downArrow&&t<s.length-1&&n(i=>i+1),l.return){o(!0);let i=s[t];e(i.profile,i.env).catch(()=>o(!1))}}}),(0,ve.jsxs)(y,{flexDirection:"column",paddingX:1,children:[(0,ve.jsx)(f,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,ve.jsx)(y,{marginTop:1,flexDirection:"column",children:s.map((a,l)=>(0,ve.jsxs)(f,{children:[l===t?"\u276F ":" ",(0,ve.jsx)(f,{color:l===t?"#ff9500":"white",bold:l===t,children:a.profile}),(0,ve.jsxs)(f,{color:"gray",children:[" [",a.env,"]"]})]},`${a.profile}-${a.env}`))}),r&&(0,ve.jsx)(y,{marginTop:1,children:(0,ve.jsx)(f,{color:"yellow",children:"Validating credentials..."})})]})}var ai=U(ii(),1),{program:Mf,createCommand:Hf,createArgument:Wf,createOption:Kf,CommanderError:Gf,InvalidArgumentError:qf,InvalidOptionArgumentError:zf,Command:li,Argument:Jf,Option:cn,Help:Xf}=ai.default;import{join as zt}from"path";var pi=U(De(),1);var Qe=U(De(),1);var Lt=U(Q(),1);function ci({steps:s,bifurcationInfo:e,perFlowMetadata:t}){return!e||e.isSingleFlow||!t||t.length<=1?null:(0,Lt.jsx)(y,{flexDirection:"column",children:t.map((n,r)=>{let o=s[r],a=o?.children??[],l=a.filter(p=>p.status==="passed").length,i=a.filter(p=>p.status==="failed").length,c=l+i,d=a.reduce((p,_)=>p+(_.duration??0),0),m=o?.status==="failed"?"failed":"passed",g=e.flows[r]??o?.objective??`Flow ${r+1}`;return(0,Lt.jsxs)(y,{flexDirection:"column",marginTop:r>0?1:0,children:[(0,Lt.jsxs)(y,{marginLeft:1,children:[(0,Lt.jsx)(f,{color:"#b388ff",bold:!0,children:"Flow "+(r+1)+": "}),(0,Lt.jsx)(f,{color:"#b388ff",children:g})]}),(0,Lt.jsx)(sn,{status:m,summary:n?.summary??"",duration:d,steps:c,stepsPassed:l,stepsFailed:i,reason:n?.error_message??void 0,creditsConsumed:n?.credits_consumed??void 0})]},`flow-summary-${r}`)})})}var Je=U(Q(),1);function ui({message:s,code:e,remediation:t,docsUrl:n}){return(0,Je.jsx)(Yo,{title:"Error",variant:"error",children:(0,Je.jsxs)(y,{flexDirection:"column",paddingY:1,children:[(0,Je.jsxs)(f,{color:v.red,bold:!0,children:[" \u2717 ",s]}),e&&(0,Je.jsxs)(y,{marginTop:0,marginLeft:5,children:[(0,Je.jsx)(f,{color:v.muted,children:"Code: "}),(0,Je.jsx)(f,{color:v.dimmed,children:e})]}),t&&(0,Je.jsxs)(y,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,Je.jsx)(f,{color:v.green,bold:!0,children:"Fix:"}),(0,Je.jsxs)(f,{color:v.cyan,children:["$ ",t]})]}),n&&(0,Je.jsxs)(y,{marginTop:1,marginLeft:5,children:[(0,Je.jsx)(f,{color:v.muted,children:"Docs: "}),(0,Je.jsx)(f,{color:v.cyan,underline:!0,children:n})]})]})})}var Ce=U(Q(),1);function di({config:s,spawnOpts:e,cancelRef:t,banner:n,onComplete:r,onStepEnd:o}){let{exit:a}=Zt(),l=sr(o),i=(0,Qe.useRef)(!1),c=(0,Qe.useRef)(!1),[d,m]=(0,Qe.useState)("");(0,Qe.useEffect)(()=>{i.current||(i.current=!0,l.startRun(s,e))},[s,e,l]),(0,Qe.useEffect)(()=>{t&&(t.current=()=>l.cancelRun())},[t,l]);let g=(0,Qe.useRef)(0);je((b,E)=>{E.ctrl&&b==="c"&&(l.isRunning?(g.current++,g.current>=2?a():l.cancelRun()):a())}),je((b,E)=>{l.askingUser&&(E.return?(l.sendAnswer(d),m("")):E.backspace||E.delete?m(A=>A.slice(0,-1)):b&&!E.ctrl&&!E.meta&&m(A=>A+b))},{isActive:!!l.askingUser}),(0,Qe.useEffect)(()=>{if(!l.isRunning&&l.lastRunEnd&&!c.current){c.current=!0;let{passed:b,failed:E,total:A}=Rn(l.steps),P=l.bifurcationInfo;r({lastRunEnd:l.lastRunEnd,stepsPassed:b,stepsFailed:E,stepsTotal:A,hadError:!1,bifurcationFlows:P&&!P.isSingleFlow?P.flows:null}),a()}},[l.isRunning,l.lastRunEnd,l.steps,r,a]),(0,Qe.useEffect)(()=>{l.runError&&!l.isRunning&&!c.current&&(c.current=!0,r({lastRunEnd:null,stepsPassed:0,stepsFailed:0,stepsTotal:0,hadError:!0,bifurcationFlows:null}),a())},[l.runError,l.isRunning,r,a]);let p=l.lastRunEnd?(()=>{let{passed:b,failed:E,total:A}=Rn(l.steps);return{status:l.lastRunEnd.status,duration:l.lastRunEnd.duration??0,summary:l.lastRunEnd.summary??"",stepsPassed:b,stepsFailed:E,stepsTotal:A,reason:l.lastRunEnd.reason,finalState:l.lastRunEnd.final_state,creditsConsumed:l.lastRunEnd.credits_consumed}})():null,_=(0,Qe.useMemo)(()=>n?[{key:"banner",...n}]:[],[n]);return(0,Ce.jsxs)(y,{flexDirection:"column",children:[(0,Ce.jsx)(Qt,{items:_,children:b=>(0,Ce.jsxs)(y,{flexDirection:"column",marginBottom:1,children:[(0,Ce.jsxs)(y,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,Ce.jsx)(f,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,Ce.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,Ce.jsx)(f,{color:v.cyan,children:b.model}),(0,Ce.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,Ce.jsx)(f,{color:v.dimmed,children:b.auth})]}),b.status?.map((E,A)=>(0,Ce.jsx)(f,{color:v.dimmed,children:E},A))]},b.key)}),(()=>{let b=zn({isRunning:l.isRunning,bifurcationInfo:l.bifurcationInfo,steps:l.steps,cmInitCounts:l.cmInitCounts});return b?(0,Ce.jsx)(qn,{label:b.label,hasBifurcation:b.hasBifurcation}):null})(),l.steps.length>0&&(0,Ce.jsx)(Kn,{steps:l.steps,bifurcated:!!l.bifurcationInfo&&!l.bifurcationInfo.isSingleFlow,flows:l.bifurcationInfo?.flows,cmInitCounts:l.cmInitCounts,staticSteps:!0}),l.askingUser&&(0,Ce.jsxs)(y,{flexDirection:"column",marginTop:1,children:[(0,Ce.jsxs)(f,{color:v.yellow,children:['Agent is asking: "',l.askingUser,'"']}),(0,Ce.jsxs)(f,{children:["> ",d,"\u2588"]})]}),l.runError&&(0,Ce.jsx)(ui,{message:l.runError,code:"RUNNER_ERROR"}),p&&l.lastRunEnd&&(0,Ce.jsx)(ci,{steps:l.steps,bifurcationInfo:l.bifurcationInfo,perFlowMetadata:l.lastRunEnd.per_flow_metadata??[]}),p&&(0,Ce.jsx)(sn,{status:p.status==="passed"?"passed":"failed",summary:p.summary??"",duration:p.duration,steps:p.stepsTotal,stepsPassed:p.stepsPassed,stepsFailed:p.stepsFailed,reason:p.reason,creditsConsumed:p.creditsConsumed})]})}import{createInterface as Ka}from"readline";function un(s){process.stdout.write(JSON.stringify(s)+`
58
+ `)}async function fi(s,e,t){let n=rr(s,e);Vn().then(m=>{m&&un({type:"update_available",current:m.current,latest:m.latest,severity:m.severity})}).catch(()=>{});let r=Ka({input:process.stdin});r.on("line",m=>{try{let g=JSON.parse(m);g.type==="user_response"?n.sendUserResponse(g.answer??""):g.type==="cancel"&&n.sendCancel(g.reason??"")}catch{}});let o=null,a=!1,l=0,i=null,c=0,d=!1;for await(let m of n.events)switch(m.type){case"run_start":d&&c++;break;case"step_start":{let g=m;t?.onStepLog?.("STEP_START",`Step ${g.index} started`,{index:g.index,objective:g.objective,child_id:g.child_id});let p={step:g.index+1,status:"running",remark:g.objective??`Step ${g.index+1}`};g.child_id&&(p.child_id=g.child_id),un(p);break}case"step_event":t?.onStepLog?.("STEP_EVENT",`Step ${m.index} ${m.event}`,{index:m.index,phase:m.event,action_type:m.action_type,detail:m.detail,child_id:m.child_id});break;case"step_end":{let g=m;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}),l++;let p={step:g.index+1,status:g.status==="passed"?"done":"failed",remark:g.summary??""};g.child_id&&(p.child_id=g.child_id),un(p);let _=d?Math.max(0,c-1):0;t?.onStepEnd?.(g.index,_);break}case"bifurcation":{let g=m,p=g.flows??[],_=g.count??p.length;(g.is_single_flow??_<=1)||(i=p,d=!0,c=0),un({type:"bifurcation",flows:p,count:_});break}case"ask_user":{let g=m;un({type:"ask_user",question:g.question,step_index:g.step_index,...g.options?{options:g.options}:{}});break}case"run_end":{o=m;break}case"error":{a=!0,un({type:"error",message:m.message});break}default:break}return r.close(),await n.exited,{lastRunEnd:o,stepsTotal:l,hadError:a,bifurcationFlows:i}}var qt=class extends Error{constructor(t,n){super(t);this.code=n;this.name="AuthError"}};async function br(s){let{creds:e,env:t,usernameFlag:n,accessKeyFlag:r,log:o}=s,a=null,l=null;if(n&&r)a={username:n,access_key:r},o("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:n});else{let p=e.resolveAuth();p?.method==="basic"&&(a={username:p.username,access_key:p.access_key},o("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:p.username}))}if(!a){let{credentials:p,profile:_}=e.getActiveCredentials();if(!p)throw new qt("Not authenticated \u2014 no credentials found","not_authenticated");if(l=p.access_token,p.expires_at-Date.now()/1e3<300)try{let E=await Xn({creds:e,profile:_,env:t,credentials:p});E&&(l=E.accessToken,o("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(E){let A=E instanceof Error?E.message:String(E);throw o("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:A}),new qt(`Token refresh failed: ${A}`,"refresh_failed")}}let i=ae(t),c=async()=>l,d=a?{username:a.username,access_key:a.access_key}:null,m=new pt(i.controllerBaseUrl,c,d,o),g=await m.resolve();return g&&!a&&(a={username:g.username,access_key:g.access_key},o("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:g.username})),{basicAuth:a,token:l,resolver:m,resolvedCreds:g}}import{mkdtempSync as Ga,rmSync as qa}from"fs";import{join as za}from"path";import{tmpdir as Ja}from"os";async function mi(s){if(s.cft)return{instance:null,tempDir:null};if(s.wsEndpoint)return{wsEndpoint:s.wsEndpoint,instance:null,tempDir:null};if(s.cdpEndpoint){let r=await fetch(`${s.cdpEndpoint}/json/version`);if(!r.ok)throw new Error(`CDP endpoint not reachable: ${s.cdpEndpoint} (${r.status})`);return{cdpEndpoint:s.cdpEndpoint,instance:null,tempDir:null}}let e,t=null;if(s.config.chrome_profile_path)e=s.config.chrome_profile_path.replace("~",process.env.HOME??"~");else{t=Ga(za(Ja(),"kane-clean-")),e=t;let r=t;Ge("tempDir",()=>{try{qa(r,{recursive:!0,force:!0})}catch{}})}let n=await tr({userDataDir:e,width:s.config.window_size.width,height:s.config.window_size.height,startUrl:s.startUrl,headless:s.headless});return{cdpEndpoint:n.cdpEndpoint,instance:n,tempDir:t}}function Pn(s){let e=new li;if(e.name("kane-cli").version(en),s[0]==="--help"||s[0]==="-h"||s[0]==="help"){(async()=>{let{HelpView:n}=await import("./HelpView-DOYUDPWZ.js"),{render:r}=await import("./build-JIKYOZUH.js"),o=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=r(o.default.createElement(n));await a(),X(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 cn("--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 cn("--model <name>","Model").default("v16-alpha").hideHelp()).option("--chrome-profile <path>","Chrome profile path").action(async n=>{let r=new He,o=new ot,a=n.env,l=n.profile;if(!process.stdin.isTTY||n.oauth||n.username){if(r.setDefaultEnv(a),n.oauth?(await new hn(l,a,r).login(),console.log(`Logged in as ${l} [${a}] via OAuth`)):n.username&&n.accessKey?(r.saveBasicAuth(l,a,{username:n.username,access_key:n.accessKey}),console.log(`Logged in as ${l} [${a}] via basic auth`)):(console.error("Provide --oauth, or --username and --access-key"),X(1,"Missing --oauth or credentials for login")),r.setActiveProfile(l),o.set("model",n.model),n.chromeProfile&&o.set("chrome_profile_path",n.chromeProfile),n.projectId)o.set("project_id",n.projectId),console.log(`Project set to ${n.projectId}`);else try{let A=await br({creds:r,env:a,log:()=>{}});if(A.resolvedCreds){let{TmsClient:P}=await import("./tms-client-VH42IFUF.js"),te=(await new P(ae(a).tmsBaseUrl,A.resolvedCreds.username,A.resolvedCreds.access_key).listProjects()).find(Z=>Z.name.toLowerCase().includes("kaneai"));te&&(o.set("project_id",te.project_id),console.log(`Auto-selected project: ${te.name} (${te.project_id})`))}}catch(E){console.warn(`Could not auto-select project: ${E instanceof Error?E.message:E}`)}n.folderId&&(o.set("folder_id",n.folderId),console.log(`Folder set to ${n.folderId}`)),console.log("Setup complete.");return}let{LoginWizard:i}=await import("./LoginWizard-NJ22OXIH.js"),{ProjectPicker:c}=await import("./ProjectPicker-43LFS6S6.js"),{FolderPicker:d}=await import("./FolderPicker-DN4OV6BI.js"),{render:m}=await import("./build-JIKYOZUH.js"),g=await import("./react-QWOAB3TB.js"),p=!1;if(await new Promise(E=>{let{unmount:A}=m(g.default.createElement(i,{devMode:process.env.KANE_DEV_MODE==="1",profiles:r.listProfiles(),onBasicLogin:(P,C,O,te)=>{r.saveBasicAuth(P,C,{username:O,access_key:te}),r.setActiveProfile(P),r.setDefaultEnv(C),a=C,l=P},onOAuthLogin:async(P,C)=>{r.setDefaultEnv(C),await new hn(P,C,r).login(),a=C,l=P},onComplete:()=>{A(),E()},onCancel:()=>{p=!0,A(),E()}}))}),p)return;let _;try{_=(await br({creds:r,env:a,log:()=>{}})).resolver}catch{console.log("Could not resolve credentials for project setup. Run: kane-cli login");return}if(!_.cached){console.log("Could not resolve credentials for project setup. Run: kane-cli login");return}let b=null;await new Promise(E=>{let{unmount:A}=m(g.default.createElement(c,{resolver:_,currentProjectId:o.load().project_id,env:a,onSelect:(P,C)=>{o.set("project_id",P),o.set("project_name",C),b=P,console.log(`Project set to ${C} (${P})`),A(),E()},onCancel:()=>{A(),E()}}))}),b&&(await new Promise(E=>{let{unmount:A}=m(g.default.createElement(d,{resolver:_,projectId:b,currentFolderId:o.load().folder_id,env:a,onSelect:(P,C)=>{o.set("folder_id",P),o.set("folder_name",C),console.log(`Folder set to ${C} (${P})`),A(),E()},onCancel:()=>{A(),E()}}))}),X(0,"Login setup complete"))}),e.command("logout").action(async()=>{let n=new He,r=n.getActiveProfile();if(!r){console.log("No active profile to logout");return}let o=n.getDefaultEnv(),a=await Yn(n,r,o);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 He,o=n.profile??r.getActiveProfile()??"default",a=r.getDefaultEnv(),l=r.loadCredentials(o,a),i=r.loadBasicAuth(o,a),c="none",d,m,g;if(i)c="basic",d=i.username;else if(l){c="oauth";let A=l.expires_at,P=Date.now()/1e3;m=A>P?"valid":"expired",g=new Date(A*1e3).toISOString().slice(0,10)}else m="missing";let{WhoamiView:p}=await import("./WhoamiView-AP6NXPTL.js"),{render:_}=await import("./build-JIKYOZUH.js"),b=await import("./react-QWOAB3TB.js"),{waitUntilExit:E}=_(b.default.createElement(p,{profile:o,env:a,authenticated:c!=="none",authMethod:c,username:d,tokenStatus:m,expiresAt:g}));await E()}),e.command("config <action> [value]").action(async(n,r)=>{let o=new ot,a=new He;if(n==="show"){let l=o.load(),i=a.getActiveProfile()??"default",c=a.getDefaultEnv(),d=a.loadBasicAuth(i,c),m=a.loadCredentials(i,c),g=d?`basic (${d.username})`:m?"oauth":"not configured",{ConfigView:p}=await import("./ConfigView-XCWDFTNS.js"),{render:_}=await import("./build-JIKYOZUH.js"),b=await import("./react-QWOAB3TB.js"),{waitUntilExit:E}=_(b.default.createElement(p,{model:l.model,mode:l.mode,authLabel:g,profile:i,env:c,defaultUrl:mt,projectId:l.project_id,projectName:l.project_name,folderId:l.folder_id,windowSize:`${l.window_size.width}x${l.window_size.height}`,chromeProfile:l.chrome_profile_path}));await E()}else if(n==="set-window"&&r){let l=r.split("x").map(Number),[i,c]=l;!i||!c||!Number.isInteger(i)||!Number.isInteger(c)?console.error("Invalid format. Use: kane-cli config set-window WIDTHxHEIGHT"):i<800||i>3840?console.error(`Width must be between 800 and 3840 (got ${i})`):c<600||c>2160?console.error(`Height must be between 600 and 2160 (got ${c})`):(o.set("window_size",{width:i,height:c}),console.log(`Window size set to ${i}x${c}`))}else if(n==="set-mode"){if(r!=="action"&&r!=="testing"){console.error("Mode must be 'action' or 'testing'."),X(1,"Invalid mode");return}o.set("mode",r),console.log(`Mode set to ${r}`)}else if(n==="chrome-profile"){if(r||!process.stdin.isTTY){r||(console.error("Usage: kane-cli config chrome-profile <path>"),X(1,"Missing chrome-profile path")),o.set("chrome_profile_path",r),console.log(`Chrome profile set to ${r}`);return}let{ChromeProfilePicker:l}=await import("./ChromeProfilePicker-VPCR7EPX.js"),{render:i}=await import("./build-JIKYOZUH.js"),c=await import("./react-QWOAB3TB.js");await new Promise(d=>{let{unmount:m}=i(c.default.createElement(l,{currentPath:o.load().chrome_profile_path,onSelect:g=>{o.set("chrome_profile_path",g),console.log(`Chrome profile set to ${g}`),m(),d()},onCancel:()=>{m(),d()}}))})}else if(n==="project"){if(r||!process.stdin.isTTY){r||(console.error("Usage: kane-cli config project <project-id>"),X(1,"Missing project ID")),o.set("project_id",r),console.log(`Project set to ${r}`);return}let l=a.getDefaultEnv(),i=ae(l),c=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!c){console.log("Login first to browse projects");return}let{ProjectPicker:d}=await import("./ProjectPicker-43LFS6S6.js"),{AuthResolver:m}=await import("./resolver-QLDOAIXU.js"),{render:g}=await import("./build-JIKYOZUH.js"),p=await import("./react-QWOAB3TB.js"),_=new m(i.controllerBaseUrl,async()=>null,c);await _.resolve(),await new Promise(b=>{let{unmount:E}=g(p.default.createElement(d,{resolver:_,currentProjectId:o.load().project_id,env:l,onSelect:(A,P)=>{o.set("project_id",A),o.set("project_name",P),console.log(`Project set to ${P} (${A})`),E(),b()},onCancel:()=>{E(),b()}}))})}else if(n==="folder"){if(r||!process.stdin.isTTY){if(r||(console.error("Usage: kane-cli config folder <folder-id>"),X(1,"Missing folder ID")),!o.load().project_id){console.log("Select a project first: kane-cli config project <id>");return}o.set("folder_id",r),console.log(`Folder set to ${r}`);return}let l=o.load();if(!l.project_id){console.log("Select a project first: kane-cli config project");return}let i=a.getDefaultEnv(),c=ae(i),d=a.loadBasicAuth(a.getActiveProfile()??"default",i);if(!d){console.log("Login first to browse folders");return}let{FolderPicker:m}=await import("./FolderPicker-DN4OV6BI.js"),{AuthResolver:g}=await import("./resolver-QLDOAIXU.js"),{render:p}=await import("./build-JIKYOZUH.js"),_=await import("./react-QWOAB3TB.js"),b=new g(c.controllerBaseUrl,async()=>null,d);await b.resolve(),await new Promise(E=>{let{unmount:A}=p(_.default.createElement(m,{resolver:b,projectId:l.project_id,currentFolderId:l.folder_id,env:i,onSelect:(P,C)=>{o.set("folder_id",P),o.set("folder_name",C),console.log(`Folder set to ${C} (${P})`),A(),E()},onCancel:()=>{A(),E()}}))})}else console.log("Usage: kane-cli config show|set-window|set-mode|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: ${zt(Ee,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new cn("--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 cn("--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("--mode <name>","Run mode: 'action' (strict \u2014 hard-stop on auth/blocked/error) or 'testing' (lenient \u2014 fall through). Overrides config; default: testing.").option("--agent","Agent mode: plain NDJSON output, no colors/UI").option("--task-skills","Enable domain-specific task skills (experimental)").addOption(new cn("--local","Skip TMS integration (no uploads, no variables/secrets push)").hideHelp()).option("--code-export","Generate code export after upload").option("--code-language <lang>","Code export language: python (only python supported for now)").option("--skip-code-validation","Skip post-codegen worker-side validation").option("--no-skip-code-validation","Force post-codegen worker-side validation").addHelpText("after",`
59
59
  Variables:
60
60
  Variables are loaded in order (later wins):
61
- 1. Global: ${Gt(Se,"variables")}/*.json
61
+ 1. Global: ${zt(Ee,"variables")}/*.json
62
62
  2. Local: {cwd}/.testmuai/variables/*.json
63
63
  3. File: --variables-file <path>
64
64
  4. Inline: --variables '{"key": {"value": "...", "secret": false}}'
@@ -73,16 +73,16 @@ Variables:
73
73
 
74
74
  Context Files:
75
75
  Context files provide additional instructions to the agent.
76
- Global: ${Gt(Se,"global-memory.md")}
76
+ Global: ${zt(Ee,"global-memory.md")}
77
77
  Local: {cwd}/.testmuai/context.md
78
78
 
79
79
  Override with --global-context / --local-context flags.
80
- `).action(async(n,r)=>{try{let o=new Ne,l=new tt().load(),i;if(r.mode===void 0)i=l.mode==="action"?"action":"testing";else if(r.mode==="action"||r.mode==="testing")i=r.mode;else{console.error("Invalid --mode. Must be 'action' or 'testing'."),X(2,"Invalid --mode");return}if(!(r.username&&r.accessKey)){let U=o.getActiveProfile(),oe=o.getDefaultEnv();U&&(o.loadBasicAuth(U,oe)||o.loadCredentials(U,oe))||(console.error("Not authenticated. Run: kane-cli login --oauth, or kane-cli login --username <user> --access-key <key>"),X(1,"Not authenticated"))}let c=`${o.getActiveProfile()??"no profile"}/${o.getDefaultEnv()}`,d=[],m=r.env??o.getDefaultEnv(),g=null,p=[],_=(U,oe,se,me)=>{g?g(U,oe,se,me):p.push([U,oe,se,me])},x;try{x=await _r({creds:o,env:m,usernameFlag:r.username,accessKeyFlag:r.accessKey,log:_})}catch(U){throw U instanceof Kt&&(console.error(U.code==="not_authenticated"?"Not authenticated. Run: kane-cli login":"Token refresh failed. Run: kane-cli login"),X(2,U.code==="not_authenticated"?"Not authenticated":"Token refresh failed")),U}let C=!!x.basicAuth,T=x.basicAuth?.username,P=x.basicAuth?.access_key,R=x.token,O=x.resolver,te=x.resolvedCreds;x.basicAuth&&d.push(`Auth: ${x.basicAuth.username}`);let Z=ft,ne=dr({objective:n,globalDir:Gt(Se,"variables"),localDir:Gt(process.cwd(),".testmuai","variables"),file:r.variablesFile,inline:r.variables,onLoadError:U=>console.error(U)}),ve;if(r.sessionContext)try{ve=JSON.parse(r.sessionContext)}catch{console.error("Invalid --session-context JSON"),X(2,"Invalid --session-context JSON")}let V=r.globalContext??Gt(Se,"global-memory.md"),F=r.localContext??Gt(process.cwd(),".testmuai","context.md"),u=on(V),w=on(F),h;try{h=await mi({config:l,startUrl:Z??void 0,headless:r.headless,cft:r.cft,wsEndpoint:r.wsEndpoint,cdpEndpoint:r.cdpEndpoint})}catch(U){console.error(er(U));let oe=U instanceof tn?"Chrome not found at standard paths":`Chrome failed: ${U instanceof Error?U.message:U}`;X(2,oe)}h.instance&&Xe("chrome",()=>{h.instance.kill()}),r.cft?d.push("CfT mode: Playwright will manage its own browser"):r.wsEndpoint?d.push(`Playwright WS endpoint (${r.wsEndpoint.slice(0,60)}...)`):r.cdpEndpoint?d.push(`CDP connected (${r.cdpEndpoint})`):h.cdpEndpoint&&d.push(`Chrome ready (${h.cdpEndpoint})`);let b=new xt;b.start({model:r.model??l.model,environment:m,profile:o.getActiveProfile()}),g=(U,oe,se,me)=>b.log(U,oe,se,me);for(let U of p)b.log(...U);if(p.length=0,x.resolvedCreds){let{createRemoteLogger:U}=await import("./logging-R5263ZJZ.js"),{getMachineId:oe}=await import("./machine-id-DZN4MYOO.js"),se=U({sessionId:b.sessionId,identity:{org_id:String(x.resolvedCreds.org_id??""),user_id:String(x.resolvedCreds.user_id??""),machine_id:oe()},environment:m,getToken:async()=>x.token});b.setRemoteLogger(se),se.start(),Xe("remote-logger",()=>se.shutdownSync()),Qn(se)}let $=x.basicAuth&&!r.local?await fr({variables:ne,auth:x.basicAuth,orgId:String(x.resolvedCreds?.org_id??""),env:m,localMode:!!r.local,log:(U,oe,se,me)=>b.log(U,oe,se,me)}):{};if(b.setAuteurVariables(ne.auteur),b.setFirstRun(n,ft),!r.local&&x.basicAuth&&l.project_id){let U=ce(m),oe=await pr({tmsBaseUrl:U.tmsBaseUrl,auth:x.basicAuth,objective:n,url:ft,projectId:l.project_id,folderId:l.folder_id??"",hasCustomProfile:!!l.chrome_profile_path,log:(se,me,Ge,ot)=>b.log(se,me,Ge,ot)});oe&&b.setTestId(oe)}let z=mr({objective:ne.auteurObjective,url:Z??void 0,model:r.model??l.model,chrome:h,auth:x,sessionId:b.sessionId,runIndex:0,windowSize:l.window_size,maxSteps:parseInt(r.maxSteps,10),headless:r.headless,disableAskUser:!process.stdin.isTTY,enableTaskSkills:r.taskSkills,variables:Object.keys(ne.auteur).length>0?ne.auteur:void 0,globalContext:u??void 0,localContext:w??void 0,sessionContext:ve}),q=null;if(!r.local)try{let{ControllerClient:U}=await import("./controller-client-7BIK5FYL.js"),oe;if(C&&T&&P)oe={username:T,accessKey:P};else if(R)oe=R;else throw new Error("No auth available");let me=await new U(ce(m).controllerBaseUrl,oe).getScreenshotSas();b.setScreenshotSas(me),q=new sn(me,3,(Ge,ot,ae,ge)=>b.log(Ge,ot,ae,ge)),b.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched",{base_url:me.base_url,container:me.container,expiry:me.expiry})}catch(U){b.log("warn","SCREENSHOT_SAS_FAIL","Screenshot SAS token fetch failed",{error:U instanceof Error?U.message:String(U)})}let re=q?(U,oe,se)=>{lr(b.sessionDir,oe,U,q,(me,Ge,ot,ae)=>b.log(me,Ge,ot,ae),se)}:void 0;if(!process.stdin.isTTY&&!r.agent&&(r.agent=!0),r.agent){let U=le=>{process.stdout.write(JSON.stringify(le)+`
81
- `)},oe=await fi(z,{environment:m,mode:i,log:(le,Ie,qe,gt)=>b.log(le,Ie,qe,gt)},{onStepEnd:re,onStepLog:(le,Ie,qe)=>b.logStep(le,Ie,qe)}),{lastRunEnd:se,stepsTotal:me,hadError:Ge,bifurcationFlows:ot}=oe;if(Ge&&b.escalateRun(0),se){let le=xn(se,0,ot);b.addRunResult(wn(se,n,0,le),se.total_runs)}He("chrome","Agent run completed");let ae;if(b.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 le=ce(m),Ie=l.project_id;if(x.basicAuth){let{UploadPipeline:qe}=await import("./pipeline-QHJGNZ7H.js");q&&await q.drain();let gt=Tn({session:b,env:m,auth:x,variables:ne,variableIds:$,projectId:Ie,folderId:l.folder_id,totalSteps:me,totalDuration:se.duration??0,codeExport:kn({codeExport:r.codeExport,codeLanguage:r.codeLanguage,skipCodeValidation:r.skipCodeValidation},l.code_export),onProgress:()=>{},log:(wr,zt,yr,Bt)=>b.log(wr,zt,yr,Bt)}),ut=await new qe(gt).execute();ut.success&&(ut.testcaseId&&b.setTestcaseId(ut.testcaseId),ut.testcaseId&&ut.shareId&&Ie&&(ae=Ht(le.testManagerUiUrl,Ie,ut.testcaseId,ut.shareId)))}}catch(le){b.log("error","DIRECT_UPLOAD_ERROR","Upload failed in agent mode",{error:le instanceof Error?le.message:String(le)})}if(se){let le={...se};ae&&(le.test_url=ae),U(le)}await b.finish("complete"),se||X(Ge?2:1,"Agent run ended with no result");let ge=se.reason??"";(ge.includes("Cancel")||ge.includes("Timeout"))&&X(3,`Agent run: ${ge}`),se.status==="passed"&&X(0,"Agent run passed"),X(1,"Agent run failed")}let ee=null,Te=0,je=!1,Ce=null,Le={current:null},{waitUntilExit:rt}=gn(pi.default.createElement(di,{config:z,spawnOpts:{environment:m,mode:i,log:(U,oe,se,me)=>b.log(U,oe,se,me)},cancelRef:Le,banner:{model:r.model??l.model,auth:c,status:d},onComplete:U=>{ee=U.lastRunEnd,Te=U.stepsTotal,je=U.hadError,Ce=U.bifurcationFlows},onStepEnd:re}),{stdout:process.stderr,exitOnCtrlC:!1}),pt;if(r.timeout){let U=parseInt(r.timeout,10)*1e3;pt=setTimeout(()=>{console.error(`
82
- Timeout: ${r.timeout}s exceeded \u2014 cancelling...`),Le.current?.()},U)}if(await rt(),pt&&clearTimeout(pt),ee){let U=xn(ee,0,Ce);b.addRunResult(wn(ee,n,0,U),ee.total_runs)}if(He("chrome","Ink run completed"),b.log("info","DIRECT_UPLOAD_START","Starting direct upload (ink mode)",{ink_mode:!0,last_event:!!ee,local:!!r.local}),ee&&!r.local)try{let U=ce(m),oe=l.project_id;if(x.basicAuth){let{UploadPipeline:se}=await import("./pipeline-QHJGNZ7H.js");q&&(b.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot upload queue before pipeline"),await q.drain(),b.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot upload queue drained"));let me=Tn({session:b,env:m,auth:x,variables:ne,variableIds:$,projectId:l.project_id,folderId:l.folder_id,totalSteps:Te,totalDuration:ee.duration??0,codeExport:kn({codeExport:r.codeExport,codeLanguage:r.codeLanguage,skipCodeValidation:r.skipCodeValidation},l.code_export),onProgress:()=>{},log:(ge,le,Ie,qe)=>b.log(ge,le,Ie,qe)}),Ge=new se(me),{renderUploadProgress:ot}=await import("./CliUploadProgress-BSXWFIP5.js"),ae=await ot(Ge,ge=>{if(ge.testcaseId&&ge.shareId&&oe)return Ht(U.testManagerUiUrl,oe,ge.testcaseId,ge.shareId)});if(ae.success){ae.testcaseId&&b.setTestcaseId(ae.testcaseId);let ge=ae.testcaseId&&ae.shareId&&oe?Ht(U.testManagerUiUrl,oe,ae.testcaseId,ae.shareId):void 0,le=ae.testcaseId&&oe?An(U.testManagerUiUrl,oe,ae.testcaseId):void 0;if(ge||le||ae.codeExportDir){let{LinksBox:Ie}=await import("./LinksBox-6CLSLM2A.js"),{render:qe}=await import("./build-JIKYOZUH.js"),gt=await import("./react-QWOAB3TB.js"),{waitUntilExit:Ct}=qe(gt.default.createElement(Ie,{shareableLink:ge,testCaseLink:le,codeExportDir:ae.codeExportDir}),{stdout:process.stderr});await Ct()}}if(b.testId){let{renderFeedbackPrompt:ge}=await import("./CliFeedbackPrompt-V6X2IESW.js"),le=await ge();if(le)try{await gr({tmsBaseUrl:U.tmsBaseUrl,username:x.basicAuth.username,accessKey:x.basicAuth.access_key,testId:b.testId,feedbackType:le,log:(Ie,qe,gt,Ct)=>b.log(Ie,qe,gt,Ct)})}catch(Ie){b.log("warn","FEEDBACK_FAILED","Feedback submission failed",{error:String(Ie)})}}}}catch(U){b.log("error","DIRECT_UPLOAD_FAILED","Direct upload failed (ink mode)",{error:U instanceof Error?U.stack??U.message:String(U)}),console.error(`Upload failed: ${U}`)}await b.finish("complete"),ee||X(je?2:1,"Run ended with no result");let cn=ee.reason??"";(cn.includes("Cancel")||cn.includes("Timeout"))&&X(3,`Run: ${cn}`),ee.status==="passed"&&X(0,"Run passed"),X(1,"Run failed")}catch(o){X(2,`CLI error: ${o instanceof Error?o.message:String(o)}`)}}),e.command("profiles [action] [name]").option("--env <name>","Environment for switch/delete").action(async(n,r,o)=>{let a=new Ne;if(n==="list"||!n&&!process.stdin.isTTY){let d=a.listProfiles();if(d.length===0){console.log("No profiles configured. Run: kane-cli login");return}let m=a.getActiveProfile(),g=a.getDefaultEnv();for(let p of d){let _=p.profile===m&&p.env===g?" (active)":"";console.log(`${p.profile} [${p.env}]${_}`)}return}if(n==="switch"&&r){let d=o?.env??a.getDefaultEnv();a.setActiveProfile(r),a.setDefaultEnv(d),console.log(`Switched to ${r} [${d}]`);return}if(n==="delete"&&r){let d=o?.env??a.getDefaultEnv();a.deleteProfileFull(r,d),console.log(`Deleted profile ${r} [${d}]`);return}process.stdin.isTTY||(console.error("Usage: kane-cli profiles list|switch|delete <name> [--env <env>]"),X(1,"Invalid profiles usage"));let{ProfilesView:l}=await import("./ProfilesView-HEUHISRN.js"),{render:i}=await import("./build-JIKYOZUH.js"),c=await import("./react-QWOAB3TB.js");await new Promise(d=>{let{unmount:m}=i(c.default.createElement(l,{creds:a,onSwitch:(g,p)=>{a.setActiveProfile(g),a.setDefaultEnv(p),console.log(`Switched to ${g} [${p}]`)},onCancel:()=>{m(),d()}}))})}),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"'),X(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"),X(1,"--details exceeds 500 character limit"));let r=new Ne,o=n.env??r.getDefaultEnv(),a=ce(o),l=!1,i=n.username,c=n.accessKey,d;if(n.username&&n.accessKey)l=!0;else{let T=r.resolveAuth();T?.method==="basic"&&(l=!0,i=T.username,c=T.access_key)}if(!l){let{credentials:T}=r.getActiveCredentials();T||(console.error("Not authenticated. Run: kane-cli login"),X(2,"Not authenticated for feedback")),d=T.access_token}let m=async()=>d??null,g=l&&i&&c?{username:i,access_key:c}:null,_=await new mt(a.controllerBaseUrl,m,g).resolve(),x=_?.username??i,C=_?.access_key??c;(!x||!C)&&(console.error(JSON.stringify({error:"Could not resolve TMS credentials"})),X(1,"Could not resolve TMS credentials for feedback"));try{let{TmsClient:T}=await import("./tms-client-VH42IFUF.js"),R=await new T(a.tmsBaseUrl,x,C).submitFeedback({instruction_id:"",test_id:n.testId,feedback_type:n.feedbackType,details:n.details,mode:"agent"});console.log(JSON.stringify(R)),X(0,"Feedback submitted")}catch(T){console.error(JSON.stringify({error:T instanceof Error?T.message:String(T)})),X(1,`Feedback failed: ${T instanceof Error?T.message:String(T)}`)}}),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 Ne,o=n.profile??r.getActiveProfile()??"default",a=n.env??r.getDefaultEnv(),l=ce(a),i=r.loadBasicAuth(o,a),c=null;if(n.username&&n.accessKey)c={username:n.username,accessKey:n.accessKey};else if(i)c={username:i.username,accessKey:i.access_key};else{let d=r.loadCredentials(o,a);d||(console.error(`No credentials for profile "${o}" [${a}]. Run "kane-cli login" first.`),X(2,`No credentials for profile "${o}" [${a}]`)),c=d.access_token}try{let{ControllerClient:d}=await import("./controller-client-7BIK5FYL.js"),g=await new d(l.controllerBaseUrl,c).getCreditBalance();console.log(`Available credits: ${g.available_credits}`),console.log(`Total credits: ${g.total_credits}`),X(0,"Balance retrieved")}catch(d){console.error(`Error: ${d instanceof Error?d.message:String(d)}`),X(1,`Balance check failed: ${d instanceof Error?d.message:String(d)}`)}}),e.command("help").action(()=>{e.help()}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async n=>{let{fetchChangelog:r,formatChangelog:o}=await import("./changelog-L2FNAYGV.js"),a=await r({all:n.all});console.log(o(a))}),e.parse(["node","kane-cli",...s])}function gi(s){let e,t,n,r=[];for(let o=0;o<s.length;o++){let a=s[o];if(a==="--code-export")e=!0;else if(a==="--skip-code-validation")n=!0;else if(a==="--no-skip-code-validation")n=!1;else if(a==="--code-language"){let l=s[o+1];l!==void 0&&(t=l,o++)}else a.startsWith("--code-language=")?t=a.slice(16):r.push(a)}return{codeExport:e,codeLanguage:t,skipCodeValidation:n,filteredArgs:r}}Ss();var bi=Vn().catch(()=>null),br=Qe.argv.slice(2),Xa=br.includes("--dev"),hi=br.includes("--local"),Ya=br.includes("--tui");Xa&&(Qe.env.KANE_DEV_MODE="1");var Qa=br.filter(s=>!["--dev","--local","--tui"].includes(s)),xr=gi(Qa),qt=xr.filteredArgs,vi=xr.codeExport,Ao=xr.codeLanguage,To=xr.skipCodeValidation,_i=()=>{bi.then(s=>{s&&Qe.stderr.write(`
83
- Update available: ${s.current} \u2192 ${s.latest} \u2014 run \`${Jo()}\` to update
80
+ `).action(async(n,r)=>{try{let o=new He,l=new ot().load(),i;if(r.mode===void 0)i=l.mode==="action"?"action":"testing";else if(r.mode==="action"||r.mode==="testing")i=r.mode;else{console.error("Invalid --mode. Must be 'action' or 'testing'."),X(2,"Invalid --mode");return}if(!(r.username&&r.accessKey)){let M=o.getActiveProfile(),ie=o.getDefaultEnv();M&&(o.loadBasicAuth(M,ie)||o.loadCredentials(M,ie))||(console.error("Not authenticated. Run: kane-cli login --oauth, or kane-cli login --username <user> --access-key <key>"),X(1,"Not authenticated"))}let c=`${o.getActiveProfile()??"no profile"}/${o.getDefaultEnv()}`,d=[],m=r.env??o.getDefaultEnv(),g=null,p=[],_=(M,ie,oe,ge)=>{g?g(M,ie,oe,ge):p.push([M,ie,oe,ge])},b;try{b=await br({creds:o,env:m,usernameFlag:r.username,accessKeyFlag:r.accessKey,log:_})}catch(M){throw M instanceof qt&&(console.error(M.code==="not_authenticated"?"Not authenticated. Run: kane-cli login":"Token refresh failed. Run: kane-cli login"),X(2,M.code==="not_authenticated"?"Not authenticated":"Token refresh failed")),M}let E=!!b.basicAuth,A=b.basicAuth?.username,P=b.basicAuth?.access_key,C=b.token,O=b.resolver,te=b.resolvedCreds;b.basicAuth&&d.push(`Auth: ${b.basicAuth.username}`);let Z=mt,ne=fr({objective:n,globalDir:zt(Ee,"variables"),localDir:zt(process.cwd(),".testmuai","variables"),file:r.variablesFile,inline:r.variables,onLoadError:M=>console.error(M)}),_e;if(r.sessionContext)try{_e=JSON.parse(r.sessionContext)}catch{console.error("Invalid --session-context JSON"),X(2,"Invalid --session-context JSON")}let F=r.globalContext??zt(Ee,"global-memory.md"),N=r.localContext??zt(process.cwd(),".testmuai","context.md"),u=an(F),x=an(N),h;try{h=await mi({config:l,startUrl:Z??void 0,headless:r.headless,cft:r.cft,wsEndpoint:r.wsEndpoint,cdpEndpoint:r.cdpEndpoint})}catch(M){console.error(er(M));let ie=M instanceof rn?"Chrome not found at standard paths":`Chrome failed: ${M instanceof Error?M.message:M}`;X(2,ie)}h.instance&&Ge("chrome",()=>{h.instance.kill()});let I=null,B=h.cdpEndpoint??r.cdpEndpoint;B&&!r.cft&&!r.wsEndpoint&&(I=or({headless:r.headless,cdpEndpoint:B}),I&&Ge("marker-overlay",()=>I.kill())),r.cft?d.push("CfT mode: Playwright will manage its own browser"):r.wsEndpoint?d.push(`Playwright WS endpoint (${r.wsEndpoint.slice(0,60)}...)`):r.cdpEndpoint?d.push(`CDP connected (${r.cdpEndpoint})`):h.cdpEndpoint&&d.push(`Chrome ready (${h.cdpEndpoint})`);let D=new bt;D.start({model:r.model??l.model,environment:m,profile:o.getActiveProfile()}),g=(M,ie,oe,ge)=>D.log(M,ie,oe,ge);for(let M of p)D.log(...M);if(p.length=0,b.resolvedCreds){let{createRemoteLogger:M}=await import("./logging-WJPMWUL5.js"),{getMachineId:ie}=await import("./machine-id-DZN4MYOO.js"),oe=M({sessionId:D.sessionId,identity:{org_id:String(b.resolvedCreds.org_id??""),user_id:String(b.resolvedCreds.user_id??""),machine_id:ie()},environment:m,getToken:async()=>b.token});D.setRemoteLogger(oe),oe.start(),Ge("remote-logger",()=>oe.shutdownSync()),Qn(oe)}let J=b.basicAuth&&!r.local?await mr({variables:ne,auth:b.basicAuth,orgId:String(b.resolvedCreds?.org_id??""),env:m,localMode:!!r.local,log:(M,ie,oe,ge)=>D.log(M,ie,oe,ge)}):{};if(D.setAuteurVariables(ne.auteur),D.setFirstRun(n,mt),!r.local&&b.basicAuth&&l.project_id){let M=ae(m),ie=await gr({tmsBaseUrl:M.tmsBaseUrl,auth:b.basicAuth,objective:n,url:mt,projectId:l.project_id,folderId:l.folder_id??"",hasCustomProfile:!!l.chrome_profile_path,log:(oe,ge,ue,Ue)=>D.log(oe,ge,ue,Ue)});ie&&D.setTestId(ie)}let re=pr({objective:ne.auteurObjective,url:Z??void 0,model:r.model??l.model,chrome:h,auth:b,sessionId:D.sessionId,runIndex:0,windowSize:l.window_size,maxSteps:parseInt(r.maxSteps,10),headless:r.headless,disableAskUser:!process.stdin.isTTY,enableTaskSkills:r.taskSkills,variables:Object.keys(ne.auteur).length>0?ne.auteur:void 0,globalContext:u??void 0,localContext:x??void 0,sessionContext:_e}),ee=null;if(!r.local)try{let{ControllerClient:M}=await import("./controller-client-7BIK5FYL.js"),ie;if(E&&A&&P)ie={username:A,accessKey:P};else if(C)ie=C;else throw new Error("No auth available");let ge=await new M(ae(m).controllerBaseUrl,ie).getScreenshotSas();D.setScreenshotSas(ge),ee=new ln(ge,3,(ue,Ue,ce,Ae)=>D.log(ue,Ue,ce,Ae)),D.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched",{base_url:ge.base_url,container:ge.container,expiry:ge.expiry})}catch(M){D.log("warn","SCREENSHOT_SAS_FAIL","Screenshot SAS token fetch failed",{error:M instanceof Error?M.message:String(M)})}let Ie=ee?(M,ie,oe)=>{cr(D.sessionDir,ie,M,ee,(ge,ue,Ue,ce)=>D.log(ge,ue,Ue,ce),oe)}:void 0;if(!process.stdin.isTTY&&!r.agent&&(r.agent=!0),r.agent){let M=de=>{process.stdout.write(JSON.stringify(de)+`
81
+ `)};I?.setRunActive(!0);let ie;try{ie=await fi(re,{environment:m,mode:i,log:(de,Oe,Me,dt)=>D.log(de,Oe,Me,dt)},{onStepEnd:Ie,onStepLog:(de,Oe,Me)=>D.logStep(de,Oe,Me)})}finally{I?.setRunActive(!1)}let{lastRunEnd:oe,stepsTotal:ge,hadError:ue,bifurcationFlows:Ue}=ie;if(ue&&D.escalateRun(0),oe){let de=xn(oe,0,Ue);D.addRunResult(wn(oe,n,0,de),oe.total_runs)}qe("chrome","Agent run completed");let ce;if(D.log("info","DIRECT_UPLOAD_START","Starting direct upload (agent mode)",{agent_mode:!0,last_run_end:!!oe,local:!!r.local}),oe&&!r.local)try{let de=ae(m),Oe=l.project_id;if(b.basicAuth){let{UploadPipeline:Me}=await import("./pipeline-ZSNZGJIH.js");ee&&await ee.drain();let dt=Tn({session:D,env:m,auth:b,variables:ne,variableIds:J,projectId:Oe,folderId:l.folder_id,totalSteps:ge,totalDuration:oe.duration??0,codeExport:kn({codeExport:r.codeExport,codeLanguage:r.codeLanguage,skipCodeValidation:r.skipCodeValidation},l.code_export),onProgress:()=>{},log:(Sr,Vt,Ft,be)=>D.log(Sr,Vt,Ft,be)}),tt=await new Me(dt).execute();tt.success&&(tt.testcaseId&&D.setTestcaseId(tt.testcaseId),tt.testcaseId&&tt.shareId&&Oe&&(ce=Kt(de.testManagerUiUrl,Oe,tt.testcaseId,tt.shareId)))}}catch(de){D.log("error","DIRECT_UPLOAD_ERROR","Upload failed in agent mode",{error:de instanceof Error?de.message:String(de)})}if(oe){let de={...oe};ce&&(de.test_url=ce),M(de)}await D.finish("complete"),oe||X(ue?2:1,"Agent run ended with no result");let Ae=oe.reason??"";(Ae.includes("Cancel")||Ae.includes("Timeout"))&&X(3,`Agent run: ${Ae}`),oe.status==="passed"&&X(0,"Agent run passed"),X(1,"Agent run failed")}let me=null,Re=0,$e=!1,et=null,Et={current:null},{waitUntilExit:yr}=gn(pi.default.createElement(di,{config:re,spawnOpts:{environment:m,mode:i,log:(M,ie,oe,ge)=>D.log(M,ie,oe,ge)},cancelRef:Et,banner:{model:r.model??l.model,auth:c,status:d},onComplete:M=>{me=M.lastRunEnd,Re=M.stepsTotal,$e=M.hadError,et=M.bifurcationFlows},onStepEnd:Ie}),{stdout:process.stderr,exitOnCtrlC:!1}),$t;if(r.timeout){let M=parseInt(r.timeout,10)*1e3;$t=setTimeout(()=>{console.error(`
82
+ Timeout: ${r.timeout}s exceeded \u2014 cancelling...`),Et.current?.()},M)}I?.setRunActive(!0);try{await yr()}finally{I?.setRunActive(!1)}if($t&&clearTimeout($t),me){let M=xn(me,0,et);D.addRunResult(wn(me,n,0,M),me.total_runs)}if(qe("chrome","Ink run completed"),D.log("info","DIRECT_UPLOAD_START","Starting direct upload (ink mode)",{ink_mode:!0,last_event:!!me,local:!!r.local}),me&&!r.local)try{let M=ae(m),ie=l.project_id;if(b.basicAuth){let{UploadPipeline:oe}=await import("./pipeline-ZSNZGJIH.js");ee&&(D.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot upload queue before pipeline"),await ee.drain(),D.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot upload queue drained"));let ge=Tn({session:D,env:m,auth:b,variables:ne,variableIds:J,projectId:l.project_id,folderId:l.folder_id,totalSteps:Re,totalDuration:me.duration??0,codeExport:kn({codeExport:r.codeExport,codeLanguage:r.codeLanguage,skipCodeValidation:r.skipCodeValidation},l.code_export),onProgress:()=>{},log:(Ae,de,Oe,Me)=>D.log(Ae,de,Oe,Me)}),ue=new oe(ge),{renderUploadProgress:Ue}=await import("./CliUploadProgress-ZVRZFMGT.js"),ce=await Ue(ue,Ae=>{if(Ae.testcaseId&&Ae.shareId&&ie)return Kt(M.testManagerUiUrl,ie,Ae.testcaseId,Ae.shareId)});if(ce.success){ce.testcaseId&&D.setTestcaseId(ce.testcaseId);let Ae=ce.testcaseId&&ce.shareId&&ie?Kt(M.testManagerUiUrl,ie,ce.testcaseId,ce.shareId):void 0,de=ce.testcaseId&&ie?An(M.testManagerUiUrl,ie,ce.testcaseId):void 0;if(Ae||de||ce.codeExportDir){let{LinksBox:Oe}=await import("./LinksBox-FR4WLNX4.js"),{render:Me}=await import("./build-JIKYOZUH.js"),dt=await import("./react-QWOAB3TB.js"),{waitUntilExit:Xt}=Me(dt.default.createElement(Oe,{shareableLink:Ae,testCaseLink:de,codeExportDir:ce.codeExportDir}),{stdout:process.stderr});await Xt()}}if(D.testId){let{renderFeedbackPrompt:Ae}=await import("./CliFeedbackPrompt-CKWGADHU.js"),de=await Ae();if(de)try{await hr({tmsBaseUrl:M.tmsBaseUrl,username:b.basicAuth.username,accessKey:b.basicAuth.access_key,testId:D.testId,feedbackType:de,log:(Oe,Me,dt,Xt)=>D.log(Oe,Me,dt,Xt)})}catch(Oe){D.log("warn","FEEDBACK_FAILED","Feedback submission failed",{error:String(Oe)})}}}}catch(M){D.log("error","DIRECT_UPLOAD_FAILED","Direct upload failed (ink mode)",{error:M instanceof Error?M.stack??M.message:String(M)}),console.error(`Upload failed: ${M}`)}await D.finish("complete"),me||X($e?2:1,"Run ended with no result");let Bt=me.reason??"";(Bt.includes("Cancel")||Bt.includes("Timeout"))&&X(3,`Run: ${Bt}`),me.status==="passed"&&X(0,"Run passed"),X(1,"Run failed")}catch(o){X(2,`CLI error: ${o instanceof Error?o.message:String(o)}`)}}),e.command("profiles [action] [name]").option("--env <name>","Environment for switch/delete").action(async(n,r,o)=>{let a=new He;if(n==="list"||!n&&!process.stdin.isTTY){let d=a.listProfiles();if(d.length===0){console.log("No profiles configured. Run: kane-cli login");return}let m=a.getActiveProfile(),g=a.getDefaultEnv();for(let p of d){let _=p.profile===m&&p.env===g?" (active)":"";console.log(`${p.profile} [${p.env}]${_}`)}return}if(n==="switch"&&r){let d=o?.env??a.getDefaultEnv();a.setActiveProfile(r),a.setDefaultEnv(d),console.log(`Switched to ${r} [${d}]`);return}if(n==="delete"&&r){let d=o?.env??a.getDefaultEnv();a.deleteProfileFull(r,d),console.log(`Deleted profile ${r} [${d}]`);return}process.stdin.isTTY||(console.error("Usage: kane-cli profiles list|switch|delete <name> [--env <env>]"),X(1,"Invalid profiles usage"));let{ProfilesView:l}=await import("./ProfilesView-ENBYW7PJ.js"),{render:i}=await import("./build-JIKYOZUH.js"),c=await import("./react-QWOAB3TB.js");await new Promise(d=>{let{unmount:m}=i(c.default.createElement(l,{creds:a,onSwitch:(g,p)=>{a.setActiveProfile(g),a.setDefaultEnv(p),console.log(`Switched to ${g} [${p}]`)},onCancel:()=>{m(),d()}}))})}),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"'),X(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"),X(1,"--details exceeds 500 character limit"));let r=new He,o=n.env??r.getDefaultEnv(),a=ae(o),l=!1,i=n.username,c=n.accessKey,d;if(n.username&&n.accessKey)l=!0;else{let A=r.resolveAuth();A?.method==="basic"&&(l=!0,i=A.username,c=A.access_key)}if(!l){let{credentials:A}=r.getActiveCredentials();A||(console.error("Not authenticated. Run: kane-cli login"),X(2,"Not authenticated for feedback")),d=A.access_token}let m=async()=>d??null,g=l&&i&&c?{username:i,access_key:c}:null,_=await new pt(a.controllerBaseUrl,m,g).resolve(),b=_?.username??i,E=_?.access_key??c;(!b||!E)&&(console.error(JSON.stringify({error:"Could not resolve TMS credentials"})),X(1,"Could not resolve TMS credentials for feedback"));try{let{TmsClient:A}=await import("./tms-client-VH42IFUF.js"),C=await new A(a.tmsBaseUrl,b,E).submitFeedback({instruction_id:"",test_id:n.testId,feedback_type:n.feedbackType,details:n.details,mode:"agent"});console.log(JSON.stringify(C)),X(0,"Feedback submitted")}catch(A){console.error(JSON.stringify({error:A instanceof Error?A.message:String(A)})),X(1,`Feedback failed: ${A instanceof Error?A.message:String(A)}`)}}),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 He,o=n.profile??r.getActiveProfile()??"default",a=n.env??r.getDefaultEnv(),l=ae(a),i=r.loadBasicAuth(o,a),c=null;if(n.username&&n.accessKey)c={username:n.username,accessKey:n.accessKey};else if(i)c={username:i.username,accessKey:i.access_key};else{let d=r.loadCredentials(o,a);d||(console.error(`No credentials for profile "${o}" [${a}]. Run "kane-cli login" first.`),X(2,`No credentials for profile "${o}" [${a}]`)),c=d.access_token}try{let{ControllerClient:d}=await import("./controller-client-7BIK5FYL.js"),g=await new d(l.controllerBaseUrl,c).getCreditBalance();console.log(`Available credits: ${g.available_credits}`),console.log(`Total credits: ${g.total_credits}`),X(0,"Balance retrieved")}catch(d){console.error(`Error: ${d instanceof Error?d.message:String(d)}`),X(1,`Balance check failed: ${d instanceof Error?d.message:String(d)}`)}}),e.command("help").action(()=>{e.help()}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async n=>{let{fetchChangelog:r,formatChangelog:o}=await import("./changelog-DFV22SXX.js"),a=await r({all:n.all});console.log(o(a))}),e.parse(["node","kane-cli",...s])}function gi(s){let e,t,n,r=[];for(let o=0;o<s.length;o++){let a=s[o];if(a==="--code-export")e=!0;else if(a==="--skip-code-validation")n=!0;else if(a==="--no-skip-code-validation")n=!1;else if(a==="--code-language"){let l=s[o+1];l!==void 0&&(t=l,o++)}else a.startsWith("--code-language=")?t=a.slice(16):r.push(a)}return{codeExport:e,codeLanguage:t,skipCodeValidation:n,filteredArgs:r}}Es();var bi=Vn().catch(()=>null),xr=Ze.argv.slice(2),Xa=xr.includes("--dev"),hi=xr.includes("--local"),Ya=xr.includes("--tui");Xa&&(Ze.env.KANE_DEV_MODE="1");var Qa=xr.filter(s=>!["--dev","--local","--tui"].includes(s)),wr=gi(Qa),Jt=wr.filteredArgs,vi=wr.codeExport,To=wr.codeLanguage,ko=wr.skipCodeValidation,_i=()=>{bi.then(s=>{s&&Ze.stderr.write(`
83
+ Update available: ${s.current} \u2192 ${s.latest} \u2014 run \`${Xo()}\` to update
84
84
 
85
- `)})},Za=qt[0]==="--help"||qt[0]==="-h";if(Za)Pn(qt);else if(Ya){Qe.stdin.isTTY||(Qe.stderr.write(`Error: --tui mode requires an interactive terminal (TTY).
86
- `),Qe.exit(1)),_i();let{waitUntilExit:s,unmount:e}=gn(ko.default.createElement(qs,{localMode:hi,codeExport:vi,codeLanguage:Ao,skipCodeValidation:To,updatePromise:bi}),{exitOnCtrlC:!1});oo(()=>e()),so(()=>{try{Qe.stdin.setRawMode?.(!1)}catch{}Qe.stdout.write("\x1B[?25h")}),s().then(()=>{X(0,"TUI session ended")})}else if(qt.length>0){let s=new Set(["login","logout","whoami","config","run","profiles","feedback","balance","help","update","changelog","setup"]),e=qt[0],t=s.has(e),n=e.startsWith("-");_i(),t||n?Pn(qt):Pn(["run",...qt])}else{Qe.stdin.isTTY||(Qe.stderr.write(`Error: kane-cli requires an interactive terminal (TTY) when run without arguments.
85
+ `)})},Za=Jt[0]==="--help"||Jt[0]==="-h";if(Za)Pn(Jt);else if(Ya){Ze.stdin.isTTY||(Ze.stderr.write(`Error: --tui mode requires an interactive terminal (TTY).
86
+ `),Ze.exit(1)),_i();let{waitUntilExit:s,unmount:e}=gn(Io.default.createElement(qs,{localMode:hi,codeExport:vi,codeLanguage:To,skipCodeValidation:ko,updatePromise:bi}),{exitOnCtrlC:!1});so(()=>e()),io(()=>{try{Ze.stdin.setRawMode?.(!1)}catch{}Ze.stdout.write("\x1B[?25h")}),s().then(()=>{X(0,"TUI session ended")})}else if(Jt.length>0){let s=new Set(["login","logout","whoami","config","run","profiles","feedback","balance","help","update","changelog","setup"]),e=Jt[0],t=s.has(e),n=e.startsWith("-");_i(),t||n?Pn(Jt):Pn(["run",...Jt])}else{Ze.stdin.isTTY||(Ze.stderr.write(`Error: kane-cli requires an interactive terminal (TTY) when run without arguments.
87
87
  Usage: kane-cli "objective" for non-interactive mode.
88
- `),Qe.exit(1));let s={current:null},{waitUntilExit:e,unmount:t}=gn(ko.default.createElement(zs,{resultRef:s}),{exitOnCtrlC:!1});oo(()=>t()),so(()=>{try{Qe.stdin.setRawMode?.(!1)}catch{}Qe.stdout.write("\x1B[?25h")}),e().then(()=>{let n=s.current;if(!n){X(0,"Single-shot session ended (no objective)");return}let r=["run",n.objective];hi&&r.push("--local"),vi&&r.push("--code-export"),Ao&&r.push("--code-language",Ao),To===!0&&r.push("--skip-code-validation"),To===!1&&r.push("--no-skip-code-validation"),Pn(r)})}
88
+ `),Ze.exit(1));let s={current:null},{waitUntilExit:e,unmount:t}=gn(Io.default.createElement(zs,{resultRef:s}),{exitOnCtrlC:!1});so(()=>t()),io(()=>{try{Ze.stdin.setRawMode?.(!1)}catch{}Ze.stdout.write("\x1B[?25h")}),e().then(()=>{let n=s.current;if(!n){X(0,"Single-shot session ended (no objective)");return}let r=["run",n.objective];hi&&r.push("--local"),vi&&r.push("--code-export"),To&&r.push("--code-language",To),ko===!0&&r.push("--skip-code-validation"),ko===!1&&r.push("--no-skip-code-validation"),Pn(r)})}