@testmuai/kane-cli 0.2.4 → 0.2.5
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-IRZUDC2R.js → ChromeProfilePicker-J34PIRKT.js} +1 -1
- package/dist/{CliFeedbackPrompt-RIIDDIY5.js → CliFeedbackPrompt-6BF5FIGV.js} +1 -1
- package/dist/{CliUploadProgress-QF57Z3FD.js → CliUploadProgress-OLN4CLU7.js} +1 -1
- package/dist/{ConfigView-5R4G4OZ6.js → ConfigView-P4W6OHZK.js} +1 -1
- package/dist/{FolderPicker-G4C4RCP2.js → FolderPicker-CJAJHSMM.js} +1 -1
- package/dist/HelpView-AZGTX7MR.js +2 -0
- package/dist/{LinksBox-623NMFSA.js → LinksBox-P7HGFKVG.js} +1 -1
- package/dist/{LoginWizard-SSE5NJVU.js → LoginWizard-LQKZ3AYY.js} +1 -1
- package/dist/{ProfilesView-DBNO4RSU.js → ProfilesView-RXVSD4YZ.js} +1 -1
- package/dist/{ProjectPicker-AFQDF2VS.js → ProjectPicker-GFSQKLDY.js} +1 -1
- package/dist/{WhoamiView-2VBZBQF7.js → WhoamiView-GVVXM665.js} +1 -1
- package/dist/{changelog-XYK3P4RQ.js → changelog-WS4VVR5W.js} +1 -1
- package/dist/{chunk-JXLB6N6Q.js → chunk-37E6GGJP.js} +1 -1
- package/dist/{chunk-KSHUUU2I.js → chunk-4XWNQQSQ.js} +1 -1
- package/dist/{chunk-B4K7UTF2.js → chunk-5DRGVR7L.js} +1 -1
- package/dist/{chunk-GNMGQOGV.js → chunk-6JF2T7BO.js} +1 -1
- package/dist/{chunk-LZZDLYE3.js → chunk-722N7IS6.js} +1 -1
- package/dist/{chunk-NRQDE7HH.js → chunk-C5U522LO.js} +1 -1
- package/dist/{chunk-XHPTLI5U.js → chunk-CVDB2PVG.js} +1 -1
- package/dist/{chunk-BSMUBGQO.js → chunk-F5NOXQWP.js} +1 -1
- package/dist/{chunk-RDG6MGL7.js → chunk-F6J3XGBQ.js} +1 -1
- package/dist/{chunk-IA4UI2BT.js → chunk-FH54KGU4.js} +1 -1
- package/dist/{chunk-3CJ6IY5O.js → chunk-GPQFSC4B.js} +1 -1
- package/dist/{chunk-RPQV6H45.js → chunk-I7KNK4LR.js} +1 -1
- package/dist/{chunk-426ZAKPO.js → chunk-UJP3DMYF.js} +1 -1
- package/dist/{chunk-GTYF5DR6.js → chunk-V77DQ5LB.js} +1 -1
- package/dist/{chunk-S2FLPRVR.js → chunk-W22K4TDJ.js} +1 -1
- package/dist/{controller-client-PS5GDXE3.js → controller-client-VI55T5AT.js} +1 -1
- package/dist/index.js +41 -41
- package/dist/{pipeline-7NY333ZT.js → pipeline-ZLHWF3V7.js} +1 -1
- package/dist/{resolver-L3Z6FAOD.js → resolver-XLRER3KZ.js} +1 -1
- package/dist/{updater-H5HYMYRG.js → updater-KDWM6PUM.js} +1 -1
- package/dist/{version-check-KS7CP3M5.js → version-check-YRWT2JIC.js} +1 -1
- package/package.json +4 -4
- package/dist/HelpView-2ZFLX7JC.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
3
|
-
import{a as Cn,b as En}from"./chunk-
|
|
4
|
-
`).replace(/^/gm," ".repeat(s))}let
|
|
5
|
-
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,n=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${s}]+`);if(e.match(a))return e;let o=t-r;if(o<n)return e;let l=e.slice(0,r),
|
|
3
|
+
import{a as Cn,b as En}from"./chunk-5DRGVR7L.js";import{a as ln,b as Gr,c as Zn,d as ts,e as ns}from"./chunk-4XWNQQSQ.js";import{a as ss}from"./chunk-FH54KGU4.js";import{c as Qr}from"./chunk-CVDB2PVG.js";import{b as Yn}from"./chunk-F5NOXQWP.js";import{b as Qn}from"./chunk-722N7IS6.js";import{a as ae,b as Xn}from"./chunk-I7KNK4LR.js";import{a as un}from"./chunk-C5U522LO.js";import{a as Zr,b as dn}from"./chunk-YNF4MUQP.js";import{a as es}from"./chunk-6JF2T7BO.js";import{a as rs}from"./chunk-UJP3DMYF.js";import{c as kn}from"./chunk-V77DQ5LB.js";import{a as cn}from"./chunk-GPQFSC4B.js";import{a as Ot}from"./chunk-I7YWZ3D2.js";import{b as Xr}from"./chunk-W22K4TDJ.js";import{b as Yr}from"./chunk-37E6GGJP.js";import{a as le}from"./chunk-HCBYKLMW.js";import{a as Pt,c as ye,d as Wr,g as Kn,h as qn,j as Jn,k as zn,l as Gn,m as Kr,n as qr,o as Jr,p as zr,r as m}from"./chunk-F6J3XGBQ.js";import{a as x,b as u,c as yn,d as Gt,i as et,j as Sn,k as Tt}from"./chunk-Q7JVDEOV.js";import{a as He}from"./chunk-6YGTRKDT.js";import{a as an,c as Nt,e as Z}from"./chunk-UR6MHSHU.js";var xn=Nt(Rr=>{"use strict";var Fn=class extends Error{constructor(e,t,r){super(r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},kr=class extends Fn{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Rr.CommanderError=Fn;Rr.InvalidArgumentError=kr});var Nn=Nt(Tr=>{"use strict";var{InvalidArgumentError:ua}=xn(),Ar=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new ua(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function da(i){let e=i.name()+(i.variadic===!0?"...":"");return i.required?"<"+e+">":"["+e+"]"}Tr.Argument=Ar;Tr.humanReadableArgName=da});var Or=Nt(uo=>{"use strict";var{humanReadableArgName:fa}=Nn(),Pr=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),r=e._getHelpCommand();return r&&!r._hidden&&t.push(r),this.sortSubcommands&&t.sort((n,s)=>n.name().localeCompare(s.name())),t}compareOptions(e,t){let r=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return r(e).localeCompare(r(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),r=e._getHelpOption();if(r&&!r.hidden){let n=r.short&&e._findOption(r.short),s=r.long&&e._findOption(r.long);!n&&!s?t.push(r):r.long&&!s?t.push(e.createOption(r.long,r.description)):r.short&&!n&&t.push(e.createOption(r.short,r.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let r=e.parent;r;r=r.parent){let n=r.options.filter(s=>!s.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(r=>fa(r)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((r,n)=>Math.max(r,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((r,n)=>Math.max(r,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((r,n)=>Math.max(r,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((r,n)=>Math.max(r,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let r="";for(let n=e.parent;n;n=n.parent)r=n.name()+" "+r;return r+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(r=>JSON.stringify(r)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let r=`(${t.join(", ")})`;return e.description?`${e.description} ${r}`:r}return e.description}formatHelp(e,t){let r=t.padWidth(e,t),n=t.helpWidth||80,s=2,a=2;function o(p,_){if(_){let v=`${p.padEnd(r+a)}${_}`;return t.wrap(v,n-s,r+a)}return p}function l(p){return p.join(`
|
|
4
|
+
`).replace(/^/gm," ".repeat(s))}let d=[`Usage: ${t.commandUsage(e)}`,""],c=t.commandDescription(e);c.length>0&&(d=d.concat([t.wrap(c,n,0),""]));let h=t.visibleArguments(e).map(p=>o(t.argumentTerm(p),t.argumentDescription(p)));h.length>0&&(d=d.concat(["Arguments:",l(h),""]));let g=t.visibleOptions(e).map(p=>o(t.optionTerm(p),t.optionDescription(p)));if(g.length>0&&(d=d.concat(["Options:",l(g),""])),this.showGlobalOptions){let p=t.visibleGlobalOptions(e).map(_=>o(t.optionTerm(_),t.optionDescription(_)));p.length>0&&(d=d.concat(["Global Options:",l(p),""]))}let S=t.visibleCommands(e).map(p=>o(t.subcommandTerm(p),t.subcommandDescription(p)));return S.length>0&&(d=d.concat(["Commands:",l(S),""])),d.join(`
|
|
5
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,r,n=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",a=new RegExp(`[\\n][${s}]+`);if(e.match(a))return e;let o=t-r;if(o<n)return e;let l=e.slice(0,r),d=e.slice(r).replace(`\r
|
|
6
6
|
`,`
|
|
7
|
-
`),
|
|
8
|
-
|.{1,${o-1}}([${
|
|
9
|
-
`?"":(
|
|
10
|
-
`)}};uo.Help=
|
|
7
|
+
`),c=" ".repeat(r),g="\\s\u200B",S=new RegExp(`
|
|
8
|
+
|.{1,${o-1}}([${g}]|$)|[^${g}]+?([${g}]|$)`,"g"),p=d.match(S)||[];return l+p.map((_,v)=>_===`
|
|
9
|
+
`?"":(v>0?c:"")+_.trimEnd()).join(`
|
|
10
|
+
`)}};uo.Help=Pr});var Br=Nt(Dr=>{"use strict";var{InvalidArgumentError:ma}=xn(),$r=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let r=ha(e);this.short=r.shortFlag,this.long=r.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,r)=>{if(!this.argChoices.includes(t))throw new ma(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,r):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return pa(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Ir=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,r)=>{this.positiveOptions.has(r)&&this.dualOptions.add(r)})}valueFromOption(e,t){let r=t.attributeName();if(!this.dualOptions.has(r))return!0;let n=this.negativeOptions.get(r).presetArg,s=n!==void 0?n:!1;return t.negate===(s===e)}};function pa(i){return i.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function ha(i){let e,t,r=i.split(/[ |,]+/);return r.length>1&&!/^[[<]/.test(r[1])&&(e=r.shift()),t=r.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}Dr.Option=$r;Dr.DualOptions=Ir});var mo=Nt(fo=>{"use strict";function ga(i,e){if(Math.abs(i.length-e.length)>3)return Math.max(i.length,e.length);let t=[];for(let r=0;r<=i.length;r++)t[r]=[r];for(let r=0;r<=e.length;r++)t[0][r]=r;for(let r=1;r<=e.length;r++)for(let n=1;n<=i.length;n++){let s=1;i[n-1]===e[r-1]?s=0:s=1,t[n][r]=Math.min(t[n-1][r]+1,t[n][r-1]+1,t[n-1][r-1]+s),n>1&&r>1&&i[n-1]===e[r-2]&&i[n-2]===e[r-1]&&(t[n][r]=Math.min(t[n][r],t[n-2][r-2]+1))}return t[i.length][e.length]}function va(i,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=i.startsWith("--");t&&(i=i.slice(2),e=e.map(a=>a.slice(2)));let r=[],n=3,s=.4;return e.forEach(a=>{if(a.length<=1)return;let o=ga(i,a),l=Math.max(i.length,a.length);(l-o)/l>s&&(o<n?(n=o,r=[a]):o===n&&r.push(a))}),r.sort((a,o)=>a.localeCompare(o)),t&&(r=r.map(a=>`--${a}`)),r.length>1?`
|
|
11
11
|
(Did you mean one of ${r.join(", ")}?)`:r.length===1?`
|
|
12
|
-
(Did you mean ${r[0]}?)`:""}fo.suggestSimilar=va});var
|
|
12
|
+
(Did you mean ${r[0]}?)`:""}fo.suggestSimilar=va});var xo=Nt(vo=>{"use strict";var xa=an("events").EventEmitter,jr=an("child_process"),yt=an("path"),Ur=an("fs"),Se=an("process"),{Argument:_a,humanReadableArgName:ba}=Nn(),{CommanderError:Vr}=xn(),{Help:wa}=Or(),{Option:po,DualOptions:ya}=Br(),{suggestSimilar:ho}=mo(),Lr=class i extends xa{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=>Se.stdout.write(t),writeErr:t=>Se.stderr.write(t),getOutHelpWidth:()=>Se.stdout.isTTY?Se.stdout.columns:void 0,getErrHelpWidth:()=>Se.stderr.isTTY?Se.stderr.columns:void 0,outputError:(t,r)=>r(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,r){let n=t,s=r;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,a,o]=e.match(/([^ ]+) *(.*)/),l=this.createCommand(a);return n&&(l.description(n),l._executableHandler=!0),s.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(s.noHelp||s.hidden),l._executableFile=s.executableFile||null,o&&l.arguments(o),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(e){return new i(e)}createHelp(){return Object.assign(new wa,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
13
13
|
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new _a(e,t)}argument(e,t,r,n){let s=this.createArgument(e,t);return typeof r=="function"?s.default(n).argParser(r):s.default(r),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,r,n]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",a=this.createCommand(r);return a.helpOption(!1),n&&a.arguments(n),s&&a.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=a,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let r=["preSubcommand","preAction","postAction"];if(!r.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
14
|
-
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new Vr(e,t,r)),
|
|
15
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),r=t(e).find(n=>this._findCommand(n));if(r){let n=t(this._findCommand(r)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let n=(s,a,o)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(r);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,a):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(r,s,o)};return this.on("option:"+t,s=>{let a=`error: option '${e.flags}' argument '${s}' is invalid.`;n(s,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let a=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;n(s,a,"env")}),this}_optionEx(e,t,r,n,s){if(typeof t=="object"&&t instanceof po)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,r);if(a.makeOptionMandatory(!!e.mandatory),typeof n=="function")a.default(s).argParser(n);else if(n instanceof RegExp){let o=n;n=(l,
|
|
14
|
+
Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,r){this._exitCallback&&this._exitCallback(new Vr(e,t,r)),Se.exit(e)}action(e){let t=r=>{let n=this.registeredArguments.length,s=r.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new po(e,t)}_callParseArg(e,t,r,n){try{return e.parseArg(t,r)}catch(s){if(s.code==="commander.invalidArgument"){let a=`${n} ${s.message}`;this.error(a,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let r=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${r}'
|
|
15
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),r=t(e).find(n=>this._findCommand(n));if(r){let n=t(this._findCommand(r)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),r=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(r,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(r,e.defaultValue,"default");let n=(s,a,o)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let l=this.getOptionValue(r);s!==null&&e.parseArg?s=this._callParseArg(e,s,l,a):s!==null&&e.variadic&&(s=e._concatValue(s,l)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(r,s,o)};return this.on("option:"+t,s=>{let a=`error: option '${e.flags}' argument '${s}' is invalid.`;n(s,a,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let a=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;n(s,a,"env")}),this}_optionEx(e,t,r,n,s){if(typeof t=="object"&&t instanceof po)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let a=this.createOption(t,r);if(a.makeOptionMandatory(!!e.mandatory),typeof n=="function")a.default(s).argParser(n);else if(n instanceof RegExp){let o=n;n=(l,d)=>{let c=o.exec(l);return c?c[0]:d},a.default(s).argParser(n)}else a.default(n);return this.addOption(a)}option(e,t,r,n){return this._optionEx({},e,t,r,n)}requiredOption(e,t,r,n){return this._optionEx({mandatory:!0},e,t,r,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,r){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=r,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(r=>{r.getOptionValueSource(e)!==void 0&&(t=r.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){Se.versions?.electron&&(t.from="electron");let n=Se.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=Se.argv),this.rawArgs=e.slice();let r;switch(t.from){case void 0:case"node":this._scriptPath=e[1],r=e.slice(2);break;case"electron":Se.defaultApp?(this._scriptPath=e[1],r=e.slice(2)):r=e.slice(1);break;case"user":r=e.slice(0);break;case"eval":r=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",r}parse(e,t){let r=this._prepareUserArgs(e,t);return this._parseCommand([],r),this}async parseAsync(e,t){let r=this._prepareUserArgs(e,t);return await this._parseCommand([],r),this}_executeSubCommand(e,t){t=t.slice();let r=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(c,h){let g=yt.resolve(c,h);if(Ur.existsSync(g))return g;if(n.includes(yt.extname(h)))return;let S=n.find(p=>Ur.existsSync(`${g}${p}`));if(S)return`${g}${S}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=e._executableFile||`${this._name}-${e._name}`,o=this._executableDir||"";if(this._scriptPath){let c;try{c=Ur.realpathSync(this._scriptPath)}catch{c=this._scriptPath}o=yt.resolve(yt.dirname(c),o)}if(o){let c=s(o,a);if(!c&&!e._executableFile&&this._scriptPath){let h=yt.basename(this._scriptPath,yt.extname(this._scriptPath));h!==this._name&&(c=s(o,`${h}-${e._name}`))}a=c||a}r=n.includes(yt.extname(a));let l;Se.platform!=="win32"?r?(t.unshift(a),t=go(Se.execArgv).concat(t),l=jr.spawn(Se.argv[0],t,{stdio:"inherit"})):l=jr.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=go(Se.execArgv).concat(t),l=jr.spawn(Se.execPath,t,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{Se.on(h,()=>{l.killed===!1&&l.exitCode===null&&l.kill(h)})});let d=this._exitCallback;l.on("close",c=>{c=c??1,d?d(new Vr(c,"commander.executeSubCommandAsync","(close)")):Se.exit(c)}),l.on("error",c=>{if(c.code==="ENOENT"){let h=o?`searched for local subcommand relative to directory '${o}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",g=`'${a}' does not exist
|
|
16
16
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
17
17
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
18
|
-
- ${h}`;throw new Error(
|
|
18
|
+
- ${h}`;throw new Error(g)}else if(c.code==="EACCES")throw new Error(`'${a}' not executable`);if(!d)Se.exit(1);else{let h=new Vr(1,"commander.executeSubCommandAsync","(error)");h.nestedError=c,d(h)}}),this.runningCommand=l}_dispatchSubcommand(e,t,r){let n=this._findCommand(e);n||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(r));else return n._parseCommand(t,r)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(r,n,s)=>{let a=n;if(n!==null&&r.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${r.name()}'.`;a=this._callParseArg(r,n,s,o)}return a};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((r,n)=>{let s=r.defaultValue;r.variadic?n<this.args.length?(s=this.args.slice(n),r.parseArg&&(s=s.reduce((a,o)=>e(r,o,a),r.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],r.parseArg&&(s=e(r,s,r.defaultValue))),t[n]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let r=e,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(a=>{n.push({hookedCommand:s,callback:a})})}),t==="postAction"&&n.reverse(),n.forEach(s=>{r=this._chainOrCall(r,()=>s.callback(s.hookedCommand,this))}),r}_chainOrCallSubCommandHook(e,t,r){let n=e;return this._lifeCycleHooks[r]!==void 0&&this._lifeCycleHooks[r].forEach(s=>{n=this._chainOrCall(n,()=>s(this,t))}),n}_parseCommand(e,t){let r=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(r.operands),t=r.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(r.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{r.unknown.length>0&&this.unknownOption(r.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let a;return a=this._chainOrCallHooks(a,"preAction"),a=this._chainOrCall(a,()=>this._actionHandler(this.processedArgs)),this.parent&&(a=this._chainOrCall(a,()=>{this.parent.emit(s,e,t)})),a=this._chainOrCallHooks(a,"postAction"),a}if(this.parent&&this.parent.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(r=>{let n=r.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(r=>r.conflictsWith.length>0).forEach(r=>{let n=e.find(s=>r.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(r,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],r=[],n=t,s=e.slice();function a(l){return l.length>1&&l[0]==="-"}let o=null;for(;s.length;){let l=s.shift();if(l==="--"){n===r&&n.push(l),n.push(...s);break}if(o&&!a(l)){this.emit(`option:${o.name()}`,l);continue}if(o=null,a(l)){let d=this._findOption(l);if(d){if(d.required){let c=s.shift();c===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,c)}else if(d.optional){let c=null;s.length>0&&!a(s[0])&&(c=s.shift()),this.emit(`option:${d.name()}`,c)}else this.emit(`option:${d.name()}`);o=d.variadic?d:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let d=this._findOption(`-${l[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,l.slice(2)):(this.emit(`option:${d.name()}`),s.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let d=l.indexOf("="),c=this._findOption(l.slice(0,d));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,l.slice(d+1));continue}}if(a(l)&&(n=r),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&r.length===0){if(this._findCommand(l)){t.push(l),s.length>0&&r.push(...s);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){t.push(l),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){r.push(l),s.length>0&&r.push(...s);break}}if(this._passThroughOptions){n.push(l),s.length>0&&n.push(...s);break}n.push(l)}return{operands:t,unknown:r}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let r=0;r<t;r++){let n=this.options[r].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
19
19
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
20
20
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
21
|
-
`),this.outputHelp({error:!0}));let r=t||{},n=r.exitCode||1,s=r.code||"commander.error";this._exit(n,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
22
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let n=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>
|
|
21
|
+
`),this.outputHelp({error:!0}));let r=t||{},n=r.exitCode||1,s=r.code||"commander.error";this._exit(n,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Se.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()}`,Se.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new ya(this.options),t=r=>this.getOptionValue(r)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(r));this.options.filter(r=>r.implied!==void 0&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(r=>{Object.keys(r.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,r.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=a=>{let o=a.attributeName(),l=this.getOptionValue(o),d=this.options.find(h=>h.negate&&o===h.attributeName()),c=this.options.find(h=>!h.negate&&o===h.attributeName());return d&&(d.presetArg===void 0&&l===!1||d.presetArg!==void 0&&l===d.presetArg)?d:c||a},n=a=>{let o=r(a),l=o.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${o.envVar}'`:`option '${o.flags}'`},s=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let a=s.createHelp().visibleOptions(s).filter(o=>o.long).map(o=>o.long);n=n.concat(a),s=s.parent}while(s&&!s._enablePositionalOptions);t=ho(e,n)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${r} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),t=ho(e,n)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let n=this.createOption(t,r);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
22
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let n=[r.name()].concat(r.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(r=>ba(r));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=yt.basename(e,yt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},r;return t.error?r=n=>this._outputConfiguration.writeErr(n):r=n=>this._outputConfiguration.writeOut(n),t.write=e.write||r,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let r=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",r)),this.emit("beforeHelp",r);let n=this.helpInformation(r);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");r.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",r),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",r))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Se.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
23
23
|
Expecting one of '${r.join("', '")}'`);let n=`${e}Help`;return this.on(n,s=>{let a;typeof t=="function"?a=t({error:s.error,command:s.command}):a=t,a&&s.write(`${a}
|
|
24
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function go(i){return i.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",n="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?n=s[3]:r=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],r=s[3],n=s[4]),t&&n!=="0"?`${t}=${r}:${parseInt(n)+1}`:e})}
|
|
25
|
-
`)}catch{}}};function as(i){let e=(0,is.useRef)(null);return e.current||(e.current=new er(i)),e.current}var
|
|
26
|
-
`),ms(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(e){let t=this.readConfig();t.active_profile=e,this.writeConfig(t)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(e){let t=this.readConfig();t.default_env=e,this.writeConfig(t)}credentialsPath(e,t){return
|
|
27
|
-
`),ms(e,384)}saveCredentials(e,t,r){this.writeSecure(this.credentialsPath(e,t),r)}loadCredentials(e,t){try{return JSON.parse(fn(this.credentialsPath(e,t),"utf-8"))}catch{return null}}saveClient(e,t,r){this.writeSecure(this.clientPath(e,t),r)}loadClient(e,t){try{return JSON.parse(fn(this.clientPath(e,t),"utf-8"))}catch{return null}}getActiveCredentials(){let e=this.getActiveProfile();if(!e)return{credentials:null,profile:null,env:null};let t=this.getDefaultEnv();return{credentials:this.loadCredentials(e,t),profile:e,env:t}}saveBasicAuth(e,t,r){this.writeSecure(this.basicAuthPath(e,t),r)}loadBasicAuth(e,t){try{return JSON.parse(fn(this.basicAuthPath(e,t),"utf-8"))}catch{return null}}deleteBasicAuth(e,t){try{dt(this.basicAuthPath(e,t))}catch{}}resolveAuth(){let e=this.getActiveProfile();if(!e)return null;let t=this.getDefaultEnv(),r=this.loadBasicAuth(e,t);return r?{method:"basic",...r,profile:e,env:t}:this.loadCredentials(e,t)?{method:"oauth",profile:e,env:t}:null}listProfiles(){let e=[];try{for(let t of sr(this.profilesDir)){let r=Me(this.profilesDir,t);try{for(let n of sr(r)){let s=Me(r,n),a=or(Me(s,"credentials")),o=or(Me(s,"client.json")),l=or(Me(s,"basic-auth"));(a||o||l)&&e.push({profile:t,env:n})}}catch{}}}catch{}return e}deleteProfile(e,t){try{dt(this.credentialsPath(e,t))}catch{}if(this.getActiveProfile()===e){let r=this.readConfig();delete r.active_profile,this.writeConfig(r)}}deleteProfileFull(e,t){if(t){try{dt(this.credentialsPath(e,t))}catch{}try{dt(this.clientPath(e,t))}catch{}try{dt(this.basicAuthPath(e,t))}catch{}try{dt(this.profileConfigPath(e,t))}catch{}}else try{let r=Me(this.profilesDir,e);for(let n of sr(r)){try{dt(Me(r,n,"credentials"))}catch{}try{dt(Me(r,n,"client.json"))}catch{}try{dt(Me(r,n,"basic-auth"))}catch{}try{dt(Me(r,n,"profile-config.json"))}catch{}}}catch{}}};var lr=G(ae(),1),ir=8,ar=7;function ps({onComplete:i}){let[e,t]=(0,Kt.useState)(0),[r,n]=(0,Kt.useState)(0),[s,a]=(0,Kt.useState)(!1),[o]=(0,Kt.useState)(()=>{let l=new Ee,c=l.getActiveProfile(),d=l.getDefaultEnv(),h=c?l.loadCredentials(c,d):null,x=c?l.loadBasicAuth(c,d):null;return{authenticated:!!(h||x),user:x?.username??c??null}});return an(()=>{t(l=>Math.min(ir,l+1))},e<ir?60:null),an(()=>{n(l=>Math.min(ar,l+1))},r<ar?80:null),(0,Kt.useEffect)(()=>{e>=ir&&r>=ar&&!s&&(a(!0),i?.())},[e,r,s,i]),(0,lr.jsx)(v,{flexDirection:"column",children:(0,lr.jsx)(An,{size:"full",helmetVisibleRows:e,textVisibleRows:r,showMeta:s,user:o.user,authenticated:o.authenticated,version:Pt})})}var vt=G(ae(),1);function hs({entry:i}){return i.type==="input"?(0,vt.jsxs)(v,{children:[(0,vt.jsx)(u,{color:m.purple,children:"\u276F "}),(0,vt.jsx)(u,{children:i.text})]}):i.type==="error"?(0,vt.jsx)(v,{marginLeft:2,children:(0,vt.jsx)(u,{color:m.red,children:i.text})}):(0,vt.jsx)(v,{marginLeft:2,children:(0,vt.jsx)(u,{color:i.type==="info"?m.dimmed:void 0,children:i.text})})}var $t=G(We(),1);var cr=G(We(),1);var ct=G(ae(),1);function gs({history:i,onSelect:e,onClose:t}){let[r,n]=(0,cr.useState)(""),[s,a]=(0,cr.useState)(0),o=r?i.search(r).slice(0,8):[];return Ze((l,c)=>{if(c.escape){t();return}if(c.return){o.length>0&&o[s]?e(o[s]):t();return}if(c.upArrow){a(d=>Math.max(0,d-1));return}if(c.downArrow){a(d=>Math.min(o.length-1,d+1));return}if(c.backspace||c.delete){n(d=>d.slice(0,-1)),a(0);return}l&&!c.ctrl&&!c.meta&&(n(d=>d+l),a(0))}),(0,ct.jsxs)(v,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,ct.jsx)(u,{color:m.muted,bold:!0,children:"reverse search"}),(0,ct.jsxs)(v,{gap:1,children:[(0,ct.jsx)(u,{color:m.dimmed,children:"search:"}),(0,ct.jsx)(u,{children:r}),(0,ct.jsx)(u,{color:m.purple,children:"\u2588"})]}),o.length>0&&(0,ct.jsx)(u,{children:" "}),o.map((l,c)=>(0,ct.jsx)(v,{marginLeft:2,children:(0,ct.jsxs)(u,{color:c===s?m.purple:m.dimmed,bold:c===s,children:[c===s?"\u25B8 ":" ",l]})},`${c}-${l}`))]})}var Ke=G(ae(),1);function xs({onSubmit:i,onEscape:e,history:t,placeholder:r="Type an objective or /command..."}){let[n,s]=(0,$t.useState)([]),[a,o]=(0,$t.useState)(0),[l,c]=(0,$t.useState)("none"),[d,h]=(0,$t.useState)(-1),x=(0,$t.useRef)(""),[S,p]=(0,$t.useState)(!0),{stdout:b}=Ot(),g=b?.columns??80,w=n.join(""),N=(()=>{if(l!=="none"||n.length===0||w.startsWith("/"))return"";let L=t.getAll();for(let M=L.length-1;M>=0;M--)if(L[M].startsWith(w)&&L[M]!==w)return L[M].slice(w.length);return""})();Ze((L,M)=>{if(S&&L&&p(!1),M.return){w.trim()&&(t.push(w.trim()),i(w.trim()),s([]),o(0),c("none"),h(-1),x.current="",p(!0));return}if(M.escape){l!=="none"?c("none"):n.length>0?(s([]),o(0),h(-1),x.current=""):e?.();return}if(M.tab){if(N){let A=w+N;s([...A]),o(A.length);return}return}if(M.ctrl&&L==="r"){c("search");return}if(M.ctrl&&L==="a"){o(0);return}if(M.ctrl&&L==="e"){o(n.length);return}if(M.ctrl&&L==="w"){if(a===0)return;let A=a-1;for(;A>0&&n[A]===" ";)A--;for(;A>0&&n[A-1]!==" ";)A--;let X=[...n.slice(0,A),...n.slice(a)];s(X),o(A);return}if(M.ctrl&&L==="u"){s([]),o(0),h(-1),c("none");return}if(M.meta&&L==="b"){let A=a-1;for(;A>0&&n[A]===" ";)A--;for(;A>0&&n[A-1]!==" ";)A--;o(Math.max(0,A));return}if(M.meta&&L==="f"){let A=a;for(;A<n.length&&n[A]!==" ";)A++;for(;A<n.length&&n[A]===" ";)A++;o(A);return}if(M.leftArrow){o(A=>Math.max(0,A-1));return}if(M.rightArrow){if(a>=n.length&&N){let A=w+N;s([...A]),o(A.length)}else o(A=>Math.min(n.length,A+1));return}if(M.upArrow){if(l==="none"){let A=t.getAll();if(A.length===0)return;if(d===-1){x.current=w,h(A.length-1);let X=A[A.length-1];s([...X]),o(X.length)}else if(d>0){let X=d-1;h(X);let f=A[X];s([...f]),o(f.length)}}return}if(M.downArrow){if(l==="none"){let A=t.getAll();if(d===-1)return;if(d<A.length-1){let X=d+1;h(X);let f=A[X];s([...f]),o(f.length)}else{h(-1);let X=x.current;s([...X]),o(X.length)}}return}if(M.backspace||M.delete){if(a>0){let A=[...n.slice(0,a-1),...n.slice(a)];s(A),o(a-1),h(-1)}return}if(L&&!M.ctrl&&!M.meta){let A=[...n.slice(0,a),...L,...n.slice(a)];s(A),o(a+L.length),h(-1)}},{isActive:l!=="search"});let W=L=>{s([...L]),o(L.length),c("none")},Q=()=>{c("none")},te=(()=>{if(S&&n.length===0)return null;let L=a>=n.length,M=n.slice(0,a).join(""),A=L?" ":n[a],X=L?"":n.slice(a+1).join(""),f="\u276F "+M+A+X+N,k=2,y=k+M.length,C=y+1,P=C+X.length,j=f.length,F=Math.max(1,Math.ceil(j/g)),Z=[];for(let Y=0;Y<F;Y++)Z.push({start:Y*g,end:Math.min((Y+1)*g,j)});return{full:f,p:k,b:y,c:C,a:P,lines:Z}})();return(0,Ke.jsxs)(v,{flexDirection:"column",children:[l==="search"&&(0,Ke.jsx)(gs,{history:t,onSelect:W,onClose:Q}),(0,Ke.jsx)(u,{color:m.muted,children:"\u2500".repeat(g)}),te===null?(0,Ke.jsxs)(v,{children:[(0,Ke.jsx)(u,{color:m.purple,children:"\u276F "}),(0,Ke.jsx)(u,{color:m.dimmed,children:r})]}):(0,Ke.jsx)(v,{flexDirection:"column",children:te.lines.map(({start:L,end:M},A)=>{let{full:X,p:f,b:k,c:y,a:C}=te,P=[];return M>0&&L<f&&P.push((0,Ke.jsx)(u,{color:m.purple,children:X.slice(Math.max(L,0),Math.min(f,M))},"p")),M>f&&L<k&&P.push((0,Ke.jsx)(u,{children:X.slice(Math.max(f,L),Math.min(k,M))},"b")),M>k&&L<y&&P.push((0,Ke.jsx)(u,{color:m.purple,inverse:!0,children:X.slice(Math.max(k,L),Math.min(y,M))},"c")),M>y&&L<C&&P.push((0,Ke.jsx)(u,{children:X.slice(Math.max(y,L),Math.min(C,M))},"a")),M>C&&P.push((0,Ke.jsx)(u,{color:m.dimmed,children:X.slice(Math.max(C,L),M)},"g")),(0,Ke.jsx)(v,{children:P},A)})})]})}var $e=G(We(),1);var bs=G(We(),1);var Tn=G(ae(),1),Ko="#ffc580",qo="#ffd9a8",vs="#ffffff";function _s({text:i,active:e=!0}){let[t,r]=(0,bs.useState)(0),n=4;if(an(()=>{r(a=>(a+1)%(i.length+n*2))},e?80:null),!e)return(0,Tn.jsx)(u,{color:vs,children:i});let s=i.split("").map((a,o)=>{let l=t-n,c=Math.abs(o-l-n/2),d;return c<=n/2?d=Ko:c<=n?d=qo:d=vs,(0,Tn.jsx)(u,{color:d,children:a},o)});return(0,Tn.jsx)(u,{children:s})}var qe=G(ae(),1),Jo={starting:m.cyan,running:m.purple,passed:m.green,failed:m.red,cancelled:m.dimmed,timed_out:m.yellow};function On({currentStep:i,maxSteps:e,elapsed:t,status:r}){let{stdout:n}=Ot(),s=n?.columns??80,a=Jo[r]??m.purple,o=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,qe.jsxs)(v,{flexDirection:"column",marginTop:1,children:[(0,qe.jsx)(u,{color:m.muted,children:"\u2500".repeat(Math.min(s,60))}),(0,qe.jsxs)(v,{children:[(0,qe.jsx)(u,{children:" "}),(0,qe.jsx)(u,{color:m.dimmed,children:"Steps "}),(0,qe.jsx)(u,{bold:!0,children:i}),(0,qe.jsxs)(u,{color:m.dimmed,children:["/",e]}),(0,qe.jsx)(u,{children:" "}),(0,qe.jsx)(u,{color:m.dimmed,children:"Elapsed "}),(0,qe.jsx)(u,{bold:!0,children:o}),(0,qe.jsx)(u,{children:" "}),(0,qe.jsx)(u,{color:m.dimmed,children:"Status "}),(0,qe.jsx)(u,{bold:!0,color:a,children:r})]})]})}var zo={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u26A1"};function ws(i){return zo[i]??"\u25CF"}var D=G(ae(),1);function Dt({step:i,indent:e=2}){let t=i.actionType?ws(i.actionType):null,r=i.status==="running",n=i.status==="passed",s=i.status==="failed",a=i.status==="pending"||i.status==="stopped",{stdout:o}=Ot(),l=o?.columns??80,c=Math.max(20,l-e-21),d=i.objective??"",h=d.length>c?d.slice(0,c-1)+"\u2026":d,x=(i.duration??0)*1e3,S=i.duration!=null?x<1e3?`${Math.round(x)}ms`:`${(x/1e3).toFixed(1)}s`:"";return(0,D.jsxs)(v,{flexDirection:"column",children:[(0,D.jsxs)(v,{marginLeft:e,children:[(0,D.jsx)(v,{width:4,children:(0,D.jsxs)(u,{color:m.muted,children:[String(i.index).padStart(2," ")," "]})}),(0,D.jsx)(v,{width:3,children:r?(0,D.jsx)(Gr,{}):n?(0,D.jsx)(u,{color:m.green,bold:!0,children:"\u2713"}):s?(0,D.jsx)(u,{color:m.red,bold:!0,children:"\u2717"}):(0,D.jsx)(u,{color:m.muted,children:"\u25CB"})}),(0,D.jsx)(v,{flexGrow:1,children:r?(0,D.jsx)(_s,{text:h,active:!0}):s?(0,D.jsx)(u,{color:m.red,children:h}):a?(0,D.jsx)(u,{color:m.dimmed,children:h}):(0,D.jsx)(u,{color:m.greenDim,children:h})}),(n||s)&&t?(0,D.jsx)(v,{width:3,marginLeft:1,children:(0,D.jsx)(u,{color:m.muted,children:t})}):(0,D.jsx)(v,{width:3,marginLeft:1}),(0,D.jsx)(v,{width:7,justifyContent:"flex-end",children:(0,D.jsx)(u,{color:m.dimmed,children:S})})]}),i.children&&i.children.length>0&&(0,D.jsx)(v,{flexDirection:"column",children:i.children.map((p,b)=>(0,D.jsx)(Dt,{step:p,indent:e+2},`child-${b}`))})]})}function Pn({steps:i,bifurcated:e,flows:t,cmInitCounts:r,maxSteps:n=50,staticSteps:s=!1,onStepCommit:a}){let o=(0,$e.useRef)(new Set),l=(0,$e.useRef)(!1),c=(0,$e.useRef)(new Set),d=(0,$e.useRef)(!1),h=(0,$e.useRef)(0);(0,$e.useEffect)(()=>{i.length===0&&h.current>0&&(o.current.clear(),l.current=!1,c.current.clear(),d.current=!1),h.current=i.length},[i.length]);let x=i.flatMap(f=>[f,...f.children??[]]),S=x.some(f=>f.status==="running"),p=x.some(f=>f.status==="failed"),b=x.length===0||x.every(f=>f.status==="pending"),g=x.filter(f=>f.status==="passed"||f.status==="failed").length,w;b?w="starting":S?w="running":p?w="failed":w="passed";let N=(0,$e.useRef)(null),[W,Q]=(0,$e.useState)(0);(0,$e.useEffect)(()=>{x.length===0||b?(N.current=null,Q(0)):S&&N.current==null&&(N.current=Date.now())},[S,b,x.length]),(0,$e.useEffect)(()=>{if(!S)return;let f=setInterval(()=>{N.current!=null&&Q((Date.now()-N.current)/1e3)},500);return()=>clearInterval(f)},[S]);let te=(0,$e.useRef)(new Set),[L,M]=(0,$e.useState)([]),A=(0,$e.useRef)(!1);(0,$e.useEffect)(()=>{if(!s||e)return;let f=[];if(!e&&!A.current&&r&&r[0]!=null&&(A.current=!0,f.push({key:"cm_init_0",type:"cm_init",count:r[0]})),e){!te.current.has(-1)&&i.length>0&&(te.current.add(-1),f.push({key:"bif_header",type:"bifurcation_header",flowCount:t?.length??i.length}));for(let k=0;k<i.length;k++){let y=i[k],C=-(k+10);te.current.has(C)||(te.current.add(C),f.push({key:`flow_header_${k}`,type:"flow_header",flowIdx:k,label:t?.[k]??y.objective,cmCount:r?.[k]}));for(let P of y.children??[])(P.status==="passed"||P.status==="failed")&&!te.current.has(P.index)&&(te.current.add(P.index),f.push({key:`step_f${k}_${P.index}`,type:"step",step:{...P}}))}}else for(let k of i)(k.status==="passed"||k.status==="failed")&&!te.current.has(k.index)&&(te.current.add(k.index),f.push({key:`step_${k.index}`,type:"step",step:{...k,children:k.children?[...k.children]:void 0}}));f.length>0&&M(k=>[...k,...f])},[i,e,t,r,s]),(0,$e.useEffect)(()=>{if(!a)return;!e&&!d.current&&r&&r[0]!=null&&(d.current=!0,a((0,D.jsx)(v,{marginLeft:2,children:(0,D.jsxs)(u,{color:m.dimmed,children:["\u25A0 Generated task with ",r[0]," checkpoints"]})}))),e&&t&&!l.current&&(l.current=!0,a((0,D.jsx)(u,{color:"#b388ff",children:"\u2501\u2501 Bifurcated into "+t.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"})));let f=e?i.flatMap((k,y)=>{let C=k.children??[];return!c.current.has(y)&&C.length>0&&(c.current.add(y),a((0,D.jsx)(u,{color:"#b388ff",children:" Flow "+(y+1)+": "+(t?.[y]??"")}))),C}):i.flatMap(k=>[k,...k.children??[]]);for(let k of f){let y=`${k.index}-${k.objective}`;o.current.has(y)||(k.status==="passed"||k.status==="failed"||k.status==="stopped")&&(o.current.add(y),a((0,D.jsx)(v,{marginLeft:2,children:(0,D.jsx)(Dt,{step:k})})))}},[i,a,e,t,r]);let X=[];if(a)if(e)for(let f of i){let y=(f.children??[]).filter(C=>{let P=`${C.index}-${C.objective}`;return!o.current.has(P)});y.length>0&&X.push({...f,children:y})}else for(let f of i){let k=`${f.index}-${f.objective}`;o.current.has(k)||X.push(f)}else if(s){if(!e)for(let f of i)te.current.has(f.index)||X.push(f)}if(!s){let f=a?X:i;return(0,D.jsxs)(v,{flexDirection:"column",children:[e?a?f.length>0?(0,D.jsx)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:f.map((y,C)=>(0,D.jsx)(v,{flexDirection:"column",marginTop:C>0?1:0,children:y.children&&y.children.length>0?y.children.map(P=>(0,D.jsx)(Dt,{step:P},`f${C}-${P.index}`)):y.status==="pending"&&(0,D.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})},C))}):null:(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,D.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",t?.length??i.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),i.map((y,C)=>(0,D.jsxs)(v,{flexDirection:"column",marginTop:C>0?1:0,children:[(0,D.jsxs)(u,{color:m.purple,children:["Flow ",C+1,": ",t?.[C]??y.objective]}),r&&r[C]!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",r[C]," checkpoints"]}),y.children&&y.children.length>0?y.children.map(P=>(0,D.jsx)(Dt,{step:P},`f${C}-${P.index}`)):y.status==="pending"&&(0,D.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},C))]}):(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&r&&r[0]!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",r[0]," checkpoints"]}),f.map(y=>(0,D.jsx)(Dt,{step:y},y.index))]}),S&&(0,D.jsx)(On,{currentStep:g,maxSteps:n,elapsed:W,status:w})]})}return e?(0,D.jsxs)(v,{flexDirection:"column",children:[(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,D.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",t?.length??i.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),i.map((f,k)=>(0,D.jsxs)(v,{flexDirection:"column",marginTop:k>0?1:0,children:[(0,D.jsxs)(u,{color:m.purple,children:["Flow ",k+1,": ",t?.[k]??f.objective]}),r&&r[k]!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",r[k]," checkpoints"]}),f.children&&f.children.length>0?f.children.map(y=>(0,D.jsx)(Dt,{step:y},`f${k}-${y.index}`)):f.status==="pending"&&(0,D.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},k))]}),S&&(0,D.jsx)(On,{currentStep:g,maxSteps:n,elapsed:W,status:w})]}):(0,D.jsxs)(v,{flexDirection:"column",children:[(0,D.jsx)(Xt,{items:L,children:f=>f.type==="cm_init"?(0,D.jsx)(v,{marginLeft:2,paddingLeft:1,children:(0,D.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",f.count," checkpoints"]})},f.key):f.type==="bifurcation_header"?(0,D.jsx)(v,{marginLeft:2,paddingLeft:1,children:(0,D.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",f.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},f.key):f.type==="flow_header"?(0,D.jsxs)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,D.jsxs)(u,{color:m.purple,children:["Flow ",f.flowIdx+1,": ",f.label]}),f.cmCount!=null&&(0,D.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",f.cmCount," checkpoints"]})]},f.key):(0,D.jsx)(v,{marginLeft:2,paddingLeft:1,children:(0,D.jsx)(Dt,{step:f.step})},f.key)}),X.length>0&&(0,D.jsx)(v,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:X.map(f=>(0,D.jsx)(Dt,{step:f},f.index))}),S&&(0,D.jsx)(On,{currentStep:g,maxSteps:n,elapsed:W,status:w})]})}var ke=G(We(),1);import{readFileSync as Go,writeFileSync as ys,mkdirSync as Ss}from"fs";import{dirname as Cs}from"path";var Es={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:null,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"action",setup_complete:!1},et=class{constructor(e=Wr){this.path=e}load(){try{let e=Go(this.path,"utf-8"),t=JSON.parse(e);return{...Es,...t}}catch{return{...Es}}}set(e,t){let r=this.load();r[e]=t,Ss(Cs(this.path),{recursive:!0}),ys(this.path,JSON.stringify(r,null,2)+`
|
|
24
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function go(i){return i.map(e=>{if(!e.startsWith("--inspect"))return e;let t,r="127.0.0.1",n="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?n=s[3]:r=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],r=s[3],n=s[4]),t&&n!=="0"?`${t}=${r}:${parseInt(n)+1}`:e})}vo.Command=Lr});var yo=Nt(st=>{"use strict";var{Argument:_o}=Nn(),{Command:Mr}=xo(),{CommanderError:Sa,InvalidArgumentError:bo}=xn(),{Help:Ca}=Or(),{Option:wo}=Br();st.program=new Mr;st.createCommand=i=>new Mr(i);st.createOption=(i,e)=>new wo(i,e);st.createArgument=(i,e)=>new _o(i,e);st.Command=Mr;st.Option=wo;st.Argument=_o;st.Help=Ca;st.CommanderError=Sa;st.InvalidArgumentError=bo;st.InvalidOptionArgumentError=bo});var Po=Z(He(),1);import jt from"process";var M=Z(He(),1);var ve=Z(le(),1);function os({profile:i,environment:e,model:t,tokenValid:r,sessionId:n,runCount:s,viewMode:a}){let{stdout:o}=Tt(),l=o?.columns??80,d=e==="stage";return(0,ve.jsxs)(x,{flexDirection:"column",children:[(0,ve.jsx)(u,{color:m.muted,children:"\u2500".repeat(l)}),(0,ve.jsx)(x,{paddingX:1,children:(0,ve.jsxs)(x,{gap:1,children:[(0,ve.jsx)(u,{color:m.dimmed,children:"Model:"}),(0,ve.jsx)(u,{color:m.dimmed,children:t}),(0,ve.jsx)(u,{color:m.muted,children:"|"}),(0,ve.jsx)(u,{color:m.dimmed,children:"Session:"}),(0,ve.jsx)(u,{color:m.dimmed,children:n.slice(-6)}),(0,ve.jsx)(u,{color:m.muted,children:"|"}),(0,ve.jsx)(u,{color:r?m.green:m.red,children:"\u25CF"}),(0,ve.jsx)(u,{color:m.dimmed,children:r?"authenticated":"not logged in"})]})}),(0,ve.jsx)(x,{paddingX:1,children:(0,ve.jsxs)(x,{gap:1,children:[(0,ve.jsx)(u,{color:m.dimmed,children:i??"no profile"}),(0,ve.jsx)(u,{color:m.muted,children:"|"}),d?(0,ve.jsx)(u,{color:m.yellow,bold:!0,children:"\u26A0 stage"}):(0,ve.jsx)(u,{color:m.green,children:e}),(0,ve.jsx)(u,{color:m.muted,children:"|"}),(0,ve.jsxs)(u,{color:m.dimmed,children:["runs: ",s]})]})}),(0,ve.jsx)(x,{paddingX:1,children:(0,ve.jsx)(u,{dimColor:!0,children:a==="chat"?"esc menu ctrl+c cancel/exit":"\u2191\u2193 navigate \u21B5 select esc back"})})]})}var is=Z(He(),1);import{readFileSync as Io,writeFileSync as Do,mkdirSync as Bo}from"fs";import{dirname as jo,join as Uo}from"path";var Vo=Uo(ye,"command-history.json"),Lo=200,er=class{entries;filePath;max;constructor(e=Vo,t=Lo){this.filePath=e,this.max=t,this.entries=this._load()}push(e){this.entries.length>0&&this.entries[this.entries.length-1]===e||(this.entries.push(e),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(e){let t=e.toLowerCase(),r=[];for(let n=this.entries.length-1;n>=0;n--)this.entries[n].toLowerCase().includes(t)&&r.push(this.entries[n]);return r}_load(){try{let e=Io(this.filePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}_save(){try{Bo(jo(this.filePath),{recursive:!0}),Do(this.filePath,JSON.stringify(this.entries)+`
|
|
25
|
+
`)}catch{}}};function as(i){let e=(0,is.useRef)(null);return e.current||(e.current=new er(i)),e.current}var Wt=Z(He(),1);var fn=[[[" "],[" "],[" "],[" "],["\u2584","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],[" "],[" "],[" "],[" "],[" "],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2584","#af87d7"],[" "],[" "],[" "],[" "]],[[" "],[" "],["\u2584","#875faf"],["\u2584","#af87d7","#875faf"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2584","#af87d7","#875faf"],["\u2584","#875faf"],[" "],[" "]],[[" "],[" "],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2584","#000000","#af87d7"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#303030"],["\u2584","#000000","#af87d7"],["\u2588","#af87d7"],["\u2588","#875faf"],[" "],[" "]],[[" "],["\u2588","#875faf"],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2584","#585858","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],["\u2588","#875faf"],[" "]],[[" "],["\u2588","#875faf"],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2588","#585858"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],["\u2588","#875faf"],[" "]],[[" "],[" "],["\u2588","#875faf"],["\u2588","#af87d7"],["\u2588","#000000"],["\u2584","#000000","#585858"],["\u2588","#000000"],["\u2588","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2584","#af87d7","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#000000"],["\u2588","#af87d7"],["\u2588","#875faf"],[" "],[" "]],[[" "],[" "],["\u2580","#875faf"],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2580","#875faf"],[" "],[" "]],[[" "],[" "],[" "],[" "],[" "],["\u2580","#af87d7"],["\u2580","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2588","#af87d7"],["\u2580","#af87d7"],["\u2580","#af87d7"],[" "],[" "],[" "],[" "],[" "]]];var te=Z(le(),1),Rn="#af87d7",tr="#875faf",ls="#5b3a7a",Mo="#ff9500",Fo="#ea580c",cs="#888888",nr="#666666",No="#555555",Ht=[[Rn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Rn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Rn,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[Rn,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[tr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[tr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588"],[tr,"\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588"]],rr=Ht.map(([,i])=>[...i]);function us({visibleRows:i=Ht.length}){let e=Math.min(i,Ht.length);return(0,te.jsxs)(x,{flexDirection:"column",children:[Ht.slice(0,e).map(([t,r],n)=>{let s=rr[n];return(0,te.jsx)(u,{children:s.map((a,o)=>{if(a==="\u2588")return(0,te.jsx)(u,{color:t,children:"\u2588"},o);let l=o>0&&s[o-1]==="\u2588",d=n>0&&o>0&&rr[n-1][o-1]==="\u2588";return l||d?(0,te.jsx)(u,{color:ls,children:"\u2592"},o):(0,te.jsx)(u,{children:" "},o)})},n)}),e>=Ht.length&&(0,te.jsxs)(u,{children:[" ",rr[Ht.length-1].map((t,r)=>t==="\u2588"?(0,te.jsx)(u,{color:ls,children:"\u2580"},r):(0,te.jsx)(u,{children:" "},r))]})]})}function Ho({visibleRows:i=fn.length}){let e=Math.min(i,fn.length);return(0,te.jsx)(x,{flexDirection:"column",children:fn.slice(0,e).map((t,r)=>(0,te.jsx)(u,{children:t.map((n,s)=>{let a=n[0],o=n[1],l=n[2];return o?(0,te.jsx)(u,{color:o,backgroundColor:l,children:a},s):(0,te.jsx)(u,{children:a},s)})},r))})}function An({size:i="compact",helmetVisibleRows:e=fn.length,textVisibleRows:t=Ht.length,showMeta:r=!1,user:n=null,authenticated:s=!1,version:a=""}){return i==="compact"?(0,te.jsx)(us,{}):(0,te.jsxs)(x,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,te.jsx)(u,{color:Mo,italic:!0,children:" Welcome to"}),(0,te.jsx)(u,{children:" "}),(0,te.jsxs)(x,{gap:2,children:[(0,te.jsx)(Ho,{visibleRows:e}),(0,te.jsxs)(x,{flexDirection:"column",children:[(0,te.jsx)(us,{visibleRows:t}),(0,te.jsx)(x,{justifyContent:"flex-end",width:73,children:(0,te.jsx)(u,{color:Fo,italic:!0,children:"Command-line interface"})})]})]}),r&&(0,te.jsxs)(te.Fragment,{children:[(0,te.jsx)(u,{children:" "}),(0,te.jsxs)(u,{children:[(0,te.jsx)(u,{color:nr,children:" Browser automation powered by AI. "}),(0,te.jsx)(u,{color:No,children:`v${a}`})]}),(0,te.jsx)(u,{children:" "}),(0,te.jsx)(u,{children:(0,te.jsx)(u,{color:nr,children:" KaneCLI can navigate websites, fill forms, test web UI, and extract"})}),(0,te.jsx)(u,{children:(0,te.jsx)(u,{color:nr,children:" data \u2014 right from your terminal."})}),(0,te.jsx)(u,{children:" "}),(0,te.jsxs)(u,{children:[(0,te.jsx)(u,{color:cs,children:" \u25CF "}),(0,te.jsx)(u,{color:cs,children:s?"Logged in as ":"Not logged in"}),s&&n&&(0,te.jsx)(u,{bold:!0,children:n})]})]})]})}import{readFileSync as mn,writeFileSync as ds,mkdirSync as fs,readdirSync as sr,unlinkSync as dt,existsSync as or,chmodSync as ms}from"fs";import{join as Le,dirname as Wo}from"path";var Re=class{baseDir;profilesDir;configFile;constructor(e=ye){this.baseDir=e,this.profilesDir=Le(e,"profiles"),this.configFile=Le(e,"config.json")}readConfig(){try{return JSON.parse(mn(this.configFile,"utf-8"))}catch{return{}}}writeConfig(e){fs(this.baseDir,{recursive:!0,mode:448}),ds(this.configFile,JSON.stringify(e,null,2)+`
|
|
26
|
+
`),ms(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(e){let t=this.readConfig();t.active_profile=e,this.writeConfig(t)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(e){let t=this.readConfig();t.default_env=e,this.writeConfig(t)}credentialsPath(e,t){return Le(this.profilesDir,e,t,"credentials")}clientPath(e,t){return Le(this.profilesDir,e,t,"client.json")}basicAuthPath(e,t){return Le(this.profilesDir,e,t,"basic-auth")}profileConfigPath(e,t){return Le(this.profilesDir,e,t,"profile-config.json")}saveProfileConfig(e,t,r){let n=this.loadProfileConfig(e,t)??{};this.writeSecure(this.profileConfigPath(e,t),{...n,...r})}loadProfileConfig(e,t){try{return JSON.parse(mn(this.profileConfigPath(e,t),"utf-8"))}catch{return null}}writeSecure(e,t){fs(Wo(e),{recursive:!0,mode:448}),ds(e,JSON.stringify(t,null,2)+`
|
|
27
|
+
`),ms(e,384)}saveCredentials(e,t,r){this.writeSecure(this.credentialsPath(e,t),r)}loadCredentials(e,t){try{return JSON.parse(mn(this.credentialsPath(e,t),"utf-8"))}catch{return null}}saveClient(e,t,r){this.writeSecure(this.clientPath(e,t),r)}loadClient(e,t){try{return JSON.parse(mn(this.clientPath(e,t),"utf-8"))}catch{return null}}getActiveCredentials(){let e=this.getActiveProfile();if(!e)return{credentials:null,profile:null,env:null};let t=this.getDefaultEnv();return{credentials:this.loadCredentials(e,t),profile:e,env:t}}saveBasicAuth(e,t,r){this.writeSecure(this.basicAuthPath(e,t),r)}loadBasicAuth(e,t){try{return JSON.parse(mn(this.basicAuthPath(e,t),"utf-8"))}catch{return null}}deleteBasicAuth(e,t){try{dt(this.basicAuthPath(e,t))}catch{}}resolveAuth(){let e=this.getActiveProfile();if(!e)return null;let t=this.getDefaultEnv(),r=this.loadBasicAuth(e,t);return r?{method:"basic",...r,profile:e,env:t}:this.loadCredentials(e,t)?{method:"oauth",profile:e,env:t}:null}listProfiles(){let e=[];try{for(let t of sr(this.profilesDir)){let r=Le(this.profilesDir,t);try{for(let n of sr(r)){let s=Le(r,n),a=or(Le(s,"credentials")),o=or(Le(s,"client.json")),l=or(Le(s,"basic-auth"));(a||o||l)&&e.push({profile:t,env:n})}}catch{}}}catch{}return e}deleteProfile(e,t){try{dt(this.credentialsPath(e,t))}catch{}if(this.getActiveProfile()===e){let r=this.readConfig();delete r.active_profile,this.writeConfig(r)}}deleteProfileFull(e,t){if(t){try{dt(this.credentialsPath(e,t))}catch{}try{dt(this.clientPath(e,t))}catch{}try{dt(this.basicAuthPath(e,t))}catch{}try{dt(this.profileConfigPath(e,t))}catch{}}else try{let r=Le(this.profilesDir,e);for(let n of sr(r)){try{dt(Le(r,n,"credentials"))}catch{}try{dt(Le(r,n,"client.json"))}catch{}try{dt(Le(r,n,"basic-auth"))}catch{}try{dt(Le(r,n,"profile-config.json"))}catch{}}}catch{}}};var lr=Z(le(),1),ir=8,ar=7;function ps({onComplete:i}){let[e,t]=(0,Wt.useState)(0),[r,n]=(0,Wt.useState)(0),[s,a]=(0,Wt.useState)(!1),[o]=(0,Wt.useState)(()=>{let l=new Re,d=l.getActiveProfile(),c=l.getDefaultEnv(),h=d?l.loadCredentials(d,c):null,g=d?l.loadBasicAuth(d,c):null;return{authenticated:!!(h||g),user:g?.username??d??null}});return ln(()=>{t(l=>Math.min(ir,l+1))},e<ir?60:null),ln(()=>{n(l=>Math.min(ar,l+1))},r<ar?80:null),(0,Wt.useEffect)(()=>{e>=ir&&r>=ar&&!s&&(a(!0),i?.())},[e,r,s,i]),(0,lr.jsx)(x,{flexDirection:"column",children:(0,lr.jsx)(An,{size:"full",helmetVisibleRows:e,textVisibleRows:r,showMeta:s,user:o.user,authenticated:o.authenticated,version:Pt})})}var xt=Z(le(),1);function hs({entry:i}){return i.type==="input"?(0,xt.jsxs)(x,{children:[(0,xt.jsx)(u,{color:m.purple,children:"\u276F "}),(0,xt.jsx)(u,{children:i.text})]}):i.type==="error"?(0,xt.jsx)(x,{marginLeft:2,children:(0,xt.jsx)(u,{color:m.red,children:i.text})}):(0,xt.jsx)(x,{marginLeft:2,children:(0,xt.jsx)(u,{color:i.type==="info"?m.dimmed:void 0,children:i.text})})}var $t=Z(He(),1);var cr=Z(He(),1);var at=Z(le(),1);function gs({history:i,onSelect:e,onClose:t}){let[r,n]=(0,cr.useState)(""),[s,a]=(0,cr.useState)(0),o=r?i.search(r).slice(0,8):[];return et((l,d)=>{if(d.escape){t();return}if(d.return){o.length>0&&o[s]?e(o[s]):t();return}if(d.upArrow){a(c=>Math.max(0,c-1));return}if(d.downArrow){a(c=>Math.min(o.length-1,c+1));return}if(d.backspace||d.delete){n(c=>c.slice(0,-1)),a(0);return}l&&!d.ctrl&&!d.meta&&(n(c=>c+l),a(0))}),(0,at.jsxs)(x,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,at.jsx)(u,{color:m.muted,bold:!0,children:"reverse search"}),(0,at.jsxs)(x,{gap:1,children:[(0,at.jsx)(u,{color:m.dimmed,children:"search:"}),(0,at.jsx)(u,{children:r}),(0,at.jsx)(u,{color:m.purple,children:"\u2588"})]}),o.length>0&&(0,at.jsx)(u,{children:" "}),o.map((l,d)=>(0,at.jsx)(x,{marginLeft:2,children:(0,at.jsxs)(u,{color:d===s?m.purple:m.dimmed,bold:d===s,children:[d===s?"\u25B8 ":" ",l]})},`${d}-${l}`))]})}var We=Z(le(),1);function vs({onSubmit:i,onEscape:e,history:t,placeholder:r="Type an objective or /command..."}){let[n,s]=(0,$t.useState)([]),[a,o]=(0,$t.useState)(0),[l,d]=(0,$t.useState)("none"),[c,h]=(0,$t.useState)(-1),g=(0,$t.useRef)(""),[S,p]=(0,$t.useState)(!0),{stdout:_}=Tt(),v=_?.columns??80,w=n.join(""),F=(()=>{if(l!=="none"||n.length===0||w.startsWith("/"))return"";let B=t.getAll();for(let $=B.length-1;$>=0;$--)if(B[$].startsWith(w)&&B[$]!==w)return B[$].slice(w.length);return""})();et((B,$)=>{if(S&&B&&p(!1),$.return){w.trim()&&(t.push(w.trim()),i(w.trim()),s([]),o(0),d("none"),h(-1),g.current="",p(!0));return}if($.escape){l!=="none"?d("none"):n.length>0?(s([]),o(0),h(-1),g.current=""):e?.();return}if($.tab){if(F){let E=w+F;s([...E]),o(E.length);return}return}if($.ctrl&&B==="r"){d("search");return}if($.ctrl&&B==="a"){o(0);return}if($.ctrl&&B==="e"){o(n.length);return}if($.ctrl&&B==="w"){if(a===0)return;let E=a-1;for(;E>0&&n[E]===" ";)E--;for(;E>0&&n[E-1]!==" ";)E--;let q=[...n.slice(0,E),...n.slice(a)];s(q),o(E);return}if($.ctrl&&B==="u"){s([]),o(0),h(-1),d("none");return}if($.meta&&B==="b"){let E=a-1;for(;E>0&&n[E]===" ";)E--;for(;E>0&&n[E-1]!==" ";)E--;o(Math.max(0,E));return}if($.meta&&B==="f"){let E=a;for(;E<n.length&&n[E]!==" ";)E++;for(;E<n.length&&n[E]===" ";)E++;o(E);return}if($.leftArrow){o(E=>Math.max(0,E-1));return}if($.rightArrow){if(a>=n.length&&F){let E=w+F;s([...E]),o(E.length)}else o(E=>Math.min(n.length,E+1));return}if($.upArrow){if(l==="none"){let E=t.getAll();if(E.length===0)return;if(c===-1){g.current=w,h(E.length-1);let q=E[E.length-1];s([...q]),o(q.length)}else if(c>0){let q=c-1;h(q);let f=E[q];s([...f]),o(f.length)}}return}if($.downArrow){if(l==="none"){let E=t.getAll();if(c===-1)return;if(c<E.length-1){let q=c+1;h(q);let f=E[q];s([...f]),o(f.length)}else{h(-1);let q=g.current;s([...q]),o(q.length)}}return}if($.backspace||$.delete){if(a>0){let E=[...n.slice(0,a-1),...n.slice(a)];s(E),o(a-1),h(-1)}return}if(B&&!$.ctrl&&!$.meta){let E=[...n.slice(0,a),...B,...n.slice(a)];s(E),o(a+B.length),h(-1)}},{isActive:l!=="search"});let K=B=>{s([...B]),o(B.length),d("none")},X=()=>{d("none")},W=(()=>{if(S&&n.length===0)return null;let B=a>=n.length,$=n.slice(0,a).join(""),E=B?" ":n[a],q=B?"":n.slice(a+1).join(""),f="\u276F "+$+E+q+F,R=2,y=R+$.length,C=y+1,O=C+q.length,V=f.length,N=Math.max(1,Math.ceil(V/v)),ee=[];for(let Y=0;Y<N;Y++)ee.push({start:Y*v,end:Math.min((Y+1)*v,V)});return{full:f,p:R,b:y,c:C,a:O,lines:ee}})();return(0,We.jsxs)(x,{flexDirection:"column",children:[l==="search"&&(0,We.jsx)(gs,{history:t,onSelect:K,onClose:X}),(0,We.jsx)(u,{color:m.muted,children:"\u2500".repeat(v)}),W===null?(0,We.jsxs)(x,{children:[(0,We.jsx)(u,{color:m.purple,children:"\u276F "}),(0,We.jsx)(u,{color:m.dimmed,children:r})]}):(0,We.jsx)(x,{flexDirection:"column",children:W.lines.map(({start:B,end:$},E)=>{let{full:q,p:f,b:R,c:y,a:C}=W,O=[];return $>0&&B<f&&O.push((0,We.jsx)(u,{color:m.purple,children:q.slice(Math.max(B,0),Math.min(f,$))},"p")),$>f&&B<R&&O.push((0,We.jsx)(u,{children:q.slice(Math.max(f,B),Math.min(R,$))},"b")),$>R&&B<y&&O.push((0,We.jsx)(u,{color:m.purple,inverse:!0,children:q.slice(Math.max(R,B),Math.min(y,$))},"c")),$>y&&B<C&&O.push((0,We.jsx)(u,{children:q.slice(Math.max(y,B),Math.min(C,$))},"a")),$>C&&O.push((0,We.jsx)(u,{color:m.dimmed,children:q.slice(Math.max(C,B),$)},"g")),(0,We.jsx)(x,{children:O},E)})})]})}var De=Z(He(),1);var _s=Z(He(),1);var Tn=Z(le(),1),Ko="#ffc580",qo="#ffd9a8",xs="#ffffff";function bs({text:i,active:e=!0}){let[t,r]=(0,_s.useState)(0),n=4;if(ln(()=>{r(a=>(a+1)%(i.length+n*2))},e?80:null),!e)return(0,Tn.jsx)(u,{color:xs,children:i});let s=i.split("").map((a,o)=>{let l=t-n,d=Math.abs(o-l-n/2),c;return d<=n/2?c=Ko:d<=n?c=qo:c=xs,(0,Tn.jsx)(u,{color:c,children:a},o)});return(0,Tn.jsx)(u,{children:s})}var Ke=Z(le(),1),Jo={starting:m.cyan,running:m.purple,passed:m.green,failed:m.red,cancelled:m.dimmed,timed_out:m.yellow};function Pn({currentStep:i,maxSteps:e,elapsed:t,status:r}){let{stdout:n}=Tt(),s=n?.columns??80,a=Jo[r]??m.purple,o=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`;return(0,Ke.jsxs)(x,{flexDirection:"column",marginTop:1,children:[(0,Ke.jsx)(u,{color:m.muted,children:"\u2500".repeat(Math.min(s,60))}),(0,Ke.jsxs)(x,{children:[(0,Ke.jsx)(u,{children:" "}),(0,Ke.jsx)(u,{color:m.dimmed,children:"Steps "}),(0,Ke.jsx)(u,{bold:!0,children:i}),(0,Ke.jsxs)(u,{color:m.dimmed,children:["/",e]}),(0,Ke.jsx)(u,{children:" "}),(0,Ke.jsx)(u,{color:m.dimmed,children:"Elapsed "}),(0,Ke.jsx)(u,{bold:!0,children:o}),(0,Ke.jsx)(u,{children:" "}),(0,Ke.jsx)(u,{color:m.dimmed,children:"Status "}),(0,Ke.jsx)(u,{bold:!0,color:a,children:r})]})]})}var zo={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u26A1"};function ws(i){return zo[i]??"\u25CF"}var j=Z(le(),1);function It({step:i,indent:e=2}){let t=i.actionType?ws(i.actionType):null,r=i.status==="running",n=i.status==="passed",s=i.status==="failed",a=i.status==="pending"||i.status==="stopped",{stdout:o}=Tt(),l=o?.columns??80,d=Math.max(20,l-e-21),c=i.objective??"",h=c.length>d?c.slice(0,d-1)+"\u2026":c,g=(i.duration??0)*1e3,S=i.duration!=null?g<1e3?`${Math.round(g)}ms`:`${(g/1e3).toFixed(1)}s`:"";return(0,j.jsxs)(x,{flexDirection:"column",children:[(0,j.jsxs)(x,{marginLeft:e,children:[(0,j.jsx)(x,{width:4,children:(0,j.jsxs)(u,{color:m.muted,children:[String(i.index).padStart(2," ")," "]})}),(0,j.jsx)(x,{width:3,children:r?(0,j.jsx)(Gr,{}):n?(0,j.jsx)(u,{color:m.green,bold:!0,children:"\u2713"}):s?(0,j.jsx)(u,{color:m.red,bold:!0,children:"\u2717"}):(0,j.jsx)(u,{color:m.muted,children:"\u25CB"})}),(0,j.jsx)(x,{flexGrow:1,children:r?(0,j.jsx)(bs,{text:h,active:!0}):s?(0,j.jsx)(u,{color:m.red,children:h}):a?(0,j.jsx)(u,{color:m.dimmed,children:h}):(0,j.jsx)(u,{color:m.greenDim,children:h})}),(n||s)&&t?(0,j.jsx)(x,{width:3,marginLeft:1,children:(0,j.jsx)(u,{color:m.muted,children:t})}):(0,j.jsx)(x,{width:3,marginLeft:1}),(0,j.jsx)(x,{width:7,justifyContent:"flex-end",children:(0,j.jsx)(u,{color:m.dimmed,children:S})})]}),i.children&&i.children.length>0&&(0,j.jsx)(x,{flexDirection:"column",children:i.children.map((p,_)=>(0,j.jsx)(It,{step:p,indent:e+2},`child-${_}`))})]})}function On({steps:i,bifurcated:e,flows:t,cmInitCounts:r,maxSteps:n=50,staticSteps:s=!1,onStepCommit:a}){let o=(0,De.useRef)(new Set),l=(0,De.useRef)(!1),d=(0,De.useRef)(new Set),c=(0,De.useRef)(!1),h=(0,De.useRef)(0);(0,De.useEffect)(()=>{i.length===0&&h.current>0&&(o.current.clear(),l.current=!1,d.current.clear(),c.current=!1),h.current=i.length},[i.length]);let g=i.flatMap(f=>[f,...f.children??[]]),S=g.some(f=>f.status==="running"),p=g.some(f=>f.status==="failed"),_=g.length===0||g.every(f=>f.status==="pending"),v=g.filter(f=>f.status==="passed"||f.status==="failed").length,w;_?w="starting":S?w="running":p?w="failed":w="passed";let F=(0,De.useRef)(null),[K,X]=(0,De.useState)(0);(0,De.useEffect)(()=>{g.length===0||_?(F.current=null,X(0)):S&&F.current==null&&(F.current=Date.now())},[S,_,g.length]),(0,De.useEffect)(()=>{if(!S)return;let f=setInterval(()=>{F.current!=null&&X((Date.now()-F.current)/1e3)},500);return()=>clearInterval(f)},[S]);let W=(0,De.useRef)(new Set),[B,$]=(0,De.useState)([]),E=(0,De.useRef)(!1);(0,De.useEffect)(()=>{if(!s||e)return;let f=[];if(!e&&!E.current&&r&&r[0]!=null&&(E.current=!0,f.push({key:"cm_init_0",type:"cm_init",count:r[0]})),e){!W.current.has(-1)&&i.length>0&&(W.current.add(-1),f.push({key:"bif_header",type:"bifurcation_header",flowCount:t?.length??i.length}));for(let R=0;R<i.length;R++){let y=i[R],C=-(R+10);W.current.has(C)||(W.current.add(C),f.push({key:`flow_header_${R}`,type:"flow_header",flowIdx:R,label:t?.[R]??y.objective,cmCount:r?.[R]}));for(let O of y.children??[])(O.status==="passed"||O.status==="failed")&&!W.current.has(O.index)&&(W.current.add(O.index),f.push({key:`step_f${R}_${O.index}`,type:"step",step:{...O}}))}}else for(let R of i)(R.status==="passed"||R.status==="failed")&&!W.current.has(R.index)&&(W.current.add(R.index),f.push({key:`step_${R.index}`,type:"step",step:{...R,children:R.children?[...R.children]:void 0}}));f.length>0&&$(R=>[...R,...f])},[i,e,t,r,s]),(0,De.useEffect)(()=>{if(!a)return;!e&&!c.current&&r&&r[0]!=null&&(c.current=!0,a((0,j.jsx)(x,{marginLeft:2,children:(0,j.jsxs)(u,{color:m.dimmed,children:["\u25A0 Generated task with ",r[0]," checkpoints"]})}))),e&&t&&!l.current&&(l.current=!0,a((0,j.jsx)(u,{color:"#b388ff",children:"\u2501\u2501 Bifurcated into "+t.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"})));let f=e?i.flatMap((R,y)=>{let C=R.children??[];return!d.current.has(y)&&C.length>0&&(d.current.add(y),a((0,j.jsx)(u,{color:"#b388ff",children:" Flow "+(y+1)+": "+(t?.[y]??"")}))),C}):i.flatMap(R=>[R,...R.children??[]]);for(let R of f){let y=`${R.index}-${R.objective}`;o.current.has(y)||(R.status==="passed"||R.status==="failed"||R.status==="stopped")&&(o.current.add(y),a((0,j.jsx)(x,{marginLeft:2,children:(0,j.jsx)(It,{step:R})})))}},[i,a,e,t,r]);let q=[];if(a)if(e)for(let f of i){let y=(f.children??[]).filter(C=>{let O=`${C.index}-${C.objective}`;return!o.current.has(O)});y.length>0&&q.push({...f,children:y})}else for(let f of i){let R=`${f.index}-${f.objective}`;o.current.has(R)||q.push(f)}else if(s){if(!e)for(let f of i)W.current.has(f.index)||q.push(f)}if(!s){let f=a?q:i;return(0,j.jsxs)(x,{flexDirection:"column",children:[e?a?f.length>0?(0,j.jsx)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:f.map((y,C)=>(0,j.jsx)(x,{flexDirection:"column",marginTop:C>0?1:0,children:y.children&&y.children.length>0?y.children.map(O=>(0,j.jsx)(It,{step:O},`f${C}-${O.index}`)):y.status==="pending"&&(0,j.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})},C))}):null:(0,j.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,j.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",t?.length??i.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),i.map((y,C)=>(0,j.jsxs)(x,{flexDirection:"column",marginTop:C>0?1:0,children:[(0,j.jsxs)(u,{color:m.purple,children:["Flow ",C+1,": ",t?.[C]??y.objective]}),r&&r[C]!=null&&(0,j.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",r[C]," checkpoints"]}),y.children&&y.children.length>0?y.children.map(O=>(0,j.jsx)(It,{step:O},`f${C}-${O.index}`)):y.status==="pending"&&(0,j.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},C))]}):(0,j.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!a&&r&&r[0]!=null&&(0,j.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",r[0]," checkpoints"]}),f.map(y=>(0,j.jsx)(It,{step:y},y.index))]}),S&&(0,j.jsx)(Pn,{currentStep:v,maxSteps:n,elapsed:K,status:w})]})}return e?(0,j.jsxs)(x,{flexDirection:"column",children:[(0,j.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,j.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",t?.length??i.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),i.map((f,R)=>(0,j.jsxs)(x,{flexDirection:"column",marginTop:R>0?1:0,children:[(0,j.jsxs)(u,{color:m.purple,children:["Flow ",R+1,": ",t?.[R]??f.objective]}),r&&r[R]!=null&&(0,j.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",r[R]," checkpoints"]}),f.children&&f.children.length>0?f.children.map(y=>(0,j.jsx)(It,{step:y},`f${R}-${y.index}`)):f.status==="pending"&&(0,j.jsx)(u,{color:m.dimmed,children:" \u25CB Waiting..."})]},R))]}),S&&(0,j.jsx)(Pn,{currentStep:v,maxSteps:n,elapsed:K,status:w})]}):(0,j.jsxs)(x,{flexDirection:"column",children:[(0,j.jsx)(Gt,{items:B,children:f=>f.type==="cm_init"?(0,j.jsx)(x,{marginLeft:2,paddingLeft:1,children:(0,j.jsxs)(u,{color:m.dimmed,children:["\u25AA Generated task with ",f.count," checkpoints"]})},f.key):f.type==="bifurcation_header"?(0,j.jsx)(x,{marginLeft:2,paddingLeft:1,children:(0,j.jsxs)(u,{color:m.dimmed,children:["\u2501\u2501 Bifurcated into ",f.flowCount," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]})},f.key):f.type==="flow_header"?(0,j.jsxs)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,j.jsxs)(u,{color:m.purple,children:["Flow ",f.flowIdx+1,": ",f.label]}),f.cmCount!=null&&(0,j.jsxs)(u,{color:m.dimmed,children:[" \u25AA Generated task with ",f.cmCount," checkpoints"]})]},f.key):(0,j.jsx)(x,{marginLeft:2,paddingLeft:1,children:(0,j.jsx)(It,{step:f.step})},f.key)}),q.length>0&&(0,j.jsx)(x,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:q.map(f=>(0,j.jsx)(It,{step:f},f.index))}),S&&(0,j.jsx)(Pn,{currentStep:v,maxSteps:n,elapsed:K,status:w})]})}var Ae=Z(He(),1);import{readFileSync as Go,writeFileSync as ys,mkdirSync as Ss}from"fs";import{dirname as Cs}from"path";var Es={window_size:{width:1920,height:1080},chrome_profile_path:"",default_url:null,model:"v16-alpha",project_id:null,project_name:null,folder_id:null,folder_name:null,mode:"action",setup_complete:!1},tt=class{constructor(e=Wr){this.path=e}load(){try{let e=Go(this.path,"utf-8"),t=JSON.parse(e);return{...Es,...t}}catch{return{...Es}}}set(e,t){let r=this.load();r[e]=t,Ss(Cs(this.path),{recursive:!0}),ys(this.path,JSON.stringify(r,null,2)+`
|
|
28
28
|
`)}save(e){let r={...this.load(),...e};Ss(Cs(this.path),{recursive:!0}),ys(this.path,JSON.stringify(r,null,2)+`
|
|
29
|
-
`)}};import{createServer as Ai}from"http";import{randomBytes as Ti}from"crypto";import{URL as
|
|
30
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as fi}from"util";import{execFile as mi}from"child_process";var pi=fi(mi),In={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},lc=new Map(Object.entries(In)),xr=class extends Error{};async function vr(i=pi){let{stdout:e}=await i("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new xr(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,n=r.lastIndexOf("."),s=r.lastIndexOf("-"),a=n===-1?void 0:r.slice(0,n),o=s===-1?void 0:r.slice(0,s);return In[r]??In[a]??In[o]??{name:r,id:r}}var xi=hi(gi),vi=i=>i.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function _r(){if(br.platform==="darwin"){let i=await hr();return{name:await gr(i),id:i}}if(br.platform==="linux"){let{stdout:i}=await xi("xdg-mime",["query","default","x-scheme-handler/http"]),e=i.trim();return{name:vi(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(br.platform==="win32")return vr();throw new Error("Only macOS, Linux, and Windows are supported")}var Si=_i(Ls.execFile),wr=Vs.dirname(bi(import.meta.url)),Is=Vs.join(wr,"xdg-open"),{platform:Yt,arch:$s}=js;async function Ci(){let i=await pr(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Us.from(e,"utf16le").toString("base64"),{stdout:r}=await Si(i,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=r.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[n]?{id:s[n]}:{}}var Ds=async(i,e)=>{let t;for(let r of i)try{return await e(r)}catch(n){t=n}throw t},$n=async i=>{if(i={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...i},Array.isArray(i.app))return Ds(i.app,o=>$n({...i,app:o}));let{name:e,arguments:t=[]}=i.app??{};if(t=[...t],Array.isArray(e))return Ds(e,o=>$n({...i,app:{name:o,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let o={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},c=Bt?await Ci():await _r();if(c.id in o){let d=o[c.id];return e==="browserPrivate"&&t.push(l[d]),$n({...i,app:{name:Jt[d],arguments:t}})}throw new Error(`${c.name} is not supported as a default browser`)}let r,n=[],s={};if(Yt==="darwin")r="open",i.wait&&n.push("--wait-apps"),i.background&&n.push("--background"),i.newInstance&&n.push("--new"),e&&n.push("-a",e);else if(Yt==="win32"||Bt&&!qt()&&!e){r=await pr(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Bt||(s.windowsVerbatimArguments=!0);let o=["Start"];i.wait&&o.push("-Wait"),e?(o.push(`"\`"${e}\`""`),i.target&&t.push(i.target)):i.target&&o.push(`"${i.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),o.push("-ArgumentList",t.join(","))),i.target=Us.from(o.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let o=!wr||wr==="/",l=!1;try{await wi.access(Is,yi.X_OK),l=!0}catch{}r=js.versions.electron??(Yt==="android"||o||!l)?"xdg-open":Is}t.length>0&&n.push(...t),i.wait||(s.stdio="ignore",s.detached=!0)}Yt==="darwin"&&t.length>0&&n.push("--args",...t),i.target&&n.push(i.target);let a=Ls.spawn(r,n,s);return i.wait?new Promise((o,l)=>{a.once("error",l),a.once("close",c=>{if(!i.allowNonzeroExitCode&&c>0){l(new Error(`Exited with code ${c}`));return}o(a)})}):(a.unref(),a)},Ei=(i,e)=>{if(typeof i!="string")throw new TypeError("Expected a `target`");return $n({...e,target:i})};function Bs(i){if(typeof i=="string"||Array.isArray(i))return i;let{[$s]:e}=i;if(!e)throw new Error(`${$s} is not supported`);return e}function Dn({[Yt]:i},{wsl:e}){if(e&&Bt)return Bs(e);if(!i)throw new Error(`${Yt} is not supported`);return Bs(i)}var Jt={};jt(Jt,"chrome",()=>Dn({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));jt(Jt,"brave",()=>Dn({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));jt(Jt,"firefox",()=>Dn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));jt(Jt,"edge",()=>Dn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));jt(Jt,"browser",()=>"browser");jt(Jt,"browserPrivate",()=>"browserPrivate");var Ms=Ei;import{createHash as ki,randomBytes as Ri}from"crypto";var Ge=class{authBaseUrl;consentUrl;constructor(e="prod"){let t=ce(e);this.authBaseUrl=t.authBaseUrl,this.consentUrl=t.consentUrl}static generatePkce(){let e=Ri(96).toString("base64url").slice(0,128),t=ki("sha256").update(e).digest("base64url");return[e,t]}buildAuthorizationUrl(e,t,r,n){let s=new URLSearchParams({response_type:"code",client_id:e,redirect_uri:n,scope:zr,code_challenge:t,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${s.toString()}`}async registerClient(e){let t=await fetch(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Jr,redirect_uris:[e],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!t.ok)throw new Error(`DCR failed: ${t.status} ${await t.text()}`);return t.json()}async exchangeCode(e,t,r,n){let s=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:n,client_id:t,code_verifier:r})});if(!s.ok)throw new Error(`Token exchange failed: ${s.status}`);return s.json()}async refreshToken(e,t){let r=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:t})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(e,t,r="access_token"){await fetch(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,token_type_hint:r,client_id:t})})}};var bt=class{profile;environment;creds;oauth;constructor(e="default",t="prod",r){this.profile=e,this.environment=t,this.creds=r??new Ee,this.oauth=new Ge(t)}async login(){let{server:e,port:t}=await this.startCallbackServer(),r=qr(t);try{let n=this.creds.loadClient(this.profile,this.environment);n||(n=await this.oauth.registerClient(r),this.creds.saveClient(this.profile,this.environment,n));let s=n.client_id,[a,o]=Ge.generatePkce(),l=Ti(32).toString("hex"),c=this.oauth.buildAuthorizationUrl(s,o,l,r),d=await this.waitForCallback(e,t,c,l);if(!d)throw new Error("Login cancelled or timed out");let h=await this.oauth.exchangeCode(d,s,a,r),x={access_token:h.access_token,refresh_token:h.refresh_token,expires_at:Math.floor(Date.now()/1e3)+h.expires_in,scope:h.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,x),this.creds.setActiveProfile(this.profile),x}catch(n){throw e.close(),n}}startCallbackServer(){return new Promise((e,t)=>{let r=zn,n=()=>{let s=Ai();s.on("error",a=>{a.code==="EADDRINUSE"&&r<Gn?(r++,n()):t(new Error(`Failed to start callback server: ${a.message}. Ports ${zn}-${Gn} are all in use.`))}),s.listen(r,Jn,()=>{e({server:s,port:r})})};n()})}waitForCallback(e,t,r,n){return new Promise(s=>{let a=!1,o=l=>{a||(a=!0,e.close(),s(l))};e.on("request",(l,c)=>{let d=new Oi(l.url??"/",`http://${Jn}:${t}`);if(d.pathname!==Kr){c.writeHead(404),c.end();return}let h=d.searchParams.get("state"),x=d.searchParams.get("code");if(d.searchParams.get("error")){c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Login Failed</h1><p>You can close this tab.</p></body></html>"),o(null);return}if(h!==n){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Invalid State</h1></body></html>"),o(null);return}c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Login Successful!</h1><p>You can close this tab and return to the terminal.</p></body></html>"),o(x)}),Ms(r).catch(()=>{}),setTimeout(()=>o(null),12e4)})}};var I=G(ae(),1),Ns="https://kaneai-playground.lambdatest.io";function Fs({onComplete:i}){let[e]=(0,ke.useState)(()=>new et),[t]=(0,ke.useState)(()=>new Ee),[r,n]=(0,ke.useState)(process.env.KANE_DEV_MODE==="1"?"env":"auth"),[s,a]=(0,ke.useState)(0),[o,l]=(0,ke.useState)(""),[c,d]=(0,ke.useState)("username"),[h,x]=(0,ke.useState)(""),[S,p]=(0,ke.useState)(null),[b,g]=(0,ke.useState)(!1),[w,N]=(0,ke.useState)([]),[W,Q]=(0,ke.useState)([]),[te,L]=(0,ke.useState)(null),M=(0,ke.useCallback)(y=>{a(0),l(""),p(null),n(y)},[]),A=(0,ke.useCallback)(()=>{e.set("default_url",Ns),e.set("setup_complete",!0),M("modes")},[e,M]),X=(0,ke.useCallback)(async()=>{let{credentials:y,profile:C,env:P}=t.getActiveCredentials();if(!y||!C||!P)return null;let j=y.expires_at,F=Date.now()/1e3;if(j-F<300){let Z=t.loadClient(C,P);if(!Z)return null;let ue=await new Ge(P).refreshToken(y.refresh_token,Z.client_id),oe={access_token:ue.access_token,refresh_token:ue.refresh_token,expires_at:Math.floor(F)+ue.expires_in,scope:ue.scope};return t.saveCredentials(C,P,oe),oe.access_token}return y.access_token},[t]),f=(0,ke.useCallback)(async()=>{n("loading-projects");try{let y=t.resolveAuth();if(!y)throw new Error("No auth configured");let C=t.getDefaultEnv(),P=ce(C),j,F;if(y.method==="basic")j=y.username,F=y.access_key;else{let oe=await X();if(!oe)throw new Error("Could not get OAuth token");let de=await new ln(P.controllerBaseUrl,oe).getTmsCredentials();j=de.username,F=de.access_key}let ue=(await new It(P.tmsBaseUrl,j,F).listProjects()).map(oe=>({id:oe.project_id,label:`${oe.name} (${oe.project_id})`,isActive:oe.name.toLowerCase().includes("kaneai")}));if(ue.length===0){p("No projects found."),A();return}N(ue),n("project")}catch(y){p(`Could not fetch projects: ${y instanceof Error?y.message:y}`),A()}},[t,X,M,A]),k=(0,ke.useCallback)(async y=>{n("loading-folders");try{let C=t.resolveAuth();if(!C)throw new Error("No auth configured");let P=t.getDefaultEnv(),j=ce(P),F,Z;if(C.method==="basic")F=C.username,Z=C.access_key;else{let de=await X();if(!de)throw new Error("Could not get OAuth token");let sn=await new ln(j.controllerBaseUrl,de).getTmsCredentials();F=sn.username,Z=sn.access_key}let Y=new It(j.tmsBaseUrl,F,Z),ue=await Y.listFolders(y),oe=await Y.getDefaultFolder(y).catch(()=>null);L(oe);let Te=ue.map(de=>({id:de.id,label:`${de.name} (${de.id}) \xB7 ${de.test_cases_count} tests`,isActive:de.id===oe}));if(Te.length===0){oe&&e.set("folder_id",oe),A();return}Q(Te),n("folder")}catch{A()}},[t,X,e,A]);return Ze((y,C)=>{if(!b&&!(r==="loading-projects"||r==="loading-folders")){if(r==="modes"){C.return&&(n("done"),setTimeout(i,300));return}if(r==="env"||r==="auth"){if(C.upArrow)a(j=>Math.max(0,j-1));else if(C.downArrow)a(j=>Math.min(1,j+1));else if(C.return){if(r==="env"){let j=s===0?"prod":"stage";t.setDefaultEnv(j),M("auth")}else if(r==="auth")if(s===0){g(!0);let j=t.getDefaultEnv(),F="default";t.setActiveProfile(F),new bt(F,j,t).login().then(()=>{g(!1),f()}).catch(Y=>{g(!1),p(`Login failed: ${Y.message}`)})}else M("auth-basic"),d("username")}return}if(r==="auth-basic"){if(C.return)if(c==="username"){if(!o.trim()){p("Username is required");return}x(o.trim()),l(""),d("access_key"),p(null)}else{if(!o.trim()){p("Access key is required");return}let P="default",j=t.getDefaultEnv();t.setActiveProfile(P),t.saveBasicAuth(P,j,{username:h,access_key:o.trim()}),f()}else C.backspace||C.delete?l(P=>P.slice(0,-1)):y&&!C.ctrl&&!C.meta&&l(P=>P+y);return}}},{isActive:r!=="project"&&r!=="folder"}),(0,I.jsx)(v,{flexDirection:"column",padding:1,children:(0,I.jsx)(Cn,{title:"Kane CLI \u2014 First-time Setup",variant:r==="done"?"success":"default",children:(0,I.jsxs)(v,{flexDirection:"column",paddingY:1,children:[r==="env"&&(0,I.jsxs)(v,{flexDirection:"column",marginBottom:1,children:[(0,I.jsxs)(v,{children:[(0,I.jsx)(u,{color:m.purple,children:"?"}),(0,I.jsx)(u,{bold:!0,children:" Select environment"})]}),(0,I.jsxs)(v,{marginLeft:2,flexDirection:"column",children:[(0,I.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","prod"]}),(0,I.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","stage"]})]})]}),r==="auth"&&(0,I.jsxs)(v,{flexDirection:"column",marginBottom:1,children:[(0,I.jsxs)(v,{children:[(0,I.jsx)(u,{color:m.purple,children:"?"}),(0,I.jsx)(u,{bold:!0,children:" Which authentication method?"})]}),(0,I.jsxs)(v,{marginLeft:2,flexDirection:"column",children:[(0,I.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","OAuth (browser login)"]}),(0,I.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","Basic (username + access key)"]})]}),b&&(0,I.jsx)(v,{marginTop:1,marginLeft:2,children:(0,I.jsx)(u,{color:m.cyan,children:"\u280B Opening browser for login\u2026"})})]}),r==="auth-basic"&&(0,I.jsxs)(v,{flexDirection:"column",children:[(0,I.jsxs)(v,{marginBottom:c==="access_key"?0:1,children:[(0,I.jsx)(u,{color:c==="access_key"?m.statusPass:m.primary,children:c==="access_key"?"\u2713":"?"}),(0,I.jsx)(u,{bold:!0,children:" Username: "}),c==="username"?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)(u,{color:m.base,children:o}),(0,I.jsx)(u,{color:m.primary,inverse:!0,children:" "})]}):(0,I.jsx)(u,{color:m.statusPass,children:h})]}),c==="access_key"&&(0,I.jsxs)(v,{marginBottom:1,children:[(0,I.jsx)(u,{color:m.primary,children:"?"}),(0,I.jsx)(u,{bold:!0,children:" Access Key: "}),(0,I.jsx)(u,{color:m.dim,children:"\u2022".repeat(o.length)}),(0,I.jsx)(u,{color:m.primary,inverse:!0,children:" "})]})]}),r==="loading-projects"&&(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.cyan,children:"\u280B Fetching projects\u2026"})}),r==="project"&&(0,I.jsx)(Xn,{title:"Select project",items:w,itemNoun:"projects",onSelect:y=>{e.set("project_id",y.id),k(y.id)},onCancel:()=>{A()}}),r==="loading-folders"&&(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.cyan,children:"\u280B Fetching folders\u2026"})}),r==="folder"&&(0,I.jsx)(Xn,{title:"Select folder",items:W,itemNoun:"folders",onSelect:y=>{e.set("folder_id",y.id),A()},onCancel:()=>{te&&e.set("folder_id",te),A()}}),r==="modes"&&(0,I.jsxs)(v,{flexDirection:"column",children:[(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.statusPass,bold:!0,children:"\u2713 Setup complete!"})}),(0,I.jsx)(v,{marginTop:1,children:(0,I.jsx)(En,{label:"Profile",value:t.getActiveProfile()??"default"})}),(0,I.jsx)(En,{label:"Environment",value:t.getDefaultEnv()}),(0,I.jsx)(En,{label:"Default URL",value:Ns}),(0,I.jsx)(v,{marginTop:1,flexDirection:"column",children:(0,I.jsx)(u,{bold:!0,color:m.primary,children:"Available modes:"})}),(0,I.jsxs)(v,{marginLeft:2,flexDirection:"column",marginTop:1,children:[(0,I.jsxs)(v,{children:[(0,I.jsx)(u,{bold:!0,color:m.base,children:"TUI "}),(0,I.jsx)(u,{color:m.dim,children:"Interactive menu + chat UI"})]}),(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.dim,children:" kane-cli"})}),(0,I.jsxs)(v,{marginTop:1,children:[(0,I.jsx)(u,{bold:!0,color:m.base,children:"CLI "}),(0,I.jsx)(u,{color:m.dim,children:"Headless single-run, JSON output"})]}),(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.dim,children:' kane-cli run "objective" --url <url>'})}),(0,I.jsxs)(v,{marginTop:1,children:[(0,I.jsx)(u,{bold:!0,color:m.base,children:"Agent "}),(0,I.jsx)(u,{color:m.dim,children:"Programmatic setup + run via CLI flags"})]}),(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.dim,children:" kane-cli setup --auth-method basic --username <u> --access-key <k>"})})]}),(0,I.jsxs)(v,{marginTop:1,children:[(0,I.jsx)(u,{color:m.dim,children:"Press "}),(0,I.jsx)(u,{bold:!0,color:m.primary,children:"Enter"}),(0,I.jsx)(u,{color:m.dim,children:" to launch TUI"})]})]}),r==="done"&&(0,I.jsx)(v,{children:(0,I.jsx)(u,{color:m.statusPass,bold:!0,children:"Launching\u2026"})}),S&&(0,I.jsx)(v,{marginTop:1,children:(0,I.jsx)(u,{color:m.red,children:S})})]})})})}var _t=G(We(),1);var Je=G(ae(),1);function Pi(i,e){let t=[],n=Math.max(e-4,30);t.push({type:"title",text:i.title});for(let s=0;s<i.sections.length;s++){let a=i.sections[s];s>0&&t.push({type:"divider",text:"\u2500".repeat(n)}),a.label&&t.push({type:"header",text:a.label});let o=a.entries.length>0?Math.max(...a.entries.map(l=>l.key.length)):0;for(let l of a.entries){let c="\xB7".repeat(Math.max(2,o-l.key.length+3)),d=`${l.key} ${c} ${l.value}`;t.push({type:"entry",text:d,color:l.color})}}return t.push({type:"footer",text:"esc back"}),t}function Hs({data:i,width:e=60}){let t=Pi(i,e);return(0,Je.jsx)(v,{flexDirection:"column",borderStyle:"round",borderColor:m.primary,paddingX:2,paddingY:1,children:t.map((r,n)=>{if(r.type==="title")return(0,Je.jsx)(u,{color:m.primary,bold:!0,children:r.text},n);if(r.type==="header")return(0,Je.jsx)(v,{marginTop:1,children:(0,Je.jsx)(u,{color:m.dim,children:r.text})},n);if(r.type==="divider")return(0,Je.jsx)(v,{marginTop:1,marginBottom:0,children:(0,Je.jsx)(u,{color:m.ambient,children:r.text})},n);if(r.type==="footer")return(0,Je.jsx)(v,{marginTop:1,children:(0,Je.jsx)(u,{color:m.dim,children:r.text})},n);let s=r.text.match(/^(.+?) (·+) (.+)$/);return s?(0,Je.jsxs)(u,{children:[(0,Je.jsxs)(u,{color:m.secondary,children:[s[1]," "]}),(0,Je.jsxs)(u,{color:m.ambient,children:[s[2]," "]}),(0,Je.jsx)(u,{color:r.color??m.base,children:s[3]})]},n):(0,Je.jsx)(u,{color:r.color??m.base,children:r.text},n)})})}var Ne=G(ae(),1);function Ws(i,e){let t=[];function r(n,s){for(let a of n)t.push({item:a,depth:s}),a.type==="submenu"&&a.children&&e.length>s&&e[s]===a.id&&r(a.children,s+1)}return r(i,0),t}function Ks({items:i,onRunSelected:e,renderLoginWizard:t,renderProfilesView:r,renderChromeProfilePicker:n,renderProjectPicker:s,renderFolderPicker:a}){let[o,l]=(0,_t.useState)({expandedPath:[],selectedIndex:0,inputValue:"",isEditing:!1,isSelecting:!1,feedback:null,activeView:null,infoData:null}),c=Ws(i,o.expandedPath),d=c[o.selectedIndex]?.item,h=(0,_t.useRef)(null),x=(0,_t.useCallback)(p=>{l(b=>({...b,feedback:p})),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{l(b=>({...b,feedback:null})),h.current=null},4e3)},[]);(0,_t.useEffect)(()=>()=>{h.current&&clearTimeout(h.current)},[]);let S=(0,_t.useCallback)(()=>{l(p=>({...p,activeView:null,infoData:null}))},[]);return Ze((p,b)=>{if(o.activeView==="infoView"){b.escape&&S();return}if(!(o.activeView==="loginWizard"||o.activeView==="profilesView"||o.activeView==="chromeProfilePicker"||o.activeView==="projectPicker"||o.activeView==="folderPicker")){if(o.isEditing){if(b.escape){l(g=>({...g,isEditing:!1,inputValue:""}));return}if(b.return){let g=o.inputValue.trim();if(d?.onValue&&g){let w=d.currentValue;d.onValue(g),x(w?`${d.label}: ${w} \u2192 ${g}`:`${d.label}: ${g}`)}l(w=>({...w,isEditing:!1,inputValue:""}));return}if(b.backspace||b.delete){l(g=>({...g,inputValue:g.inputValue.slice(0,-1)}));return}p&&!b.ctrl&&!b.meta&&l(g=>({...g,inputValue:g.inputValue+p}));return}if(o.isSelecting&&d?.options){let g=d.options;if(b.escape){l(w=>({...w,isSelecting:!1}));return}if(b.upArrow){l(w=>({...w,inputValue:String(Math.max(0,Number(w.inputValue||"0")-1))}));return}if(b.downArrow){l(w=>({...w,inputValue:String(Math.min(g.length-1,Number(w.inputValue||"0")+1))}));return}if(b.return){let w=Number(o.inputValue||"0"),N=g[w];if(N&&d.onValue){let W=d.currentValue;d.onValue(N.value),x(W?`${d.label}: ${W} \u2192 ${N.label}`:`${d.label}: ${N.label}`)}l(W=>({...W,isSelecting:!1,inputValue:""}));return}return}if(b.upArrow){l(g=>({...g,selectedIndex:Math.max(0,g.selectedIndex-1)}));return}if(b.downArrow){l(g=>({...g,selectedIndex:Math.min(c.length-1,g.selectedIndex+1)}));return}if(b.escape){l(g=>{if(g.expandedPath.length===0)return g;let w=g.expandedPath.slice(0,-1),N=Ws(i,w),W=g.expandedPath[g.expandedPath.length-1],Q=N.findIndex(te=>te.item.id===W);return{...g,expandedPath:w,selectedIndex:Q>=0?Q:0}});return}if(b.return&&d){if(d.id==="run-start"){e();return}if(d.type==="submenu"){let g=c[o.selectedIndex]?.depth??0;l(w=>({...w,expandedPath:[...w.expandedPath.slice(0,g),d.id],selectedIndex:w.selectedIndex+1}));return}if(d.onInfo){let g=d.onInfo();l(w=>({...w,activeView:"infoView",infoData:g}));return}if(d.onLoginWizard){d.onLoginWizard(),l(g=>({...g,activeView:"loginWizard"}));return}if(d.onProfilesView){d.onProfilesView(),l(g=>({...g,activeView:"profilesView"}));return}if(d.onChromeProfilePicker){d.onChromeProfilePicker(),l(g=>({...g,activeView:"chromeProfilePicker"}));return}if(d.onProjectPicker){d.onProjectPicker(),l(g=>({...g,activeView:"projectPicker"}));return}if(d.onFolderPicker){d.onFolderPicker(),l(g=>({...g,activeView:"folderPicker"}));return}if(d.type==="action"){d.onAction?.(),x(`${d.label} done`);return}if(d.type==="select"&&d.options){let g=d.options.findIndex(w=>w.value===d.currentValue);l(w=>({...w,isSelecting:!0,inputValue:String(Math.max(0,g))}));return}if(d.type==="text-input"){l(g=>({...g,isEditing:!0,inputValue:d.currentValue??""}));return}}}}),(0,Ne.jsx)(v,{flexDirection:"column",paddingX:1,children:o.activeView==="infoView"&&o.infoData?(0,Ne.jsx)(Hs,{data:o.infoData}):o.activeView==="loginWizard"&&t?t(S):o.activeView==="profilesView"&&r?r(S):o.activeView==="chromeProfilePicker"&&n?n(S):o.activeView==="projectPicker"&&s?s(S):o.activeView==="folderPicker"&&a?a(S):(0,Ne.jsxs)(Ne.Fragment,{children:[c.map(({item:p,depth:b},g)=>{let w=g===o.selectedIndex,N=" ".repeat(b),W=w?"\u276F ":" ",Q=p.type==="submenu"?o.expandedPath.includes(p.id)?"\u25BC ":"\u25B6 ":" ",te=p.currentValue!=null?` [${p.currentValue}]`:"";if(w&&o.isSelecting&&p.options){let L=Number(o.inputValue||"0");return(0,Ne.jsxs)(v,{flexDirection:"column",children:[(0,Ne.jsxs)(u,{color:m.cyan,children:[N,W,Q,p.label]}),p.options.map((M,A)=>(0,Ne.jsxs)(u,{color:A===L?m.cyan:void 0,children:[N," ",A===L?"\u276F ":" ",M.label]},M.value))]},p.id)}return w&&o.isEditing?(0,Ne.jsxs)(u,{color:m.cyan,children:[N,W,Q,p.label,": ",o.inputValue,(0,Ne.jsx)(u,{color:m.dimmed,children:"\u2588"})]},p.id):(0,Ne.jsxs)(u,{color:w?m.cyan:void 0,dimColor:!w&&b>0,children:[N,W,Q,p.label,(0,Ne.jsx)(u,{dimColor:!0,children:te})]},p.id)}),o.feedback&&(0,Ne.jsx)(v,{marginTop:1,children:(0,Ne.jsxs)(u,{color:m.green,children:["\u2713 ",o.feedback]})})]})})}import{randomBytes as Ii,randomUUID as $i}from"crypto";import{mkdirSync as Di,writeFileSync as qs,appendFileSync as Bi,existsSync as Js}from"fs";import{join as mn}from"path";var ji=mn(_e,"sessions"),Qt=class{sessionId;sessionDir;runs=[];_nextIndex=0;_started=!1;_testId=null;_testcaseId=null;_projectId=null;_uploadStatus="pending";_uploadAttempts=0;_uploadError=null;_firstObjective=null;_firstUrl=null;_commitId=null;_auteurVariables={};_screenshotSas=null;_model="";_environment="";_profile=null;_startedAt="";constructor(){let e=new Date,t=e.toISOString().slice(0,10),r=e.toTimeString().slice(0,8).replace(/:/g,"-"),n=Ii(3).toString("hex");this.sessionId=`${t}_${r}_${n}`,this.sessionDir=mn(ji,this.sessionId)}start(e){if(this._started)return;this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString(),Di(this.sessionDir,{recursive:!0});let t={session_id:this.sessionId,started_at:this._startedAt,model:e.model,environment:e.environment,profile:e.profile,objectives:[],runs:[],status:"in_progress"};qs(mn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
|
|
31
|
-
`),this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`)}setAuteurVariables(e){Object.assign(this._auteurVariables,e)}get auteurVariables(){return this._auteurVariables}setScreenshotSas(e){this._screenshotSas=e}get screenshotSas(){return this._screenshotSas}get screenshotBaseUrl(){return this._screenshotSas?`${this._screenshotSas.base_url}/${this._screenshotSas.container}`:""}get startedAt(){return this._startedAt||new Date().toISOString()}log(e){this._log(e)}logCommand(e){this._log(`COMMAND ${e}`)}logRunStart(e,t,r){this._log(`RUN ${e} START objective="${t.slice(0,100)}" url=${r}`)}logRunEnd(e,t,r,n){let s=(r??0).toFixed(1),a=(n??"").slice(0,100);this._log(`RUN ${e} END status=${t} duration=${s}s summary="${a}"`)}logChromeLaunch(e,t){this._log(`CHROME LAUNCH port=${e} endpoint=${t}`)}finish(e="complete"){this._log(`SESSION END status=${e} total_runs=${this.runs.length}`);let t={session_id:this.sessionId,started_at:this._startedAt,ended_at:new Date().toISOString(),model:this._model,environment:this._environment,profile:this._profile,status:e,total_runs:this.runs.length,test_id:this._testId,testcase_id:this._testcaseId,commit_id:this.
|
|
32
|
-
`)}nextRunIndex(){return this._nextIndex}addRunResult(e,t){this.runs.push(e),this._nextIndex+=t??1}getContext(){return{prior_runs:this.runs.map(e=>({index:e.index,objective:e.objective,summary:e.summary,status:e.status,memory:e.context.memory,variables:e.context.variables,pointer:e.context.pointer}))}}setTestId(e){this._testId=e}get testId(){return this._testId}setTestcaseId(e){this._testcaseId=e}get testcaseId(){return this._testcaseId}setProjectId(e){this._projectId=e}setFirstRun(e,t){this._firstObjective||(this._firstObjective=e,this._firstUrl=t)}get firstObjective(){return this._firstObjective}get firstUrl(){return this._firstUrl}
|
|
33
|
-
`)}};var Fe=
|
|
34
|
-
`);let s=1e5,a="";n.stderr.on("data",h=>{a+=h.toString(),a.length>s&&(a=a.slice(-s))});let o=null,l=null,
|
|
35
|
-
`)}catch{}},sendCancel(h){let
|
|
36
|
-
`)}catch{}},cancel(){n.kill("SIGTERM")},get stderr(){return a},get exitCode(){return o},get exitSignal(){return l},exited:
|
|
37
|
-
`))}t(!1),
|
|
38
|
-
`)),t(!1),
|
|
39
|
-
`).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function Er({status:i,summary:e,duration:t,steps:r,stepsPassed:n,stepsFailed:s,reason:a}){let o=i==="passed",l=o?m.green:m.red,c=o?"\u2713":"\u2717",d=i.toUpperCase(),h=n??(o?r:Math.max(0,r-1)),x=s??(o?0:1),S=x>0?`${r} steps (${h} passed, ${x} failed)`:`${r} steps`,p=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,b=aa(e);return(0,Xe.jsx)(v,{flexDirection:"column",marginTop:1,children:(0,Xe.jsxs)(v,{borderStyle:"round",borderColor:l,flexDirection:"column",paddingX:2,paddingY:1,width:ia+6,children:[(0,Xe.jsxs)(v,{children:[(0,Xe.jsxs)(u,{bold:!0,color:l,children:[c," ",d]}),(0,Xe.jsxs)(u,{color:m.dimmed,children:[" ","\xB7 ",S," \xB7 ",p]})]}),b.length>0&&(0,Xe.jsx)(v,{flexDirection:"column",marginTop:1,marginLeft:1,children:b.map((g,w)=>(0,Xe.jsxs)(v,{marginBottom:w<b.length-1?1:0,children:[(0,Xe.jsx)(u,{color:m.primary,children:"\u25CF "}),(0,Xe.jsx)(v,{flexShrink:1,children:(0,Xe.jsx)(u,{wrap:"wrap",children:g})})]},w))}),a&&!o&&(0,Xe.jsx)(v,{marginTop:1,children:(0,Xe.jsxs)(u,{color:m.red,wrap:"wrap",children:["Reason: ",a]})})]})})}var Ye=G(ae(),1);function oo({message:i,code:e,remediation:t,docsUrl:r}){return(0,Ye.jsx)(Cn,{title:"Error",variant:"error",children:(0,Ye.jsxs)(v,{flexDirection:"column",paddingY:1,children:[(0,Ye.jsxs)(u,{color:m.red,bold:!0,children:[" \u2717 ",i]}),e&&(0,Ye.jsxs)(v,{marginTop:0,marginLeft:5,children:[(0,Ye.jsx)(u,{color:m.muted,children:"Code: "}),(0,Ye.jsx)(u,{color:m.dimmed,children:e})]}),t&&(0,Ye.jsxs)(v,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,Ye.jsx)(u,{color:m.green,bold:!0,children:"Fix:"}),(0,Ye.jsxs)(u,{color:m.cyan,children:["$ ",t]})]}),r&&(0,Ye.jsxs)(v,{marginTop:1,marginLeft:5,children:[(0,Ye.jsx)(u,{color:m.muted,children:"Docs: "}),(0,Ye.jsx)(u,{color:m.cyan,underline:!0,children:r})]})]})})}var Ae=G(ae(),1);function io({data:i,color:e}){let t=i.status==="passed"?"passed":"failed";return(0,Ae.jsx)(Er,{status:t,summary:i.summary??"",duration:i.duration,steps:i.stepsTotal,stepsPassed:i.stepsPassed,stepsFailed:i.stepsFailed,reason:i.reason})}function ao({config:i,spawnOpts:e,cancelRef:t,banner:r,onComplete:n,onStepEnd:s}){let{exit:a}=Sn(),o=Vn(s),l=(0,tt.useRef)(!1),c=(0,tt.useRef)(!1),[d,h]=(0,tt.useState)("");(0,tt.useEffect)(()=>{l.current||(l.current=!0,o.startRun(i,e))},[i,e,o]),(0,tt.useEffect)(()=>{t&&(t.current=()=>o.cancelRun())},[t,o]);let x=(0,tt.useRef)(0);Ze((b,g)=>{g.ctrl&&b==="c"&&(o.isRunning?(x.current++,x.current>=2?a():o.cancelRun()):a())}),Ze((b,g)=>{o.askingUser&&(g.return?(o.sendAnswer(d),h("")):g.backspace||g.delete?h(w=>w.slice(0,-1)):b&&!g.ctrl&&!g.meta&&h(w=>w+b))},{isActive:!!o.askingUser}),(0,tt.useEffect)(()=>{if(!o.isRunning&&o.lastRunEnd&&!c.current){c.current=!0;let b=o.steps.flatMap(Q=>{let te=Q.children??[];return[Q,...te]}),g=b.filter(Q=>Q.status==="passed").length,w=b.filter(Q=>Q.status==="failed").length,N=b.filter(Q=>Q.status==="passed"||Q.status==="failed").length,W=o.bifurcationInfo;n({lastRunEnd:o.lastRunEnd,stepsPassed:g,stepsFailed:w,stepsTotal:N,hadError:!1,bifurcationFlows:W&&!W.isSingleFlow?W.flows:null}),a()}},[o.isRunning,o.lastRunEnd,o.steps,n,a]),(0,tt.useEffect)(()=>{o.runError&&!o.isRunning&&!c.current&&(c.current=!0,n({lastRunEnd:null,stepsPassed:0,stepsFailed:0,stepsTotal:0,hadError:!0,bifurcationFlows:null}),a())},[o.runError,o.isRunning,n,a]);let S=o.lastRunEnd?(()=>{let b=o.steps.flatMap(W=>[W,...W.children??[]]),g=b.filter(W=>W.status==="passed").length,w=b.filter(W=>W.status==="failed").length,N=b.filter(W=>W.status==="passed"||W.status==="failed").length;return{status:o.lastRunEnd.status,duration:o.lastRunEnd.duration??0,summary:o.lastRunEnd.summary??"",stepsPassed:g,stepsFailed:w,stepsTotal:N,reason:o.lastRunEnd.reason,finalState:o.lastRunEnd.final_state}})():null,p=(0,tt.useMemo)(()=>r?[{key:"banner",...r}]:[],[r]);return(0,Ae.jsxs)(v,{flexDirection:"column",children:[(0,Ae.jsx)(Xt,{items:p,children:b=>(0,Ae.jsxs)(v,{flexDirection:"column",marginBottom:1,children:[(0,Ae.jsxs)(v,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,Ae.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,Ae.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,Ae.jsx)(u,{color:m.cyan,children:b.model}),(0,Ae.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,Ae.jsx)(u,{color:m.dimmed,children:b.auth})]}),b.status?.map((g,w)=>(0,Ae.jsx)(u,{color:m.dimmed,children:g},w))]},b.key)}),o.steps.length>0&&(0,Ae.jsx)(Pn,{steps:o.steps,bifurcated:!!o.bifurcationInfo&&!o.bifurcationInfo.isSingleFlow,flows:o.bifurcationInfo?.flows,cmInitCounts:o.cmInitCounts,staticSteps:!0}),o.askingUser&&(0,Ae.jsxs)(v,{flexDirection:"column",marginTop:1,children:[(0,Ae.jsxs)(u,{color:m.yellow,children:['Agent is asking: "',o.askingUser,'"']}),(0,Ae.jsxs)(u,{children:["> ",d,"\u2588"]})]}),o.runError&&(0,Ae.jsx)(oo,{message:o.runError,code:"RUNNER_ERROR"}),S&&(0,Ae.jsx)(Er,{status:S.status==="passed"?"passed":"failed",summary:S.summary??"",duration:S.duration,steps:S.stepsTotal,stepsPassed:S.stepsPassed,stepsFailed:S.stepsFailed,reason:S.reason})]})}var en=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString("base64")}`,r=await fetch(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:t,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:e.secretKey,secretValue:e.secretValue,orgId:e.orgId,username:e.username,scope:"user",type:"user",accessKey:e.accessKey})});if(!r.ok)throw new Error(`Push secret failed: ${r.status} ${await r.text()}`)}static extractVariableKeys(e){let t=e.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),r=new Set;for(let n of t)r.add(n[1]);return[...r]}};var tn=class{constructor(e,t,r){this.baseUrl=e;this.authHeader=`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}authHeader;headers(){return{Authorization:this.authHeader,"Content-Type":"application/json",Accept:"application/json"}}async upsertVariable(e){let t=e.environmentId??0,r=await fetch(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:e.name,value:String(e.value),type:"variable",value_type:"string",is_persist:e.isPersist??!1,environment_id:t})});if(r.ok)return{id:(await r.json()).id??0};if(r.status!==409&&r.status!==422)return{id:0};if(!(await fetch(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(e.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(e.value),value_type:"string",type:"variable",environment_id:t})})).ok)return{id:0};let s=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${t}`,{method:"GET",headers:this.headers()});return s.ok?{id:(await s.json()).data?.id??0}:{id:0}}};import la from"sharp";var nn=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;constructor(e,t=3){this.sas=e,this.maxWorkers=t}updateSas(e){this.sas=e}enqueue(e,t){this.queue.push({operationId:e,buffer:t}),this.pump()}async drain(e=3e4){if(!(this.queue.length===0&&this.activeCount===0))return new Promise(t=>{this.drainResolvers.push(t),setTimeout(()=>{t()},e)})}pump(){for(;this.activeCount<this.maxWorkers&&this.queue.length>0;){let e=this.queue.shift();this.activeCount++,this.processJob(e).finally(()=>{if(this.activeCount--,this.pump(),this.queue.length===0&&this.activeCount===0){for(let t of this.drainResolvers)t();this.drainResolvers=[]}})}}async processJob(e){let t,r="image/webp";try{let o=await la(e.buffer).webp({quality:80}).toBuffer();t=new Uint8Array(o)}catch{t=new Uint8Array(e.buffer),r="image/png"}let n=r==="image/webp"?"webp":"png",s=`test_screenshots/untagged_screenshot/${e.operationId}.${n}`,a=`${this.sas.base_url}/${this.sas.container}/${s}?${this.sas.sas_token}`;for(let o=0;o<=this.maxRetries;o++)try{if((await fetch(a,{method:"PUT",headers:{"Content-Type":r,"x-ms-blob-type":"BlockBlob"},body:t})).ok)return;if(o<this.maxRetries){await this.backoff(o);continue}}catch{if(o<this.maxRetries){await this.backoff(o);continue}}}backoff(e){let t=e===0?1e3:3e3;return new Promise(r=>setTimeout(r,t))}isNearExpiry(){if(!this.sas.expiry)return!1;let e=new Date(this.sas.expiry).getTime();return Date.now()>e-5*6e4}};var H=G(ae(),1);function co({localMode:i=!1,codeExport:e=!1,updatePromise:t}={}){let{exit:r}=Sn(),[n]=(0,U.useState)(()=>new Qt),[s]=(0,U.useState)(()=>new et),a=(0,U.useRef)(0),o=(0,U.useCallback)(()=>`msg-${++a.current}`,[]),[l,c]=(0,U.useState)(!1),[d,h]=(0,U.useState)(null),[x,S]=(0,U.useState)(!1),[p,b]=(0,U.useState)(null),[g,w]=(0,U.useState)(!1),[N,W]=(0,U.useState)(0),[Q,te]=(0,U.useState)(!1),[L,M]=(0,U.useState)(null),[A,X]=(0,U.useState)(null),[f,k]=(0,U.useState)(Zn()),[y,C]=(0,U.useState)(null),[P,j]=(0,U.useState)(!1),F=(0,U.useRef)(null),Z=(0,U.useRef)(0),Y=(0,U.useRef)(""),ue=(0,U.useRef)(0),[oe,Te]=(0,U.useState)([]),de=(0,U.useCallback)(_=>{let T=`s-${++ue.current}`;Te(R=>[...R,{id:T,content:_}])},[]),[zt,sn]=(0,U.useState)(()=>new et().load().setup_complete),[Vt,St]=(0,U.useState)("menu"),[fe,nt]=(0,U.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),q=as(),$=zs(),Be=Ys(),bn=(0,U.useCallback)((_,T)=>{let R=F.current;if(!R)return;let O=Z.current+T,V=De(n.sessionDir,"runs",String(O),"run-test");try{if(!gn(V)){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=runsDir_not_found path=${V}`);return}let z=V;if(gn(De(V,"screenshots")))z=V;else{let xe=ca(V).filter(lt=>gn(De(V,lt,"screenshots")));if(xe.length===0){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=no_screenshots_dir`);return}z=De(V,xe[0])}let se=De(z,"screenshots",`step_${String(_).padStart(3,"0")}.png`);if(!gn(se)){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=screenshot_not_found path=${se}`);return}let Ue=lo(se),Se=De(z,"actions.ndjson");if(!gn(Se)){n.log(`SCREENSHOT_UPLOAD skip step=${_} reason=ndjson_not_found`);return}let Pe=lo(Se,"utf-8").trim().split(`
|
|
40
|
-
`),
|
|
41
|
-
`)})}}},[
|
|
29
|
+
`)}};import{createServer as Ai}from"http";import{randomBytes as Ti}from"crypto";import{URL as Pi}from"url";import js from"process";import{Buffer as Us}from"buffer";import Vs from"path";import{fileURLToPath as _i}from"url";import{promisify as bi}from"util";import Ls from"child_process";import wi,{constants as yi}from"fs/promises";import Ts from"process";import Ps,{constants as ti}from"fs/promises";import As from"process";import ei from"os";import mr from"fs";import Qo from"fs";import ks from"fs";var ur;function Xo(){try{return ks.statSync("/.dockerenv"),!0}catch{return!1}}function Yo(){try{return ks.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function dr(){return ur===void 0&&(ur=Xo()||Yo()),ur}var fr,Zo=()=>{try{return Qo.statSync("/run/.containerenv"),!0}catch{return!1}};function Kt(){return fr===void 0&&(fr=Zo()||dr()),fr}var Rs=()=>{if(As.platform!=="linux")return!1;if(ei.release().toLowerCase().includes("microsoft"))return!Kt();try{if(mr.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!Kt()}catch{}return mr.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||mr.existsSync("/run/WSL")?!Kt():!1},Dt=As.env.__IS_WSL_TEST__?Rs:Rs();var ni=(()=>{let i="/mnt/",e;return async function(){if(e)return e;let t="/etc/wsl.conf",r=!1;try{await Ps.access(t,ti.F_OK),r=!0}catch{}if(!r)return i;let n=await Ps.readFile(t,{encoding:"utf8"}),s=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(n);return s?(e=s.groups.mountPoint.trim(),e=e.endsWith("/")?e:`${e}/`,e):i}})(),ri=async()=>`${await ni()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,pr=async()=>Dt?ri():`${Ts.env.SYSTEMROOT||Ts.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Bt(i,e,t){let r=n=>Object.defineProperty(i,e,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(i,e,{configurable:!0,enumerable:!0,get(){let n=t();return r(n),n},set(n){r(n)}}),i}import{promisify as hi}from"util";import _r from"process";import{execFile as gi}from"child_process";import{promisify as si}from"util";import oi from"process";import{execFile as ii}from"child_process";var ai=si(ii);async function hr(){if(oi.platform!=="darwin")throw new Error("macOS only");let{stdout:i}=await ai("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(i)?.groups.id??"com.apple.Safari";return t==="com.apple.safari"?"com.apple.Safari":t}import li from"process";import{promisify as ci}from"util";import{execFile as ui,execFileSync as tc}from"child_process";var di=ci(ui);async function Os(i,{humanReadableOutput:e=!0,signal:t}={}){if(li.platform!=="darwin")throw new Error("macOS only");let r=e?[]:["-ss"],n={};t&&(n.signal=t);let{stdout:s}=await di("osascript",["-e",i,r],n);return s.trim()}async function gr(i){return Os(`tell application "Finder" to set app_path to application file id "${i}" as string
|
|
30
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as fi}from"util";import{execFile as mi}from"child_process";var pi=fi(mi),$n={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},ac=new Map(Object.entries($n)),vr=class extends Error{};async function xr(i=pi){let{stdout:e}=await i("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(e);if(!t)throw new vr(`Cannot find Windows browser in stdout: ${JSON.stringify(e)}`);let{id:r}=t.groups,n=r.lastIndexOf("."),s=r.lastIndexOf("-"),a=n===-1?void 0:r.slice(0,n),o=s===-1?void 0:r.slice(0,s);return $n[r]??$n[a]??$n[o]??{name:r,id:r}}var vi=hi(gi),xi=i=>i.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function br(){if(_r.platform==="darwin"){let i=await hr();return{name:await gr(i),id:i}}if(_r.platform==="linux"){let{stdout:i}=await vi("xdg-mime",["query","default","x-scheme-handler/http"]),e=i.trim();return{name:xi(e.replace(/.desktop$/,"").replace("-"," ")),id:e}}if(_r.platform==="win32")return xr();throw new Error("Only macOS, Linux, and Windows are supported")}var Si=bi(Ls.execFile),wr=Vs.dirname(_i(import.meta.url)),$s=Vs.join(wr,"xdg-open"),{platform:Xt,arch:Is}=js;async function Ci(){let i=await pr(),e=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,t=Us.from(e,"utf16le").toString("base64"),{stdout:r}=await Si(i,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),n=r.trim(),s={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return s[n]?{id:s[n]}:{}}var Ds=async(i,e)=>{let t;for(let r of i)try{return await e(r)}catch(n){t=n}throw t},In=async i=>{if(i={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...i},Array.isArray(i.app))return Ds(i.app,o=>In({...i,app:o}));let{name:e,arguments:t=[]}=i.app??{};if(t=[...t],Array.isArray(e))return Ds(e,o=>In({...i,app:{name:o,arguments:t}}));if(e==="browser"||e==="browserPrivate"){let o={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d=Dt?await Ci():await br();if(d.id in o){let c=o[d.id];return e==="browserPrivate"&&t.push(l[c]),In({...i,app:{name:qt[c],arguments:t}})}throw new Error(`${d.name} is not supported as a default browser`)}let r,n=[],s={};if(Xt==="darwin")r="open",i.wait&&n.push("--wait-apps"),i.background&&n.push("--background"),i.newInstance&&n.push("--new"),e&&n.push("-a",e);else if(Xt==="win32"||Dt&&!Kt()&&!e){r=await pr(),n.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),Dt||(s.windowsVerbatimArguments=!0);let o=["Start"];i.wait&&o.push("-Wait"),e?(o.push(`"\`"${e}\`""`),i.target&&t.push(i.target)):i.target&&o.push(`"${i.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),o.push("-ArgumentList",t.join(","))),i.target=Us.from(o.join(" "),"utf16le").toString("base64")}else{if(e)r=e;else{let o=!wr||wr==="/",l=!1;try{await wi.access($s,yi.X_OK),l=!0}catch{}r=js.versions.electron??(Xt==="android"||o||!l)?"xdg-open":$s}t.length>0&&n.push(...t),i.wait||(s.stdio="ignore",s.detached=!0)}Xt==="darwin"&&t.length>0&&n.push("--args",...t),i.target&&n.push(i.target);let a=Ls.spawn(r,n,s);return i.wait?new Promise((o,l)=>{a.once("error",l),a.once("close",d=>{if(!i.allowNonzeroExitCode&&d>0){l(new Error(`Exited with code ${d}`));return}o(a)})}):(a.unref(),a)},Ei=(i,e)=>{if(typeof i!="string")throw new TypeError("Expected a `target`");return In({...e,target:i})};function Bs(i){if(typeof i=="string"||Array.isArray(i))return i;let{[Is]:e}=i;if(!e)throw new Error(`${Is} is not supported`);return e}function Dn({[Xt]:i},{wsl:e}){if(e&&Dt)return Bs(e);if(!i)throw new Error(`${Xt} is not supported`);return Bs(i)}var qt={};Bt(qt,"chrome",()=>Dn({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Bt(qt,"brave",()=>Dn({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Bt(qt,"firefox",()=>Dn({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Bt(qt,"edge",()=>Dn({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Bt(qt,"browser",()=>"browser");Bt(qt,"browserPrivate",()=>"browserPrivate");var Ms=Ei;import{createHash as ki,randomBytes as Ri}from"crypto";var ze=class{authBaseUrl;consentUrl;constructor(e="prod"){let t=ae(e);this.authBaseUrl=t.authBaseUrl,this.consentUrl=t.consentUrl}static generatePkce(){let e=Ri(96).toString("base64url").slice(0,128),t=ki("sha256").update(e).digest("base64url");return[e,t]}buildAuthorizationUrl(e,t,r,n){let s=new URLSearchParams({response_type:"code",client_id:e,redirect_uri:n,scope:zr,code_challenge:t,code_challenge_method:"S256",state:r});return`${this.consentUrl}/oauth2?${s.toString()}`}async registerClient(e){let t=await fetch(`${this.authBaseUrl}/oauth2/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:Jr,redirect_uris:[e],grant_types:["authorization_code"],response_types:["code"],client_type:"public",application_type:"native"})});if(!t.ok)throw new Error(`DCR failed: ${t.status} ${await t.text()}`);return t.json()}async exchangeCode(e,t,r,n){let s=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:e,redirect_uri:n,client_id:t,code_verifier:r})});if(!s.ok)throw new Error(`Token exchange failed: ${s.status}`);return s.json()}async refreshToken(e,t){let r=await fetch(`${this.authBaseUrl}/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:t})});if(!r.ok)throw new Error(`Token refresh failed: ${r.status}`);return r.json()}async revokeToken(e,t,r="access_token"){await fetch(`${this.authBaseUrl}/oauth2/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,token_type_hint:r,client_id:t})})}};var _t=class{profile;environment;creds;oauth;constructor(e="default",t="prod",r){this.profile=e,this.environment=t,this.creds=r??new Re,this.oauth=new ze(t)}async login(){let{server:e,port:t}=await this.startCallbackServer(),r=qr(t);try{let n=this.creds.loadClient(this.profile,this.environment);n||(n=await this.oauth.registerClient(r),this.creds.saveClient(this.profile,this.environment,n));let s=n.client_id,[a,o]=ze.generatePkce(),l=Ti(32).toString("hex"),d=this.oauth.buildAuthorizationUrl(s,o,l,r),c=await this.waitForCallback(e,t,d,l);if(!c)throw new Error("Login cancelled or timed out");let h=await this.oauth.exchangeCode(c,s,a,r),g={access_token:h.access_token,refresh_token:h.refresh_token,expires_at:Math.floor(Date.now()/1e3)+h.expires_in,scope:h.scope??"*"};return this.creds.saveCredentials(this.profile,this.environment,g),this.creds.setActiveProfile(this.profile),g}catch(n){throw e.close(),n}}startCallbackServer(){return new Promise((e,t)=>{let r=zn,n=()=>{let s=Ai();s.on("error",a=>{a.code==="EADDRINUSE"&&r<Gn?(r++,n()):t(new Error(`Failed to start callback server: ${a.message}. Ports ${zn}-${Gn} are all in use.`))}),s.listen(r,Jn,()=>{e({server:s,port:r})})};n()})}waitForCallback(e,t,r,n){return new Promise(s=>{let a=!1,o=setTimeout(()=>l(null),12e4),l=d=>{a||(a=!0,clearTimeout(o),e.close(),s(d))};e.on("request",(d,c)=>{let h=new Pi(d.url??"/",`http://${Jn}:${t}`);if(h.pathname!==Kr){c.writeHead(404),c.end();return}let g=h.searchParams.get("state"),S=h.searchParams.get("code");if(h.searchParams.get("error")){c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Login Failed</h1><p>You can close this tab.</p></body></html>"),l(null);return}if(g!==n){c.writeHead(400,{"Content-Type":"text/html"}),c.end("<html><body><h1>Invalid State</h1></body></html>"),l(null);return}c.writeHead(200,{"Content-Type":"text/html"}),c.end("<html><body><h1>Login Successful!</h1><p>You can close this tab and return to the terminal.</p></body></html>"),l(S)}),Ms(r).catch(()=>{})})}};var D=Z(le(),1),Fs="https://kaneai-playground.lambdatest.io";function Ns({onComplete:i}){let[e]=(0,Ae.useState)(()=>new tt),[t]=(0,Ae.useState)(()=>new Re),[r,n]=(0,Ae.useState)(process.env.KANE_DEV_MODE==="1"?"env":"auth"),[s,a]=(0,Ae.useState)(0),[o,l]=(0,Ae.useState)(""),[d,c]=(0,Ae.useState)("username"),[h,g]=(0,Ae.useState)(""),[S,p]=(0,Ae.useState)(null),[_,v]=(0,Ae.useState)(!1),[w,F]=(0,Ae.useState)([]),[K,X]=(0,Ae.useState)([]),[W,B]=(0,Ae.useState)(null),$=(0,Ae.useCallback)(y=>{a(0),l(""),p(null),n(y)},[]),E=(0,Ae.useCallback)(()=>{e.set("default_url",Fs),e.set("setup_complete",!0),$("modes")},[e,$]),q=(0,Ae.useCallback)(async()=>{let{credentials:y,profile:C,env:O}=t.getActiveCredentials();if(!y||!C||!O)return null;let V=y.expires_at,N=Date.now()/1e3;if(V-N<300){let ee=t.loadClient(C,O);if(!ee)return null;let ce=await new ze(O).refreshToken(y.refresh_token,ee.client_id),oe={access_token:ce.access_token,refresh_token:ce.refresh_token,expires_at:Math.floor(N)+ce.expires_in,scope:ce.scope};return t.saveCredentials(C,O,oe),oe.access_token}return y.access_token},[t]),f=(0,Ae.useCallback)(async()=>{n("loading-projects");try{let y=t.resolveAuth();if(!y)throw new Error("No auth configured");let C=t.getDefaultEnv(),O=ae(C),V,N;if(y.method==="basic")V=y.username,N=y.access_key;else{let oe=await q();if(!oe)throw new Error("Could not get OAuth token");let de=await new cn(O.controllerBaseUrl,oe).getTmsCredentials();V=de.username,N=de.access_key}let ce=(await new Ot(O.tmsBaseUrl,V,N).listProjects()).map(oe=>({id:oe.project_id,label:`${oe.name} (${oe.project_id})`,isActive:oe.name.toLowerCase().includes("kaneai")}));if(ce.length===0){p("No projects found."),E();return}F(ce),n("project")}catch(y){p(`Could not fetch projects: ${y instanceof Error?y.message:y}`),E()}},[t,q,$,E]),R=(0,Ae.useCallback)(async y=>{n("loading-folders");try{let C=t.resolveAuth();if(!C)throw new Error("No auth configured");let O=t.getDefaultEnv(),V=ae(O),N,ee;if(C.method==="basic")N=C.username,ee=C.access_key;else{let de=await q();if(!de)throw new Error("Could not get OAuth token");let sn=await new cn(V.controllerBaseUrl,de).getTmsCredentials();N=sn.username,ee=sn.access_key}let Y=new Ot(V.tmsBaseUrl,N,ee),ce=await Y.listFolders(y),oe=await Y.getDefaultFolder(y).catch(()=>null);B(oe);let Oe=ce.map(de=>({id:de.id,label:`${de.name} (${de.id}) \xB7 ${de.test_cases_count} tests`,isActive:de.id===oe}));if(Oe.length===0){oe&&e.set("folder_id",oe),E();return}X(Oe),n("folder")}catch{E()}},[t,q,e,E]);return et((y,C)=>{if(!_&&!(r==="loading-projects"||r==="loading-folders")){if(r==="modes"){C.return&&(n("done"),setTimeout(i,300));return}if(r==="env"||r==="auth"){if(C.upArrow)a(V=>Math.max(0,V-1));else if(C.downArrow)a(V=>Math.min(1,V+1));else if(C.return){if(r==="env"){let V=s===0?"prod":"stage";t.setDefaultEnv(V),$("auth")}else if(r==="auth")if(s===0){v(!0);let V=t.getDefaultEnv(),N="default";t.setActiveProfile(N),new _t(N,V,t).login().then(()=>{v(!1),f()}).catch(Y=>{v(!1),p(`Login failed: ${Y.message}`)})}else $("auth-basic"),c("username")}return}if(r==="auth-basic"){if(C.return)if(d==="username"){if(!o.trim()){p("Username is required");return}g(o.trim()),l(""),c("access_key"),p(null)}else{if(!o.trim()){p("Access key is required");return}let O="default",V=t.getDefaultEnv();t.setActiveProfile(O),t.saveBasicAuth(O,V,{username:h,access_key:o.trim()}),f()}else C.backspace||C.delete?l(O=>O.slice(0,-1)):y&&!C.ctrl&&!C.meta&&l(O=>O+y);return}}},{isActive:r!=="project"&&r!=="folder"}),(0,D.jsx)(x,{flexDirection:"column",padding:1,children:(0,D.jsx)(Cn,{title:"Kane CLI \u2014 First-time Setup",variant:r==="done"?"success":"default",children:(0,D.jsxs)(x,{flexDirection:"column",paddingY:1,children:[r==="env"&&(0,D.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,D.jsxs)(x,{children:[(0,D.jsx)(u,{color:m.purple,children:"?"}),(0,D.jsx)(u,{bold:!0,children:" Select environment"})]}),(0,D.jsxs)(x,{marginLeft:2,flexDirection:"column",children:[(0,D.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","prod"]}),(0,D.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","stage"]})]})]}),r==="auth"&&(0,D.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,D.jsxs)(x,{children:[(0,D.jsx)(u,{color:m.purple,children:"?"}),(0,D.jsx)(u,{bold:!0,children:" Which authentication method?"})]}),(0,D.jsxs)(x,{marginLeft:2,flexDirection:"column",children:[(0,D.jsxs)(u,{color:s===0?m.purple:m.dimmed,children:[s===0?"\u25CF ":"\u25CB ","OAuth (browser login)"]}),(0,D.jsxs)(u,{color:s===1?m.purple:m.dimmed,children:[s===1?"\u25CF ":"\u25CB ","Basic (username + access key)"]})]}),_&&(0,D.jsx)(x,{marginTop:1,marginLeft:2,children:(0,D.jsx)(u,{color:m.cyan,children:"\u280B Opening browser for login\u2026"})})]}),r==="auth-basic"&&(0,D.jsxs)(x,{flexDirection:"column",children:[(0,D.jsxs)(x,{marginBottom:d==="access_key"?0:1,children:[(0,D.jsx)(u,{color:d==="access_key"?m.statusPass:m.primary,children:d==="access_key"?"\u2713":"?"}),(0,D.jsx)(u,{bold:!0,children:" Username: "}),d==="username"?(0,D.jsxs)(D.Fragment,{children:[(0,D.jsx)(u,{color:m.base,children:o}),(0,D.jsx)(u,{color:m.primary,inverse:!0,children:" "})]}):(0,D.jsx)(u,{color:m.statusPass,children:h})]}),d==="access_key"&&(0,D.jsxs)(x,{marginBottom:1,children:[(0,D.jsx)(u,{color:m.primary,children:"?"}),(0,D.jsx)(u,{bold:!0,children:" Access Key: "}),(0,D.jsx)(u,{color:m.dim,children:"\u2022".repeat(o.length)}),(0,D.jsx)(u,{color:m.primary,inverse:!0,children:" "})]})]}),r==="loading-projects"&&(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.cyan,children:"\u280B Fetching projects\u2026"})}),r==="project"&&(0,D.jsx)(Xn,{title:"Select project",items:w,itemNoun:"projects",onSelect:y=>{e.set("project_id",y.id),R(y.id)},onCancel:()=>{E()}}),r==="loading-folders"&&(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.cyan,children:"\u280B Fetching folders\u2026"})}),r==="folder"&&(0,D.jsx)(Xn,{title:"Select folder",items:K,itemNoun:"folders",onSelect:y=>{e.set("folder_id",y.id),E()},onCancel:()=>{W&&e.set("folder_id",W),E()}}),r==="modes"&&(0,D.jsxs)(x,{flexDirection:"column",children:[(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.statusPass,bold:!0,children:"\u2713 Setup complete!"})}),(0,D.jsx)(x,{marginTop:1,children:(0,D.jsx)(En,{label:"Profile",value:t.getActiveProfile()??"default"})}),(0,D.jsx)(En,{label:"Environment",value:t.getDefaultEnv()}),(0,D.jsx)(En,{label:"Default URL",value:Fs}),(0,D.jsx)(x,{marginTop:1,flexDirection:"column",children:(0,D.jsx)(u,{bold:!0,color:m.primary,children:"Available modes:"})}),(0,D.jsxs)(x,{marginLeft:2,flexDirection:"column",marginTop:1,children:[(0,D.jsxs)(x,{children:[(0,D.jsx)(u,{bold:!0,color:m.base,children:"TUI "}),(0,D.jsx)(u,{color:m.dim,children:"Interactive menu + chat UI"})]}),(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.dim,children:" kane-cli"})}),(0,D.jsxs)(x,{marginTop:1,children:[(0,D.jsx)(u,{bold:!0,color:m.base,children:"CLI "}),(0,D.jsx)(u,{color:m.dim,children:"Headless single-run, JSON output"})]}),(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.dim,children:' kane-cli run "objective" --url <url>'})}),(0,D.jsxs)(x,{marginTop:1,children:[(0,D.jsx)(u,{bold:!0,color:m.base,children:"Agent "}),(0,D.jsx)(u,{color:m.dim,children:"Programmatic setup + run via CLI flags"})]}),(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.dim,children:" kane-cli login --username <u> --access-key <k>"})})]}),(0,D.jsxs)(x,{marginTop:1,children:[(0,D.jsx)(u,{color:m.dim,children:"Press "}),(0,D.jsx)(u,{bold:!0,color:m.primary,children:"Enter"}),(0,D.jsx)(u,{color:m.dim,children:" to launch TUI"})]})]}),r==="done"&&(0,D.jsx)(x,{children:(0,D.jsx)(u,{color:m.statusPass,bold:!0,children:"Launching\u2026"})}),S&&(0,D.jsx)(x,{marginTop:1,children:(0,D.jsx)(u,{color:m.red,children:S})})]})})})}var bt=Z(He(),1);var qe=Z(le(),1);function Oi(i,e){let t=[],n=Math.max(e-4,30);t.push({type:"title",text:i.title});for(let s=0;s<i.sections.length;s++){let a=i.sections[s];s>0&&t.push({type:"divider",text:"\u2500".repeat(n)}),a.label&&t.push({type:"header",text:a.label});let o=a.entries.length>0?Math.max(...a.entries.map(l=>l.key.length)):0;for(let l of a.entries){let d="\xB7".repeat(Math.max(2,o-l.key.length+3)),c=`${l.key} ${d} ${l.value}`;t.push({type:"entry",text:c,color:l.color})}}return t.push({type:"footer",text:"esc back"}),t}function Hs({data:i,width:e=60}){let t=Oi(i,e);return(0,qe.jsx)(x,{flexDirection:"column",borderStyle:"round",borderColor:m.primary,paddingX:2,paddingY:1,children:t.map((r,n)=>{if(r.type==="title")return(0,qe.jsx)(u,{color:m.primary,bold:!0,children:r.text},n);if(r.type==="header")return(0,qe.jsx)(x,{marginTop:1,children:(0,qe.jsx)(u,{color:m.dim,children:r.text})},n);if(r.type==="divider")return(0,qe.jsx)(x,{marginTop:1,marginBottom:0,children:(0,qe.jsx)(u,{color:m.ambient,children:r.text})},n);if(r.type==="footer")return(0,qe.jsx)(x,{marginTop:1,children:(0,qe.jsx)(u,{color:m.dim,children:r.text})},n);let s=r.text.match(/^(.+?) (·+) (.+)$/);return s?(0,qe.jsxs)(u,{children:[(0,qe.jsxs)(u,{color:m.secondary,children:[s[1]," "]}),(0,qe.jsxs)(u,{color:m.ambient,children:[s[2]," "]}),(0,qe.jsx)(u,{color:r.color??m.base,children:s[3]})]},n):(0,qe.jsx)(u,{color:r.color??m.base,children:r.text},n)})})}var Me=Z(le(),1);function Ws(i,e){let t=[];function r(n,s){for(let a of n)t.push({item:a,depth:s}),a.type==="submenu"&&a.children&&e.length>s&&e[s]===a.id&&r(a.children,s+1)}return r(i,0),t}function Ks({items:i,onRunSelected:e,renderLoginWizard:t,renderProfilesView:r,renderChromeProfilePicker:n,renderProjectPicker:s,renderFolderPicker:a}){let[o,l]=(0,bt.useState)({expandedPath:[],selectedIndex:0,inputValue:"",isEditing:!1,isSelecting:!1,feedback:null,activeView:null,infoData:null}),d=Ws(i,o.expandedPath),c=d[o.selectedIndex]?.item,h=(0,bt.useRef)(null),g=(0,bt.useCallback)(p=>{l(_=>({..._,feedback:p})),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{l(_=>({..._,feedback:null})),h.current=null},4e3)},[]);(0,bt.useEffect)(()=>()=>{h.current&&clearTimeout(h.current)},[]);let S=(0,bt.useCallback)(()=>{l(p=>({...p,activeView:null,infoData:null}))},[]);return et((p,_)=>{if(o.activeView==="infoView"){_.escape&&S();return}if(!(o.activeView==="loginWizard"||o.activeView==="profilesView"||o.activeView==="chromeProfilePicker"||o.activeView==="projectPicker"||o.activeView==="folderPicker")){if(o.isEditing){if(_.escape){l(v=>({...v,isEditing:!1,inputValue:""}));return}if(_.return){let v=o.inputValue.trim();if(c?.onValue&&v){let w=c.currentValue;c.onValue(v),g(w?`${c.label}: ${w} \u2192 ${v}`:`${c.label}: ${v}`)}l(w=>({...w,isEditing:!1,inputValue:""}));return}if(_.backspace||_.delete){l(v=>({...v,inputValue:v.inputValue.slice(0,-1)}));return}p&&!_.ctrl&&!_.meta&&l(v=>({...v,inputValue:v.inputValue+p}));return}if(o.isSelecting&&c?.options){let v=c.options;if(_.escape){l(w=>({...w,isSelecting:!1}));return}if(_.upArrow){l(w=>({...w,inputValue:String(Math.max(0,Number(w.inputValue||"0")-1))}));return}if(_.downArrow){l(w=>({...w,inputValue:String(Math.min(v.length-1,Number(w.inputValue||"0")+1))}));return}if(_.return){let w=Number(o.inputValue||"0"),F=v[w];if(F&&c.onValue){let K=c.currentValue;c.onValue(F.value),g(K?`${c.label}: ${K} \u2192 ${F.label}`:`${c.label}: ${F.label}`)}l(K=>({...K,isSelecting:!1,inputValue:""}));return}return}if(_.upArrow){l(v=>({...v,selectedIndex:Math.max(0,v.selectedIndex-1)}));return}if(_.downArrow){l(v=>({...v,selectedIndex:Math.min(d.length-1,v.selectedIndex+1)}));return}if(_.escape){l(v=>{if(v.expandedPath.length===0)return v;let w=v.expandedPath.slice(0,-1),F=Ws(i,w),K=v.expandedPath[v.expandedPath.length-1],X=F.findIndex(W=>W.item.id===K);return{...v,expandedPath:w,selectedIndex:X>=0?X:0}});return}if(_.return&&c){if(c.id==="run-start"){e();return}if(c.type==="submenu"){let v=d[o.selectedIndex]?.depth??0;l(w=>({...w,expandedPath:[...w.expandedPath.slice(0,v),c.id],selectedIndex:w.selectedIndex+1}));return}if(c.onInfo){let v=c.onInfo();l(w=>({...w,activeView:"infoView",infoData:v}));return}if(c.onLoginWizard){c.onLoginWizard(),l(v=>({...v,activeView:"loginWizard"}));return}if(c.onProfilesView){c.onProfilesView(),l(v=>({...v,activeView:"profilesView"}));return}if(c.onChromeProfilePicker){c.onChromeProfilePicker(),l(v=>({...v,activeView:"chromeProfilePicker"}));return}if(c.onProjectPicker){c.onProjectPicker(),l(v=>({...v,activeView:"projectPicker"}));return}if(c.onFolderPicker){c.onFolderPicker(),l(v=>({...v,activeView:"folderPicker"}));return}if(c.type==="action"){c.onAction?.(),g(`${c.label} done`);return}if(c.type==="select"&&c.options){let v=c.options.findIndex(w=>w.value===c.currentValue);l(w=>({...w,isSelecting:!0,inputValue:String(Math.max(0,v))}));return}if(c.type==="text-input"){l(v=>({...v,isEditing:!0,inputValue:c.currentValue??""}));return}}}}),(0,Me.jsx)(x,{flexDirection:"column",paddingX:1,children:o.activeView==="infoView"&&o.infoData?(0,Me.jsx)(Hs,{data:o.infoData}):o.activeView==="loginWizard"&&t?t(S):o.activeView==="profilesView"&&r?r(S):o.activeView==="chromeProfilePicker"&&n?n(S):o.activeView==="projectPicker"&&s?s(S):o.activeView==="folderPicker"&&a?a(S):(0,Me.jsxs)(Me.Fragment,{children:[d.map(({item:p,depth:_},v)=>{let w=v===o.selectedIndex,F=" ".repeat(_),K=w?"\u276F ":" ",X=p.type==="submenu"?o.expandedPath.includes(p.id)?"\u25BC ":"\u25B6 ":" ",W=p.currentValue!=null?` [${p.currentValue}]`:"";if(w&&o.isSelecting&&p.options){let B=Number(o.inputValue||"0");return(0,Me.jsxs)(x,{flexDirection:"column",children:[(0,Me.jsxs)(u,{color:m.cyan,children:[F,K,X,p.label]}),p.options.map(($,E)=>(0,Me.jsxs)(u,{color:E===B?m.cyan:void 0,children:[F," ",E===B?"\u276F ":" ",$.label]},$.value))]},p.id)}return w&&o.isEditing?(0,Me.jsxs)(u,{color:m.cyan,children:[F,K,X,p.label,": ",o.inputValue,(0,Me.jsx)(u,{color:m.dimmed,children:"\u2588"})]},p.id):(0,Me.jsxs)(u,{color:w?m.cyan:void 0,dimColor:!w&&_>0,children:[F,K,X,p.label,(0,Me.jsx)(u,{dimColor:!0,children:W})]},p.id)}),o.feedback&&(0,Me.jsx)(x,{marginTop:1,children:(0,Me.jsxs)(u,{color:m.green,children:["\u2713 ",o.feedback]})})]})})}import{randomUUID as $i}from"crypto";import{mkdirSync as Ii,writeFileSync as qs,appendFileSync as Di,existsSync as Js}from"fs";import{join as pn}from"path";var Bi=pn(ye,"sessions"),Yt=class{sessionId;sessionDir;runs=[];_nextIndex=0;_started=!1;_testId=null;_testcaseId=null;_projectId=null;_uploadStatus="pending";_uploadAttempts=0;_uploadError=null;_firstObjective=null;_firstUrl=null;_auteurVariables={};_screenshotSas=null;_model="";_environment="";_profile=null;_startedAt="";constructor(){this.sessionId=$i(),this.sessionDir=pn(Bi,this.sessionId)}start(e){if(this._started)return;this._started=!0,this._model=e.model,this._environment=e.environment,this._profile=e.profile,this._startedAt=new Date().toISOString(),Ii(this.sessionDir,{recursive:!0});let t={session_id:this.sessionId,started_at:this._startedAt,model:e.model,environment:e.environment,profile:e.profile,objectives:[],runs:[],status:"in_progress"};qs(pn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
|
|
31
|
+
`),this._log(`SESSION START session_id=${this.sessionId}`),this._log(`CONFIG model=${e.model} env=${e.environment} profile=${e.profile}`)}setAuteurVariables(e){Object.assign(this._auteurVariables,e)}get auteurVariables(){return this._auteurVariables}setScreenshotSas(e){this._screenshotSas=e}get screenshotSas(){return this._screenshotSas}get screenshotBaseUrl(){return this._screenshotSas?`${this._screenshotSas.base_url}/${this._screenshotSas.container}`:""}get startedAt(){return this._startedAt||new Date().toISOString()}log(e){this._log(e)}logCommand(e){this._log(`COMMAND ${e}`)}logRunStart(e,t,r){this._log(`RUN ${e} START objective="${t.slice(0,100)}" url=${r}`)}logRunEnd(e,t,r,n){let s=(r??0).toFixed(1),a=(n??"").slice(0,100);this._log(`RUN ${e} END status=${t} duration=${s}s summary="${a}"`)}logChromeLaunch(e,t){this._log(`CHROME LAUNCH port=${e} endpoint=${t}`)}finish(e="complete"){this._log(`SESSION END status=${e} total_runs=${this.runs.length}`);let t={session_id:this.sessionId,started_at:this._startedAt,ended_at:new Date().toISOString(),model:this._model,environment:this._environment,profile:this._profile,status:e,total_runs:this.runs.length,test_id:this._testId,testcase_id:this._testcaseId,commit_id:this.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(r=>({index:r.index,objective:r.objective,status:r.status,summary:r.summary,run_dir:r.run_dir}))};Js(this.sessionDir)&&qs(pn(this.sessionDir,"session.json"),JSON.stringify(t,null,2)+`
|
|
32
|
+
`)}nextRunIndex(){return this._nextIndex}addRunResult(e,t){this.runs.push(e),this._nextIndex+=t??1}getContext(){return{prior_runs:this.runs.map(e=>({index:e.index,objective:e.objective,summary:e.summary,status:e.status,memory:e.context.memory,variables:e.context.variables,pointer:e.context.pointer}))}}setTestId(e){this._testId=e}get testId(){return this._testId}setTestcaseId(e){this._testcaseId=e}get testcaseId(){return this._testcaseId}setProjectId(e){this._projectId=e}setFirstRun(e,t){this._firstObjective||(this._firstObjective=e,this._firstUrl=t)}get firstObjective(){return this._firstObjective}get firstUrl(){return this._firstUrl}getRunDirs(){let e=[];for(let t of this.runs)t.run_dirs&&t.run_dirs.length>0?e.push(...t.run_dirs):t.run_dir&&e.push(t.run_dir);return e}getRunObjectives(){let e=[];for(let t of this.runs)t.flow_objectives&&t.flow_objectives.length>0?e.push(...t.flow_objectives):e.push(t.objective);return e}setUploadStatus(e,t){this._uploadStatus=e,this._uploadAttempts+=1,this._uploadError=t??null}_log(e){if(!this._started||!Js(this.sessionDir))return;let t=new Date().toISOString().slice(0,19).replace("T"," "),r=pn(this.sessionDir,"tui.log");Di(r,`[${t}] ${e}
|
|
33
|
+
`)}};var Fe=Z(He(),1);function zs(){let[i]=(0,Fe.useState)(()=>new Re),[e,t]=(0,Fe.useState)(()=>{let p=i.resolveAuth();if(!p)return!1;if(p.method==="basic")return!0;let{credentials:_}=i.getActiveCredentials();return _?_.expires_at>Date.now()/1e3:!1}),r=(0,Fe.useRef)(null),n=(0,Fe.useRef)(null),s=(0,Fe.useCallback)(()=>{let p=i.resolveAuth();return p?{method:p.method,profile:p.profile,env:p.env}:null},[i]),a=(0,Fe.useCallback)(async()=>{let{credentials:p,profile:_,env:v}=i.getActiveCredentials();if(!p||!_||!v)return null;let w=p.expires_at,F=Date.now()/1e3;if(w-F<300){if(n.current)return n.current;let K=(async()=>{let X=i.loadClient(_,v);if(!X)return null;try{let B=await new ze(v).refreshToken(p.refresh_token,X.client_id),$={access_token:B.access_token,refresh_token:B.refresh_token,expires_at:Math.floor(F)+B.expires_in,scope:B.scope};return i.saveCredentials(_,v,$),t(!0),$.access_token}catch{return t(!1),null}finally{n.current=null}})();return n.current=K,K}return t(!0),p.access_token},[i]),o=(0,Fe.useCallback)(()=>{let p=i.resolveAuth();return!p||p.method!=="basic"?null:{username:p.username,access_key:p.access_key}},[i]),l=(0,Fe.useCallback)((p,_)=>{r.current?.revoke();let v=ae(p),w=o(),F=new un(v.controllerBaseUrl,a,w,_);return r.current=F,F},[o,a]),d=(0,Fe.useCallback)(()=>r.current,[]),c=(0,Fe.useCallback)(()=>{let p=o();if(p)return p;let _=r.current?.cached;return _?{username:_.username,access_key:_.access_key}:null},[o]),h=(0,Fe.useCallback)(async()=>{let p=r.current;return p?p.resolve():null},[]),g=(0,Fe.useCallback)(async(p="default")=>{let _=i.getDefaultEnv();await new _t(p,_,i).login(),t(!0)},[i]),S=(0,Fe.useCallback)(async()=>{let p=i.getActiveProfile();if(!p)return null;let _=i.getDefaultEnv(),v=i.loadCredentials(p,_),w=i.loadClient(p,_);if(v&&w){let K=new ze(_);K.revokeToken(v.access_token,w.client_id,"access_token").catch(()=>{}),K.revokeToken(v.refresh_token,w.client_id,"refresh_token").catch(()=>{})}i.deleteProfileFull(p,_);let F=i.listProfiles();return F.length>0&&(i.setActiveProfile(F[0].profile),i.setDefaultEnv(F[0].env)),t(!1),{profile:p,env:_}},[i]);return{creds:i,tokenValid:e,setTokenValid:t,getToken:a,getBasicAuth:o,getAuthInfo:s,login:g,logout:S,initResolver:l,getResolver:d,getResolvedBasicAuth:c,resolveBasicAuth:h}}var ft=Z(He(),1);import{spawn as Gs}from"child_process";import{existsSync as ji}from"fs";import{createConnection as Ui}from"net";import{homedir as hn,platform as yr}from"os";import{join as gn}from"path";var Xs={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",gn(hn(),"Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",gn(hn(),"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",gn(hn(),"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",gn(hn(),"AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"),"C:\\chrome-for-testing\\chrome-win64\\chrome.exe",gn(hn(),"AppData\\Local\\chrome-for-testing\\chrome-win64\\chrome.exe")]};function Vi(){let i=yr(),e=Xs[i]??Xs.linux;for(let t of e)if(ji(t))return t;return i==="win32"?"chrome.exe":"google-chrome"}function Li(i){let e=yr(),t=[`--remote-debugging-port=${i.port}`,`--user-data-dir=${i.userDataDir}`,`--window-size=${i.width},${i.height}`,"--no-first-run","--no-default-browser-check","--disable-blink-features=AutomationControlled","--disable-features=DownloadBubble,DownloadBubbleV2","--safebrowsing-disable-download-protection","--disable-popup-blocking","--disable-notifications","--disable-infobars","--disable-translate","--disable-prompt-on-repost","--disable-background-networking","--disable-client-side-phishing-detection","--disable-default-apps","--disable-hang-monitor","--disable-sync","--metrics-recording-only","--safebrowsing-disable-auto-update","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--test-type=webdriver","--allow-pre-commit-input","--enable-logging","--v=1"];return e==="linux"&&(t.push("--no-sandbox"),t.push("--disable-dev-shm-usage"),t.push("--password-store=basic")),e==="darwin"&&t.push("--use-mock-keychain"),i.headless&&t.push("--headless=new"),t}function Mi(i){return new Promise(e=>{let t=Ui({port:i,host:"127.0.0.1"});t.setTimeout(1e3),t.on("connect",()=>{t.destroy(),e(!0)}),t.on("timeout",()=>{t.destroy(),e(!1)}),t.on("error",()=>{t.destroy(),e(!1)})})}async function Fi(){for(let i=Kn;i<=qn;i++)if(!await Mi(i))return i;throw new Error(`All CDP ports ${Kn}-${qn} are in use. Close other Chrome instances.`)}async function Ni(i,e=15e3){let t=Date.now(),r=`http://127.0.0.1:${i}/json/version`;for(;Date.now()-t<e;){try{if((await fetch(r)).ok)return`http://127.0.0.1:${i}`}catch{}await new Promise(n=>setTimeout(n,200))}throw new Error(`Chrome CDP not ready after ${e}ms on port ${i}`)}async function Bn(i){let e=yr(),t=await Fi(),r=Vi(),n=Li({port:t,...i});i.startUrl&&n.push(i.startUrl);let s=Gs(r,n,{stdio:"ignore",detached:!0,windowsHide:!0});s.unref();let a=await new Promise((o,l)=>{s.on("error",d=>{l(new Error(`Failed to launch Chrome: ${d.message}. Is Chrome installed at ${r}?`))}),s.on("close",d=>{d!==null&&d!==0&&l(new Error(`Chrome exited during startup with code ${d}`))}),Ni(t).then(o,l)});return{process:s,port:t,cdpEndpoint:a,kill(){try{if(s.pid)if(e==="win32")Gs("taskkill",["/pid",String(s.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-s.pid,"SIGKILL")}catch{s.kill("SIGKILL")}else s.kill("SIGKILL")}catch{}}}}import{mkdtempSync as Hi,rmSync as Wi}from"fs";import{join as Ki}from"path";import{tmpdir as qi}from"os";function Ys(){let[i]=(0,ft.useState)(()=>new tt),e=(0,ft.useRef)(null),t=(0,ft.useRef)(null),r=(0,ft.useRef)(null),[n,s]=(0,ft.useState)(!1),a=(0,ft.useCallback)(async l=>{if(e.current)return e.current;if(r.current)return r.current;let d=(async()=>{let c=i.load(),h;if(c.chrome_profile_path)h=c.chrome_profile_path.replace("~",process.env.HOME??"~");else{let S=Hi(Ki(qi(),"kane-clean-"));t.current=S,h=S}let g=await Bn({userDataDir:h,width:c.window_size.width,height:c.window_size.height,startUrl:l??c.default_url??void 0});return e.current=g,Zr(()=>g.kill()),s(!0),g})();r.current=d;try{return await d}finally{r.current=null}},[i]),o=(0,ft.useCallback)(()=>{if(e.current?.kill(),e.current=null,t.current){try{Wi(t.current,{recursive:!0,force:!0})}catch{}t.current=null}s(!1)},[]);return{ensureChrome:a,killChrome:o,ready:n}}var Te=Z(He(),1);import{spawn as zi,execSync as Gi}from"child_process";import{existsSync as jn}from"fs";import{resolve as Ne,dirname as Xi}from"path";import{fileURLToPath as Yi}from"url";import{createInterface as Ji}from"readline";async function*Qs(i){let e=Ji({input:i,crlfDelay:1/0});for await(let t of e){let r=t.trim();if(r)try{let n=JSON.parse(r);n&&typeof n.type=="string"&&(yield n)}catch{}}}var wt=Xi(Yi(import.meta.url));function Qi(){for(let i of["python3","python"])try{return Gi(`${i} --version`,{stdio:"ignore"}),i}catch{}return null}function Zi(){let e=process.platform==="win32"?"v16-runner.exe":"v16-runner",t={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},r=`${process.platform}-${process.arch}`,n=t[r];if(n)for(let o of n){let l=[Ne(wt,"..","node_modules",o,"bin",e),Ne(wt,"..","..","node_modules",o,"bin",e),Ne(wt,"..","..","..","node_modules",o,"bin",e)];for(let d of l)if(jn(d))return{cmd:d,args:[]}}let s=[Ne(wt,"bin",e),Ne(wt,"..","bin",e),Ne(wt,"..","..","..","..","v16-runner","dist",e),Ne(wt,"..","..","..","v16-runner","dist",e),Ne(process.cwd(),"v16-runner","dist",e),Ne(process.cwd(),"..","v16-runner","dist",e)];for(let o of s)if(jn(o))return{cmd:o,args:[]};let a=[Ne(wt,"..","..","..","..","v16-runner"),Ne(wt,"..","..","..","v16-runner"),Ne(process.cwd(),"v16-runner"),Ne(process.cwd(),"..","v16-runner")];for(let o of a)if(jn(Ne(o,"main.py"))){for(let d of[Ne(o,".venv","bin","python"),Ne(o,"..","browser-agent",".venv","bin","python")])if(jn(d))return{cmd:d,args:["main.py"],cwd:o};let l=Qi();if(l)return{cmd:l,args:["main.py"],cwd:o}}return null}function Un(i,e){let t=Zi();if(!t)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");let r={...process.env};e?.environment&&(r.TESTMUAI_ENV=e.environment),r.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(r.PYTHONIOENCODING="utf-8"),r.V16_SERVER_API_HOST=ae(e?.environment).v16ServerHost,i.username&&i.access_key&&(r.LT_USERNAME=i.username,r.LT_ACCESS_KEY=i.access_key);let n=zi(t.cmd,t.args,{stdio:["pipe","pipe","pipe"],env:r,cwd:t.cwd});n.stdin.on("error",()=>{}),n.stdin.write(JSON.stringify(i)+`
|
|
34
|
+
`);let s=1e5,a="";n.stderr.on("data",h=>{a+=h.toString(),a.length>s&&(a=a.slice(-s))});let o=null,l=null,d=new Promise(h=>{n.on("close",(g,S)=>{o=g,l=S?String(S):null,h({code:g,signal:l})})}),c=Qs(n.stdout);return{child:n,events:c,sendUserResponse(h){let g=JSON.stringify({type:"user_response",answer:h});try{n.stdin.write(g+`
|
|
35
|
+
`)}catch{}},sendCancel(h){let g=JSON.stringify({type:"cancel",reason:h});try{n.stdin.write(g+`
|
|
36
|
+
`)}catch{}},cancel(){n.kill("SIGTERM")},get stderr(){return a},get exitCode(){return o},get exitSignal(){return l},exited:d}}function Sr(i){let e=i.indexOf(": ");return e>0&&e<15?i.slice(e+2):i}function Cr(i){return i.map(e=>{let t=e.children?Cr(e.children):e.children;return e.status==="running"?{...e,status:"stopped",phase:void 0,children:t}:t!==e.children?{...e,children:t}:e})}function Vn(i){let[e,t]=(0,Te.useState)(!1),[r,n]=(0,Te.useState)([]),[s,a]=(0,Te.useState)(null),[o,l]=(0,Te.useState)(null),[d,c]=(0,Te.useState)(null),[h,g]=(0,Te.useState)(null),[S,p]=(0,Te.useState)([]),_=(0,Te.useRef)(null),v=(0,Te.useRef)(null),w=(0,Te.useRef)(0),F=(0,Te.useRef)(!1),K=(0,Te.useCallback)((B,$)=>{_.current&&(_.current.cancel(),_.current=null),n([]),a(null),l(null),c(null),g(null),p([]),t(!0),v.current=null,w.current=0;let E=Un(B,$);_.current=E,(async()=>{F.current=!1;for await(let f of E.events){if(F.current)break;switch(f.type){case"run_start":if(v.current&&!v.current.isSingleFlow){let R=w.current;w.current++,n(y=>y.map((C,O)=>O===R?{...C,status:"running"}:C.status==="running"&&!C.children?.some(V=>V.status==="running")?{...C,status:C.children?.some(V=>V.status==="failed")?"failed":"passed"}:C))}break;case"bifurcation":{let R=f.flows??[],y=f.count??R.length,C={flows:R,isSingleFlow:f.is_single_flow??y<=1};g(C),v.current=C,w.current=0,n(R.map((O,V)=>({index:V+1,objective:O??`Flow ${V+1}`,status:"pending"})));break}case"step_start":{let R=f.index,y=f.objective??`Step ${R}`,C=f.child_id,O=v.current&&!v.current.isSingleFlow;if(C)n(V=>{let N=V.findIndex(Oe=>Oe.status==="running"||Oe.children?.some(de=>de.status==="running"));if(N===-1)return V;let ee=[...V],Y={...ee[N]},oe=[...Y.children??[]].map(Oe=>Oe.status==="running"?{...Oe,status:"stopped",phase:void 0}:Oe);return oe.push({index:R,objective:y,status:"running"}),Y.children=oe,ee[N]=Y,ee});else if(O){let V=Math.max(0,w.current-1);n(N=>{let ee=[...N];if(V>=ee.length)return N;let Y={...ee[V]},oe=[...Y.children??[]].map(Oe=>Oe.status==="running"?{...Oe,status:"stopped",phase:void 0}:Oe);return oe.push({index:R,objective:y,status:"running"}),Y.children=oe,Y.status="running",ee[V]=Y,ee})}else n(V=>{let N=Cr(V);return N.some(Y=>Y.index===R)?N.map(Y=>Y.index===R?{...Y,status:"running",objective:y}:Y):[...N,{index:R,objective:y,status:"running"}]});break}case"step_event":{let R=f.child_id,y=v.current&&!v.current.isSingleFlow;if(f.event==="cm_init"&&f.checkpoint_count!=null){p(C=>[...C,f.checkpoint_count]);break}if(R)n(C=>C.map(O=>{if(!O.children)return O;let V=O.children.map(N=>{if(N.index!==f.index)return N;let ee={phase:f.event};return f.event==="reasoning"&&f.detail&&f.detail!=="reasoning"&&(ee.objective=f.detail),f.action_type&&(ee.actionType=f.action_type),{...N,...ee}});return{...O,children:V}}));else if(y){let C=Math.max(0,w.current-1);n(O=>{let V=[...O];if(C>=V.length)return O;let N={...V[C]},ee=[...N.children??[]];if(!ee.some(ce=>ce.index===f.index))ee.push({index:f.index,objective:`Step ${f.index}`,status:"running",phase:f.event,actionType:f.action_type});else for(let ce=0;ce<ee.length;ce++){if(ee[ce].index!==f.index)continue;let oe={phase:f.event};f.event==="reasoning"&&f.detail&&f.detail!=="reasoning"&&(oe.objective=f.detail),f.action_type&&(oe.actionType=f.action_type),ee[ce]={...ee[ce],...oe}}return N.children=ee,V[C]=N,V})}else n(C=>C.some(V=>V.index===f.index)?C.map(V=>{if(V.index!==f.index)return V;let N={phase:f.event};return f.event==="reasoning"&&f.detail&&f.detail!=="reasoning"&&(N.objective=f.detail),f.action_type&&(N.actionType=f.action_type),{...V,...N}}):[...Cr(C),{index:f.index,objective:`Step ${f.index}`,status:"running",phase:f.event,actionType:f.action_type}]);break}case"step_end":{let R=f.child_id,y=v.current&&!v.current.isSingleFlow;if(R)n(C=>C.map(O=>{if(!O.children)return O;let V=O.children.map(N=>N.index===f.index?{...N,status:f.status,duration:f.duration,phase:void 0,objective:N.objective.startsWith("Step ")?Sr(f.summary||N.objective):N.objective}:N);return{...O,children:V}}));else if(y){let C=Math.max(0,w.current-1);n(O=>{let V=[...O];if(C>=V.length)return O;let N={...V[C]},ee=(N.children??[]).map(Y=>Y.index===f.index?{...Y,status:f.status,duration:f.duration,phase:void 0,objective:Y.objective.startsWith("Step ")?Sr(f.summary||Y.objective):Y.objective}:Y);return N.children=ee,V[C]=N,V})}else n(C=>C.map(O=>O.index===f.index?{...O,status:f.status,duration:f.duration,phase:void 0,objective:O.objective.startsWith("Step ")?Sr(f.summary||O.objective):O.objective}:O));if(!f.child_id){let O=v.current&&!v.current.isSingleFlow?Math.max(0,w.current-1):0;i?.(f.index,O)}break}case"child_agent_start":{let R=f.objective??"";n(y=>y.map(C=>C.status==="running"?{...C,objective:R,phase:`child: ${R.slice(0,50)}`}:C));break}case"child_agent_end":n(R=>R.map(y=>y.phase?.startsWith("child:")?{...y,phase:`child ${f.success?"done":"failed"}`}:y));break;case"ask_user":a(f.question??"");break;case"run_end":n(R=>R.map(y=>y.status==="running"?{...y,status:f.status,phase:void 0}:y)),l(f),t(!1),_.current=null;break;case"error":c(f.message??"Runner error"),n(R=>R.map(y=>y.status==="running"?{...y,status:"failed",phase:void 0}:y)),t(!1),_.current=null;break}}let q=_.current;if(q){let{code:f,signal:R}=await q.exited,y=q.stderr,C=[];f!==null&&f!==0&&C.push(`Runner exited with code ${f}`),R&&C.push(`Runner killed by signal ${R}`),y&&C.push(y),C.length>0&&c(C.join(`
|
|
37
|
+
`))}t(!1),_.current=null})().catch(q=>{let f=_.current,R=[`Runner event loop error: ${q}`];f&&(f.exitCode!==null&&f.exitCode!==0&&R.push(`Exit code: ${f.exitCode}`),f.exitSignal&&R.push(`Signal: ${f.exitSignal}`),f.stderr&&R.push(f.stderr)),c(R.join(`
|
|
38
|
+
`)),t(!1),_.current=null})},[i]),X=(0,Te.useCallback)(B=>{_.current?.sendUserResponse(B),a(null)},[]),W=(0,Te.useCallback)(()=>{let B=_.current;B&&(B.sendCancel("user"),t(!1),a(null),setTimeout(()=>{_.current===B&&(B.cancel(),_.current=null)},5e3))},[]);return(0,Te.useEffect)(()=>()=>{F.current=!0,_.current?.cancel(),_.current=null},[]),{isRunning:e,steps:r,askingUser:s,lastRunEnd:o,runError:d,bifurcationInfo:h,cmInitCounts:S,startRun:K,sendAnswer:X,cancelRun:W}}var ea=null;function Zs(i){ea=i}import{readdirSync as ta,readFileSync as to,existsSync as no}from"fs";import{join as na}from"path";function eo(i,e){if(!no(i))return{};let t={},r;try{r=ta(i).filter(n=>n.endsWith(".json")).sort()}catch{return{}}for(let n of r)try{let s=to(na(i,n),"utf-8"),a=JSON.parse(s);if(a&&typeof a=="object"){for(let[o,l]of Object.entries(a))if(l&&typeof l=="object"&&"value"in l){let d=l;t[o]={value:d.value,secret:d.secret??!1,syntax:d.syntax??`{{${o}}}`}}}}catch{e?.(`Warning: skipping invalid variables file: ${n}`)}return t}function ro(i){no(i)||(console.error(`Variables file not found: ${i}`),process.exit(2));let e=to(i,"utf-8"),t=JSON.parse(e),r={};if(t&&typeof t=="object"){for(let[n,s]of Object.entries(t))if(s&&typeof s=="object"&&"value"in s){let a=s;r[n]={value:a.value,secret:a.secret??!1,syntax:a.syntax??`{{${n}}}`}}}return r}function so(i){let e;try{e=JSON.parse(i)}catch{console.error("Invalid --variables JSON"),process.exit(2)}let t={};if(e&&typeof e=="object"){for(let[r,n]of Object.entries(e))if(n&&typeof n=="object"&&"value"in n){let s=n;t[r]={value:s.value,secret:s.secret??!1,syntax:s.syntax??`{{${r}}}`}}}return t}function Ln(i,e,t){let r=eo(i,t),n=eo(e,t);return{...r,...n}}import{readFileSync as ra,existsSync as sa}from"fs";function Qt(i){if(!sa(i))return null;try{return ra(i,"utf-8").trim()||null}catch{return null}}function Mn(i,e){let t={},r={},n=e;for(let[s,a]of Object.entries(i))if(a.secret){let o=`secrets.user.${s}`;t[o]={value:a.value,secret:!0,syntax:`{{secrets.user.${s}}}`,type:"secret"},r[s]=o,n=n.replaceAll(`{{${s}}}`,`{{secrets.user.${s}}}`)}else{let o=`global.${s}`;t[o]={value:a.value,secret:!1,syntax:`{{global.${s}}}`,type:"global"},r[s]=o,n=n.replaceAll(`{{${s}}}`,`{{global.${s}}}`)}return{variables:t,objective:n,keyMap:r}}import{readFileSync as lo,readdirSync as la,existsSync as vn}from"fs";import{dirname as ca,join as Be}from"path";var nt=Z(He(),1);var Ge=Z(le(),1),oa=64;function ia(i){return i.split(`
|
|
39
|
+
`).map(e=>e.replace(/^[-–•]\s*/,"").trim()).filter(e=>e.length>0)}function Er({status:i,summary:e,duration:t,steps:r,stepsPassed:n,stepsFailed:s,reason:a,creditsConsumed:o}){let l=i==="passed",d=l?m.green:m.red,c=l?"\u2713":"\u2717",h=i.toUpperCase(),g=n??(l?r:Math.max(0,r-1)),S=s??(l?0:1),p=S>0?`${r} steps (${g} passed, ${S} failed)`:`${r} steps`,_=t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`,v=ia(e);return(0,Ge.jsx)(x,{flexDirection:"column",marginTop:1,children:(0,Ge.jsxs)(x,{borderStyle:"round",borderColor:d,flexDirection:"column",paddingX:2,paddingY:1,width:oa+6,children:[(0,Ge.jsxs)(x,{children:[(0,Ge.jsxs)(u,{bold:!0,color:d,children:[c," ",h]}),(0,Ge.jsxs)(u,{color:m.dimmed,children:[" ","\xB7 ",p," \xB7 ",_,typeof o=="number"&&o>0?` \xB7 ${o.toFixed(4)} credits`:""]})]}),v.length>0&&(0,Ge.jsx)(x,{flexDirection:"column",marginTop:1,marginLeft:1,children:v.map((w,F)=>(0,Ge.jsxs)(x,{marginBottom:F<v.length-1?1:0,children:[(0,Ge.jsx)(u,{color:m.primary,children:"\u25CF "}),(0,Ge.jsx)(x,{flexShrink:1,children:(0,Ge.jsx)(u,{wrap:"wrap",children:w})})]},F))}),a&&!l&&(0,Ge.jsx)(x,{marginTop:1,children:(0,Ge.jsxs)(u,{color:m.red,wrap:"wrap",children:["Reason: ",a]})})]})})}var Xe=Z(le(),1);function oo({message:i,code:e,remediation:t,docsUrl:r}){return(0,Xe.jsx)(Cn,{title:"Error",variant:"error",children:(0,Xe.jsxs)(x,{flexDirection:"column",paddingY:1,children:[(0,Xe.jsxs)(u,{color:m.red,bold:!0,children:[" \u2717 ",i]}),e&&(0,Xe.jsxs)(x,{marginTop:0,marginLeft:5,children:[(0,Xe.jsx)(u,{color:m.muted,children:"Code: "}),(0,Xe.jsx)(u,{color:m.dimmed,children:e})]}),t&&(0,Xe.jsxs)(x,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,Xe.jsx)(u,{color:m.green,bold:!0,children:"Fix:"}),(0,Xe.jsxs)(u,{color:m.cyan,children:["$ ",t]})]}),r&&(0,Xe.jsxs)(x,{marginTop:1,marginLeft:5,children:[(0,Xe.jsx)(u,{color:m.muted,children:"Docs: "}),(0,Xe.jsx)(u,{color:m.cyan,underline:!0,children:r})]})]})})}var Pe=Z(le(),1);function io({data:i,color:e}){let t=i.status==="passed"?"passed":"failed";return(0,Pe.jsx)(Er,{status:t,summary:i.summary??"",duration:i.duration,steps:i.stepsTotal,stepsPassed:i.stepsPassed,stepsFailed:i.stepsFailed,reason:i.reason,creditsConsumed:i.creditsConsumed})}function ao({config:i,spawnOpts:e,cancelRef:t,banner:r,onComplete:n,onStepEnd:s}){let{exit:a}=Sn(),o=Vn(s),l=(0,nt.useRef)(!1),d=(0,nt.useRef)(!1),[c,h]=(0,nt.useState)("");(0,nt.useEffect)(()=>{l.current||(l.current=!0,o.startRun(i,e))},[i,e,o]),(0,nt.useEffect)(()=>{t&&(t.current=()=>o.cancelRun())},[t,o]);let g=(0,nt.useRef)(0);et((_,v)=>{v.ctrl&&_==="c"&&(o.isRunning?(g.current++,g.current>=2?a():o.cancelRun()):a())}),et((_,v)=>{o.askingUser&&(v.return?(o.sendAnswer(c),h("")):v.backspace||v.delete?h(w=>w.slice(0,-1)):_&&!v.ctrl&&!v.meta&&h(w=>w+_))},{isActive:!!o.askingUser}),(0,nt.useEffect)(()=>{if(!o.isRunning&&o.lastRunEnd&&!d.current){d.current=!0;let _=o.steps.flatMap(X=>{let W=X.children??[];return[X,...W]}),v=_.filter(X=>X.status==="passed").length,w=_.filter(X=>X.status==="failed").length,F=_.filter(X=>X.status==="passed"||X.status==="failed").length,K=o.bifurcationInfo;n({lastRunEnd:o.lastRunEnd,stepsPassed:v,stepsFailed:w,stepsTotal:F,hadError:!1,bifurcationFlows:K&&!K.isSingleFlow?K.flows:null}),a()}},[o.isRunning,o.lastRunEnd,o.steps,n,a]),(0,nt.useEffect)(()=>{o.runError&&!o.isRunning&&!d.current&&(d.current=!0,n({lastRunEnd:null,stepsPassed:0,stepsFailed:0,stepsTotal:0,hadError:!0,bifurcationFlows:null}),a())},[o.runError,o.isRunning,n,a]);let S=o.lastRunEnd?(()=>{let _=o.steps.flatMap(K=>[K,...K.children??[]]),v=_.filter(K=>K.status==="passed").length,w=_.filter(K=>K.status==="failed").length,F=_.filter(K=>K.status==="passed"||K.status==="failed").length;return{status:o.lastRunEnd.status,duration:o.lastRunEnd.duration??0,summary:o.lastRunEnd.summary??"",stepsPassed:v,stepsFailed:w,stepsTotal:F,reason:o.lastRunEnd.reason,finalState:o.lastRunEnd.final_state,creditsConsumed:o.lastRunEnd.credits_consumed}})():null,p=(0,nt.useMemo)(()=>r?[{key:"banner",...r}]:[],[r]);return(0,Pe.jsxs)(x,{flexDirection:"column",children:[(0,Pe.jsx)(Gt,{items:p,children:_=>(0,Pe.jsxs)(x,{flexDirection:"column",marginBottom:1,children:[(0,Pe.jsxs)(x,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,Pe.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,Pe.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,Pe.jsx)(u,{color:m.cyan,children:_.model}),(0,Pe.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,Pe.jsx)(u,{color:m.dimmed,children:_.auth})]}),_.status?.map((v,w)=>(0,Pe.jsx)(u,{color:m.dimmed,children:v},w))]},_.key)}),o.steps.length>0&&(0,Pe.jsx)(On,{steps:o.steps,bifurcated:!!o.bifurcationInfo&&!o.bifurcationInfo.isSingleFlow,flows:o.bifurcationInfo?.flows,cmInitCounts:o.cmInitCounts,staticSteps:!0}),o.askingUser&&(0,Pe.jsxs)(x,{flexDirection:"column",marginTop:1,children:[(0,Pe.jsxs)(u,{color:m.yellow,children:['Agent is asking: "',o.askingUser,'"']}),(0,Pe.jsxs)(u,{children:["> ",c,"\u2588"]})]}),o.runError&&(0,Pe.jsx)(oo,{message:o.runError,code:"RUNNER_ERROR"}),S&&(0,Pe.jsx)(Er,{status:S.status==="passed"?"passed":"failed",summary:S.summary??"",duration:S.duration,steps:S.stepsTotal,stepsPassed:S.stepsPassed,stepsFailed:S.stepsFailed,reason:S.reason,creditsConsumed:S.creditsConsumed})]})}var Zt=class{constructor(e){this.baseUrl=e}async pushSecret(e){let t=`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString("base64")}`,r=await fetch(`${this.baseUrl}/logistics/v1.0/secrets/create`,{method:"PUT",headers:{Authorization:t,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({secretKey:e.secretKey,secretValue:e.secretValue,orgId:e.orgId,username:e.username,scope:"user",type:"user",accessKey:e.accessKey})});if(!r.ok)throw new Error(`Push secret failed: ${r.status} ${await r.text()}`)}static extractVariableKeys(e){let t=e.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g),r=new Set;for(let n of t)r.add(n[1]);return[...r]}};var en=class{constructor(e,t,r){this.baseUrl=e;this.authHeader=`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`}authHeader;headers(){return{Authorization:this.authHeader,"Content-Type":"application/json",Accept:"application/json"}}async upsertVariable(e){let t=e.environmentId??0,r=await fetch(`${this.baseUrl}/v1/variables`,{method:"POST",headers:this.headers(),body:JSON.stringify({name:e.name,value:String(e.value),type:"variable",value_type:"string",is_persist:e.isPersist??!1,environment_id:t})});if(r.ok)return{id:(await r.json()).id??0};if(r.status!==409&&r.status!==422)return{id:0};if(!(await fetch(`${this.baseUrl}/v1/variables/name/${encodeURIComponent(e.name)}`,{method:"PUT",headers:this.headers(),body:JSON.stringify({value:String(e.value),value_type:"string",type:"variable",environment_id:t})})).ok)return{id:0};let s=await fetch(`${this.baseUrl}/v1/variables/${encodeURIComponent(e.name)}?environment_id=${t}`,{method:"GET",headers:this.headers()});return s.ok?{id:(await s.json()).data?.id??0}:{id:0}}};import aa from"sharp";var tn=class{maxWorkers;maxRetries=2;queue=[];activeCount=0;drainResolvers=[];sas;constructor(e,t=3){this.sas=e,this.maxWorkers=t}updateSas(e){this.sas=e}enqueue(e,t){this.queue.push({operationId:e,buffer:t}),this.pump()}async drain(e=3e4){if(!(this.queue.length===0&&this.activeCount===0))return new Promise(t=>{this.drainResolvers.push(t),setTimeout(()=>{t()},e)})}pump(){for(;this.activeCount<this.maxWorkers&&this.queue.length>0;){let e=this.queue.shift();this.activeCount++,this.processJob(e).finally(()=>{if(this.activeCount--,this.pump(),this.queue.length===0&&this.activeCount===0){for(let t of this.drainResolvers)t();this.drainResolvers=[]}})}}async processJob(e){let t,r="image/webp";try{let o=await aa(e.buffer).webp({quality:80}).toBuffer();t=new Uint8Array(o)}catch{t=new Uint8Array(e.buffer),r="image/png"}let n=r==="image/webp"?"webp":"png",s=`test_screenshots/untagged_screenshot/${e.operationId}.${n}`,a=`${this.sas.base_url}/${this.sas.container}/${s}?${this.sas.sas_token}`;for(let o=0;o<=this.maxRetries;o++)try{if((await fetch(a,{method:"PUT",headers:{"Content-Type":r,"x-ms-blob-type":"BlockBlob"},body:t})).ok)return;if(o<this.maxRetries){await this.backoff(o);continue}}catch{if(o<this.maxRetries){await this.backoff(o);continue}}}backoff(e){let t=e===0?1e3:3e3;return new Promise(r=>setTimeout(r,t))}isNearExpiry(){if(!this.sas.expiry)return!1;let e=new Date(this.sas.expiry).getTime();return Date.now()>e-5*6e4}};var J=Z(le(),1);function co({localMode:i=!1,codeExport:e=!1,updatePromise:t}={}){let{exit:r}=Sn(),[n]=(0,M.useState)(()=>new Yt),[s]=(0,M.useState)(()=>new tt),a=(0,M.useRef)(0),o=(0,M.useCallback)(()=>`msg-${++a.current}`,[]),[l,d]=(0,M.useState)(!1),[c,h]=(0,M.useState)(null),[g,S]=(0,M.useState)(!1),[p,_]=(0,M.useState)(null),[v,w]=(0,M.useState)(!1),[F,K]=(0,M.useState)(0),[X,W]=(0,M.useState)(!1),[B,$]=(0,M.useState)(null),[E,q]=(0,M.useState)(null),[f,R]=(0,M.useState)(Zn()),[y,C]=(0,M.useState)(null),[O,V]=(0,M.useState)(!1),N=(0,M.useRef)(null),ee=(0,M.useRef)(0),Y=(0,M.useRef)(""),ce=(0,M.useRef)(0),[oe,Oe]=(0,M.useState)([]),de=(0,M.useCallback)(b=>{let P=`s-${++ce.current}`;Oe(A=>[...A,{id:P,content:b}])},[]),[Jt,sn]=(0,M.useState)(()=>new tt().load().setup_complete),[Ut,St]=(0,M.useState)("menu"),[me,rt]=(0,M.useState)({headless:!1,maxSteps:50,timeout:0,cdpEndpoint:"",wsEndpoint:"",useCft:!1}),G=as(),I=zs(),je=Ys(),bn=(0,M.useCallback)((b,P)=>{let A=N.current;if(!A)return;let T=ee.current+P,L=Be(n.sessionDir,"runs",String(T),"run-test");try{if(!vn(L)){n.log(`SCREENSHOT_UPLOAD skip step=${b} reason=runsDir_not_found path=${L}`);return}let H=L;if(vn(Be(L,"screenshots")))H=L;else{let we=la(L).filter(gt=>vn(Be(L,gt,"screenshots")));if(we.length===0){n.log(`SCREENSHOT_UPLOAD skip step=${b} reason=no_screenshots_dir`);return}H=Be(L,we[0])}let re=Be(H,"screenshots",`step_${String(b).padStart(3,"0")}.png`);if(!vn(re)){n.log(`SCREENSHOT_UPLOAD skip step=${b} reason=screenshot_not_found path=${re}`);return}let Ee=lo(re),_e=Be(H,"actions.ndjson");if(!vn(_e)){n.log(`SCREENSHOT_UPLOAD skip step=${b} reason=ndjson_not_found`);return}let ke=lo(_e,"utf-8").trim().split(`
|
|
40
|
+
`),fe=ke[ke.length-1];if(!fe){n.log(`SCREENSHOT_UPLOAD skip step=${b} reason=ndjson_empty`);return}let Ze=JSON.parse(fe).action_id;if(!Ze){n.log(`SCREENSHOT_UPLOAD skip step=${b} reason=no_action_id`);return}A.enqueue(Ze,Ee),n.log(`SCREENSHOT_UPLOAD enqueued step=${b} action_id=${Ze} size=${Ee.length}`)}catch(H){n.log(`SCREENSHOT_UPLOAD error step=${b}: ${H instanceof Error?H.message:String(H)}`)}},[n]),U=Vn(bn),[z,Ct]=(0,M.useState)(()=>s.load()),[,zt]=(0,M.useState)(0),Et=(0,M.useCallback)(()=>zt(b=>b+1),[]),[be,ot]=(0,M.useState)(null),Vt=I.creds.getActiveProfile(),k=I.creds.getDefaultEnv(),ie=(0,M.useCallback)((b,P)=>{let A=b?I.creds.loadProfileConfig(b,P):null;s.save({project_id:A?.project_id??null,project_name:A?.project_name??null,folder_id:A?.folder_id??null,folder_name:A?.folder_name??null}),Ct(s.load())},[I.creds,s]);(0,M.useEffect)(()=>{v||(n.start({model:z.model,environment:k,profile:Vt}),w(!0))},[n,v,z.model,k,Vt]);let Q=(0,M.useCallback)(async b=>{let P=ae(b),A=I.getBasicAuth(),T=A?{username:A.username,accessKey:A.access_key}:await I.getToken().then(H=>H??"");if(!T)return;let L=new cn(P.controllerBaseUrl,T);try{let H=await L.getScreenshotSas();n.setScreenshotSas(H),N.current=new tn(H,3),n.log("SCREENSHOT_SAS fetched OK")}catch(H){n.log(`SCREENSHOT_SAS failed: ${H instanceof Error?H.message:String(H)}`)}},[I,n]),se=(0,M.useCallback)(async b=>{let P=b??I.creds.getDefaultEnv();C(null),N.current=null;let T=await I.initResolver(P,L=>n.log(L)).resolve(!0).catch(()=>null);return C(T),T&&(n.log(`AUTH_RESET resolved: user=${T.username} org=${T.org_id} env=${P}`),await Q(P)),T},[I,n,Q]),Ce=(0,M.useRef)(!1);(0,M.useEffect)(()=>{!l||Ce.current||!v||(Ce.current=!0,se().then(b=>{b?n.log(`BOOT_RESOLVE basic auth resolved: user=${b.username} org=${b.org_id}`):n.log("BOOT_RESOLVE failed \u2014 non-controller APIs may fail")}).catch(b=>{n.log(`BOOT_RESOLVE error: ${b instanceof Error?b.message:String(b)}`)}))},[l,v,se,n]);let pe=(0,M.useCallback)(async()=>{if(y)return n.log(`TMS_CREDS using cached credentials for user=${y.username} org=${y.org_id}`),y;let b=await I.resolveBasicAuth();return b?(n.log(`TMS_CREDS resolved: user=${b.username} org=${b.org_id} user_id=${b.user_id}`),C(b)):n.log("TMS_CREDS failed: no credentials resolved"),b},[I,y,n]),Je=(0,M.useCallback)(async()=>{let b=await pe();if(!b)return n.log("PROJECT failed: no TMS credentials"),null;let P=ae(k),A=new Ot(P.tmsBaseUrl,b.username,b.access_key),T=I.creds.getActiveProfile(),L=I.creds.getDefaultEnv(),H=T?I.creds.loadProfileConfig(T,L):null,re=H?.project_id??z.project_id;if(re)n.log(`PROJECT using cached project_id=${re}`);else{n.log("PROJECT no project_id in config, fetching from TMS...");try{n.log(`PROJECT listing projects from: ${P.tmsBaseUrl}/v1/projects`);let _e=await A.listProjects(fe=>n.log(fe));n.log(`PROJECT found ${_e.length} projects`);let ke=_e.find(fe=>fe.name==="KaneAI Generated");if(ke)re=ke.project_id,n.log(`PROJECT using "KaneAI Generated" project_id=${re}`);else if(_e.length>0){let fe=_e[0];re=fe.project_id,n.log(`PROJECT using first project: name="${fe.name}" project_id=${re}`)}re&&s.set("project_id",re)}catch(_e){return n.log(`PROJECT listing failed: ${_e}`),null}}if(!re)return n.log("PROJECT no projects found"),null;let Ee=H?.folder_id??z.folder_id;if(Ee)n.log(`FOLDER using cached folder_id=${Ee}`);else try{n.log(`FOLDER fetching default folder for project_id=${re}`),Ee=await A.getDefaultFolder(re),n.log(`FOLDER got default folder_id=${Ee}`),Ee&&s.set("folder_id",Ee)}catch(_e){return n.log(`FOLDER default folder fetch failed: ${_e}`),null}return{projectId:re,folderId:Ee??""}},[z.project_id,z.folder_id,pe,k,s,n]),ne=(0,M.useCallback)(b=>{let P=o(),A={...b,id:P};de((0,J.jsx)(hs,{entry:A}))},[o,de]),ue=(0,M.useCallback)(async(b,P)=>{let A=n.nextRunIndex();ee.current=A,Y.current=b,n.logRunStart(A,b,P??""),n.setFirstRun(b,P??"");let L=I.getResolvedBasicAuth(),H=null;if(!L&&(H=await I.getToken(),!H)){ne({type:"error",text:"Not authenticated. Run /login first."});return}if(A===0&&!i){n.log("ATM_CREATE runIndex=0 \u2014 creating test via ATM endpoint");let Ie=await Je();try{let Mt=ae(k),vt=L?{username:L.username,access_key:L.access_key}:await pe(),Ft=vt?.username??"",At=vt?.access_key??"",Hr=await new Ot(Mt.tmsBaseUrl,Ft,At).createAtmTest({objective:b.slice(0,100),creation_mode:"KANECLI",playground_disabled:!!z.chrome_profile_path,testURL:P??z.default_url??"",project_id:Ie?.projectId??z.project_id??"",folder_id:Ie?.folderId??z.folder_id??"",authoring_version:4});n.log(`ATM_CREATE success: test_id=${Hr}`),n.setTestId(Hr),Ie?.projectId&&n.setProjectId(Ie.projectId)}catch(Mt){n.log(`ATM_CREATE failed: ${Mt}`)}}let re=null;if(me.useCft)ne({type:"info",text:"CfT mode: Playwright will manage browser"});else if(me.wsEndpoint)ne({type:"info",text:`WS endpoint: ${me.wsEndpoint.slice(0,60)}...`});else if(me.cdpEndpoint)ne({type:"info",text:`CDP endpoint: ${me.cdpEndpoint}`});else{ne({type:"info",text:"Starting Chrome..."});try{re=await je.ensureChrome(P)}catch(Ie){ne({type:"error",text:`Chrome failed: ${Ie instanceof Error?Ie.message:String(Ie)}`});return}n.logChromeLaunch(re.port,re.cdpEndpoint),ne({type:"info",text:`Chrome ready (port ${re.port})`})}let Ee=Be(ye,"variables"),_e=Be(process.cwd(),".testmuai","variables"),ke=Ln(Ee,_e),fe=Qt(Be(ye,"global-memory.md")),$e=Qt(Be(process.cwd(),".testmuai","context.md")),Ze=Object.keys(ke).length>0,{variables:we,objective:gt}=Ze?Mn(ke,b):{variables:ke,objective:b};n.setAuteurVariables(we);let Lt=Object.entries(ke).filter(([,Ie])=>Ie.secret);if(!i&&Lt.length>0&&L){let Ie=ae(k),Mt=new Zt(Ie.secretsBaseUrl),vt=await pe();for(let[Ft,At]of Lt)Mt.pushSecret({secretKey:Ft,secretValue:At.value,username:L.username,accessKey:L.access_key,orgId:String(vt?.org_id??"")}).then(()=>n.log(`SECRET_PUSH success key=${Ft}`)).catch(Nr=>n.log(`SECRET_PUSH failed key=${Ft}: ${Nr}`))}let Fr={},wn=Object.entries(ke).filter(([,Ie])=>!Ie.secret);if(!i&&wn.length>0&&L){let Ie=ae(k),Mt=new en(Ie.tmsBaseUrl,L.username,L.access_key);for(let[vt,Ft]of wn)try{let At=await Mt.upsertVariable({name:vt,value:Ft.value});Fr[vt]=At.id,n.log(`VAR_PUSH success name=${vt} id=${At.id}`)}catch(At){n.log(`VAR_PUSH failed name=${vt}: ${At}`)}}let $o={objective:gt,...P?{url:P}:{},model:z.model,...me.wsEndpoint?{ws_endpoint:me.wsEndpoint}:me.cdpEndpoint?{cdp_endpoint:me.cdpEndpoint}:re?{cdp_endpoint:re.cdpEndpoint}:{},width:z.window_size.width,height:z.window_size.height,session_id:n.sessionId,run_index:A,stream:!0,...me.maxSteps!==50?{max_steps:me.maxSteps}:{},...me.headless?{headless:!0}:{},...L?{username:L.username,access_key:L.access_key}:H?{auth:{type:"bearer",token:H}}:{},session_context:n.getContext(),variables:Object.keys(we).length>0?we:void 0,global_context:fe??void 0,local_context:$e??void 0};P&&_(P),$(null),U.startRun($o,{environment:k}),K(Ie=>Ie+1)},[I,je,s,z,n,k,U,ne,me,Je,pe]);(0,M.useEffect)(()=>{if(U.bifurcationInfo){let{flows:b,isSingleFlow:P}=U.bifurcationInfo;if(P&&b.length===1&&b[0])n.log(`OBJECTIVE_REWRITTEN ${b[0]}`),ne({type:"info",text:`Objective: ${b[0]}`});else if(!P&&b.length>1){let A=[`Bifurcated into ${b.length} flows:`];b.forEach((T,L)=>A.push(` ${L+1}. ${T}`)),n.log(`BIFURCATION ${b.length} flows`),ne({type:"info",text:A.join(`
|
|
41
|
+
`)})}}},[U.bifurcationInfo,n,ne]);let Ue=M.default.useRef(null),xe=M.default.useRef(0),he=M.default.useRef(0);(0,M.useEffect)(()=>{if(U.lastRunEnd&&U.lastRunEnd!==Ue.current){Ue.current=U.lastRunEnd;let{status:b,duration:P,summary:A,reason:T,context:L}=U.lastRunEnd,H=U.steps.flatMap(we=>{let gt=we.children??[];return[we,...gt]}),re=H.filter(we=>we.status==="passed").length,Ee=H.filter(we=>we.status==="failed").length,_e=H.filter(we=>we.status==="passed"||we.status==="failed").length;xe.current+=_e,he.current+=P??0,$({status:b,duration:P??0,summary:A??"",stepsPassed:re,stepsFailed:Ee,stepsTotal:_e,reason:T,finalState:U.lastRunEnd?.final_state,creditsConsumed:U.lastRunEnd?.credits_consumed}),n.logRunEnd(ee.current,b,P,A);let ke=U.lastRunEnd?.total_runs??1,fe=U.lastRunEnd?.run_dir,$e,Ze;if(ke>1&&fe){let we=ca(fe),gt=ee.current;$e=Array.from({length:ke},(Fr,wn)=>Be(we,String(gt+wn)));let Lt=U.bifurcationInfo;Lt&&!Lt.isSingleFlow&&Lt.flows.length===ke&&(Ze=Lt.flows)}n.addRunResult({index:ee.current,objective:Y.current,summary:A,status:b,context:L??{memory:{},variables:{},pointer:""},run_dir:fe,run_dirs:$e,flow_objectives:Ze},U.lastRunEnd?.total_runs)}},[U.lastRunEnd,n,ne]);let lt=(0,M.useRef)(null);(0,M.useEffect)(()=>{U.askingUser&&U.askingUser!==lt.current&&(lt.current=U.askingUser,de((0,J.jsxs)(x,{children:[(0,J.jsx)(u,{color:"#ff9500",children:"? "}),(0,J.jsx)(u,{color:"#ff9500",children:"Agent asks: "}),(0,J.jsx)(u,{children:U.askingUser})]}))),U.askingUser||(lt.current=null)},[U.askingUser,de]);let kt=(0,M.useRef)(null);(0,M.useEffect)(()=>{if(B&&!U.isRunning&&U.lastRunEnd){let b=`${U.lastRunEnd.status}-${U.lastRunEnd.summary?.slice(0,20)}`;if(kt.current===b)return;kt.current=b,de((0,J.jsx)(io,{data:B,color:B.status==="passed"?"#4ade80":"#ef4444"})),$(null)}},[B,U.isRunning,U.lastRunEnd,de]),(0,M.useEffect)(()=>{if(U.runError&&!U.isRunning){let b=U.runError.trim();n.log(`RUNNER_ERROR ${b.replace(/\n/g,"\\n")}`);let A=b.split(`
|
|
42
42
|
`).slice(-8).join(`
|
|
43
|
-
`);
|
|
44
|
-
${R}`})}},[B.runError,B.isRunning,re,n]);let Rt=(0,U.useCallback)(async()=>{n.log("EXIT_UPLOAD starting exit upload pipeline"),k(Zn()),X({status:"uploading"});let _=ce(E),T=$.getResolvedBasicAuth(),R;if(T)n.log("EXIT_UPLOAD using resolved basic auth for controller"),R={username:T.username,accessKey:T.access_key};else{let Ce=await $.getToken();if(!Ce)return n.log("EXIT_UPLOAD aborted: no auth available"),null;R=Ce}let O=y??await me();if(!O)return n.log("EXIT_UPLOAD aborted: no TMS credentials"),n.setUploadStatus("failed","Could not get TMS credentials"),null;let V=n.generateCommitId();n.log(`EXIT_UPLOAD config: testId=${n.testId} commitId=${V} projectId=${K.project_id} sessionDir=${n.sessionDir} runDirs=${JSON.stringify(n.getRunDirs())}`);let z=T?.username??O.username,se=T?.access_key??O.access_key,Ue=n.getContext().prior_runs,Se=n.getRunObjectives(),Pe=[];for(let[Ce]of Object.entries(n.auteurVariables))if(Ce.startsWith("secrets.user.")){let xe=Ce.replace("secrets.user.","");Pe.push({key_name:xe,scope:"user"})}F.current&&(n.log("SCREENSHOT_UPLOAD draining queue before pipeline"),await F.current.drain(),n.log("SCREENSHOT_UPLOAD queue drained"));let Ve=await new es({controllerBaseUrl:_.controllerBaseUrl,tmsBaseUrl:_.tmsBaseUrl,auth:R,authResolver:$.getResolver()??void 0,sessionId:n.sessionId,sessionDir:n.sessionDir,testId:n.testId,commitId:V,projectId:K.project_id,folderId:K.folder_id,firstObjective:n.firstObjective??"KaneAI Test",firstUrl:n.firstUrl??"",runDirs:n.getRunDirs(),runObjectives:Se,startedAt:n.startedAt,endedAt:new Date().toISOString(),totalSteps:ge.current,totalDuration:pe.current,runStatuses:Ue.map(Ce=>Ce.status),orgId:O.org_id,userId:O.user_id,tmsUsername:z,tmsAccessKey:se,screenshotBaseUrl:n.screenshotBaseUrl,shareApiBaseUrl:_.shareApiBaseUrl,testManagerUiUrl:_.testManagerUiUrl,variables:Object.keys(n.auteurVariables).length>0?n.auteurVariables:void 0,variableIds:{},secrets:Pe,codeExport:e,onProgress:(Ce,xe,lt)=>{n.log(`EXIT_PROGRESS step=${Ce} status=${xe}${lt?` detail=${lt}`:""}`),k(gt=>ts(gt,Ce,xe,lt))},log:Ce=>n.log(Ce)}).execute();return Ve.success?(n.log(`EXIT_UPLOAD success: testId=${Ve.testId} testcaseId=${Ve.testcaseId??"none"} shareId=${Ve.shareId??"none"}`),n.setUploadStatus("uploaded"),Ve.testId&&n.setTestId(Ve.testId),Ve.testcaseId&&n.setTestcaseId(Ve.testcaseId)):(n.log(`EXIT_UPLOAD failed: ${Ve.error}`),n.setUploadStatus("failed",Ve.error)),Ve},[$,E,n,K,y,me]),At=(0,U.useCallback)(()=>{n.finish("complete"),un(),Be.killChrome(),setTimeout(()=>r(),1500)},[n,Be,r]),rt=(0,U.useCallback)(async _=>{if(j(!1),_&&n.testId){n.log(`EXIT feedback=${_}, submitting...`);try{let T=ce(E),R=$.getResolvedBasicAuth();R&&(await new It(T.tmsBaseUrl,R.username,R.access_key).submitFeedback({instruction_id:"",test_id:n.testId,feedback_type:_,mode:"human"}),n.log("EXIT feedback submitted"))}catch(T){n.log(`EXIT feedback failed: ${T}`)}}else n.log("EXIT feedback skipped");At()},[E,$,n,At]),mt=(0,U.useCallback)(()=>{if(Q)return;let _=n.nextRunIndex()>0;if(n.log(`EXIT hasRuns=${_} localMode=${i}`),!_||i){n.log(`EXIT quick exit \u2014 ${_?"local mode":"no runs"}`),n.finish("complete"),un(),Be.killChrome(),r();return}n.log("EXIT starting upload pipeline..."),te(!0),Rt().then(T=>{let R=ce(E),O=K.project_id;if(T?.testcaseId&&O){let V=`${R.testManagerUiUrl}/projects/${O}/test-cases/${T.testcaseId}`,z=T.shareId?`${V}/dashboard/share/${T.shareId}`:void 0,se=`${V}/dashboard?type=summary&agentView=true&fqdn=summary-page`;X({status:"success",testUrl:z,testCaseLink:se,codeExportDir:T.codeExportDir}),Zs({shareableLink:z,testCaseLink:se,codeExportDir:T.codeExportDir})}else X({status:T?.success?"success":"failed",error:T?.error});j(!0)}).catch(T=>{n.log(`EXIT_UPLOAD exception: ${T}`),n.setUploadStatus("failed",String(T)),X({status:"failed",error:String(T)}),j(!0)})},[Q,n,Be,r,i,Rt,E,K]);(0,U.useEffect)(()=>{if(!Q)return;let _=300*1e3,T=setTimeout(()=>{n.setUploadStatus("failed","Upload timed out after 5m"),n.finish("complete"),un(),Be.killChrome(),process.exit(0)},_);return()=>clearTimeout(T)},[Q,n,Be]);let Mt=U.default.useRef(0),Oe=U.default.useRef(null),be=U.default.useRef(0);Ze((_,T)=>{if(T.ctrl&&_==="c"){if(Q){be.current+=1,be.current>=2&&(n.setUploadStatus("pending","Force exit by user"),n.finish("complete"),un(),Be.killChrome(),process.exit(0));return}if(B.isRunning){B.cancelRun(),re({type:"info",text:"Run cancelled."}),Mt.current++,Oe.current&&clearTimeout(Oe.current),Oe.current=setTimeout(()=>{Mt.current=0},2e3),Mt.current>=2&&mt();return}if(Vt==="chat"){St("menu");return}mt()}});let st=U.default.useMemo(()=>{let _=$.creds.getActiveProfile()??"none",T=$.creds.getDefaultEnv();return[{id:"run",label:"Run",type:"submenu",children:[{id:"run-start",label:"Start Run",type:"action"},{id:"run-config",label:"Run Config",type:"submenu",children:[{id:"run-headless",label:"Headless",type:"select",currentValue:fe.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:R=>{nt(O=>({...O,headless:R==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(fe.maxSteps),onValue:R=>{let O=parseInt(R,10);O>0&&nt(V=>({...V,maxSteps:O}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:fe.timeout?String(fe.timeout):"",placeholder:"0 = no timeout",onValue:R=>{let O=parseInt(R,10);nt(V=>({...V,timeout:isNaN(O)?0:O}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:fe.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:R=>{nt(O=>({...O,cdpEndpoint:R}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:fe.wsEndpoint,placeholder:"wss://...",onValue:R=>{nt(O=>({...O,wsEndpoint:R}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{$.logout().then(R=>{Et();let O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv();ie(O,V),ne().catch(()=>{}),re(R?{type:"info",text:`Logged out: ${R.profile} [${R.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{re({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let R=$.creds.getActiveProfile()??"none",O=$.creds.getDefaultEnv(),V=$.creds.loadBasicAuth(R,O),z=V?"basic":$.creds.loadCredentials(R,O)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:R},{key:"Environment",value:O}]},{label:"Authentication",entries:[{key:"Method",value:z},...V?[{key:"Username",value:V.username}]:[]]},{label:"Token",entries:[{key:"Status",value:$.tokenValid?"valid":"not logged in",color:$.tokenValid?m.statusPass:m.statusFail}]}]}}},{id:"profiles",label:"Profiles",type:"action",onProfilesView:()=>{}}]},{id:"config",label:"Config",type:"submenu",children:[{id:"config-show",label:"Show",type:"action",onInfo:()=>({title:"Show Config",sections:[{label:"General",entries:[{key:"Model",value:"v16-alpha"}]},{label:"Browser",entries:[{key:"Window",value:`${K.window_size.width}x${K.window_size.height}`},{key:"Chrome Profile",value:K.chrome_profile_path?K.chrome_profile_path.split("/").pop()??K.chrome_profile_path:"(temporary)"}]},{label:"Project",entries:[{key:"Project",value:K.project_name?`${K.project_name} (${K.project_id})`:K.project_id??"(none)"},{key:"Folder",value:K.folder_name?`${K.folder_name} (${K.folder_id})`:K.folder_id??"(none)"},{key:"Default URL",value:K.default_url??"(none)"}]}]})},{id:"config-chrome",label:"Chrome Profile",type:"action",onChromeProfilePicker:()=>{}},{id:"config-project",label:"Project",type:"action",onProjectPicker:()=>{}},{id:"config-folder",label:"Folder",type:"action",...K.project_id?{onFolderPicker:()=>{}}:{onInfo:()=>({title:"Folder",sections:[{entries:[{key:"Status",value:"Select a project first",color:m.dim}]}]})}},{id:"config-url",label:"Default URL",type:"text-input",currentValue:K.default_url??"",onValue:R=>{s.set("default_url",R)}},{id:"config-window",label:"Window Size",type:"text-input",currentValue:`${K.window_size.width}x${K.window_size.height}`,placeholder:"WIDTHxHEIGHT",onValue:R=>{let O=R.split("x").map(Number);O[0]&&O[1]&&s.set("window_size",{width:O[0],height:O[1]})}}]},{id:"help",label:"Help",type:"submenu",children:[{id:"help-paths",label:"File Paths",type:"action",onInfo:()=>({title:"File Paths",sections:[{label:"Variables",entries:[{key:"Global dir",value:`${De(_e,"variables")}/*.json`},{key:"Local dir",value:"{cwd}/.testmuai/variables/*.json"},{key:"Format",value:'{ "key": { "value": "...", "secret": false } }'},{key:"Usage",value:"{{key}} in objectives"}]},{label:"Context Files",entries:[{key:"Global",value:De(_e,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:De(_e,"tui-config.json")},{key:"Auth",value:De(_e,"config.json")},{key:"Sessions",value:`${De(_e,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${De(_e,"variables")}/*.json`},{key:"2. Local",value:"{cwd}/.testmuai/variables/*.json"},{key:"3. CLI",value:"--variables-file <path>"},{key:"4. Inline",value:`--variables '{"key": {"value": "..."}}"`}]},{label:"Format",entries:[{key:"Normal",value:'{ "username": { "value": "alice", "secret": false } }'},{key:"Secret",value:'{ "api_key": { "value": "sk-...", "secret": true } }'}]},{label:"Usage",entries:[{key:"Syntax",value:"{{key}} in objectives to reference variables"}]}]})},{id:"help-context",label:"Context Files",type:"action",onInfo:()=>({title:"Context Files",sections:[{entries:[{key:"Description",value:"Additional instructions for the agent"}]},{label:"Paths",entries:[{key:"Global",value:De(_e,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"CLI Overrides",entries:[{key:"Global",value:"--global-context <file>"},{key:"Local",value:"--local-context <file>"}]}]})}]},{id:"update",label:d?`Update (${d.current} \u2192 ${d.latest})`:"Update",type:"action",onAction:()=>{x||(S(!0),re({type:"info",text:"Checking for updates..."}),(async()=>{let{checkForUpdate:R}=await import("./version-check-KS7CP3M5.js"),O=await R();if(!O){re({type:"info",text:`Already on latest version (${Pt})`}),S(!1);return}re({type:"info",text:`Update available: ${O.current} \u2192 ${O.latest}. Installing...`});let{runSelfUpdate:V}=await import("./updater-H5HYMYRG.js"),z=await V();z.success?re({type:"info",text:`\u2713 Updated to ${z.toVersion}. Restart kane-cli to use the new version.`}):re({type:"error",text:`Update failed: ${z.error}`}),S(!1)})())}},{id:"exit",label:"Exit",type:"action",onAction:()=>{mt()}}]},[$,s,K,re,mt,fe,Et,d,x]),pt=(0,U.useCallback)(_=>{if(B.askingUser){de((0,H.jsxs)(v,{children:[(0,H.jsx)(u,{color:"#888888",children:"\u2192 "}),(0,H.jsx)(u,{color:"#888888",children:"You answered: "}),(0,H.jsx)(u,{children:_})]})),B.sendAnswer(_);return}if(n.logCommand(_),B.isRunning){re({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}de((0,H.jsxs)(v,{children:[(0,H.jsx)(u,{color:"#b388ff",children:"\u276F "}),(0,H.jsx)(u,{children:_})]}));let T=p??K.default_url;le(_,T||void 0)},[B,re,de,n,p,K,le]),_n="KaneAI CLI",ot=$.getAuthInfo(),ht=ot?ot.method==="basic"?"basic auth":"oauth":"not logged in";return zt?(0,H.jsxs)(v,{flexDirection:"column",children:[oe.length>0&&(0,H.jsx)(Xt,{items:oe,children:_=>(0,H.jsx)(v,{paddingX:1,children:_.content},_.id)}),!l&&(0,H.jsx)(ps,{onComplete:()=>{let _=$.creds.getActiveProfile(),T=$.creds.getDefaultEnv(),R=_?$.creds.loadCredentials(_,T):null,O=_?$.creds.loadBasicAuth(_,T):null,V=!!(R||O),z=O?.username??_??null;de((0,H.jsx)(An,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:Pt,authenticated:V,user:z})),c(!0),t&&t.then(se=>{se&&(h(se),re({type:"info",text:`Update available: ${se.current} \u2192 ${se.latest} \u2014 select Update from menu or run \`kane-cli update\``}))}).catch(()=>{})}}),l&&Vt==="menu"&&!Q&&(0,H.jsx)(v,{marginBottom:1,children:(0,H.jsxs)(v,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,H.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,H.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,H.jsx)(u,{color:"#ff9500",children:K.model}),(0,H.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,H.jsx)(u,{color:m.dimmed,children:ht}),(0,H.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,H.jsxs)(u,{color:m.dimmed,children:[Lt??"no profile","/",E]})]})}),l&&!Q&&(0,H.jsxs)(v,{flexDirection:"column",flexGrow:1,children:[Vt==="menu"&&(0,H.jsx)(H.Fragment,{children:(0,H.jsx)(Ks,{items:st,onRunSelected:()=>St("chat"),renderLoginWizard:_=>{let T=ve?.phase??"wizard";if(T==="project")return(0,H.jsx)(Yn,{resolver:$.getResolver(),currentProjectId:null,env:ve.env,onSelect:(R,O)=>{$.creds.saveProfileConfig(ve.profile,ve.env,{project_id:R,project_name:O}),at(V=>V?{...V,phase:"folder"}:null)},onCancel:()=>{ie(ve.profile,ve.env),at(null),_()}});if(T==="folder"){let R=$.creds.loadProfileConfig(ve.profile,ve.env);return(0,H.jsx)(Qn,{resolver:$.getResolver(),projectId:R?.project_id??"",currentFolderId:null,env:ve.env,onSelect:(O,V)=>{$.creds.saveProfileConfig(ve.profile,ve.env,{folder_id:O,folder_name:V}),ie(ve.profile,ve.env),at(null),_()},onCancel:async()=>{let O=$.creds.loadProfileConfig(ve.profile,ve.env);if(O?.project_id)try{let z=$.getResolver()?.cached;if(z){let se=ce(ve.env),Se=await new It(se.tmsBaseUrl,z.username,z.access_key).getDefaultFolder(O.project_id);Se&&$.creds.saveProfileConfig(ve.profile,ve.env,{folder_id:Se,folder_name:"Default"})}}catch{}ie(ve.profile,ve.env),at(null),_()}})}return(0,H.jsx)(Xr,{devMode:process.env.KANE_DEV_MODE==="1",profiles:$.creds.listProfiles(),onBasicLogin:(R,O,V,z)=>{$.creds.saveBasicAuth(R,O,{username:V,access_key:z}),$.creds.setActiveProfile(R),$.creds.setDefaultEnv(O),$.setTokenValid(!0),Et()},onOAuthLogin:async(R,O)=>{$.creds.setDefaultEnv(O),await $.login(R),Et()},onComplete:(R,O)=>{ne(O).then(()=>{at({phase:"project",profile:R,env:O})}).catch(()=>{at({phase:"project",profile:R,env:O})})},onCancel:()=>{at(null),_()}})},renderProfilesView:_=>(0,H.jsx)(Yr,{creds:$.creds,onSwitch:(T,R)=>{$.creds.setActiveProfile(T),$.creds.setDefaultEnv(R),ie(T,R),Et(),ne(R).catch(()=>{}),re({type:"info",text:`Switched to ${T} [${R}]`})},onCancel:_}),renderChromeProfilePicker:_=>(0,H.jsx)(Qr,{currentPath:K.chrome_profile_path,onSelect:T=>{s.set("chrome_profile_path",T),Ct(s.load())},onCancel:_}),renderProjectPicker:_=>(0,H.jsx)(Yn,{resolver:$.getResolver(),currentProjectId:K.project_id,env:E,onSelect:(T,R)=>{s.save({project_id:T,project_name:R});let O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv();O&&$.creds.saveProfileConfig(O,V,{project_id:T,project_name:R}),Ct(s.load()),_()},onCancel:_}),renderFolderPicker:_=>(0,H.jsx)(Qn,{resolver:$.getResolver(),projectId:K.project_id??"",currentFolderId:K.folder_id,env:E,onSelect:(T,R)=>{s.save({folder_id:T,folder_name:R});let O=$.creds.getActiveProfile(),V=$.creds.getDefaultEnv();O&&$.creds.saveProfileConfig(O,V,{folder_id:T,folder_name:R}),Ct(s.load()),_()},onCancel:_})})}),Vt==="chat"&&(0,H.jsxs)(H.Fragment,{children:[B.isRunning&&B.steps.length>0&&(0,H.jsx)(Pn,{steps:B.steps,bifurcated:!!B.bifurcationInfo&&!B.bifurcationInfo.isSingleFlow,flows:B.bifurcationInfo?.flows,cmInitCounts:B.cmInitCounts,onStepCommit:de},`run-${Z.current}`),(0,H.jsx)(xs,{onSubmit:pt,onEscape:()=>{!B.isRunning&&!B.askingUser&&St("menu")},history:q,placeholder:B.askingUser?"Type your answer...":B.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (esc = menu)"})]})]}),l&&Q&&A&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(ns,{steps:f,status:A.status,testUrl:A.testUrl,error:A.error}),A.status==="success"&&(0,H.jsx)(rs,{shareableLink:A.testUrl,testCaseLink:A.testCaseLink,codeExportDir:A.codeExportDir,autoExit:!1})]}),P&&(0,H.jsx)(ss,{onSubmit:rt}),l&&!Q&&(0,H.jsx)(os,{profile:Lt,environment:E,model:K.model,tokenValid:$.tokenValid,sessionId:n.sessionId,runCount:N,viewMode:Vt})]}):(0,H.jsx)(Fs,{onComplete:()=>{Ct(s.load()),sn(!0)}})}var So=G(yo(),1),{program:uf,createCommand:df,createArgument:ff,createOption:mf,CommanderError:pf,InvalidArgumentError:hf,InvalidOptionArgumentError:gf,Command:Co,Argument:xf,Option:Hn,Help:vf}=So.default;import{join as Qe}from"path";import{readFileSync as ko,readdirSync as Ra,existsSync as vn}from"fs";var Ro=G(We(),1);import{createInterface as ka}from"readline";function rn(i){process.stdout.write(JSON.stringify(i)+`
|
|
45
|
-
`)}async function Eo(i,e,t){let r=Un(i,e);kn().then(h=>{h&&rn({type:"update_available",current:h.current,latest:h.latest,severity:h.severity})}).catch(()=>{});let n=ka({input:process.stdin});n.on("line",h=>{try{let x=JSON.parse(h);x.type==="user_response"?r.sendUserResponse(x.answer??""):x.type==="cancel"&&r.sendCancel(x.reason??"")}catch{}});let s=null,a=!1,o=0,l=null,c=0,d=!1;for await(let h of r.events)switch(h.type){case"run_start":d&&c++;break;case"step_start":{let x=h,S={step:x.index+1,status:"running",remark:x.objective??`Step ${x.index+1}`};x.child_id&&(S.child_id=x.child_id),rn(S);break}case"step_end":{let x=h;o++;let S={step:x.index+1,status:x.status==="passed"?"done":"failed",remark:x.summary??""};x.child_id&&(S.child_id=x.child_id),rn(S);let p=d?Math.max(0,c-1):0;t?.onStepEnd?.(x.index,p);break}case"bifurcation":{let x=h,S=x.flows??[],p=x.count??S.length;(x.is_single_flow??p<=1)||(l=S,d=!0,c=0),rn({type:"bifurcation",flows:S,count:p});break}case"ask_user":{let x=h;rn({type:"ask_user",question:x.question,step_index:x.step_index,...x.options?{options:x.options}:{}});break}case"run_end":{s=h;break}case"error":{a=!0,rn({type:"error",message:h.message});break}default:break}return n.close(),await r.exited,{lastRunEnd:s,stepsTotal:o,hadError:a,bifurcationFlows:l}}function Ao(i){let e=new Co;if(e.name("kane-cli").version(Pt),i[0]==="--help"||i[0]==="-h"||i[0]==="help"){(async()=>{let{HelpView:r}=await import("./HelpView-2ZFLX7JC.js"),{render:n}=await import("./build-MFETN2BY.js"),s=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=n(s.default.createElement(r));await a(),process.exit(0)})();return}e.command("login").action(async()=>{let r=new Ee,{LoginWizard:n}=await import("./LoginWizard-SSE5NJVU.js"),{render:s}=await import("./build-MFETN2BY.js"),a=await import("./react-QWOAB3TB.js");await new Promise(o=>{let{unmount:l}=s(a.default.createElement(n,{devMode:process.env.KANE_DEV_MODE==="1",profiles:r.listProfiles(),onBasicLogin:(c,d,h,x)=>{r.saveBasicAuth(c,d,{username:h,access_key:x}),r.setActiveProfile(c),r.setDefaultEnv(d),l(),o()},onOAuthLogin:async(c,d)=>{r.setDefaultEnv(d),await new bt(c,d,r).login(),l(),o()},onCancel:()=>{l(),o()}}))})}),e.command("logout").action(async()=>{let r=new Ee,n=r.getActiveProfile();if(!n){console.log("No active profile to logout");return}let s=r.getDefaultEnv(),a=r.loadCredentials(n,s),o=r.loadClient(n,s);if(a&&o){let c=new Ge(s);try{await c.revokeToken(a.access_token,o.client_id,"access_token")}catch{}try{await c.revokeToken(a.refresh_token,o.client_id,"refresh_token")}catch{}}r.deleteProfileFull(n,s);let l=r.listProfiles();l.length>0?(r.setActiveProfile(l[0].profile),r.setDefaultEnv(l[0].env),console.log(`Logged out ${n} [${s}]. Switched to ${l[0].profile} [${l[0].env}]`)):console.log(`Logged out ${n} [${s}]. No profiles remaining.`)}),e.command("whoami").option("--profile <name>","Profile name").action(async r=>{let n=new Ee,s=r.profile??n.getActiveProfile()??"default",a=n.getDefaultEnv(),o=n.loadCredentials(s,a),l=n.loadBasicAuth(s,a),c="none",d,h,x;if(l)c="basic",d=l.username;else if(o){c="oauth";let w=o.expires_at,N=Date.now()/1e3;h=w>N?"valid":"expired",x=new Date(w*1e3).toISOString().slice(0,10)}else h="missing";let{WhoamiView:S}=await import("./WhoamiView-2VBZBQF7.js"),{render:p}=await import("./build-MFETN2BY.js"),b=await import("./react-QWOAB3TB.js"),{waitUntilExit:g}=p(b.default.createElement(S,{profile:s,env:a,authenticated:c!=="none",authMethod:c,username:d,tokenStatus:h,expiresAt:x}));await g()}),e.command("config <action> [value]").action(async(r,n)=>{let s=new et,a=new Ee;if(r==="show"){let o=s.load(),l=a.getActiveProfile()??"default",c=a.getDefaultEnv(),d=a.loadBasicAuth(l,c),h=a.loadCredentials(l,c),x=d?`basic (${d.username})`:h?"oauth":"not configured",{ConfigView:S}=await import("./ConfigView-5R4G4OZ6.js"),{render:p}=await import("./build-MFETN2BY.js"),b=await import("./react-QWOAB3TB.js"),{waitUntilExit:g}=p(b.default.createElement(S,{model:o.model,authLabel:x,profile:l,env:c,defaultUrl:o.default_url,projectId:o.project_id,projectName:o.project_name,folderId:o.folder_id,windowSize:`${o.window_size.width}x${o.window_size.height}`,chromeProfile:o.chrome_profile_path,setupComplete:o.setup_complete}));await g()}else if(r==="set-url"&&n)s.set("default_url",n),console.log(`Default URL set to ${n}`);else if(r==="set-window"&&n){let o=n.split("x").map(Number);o[0]&&o[1]&&(s.set("window_size",{width:o[0],height:o[1]}),console.log(`Window size set to ${o[0]}x${o[1]}`))}else if(r==="chrome-profile"){let{ChromeProfilePicker:o}=await import("./ChromeProfilePicker-IRZUDC2R.js"),{render:l}=await import("./build-MFETN2BY.js"),c=await import("./react-QWOAB3TB.js");await new Promise(d=>{let{unmount:h}=l(c.default.createElement(o,{currentPath:s.load().chrome_profile_path,onSelect:x=>{s.set("chrome_profile_path",x),console.log(`Chrome profile set to ${x}`),h(),d()},onCancel:()=>{h(),d()}}))})}else if(r==="project"){let o=a.getDefaultEnv(),l=ce(o),c=a.loadBasicAuth(a.getActiveProfile()??"default",o);if(!c){console.log("Login first to browse projects");return}let{ProjectPicker:d}=await import("./ProjectPicker-AFQDF2VS.js"),{AuthResolver:h}=await import("./resolver-L3Z6FAOD.js"),{render:x}=await import("./build-MFETN2BY.js"),S=await import("./react-QWOAB3TB.js"),p=new h(l.controllerBaseUrl,async()=>null,c);await p.resolve(),await new Promise(b=>{let{unmount:g}=x(S.default.createElement(d,{resolver:p,currentProjectId:s.load().project_id,env:o,onSelect:(w,N)=>{s.set("project_id",w),s.set("project_name",N),console.log(`Project set to ${N} (${w})`),g(),b()},onCancel:()=>{g(),b()}}))})}else if(r==="folder"){let o=s.load();if(!o.project_id){console.log("Select a project first: kane-cli config project");return}let l=a.getDefaultEnv(),c=ce(l),d=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!d){console.log("Login first to browse folders");return}let{FolderPicker:h}=await import("./FolderPicker-G4C4RCP2.js"),{AuthResolver:x}=await import("./resolver-L3Z6FAOD.js"),{render:S}=await import("./build-MFETN2BY.js"),p=await import("./react-QWOAB3TB.js"),b=new x(c.controllerBaseUrl,async()=>null,d);await b.resolve(),await new Promise(g=>{let{unmount:w}=S(p.default.createElement(h,{resolver:b,projectId:o.project_id,currentFolderId:o.folder_id,env:l,onSelect:(N,W)=>{s.set("folder_id",N),s.set("folder_name",W),console.log(`Folder set to ${W} (${N})`),w(),g()},onCancel:()=>{w(),g()}}))})}else console.log("Usage: kane-cli config show|set-url|set-window|chrome-profile|project|folder")}),e.command("run").argument("<objective>","Test objective (use {{var}} to reference variables)").option("--url <url>","Target URL").option("--headless","Run Chrome in headless mode").option("--max-steps <n>","Maximum agent steps","30").option("--timeout <seconds>","Kill run after N seconds").option("--cdp-endpoint <url>","Connect to existing Chrome CDP endpoint").option("--ws-endpoint <url>","Connect via Playwright WebSocket (e.g. LambdaTest wss:// URL)").option("--global-context <file>",`Override global context markdown (default: ${Qe(_e,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new Hn("--model <name>","Model override").hideHelp()).option("--variables <json>",`Inline variables JSON, e.g. '{"user": {"value": "alice"}}'`).option("--variables-file <path>","Load variables from a JSON file").option("--session-context <json>","Session context JSON (prior runs)").addOption(new Hn("--cft","Use Playwright Chromium instead of managed Chrome").hideHelp()).option("--username <user>","Basic auth username (skip OAuth)").option("--access-key <key>","Basic auth access key (skip OAuth)").option("--env <name>","Environment (prod or stage)").option("--agent","Agent mode: plain NDJSON output, no colors/UI").option("--task-skills","Enable domain-specific task skills (experimental)").addOption(new Hn("--local","Skip TMS integration (no uploads, no variables/secrets push)").hideHelp()).option("--code-export","Generate code export after upload").addHelpText("after",`
|
|
43
|
+
`);ne({type:"error",text:`Runner error:
|
|
44
|
+
${A}`})}},[U.runError,U.isRunning,ne,n]);let mt=(0,M.useCallback)(async()=>{n.log("EXIT_UPLOAD starting exit upload pipeline"),R(Zn()),q({status:"uploading"});let b=ae(k),P=I.getResolvedBasicAuth(),A;if(P)n.log("EXIT_UPLOAD using resolved basic auth for controller"),A={username:P.username,accessKey:P.access_key};else{let $e=await I.getToken();if(!$e)return n.log("EXIT_UPLOAD aborted: no auth available"),null;A=$e}let T=y??await pe();if(!T)return n.log("EXIT_UPLOAD aborted: no TMS credentials"),n.setUploadStatus("failed","Could not get TMS credentials"),null;n.log(`EXIT_UPLOAD config: testId=${n.testId} commitId=${n.sessionId} projectId=${z.project_id} sessionDir=${n.sessionDir} runDirs=${JSON.stringify(n.getRunDirs())}`);let L=P?.username??T.username,H=P?.access_key??T.access_key,re=n.getContext().prior_runs,Ee=n.getRunObjectives(),_e=[];for(let[$e]of Object.entries(n.auteurVariables))if($e.startsWith("secrets.user.")){let Ze=$e.replace("secrets.user.","");_e.push({key_name:Ze,scope:"user"})}N.current&&(n.log("SCREENSHOT_UPLOAD draining queue before pipeline"),await N.current.drain(),n.log("SCREENSHOT_UPLOAD queue drained"));let fe=await new es({controllerBaseUrl:b.controllerBaseUrl,tmsBaseUrl:b.tmsBaseUrl,auth:A,authResolver:I.getResolver()??void 0,sessionId:n.sessionId,sessionDir:n.sessionDir,testId:n.testId,commitId:n.sessionId,projectId:z.project_id,folderId:z.folder_id,firstObjective:n.firstObjective??"KaneAI Test",firstUrl:n.firstUrl??"",runDirs:n.getRunDirs(),runObjectives:Ee,startedAt:n.startedAt,endedAt:new Date().toISOString(),totalSteps:xe.current,totalDuration:he.current,runStatuses:re.map($e=>$e.status),orgId:T.org_id,userId:T.user_id,tmsUsername:L,tmsAccessKey:H,screenshotBaseUrl:n.screenshotBaseUrl,shareApiBaseUrl:b.shareApiBaseUrl,testManagerUiUrl:b.testManagerUiUrl,variables:Object.keys(n.auteurVariables).length>0?n.auteurVariables:void 0,variableIds:{},secrets:_e,codeExport:e,onProgress:($e,Ze,we)=>{n.log(`EXIT_PROGRESS step=${$e} status=${Ze}${we?` detail=${we}`:""}`),R(gt=>ts(gt,$e,Ze,we))},log:$e=>n.log($e)}).execute();return fe.success?(n.log(`EXIT_UPLOAD success: testId=${fe.testId} testcaseId=${fe.testcaseId??"none"} shareId=${fe.shareId??"none"}`),n.setUploadStatus("uploaded"),fe.testId&&n.setTestId(fe.testId),fe.testcaseId&&n.setTestcaseId(fe.testcaseId)):(n.log(`EXIT_UPLOAD failed: ${fe.error}`),n.setUploadStatus("failed",fe.error)),fe},[I,k,n,z,y,pe]),Rt=(0,M.useCallback)(()=>{n.finish("complete"),dn(),je.killChrome(),setTimeout(()=>r(),1500)},[n,je,r]),it=(0,M.useCallback)(async b=>{if(V(!1),b&&n.testId){n.log(`EXIT feedback=${b}, submitting...`);try{let P=ae(k),A=I.getResolvedBasicAuth();A&&(await new Ot(P.tmsBaseUrl,A.username,A.access_key).submitFeedback({instruction_id:"",test_id:n.testId,feedback_type:b,mode:"human"}),n.log("EXIT feedback submitted"))}catch(P){n.log(`EXIT feedback failed: ${P}`)}}else n.log("EXIT feedback skipped");Rt()},[k,I,n,Rt]),pt=(0,M.useCallback)(()=>{if(X)return;let b=n.nextRunIndex()>0;if(n.log(`EXIT hasRuns=${b} localMode=${i}`),!b||i){n.log(`EXIT quick exit \u2014 ${b?"local mode":"no runs"}`),n.finish("complete"),dn(),je.killChrome(),r();return}n.log("EXIT starting upload pipeline..."),W(!0),mt().then(P=>{let A=ae(k),T=z.project_id;if(P?.testcaseId&&T){let L=`${A.testManagerUiUrl}/projects/${T}/test-cases/${P.testcaseId}`,H=P.shareId?`${L}/dashboard/share/${P.shareId}`:void 0,re=`${L}/dashboard?type=summary&agentView=true&fqdn=summary-page`;q({status:"success",testUrl:H,testCaseLink:re,codeExportDir:P.codeExportDir}),Zs({shareableLink:H,testCaseLink:re,codeExportDir:P.codeExportDir})}else q({status:P?.success?"success":"failed",error:P?.error});V(!0)}).catch(P=>{n.log(`EXIT_UPLOAD exception: ${P}`),n.setUploadStatus("failed",String(P)),q({status:"failed",error:String(P)}),V(!0)})},[X,n,je,r,i,mt,k,z]);(0,M.useEffect)(()=>{if(!X)return;let b=300*1e3,P=setTimeout(()=>{n.setUploadStatus("failed","Upload timed out after 5m"),n.finish("complete"),dn(),je.killChrome(),process.exit(0)},b);return()=>clearTimeout(P)},[X,n,je]);let Ve=M.default.useRef(0),ge=M.default.useRef(null),Qe=M.default.useRef(0);et((b,P)=>{if(P.ctrl&&b==="c"){if(X){Qe.current+=1,Qe.current>=2&&(n.setUploadStatus("pending","Force exit by user"),n.finish("complete"),dn(),je.killChrome(),process.exit(0));return}if(U.isRunning){U.cancelRun(),ne({type:"info",text:"Run cancelled."}),Ve.current++,ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{Ve.current=0},2e3),Ve.current>=2&&pt();return}if(Ut==="chat"){St("menu");return}pt()}});let ht=M.default.useMemo(()=>{let b=I.creds.getActiveProfile()??"none",P=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:me.headless?"on":"off",options:[{label:"off",value:"off"},{label:"on",value:"on"}],onValue:A=>{rt(T=>({...T,headless:A==="on"}))}},{id:"run-max-steps",label:"Max Steps",type:"text-input",currentValue:String(me.maxSteps),onValue:A=>{let T=parseInt(A,10);T>0&&rt(L=>({...L,maxSteps:T}))}},{id:"run-timeout",label:"Timeout (sec)",type:"text-input",currentValue:me.timeout?String(me.timeout):"",placeholder:"0 = no timeout",onValue:A=>{let T=parseInt(A,10);rt(L=>({...L,timeout:isNaN(T)?0:T}))}},{id:"run-cdp",label:"CDP Endpoint",type:"text-input",currentValue:me.cdpEndpoint,placeholder:"http://127.0.0.1:9222",onValue:A=>{rt(T=>({...T,cdpEndpoint:A}))}},{id:"run-ws",label:"WS Endpoint",type:"text-input",currentValue:me.wsEndpoint,placeholder:"wss://...",onValue:A=>{rt(T=>({...T,wsEndpoint:A}))}}]}]},{id:"auth",label:"Auth",type:"submenu",children:[{id:"login",label:"Login",type:"action",onLoginWizard:()=>{}},{id:"logout",label:"Logout",type:"action",onAction:()=>{I.logout().then(A=>{Et();let T=I.creds.getActiveProfile(),L=I.creds.getDefaultEnv();ie(T,L),se().catch(()=>{}),ne(A?{type:"info",text:`Logged out: ${A.profile} [${A.env}]`}:{type:"info",text:"No active profile"})}).catch(()=>{ne({type:"error",text:"Logout failed"})})}},{id:"whoami",label:"Who Am I",type:"action",onInfo:()=>{let A=I.creds.getActiveProfile()??"none",T=I.creds.getDefaultEnv(),L=I.creds.loadBasicAuth(A,T),H=L?"basic":I.creds.loadCredentials(A,T)?"oauth":"not configured";return{title:"Who Am I",sections:[{label:"Identity",entries:[{key:"Profile",value:A},{key:"Environment",value:T}]},{label:"Authentication",entries:[{key:"Method",value:H},...L?[{key:"Username",value:L.username}]:[]]},{label:"Token",entries:[{key:"Status",value:I.tokenValid?"valid":"not logged in",color:I.tokenValid?m.statusPass:m.statusFail}]}]}}},{id:"balance",label:"Credit Balance",type:"action",onAction:()=>{(async()=>{let A=I.creds.getActiveProfile()??"default",T=I.creds.getDefaultEnv(),L=ae(T);try{let H=I.getBasicAuth(),re=H?null:await I.getToken();if(!H&&!re){ne({type:"error",text:"Not authenticated. Run /login first."});return}let{ControllerClient:Ee}=await import("./controller-client-VI55T5AT.js"),ke=await(H?new Ee(L.controllerBaseUrl,{username:H.username,accessKey:H.access_key}):new Ee(L.controllerBaseUrl,re)).getCreditBalance();ne({type:"info",text:`Credits \u2014 available: ${ke.available_credits}, total: ${ke.total_credits} (${A} / ${T})`})}catch(H){ne({type:"error",text:`Balance check failed: ${H instanceof Error?H.message:String(H)}`})}})()}},{id:"profiles",label:"Profiles",type:"action",onProfilesView:()=>{}}]},{id:"config",label:"Config",type:"submenu",children:[{id:"config-show",label:"Show",type:"action",onInfo:()=>({title:"Show Config",sections:[{label:"General",entries:[{key:"Model",value:"v16-alpha"}]},{label:"Browser",entries:[{key:"Window",value:`${z.window_size.width}x${z.window_size.height}`},{key:"Chrome Profile",value:z.chrome_profile_path?z.chrome_profile_path.split("/").pop()??z.chrome_profile_path:"(temporary)"}]},{label:"Project",entries:[{key:"Project",value:z.project_name?`${z.project_name} (${z.project_id})`:z.project_id??"(none)"},{key:"Folder",value:z.folder_name?`${z.folder_name} (${z.folder_id})`:z.folder_id??"(none)"},{key:"Default URL",value:z.default_url??"(none)"}]}]})},{id:"config-chrome",label:"Chrome Profile",type:"action",onChromeProfilePicker:()=>{}},{id:"config-project",label:"Project",type:"action",onProjectPicker:()=>{}},{id:"config-folder",label:"Folder",type:"action",...z.project_id?{onFolderPicker:()=>{}}:{onInfo:()=>({title:"Folder",sections:[{entries:[{key:"Status",value:"Select a project first",color:m.dim}]}]})}},{id:"config-url",label:"Default URL",type:"text-input",currentValue:z.default_url??"",onValue:A=>{s.set("default_url",A)}},{id:"config-window",label:"Window Size",type:"text-input",currentValue:`${z.window_size.width}x${z.window_size.height}`,placeholder:"WIDTHxHEIGHT",onValue:A=>{let T=A.split("x").map(Number);T[0]&&T[1]&&s.set("window_size",{width:T[0],height:T[1]})}}]},{id:"help",label:"Help",type:"submenu",children:[{id:"help-paths",label:"File Paths",type:"action",onInfo:()=>({title:"File Paths",sections:[{label:"Variables",entries:[{key:"Global dir",value:`${Be(ye,"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:Be(ye,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"Config",entries:[{key:"TUI config",value:Be(ye,"tui-config.json")},{key:"Auth",value:Be(ye,"config.json")},{key:"Sessions",value:`${Be(ye,"sessions")}/`}]}]})},{id:"help-variables",label:"Variables",type:"action",onInfo:()=>({title:"Variables",sections:[{label:"Loading Order (later wins)",entries:[{key:"1. Global",value:`${Be(ye,"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:Be(ye,"global-memory.md")},{key:"Local",value:"{cwd}/.testmuai/context.md"}]},{label:"CLI Overrides",entries:[{key:"Global",value:"--global-context <file>"},{key:"Local",value:"--local-context <file>"}]}]})}]},{id:"update",label:c?`Update (${c.current} \u2192 ${c.latest})`:"Update",type:"action",onAction:()=>{g||(S(!0),ne({type:"info",text:"Checking for updates..."}),(async()=>{let{checkForUpdate:A}=await import("./version-check-YRWT2JIC.js"),T=await A();if(!T){ne({type:"info",text:`Already on latest version (${Pt})`}),S(!1);return}ne({type:"info",text:`Update available: ${T.current} \u2192 ${T.latest}. Installing...`});let{runSelfUpdate:L}=await import("./updater-KDWM6PUM.js"),H=await L();H.success?ne({type:"info",text:`\u2713 Updated to ${H.toVersion}. Restart kane-cli to use the new version.`}):ne({type:"error",text:`Update failed: ${H.error}`}),S(!1)})())}},{id:"exit",label:"Exit",type:"action",onAction:()=>{pt()}}]},[I,s,z,ne,pt,me,Et,c,g]),on=(0,M.useCallback)(b=>{if(U.askingUser){de((0,J.jsxs)(x,{children:[(0,J.jsx)(u,{color:"#888888",children:"\u2192 "}),(0,J.jsx)(u,{color:"#888888",children:"You answered: "}),(0,J.jsx)(u,{children:b})]})),U.sendAnswer(b);return}if(n.logCommand(b),U.isRunning){ne({type:"error",text:"Run in progress. Ctrl+C to cancel."});return}de((0,J.jsxs)(x,{children:[(0,J.jsx)(u,{color:"#b388ff",children:"\u276F "}),(0,J.jsx)(u,{children:b})]}));let P=p??z.default_url;ue(b,P||void 0)},[U,ne,de,n,p,z,ue]),ct="KaneAI CLI",ut=I.getAuthInfo(),Wn=ut?ut.method==="basic"?"basic auth":"oauth":"not logged in";return Jt?(0,J.jsxs)(x,{flexDirection:"column",children:[oe.length>0&&(0,J.jsx)(Gt,{items:oe,children:b=>(0,J.jsx)(x,{paddingX:1,children:b.content},b.id)}),!l&&(0,J.jsx)(ps,{onComplete:()=>{let b=I.creds.getActiveProfile(),P=I.creds.getDefaultEnv(),A=b?I.creds.loadCredentials(b,P):null,T=b?I.creds.loadBasicAuth(b,P):null,L=!!(A||T),H=T?.username??b??null;de((0,J.jsx)(An,{size:"full",helmetVisibleRows:8,textVisibleRows:7,showMeta:!0,version:Pt,authenticated:L,user:H})),d(!0),t&&t.then(re=>{re&&(h(re),ne({type:"info",text:`Update available: ${re.current} \u2192 ${re.latest} \u2014 select Update from menu or run \`kane-cli update\``}))}).catch(()=>{})}}),l&&Ut==="menu"&&!X&&(0,J.jsx)(x,{marginBottom:1,children:(0,J.jsxs)(x,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,J.jsx)(u,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,J.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,J.jsx)(u,{color:"#ff9500",children:z.model}),(0,J.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,J.jsx)(u,{color:m.dimmed,children:Wn}),(0,J.jsx)(u,{color:m.dimmed,children:" \u2502 "}),(0,J.jsxs)(u,{color:m.dimmed,children:[Vt??"no profile","/",k]})]})}),l&&!X&&(0,J.jsxs)(x,{flexDirection:"column",flexGrow:1,children:[Ut==="menu"&&(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(Ks,{items:ht,onRunSelected:()=>St("chat"),renderLoginWizard:b=>{let P=be?.phase??"wizard";if(P==="project")return(0,J.jsx)(Yn,{resolver:I.getResolver(),currentProjectId:null,env:be.env,onSelect:(A,T)=>{I.creds.saveProfileConfig(be.profile,be.env,{project_id:A,project_name:T}),ot(L=>L?{...L,phase:"folder"}:null)},onCancel:()=>{ie(be.profile,be.env),ot(null),b()}});if(P==="folder"){let A=I.creds.loadProfileConfig(be.profile,be.env);return(0,J.jsx)(Qn,{resolver:I.getResolver(),projectId:A?.project_id??"",currentFolderId:null,env:be.env,onSelect:(T,L)=>{I.creds.saveProfileConfig(be.profile,be.env,{folder_id:T,folder_name:L}),ie(be.profile,be.env),ot(null),b()},onCancel:async()=>{let T=I.creds.loadProfileConfig(be.profile,be.env);if(T?.project_id)try{let H=I.getResolver()?.cached;if(H){let re=ae(be.env),_e=await new Ot(re.tmsBaseUrl,H.username,H.access_key).getDefaultFolder(T.project_id);_e&&I.creds.saveProfileConfig(be.profile,be.env,{folder_id:_e,folder_name:"Default"})}}catch{}ie(be.profile,be.env),ot(null),b()}})}return(0,J.jsx)(Xr,{devMode:process.env.KANE_DEV_MODE==="1",profiles:I.creds.listProfiles(),onBasicLogin:(A,T,L,H)=>{I.creds.saveBasicAuth(A,T,{username:L,access_key:H}),I.creds.setActiveProfile(A),I.creds.setDefaultEnv(T),I.setTokenValid(!0),Et()},onOAuthLogin:async(A,T)=>{I.creds.setDefaultEnv(T),await I.login(A),Et()},onComplete:(A,T)=>{se(T).then(()=>{ot({phase:"project",profile:A,env:T})}).catch(()=>{ot({phase:"project",profile:A,env:T})})},onCancel:()=>{ot(null),b()}})},renderProfilesView:b=>(0,J.jsx)(Yr,{creds:I.creds,onSwitch:(P,A)=>{I.creds.setActiveProfile(P),I.creds.setDefaultEnv(A),ie(P,A),Et(),se(A).catch(()=>{}),ne({type:"info",text:`Switched to ${P} [${A}]`})},onCancel:b}),renderChromeProfilePicker:b=>(0,J.jsx)(Qr,{currentPath:z.chrome_profile_path,onSelect:P=>{s.set("chrome_profile_path",P),Ct(s.load())},onCancel:b}),renderProjectPicker:b=>(0,J.jsx)(Yn,{resolver:I.getResolver(),currentProjectId:z.project_id,env:k,onSelect:(P,A)=>{s.save({project_id:P,project_name:A});let T=I.creds.getActiveProfile(),L=I.creds.getDefaultEnv();T&&I.creds.saveProfileConfig(T,L,{project_id:P,project_name:A}),Ct(s.load()),b()},onCancel:b}),renderFolderPicker:b=>(0,J.jsx)(Qn,{resolver:I.getResolver(),projectId:z.project_id??"",currentFolderId:z.folder_id,env:k,onSelect:(P,A)=>{s.save({folder_id:P,folder_name:A});let T=I.creds.getActiveProfile(),L=I.creds.getDefaultEnv();T&&I.creds.saveProfileConfig(T,L,{folder_id:P,folder_name:A}),Ct(s.load()),b()},onCancel:b})})}),Ut==="chat"&&(0,J.jsxs)(J.Fragment,{children:[U.isRunning&&U.steps.length>0&&(0,J.jsx)(On,{steps:U.steps,bifurcated:!!U.bifurcationInfo&&!U.bifurcationInfo.isSingleFlow,flows:U.bifurcationInfo?.flows,cmInitCounts:U.cmInitCounts,onStepCommit:de},`run-${ee.current}`),(0,J.jsx)(vs,{onSubmit:on,onEscape:()=>{!U.isRunning&&!U.askingUser&&St("menu")},history:G,placeholder:U.askingUser?"Type your answer...":U.isRunning?"Run in progress... Ctrl+C to cancel":"Type an objective... (esc = menu)"})]})]}),l&&X&&E&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ns,{steps:f,status:E.status,testUrl:E.testUrl,error:E.error}),E.status==="success"&&(0,J.jsx)(rs,{shareableLink:E.testUrl,testCaseLink:E.testCaseLink,codeExportDir:E.codeExportDir,autoExit:!1})]}),O&&(0,J.jsx)(ss,{onSubmit:it}),l&&!X&&(0,J.jsx)(os,{profile:Vt,environment:k,model:z.model,tokenValid:I.tokenValid,sessionId:n.sessionId,runCount:F,viewMode:Ut})]}):(0,J.jsx)(Ns,{onComplete:()=>{Ct(s.load()),sn(!0)}})}var So=Z(yo(),1),{program:cf,createCommand:uf,createArgument:df,createOption:ff,CommanderError:mf,InvalidArgumentError:pf,InvalidOptionArgumentError:hf,Command:Co,Argument:gf,Option:nn,Help:vf}=So.default;import{join as Ye}from"path";import{readFileSync as ko,readdirSync as ka,existsSync as _n}from"fs";var Ro=Z(He(),1);import{createInterface as Ea}from"readline";function rn(i){process.stdout.write(JSON.stringify(i)+`
|
|
45
|
+
`)}async function Eo(i,e,t){let r=Un(i,e);kn().then(h=>{h&&rn({type:"update_available",current:h.current,latest:h.latest,severity:h.severity})}).catch(()=>{});let n=Ea({input:process.stdin});n.on("line",h=>{try{let g=JSON.parse(h);g.type==="user_response"?r.sendUserResponse(g.answer??""):g.type==="cancel"&&r.sendCancel(g.reason??"")}catch{}});let s=null,a=!1,o=0,l=null,d=0,c=!1;for await(let h of r.events)switch(h.type){case"run_start":c&&d++;break;case"step_start":{let g=h,S={step:g.index+1,status:"running",remark:g.objective??`Step ${g.index+1}`};g.child_id&&(S.child_id=g.child_id),rn(S);break}case"step_end":{let g=h;o++;let S={step:g.index+1,status:g.status==="passed"?"done":"failed",remark:g.summary??""};g.child_id&&(S.child_id=g.child_id),rn(S);let p=c?Math.max(0,d-1):0;t?.onStepEnd?.(g.index,p);break}case"bifurcation":{let g=h,S=g.flows??[],p=g.count??S.length;(g.is_single_flow??p<=1)||(l=S,c=!0,d=0),rn({type:"bifurcation",flows:S,count:p});break}case"ask_user":{let g=h;rn({type:"ask_user",question:g.question,step_index:g.step_index,...g.options?{options:g.options}:{}});break}case"run_end":{s=h;break}case"error":{a=!0,rn({type:"error",message:h.message});break}default:break}return n.close(),await r.exited,{lastRunEnd:s,stepsTotal:o,hadError:a,bifurcationFlows:l}}function Ao(i){let e=new Co;if(e.name("kane-cli").version(Pt),i[0]==="--help"||i[0]==="-h"||i[0]==="help"){(async()=>{let{HelpView:r}=await import("./HelpView-AZGTX7MR.js"),{render:n}=await import("./build-MFETN2BY.js"),s=await import("./react-QWOAB3TB.js"),{waitUntilExit:a}=n(s.default.createElement(r));await a(),process.exit(0)})();return}e.command("login").option("--oauth","Login via OAuth (opens browser)").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").addOption(new nn("--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 nn("--model <name>","Model").default("v16-alpha").hideHelp()).option("--chrome-profile <path>","Chrome profile path").option("--default-url <url>","Default URL").action(async r=>{let n=new Re,s=new tt,a=r.env,o=r.profile;if(!process.stdin.isTTY||r.oauth||r.username){if(n.setDefaultEnv(a),r.oauth?(await new _t(o,a,n).login(),console.log(`Logged in as ${o} [${a}] via OAuth`)):r.username&&r.accessKey?(n.saveBasicAuth(o,a,{username:r.username,access_key:r.accessKey}),console.log(`Logged in as ${o} [${a}] via basic auth`)):(console.error("Provide --oauth, or --username and --access-key"),process.exit(1)),n.setActiveProfile(o),s.set("model",r.model),r.chromeProfile&&s.set("chrome_profile_path",r.chromeProfile),r.defaultUrl&&s.set("default_url",r.defaultUrl),r.projectId)s.set("project_id",r.projectId),console.log(`Project set to ${r.projectId}`);else try{let W=n.resolveAuth();if(W){let B=ae(a),$,E;if(W.method==="basic")$=W.username,E=W.access_key;else{let C=n.getActiveCredentials(),O=n.loadClient(C.profile,C.env),N=await new ze(a).refreshToken(C.credentials.refresh_token,O.client_id),{ControllerClient:ee}=await import("./controller-client-VI55T5AT.js"),ce=await new ee(B.controllerBaseUrl,N.access_token).getTmsCredentials();$=ce.username,E=ce.access_key}let{TmsClient:q}=await import("./tms-client-QWVBCUUT.js"),y=(await new q(ae(a).tmsBaseUrl,$,E).listProjects()).find(C=>C.name.toLowerCase().includes("kaneai"));y&&(s.set("project_id",y.project_id),console.log(`Auto-selected project: ${y.name} (${y.project_id})`))}}catch(W){console.warn(`Could not auto-select project: ${W instanceof Error?W.message:W}`)}r.folderId&&(s.set("folder_id",r.folderId),console.log(`Folder set to ${r.folderId}`)),s.set("setup_complete",!0),console.log("Setup complete.");return}let{LoginWizard:l}=await import("./LoginWizard-LQKZ3AYY.js"),{ProjectPicker:d}=await import("./ProjectPicker-GFSQKLDY.js"),{FolderPicker:c}=await import("./FolderPicker-CJAJHSMM.js"),{AuthResolver:h}=await import("./resolver-XLRER3KZ.js"),{render:g}=await import("./build-MFETN2BY.js"),S=await import("./react-QWOAB3TB.js"),p=!1;if(await new Promise(W=>{let{unmount:B}=g(S.default.createElement(l,{devMode:process.env.KANE_DEV_MODE==="1",profiles:n.listProfiles(),onBasicLogin:($,E,q,f)=>{n.saveBasicAuth($,E,{username:q,access_key:f}),n.setActiveProfile($),n.setDefaultEnv(E),a=E,o=$},onOAuthLogin:async($,E)=>{n.setDefaultEnv(E),await new _t($,E,n).login(),a=E,o=$},onComplete:()=>{B(),W()},onCancel:()=>{p=!0,B(),W()}}))}),p)return;let _=ae(a),v=n.loadBasicAuth(o,a),w=v?null:n.loadCredentials(o,a),F=async()=>w?.access_token??null,K=new h(_.controllerBaseUrl,F,v);if(await K.resolve(),!K.cached){console.log("Could not resolve credentials for project setup.");return}let X=null;await new Promise(W=>{let{unmount:B}=g(S.default.createElement(d,{resolver:K,currentProjectId:s.load().project_id,env:a,onSelect:($,E)=>{s.set("project_id",$),s.set("project_name",E),X=$,console.log(`Project set to ${E} (${$})`),B(),W()},onCancel:()=>{B(),W()}}))}),X&&(await new Promise(W=>{let{unmount:B}=g(S.default.createElement(c,{resolver:K,projectId:X,currentFolderId:s.load().folder_id,env:a,onSelect:($,E)=>{s.set("folder_id",$),s.set("folder_name",E),console.log(`Folder set to ${E} (${$})`),B(),W()},onCancel:()=>{B(),W()}}))}),s.set("setup_complete",!0),process.exit(0))}),e.command("logout").action(async()=>{let r=new Re,n=r.getActiveProfile();if(!n){console.log("No active profile to logout");return}let s=r.getDefaultEnv(),a=r.loadCredentials(n,s),o=r.loadClient(n,s);if(a&&o){let d=new ze(s);try{await d.revokeToken(a.access_token,o.client_id,"access_token")}catch{}try{await d.revokeToken(a.refresh_token,o.client_id,"refresh_token")}catch{}}r.deleteProfileFull(n,s);let l=r.listProfiles();l.length>0?(r.setActiveProfile(l[0].profile),r.setDefaultEnv(l[0].env),console.log(`Logged out ${n} [${s}]. Switched to ${l[0].profile} [${l[0].env}]`)):console.log(`Logged out ${n} [${s}]. No profiles remaining.`)}),e.command("whoami").option("--profile <name>","Profile name").action(async r=>{let n=new Re,s=r.profile??n.getActiveProfile()??"default",a=n.getDefaultEnv(),o=n.loadCredentials(s,a),l=n.loadBasicAuth(s,a),d="none",c,h,g;if(l)d="basic",c=l.username;else if(o){d="oauth";let w=o.expires_at,F=Date.now()/1e3;h=w>F?"valid":"expired",g=new Date(w*1e3).toISOString().slice(0,10)}else h="missing";let{WhoamiView:S}=await import("./WhoamiView-GVVXM665.js"),{render:p}=await import("./build-MFETN2BY.js"),_=await import("./react-QWOAB3TB.js"),{waitUntilExit:v}=p(_.default.createElement(S,{profile:s,env:a,authenticated:d!=="none",authMethod:d,username:c,tokenStatus:h,expiresAt:g}));await v()}),e.command("config <action> [value]").action(async(r,n)=>{let s=new tt,a=new Re;if(r==="show"){let o=s.load(),l=a.getActiveProfile()??"default",d=a.getDefaultEnv(),c=a.loadBasicAuth(l,d),h=a.loadCredentials(l,d),g=c?`basic (${c.username})`:h?"oauth":"not configured",{ConfigView:S}=await import("./ConfigView-P4W6OHZK.js"),{render:p}=await import("./build-MFETN2BY.js"),_=await import("./react-QWOAB3TB.js"),{waitUntilExit:v}=p(_.default.createElement(S,{model:o.model,authLabel:g,profile:l,env:d,defaultUrl:o.default_url,projectId:o.project_id,projectName:o.project_name,folderId:o.folder_id,windowSize:`${o.window_size.width}x${o.window_size.height}`,chromeProfile:o.chrome_profile_path,setupComplete:o.setup_complete}));await v()}else if(r==="set-url"&&n)s.set("default_url",n),console.log(`Default URL set to ${n}`);else if(r==="set-window"&&n){let o=n.split("x").map(Number);o[0]&&o[1]&&(s.set("window_size",{width:o[0],height:o[1]}),console.log(`Window size set to ${o[0]}x${o[1]}`))}else if(r==="chrome-profile"){if(n||!process.stdin.isTTY){n||(console.error("Usage: kane-cli config chrome-profile <path>"),process.exit(1)),s.set("chrome_profile_path",n),console.log(`Chrome profile set to ${n}`);return}let{ChromeProfilePicker:o}=await import("./ChromeProfilePicker-J34PIRKT.js"),{render:l}=await import("./build-MFETN2BY.js"),d=await import("./react-QWOAB3TB.js");await new Promise(c=>{let{unmount:h}=l(d.default.createElement(o,{currentPath:s.load().chrome_profile_path,onSelect:g=>{s.set("chrome_profile_path",g),console.log(`Chrome profile set to ${g}`),h(),c()},onCancel:()=>{h(),c()}}))})}else if(r==="project"){if(n||!process.stdin.isTTY){n||(console.error("Usage: kane-cli config project <project-id>"),process.exit(1)),s.set("project_id",n),console.log(`Project set to ${n}`);return}let o=a.getDefaultEnv(),l=ae(o),d=a.loadBasicAuth(a.getActiveProfile()??"default",o);if(!d){console.log("Login first to browse projects");return}let{ProjectPicker:c}=await import("./ProjectPicker-GFSQKLDY.js"),{AuthResolver:h}=await import("./resolver-XLRER3KZ.js"),{render:g}=await import("./build-MFETN2BY.js"),S=await import("./react-QWOAB3TB.js"),p=new h(l.controllerBaseUrl,async()=>null,d);await p.resolve(),await new Promise(_=>{let{unmount:v}=g(S.default.createElement(c,{resolver:p,currentProjectId:s.load().project_id,env:o,onSelect:(w,F)=>{s.set("project_id",w),s.set("project_name",F),console.log(`Project set to ${F} (${w})`),v(),_()},onCancel:()=>{v(),_()}}))})}else if(r==="folder"){if(n||!process.stdin.isTTY){if(n||(console.error("Usage: kane-cli config folder <folder-id>"),process.exit(1)),!s.load().project_id){console.log("Select a project first: kane-cli config project <id>");return}s.set("folder_id",n),console.log(`Folder set to ${n}`);return}let o=s.load();if(!o.project_id){console.log("Select a project first: kane-cli config project");return}let l=a.getDefaultEnv(),d=ae(l),c=a.loadBasicAuth(a.getActiveProfile()??"default",l);if(!c){console.log("Login first to browse folders");return}let{FolderPicker:h}=await import("./FolderPicker-CJAJHSMM.js"),{AuthResolver:g}=await import("./resolver-XLRER3KZ.js"),{render:S}=await import("./build-MFETN2BY.js"),p=await import("./react-QWOAB3TB.js"),_=new g(d.controllerBaseUrl,async()=>null,c);await _.resolve(),await new Promise(v=>{let{unmount:w}=S(p.default.createElement(h,{resolver:_,projectId:o.project_id,currentFolderId:o.folder_id,env:l,onSelect:(F,K)=>{s.set("folder_id",F),s.set("folder_name",K),console.log(`Folder set to ${K} (${F})`),w(),v()},onCancel:()=>{w(),v()}}))})}else console.log("Usage: kane-cli config show|set-url|set-window|chrome-profile|project|folder")}),e.command("run").argument("<objective>","Test objective (use {{var}} to reference variables)").option("--url <url>","Target URL").option("--headless","Run Chrome in headless mode").option("--max-steps <n>","Maximum agent steps","30").option("--timeout <seconds>","Kill run after N seconds").option("--cdp-endpoint <url>","Connect to existing Chrome CDP endpoint").option("--ws-endpoint <url>","Connect via Playwright WebSocket (e.g. LambdaTest wss:// URL)").option("--global-context <file>",`Override global context markdown (default: ${Ye(ye,"global-memory.md")})`).option("--local-context <file>","Override local context markdown (default: .testmuai/context.md in cwd)").addOption(new nn("--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 nn("--cft","Use Playwright Chromium instead of managed Chrome").hideHelp()).option("--username <user>","Basic auth username (skip OAuth)").option("--access-key <key>","Basic auth access key (skip OAuth)").option("--env <name>","Environment (prod or stage)").option("--agent","Agent mode: plain NDJSON output, no colors/UI").option("--task-skills","Enable domain-specific task skills (experimental)").addOption(new nn("--local","Skip TMS integration (no uploads, no variables/secrets push)").hideHelp()).option("--code-export","Generate code export after upload").addHelpText("after",`
|
|
46
46
|
Variables:
|
|
47
47
|
Variables are loaded in order (later wins):
|
|
48
|
-
1. Global: ${
|
|
48
|
+
1. Global: ${Ye(ye,"variables")}/*.json
|
|
49
49
|
2. Local: {cwd}/.testmuai/variables/*.json
|
|
50
50
|
3. File: --variables-file <path>
|
|
51
51
|
4. Inline: --variables '{"key": {"value": "...", "secret": false}}'
|
|
@@ -60,17 +60,17 @@ Variables:
|
|
|
60
60
|
|
|
61
61
|
Context Files:
|
|
62
62
|
Context files provide additional instructions to the agent.
|
|
63
|
-
Global: ${
|
|
63
|
+
Global: ${Ye(ye,"global-memory.md")}
|
|
64
64
|
Local: {cwd}/.testmuai/context.md
|
|
65
65
|
|
|
66
66
|
Override with --global-context / --local-context flags.
|
|
67
|
-
`).action(async(r,n)=>{let s=new
|
|
68
|
-
`),
|
|
69
|
-
`)},ie=await Eo(
|
|
70
|
-
Timeout: ${n.timeout}s exceeded \u2014 cancelling...`),Et.current?.()},
|
|
67
|
+
`).action(async(r,n)=>{let s=new Re,o=new tt().load();!o.setup_complete&&!(n.username&&n.accessKey)&&(console.error("First-time setup required. Run: kane-cli login --oauth, or kane-cli login --username <user> --access-key <key>"),process.exit(1));let l=`${s.getActiveProfile()??"no profile"}/${s.getDefaultEnv()}`,d=[],c=n.env??s.getDefaultEnv(),h,g=!1,S=n.username,p=n.accessKey;if(n.username&&n.accessKey)g=!0,d.push(`Using basic auth (${n.username})`);else{let k=s.resolveAuth();k?.method==="basic"&&(g=!0,S=k.username,p=k.access_key,d.push(`Using basic auth from config (${k.username})`))}if(!g){let{credentials:k,profile:ie}=s.getActiveCredentials();if(k||(console.error("Not authenticated. Run: kane-cli login"),process.exit(2)),h=k.access_token,k.expires_at-Date.now()/1e3<300){let se=s.loadClient(ie,c);if(se)try{let pe=await new ze(c).refreshToken(k.refresh_token,se.client_id);h=pe.access_token,s.saveCredentials(ie,c,{access_token:h,refresh_token:pe.refresh_token,expires_at:Math.floor(Date.now()/1e3)+pe.expires_in,scope:pe.scope})}catch{console.error("Token refresh failed. Run: kane-cli login"),process.exit(2)}}}let _=async()=>h??null,v=g&&S&&p?{username:S,access_key:p}:null,w=null,F=[],K=k=>{w?w(k):F.push(k)},X=new un(ae(c).controllerBaseUrl,_,v,K),W=await X.resolve();W&&(g||(g=!0,S=W.username,p=W.access_key,d.push(`Resolved basic auth (${W.username})`)));let B=n.url??o.default_url,$=Ye(ye,"variables"),E=Ye(process.cwd(),".testmuai","variables"),q=Ln($,E,k=>console.error(k)),f=n.variablesFile?ro(n.variablesFile):{},R=n.variables?so(n.variables):{},y={...q,...f,...R},C;if(n.sessionContext)try{C=JSON.parse(n.sessionContext)}catch{console.error("Invalid --session-context JSON"),process.exit(2)}let O=n.globalContext??Ye(ye,"global-memory.md"),V=n.localContext??Ye(process.cwd(),".testmuai","context.md"),N=Qt(O),ee=Qt(V),Y,ce=null,oe=null;if(n.cft)d.push("CfT mode: Playwright will manage its own browser");else if(n.wsEndpoint)Y=n.wsEndpoint,d.push(`Playwright WS endpoint (${Y.slice(0,60)}...)`);else if(n.cdpEndpoint){try{let k=await fetch(`${n.cdpEndpoint}/json/version`);if(!k.ok)throw new Error(`CDP returned ${k.status}`)}catch{console.error(`CDP endpoint not reachable: ${n.cdpEndpoint}`),process.exit(2)}Y=n.cdpEndpoint,d.push(`CDP connected (${Y})`)}else{let k;if(o.chrome_profile_path)k=o.chrome_profile_path.replace("~",process.env.HOME??"~");else{let{mkdtempSync:ie}=await import("fs"),{tmpdir:Q}=await import("os");oe=ie(Ye(Q(),"kane-clean-")),k=oe}d.push("Starting Chrome...");try{ce=await Bn({userDataDir:k,width:o.window_size.width,height:o.window_size.height,headless:n.headless,startUrl:B})}catch(ie){console.error(`Chrome failed: ${ie instanceof Error?ie.message:ie}`),process.exit(2)}Y=ce.cdpEndpoint,d.push(`Chrome ready (${Y})`)}let Oe=Object.keys(y).length>0,{variables:de,objective:Jt,keyMap:sn}=Oe?Mn(y,r):{variables:{},objective:r,keyMap:{}},Ut=W?String(W.org_id):"",St=Object.entries(y).filter(([,k])=>k.secret);if(!n.local&&St.length>0&&g&&S&&p){let k=ae(c),ie=new Zt(k.secretsBaseUrl);for(let[Q,se]of St)ie.pushSecret({secretKey:Q,secretValue:se.value,username:S,accessKey:p,orgId:Ut}).then(()=>console.error(`Secret pushed: ${Q}`)).catch(Ce=>console.error(`Secret push failed (${Q}): ${Ce}`))}let me={},rt=Object.entries(y).filter(([,k])=>!k.secret);if(!n.local&&rt.length>0&&g&&S&&p){let k=ae(c),ie=new en(k.tmsBaseUrl,S,p);for(let[Q,se]of rt)try{let Ce=await ie.upsertVariable({name:Q,value:se.value});me[Q]=Ce.id,console.error(`Variable pushed: ${Q} (id=${Ce.id})`)}catch(Ce){console.error(`Variable push failed (${Q}): ${Ce}`)}}let G=new Yt;G.start({model:n.model??o.model,environment:c,profile:s.getActiveProfile()}),w=k=>G.log(k);for(let k of F)G.log(k);F.length=0;let I={objective:Jt,...B?{url:B}:{},model:n.model??o.model,...n.wsEndpoint?{ws_endpoint:Y}:Y?{cdp_endpoint:Y}:{},width:o.window_size.width,height:o.window_size.height,session_id:G.sessionId,run_index:0,stream:!0,...g&&S&&p?{username:S,access_key:p}:h?{auth:{type:"bearer",token:h}}:{},headless:n.headless??!1,max_steps:parseInt(n.maxSteps,10),disable_ask_user:!process.stdin.isTTY,variables:Object.keys(de).length>0?de:void 0,global_context:N??void 0,local_context:ee??void 0,enable_task_skills:n.taskSkills??!1,session_context:C},je=null;if(!n.local)try{let{ControllerClient:k}=await import("./controller-client-VI55T5AT.js"),ie;if(g&&S&&p)ie={username:S,accessKey:p};else if(h)ie=h;else throw new Error("No auth available");let se=await new k(ae(c).controllerBaseUrl,ie).getScreenshotSas();G.setScreenshotSas(se),je=new tn(se,3),G.log(`SCREENSHOT_SAS fetched OK base_url=${se.base_url} container=${se.container} expiry=${se.expiry}`)}catch(k){G.log(`SCREENSHOT_SAS failed: ${k instanceof Error?k.message:String(k)}`)}let bn=je?(k,ie)=>{try{let Q=ie,se=Ye(G.sessionDir,"runs",String(Q),"run-test");if(!_n(se)){G.log(`SCREENSHOT_UPLOAD skip step=${k} reason=runsDir_not_found path=${se}`);return}let Ce=se;if(_n(Ye(se,"screenshots")))Ce=se;else{let xe=ka(se).filter(he=>_n(Ye(se,he,"screenshots")));if(xe.length===0){G.log(`SCREENSHOT_UPLOAD skip step=${k} reason=no_screenshots_dir`);return}Ce=Ye(se,xe[0])}let pe=Ye(Ce,"screenshots",`step_${String(k).padStart(3,"0")}.png`),Je=Ye(Ce,"actions.ndjson");if(!_n(pe)){G.log(`SCREENSHOT_UPLOAD skip step=${k} reason=screenshot_not_found path=${pe}`);return}if(!_n(Je)){G.log(`SCREENSHOT_UPLOAD skip step=${k} reason=ndjson_not_found path=${Je}`);return}let ne=ko(Je,"utf-8").trim().split(`
|
|
68
|
+
`),ue=ne[ne.length-1];if(!ue){G.log(`SCREENSHOT_UPLOAD skip step=${k} reason=ndjson_empty`);return}let Ue=JSON.parse(ue);if(Ue.action_id){let xe=ko(pe);je.enqueue(Ue.action_id,xe),G.log(`SCREENSHOT_UPLOAD enqueued step=${k} action_id=${Ue.action_id} size=${xe.length}`)}else G.log(`SCREENSHOT_UPLOAD skip step=${k} reason=no_action_id`)}catch(Q){G.log(`SCREENSHOT_UPLOAD error step=${k}: ${Q instanceof Error?Q.message:String(Q)}`)}}:void 0;if(!process.stdin.isTTY&&!n.agent&&(n.agent=!0),n.agent){let k=ue=>{process.stdout.write(JSON.stringify(ue)+`
|
|
69
|
+
`)},ie=await Eo(I,{environment:c},{onStepEnd:bn}),{lastRunEnd:Q,stepsTotal:se,hadError:Ce,bifurcationFlows:pe}=ie;if(Q){let ue=Q.total_runs??1,Ue=Q.run_dir,xe,he;if(ue>1&&Ue){let{dirname:lt,join:kt}=await import("path"),mt=lt(Ue);xe=Array.from({length:ue},(Rt,it)=>kt(mt,String(it))),pe&&pe.length===ue&&(he=pe)}G.addRunResult({index:0,objective:r,summary:Q.summary,status:Q.status,context:Q.context??{memory:{},variables:{},pointer:""},run_dir:Ue,run_dirs:xe,flow_objectives:he},Q.total_runs)}if(ce&&ce.kill(),oe)try{let{rmSync:ue}=await import("fs");ue(oe,{recursive:!0,force:!0})}catch{}let Je;if(G.log(`DIRECT_UPLOAD agent_mode=true lastRunEnd=${!!Q} opts.local=${!!n.local}`),Q&&!n.local)try{let ue=ae(c),Ue=W??await X.resolve(),xe=Ue?.username||S,he=Ue?.access_key||p;G.log(`DIRECT_UPLOAD tmsUsername=${xe} tmsAccessKey=${!!he} resolvedCreds=${!!W} basicUsername=${!!S}`);let lt=xe&&he?{username:xe,accessKey:he}:h??"";if(xe&&he){let{TmsClient:kt}=await import("./tms-client-QWVBCUUT.js"),{UploadPipeline:mt}=await import("./pipeline-ZLHWF3V7.js"),Rt=new kt(ue.tmsBaseUrl,xe,he),it=o.project_id,pt=o.folder_id,Ve=n.url??o.default_url,ge=null;if(it)try{ge=await Rt.createAtmTest({objective:r.slice(0,100),creation_mode:"KANECLI",playground_disabled:!!o.chrome_profile_path,testURL:Ve??o.default_url??"",project_id:it,folder_id:pt??"",authoring_version:4})}catch{}let Qe=g&&S?S:xe,ht=g&&p?p:he;je&&await je.drain();let ct=await new mt({controllerBaseUrl:ue.controllerBaseUrl,tmsBaseUrl:ue.tmsBaseUrl,auth:lt,authResolver:X,sessionId:G.sessionId,sessionDir:G.sessionDir,testId:ge,commitId:G.sessionId,projectId:it,folderId:pt,firstObjective:Jt,firstUrl:n.url??o.default_url??"",runDirs:G.getRunDirs(),runObjectives:G.getRunObjectives(),startedAt:G.startedAt,endedAt:new Date().toISOString(),totalSteps:se,totalDuration:Q.duration??0,runStatuses:[Q.status],orgId:Ue?.org_id??0,userId:Ue?.user_id??0,tmsUsername:Qe,tmsAccessKey:ht,screenshotBaseUrl:G.screenshotBaseUrl,shareApiBaseUrl:ue.shareApiBaseUrl,variables:rt.length>0?Object.fromEntries(rt.map(([ut,Wn])=>[ut,Wn])):void 0,variableIds:me,secrets:St.map(([ut])=>({key_name:ut,scope:"user"})),codeExport:!!n.codeExport,onProgress:()=>{},log:ut=>G.log(ut)}).execute();ct.success&&(ct.testcaseId&&G.setTestcaseId(ct.testcaseId),ct.testcaseId&&ct.shareId&&it&&(Je=`${ue.testManagerUiUrl}/projects/${it}/test-cases/${ct.testcaseId}/dashboard/share/${ct.shareId}`))}}catch(ue){G.log(`DIRECT_UPLOAD agent error: ${ue instanceof Error?ue.message:String(ue)}`)}if(Q){let ue={...Q};Je&&(ue.test_url=Je),k(ue)}G.finish("complete"),Q||process.exit(Ce?2:1);let ne=Q.reason??"";(ne.includes("Cancel")||ne.includes("Timeout"))&&process.exit(3),Q.status==="passed"&&process.exit(0),process.exit(1)}let U=null,z=0,Ct=!1,zt=null,Et={current:null},{waitUntilExit:be}=yn(Ro.default.createElement(ao,{config:I,spawnOpts:{environment:c},cancelRef:Et,banner:{model:n.model??o.model,auth:l,status:d},onComplete:k=>{U=k.lastRunEnd,z=k.stepsTotal,Ct=k.hadError,zt=k.bifurcationFlows},onStepEnd:bn}),{stdout:process.stderr,exitOnCtrlC:!1}),ot;if(n.timeout){let k=parseInt(n.timeout,10)*1e3;ot=setTimeout(()=>{console.error(`
|
|
70
|
+
Timeout: ${n.timeout}s exceeded \u2014 cancelling...`),Et.current?.()},k)}if(await be(),ot&&clearTimeout(ot),U){let k=U.total_runs??1,ie=U.run_dir,Q,se;if(k>1&&ie){let{dirname:Ce,join:pe}=await import("path"),Je=Ce(ie);Q=Array.from({length:k},(ne,ue)=>pe(Je,String(ue))),zt&&zt.length===k&&(se=zt)}G.addRunResult({index:0,objective:r,summary:U.summary,status:U.status,context:U.context??{memory:{},variables:{},pointer:""},run_dir:ie,run_dirs:Q,flow_objectives:se},U.total_runs)}if(ce&&ce.kill(),oe)try{let{rmSync:k}=await import("fs");k(oe,{recursive:!0,force:!0})}catch{}if(G.log(`DIRECT_UPLOAD ink_mode=true lastEvent=${!!U} opts.local=${!!n.local}`),U&&!n.local)try{let k=ae(c),ie=W??await X.resolve(),Q=ie?.username||S,se=ie?.access_key||p,Ce=ie?.org_id??0,pe=ie?.user_id??0;G.log(`DIRECT_UPLOAD tmsUsername=${Q} tmsAccessKey=${!!se} resolvedCreds=${!!W} basicUsername=${!!S} projectId=${o.project_id}`);let Je=Q&&se?{username:Q,accessKey:se}:h??"";if(Q&&se){let{TmsClient:ne}=await import("./tms-client-QWVBCUUT.js"),{UploadPipeline:ue}=await import("./pipeline-ZLHWF3V7.js"),Ue=new ne(k.tmsBaseUrl,Q,se),xe=null,he=o.project_id,lt=o.folder_id,kt=n.url??o.default_url;if(he)try{xe=await Ue.createAtmTest({objective:r.slice(0,100),creation_mode:"KANECLI",playground_disabled:!!o.chrome_profile_path,testURL:kt??o.default_url??"",project_id:he,folder_id:lt,authoring_version:4})}catch(ge){console.error(`Test creation failed: ${ge}`)}let mt=g&&S?S:Q,Rt=g&&p?p:se;je&&(G.log("SCREENSHOT_UPLOAD draining queue before pipeline"),await je.drain(),G.log("SCREENSHOT_UPLOAD queue drained"));let it=new ue({controllerBaseUrl:k.controllerBaseUrl,tmsBaseUrl:k.tmsBaseUrl,auth:Je,authResolver:X,sessionId:G.sessionId,sessionDir:G.sessionDir,testId:xe,commitId:G.sessionId,projectId:he,folderId:lt,firstObjective:Jt,firstUrl:n.url??o.default_url??"",runDirs:G.getRunDirs(),runObjectives:G.getRunObjectives(),startedAt:new Date().toISOString(),endedAt:new Date().toISOString(),totalSteps:z,totalDuration:U.duration??0,runStatuses:[U.status],orgId:Ce,userId:pe,tmsUsername:mt,tmsAccessKey:Rt,screenshotBaseUrl:G.screenshotBaseUrl,shareApiBaseUrl:k.shareApiBaseUrl,variables:rt.length>0?Object.fromEntries(rt.map(([ge,Qe])=>[ge,Qe])):void 0,variableIds:me,secrets:St.map(([ge])=>({key_name:ge,scope:"user"})),codeExport:!!n.codeExport,onProgress:()=>{},log:ge=>G.log(ge)}),{renderUploadProgress:pt}=await import("./CliUploadProgress-OLN4CLU7.js"),Ve=await pt(it,ge=>{if(ge.testcaseId&&ge.shareId&&he)return`${k.testManagerUiUrl}/projects/${he}/test-cases/${ge.testcaseId}/dashboard/share/${ge.shareId}`});if(Ve.success){Ve.testcaseId&&G.setTestcaseId(Ve.testcaseId);let ge=Ve.testcaseId&&Ve.shareId&&he?`${k.testManagerUiUrl}/projects/${he}/test-cases/${Ve.testcaseId}/dashboard/share/${Ve.shareId}`:void 0,Qe=Ve.testcaseId&&he?`${k.testManagerUiUrl}/projects/${he}/test-cases/${Ve.testcaseId}/dashboard?type=summary&agentView=true&fqdn=summary-page`:void 0;if(ge||Qe||Ve.codeExportDir){let{LinksBox:ht}=await import("./LinksBox-P7HGFKVG.js"),{render:on}=await import("./build-MFETN2BY.js"),ct=await import("./react-QWOAB3TB.js"),{waitUntilExit:ut}=on(ct.default.createElement(ht,{shareableLink:ge,testCaseLink:Qe,codeExportDir:Ve.codeExportDir}),{stdout:process.stderr});await ut()}}if(xe){let{renderFeedbackPrompt:ge}=await import("./CliFeedbackPrompt-6BF5FIGV.js"),Qe=await ge();if(Qe)try{let{TmsClient:ht}=await import("./tms-client-QWVBCUUT.js");await new ht(k.tmsBaseUrl,mt,Rt).submitFeedback({instruction_id:"",test_id:xe,feedback_type:Qe,mode:"human"}),G.log(`FEEDBACK submitted type=${Qe}`)}catch(ht){G.log(`FEEDBACK failed: ${ht}`)}}}}catch(k){G.log(`DIRECT_UPLOAD ink error: ${k instanceof Error?k.stack??k.message:String(k)}`),console.error(`Upload failed: ${k}`)}G.finish("complete"),U||process.exit(Ct?2:1);let Vt=U.reason??"";(Vt.includes("Cancel")||Vt.includes("Timeout"))&&process.exit(3),U.status==="passed"&&process.exit(0),process.exit(1)}),e.command("profiles [action] [name]").option("--env <name>","Environment for switch/delete").action(async(r,n,s)=>{let a=new Re;if(r==="list"||!r&&!process.stdin.isTTY){let c=a.listProfiles();if(c.length===0){console.log("No profiles configured. Run: kane-cli login");return}let h=a.getActiveProfile(),g=a.getDefaultEnv();for(let S of c){let p=S.profile===h&&S.env===g?" (active)":"";console.log(`${S.profile} [${S.env}]${p}`)}return}if(r==="switch"&&n){let c=s?.env??a.getDefaultEnv();a.setActiveProfile(n),a.setDefaultEnv(c),console.log(`Switched to ${n} [${c}]`);return}if(r==="delete"&&n){let c=s?.env??a.getDefaultEnv();a.deleteProfileFull(n,c),console.log(`Deleted profile ${n} [${c}]`);return}process.stdin.isTTY||(console.error("Usage: kane-cli profiles list|switch|delete <name> [--env <env>]"),process.exit(1));let{ProfilesView:o}=await import("./ProfilesView-RXVSD4YZ.js"),{render:l}=await import("./build-MFETN2BY.js"),d=await import("./react-QWOAB3TB.js");await new Promise(c=>{let{unmount:h}=l(d.default.createElement(o,{creds:a,onSwitch:(g,S)=>{a.setActiveProfile(g),a.setDefaultEnv(S),console.log(`Switched to ${g} [${S}]`)},onCancel:()=>{h(),c()}}))})}),e.command("feedback").requiredOption("--test-id <id>","Test ID").requiredOption("--feedback-type <type>","Feedback type: positive or negative").option("--details <text>","Feedback details (max 500 characters)").option("--username <user>","Basic auth username").option("--access-key <key>","Basic auth access key").option("--env <name>","Environment (prod or stage)").action(async r=>{r.feedbackType!=="positive"&&r.feedbackType!=="negative"&&(console.error('Error: --feedback-type must be "positive" or "negative"'),process.exit(1)),r.details&&r.details.length>500&&(console.error("Error: --details must be 500 characters or fewer"),process.exit(1));let n=new Re,s=r.env??n.getDefaultEnv(),a=ae(s),o=!1,l=r.username,d=r.accessKey,c;if(r.username&&r.accessKey)o=!0;else{let w=n.resolveAuth();w?.method==="basic"&&(o=!0,l=w.username,d=w.access_key)}if(!o){let{credentials:w}=n.getActiveCredentials();w||(console.error("Not authenticated. Run: kane-cli login"),process.exit(2)),c=w.access_token}let h=async()=>c??null,g=o&&l&&d?{username:l,access_key:d}:null,p=await new un(a.controllerBaseUrl,h,g).resolve(),_=p?.username??l,v=p?.access_key??d;(!_||!v)&&(console.error(JSON.stringify({error:"Could not resolve TMS credentials"})),process.exit(1));try{let{TmsClient:w}=await import("./tms-client-QWVBCUUT.js"),K=await new w(a.tmsBaseUrl,_,v).submitFeedback({instruction_id:"",test_id:r.testId,feedback_type:r.feedbackType,details:r.details,mode:"agent"});console.log(JSON.stringify(K)),process.exit(0)}catch(w){console.error(JSON.stringify({error:w instanceof Error?w.message:String(w)})),process.exit(1)}}),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 r=>{let n=new Re,s=r.profile??n.getActiveProfile()??"default",a=r.env??n.getDefaultEnv(),o=ae(a),l=n.loadBasicAuth(s,a),d=null;if(r.username&&r.accessKey)d={username:r.username,accessKey:r.accessKey};else if(l)d={username:l.username,accessKey:l.access_key};else{let c=n.loadCredentials(s,a);c||(console.error(`No credentials for profile "${s}" [${a}]. Run "kane-cli login" first.`),process.exit(2)),d=c.access_token}try{let{ControllerClient:c}=await import("./controller-client-VI55T5AT.js"),g=await new c(o.controllerBaseUrl,d).getCreditBalance();console.log(`Available credits: ${g.available_credits}`),console.log(`Total credits: ${g.total_credits}`),process.exit(0)}catch(c){console.error(`Error: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}}),e.command("help").action(()=>{e.help()}),e.command("update").description("Update kane-cli to the latest version").action(async()=>{let{checkForUpdate:r}=await import("./version-check-YRWT2JIC.js"),{runSelfUpdate:n}=await import("./updater-KDWM6PUM.js");console.log("Checking for updates...");let s=await r();if(!s){console.log(`Already on latest version (${Pt})`);return}console.log(`Update available: ${s.current} \u2192 ${s.latest}
|
|
71
71
|
`),console.log("Updating @testmuai/kane-cli...");let a=await n(o=>{process.stdout.write(o)});a.success?(console.log(`
|
|
72
72
|
\u2713 Updated to ${a.toVersion}`),console.log("\nRun `kane-cli changelog` to see what's new.")):console.error(`
|
|
73
|
-
\u2717 Update failed: ${a.error}`)}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async r=>{let{fetchChangelog:n,formatChangelog:s}=await import("./changelog-
|
|
73
|
+
\u2717 Update failed: ${a.error}`)}),e.command("changelog").description("Show recent release notes").option("--all","Show all releases instead of latest 5").action(async r=>{let{fetchChangelog:n,formatChangelog:s}=await import("./changelog-WS4VVR5W.js"),a=await n({all:r.all});console.log(s(a))}),e.parse(["node","kane-cli",...i])}var To=kn().catch(()=>null),Hn=jt.argv.slice(2),Ra=Hn.includes("--dev"),Aa=Hn.includes("--local"),Ta=Hn.includes("--code-export"),Oo=Hn.filter(i=>i!=="--dev"),Pa=new Set(["--local","--code-export"]),Oa=Oo.some(i=>!Pa.has(i));Ra&&(jt.env.KANE_DEV_MODE="1");if(Oa)To.then(i=>{i&&jt.stderr.write(`
|
|
74
74
|
Update available: ${i.current} \u2192 ${i.latest} \u2014 run \`kane-cli update\`
|
|
75
75
|
|
|
76
|
-
`)}),Ao(
|
|
76
|
+
`)}),Ao(Oo);else{jt.on("SIGINT",()=>{jt.exit(130)}),jt.on("SIGTERM",async()=>{let{runExitCleanup:e}=await import("./exitCleanup-J3GVD6U2.js");e(),jt.exit(143)});let{waitUntilExit:i}=yn(Po.default.createElement(co,{localMode:Aa,codeExport:Ta,updatePromise:To}),{exitOnCtrlC:!1});i().then(()=>{jt.exit(0)})}
|