@testmuai/kane-cli 0.2.8 → 0.2.9
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.
- package/dist/{ChromeProfilePicker-GJA52BNZ.js → ChromeProfilePicker-ZDIWVMLR.js} +1 -1
- package/dist/{CliFeedbackPrompt-4OSH6D53.js → CliFeedbackPrompt-V6X2IESW.js} +1 -1
- package/dist/{CliUploadProgress-UORYVN7R.js → CliUploadProgress-BSXWFIP5.js} +1 -1
- package/dist/{ConfigView-DHYUHQTK.js → ConfigView-53QUJ3UT.js} +1 -1
- package/dist/{FolderPicker-TXCV7G4Y.js → FolderPicker-BHEDYLKA.js} +1 -1
- package/dist/{HelpView-64BD2OKB.js → HelpView-ZR5EXR7F.js} +1 -1
- package/dist/{LinksBox-DNJBK25G.js → LinksBox-6CLSLM2A.js} +1 -1
- package/dist/{LoginWizard-X5DLBHLV.js → LoginWizard-NJA5AAYO.js} +1 -1
- package/dist/{ProfilesView-N4G4L2VO.js → ProfilesView-HEUHISRN.js} +1 -1
- package/dist/{ProjectPicker-XL67H337.js → ProjectPicker-YZZUJDOQ.js} +1 -1
- package/dist/{WhoamiView-JYNYZVTK.js → WhoamiView-AXPRRGNG.js} +1 -1
- package/dist/{changelog-IPUSJH3G.js → changelog-L2FNAYGV.js} +1 -1
- package/dist/{chunk-CLF6GATH.js → chunk-2ATFRKHW.js} +1 -1
- package/dist/{chunk-MYZUROOZ.js → chunk-4HQOC372.js} +1 -1
- package/dist/{chunk-DSCYZSVU.js → chunk-4RVMT7O2.js} +1 -1
- package/dist/{chunk-GCZ4YXN4.js → chunk-56DFEK7K.js} +1 -1
- package/dist/{chunk-MJYMADLM.js → chunk-BTLH2ZWO.js} +1 -1
- package/dist/{chunk-M7JR2ZX5.js → chunk-BXWE7UO7.js} +1 -1
- package/dist/{chunk-BCTJUECQ.js → chunk-C7FS7B4O.js} +1 -1
- package/dist/{chunk-LDQZDX3F.js → chunk-CUBXICTI.js} +1 -1
- package/dist/{chunk-E4454TNP.js → chunk-DGFG2WJH.js} +1 -1
- package/dist/chunk-EOOULVWR.js +2 -0
- package/dist/{chunk-YXQQ33RG.js → chunk-GIXIZJ6Y.js} +1 -1
- package/dist/{chunk-U3KZXIN2.js → chunk-QX4WHNRG.js} +1 -1
- package/dist/{chunk-UL7ZRTTG.js → chunk-RTOXLI4C.js} +1 -1
- package/dist/{chunk-LACJLE5X.js → chunk-TV6MHKZV.js} +1 -1
- package/dist/{chunk-KEU7JQAB.js → chunk-YLC6PSJZ.js} +1 -1
- package/dist/index.js +46 -49
- package/dist/{logging-32VNKE6C.js → logging-R5263ZJZ.js} +1 -1
- package/dist/login-flow-J5AIWRWS.js +2 -0
- package/dist/version-check-NUVM7TOP.js +2 -0
- package/package.json +5 -5
- package/dist/chunk-RWLPN2OC.js +0 -2
- package/dist/login-flow-TNDBDANY.js +0 -2
- package/dist/updater-VR2G73FF.js +0 -2
- package/dist/version-check-RN63L7BF.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
|
|
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(
|
|
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(`
|
|
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((
|
|
9
|
-
`?"":(C>0?d:"")+
|
|
10
|
-
`)}};
|
|
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?`
|
|
11
11
|
(Did you mean one of ${n.join(", ")}?)`:n.length===1?`
|
|
12
|
-
(Did you mean ${n[0]}?)`:""}
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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)
|
|
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}
|
|
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
|
|
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=>
|
|
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.
|
|
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
|
|
25
|
-
`)}catch{}}};function Nn(s){let e=(0,Zo.useRef)(null);return e.current||(e.current=new Nr(s)),e.current}var Ft=M(De(),1);var hn=[[[" "],[" "],[" "],[" "],["\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=M(Q(),1),Mn="#af87d7",Mr="#875faf",es="#5b3a7a",Vi="#ff9500",Ui="#ea580c";var Hr="#666666",Fi="#555555",Ut=[[Mn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Mn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Mn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Mn,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\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,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \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,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\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,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588"]],Wr=Ut.map(([,s])=>[...s]);function ts({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=Wr[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&&Wr[r-1][l-1]==="\u2588";return i||c?(0,ie.jsx)(f,{color:es,children:"\u2592"},l):(0,ie.jsx)(f,{children:" "},l)})},r)}),e>=Ut.length&&(0,ie.jsxs)(f,{children:[" ",Wr[Ut.length-1].map((t,n)=>t==="\u2588"?(0,ie.jsx)(f,{color:es,children:"\u2580"},n):(0,ie.jsx)(f,{children:" "},n))]})]})}function Ni({visibleRows:s=hn.length}){let e=Math.min(s,hn.length);return(0,ie.jsx)(S,{flexDirection:"column",children:hn.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 Hn({size:s="compact",helmetVisibleRows:e=hn.length,textVisibleRows:t=Ut.length,showMeta:n=!1,user:r=null,authenticated:o=!1,version:a=""}){return s==="compact"?(0,ie.jsx)(ts,{}):(0,ie.jsxs)(S,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,ie.jsx)(f,{color:Vi,italic:!0,children:" Welcome to"}),(0,ie.jsx)(f,{children:" "}),(0,ie.jsxs)(S,{gap:2,children:[(0,ie.jsx)(Ni,{visibleRows:e}),(0,ie.jsxs)(S,{flexDirection:"column",children:[(0,ie.jsx)(ts,{visibleRows:t}),(0,ie.jsx)(S,{justifyContent:"flex-end",width:73,children:(0,ie.jsx)(f,{color:Ui,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:Hr,children:" Browser automation powered by AI. "}),(0,ie.jsx)(f,{color:Fi,children:`v${a}`})]}),(0,ie.jsx)(f,{children:" "}),(0,ie.jsx)(f,{children:(0,ie.jsx)(f,{color:Hr,children:" KaneCLI can navigate websites, fill forms, test web UI, and extract"})}),(0,ie.jsx)(f,{children:(0,ie.jsx)(f,{color:Hr,children:" data \u2014 right from your terminal."})}),(0,ie.jsx)(f,{children:" "})]})]})}var qr=M(Q(),1),Kr=8,Gr=7;function ns({onComplete:s}){let[e,t]=(0,Ft.useState)(0),[n,r]=(0,Ft.useState)(0),[o,a]=(0,Ft.useState)(!1),[l]=(0,Ft.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(Kr,i+1))},e<Kr?60:null),kt(()=>{r(i=>Math.min(Gr,i+1))},n<Gr?80:null),(0,Ft.useEffect)(()=>{e>=Kr&&n>=Gr&&!o&&(a(!0),s?.())},[e,n,o,s]),(0,qr.jsx)(S,{flexDirection:"column",children:(0,qr.jsx)(Hn,{size:"full",helmetVisibleRows:e,textVisibleRows:n,showMeta:o,user:l.user,authenticated:l.authenticated,version:ht})})}var vt=M(Q(),1);function rs({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=M(De(),1);var zr=M(De(),1);var ct=M(Q(),1);function os({history:s,onSelect:e,onClose:t}){let[n,r]=(0,zr.useState)(""),[o,a]=(0,zr.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)(S,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,ct.jsx)(f,{color:v.muted,bold:!0,children:"reverse search"}),(0,ct.jsxs)(S,{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)(S,{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=M(Q(),1);function ss({commands:s,selectedIndex:e}){return s.length===0?null:(0,Pt.jsx)(S,{flexDirection:"column",marginBottom:0,children:s.map((t,n)=>{let r=n===e;return(0,Pt.jsxs)(S,{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=M(Q(),1);function Wn({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)(""),[_,y]=(0,_t.useState)(!0),{stdout:C}=At(),T=C?.columns??80,[P,R]=(0,_t.useState)(0),O=o.join(""),oe=(()=>{if(c!=="none"||o.length===0)return"";if(O.startsWith("/")&&r&&O.length>=2){let w=O.slice(1).toLowerCase(),h=r.find(x=>x.name.startsWith(w)&&x.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""})(),te=(()=>{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))})(),ae=te.length>0&&O.startsWith("/");je((u,w)=>{if(_&&u&&y(!1),w.return){if(ae&&te[P]){let h=`/${te[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="",y(!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(oe){let h=O+oe;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 x=[...o.slice(0,h),...o.slice(l)];a(x),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&&oe){let h=O+oe;a([...h]),i(h.length)}else i(h=>Math.min(o.length,h+1));return}if(w.upArrow){if(ae){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 x=h[h.length-1];a([...x]),i(x.length)}else if(m>0){let x=m-1;g(x);let L=h[x];a([...L]),i(L.length)}}return}if(w.downArrow){if(ae){R(h=>Math.min(te.length-1,h+1));return}if(c==="none"){let h=t.getAll();if(m===-1)return;if(m<h.length-1){let x=m+1;g(x);let L=h[x];a([...L]),i(L.length)}else{g(-1);let x=p.current;a([...x]),i(x.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 fe=u=>{a([...u]),i(u.length),d("none")},N=()=>{d("none")},B=(()=>{if(_&&o.length===0)return null;let u=l>=o.length,w=o.slice(0,l).join(""),h=u?" ":o[l],x=u?"":o.slice(l+1).join(""),L="\u276F "+w+h+x+oe,z=2,J=z+w.length,se=J+1,X=se+x.length,ye=L.length,he=Math.max(1,Math.ceil(ye/T)),Ae=[];for(let st=0;st<he;st++)Ae.push({start:st*T,end:Math.min((st+1)*T,ye)});return{full:L,p:z,b:J,c:se,a:X,lines:Ae}})();return(0,Be.jsxs)(S,{flexDirection:"column",children:[c==="search"&&(0,Be.jsx)(os,{history:t,onSelect:fe,onClose:N}),ae&&(0,Be.jsx)(ss,{commands:te,selectedIndex:P}),(0,Be.jsx)(f,{color:v.muted,children:"\u2500".repeat(T)}),B===null?(0,Be.jsxs)(S,{children:[(0,Be.jsx)(f,{color:v.purple,children:"\u276F "}),(0,Be.jsx)(f,{color:v.dimmed,children:n})]}):(0,Be.jsx)(S,{flexDirection:"column",children:B.lines.map(({start:u,end:w},h)=>{let{full:x,p:L,b:z,c:J,a:se}=B,X=[];return w>0&&u<L&&X.push((0,Be.jsx)(f,{color:v.purple,children:x.slice(Math.max(u,0),Math.min(L,w))},"p")),w>L&&u<z&&X.push((0,Be.jsx)(f,{children:x.slice(Math.max(L,u),Math.min(z,w))},"b")),w>z&&u<J&&X.push((0,Be.jsx)(f,{color:v.purple,inverse:!0,children:x.slice(Math.max(z,u),Math.min(J,w))},"c")),w>J&&u<se&&X.push((0,Be.jsx)(f,{children:x.slice(Math.max(J,u),Math.min(se,w))},"a")),w>se&&X.push((0,Be.jsx)(f,{color:v.dimmed,children:x.slice(Math.max(se,u),w)},"g")),(0,Be.jsx)(S,{children:X},h)})})]})}var Te=M(De(),1);var as=M(De(),1);var Kn=M(Q(),1),Mi="#ffc580",Hi="#ffd9a8",is="#ffffff";function ls({text:s,active:e=!0}){let[t,n]=(0,as.useState)(0),r=4;if(kt(()=>{n(a=>(a+1)%(s.length+r*2))},e?80:null),!e)return(0,Kn.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=Mi:c<=r?d=Hi:d=is,(0,Kn.jsx)(f,{color:d,children:a},l)});return(0,Kn.jsx)(f,{children:o})}var Me=M(Q(),1),Wi={starting:v.cyan,running:v.purple,passed:v.green,failed:v.red,cancelled:v.dimmed,timed_out:v.yellow};function Gn({currentStep:s,maxSteps:e,elapsed:t,status:n}){let{stdout:r}=At(),o=r?.columns??80,a=Wi[n]??v.purple,l=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,Me.jsxs)(S,{flexDirection:"column",marginTop:1,children:[(0,Me.jsx)(f,{color:v.muted,children:"\u2500".repeat(Math.min(o,60))}),(0,Me.jsxs)(S,{children:[(0,Me.jsx)(f,{children:" "}),(0,Me.jsx)(f,{color:v.dimmed,children:"Steps "}),(0,Me.jsx)(f,{bold:!0,children:s}),(0,Me.jsxs)(f,{color:v.dimmed,children:["/",e]}),(0,Me.jsx)(f,{children:" "}),(0,Me.jsx)(f,{color:v.dimmed,children:"Elapsed "}),(0,Me.jsx)(f,{bold:!0,children:l}),(0,Me.jsx)(f,{children:" "}),(0,Me.jsx)(f,{color:v.dimmed,children:"Status "}),(0,Me.jsx)(f,{bold:!0,color:a,children:n})]})]})}var Ki={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 Ki[s]??"\u25CF"}var Ot=M(Q(),1);function Jr({steps:s,flows:e,cmInitCounts:t,renderStep:n}){return(0,Ot.jsxs)(S,{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)(S,{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 U=M(Q(),1);function nt({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,U.jsxs)(S,{flexDirection:"column",children:[(0,U.jsxs)(S,{marginLeft:e,children:[(0,U.jsx)(S,{width:4,children:(0,U.jsxs)(f,{color:v.muted,children:[String(s.index).padStart(2," ")," "]})}),(0,U.jsx)(S,{width:3,children:n?(0,U.jsx)(Mo,{}):r?(0,U.jsx)(f,{color:v.green,bold:!0,children:"\u2713"}):o?(0,U.jsx)(f,{color:v.red,bold:!0,children:"\u2717"}):(0,U.jsx)(f,{color:v.muted,children:"\u25CB"})}),(0,U.jsx)(S,{flexGrow:1,children:n?(0,U.jsx)(ls,{text:m,active:!0}):o?(0,U.jsx)(f,{color:v.red,children:m}):a?(0,U.jsx)(f,{color:v.dimmed,children:m}):(0,U.jsx)(f,{color:v.greenDim,children:m})}),(r||o)&&t?(0,U.jsx)(S,{width:3,marginLeft:1,children:(0,U.jsx)(f,{color:v.muted,children:t})}):(0,U.jsx)(S,{width:3,marginLeft:1}),(0,U.jsx)(S,{width:7,justifyContent:"flex-end",children:(0,U.jsx)(f,{color:v.dimmed,children:p})})]}),s.children&&s.children.length>0&&(0,U.jsx)(S,{flexDirection:"column",children:s.children.map((_,y)=>(0,U.jsx)(nt,{step:_,indent:e+2},`child-${y}`))})]})}function qn({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"),y=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":y?P="failed":P="passed";let R=(0,Te.useRef)(null),[O,oe]=(0,Te.useState)(0);(0,Te.useEffect)(()=>{p.length===0||C?(R.current=null,oe(0)):_&&R.current==null&&(R.current=Date.now())},[_,C,p.length]),(0,Te.useEffect)(()=>{if(!_)return;let u=setInterval(()=>{R.current!=null&&oe((Date.now()-R.current)/1e3)},500);return()=>clearInterval(u)},[_]);let te=(0,Te.useRef)(new Set),[ae,fe]=(0,Te.useState)([]),N=(0,Te.useRef)(!1);(0,Te.useEffect)(()=>{if(!o||e)return;let u=[];if(!e&&!N.current&&n&&n[0]!=null&&(N.current=!0,n[0]>0&&u.push({key:"cm_init_0",type:"cm_init",count:n[0]})),e){!te.current.has(-1)&&s.length>0&&(te.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],x=-(w+10);te.current.has(x)||(te.current.add(x),u.push({key:`flow_header_${w}`,type:"flow_header",flowIdx:w,label:t?.[w]??h.objective,cmCount:n?.[w]}));for(let L of h.children??[])(L.status==="passed"||L.status==="failed")&&!te.current.has(L.index)&&(te.current.add(L.index),u.push({key:`step_f${w}_${L.index}`,type:"step",step:{...L}}))}}else for(let w of s)(w.status==="passed"||w.status==="failed")&&!te.current.has(w.index)&&(te.current.add(w.index),u.push({key:`step_${w.index}`,type:"step",step:{...w,children:w.children?[...w.children]:void 0}}));u.length>0&&fe(w=>[...w,...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,U.jsx)(S,{marginLeft:2,children:(0,U.jsxs)(f,{color:v.dimmed,children:["\u25A0 Generated task with ",n[0]," checkpoints"]})}))),e&&t&&!i.current&&(i.current=!0,a((0,U.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 x=w.children??[];return!c.current.has(h)&&x.length>0&&(c.current.add(h),a((0,U.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,U.jsx)(S,{marginLeft:2,children:(0,U.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,U.jsx)(S,{marginLeft:2,children:(0,U.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",n[h]," checkpoints"]})}))),x});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,U.jsx)(S,{marginLeft:2,children:(0,U.jsx)(nt,{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,U.jsx)(S,{marginLeft:2,children:(0,U.jsx)(nt,{step:{...u,children:void 0}})})));for(let x of u.children??[]){let L=`child-${u.index}-${x.index}-${x.objective}`;l.current.has(L)||(x.status==="passed"||x.status==="failed"||x.status==="stopped")&&(l.current.add(L),a((0,U.jsx)(S,{marginLeft:4,children:(0,U.jsx)(nt,{step:x})})))}!h&&!l.current.has(w)&&(u.status==="passed"||u.status==="failed"||u.status==="stopped")&&(l.current.add(w),a((0,U.jsx)(S,{marginLeft:2,children:(0,U.jsx)(nt,{step:{...u,children:void 0}})})))}},[s,a,e,t,n]);let B=[];if(a)if(e)for(let u of s){let h=(u.children??[]).filter(x=>{let L=`${x.index}-${x.objective}`;return!l.current.has(L)});h.length>0&&B.push({...u,children:h})}else for(let u of s){let w=`${u.index}-${u.objective}`,h=l.current.has(w),x=(u.children??[]).filter(L=>{let z=`child-${u.index}-${L.index}-${L.objective}`;return!l.current.has(z)});h?x.length>0&&B.push({...u,children:x}):B.push({...u,children:x})}else if(o){if(!e)for(let u of s)te.current.has(u.index)||B.push(u)}if(!o){let u=a?B:s;return(0,U.jsxs)(S,{flexDirection:"column",children:[e?a?u.length>0?(0,U.jsx)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:u.map((h,x)=>(0,U.jsx)(S,{flexDirection:"column",marginTop:x>0?1:0,children:h.children&&h.children.length>0?h.children.map(L=>(0,U.jsx)(nt,{step:L},`f${x}-${L.index}`)):h.status==="pending"&&(0,U.jsx)(f,{color:v.dimmed,children:" \u25CB Waiting..."})},x))}):null:(0,U.jsx)(Jr,{steps:s,flows:t,cmInitCounts:n,renderStep:(h,x)=>(0,U.jsx)(nt,{step:h},x)}):(0,U.jsxs)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&n&&n[0]!=null&&(0,U.jsxs)(f,{color:v.dimmed,children:["\u25AA Generated task with ",n[0]," checkpoints"]}),u.map(h=>{let x=`${h.index}-${h.objective}`;return a&&l.current.has(x)?(0,U.jsx)(S,{flexDirection:"column",children:(h.children??[]).map(L=>(0,U.jsx)(S,{marginLeft:2,children:(0,U.jsx)(nt,{step:L})},L.index))},`branch-children-${h.index}`):(0,U.jsx)(nt,{step:h},h.index)})]}),_&&(0,U.jsx)(Gn,{currentStep:T,maxSteps:r,elapsed:O,status:P})]})}return e?(0,U.jsxs)(S,{flexDirection:"column",children:[(0,U.jsx)(Jr,{steps:s,flows:t,cmInitCounts:n,renderStep:(u,w)=>(0,U.jsx)(nt,{step:u},w)}),_&&(0,U.jsx)(Gn,{currentStep:T,maxSteps:r,elapsed:O,status:P})]}):(0,U.jsxs)(S,{flexDirection:"column",children:[(0,U.jsx)(zt,{items:ae,children:u=>u.type==="cm_init"?(0,U.jsx)(S,{marginLeft:2,paddingLeft:1,children:(0,U.jsxs)(f,{color:v.dimmed,children:["\u25AA Generated task with ",u.count," checkpoints"]})},u.key):u.type==="bifurcation_header"?(0,U.jsx)(S,{marginLeft:2,paddingLeft:1,children:(0,U.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,U.jsxs)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,U.jsxs)(f,{color:v.purple,children:["Flow ",u.flowIdx+1,": ",u.label]}),u.cmCount!=null&&(0,U.jsxs)(f,{color:v.dimmed,children:[" \u25AA Generated task with ",u.cmCount," checkpoints"]})]},u.key):(0,U.jsx)(S,{marginLeft:2,paddingLeft:1,children:(0,U.jsx)(nt,{step:u.step})},u.key)}),B.length>0&&(0,U.jsx)(S,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:B.map(u=>(0,U.jsx)(nt,{step:u},u.index))}),_&&(0,U.jsx)(Gn,{currentStep:T,maxSteps:r,elapsed:O,status:P})]})}var Xr=M(De(),1);var zn=M(Q(),1),us=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Jn({label:s,hasBifurcation:e=!1}){let[t,n]=(0,Xr.useState)(0),[r,o]=(0,Xr.useState)(0);kt(()=>{n(l=>(l+1)%us.length)},80),kt(()=>{o(l=>(l+1)%4)},400);let a=s??(e?"Planning approach":"Analyzing objective");return(0,zn.jsxs)(S,{marginLeft:1,children:[(0,zn.jsxs)(f,{color:v.primary,children:[us[t]," "]}),(0,zn.jsxs)(f,{color:v.dim,children:[a,".".repeat(r+1)]})]})}function Xn(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=M(De(),1);var He=M(Q(),1);function Gi(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=Gi(s,e);return(0,He.jsx)(S,{flexDirection:"column",borderStyle:"round",borderColor:v.primary,paddingX:2,paddingY:1,children:t.map((n,r)=>{if(n.type==="title")return(0,He.jsx)(f,{color:v.primary,bold:!0,children:n.text},r);if(n.type==="header")return(0,He.jsx)(S,{marginTop:1,children:(0,He.jsx)(f,{color:v.dim,children:n.text})},r);if(n.type==="divider")return(0,He.jsx)(S,{marginTop:1,marginBottom:0,children:(0,He.jsx)(f,{color:v.ambient,children:n.text})},r);if(n.type==="footer")return(0,He.jsx)(S,{marginTop:1,children:(0,He.jsx)(f,{color:v.dim,children:n.text})},r);let o=n.text.match(/^(.+?) (·+) (.+)$/);return o?(0,He.jsxs)(f,{children:[(0,He.jsxs)(f,{color:v.secondary,children:[o[1]," "]}),(0,He.jsxs)(f,{color:v.ambient,children:[o[2]," "]}),(0,He.jsx)(f,{color:n.color??v.base,children:o[3]})]},r):(0,He.jsx)(f,{color:n.color??v.base,children:n.text},r)})})}var Ve=M(Q(),1);function Yr(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 Qr({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=Yr(s,T),R=0;if(T.length>0){let O=P.findIndex(oe=>oe.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=Yr(s,d.expandedPath),p=g[d.selectedIndex]?.item,_=(0,bt.useRef)(null),y=(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 je((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),y(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"),oe=R[O];if(oe&&p.onValue){let te=p.currentValue;p.onValue(oe.value),y(te?`${p.label}: ${te} \u2192 ${oe.label}`:`${p.label}: ${oe.label}`)}m(te=>({...te,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),oe=Yr(s,O),te=R.expandedPath[R.expandedPath.length-1],ae=oe.findIndex(fe=>fe.item.id===te);return{...R,expandedPath:O,selectedIndex:ae>=0?ae: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||y(`${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,Ve.jsx)(S,{flexDirection:"column",paddingX:1,children:d.activeView==="infoView"&&d.infoData?(0,Ve.jsx)(ds,{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,Ve.jsxs)(Ve.Fragment,{children:[g.map(({item:T,depth:P},R)=>{let O=R===d.selectedIndex,oe=" ".repeat(P),te=O?"\u276F ":" ",ae=T.type==="submenu"?d.expandedPath.includes(T.id)?"\u25BC ":"\u25B6 ":" ",fe=T.currentValue!=null?` [${T.currentValue}]`:"";if(O&&d.isSelecting&&T.options){let N=Number(d.inputValue||"0");return(0,Ve.jsxs)(S,{flexDirection:"column",children:[(0,Ve.jsxs)(f,{color:v.cyan,children:[oe,te,ae,T.label]}),T.options.map((B,u)=>(0,Ve.jsxs)(f,{color:u===N?v.cyan:void 0,children:[oe," ",u===N?"\u276F ":" ",B.label]},B.value))]},T.id)}return O&&d.isEditing?(0,Ve.jsxs)(f,{color:v.cyan,children:[oe,te,ae,T.label,": ",d.inputValue,(0,Ve.jsx)(f,{color:v.dimmed,children:"\u2588"})]},T.id):(0,Ve.jsxs)(f,{color:O?v.cyan:void 0,dimColor:!O&&P>0,children:[oe,te,ae,T.label,(0,Ve.jsx)(f,{dimColor:!0,children:fe})]},T.id)}),d.feedback&&(0,Ve.jsx)(S,{marginTop:1,children:(0,Ve.jsxs)(f,{color:v.green,children:["\u2713 ",d.feedback]})})]})})}var vn=M(De(),1);var Le=M(Q(),1),Zr=800,eo=3840,to=600,no=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<Zr)return`Min ${Zr}`;if(t>eo)return`Max ${eo}`}else{if(t<to)return`Min ${to}`;if(t>no)return`Max ${no}`}return null}function ro({currentWidth:s,currentHeight:e,onSelect:t,onCancel:n}){let[r,o]=(0,vn.useState)("width"),[a,l]=(0,vn.useState)(String(s)),[i,c]=(0,vn.useState)(String(e)),[d,m]=(0,vn.useState)(null);je((p,_)=>{if(_.escape){n();return}if(_.tab||_.rightArrow||_.leftArrow){o(y=>y==="width"?"height":"width"),m(null);return}if(_.return){let y=fs("width",a);if(y){o("width"),m(`Width: ${y}`);return}let C=fs("height",i);if(C){o("height"),m(`Height: ${C}`);return}t(Number(a),Number(i));return}if(_.backspace||_.delete){r==="width"?l(y=>y.slice(0,-1)):c(y=>y.slice(0,-1)),m(null);return}p&&/^\d$/.test(p)&&(r==="width"?l(y=>y+p):c(y=>y+p),m(null))});let g=(p,_,y)=>{let C=r===y,T=C?v.primary:v.secondary;return(0,Le.jsxs)(S,{flexDirection:"column",children:[(0,Le.jsxs)(f,{color:v.dim,children:[" ",p]}),(0,Le.jsx)(S,{borderStyle:"round",borderColor:T,paddingX:1,width:10,children:(0,Le.jsxs)(f,{color:C?v.base:v.dim,children:[_||" ",C?(0,Le.jsx)(f,{color:v.dimmed,children:"\u2588"}):""]})}),(0,Le.jsxs)(f,{color:v.dim,dimColor:!0,children:[" ",y==="width"?`${Zr}\u2013${eo}`:`${to}\u2013${no}`]})]})};return(0,Le.jsxs)(S,{flexDirection:"column",paddingX:1,children:[(0,Le.jsx)(f,{color:v.primary,bold:!0,children:"Window Size"}),(0,Le.jsxs)(S,{marginTop:1,gap:1,children:[g("Width",a,"width"),(0,Le.jsx)(S,{alignItems:"center",marginTop:1,children:(0,Le.jsx)(f,{color:v.dim,children:"x"})}),g("Height",i,"height")]}),d&&(0,Le.jsx)(S,{marginTop:1,children:(0,Le.jsx)(f,{color:v.red,children:d})}),(0,Le.jsx)(S,{marginTop:1,children:(0,Le.jsx)(f,{color:v.dim,children:"Tab/arrows to switch Enter to save Esc to cancel"})})]})}import{randomUUID as qi}from"crypto";import{mkdirSync as zi,writeFileSync as ms,appendFileSync as Ji,existsSync as ps}from"fs";import{join as _n}from"path";var Xi=_n(Ce,"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=qi(),this.sessionDir=_n(Xi,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{zi(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(_n(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}))};
|
|
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||!
|
|
28
|
-
`)}catch{}}};import{dirname as
|
|
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)+`
|
|
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};hs(
|
|
30
|
+
`)}}save(e){try{let n={...this.load(),...e};gs(hs(this.path),{recursive:!0}),ps(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
|
|
33
|
-
`)}e&&n&&
|
|
34
|
-
`)}function
|
|
35
|
-
`)}if(
|
|
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}
|
|
36
36
|
`),r.length>0&&process.stderr.write(`[exit-manager] cleaned up: ${r.join(", ")}
|
|
37
|
-
`)),t&&
|
|
37
|
+
`)),t&&ro){try{ro()}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(
|
|
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(`
|
|
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
|
|
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=
|
|
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+`
|
|
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
|
|
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
|
|
49
|
-
`))}n(!1),
|
|
50
|
-
`)),n(!1),
|
|
51
|
-
`).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function
|
|
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 _=
|
|
53
|
-
`)}return t}function Hs(s){if(!Ms(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 Ws(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 Ks(s,e,t){let n=Fs(s,t),r=Fs(e,t);return{...n,...r}}function Gs(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 dr=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=Ho(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 fr=class extends Wo{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 mr(s){let e=Ks(s.globalDir,s.localDir,s.onLoadError),t=s.file?Hs(s.file):{},n=s.inline?Ws(s.inline):{},r={...e,...t,...n},o=Object.keys(r).length>0,{variables:a,objective:l}=o?Gs(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 pr(s){if(s.localMode)return{};let e=le(s.env);if(s.variables.secretEntries.length>0){let n=new dr(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 fr(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 gr(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 An(s){let e=le(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 qs=["python"];function Ia(s){if(s!==void 0){if(!qs.includes(s))throw new Error(`--code-language must be one of: ${qs.join(", ")} (got "${s}")`);return s}}function kn(s,e){let t=Ia(s.codeLanguage);return{enabled:s.codeExport??e.enabled,language:t??e.language,skipValidation:s.skipCodeValidation??e.skip_validation}}async function hr(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 vr(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 D=M(Q(),1);function zs({localMode:s=!1,codeExport:e,codeLanguage:t,skipCodeValidation:n,updatePromise:r}={}){Jt();let o=(0,$.useRef)(new xt),[a,l]=(0,$.useState)(0),i=o.current,[c]=(0,$.useState)(()=>new rt),d=(0,$.useRef)(0),m=(0,$.useCallback)(()=>`msg-${++d.current}`,[]),[g,p]=(0,$.useState)(!1),[_,y]=(0,$.useState)(null),[C,T]=(0,$.useState)(!1),[P,R]=(0,$.useState)(null),[O,oe]=(0,$.useState)(!1),[te,ae]=(0,$.useState)(0),[fe,N]=(0,$.useState)(!1),[B,u]=(0,$.useState)(null),[w,h]=(0,$.useState)(null),x=(0,$.useRef)(null),[L,z]=(0,$.useState)(null),[J,se]=(0,$.useState)(Un()),[X,ye]=(0,$.useState)(null),[he,Ae]=(0,$.useState)([]),[st,Pn]=(0,$.useState)(!1),[sn,Gt]=(0,$.useState)(!1),F=(0,$.useRef)(null),ne=(0,$.useRef)(0),re=(0,$.useRef)(""),pe=(0,$.useRef)(null),We=(0,$.useRef)(null),ze=(0,$.useRef)({}),_e=(0,$.useRef)(null),ke=(0,$.useRef)(0),[ue,Oe]=(0,$.useState)([]),ce=(0,$.useCallback)(E=>{let k=`s-${++ke.current}`;Oe(b=>[...b,{id:k,content:E}])},[]),[Je,$e]=(0,$.useState)("booting"),[pt,Sr]=(0,$.useState)([]),[Er,an]=(0,$.useState)(!1),[On,wi]=(0,$.useState)(!1),[Dn,yi]=(0,$.useState)("chat"),[ln,cn]=(0,$.useState)(null),[Se,un]=(0,$.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),Si=Nn(),I=_s(),jn=Rs(),Ei=(0,$.useCallback)((E,k,b)=>{let A=F.current;if(!A)return;let j=ne.current+k;ur(i.sessionDir,j,E,A,(V,G,q,Z)=>i.log(V,G,q,Z),b)},[i]),Ci=(0,$.useCallback)((E,k,b)=>{i.logStep(E,k,b)},[i]),H=ir(Ei,Ci),[W,tt]=(0,$.useState)(()=>c.load()),[,Ri]=(0,$.useState)(0),Xe=(0,$.useCallback)(()=>Ri(E=>E+1),[]),[K,Ee]=(0,$.useState)(null),qt=I.creds.getActiveProfile(),me=I.creds.getDefaultEnv(),Ye=(0,$.useCallback)((E,k)=>{let b=E?I.creds.loadProfileConfig(E,k):null;c.save({project_id:b?.project_id??null,project_name:b?.project_name??null,folder_id:b?.folder_id??null,folder_name:b?.folder_name??null}),tt(c.load())},[I.creds,c]);(0,$.useEffect)(()=>{O||(i.start({model:W.model,environment:me,profile:qt}),oe(!0))},[i,O,W.model,me,qt]);let Oo=(0,$.useCallback)(async E=>{let k=le(E),b=I.getBasicAuth(),A=b?{username:b.username,accessKey:b.access_key}:await I.getToken().then(V=>V??"");if(!A)return;let j=new Ko(k.controllerBaseUrl,A);try{let V=await j.getScreenshotSas();i.setScreenshotSas(V),F.current=new nn(V,3,(G,q,Z,de)=>i.log(G,q,Z,de)),i.log("info","SCREENSHOT_SAS_OK","Screenshot SAS token fetched")}catch(V){i.log("warn","SCREENSHOT_SAS_FAILED","Screenshot SAS fetch failed",{error:V instanceof Error?V.message:String(V)})}},[I,i]),Ct=(0,$.useCallback)(async E=>{let k=E??I.creds.getDefaultEnv();ye(null),F.current=null;let A=await I.initResolver(k,(j,V,G,q)=>i.log(j,V,G,q)).resolve(!0).catch(()=>null);return ye(A),A&&(i.log("info","AUTH_RESET_OK","Auth reset resolved",{username:A.username,org_id:A.org_id,env:k}),await Oo(k)),A},[I,i,Oo]),Do=(0,$.useRef)(!1);(0,$.useEffect)(()=>{!g||Do.current||!O||(Do.current=!0,Ct().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 k=Go({sessionId:i.sessionId,identity:{org_id:String(E.org_id??""),user_id:String(E.user_id??""),machine_id:qo()},environment:me,getToken:async()=>I.getToken()});i.setRemoteLogger(k),k.start(),Qe("remote-logger",()=>k.shutdownSync()),er(k)}}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,O,Ct,i]);let $t=(0,$.useCallback)(async()=>{if(X)return i.log("info","TMS_CREDS_CACHED","Using cached TMS credentials",{username:X.username,org_id:X.org_id}),X;let E=await I.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}),ye(E)):i.log("warn","TMS_CREDS_FAILED","No TMS credentials resolved"),E},[I,X,i]),jo=(0,$.useCallback)(async()=>{let E=await $t();if(!E)return i.log("warn","PROJECT_FAILED","No TMS credentials for project resolution"),null;let k=le(me),b=new lt(k.tmsBaseUrl,E.username,E.access_key),A=I.creds.getActiveProfile(),j=I.creds.getDefaultEnv(),V=A?I.creds.loadProfileConfig(A,j):null,G=V?.project_id??W.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:`${k.tmsBaseUrl}/v1/projects`});let Z=await b.listProjects((xe,dn,Rt,dt)=>i.log(xe,dn,Rt,dt));i.log("info","PROJECT_LIST_OK","Projects listed",{count:Z.length});let de=Z.find(xe=>xe.name==="KaneAI Generated");if(de)G=de.project_id,i.log("info","PROJECT_SELECTED","Using KaneAI Generated project",{project_id:G});else if(Z.length>0){let xe=Z[0];G=xe.project_id,i.log("info","PROJECT_SELECTED","Using first project",{name:xe.name,project_id:G})}G&&c.set("project_id",G)}catch(Z){return i.log("error","PROJECT_LIST_FAILED","Project listing failed",{error:String(Z)}),null}}if(!G)return i.log("warn","PROJECT_NONE","No projects found"),null;let q=V?.folder_id??W.folder_id;if(q)i.log("info","FOLDER_CACHED","Using cached folder",{folder_id:q});else try{i.log("info","FOLDER_FETCH","Fetching default folder",{project_id:G}),q=await b.getDefaultFolder(G),i.log("info","FOLDER_OK","Default folder resolved",{folder_id:q}),q&&c.set("folder_id",q)}catch(Z){return i.log("error","FOLDER_FAILED","Default folder fetch failed",{error:String(Z)}),null}return{projectId:G,folderId:q??""}},[W.project_id,W.folder_id,$t,me,c,i]),ee=(0,$.useCallback)(E=>{let k=m(),b={...E,id:k};ce((0,D.jsx)(rs,{entry:b}))},[m,ce]),Lo=(0,$.useCallback)(async(E,k)=>{let b=i.nextRunIndex();ne.current=b,re.current=E,i.logRunStart(b,E,k??""),i.setFirstRun(E,k??"");let A=I.getResolvedBasicAuth(),j=A,V=null;if(!j&&(V=await I.getToken(),!V)){ee({type:"error",text:"Not authenticated. Run /login first."});return}let G={basicAuth:A??null,token:V,resolver:I.getResolver(),resolvedCreds:null};if(pe.current=G,b===0&&!s){i.log("info","ATM_CREATE_START","Creating test via ATM endpoint",{run_index:0});let Pe=await jo(),it=le(me),at=j?{username:j.username,access_key:j.access_key}:await $t();if(at){let gt=await hr({tmsBaseUrl:it.tmsBaseUrl,auth:{username:at.username,access_key:at.access_key},objective:E,url:k??W.default_url??"",projectId:Pe?.projectId??W.project_id??"",folderId:Pe?.folderId??W.folder_id??"",hasCustomProfile:!!W.chrome_profile_path,log:(Vn,Or,Dr,jr)=>i.log(Vn,Or,Dr,jr)});gt&&(i.setTestId(gt),Pe?.projectId&&i.setProjectId(Pe.projectId))}}let q=null;if(Se.useCft)ee({type:"info",text:"CfT mode: Playwright will manage browser"});else if(Se.wsEndpoint)ee({type:"info",text:`WS endpoint: ${Se.wsEndpoint.slice(0,60)}...`});else if(Se.cdpEndpoint)ee({type:"info",text:`CDP endpoint: ${Se.cdpEndpoint}`});else{ee({type:"info",text:"Starting Chrome..."});try{q=await jn.ensureChrome(k)}catch(it){ee({type:"error",text:nr(it)});return}i.logChromeLaunch(q.port,q.cdpEndpoint),ee({type:"info",text:`Chrome ready (port ${q.port})`});let Pe=Is({headless:Se.headless,cdpEndpoint:q.cdpEndpoint});Pe&&(_e.current=Pe,Qe("marker-overlay",()=>Pe.kill()))}let Z=mr({objective:E,globalDir:ut(Ce,"variables"),localDir:ut(process.cwd(),".testmuai","variables")});i.setAuteurVariables(Z.auteur),We.current=Z;let de=j&&!s?await pr({variables:Z,auth:j,orgId:String((await $t())?.org_id??""),env:me,localMode:s,log:(Pe,it,at,gt)=>i.log(Pe,it,at,gt)}):{};ze.current=de;let xe=tn(ut(Ce,"global-memory.md")),dn=tn(ut(process.cwd(),".testmuai","context.md")),Rt=q?{cdpEndpoint:q.cdpEndpoint,instance:q,tempDir:null}:Se.wsEndpoint?{wsEndpoint:Se.wsEndpoint,instance:null,tempDir:null}:Se.cdpEndpoint?{cdpEndpoint:Se.cdpEndpoint,instance:null,tempDir:null}:{instance:null,tempDir:null},dt=gr({objective:Z.auteurObjective,url:k,model:W.model,chrome:Rt,auth:G,sessionId:i.sessionId,runIndex:b,windowSize:W.window_size,maxSteps:Se.maxSteps,headless:Se.headless,variables:Object.keys(Z.auteur).length>0?Z.auteur:void 0,globalContext:xe??void 0,localContext:dn??void 0,sessionContext:i.getContext()});k&&R(k),u(null),H.startRun(dt,{environment:me,mode:W.mode,log:(Pe,it,at,gt)=>i.log(Pe,it,at,gt)}),ae(Pe=>Pe+1)},[I,jn,c,W,i,me,H,ee,Se,jo,$t]),Cr=(0,$.useRef)(null);(0,$.useEffect)(()=>{if(H.bifurcationInfo&&H.bifurcationInfo!==Cr.current){Cr.current=H.bifurcationInfo;let{flows:E,isSingleFlow:k}=H.bifurcationInfo;if(k&&E.length===1&&E[0])i.log("info","OBJECTIVE_REWRITTEN","Objective rewritten",{objective:E[0]}),ee({type:"info",text:`Objective: ${E[0]}`});else if(!k&&E.length>1){let b=[`Bifurcated into ${E.length} flows:`];E.forEach((A,j)=>b.push(` ${j+1}. ${A}`)),i.log("info","BIFURCATION","Objective bifurcated into flows",{flow_count:E.length}),ee({type:"info",text:b.join(`
|
|
54
|
-
`)})}}},[
|
|
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(`
|
|
55
55
|
`).slice(-8).join(`
|
|
56
|
-
`);
|
|
57
|
-
${b}`})}},[H.runError,H.isRunning,ee,i]);let $n=(0,$.useCallback)(async()=>{i.log("info","EXIT_UPLOAD_START","Starting exit upload pipeline"),se(Un()),z({status:"uploading"});let E=I.getResolvedBasicAuth(),k=null;if(!E&&(k=await I.getToken(),!k))return i.log("warn","EXIT_UPLOAD_ABORTED","Exit upload aborted \u2014 no auth available"),null;let b=X??await $t();if(!b)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 A={basicAuth:E??null,token:k,resolver:I.getResolver(),resolvedCreds:b};F.current&&(i.log("info","SCREENSHOT_UPLOAD_DRAIN","Draining screenshot queue before pipeline"),await F.current.drain(),i.log("info","SCREENSHOT_UPLOAD_DRAINED","Screenshot queue drained"));let j=An({session:i,env:me,auth:A,variables:We.current??{raw:{},auteur:{},auteurObjective:"",secretEntries:[],nonSecretEntries:[]},variableIds:ze.current,projectId:W.project_id,folderId:W.folder_id,totalSteps:Ar.current,totalDuration:kr.current,codeExport:kn({codeExport:e,codeLanguage:t,skipCodeValidation:n},W.code_export),onProgress:(q,Z,de)=>{i.log("info","EXIT_PROGRESS","Upload progress",{step:q,status:Z,detail:de}),se(xe=>Jo(xe,q,Z,de))},log:(q,Z,de,xe)=>i.log(q,Z,de,xe)}),G=await new zo(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 q=le(me),Z=W.project_id,de=G.testcaseId&&G.shareId&&Z?Nt(q.testManagerUiUrl,Z,G.testcaseId,G.shareId):void 0,xe=G.testcaseId&&Z?Rn(q.testManagerUiUrl,Z,G.testcaseId):void 0;z({status:"success",testUrl:de,testCaseLink:xe,codeExportDir:G.codeExportDir}),Ds({shareableLink:de,testCaseLink:xe,codeExportDir:G.codeExportDir})}else i.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:G.error}),i.setUploadStatus("failed",G.error),z({status:"failed",error:G.error});return G},[I,me,i,W,X,$t]),$o=(0,$.useCallback)(async()=>{if(!(i.nextRunIndex()>0)){ee({type:"info",text:"No runs in current session."});return}if(H.isRunning){ee({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"),Pn(!0);let k=i.getFlows();k.length>0&&ce((0,D.jsx)(mo,{flows:k}));let b=null;if(!s)try{b=await $n()??null}catch(j){i.log("error","SESSION_RESET_UPLOAD_FAILED","Upload failed during /new",{error:String(j)}),ee({type:"error",text:"Upload failed \u2014 session data saved locally."})}if(b?.success&&b.testcaseId){let j=le(me),V=W.project_id;ce((0,D.jsx)(Fr,{shareableLink:b.shareId&&V?Nt(j.testManagerUiUrl,V,b.testcaseId,b.shareId):void 0,testCaseLink:V?Rn(j.testManagerUiUrl,V,b.testcaseId):void 0,codeExportDir:b.codeExportDir,autoExit:!1}))}i.testId&&Ae(j=>[...j,{testId:i.testId,runCount:te}]),jn.killChrome(),await i.finish("complete");let A=new xt;A.start({model:W.model,environment:me,profile:qt??null}),o.current=A,l(j=>j+1),i.log("info","SESSION_RESET_COMPLETE","Session reset complete",{new_session_id:A.sessionId}),ae(0),Ar.current=0,kr.current=0,ne.current=0,re.current="",We.current=null,ze.current={},F.current=null,Bn.current=0,Pr.current=0,Ln.current=null,Tr.current=null,Rr.current=null,Cr.current=null,u(null),R(null),z(null),se(Un()),Pn(!1),ce((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,H,ee,ce,s,$n,jn,te,W,me,qt,a]),Bo=(0,$.useCallback)(async()=>{await i.finish("complete"),Y(0,"Session complete")},[i]),Ai=(0,$.useCallback)(async E=>{Gt(!1);let k=i.testId??(he.length>0?he[he.length-1].testId:null);if(E&&k){i.log("info","EXIT_FEEDBACK_SUBMIT","Submitting session feedback",{choice:E});try{let b=le(me),A=I.getResolvedBasicAuth();A&&await vr({tmsBaseUrl:b.tmsBaseUrl,username:A.username,accessKey:A.access_key,testId:k,feedbackType:E,log:(j,V,G,q)=>i.log(j,V,G,q)})}catch(b){i.log("error","EXIT_FEEDBACK_FAILED","Feedback submission failed",{error:String(b)})}}else i.log("info","EXIT_FEEDBACK_SKIPPED","Feedback skipped");Bo()},[me,I,i,Bo,he]),Bt=(0,$.useCallback)(async()=>{if(fe)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"),N(!0);try{await $n()}catch(b){i.log("error","EXIT_UPLOAD_FAILED","Exit upload failed",{error:String(b)})}i.testId&&Ae(b=>[...b,{testId:i.testId,runCount:te}]),await i.finish("complete")}if(!(i.testId??(he.length>0?he[he.length-1].testId:null))||s){await i.finish("complete"),Y(0,"No test ID \u2014 quick exit");return}N(!0),Gt(!0)},[fe,i,s,$n,te,he]);(0,$.useEffect)(()=>{if(!fe)return;let E=300*1e3,k=setTimeout(async()=>{i.setUploadStatus("failed","Upload timed out after 5m"),await i.finish("complete"),Y(0,"Upload timed out after 5m")},E);return()=>clearTimeout(k)},[fe,i]);let Bn=$.default.useRef(0),Ir=$.default.useRef(null),Pr=$.default.useRef(0);je((E,k)=>{if(k.ctrl&&E==="c"){if(fe){Pr.current+=1,Pr.current>=2&&(i.setUploadStatus("pending","Force exit by user"),i.finish("complete"),Y(0,"Force exit by user"));return}if(H.isRunning){H.cancelRun(),ee({type:"info",text:"Run cancelled."}),Bn.current++,Ir.current&&clearTimeout(Ir.current),Ir.current=setTimeout(()=>{Bn.current=0},2e3),Bn.current>=2&&Bt();return}Bt()}});let Vo=$.default.useMemo(()=>{let E=I.creds.getActiveProfile()??"none",k=I.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:Se.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:b=>{un(A=>({...A,headless:b==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(Se.maxSteps),onValue:b=>{let A=parseInt(b,10);A>0&&un(j=>({...j,maxSteps:A}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:Se.timeout?String(Se.timeout):"",placeholder:"0 = no timeout",onValue:b=>{let A=parseInt(b,10);un(j=>({...j,timeout:isNaN(A)?0:A}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:Se.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:b=>{un(A=>({...A,cdpEndpoint:b}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:Se.wsEndpoint,placeholder:"wss://...",onValue:b=>{un(A=>({...A,wsEndpoint:b}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{I.logout().then(b=>{Xe();let A=I.creds.getActiveProfile(),j=I.creds.getDefaultEnv();Ye(A,j),Ct().catch(()=>{}),ee(b?{type:"info",text:`Logged out: ${b.profile} [${b.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{ee({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let b=I.creds.getActiveProfile()??"none",A=I.creds.getDefaultEnv(),j=I.creds.loadBasicAuth(b,A),V=j?"basic":I.creds.loadCredentials(b,A)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:b},{key:"Environment",value:A}]},{label:"Authentication",entries:[{key:"Method",value:V},...j?[{key:"Username",value:j.username}]:[]]},{label:"Token",entries:[{key:"Status",value:I.tokenValid?"valid":"not logged in",color:I.tokenValid?v.statusPass:v.statusFail}]}]}}},{id:"balance",label:"Credit Balance",type:"action",suppressFeedback:!0,onAction:()=>{(async()=>{let b=I.creds.getActiveProfile()??"default",A=I.creds.getDefaultEnv(),j=le(A);try{let V=I.getBasicAuth(),G=V?null:await I.getToken();if(!V&&!G){h({text:"Not authenticated. Run /login first.",color:v.red});return}let{ControllerClient:q}=await import("./controller-client-7BIK5FYL.js"),de=await(V?new q(j.controllerBaseUrl,{username:V.username,accessKey:V.access_key}):new q(j.controllerBaseUrl,G)).getCreditBalance();h({text:`Credits \u2014 available: ${de.available_credits}, total: ${de.total_credits} (${b} / ${A})`,color:v.green})}catch(V){h({text:`Balance check failed: ${V instanceof Error?V.message:String(V)}`,color:v.red})}x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{h(null),x.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:ft}]},{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:b=>{(b==="action"||b==="testing")&&(c.set("mode",b),tt(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:b=>{c.set("code_export",{...W.code_export,enabled:b==="on"}),tt(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:b=>{c.set("code_export",{...W.code_export,skip_validation:b==="on"}),tt(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(Ce,"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(Ce,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:ut(Ce,"tui-config.json")},{key:"Auth",value:ut(Ce,"config.json")},{key:"Sessions",value:`${ut(Ce,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${ut(Ce,"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(Ce,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"CLI Overrides",entries:[{key:"Global",value:"--global-context <file>"},{key:"Local",value:"--local-context <file>"}]}]})}]},{id:"update",label:_?`Update (${_.current} \u2192 ${_.latest})`:"Update",type:"action",onAction:()=>{C||(T(!0),ee({type:"info",text:"Checking for updates..."}),(async()=>{let{checkForUpdate:b}=await import("./version-check-RN63L7BF.js"),A=await b();if(!A){ee({type:"info",text:`Already on latest version (${ht})`}),T(!1);return}ee({type:"info",text:`Update available: ${A.current} \u2192 ${A.latest}. Installing...`});let{runSelfUpdate:j}=await import("./updater-VR2G73FF.js"),V=await j();V.success?ee({type:"info",text:`\u2713 Updated to ${V.toVersion}. Restart kane-cli to use the new version.`}):ee({type:"error",text:`Update failed: ${V.error}`}),T(!1)})())}},{id:"exit",label:"Exit",type:"action",onAction:()=>{Bt()}}]},[I,c,W,ee,Bt,Se,Xe,_,C]),ki=(0,$.useCallback)(E=>{if(H.askingUser){ce((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})]})),H.sendAnswer(E);return}if(i.logCommand(E),H.isRunning){ee({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}let k=Ps(E);if(k)switch(k.command){case"login":case"logout":case"whoami":case"profiles":case"balance":case"auth":cn("auth");return;case"config":cn("config");return;case"help":cn("help");return;case"update":{if(H.isRunning){ee({type:"error",text:"Cannot update while a run is in progress."});return}ee({type:"info",text:"Checking for updates..."}),(async()=>{try{let{checkForUpdate:b}=await import("./version-check-RN63L7BF.js"),A=await b();if(!A){ee({type:"info",text:`Already on latest version (${ht})`});return}ee({type:"info",text:`Update available: ${A.current} \u2192 ${A.latest}. Installing...`});let{runSelfUpdate:j}=await import("./updater-VR2G73FF.js"),V=await j();V.success?ee({type:"info",text:`Updated to ${V.toVersion}. Restart kane-cli to use the new version.`}):ee({type:"error",text:`Update failed: ${V.error}`})}catch(b){ee({type:"error",text:`Update failed: ${b instanceof Error?b.message:String(b)}`})}})();return}case"summary":{let b=i.getFlows();if(b.length===0){ee({type:"info",text:"No runs yet in this session."});return}let A=k.args.index?parseInt(k.args.index,10):void 0;if(A!==void 0&&!i.getFlow(A)){ee({type:"error",text:`No flow at index ${A}. ${b.length} flow${b.length===1?"":"s"} available. Use /summary to see all.`});return}ce((0,D.jsx)(mo,{flows:b,filterIndex:A}));return}case"new":$o();return;case"cancel":H.cancelRun(),ee({type:"info",text:"Run cancelled."});return;case"clear":return;case"exit":Bt();return;default:ee({type:"error",text:`Unknown command: /${k.command}`});return}if(E.trim().toLowerCase()==="exit"){Bt();return}ce((0,D.jsxs)(S,{children:[(0,D.jsx)(f,{color:"#b388ff",children:"\u276F "}),(0,D.jsx)(f,{children:E})]})),Lo(E,ft)},[H,ee,ce,i,Lo,Bt,$o]),Uo=I.getAuthInfo(),Ti=Uo?Uo.method==="basic"?"basic auth":"oauth":"not logged in";return(0,D.jsxs)(S,{flexDirection:"column",children:[ue.length>0&&(0,D.jsx)(zt,{items:ue,children:E=>(0,D.jsx)(S,{paddingX:1,children:E.content},E.id)}),!g&&!On&&(0,D.jsx)(ns,{onComplete:()=>{let E=I.creds.getActiveProfile(),k=I.creds.getDefaultEnv(),b=E?I.creds.loadCredentials(E,k):null,A=E?I.creds.loadBasicAuth(E,k):null,j=!!(b||A),V=A?.username??E??null;ce((0,D.jsx)(Hn,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:ht,authenticated:j,user:V})),wi(!0);let G=(q,Z,de,xe)=>{i.log(q,Z,de,xe)};ar(I.creds,G).then(q=>{if(q.status==="authenticated"){let{profile:Z,env:de,tmsCreds:xe}=q.result;I.creds.setActiveProfile(Z),I.creds.setDefaultEnv(de),Xe(),ye(xe),$e("ready"),p(!0)}else q.status==="needs_pick"?(Sr(q.profiles),$e("pick")):$e("login")}).catch(q=>{i.log("error","STARTUP_GATE_ERROR","Auth gate failed",{error:String(q)}),$e("login")}),r&&r.then(q=>{q&&(y(q),ee({type:"info",text:`Update available: ${q.current} \u2192 ${q.latest} \u2014 select Update from menu or run \`kane-cli update\``}))}).catch(()=>{})}}),!g&&Je==="booting"&&On&&(0,D.jsx)(S,{paddingX:1,children:(0,D.jsx)(f,{color:"yellow",children:"Checking authentication..."})}),!g&&Je==="pick"&&(0,D.jsx)(Pa,{profiles:pt,onCancel:()=>$e("login"),onSelect:async(E,k)=>{I.creds.setActiveProfile(E),I.creds.setDefaultEnv(k),Xe(),an(!0);let b=(A,j,V,G)=>{i.log(A,j,V,G)};try{let A=await Zt(I.creds,E,k,b);an(!1),A.status==="authenticated"?(Ye(E,k),$e("ready"),p(!0)):$e("login")}catch{an(!1),$e("login")}},validating:Er}),!g&&Je==="login"&&!K&&(0,D.jsx)(Xt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:I.creds.listProfiles(),onBasicLogin:(E,k,b,A)=>{I.creds.saveBasicAuth(E,k,{username:b,access_key:A}),I.creds.setActiveProfile(E),I.creds.setDefaultEnv(k),I.setTokenValid(!0),Xe()},onOAuthLogin:async(E,k)=>{I.creds.setDefaultEnv(k),await I.login(E),Xe()},onComplete:(E,k)=>{Ct(k).then(()=>{Xe(),Ee({phase:"project",profile:E,env:k})}).catch(()=>{Ee({phase:"project",profile:E,env:k})})},onCancel:()=>{Y(0,"Login cancelled at startup")}}),!g&&Je==="login"&&K?.phase==="project"&&(0,D.jsx)(Tt,{resolver:I.getResolver(),currentProjectId:null,env:K.env,onSelect:(E,k)=>{I.creds.saveProfileConfig(K.profile,K.env,{project_id:E,project_name:k}),Ee({...K,phase:"folder"})},onCancel:()=>{Ye(K.profile,K.env),Ee(null),$e("ready"),p(!0)}}),!g&&Je==="login"&&K?.phase==="folder"&&(0,D.jsx)(It,{resolver:I.getResolver(),projectId:I.creds.loadProfileConfig(K.profile,K.env)?.project_id??"",currentFolderId:null,env:K.env,onSelect:(E,k)=>{I.creds.saveProfileConfig(K.profile,K.env,{folder_id:E,folder_name:k}),Ye(K.profile,K.env),Ee(null),$e("ready"),p(!0)},onCancel:async()=>{let E=I.creds.loadProfileConfig(K.profile,K.env);if(E?.project_id)try{let b=I.getResolver()?.cached;if(b){let A=le(K.env),V=await new lt(A.tmsBaseUrl,b.username,b.access_key).getDefaultFolder(E.project_id);V&&I.creds.saveProfileConfig(K.profile,K.env,{folder_id:V,folder_name:"Default"})}}catch{}Ye(K.profile,K.env),Ee(null),$e("ready"),p(!0)}}),g&&Dn==="menu"&&!fe&&(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:W.model}),(0,D.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,D.jsx)(f,{color:v.dimmed,children:Ti}),(0,D.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,D.jsxs)(f,{color:v.dimmed,children:[qt??"no profile","/",me]})]})}),g&&!fe&&(0,D.jsxs)(S,{flexDirection:"column",flexGrow:1,children:[Dn==="menu"&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(Qr,{items:Vo,onRunSelected:()=>yi("chat"),renderLoginWizard:E=>{let k=K?.phase??"wizard";if(k==="project")return(0,D.jsx)(Tt,{resolver:I.getResolver(),currentProjectId:null,env:K.env,onSelect:(b,A)=>{I.creds.saveProfileConfig(K.profile,K.env,{project_id:b,project_name:A}),Ee(j=>j?{...j,phase:"folder"}:null)},onCancel:()=>{Ye(K.profile,K.env),Ee(null),E()}});if(k==="folder"){let b=I.creds.loadProfileConfig(K.profile,K.env);return(0,D.jsx)(It,{resolver:I.getResolver(),projectId:b?.project_id??"",currentFolderId:null,env:K.env,onSelect:(A,j)=>{I.creds.saveProfileConfig(K.profile,K.env,{folder_id:A,folder_name:j}),Ye(K.profile,K.env),Ee(null),E()},onCancel:async()=>{let A=I.creds.loadProfileConfig(K.profile,K.env);if(A?.project_id)try{let V=I.getResolver()?.cached;if(V){let G=le(K.env),Z=await new lt(G.tmsBaseUrl,V.username,V.access_key).getDefaultFolder(A.project_id);Z&&I.creds.saveProfileConfig(K.profile,K.env,{folder_id:Z,folder_name:"Default"})}}catch{}Ye(K.profile,K.env),Ee(null),E()}})}return(0,D.jsx)(Xt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:I.creds.listProfiles(),onBasicLogin:(b,A,j,V)=>{I.creds.saveBasicAuth(b,A,{username:j,access_key:V}),I.creds.setActiveProfile(b),I.creds.setDefaultEnv(A),I.setTokenValid(!0),Xe()},onOAuthLogin:async(b,A)=>{I.creds.setDefaultEnv(A),await I.login(b),Xe()},onComplete:(b,A)=>{Ct(A).then(()=>{Ee({phase:"project",profile:b,env:A})}).catch(()=>{Ee({phase:"project",profile:b,env:A})})},onCancel:()=>{Ee(null),E()}})},renderProfilesView:E=>(0,D.jsx)(Br,{creds:I.creds,onSwitch:(k,b)=>{I.creds.setActiveProfile(k),I.creds.setDefaultEnv(b),Ye(k,b),Xe(),Ct(b).catch(()=>{}),ee({type:"info",text:`Switched to ${k} [${b}]`})},onCancel:E}),renderChromeProfilePicker:E=>(0,D.jsx)(Vr,{currentPath:W.chrome_profile_path,onSelect:k=>{c.set("chrome_profile_path",k),tt(c.load())},onCancel:E}),renderProjectPicker:E=>(0,D.jsx)(Tt,{resolver:I.getResolver(),currentProjectId:W.project_id,env:me,onSelect:(k,b)=>{c.save({project_id:k,project_name:b});let A=I.creds.getActiveProfile(),j=I.creds.getDefaultEnv();A&&I.creds.saveProfileConfig(A,j,{project_id:k,project_name:b}),tt(c.load()),E()},onCancel:E}),renderFolderPicker:E=>(0,D.jsx)(It,{resolver:I.getResolver(),projectId:W.project_id??"",currentFolderId:W.folder_id,env:me,onSelect:(k,b)=>{c.save({folder_id:k,folder_name:b});let A=I.creds.getActiveProfile(),j=I.creds.getDefaultEnv();A&&I.creds.saveProfileConfig(A,j,{folder_id:k,folder_name:b}),tt(c.load()),E()},onCancel:E}),renderWindowSizePicker:E=>(0,D.jsx)(ro,{currentWidth:W.window_size.width,currentHeight:W.window_size.height,onSelect:(k,b)=>{c.set("window_size",{width:k,height:b}),tt(c.load()),E()},onCancel:E})}),w&&(0,D.jsx)(S,{paddingX:1,marginTop:1,children:(0,D.jsx)(f,{color:w.color,children:w.text})})]}),Dn==="chat"&&(0,D.jsxs)(D.Fragment,{children:[(()=>{let E=Xn({isRunning:H.isRunning,bifurcationInfo:H.bifurcationInfo,steps:H.steps,cmInitCounts:H.cmInitCounts});return E?(0,D.jsx)(Jn,{label:E.label,hasBifurcation:E.hasBifurcation}):null})(),H.isRunning&&H.steps.length>0&&(0,D.jsx)(qn,{steps:H.steps,bifurcated:!!H.bifurcationInfo&&!H.bifurcationInfo.isSingleFlow,flows:H.bifurcationInfo?.flows,cmInitCounts:H.cmInitCounts,onStepCommit:ce},`run-${ne.current}`),ln&&!H.isRunning&&(()=>{let E=Vo.find(k=>k.id===ln);return E?.children?(0,D.jsx)(Qr,{items:E.children,onRunSelected:()=>cn(null),onDismiss:()=>cn(null),renderLoginWizard:k=>{let b=K?.phase??"wizard";if(b==="project")return(0,D.jsx)(Tt,{resolver:I.getResolver(),currentProjectId:null,env:K.env,onSelect:(A,j)=>{I.creds.saveProfileConfig(K.profile,K.env,{project_id:A,project_name:j}),Ee(V=>V?{...V,phase:"folder"}:null)},onCancel:()=>{Ye(K.profile,K.env),Ee(null),k()}});if(b==="folder"){let A=I.creds.loadProfileConfig(K.profile,K.env);return(0,D.jsx)(It,{resolver:I.getResolver(),projectId:A?.project_id??"",currentFolderId:null,env:K.env,onSelect:(j,V)=>{I.creds.saveProfileConfig(K.profile,K.env,{folder_id:j,folder_name:V}),Ye(K.profile,K.env),Ee(null),k()},onCancel:async()=>{let j=I.creds.loadProfileConfig(K.profile,K.env);if(j?.project_id)try{let G=I.getResolver()?.cached;if(G){let q=le(K.env),de=await new lt(q.tmsBaseUrl,G.username,G.access_key).getDefaultFolder(j.project_id);de&&I.creds.saveProfileConfig(K.profile,K.env,{folder_id:de,folder_name:"Default"})}}catch{}Ye(K.profile,K.env),Ee(null),k()}})}return(0,D.jsx)(Xt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:I.creds.listProfiles(),onBasicLogin:(A,j,V,G)=>{I.creds.saveBasicAuth(A,j,{username:V,access_key:G}),I.creds.setActiveProfile(A),I.creds.setDefaultEnv(j),I.setTokenValid(!0),Xe()},onOAuthLogin:async(A,j)=>{I.creds.setDefaultEnv(j),await I.login(A),Xe()},onComplete:(A,j)=>{Ct(j).then(()=>{Ee({phase:"project",profile:A,env:j})}).catch(()=>{Ee({phase:"project",profile:A,env:j})})},onCancel:()=>{Ee(null),k()}})},renderProfilesView:k=>(0,D.jsx)(Br,{creds:I.creds,onSwitch:(b,A)=>{I.creds.setActiveProfile(b),I.creds.setDefaultEnv(A),Ye(b,A),Xe(),Ct(A).catch(()=>{}),ee({type:"info",text:`Switched to ${b} [${A}]`}),k()},onCancel:k}),renderChromeProfilePicker:k=>(0,D.jsx)(Vr,{currentPath:W.chrome_profile_path,onSelect:b=>{c.save({chrome_profile_path:b}),tt(c.load()),k()},onCancel:k}),renderProjectPicker:k=>(0,D.jsx)(Tt,{resolver:I.getResolver(),currentProjectId:W.project_id,env:me,onSelect:(b,A)=>{c.save({project_id:b,project_name:A});let j=I.creds.getActiveProfile();j&&I.creds.saveProfileConfig(j,me,{project_id:b,project_name:A}),tt(c.load()),k()},onCancel:k}),renderFolderPicker:k=>(0,D.jsx)(It,{resolver:I.getResolver(),projectId:W.project_id??"",currentFolderId:W.folder_id,env:me,onSelect:(b,A)=>{c.save({folder_id:b,folder_name:A});let j=I.creds.getActiveProfile();j&&I.creds.saveProfileConfig(j,me,{folder_id:b,folder_name:A}),tt(c.load()),k()},onCancel:k}),renderWindowSizePicker:k=>(0,D.jsx)(ro,{currentWidth:W.window_size.width,currentHeight:W.window_size.height,onSelect:(b,A)=>{c.set("window_size",{width:b,height:A}),tt(c.load()),k()},onCancel:k})},ln):null})(),ln&&w&&(0,D.jsx)(S,{paddingX:1,marginTop:1,children:(0,D.jsx)(f,{color:w.color,children:w.text})}),!ln&&(0,D.jsx)(Wn,{onSubmit:ki,onEscape:void 0,history:Si,commands:Os,placeholder:H.askingUser?"Type your answer...":H.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (/ = commands)"})]})]}),g&&fe&&L&&(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(Ur,{steps:J,status:L.status,testUrl:L.testUrl,error:L.error}),L.status==="success"&&(0,D.jsx)(Fr,{shareableLink:L.testUrl,testCaseLink:L.testCaseLink,codeExportDir:L.codeExportDir,autoExit:!1})]}),sn&&(0,D.jsx)(Xo,{onSubmit:Ai}),st&&L&&(0,D.jsx)(Ur,{steps:J,status:L.status,error:L.error}),g&&!fe&&(0,D.jsx)(Qo,{profile:qt,environment:me,model:W.model,tokenValid:I.tokenValid,sessionId:i.sessionId,runCount:te,viewMode:Dn})]})}function Pa({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,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 we=M(De(),1);var ve=M(Q(),1);function Js({resultRef:s}){let{exit:e}=Jt(),t=(0,we.useRef)(new Ne),n=(0,we.useRef)(new rt),r=(0,we.useRef)(new xt),o=t.current,a=n.current,l=r.current,i=Nn(),[c,d]=(0,we.useState)("gate"),[m,g]=(0,we.useState)(null),[p,_]=(0,we.useState)(null),[y,C]=(0,we.useState)(null),[T,P]=(0,we.useState)(null),R=(0,we.useCallback)((N,B,u,w)=>l.log(N,B,u,w),[l]),O=(0,we.useCallback)((N,B)=>{let u=N?o.loadProfileConfig(N,B):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((N,B)=>{B.ctrl&&N==="c"&&Y(0,"Ctrl+C exit")});let oe=(0,we.useRef)(!1);we.default.useEffect(()=>{oe.current||(oe.current=!0,ar(o,R).then(N=>{g(N),N.status==="authenticated"?(O(N.result.profile,N.result.env),d("input")):N.status==="needs_pick"?d("pick"):(_(N.profile??null),C(N.env??null),d("login"))}).catch(N=>{P(`Auth check failed: ${N instanceof Error?N.message:String(N)}`)}))},[o,R]);let te=(0,we.useCallback)(N=>{s.current={objective:N},e()},[s,e]),ae=(0,we.useCallback)(async(N,B)=>{o.setActiveProfile(N),o.setDefaultEnv(B),(await Zt(o,N,B,R)).status==="authenticated"?(O(N,B),d("input")):(_(N),C(B),d("login"))},[o,R,O]),fe=(0,we.useCallback)(()=>{let N=o.getActiveProfile(),B=o.getDefaultEnv();if(!N)return null;let u=le(B),w=o.loadBasicAuth(N,B);return new mt(u.controllerBaseUrl,async()=>o.loadCredentials(N,B)?.access_token??null,w,R)},[o,R]);if(c==="gate")return(0,ve.jsx)(S,{paddingX:1,children:(0,ve.jsx)(f,{color:"yellow",children:"Checking authentication..."})});if(T)return(0,ve.jsxs)(S,{flexDirection:"column",paddingX:1,children:[(0,ve.jsx)(f,{color:"red",children:T}),(0,ve.jsx)(f,{color:"gray",children:"Press Ctrl+C to exit."})]});if(c==="pick"&&m?.status==="needs_pick")return(0,ve.jsx)(Oa,{profiles:m.profiles,onSelect:ae});if(c==="login"||c==="login-project"||c==="login-folder"){if(c==="login-project")return(0,ve.jsx)(Tt,{resolver:fe(),currentProjectId:null,env:y??"prod",onSelect:(N,B)=>{let u=p??o.getActiveProfile()??"default",w=y??o.getDefaultEnv();o.saveProfileConfig(u,w,{project_id:N,project_name:B}),d("login-folder")},onCancel:()=>{let N=p??o.getActiveProfile()??"default",B=y??o.getDefaultEnv();O(N,B),d("input")}});if(c==="login-folder"){let N=p??o.getActiveProfile()??"default",B=y??o.getDefaultEnv(),u=o.loadProfileConfig(N,B);return(0,ve.jsx)(It,{resolver:fe(),projectId:u?.project_id??"",currentFolderId:null,env:B,onSelect:(w,h)=>{o.saveProfileConfig(N,B,{folder_id:w,folder_name:h}),O(N,B),d("input")},onCancel:async()=>{if(u?.project_id)try{let w=le(B),h=o.loadBasicAuth(N,B);if(h){let L=await new lt(w.tmsBaseUrl,h.username,h.access_key).getDefaultFolder(u.project_id);L&&o.saveProfileConfig(N,B,{folder_id:L,folder_name:"Default"})}}catch{}O(N,B),d("input")}})}return(0,ve.jsx)(Xt,{devMode:process.env.KANE_DEV_MODE==="1",profiles:o.listProfiles(),onBasicLogin:(N,B,u,w)=>{o.saveBasicAuth(N,B,{username:u,access_key:w}),o.setActiveProfile(N),o.setDefaultEnv(B)},onOAuthLogin:async(N,B)=>{let{LoginFlow:u}=await import("./login-flow-TNDBDANY.js");o.setDefaultEnv(B),o.setActiveProfile(N),await new u(N,B,o).login()},onComplete:(N,B)=>{_(N),C(B),o.setActiveProfile(N),o.setDefaultEnv(B),d("login-project")},onCancel:()=>{Y(0,"Login cancelled")}})}return c==="input"?(0,ve.jsx)(Wn,{onSubmit:te,onEscape:()=>Y(0,"User pressed Escape"),history:i,placeholder:"Type an objective..."}):(0,ve.jsx)(ve.Fragment,{})}function Oa({profiles:s,onSelect:e}){let[t,n]=(0,we.useState)(0),[r,o]=(0,we.useState)(!1);return je((a,l)=>{if(!r){if(l.escape){Y(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)(S,{flexDirection:"column",paddingX:1,children:[(0,ve.jsx)(f,{color:"#ff9500",bold:!0,children:"Select a profile:"}),(0,ve.jsx)(S,{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)(S,{marginTop:1,children:(0,ve.jsx)(f,{color:"yellow",children:"Validating credentials..."})})]})}var li=M(ai(),1),{program:Kf,createCommand:Gf,createArgument:qf,createOption:zf,CommanderError:Jf,InvalidArgumentError:Xf,InvalidOptionArgumentError:Yf,Command:ci,Argument:Qf,Option:rn,Help:Zf}=li.default;import{join as Wt}from"path";var gi=M(De(),1);var Ze=M(De(),1);var Lt=M(Q(),1);function ui({steps:s,bifurcationInfo:e,perFlowMetadata:t}){return!e||e.isSingleFlow||!t||t.length<=1?null:(0,Lt.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,Lt.jsxs)(S,{flexDirection:"column",marginTop:r>0?1:0,children:[(0,Lt.jsxs)(S,{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)(en,{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 qe=M(Q(),1);function di({message:s,code:e,remediation:t,docsUrl:n}){return(0,qe.jsx)(Yo,{title:"Error",variant:"error",children:(0,qe.jsxs)(S,{flexDirection:"column",paddingY:1,children:[(0,qe.jsxs)(f,{color:v.red,bold:!0,children:[" \u2717 ",s]}),e&&(0,qe.jsxs)(S,{marginTop:0,marginLeft:5,children:[(0,qe.jsx)(f,{color:v.muted,children:"Code: "}),(0,qe.jsx)(f,{color:v.dimmed,children:e})]}),t&&(0,qe.jsxs)(S,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,qe.jsx)(f,{color:v.green,bold:!0,children:"Fix:"}),(0,qe.jsxs)(f,{color:v.cyan,children:["$ ",t]})]}),n&&(0,qe.jsxs)(S,{marginTop:1,marginLeft:5,children:[(0,qe.jsx)(f,{color:v.muted,children:"Docs: "}),(0,qe.jsx)(f,{color:v.cyan,underline:!0,children:n})]})]})})}var Re=M(Q(),1);function fi({config:s,spawnOpts:e,cancelRef:t,banner:n,onComplete:r,onStepEnd:o}){let{exit:a}=Jt(),l=ir(o),i=(0,Ze.useRef)(!1),c=(0,Ze.useRef)(!1),[d,m]=(0,Ze.useState)("");(0,Ze.useEffect)(()=>{i.current||(i.current=!0,l.startRun(s,e))},[s,e,l]),(0,Ze.useEffect)(()=>{t&&(t.current=()=>l.cancelRun())},[t,l]);let g=(0,Ze.useRef)(0);je((y,C)=>{C.ctrl&&y==="c"&&(l.isRunning?(g.current++,g.current>=2?a():l.cancelRun()):a())}),je((y,C)=>{l.askingUser&&(C.return?(l.sendAnswer(d),m("")):C.backspace||C.delete?m(T=>T.slice(0,-1)):y&&!C.ctrl&&!C.meta&&m(T=>T+y))},{isActive:!!l.askingUser}),(0,Ze.useEffect)(()=>{if(!l.isRunning&&l.lastRunEnd&&!c.current){c.current=!0;let{passed:y,failed:C,total:T}=Cn(l.steps),P=l.bifurcationInfo;r({lastRunEnd:l.lastRunEnd,stepsPassed:y,stepsFailed:C,stepsTotal:T,hadError:!1,bifurcationFlows:P&&!P.isSingleFlow?P.flows:null}),a()}},[l.isRunning,l.lastRunEnd,l.steps,r,a]),(0,Ze.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:y,failed:C,total:T}=Cn(l.steps);return{status:l.lastRunEnd.status,duration:l.lastRunEnd.duration??0,summary:l.lastRunEnd.summary??"",stepsPassed:y,stepsFailed:C,stepsTotal:T,reason:l.lastRunEnd.reason,finalState:l.lastRunEnd.final_state,creditsConsumed:l.lastRunEnd.credits_consumed}})():null,_=(0,Ze.useMemo)(()=>n?[{key:"banner",...n}]:[],[n]);return(0,Re.jsxs)(S,{flexDirection:"column",children:[(0,Re.jsx)(zt,{items:_,children:y=>(0,Re.jsxs)(S,{flexDirection:"column",marginBottom:1,children:[(0,Re.jsxs)(S,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,Re.jsx)(f,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,Re.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,Re.jsx)(f,{color:v.cyan,children:y.model}),(0,Re.jsx)(f,{color:v.dimmed,children:" \u2502 "}),(0,Re.jsx)(f,{color:v.dimmed,children:y.auth})]}),y.status?.map((C,T)=>(0,Re.jsx)(f,{color:v.dimmed,children:C},T))]},y.key)}),(()=>{let y=Xn({isRunning:l.isRunning,bifurcationInfo:l.bifurcationInfo,steps:l.steps,cmInitCounts:l.cmInitCounts});return y?(0,Re.jsx)(Jn,{label:y.label,hasBifurcation:y.hasBifurcation}):null})(),l.steps.length>0&&(0,Re.jsx)(qn,{steps:l.steps,bifurcated:!!l.bifurcationInfo&&!l.bifurcationInfo.isSingleFlow,flows:l.bifurcationInfo?.flows,cmInitCounts:l.cmInitCounts,staticSteps:!0}),l.askingUser&&(0,Re.jsxs)(S,{flexDirection:"column",marginTop:1,children:[(0,Re.jsxs)(f,{color:v.yellow,children:['Agent is asking: "',l.askingUser,'"']}),(0,Re.jsxs)(f,{children:["> ",d,"\u2588"]})]}),l.runError&&(0,Re.jsx)(di,{message:l.runError,code:"RUNNER_ERROR"}),p&&l.lastRunEnd&&(0,Re.jsx)(ui,{steps:l.steps,bifurcationInfo:l.bifurcationInfo,perFlowMetadata:l.lastRunEnd.per_flow_metadata??[]}),p&&(0,Re.jsx)(en,{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 za}from"readline";function on(s){process.stdout.write(JSON.stringify(s)+`
|
|
58
|
-
`)}async function mi(s,e,t){let n=sr(s,e);Fn().then(m=>{m&&on({type:"update_available",current:m.current,latest:m.latest,severity:m.severity})}).catch(()=>{});let r=za({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),on(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),on(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),on({type:"bifurcation",flows:p,count:_});break}case"ask_user":{let g=m;on({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,on({type:"error",message:m.message});break}default:break}return r.close(),await n.exited,{lastRunEnd:o,stepsTotal:l,hadError:a,bifurcationFlows:i}}var Ht=class extends Error{constructor(t,n){super(t);this.code=n;this.name="AuthError"}};async function xr(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 Ht("Not authenticated \u2014 no credentials found","not_authenticated");if(l=p.access_token,p.expires_at-Date.now()/1e3<300)try{let C=await Qn({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 Ht(`Token refresh failed: ${T}`,"refresh_failed")}}let i=le(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 Ja,rmSync as Xa}from"fs";import{join as Ya}from"path";import{tmpdir as Qa}from"os";async function pi(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=Ja(Ya(Qa(),"kane-clean-")),e=t;let r=t;Qe("tempDir",()=>{try{Xa(r,{recursive:!0,force:!0})}catch{}})}let n=await rr({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 In(s){let e=new ci;if(e.name("kane-cli").version(ht),s[0]==="--help"||s[0]==="-h"||s[0]==="help"){(async()=>{let{HelpView:n}=await import("./HelpView-64BD2OKB.js"),{render:r}=await import("./build-JIKYOZUH.js"),o=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=r(o.default.createElement(n));await a(),Y(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 rn("--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 rn("--model <name>","Model").default("v16-alpha").hideHelp()).option("--chrome-profile <path>","Chrome profile path").action(async n=>{let r=new Ne,o=new rt,a=n.env,l=n.profile;if(!process.stdin.isTTY||n.oauth||n.username){if(r.setDefaultEnv(a),n.oauth?(await new gn(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"),Y(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 xr({creds:r,env:a,log:()=>{}});if(T.resolvedCreds){let{TmsClient:P}=await import("./tms-client-VH42IFUF.js"),oe=(await new P(le(a).tmsBaseUrl,T.resolvedCreds.username,T.resolvedCreds.access_key).listProjects()).find(te=>te.name.toLowerCase().includes("kaneai"));oe&&(o.set("project_id",oe.project_id),console.log(`Auto-selected project: ${oe.name} (${oe.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-X5DLBHLV.js"),{ProjectPicker:c}=await import("./ProjectPicker-XL67H337.js"),{FolderPicker:d}=await import("./FolderPicker-TXCV7G4Y.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,oe)=>{r.saveBasicAuth(P,R,{username:O,access_key:oe}),r.setActiveProfile(P),r.setDefaultEnv(R),a=R,l=P},onOAuthLogin:async(P,R)=>{r.setDefaultEnv(R),await new gn(P,R,r).login(),a=R,l=P},onComplete:()=>{T(),C()},onCancel:()=>{p=!0,T(),C()}}))}),p)return;let _;try{_=(await xr({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 y=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),y=P,console.log(`Project set to ${R} (${P})`),T(),C()},onCancel:()=>{T(),C()}}))}),y&&(await new Promise(C=>{let{unmount:T}=m(g.default.createElement(d,{resolver:_,projectId:y,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()}}))}),Y(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 Zn(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-JYNYZVTK.js"),{render:_}=await import("./build-JIKYOZUH.js"),y=await import("./react-QWOAB3TB.js"),{waitUntilExit:C}=_(y.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 rt,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-DHYUHQTK.js"),{render:_}=await import("./build-JIKYOZUH.js"),y=await import("./react-QWOAB3TB.js"),{waitUntilExit:C}=_(y.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'."),Y(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>"),Y(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-GJA52BNZ.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>"),Y(1,"Missing project ID")),o.set("project_id",r),console.log(`Project set to ${r}`);return}let l=a.getDefaultEnv(),i=le(l),c=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!c){console.log("Login first to browse projects");return}let{ProjectPicker:d}=await import("./ProjectPicker-XL67H337.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(y=>{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(),y()},onCancel:()=>{C(),y()}}))})}else if(n==="folder"){if(r||!process.stdin.isTTY){if(r||(console.error("Usage: kane-cli config folder <folder-id>"),Y(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=le(i),d=a.loadBasicAuth(a.getActiveProfile()??"default",i);if(!d){console.log("Login first to browse folders");return}let{FolderPicker:m}=await import("./FolderPicker-TXCV7G4Y.js"),{AuthResolver:g}=await import("./resolver-QLDOAIXU.js"),{render:p}=await import("./build-JIKYOZUH.js"),_=await import("./react-QWOAB3TB.js"),y=new g(c.controllerBaseUrl,async()=>null,d);await y.resolve(),await new Promise(C=>{let{unmount:T}=p(_.default.createElement(m,{resolver:y,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: ${Wt(Ce,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new rn("--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 rn("--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 rn("--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
|
+
`);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",`
|
|
59
59
|
Variables:
|
|
60
60
|
Variables are loaded in order (later wins):
|
|
61
|
-
1. Global: ${
|
|
61
|
+
1. Global: ${Gt(Se,"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,19 +73,16 @@ Variables:
|
|
|
73
73
|
|
|
74
74
|
Context Files:
|
|
75
75
|
Context files provide additional instructions to the agent.
|
|
76
|
-
Global: ${
|
|
76
|
+
Global: ${Gt(Se,"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
|
|
81
|
-
`)},
|
|
82
|
-
Timeout: ${r.timeout}s exceeded \u2014 cancelling...`),
|
|
83
|
-
|
|
84
|
-
\u2713 Updated to ${a.toVersion}`),console.log("\nRun `kane-cli changelog` to see what's new.")):console.error(`
|
|
85
|
-
\u2717 Update failed: ${a.error}`)}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async n=>{let{fetchChangelog:r,formatChangelog:o}=await import("./changelog-IPUSJH3G.js"),a=await r({all:n.all});console.log(o(a))}),e.parse(["node","kane-cli",...s])}function hi(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 xi=Fn().catch(()=>null),wr=et.argv.slice(2),Za=wr.includes("--dev"),vi=wr.includes("--local"),el=wr.includes("--tui");Za&&(et.env.KANE_DEV_MODE="1");var tl=wr.filter(s=>!["--dev","--local","--tui"].includes(s)),yr=hi(tl),Kt=yr.filteredArgs,_i=yr.codeExport,To=yr.codeLanguage,Io=yr.skipCodeValidation,bi=()=>{xi.then(s=>{s&&et.stderr.write(`
|
|
86
|
-
Update available: ${s.current} \u2192 ${s.latest} \u2014 run \`kane-cli update\`
|
|
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
|
|
87
84
|
|
|
88
|
-
`)})},
|
|
89
|
-
`),
|
|
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.
|
|
90
87
|
Usage: kane-cli "objective" for non-interactive mode.
|
|
91
|
-
`),
|
|
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)})}
|