monkeyscode-cli 0.1.6 → 0.1.8
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/monkeyscode-cli.cjs +229 -220
- package/package.json +1 -1
package/dist/monkeyscode-cli.cjs
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
"use strict";var
|
|
4
|
-
`)}displayWidth(e){return
|
|
3
|
+
"use strict";var Ig=Object.create;var As=Object.defineProperty;var jg=Object.getOwnPropertyDescriptor;var Ng=Object.getOwnPropertyNames;var Lg=Object.getPrototypeOf,Bg=Object.prototype.hasOwnProperty;var l=(s,e)=>As(s,"name",{value:e,configurable:!0});var G=(s,e)=>()=>(s&&(e=s(s=0)),e);var ce=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ae=(s,e)=>{for(var t in e)As(s,t,{get:e[t],enumerable:!0})},gl=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ng(e))!Bg.call(s,n)&&n!==t&&As(s,n,{get:()=>e[n],enumerable:!(o=jg(e,n))||o.enumerable});return s};var b=(s,e,t)=>(t=s!=null?Ig(Lg(s)):{},gl(e||!s||!s.__esModule?As(t,"default",{value:s,enumerable:!0}):t,s)),Ps=s=>gl(As({},"__esModule",{value:!0}),s);var Ms=ce(hi=>{var Nn=class extends Error{static{l(this,"CommanderError")}constructor(e,t,o){super(o),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},gi=class extends Nn{static{l(this,"InvalidArgumentError")}constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};hi.CommanderError=Nn;hi.InvalidArgumentError=gi});var Ln=ce(bi=>{var{InvalidArgumentError:Ug}=Ms(),yi=class{static{l(this,"Argument")}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,o)=>{if(!this.argChoices.includes(t))throw new Ug(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,o):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function Wg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}l(Wg,"humanReadableArgName");bi.Argument=yi;bi.humanReadableArgName=Wg});var Di=ce(ki=>{var{humanReadableArgName:Hg}=Ln(),wi=class{static{l(this,"Help")}constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(e){this.helpWidth=this.helpWidth??e.helpWidth??80}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),o=e._getHelpCommand();return o&&!o._hidden&&t.push(o),this.sortSubcommands&&t.sort((n,r)=>n.name().localeCompare(r.name())),t}compareOptions(e,t){let o=l(n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,""),"getSortKey");return o(e).localeCompare(o(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),o=e._getHelpOption();if(o&&!o.hidden){let n=o.short&&e._findOption(o.short),r=o.long&&e._findOption(o.long);!n&&!r?t.push(o):o.long&&!r?t.push(e.createOption(o.long,o.description)):o.short&&!n&&t.push(e.createOption(o.short,o.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let o=e.parent;o;o=o.parent){let n=o.options.filter(r=>!r.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(o=>Hg(o)).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((o,n)=>Math.max(o,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(n)))),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((o,n)=>Math.max(o,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((o,n)=>Math.max(o,this.displayWidth(t.styleOptionTerm(t.optionTerm(n)))),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((o,n)=>Math.max(o,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(n)))),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let o="";for(let n=e.parent;n;n=n.parent)o=n.name()+" "+o;return o+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(o=>JSON.stringify(o)).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(o=>JSON.stringify(o)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let o=`(${t.join(", ")})`;return e.description?`${e.description} ${o}`:o}return e.description}formatHelp(e,t){let o=t.padWidth(e,t),n=t.helpWidth??80;function r(f,m){return t.formatItem(f,o,m,t)}l(r,"callFormatItem");let i=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(e))}`,""],c=t.commandDescription(e);c.length>0&&(i=i.concat([t.boxWrap(t.styleCommandDescription(c),n),""]));let u=t.visibleArguments(e).map(f=>r(t.styleArgumentTerm(t.argumentTerm(f)),t.styleArgumentDescription(t.argumentDescription(f))));u.length>0&&(i=i.concat([t.styleTitle("Arguments:"),...u,""]));let d=t.visibleOptions(e).map(f=>r(t.styleOptionTerm(t.optionTerm(f)),t.styleOptionDescription(t.optionDescription(f))));if(d.length>0&&(i=i.concat([t.styleTitle("Options:"),...d,""])),t.showGlobalOptions){let f=t.visibleGlobalOptions(e).map(m=>r(t.styleOptionTerm(t.optionTerm(m)),t.styleOptionDescription(t.optionDescription(m))));f.length>0&&(i=i.concat([t.styleTitle("Global Options:"),...f,""]))}let p=t.visibleCommands(e).map(f=>r(t.styleSubcommandTerm(t.subcommandTerm(f)),t.styleSubcommandDescription(t.subcommandDescription(f))));return p.length>0&&(i=i.concat([t.styleTitle("Commands:"),...p,""])),i.join(`
|
|
4
|
+
`)}displayWidth(e){return hl(e).length}styleTitle(e){return e}styleUsage(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(e){return this.styleDescriptionText(e)}styleOptionDescription(e){return this.styleDescriptionText(e)}styleSubcommandDescription(e){return this.styleDescriptionText(e)}styleArgumentDescription(e){return this.styleDescriptionText(e)}styleDescriptionText(e){return e}styleOptionTerm(e){return this.styleOptionText(e)}styleSubcommandTerm(e){return e.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(e){return this.styleArgumentText(e)}styleOptionText(e){return e}styleArgumentText(e){return e}styleSubcommandText(e){return e}styleCommandText(e){return e}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}preformatted(e){return/\n[^\S\r\n]/.test(e)}formatItem(e,t,o,n){let i=" ".repeat(2);if(!o)return i+e;let c=e.padEnd(t+e.length-n.displayWidth(e)),u=2,p=(this.helpWidth??80)-t-u-2,f;return p<this.minWidthToWrap||n.preformatted(o)?f=o:f=n.boxWrap(o,p).replace(/\n/g,`
|
|
5
5
|
`+" ".repeat(t+u)),i+c+" ".repeat(u)+f.replace(/\n/g,`
|
|
6
6
|
${i}`)}boxWrap(e,t){if(t<this.minWidthToWrap)return e;let o=e.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return o.forEach(i=>{let c=i.match(n);if(c===null){r.push("");return}let u=[c.shift()],d=this.displayWidth(u[0]);c.forEach(p=>{let f=this.displayWidth(p);if(d+f<=t){u.push(p),d+=f;return}r.push(u.join(""));let m=p.trimStart();u=[m],d=this.displayWidth(m)}),r.push(u.join(""))}),r.join(`
|
|
7
|
-
`)}};function
|
|
7
|
+
`)}};function hl(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}l(hl,"stripColor");ki.Help=wi;ki.stripColor=hl});var $i=ce(xi=>{var{InvalidArgumentError:Gg}=Ms(),vi=class{static{l(this,"Option")}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 o=qg(e);this.short=o.shortFlag,this.long=o.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,o)=>{if(!this.argChoices.includes(t))throw new Gg(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,o):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?yl(this.name().replace(/^no-/,"")):yl(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Si=class{static{l(this,"DualOptions")}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,o)=>{this.positiveOptions.has(o)&&this.dualOptions.add(o)})}valueFromOption(e,t){let o=t.attributeName();if(!this.dualOptions.has(o))return!0;let n=this.negativeOptions.get(o).presetArg,r=n!==void 0?n:!1;return t.negate===(r===e)}};function yl(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(yl,"camelcase");function qg(s){let e,t,o=/^-[^-]$/,n=/^--[^-]/,r=s.split(/[ |,]+/).concat("guard");if(o.test(r[0])&&(e=r.shift()),n.test(r[0])&&(t=r.shift()),!e&&o.test(r[0])&&(e=r.shift()),!e&&n.test(r[0])&&(e=t,t=r.shift()),r[0].startsWith("-")){let i=r[0],c=`option creation failed due to '${i}' in option flags '${s}'`;throw/^-[^-][^-]/.test(i)?new Error(`${c}
|
|
8
8
|
- a short flag is a single dash and a single character
|
|
9
9
|
- either use a single dash and a single character (for a short flag)
|
|
10
10
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):o.test(i)?new Error(`${c}
|
|
11
11
|
- too many short flags`):n.test(i)?new Error(`${c}
|
|
12
12
|
- too many long flags`):new Error(`${c}
|
|
13
|
-
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${s}'.`);return{shortFlag:e,longFlag:t}}l(
|
|
13
|
+
- unrecognised flag format`)}if(e===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${s}'.`);return{shortFlag:e,longFlag:t}}l(qg,"splitOptionFlags");xi.Option=vi;xi.DualOptions=Si});var wl=ce(bl=>{function Vg(s,e){if(Math.abs(s.length-e.length)>3)return Math.max(s.length,e.length);let t=[];for(let o=0;o<=s.length;o++)t[o]=[o];for(let o=0;o<=e.length;o++)t[0][o]=o;for(let o=1;o<=e.length;o++)for(let n=1;n<=s.length;n++){let r=1;s[n-1]===e[o-1]?r=0:r=1,t[n][o]=Math.min(t[n-1][o]+1,t[n][o-1]+1,t[n-1][o-1]+r),n>1&&o>1&&s[n-1]===e[o-2]&&s[n-2]===e[o-1]&&(t[n][o]=Math.min(t[n][o],t[n-2][o-2]+1))}return t[s.length][e.length]}l(Vg,"editDistance");function zg(s,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=s.startsWith("--");t&&(s=s.slice(2),e=e.map(i=>i.slice(2)));let o=[],n=3,r=.4;return e.forEach(i=>{if(i.length<=1)return;let c=Vg(s,i),u=Math.max(s.length,i.length);(u-c)/u>r&&(c<n?(n=c,o=[i]):c===n&&o.push(i))}),o.sort((i,c)=>i.localeCompare(c)),t&&(o=o.map(i=>`--${i}`)),o.length>1?`
|
|
14
14
|
(Did you mean one of ${o.join(", ")}?)`:o.length===1?`
|
|
15
|
-
(Did you mean ${o[0]}?)`:""}l(
|
|
16
|
-
- 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
|
|
17
|
-
Expecting one of '${o.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,o){this._exitCallback&&this._exitCallback(new
|
|
18
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=l(n=>[n.name()].concat(n.aliases()),"knownBy"),o=t(e).find(n=>this._findCommand(n));if(o){let n=t(this._findCommand(o)).join("|"),r=t(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),o=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(o,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(o,e.defaultValue,"default");let n=l((r,i,c)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let u=this.getOptionValue(o);r!==null&&e.parseArg?r=this._callParseArg(e,r,u,i):r!==null&&e.variadic&&(r=e._concatValue(r,u)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(o,r,c)},"handleOptionValue");return this.on("option:"+t,r=>{let i=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,i,"cli")}),e.envVar&&this.on("optionEnv:"+t,r=>{let i=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,i,"env")}),this}_optionEx(e,t,o,n,r){if(typeof t=="object"&&t instanceof
|
|
19
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,o){if(
|
|
15
|
+
(Did you mean ${o[0]}?)`:""}l(zg,"suggestSimilar");bl.suggestSimilar=zg});var Sl=ce(Ti=>{var Jg=require("node:events").EventEmitter,Ci=require("node:child_process"),Tt=require("node:path"),Bn=require("node:fs"),Z=require("node:process"),{Argument:Kg,humanReadableArgName:Yg}=Ln(),{CommanderError:_i}=Ms(),{Help:Xg,stripColor:Qg}=Di(),{Option:kl,DualOptions:Zg}=$i(),{suggestSimilar:Dl}=wl(),Ei=class s extends Jg{static{l(this,"Command")}constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,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._savedState=null,this._outputConfiguration={writeOut:l(t=>Z.stdout.write(t),"writeOut"),writeErr:l(t=>Z.stderr.write(t),"writeErr"),outputError:l((t,o)=>o(t),"outputError"),getOutHelpWidth:l(()=>Z.stdout.isTTY?Z.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>Z.stderr.isTTY?Z.stderr.columns:void 0,"getErrHelpWidth"),getOutHasColors:l(()=>Fi()??(Z.stdout.isTTY&&Z.stdout.hasColors?.()),"getOutHasColors"),getErrHasColors:l(()=>Fi()??(Z.stderr.isTTY&&Z.stderr.hasColors?.()),"getErrHasColors"),stripColor:l(t=>Qg(t),"stripColor")},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,o){let n=t,r=o;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,i,c]=e.match(/([^ ]+) *(.*)/),u=this.createCommand(i);return n&&(u.description(n),u._executableHandler=!0),r.isDefault&&(this._defaultCommandName=u._name),u._hidden=!!(r.noHelp||r.hidden),u._executableFile=r.executableFile||null,c&&u.arguments(c),this._registerCommand(u),u.parent=this,u.copyInheritedSettings(this),n?this:u}createCommand(e){return new s(e)}createHelp(){return Object.assign(new Xg,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
|
|
16
|
+
- 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 Kg(e,t)}argument(e,t,o,n){let r=this.createArgument(e,t);return typeof o=="function"?r.default(n).argParser(o):r.default(o),this.addArgument(r),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[,o,n]=e.match(/([^ ]+) *(.*)/),r=t??"display help for command",i=this.createCommand(o);return i.helpOption(!1),n&&i.arguments(n),r&&i.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=i,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 o=["preSubcommand","preAction","postAction"];if(!o.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
17
|
+
Expecting one of '${o.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,o){this._exitCallback&&this._exitCallback(new _i(e,t,o)),Z.exit(e)}action(e){let t=l(o=>{let n=this.registeredArguments.length,r=o.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)},"listener");return this._actionHandler=t,this}createOption(e,t){return new kl(e,t)}_callParseArg(e,t,o,n){try{return e.parseArg(t,o)}catch(r){if(r.code==="commander.invalidArgument"){let i=`${n} ${r.message}`;this.error(i,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let o=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 '${o}'
|
|
18
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=l(n=>[n.name()].concat(n.aliases()),"knownBy"),o=t(e).find(n=>this._findCommand(n));if(o){let n=t(this._findCommand(o)).join("|"),r=t(e).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),o=e.attributeName();if(e.negate){let r=e.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(o,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(o,e.defaultValue,"default");let n=l((r,i,c)=>{r==null&&e.presetArg!==void 0&&(r=e.presetArg);let u=this.getOptionValue(o);r!==null&&e.parseArg?r=this._callParseArg(e,r,u,i):r!==null&&e.variadic&&(r=e._concatValue(r,u)),r==null&&(e.negate?r=!1:e.isBoolean()||e.optional?r=!0:r=""),this.setOptionValueWithSource(o,r,c)},"handleOptionValue");return this.on("option:"+t,r=>{let i=`error: option '${e.flags}' argument '${r}' is invalid.`;n(r,i,"cli")}),e.envVar&&this.on("optionEnv:"+t,r=>{let i=`error: option '${e.flags}' value '${r}' from env '${e.envVar}' is invalid.`;n(r,i,"env")}),this}_optionEx(e,t,o,n,r){if(typeof t=="object"&&t instanceof kl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(t,o);if(i.makeOptionMandatory(!!e.mandatory),typeof n=="function")i.default(r).argParser(n);else if(n instanceof RegExp){let c=n;n=l((u,d)=>{let p=c.exec(u);return p?p[0]:d},"fn"),i.default(r).argParser(n)}else i.default(n);return this.addOption(i)}option(e,t,o,n){return this._optionEx({},e,t,o,n)}requiredOption(e,t,o,n){return this._optionEx({mandatory:!0},e,t,o,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,o){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=o,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(o=>{o.getOptionValueSource(e)!==void 0&&(t=o.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){Z.versions?.electron&&(t.from="electron");let n=Z.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=Z.argv),this.rawArgs=e.slice();let o;switch(t.from){case void 0:case"node":this._scriptPath=e[1],o=e.slice(2);break;case"electron":Z.defaultApp?(this._scriptPath=e[1],o=e.slice(2)):o=e.slice(1);break;case"user":o=e.slice(0);break;case"eval":o=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",o}parse(e,t){this._prepareForParse();let o=this._prepareUserArgs(e,t);return this._parseCommand([],o),this}async parseAsync(e,t){this._prepareForParse();let o=this._prepareUserArgs(e,t);return await this._parseCommand([],o),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
19
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,o){if(Bn.existsSync(e))return;let n=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${e}' does not exist
|
|
20
20
|
- if '${o}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${n}`;throw new Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(p,f){let m=
|
|
22
|
+
- ${n}`;throw new Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(p,f){let m=Tt.resolve(p,f);if(Bn.existsSync(m))return m;if(n.includes(Tt.extname(f)))return;let g=n.find(h=>Bn.existsSync(`${m}${h}`));if(g)return`${m}${g}`}l(r,"findFile"),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let p;try{p=Bn.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=Tt.resolve(Tt.dirname(p),c)}if(c){let p=r(c,i);if(!p&&!e._executableFile&&this._scriptPath){let f=Tt.basename(this._scriptPath,Tt.extname(this._scriptPath));f!==this._name&&(p=r(c,`${f}-${e._name}`))}i=p||i}o=n.includes(Tt.extname(i));let u;Z.platform!=="win32"?o?(t.unshift(i),t=vl(Z.execArgv).concat(t),u=Ci.spawn(Z.argv[0],t,{stdio:"inherit"})):u=Ci.spawn(i,t,{stdio:"inherit"}):(this._checkForMissingExecutable(i,c,e._name),t.unshift(i),t=vl(Z.execArgv).concat(t),u=Ci.spawn(Z.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{Z.on(f,()=>{u.killed===!1&&u.exitCode===null&&u.kill(f)})});let d=this._exitCallback;u.on("close",p=>{p=p??1,d?d(new _i(p,"commander.executeSubCommandAsync","(close)")):Z.exit(p)}),u.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(i,c,e._name);else if(p.code==="EACCES")throw new Error(`'${i}' not executable`);if(!d)Z.exit(1);else{let f=new _i(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,d(f)}}),this.runningCommand=u}_dispatchSubcommand(e,t,o){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(o));else return n._parseCommand(t,o)}),r}_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=l((o,n,r)=>{let i=n;if(n!==null&&o.parseArg){let c=`error: command-argument value '${n}' is invalid for argument '${o.name()}'.`;i=this._callParseArg(o,n,r,c)}return i},"myParseArg");this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((o,n)=>{let r=o.defaultValue;o.variadic?n<this.args.length?(r=this.args.slice(n),o.parseArg&&(r=r.reduce((i,c)=>e(o,c,i),o.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],o.parseArg&&(r=e(o,r,o.defaultValue))),t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let o=e,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[t]!==void 0).forEach(r=>{r._lifeCycleHooks[t].forEach(i=>{n.push({hookedCommand:r,callback:i})})}),t==="postAction"&&n.reverse(),n.forEach(r=>{o=this._chainOrCall(o,()=>r.callback(r.hookedCommand,this))}),o}_chainOrCallSubCommandHook(e,t,o){let n=e;return this._lifeCycleHooks[o]!==void 0&&this._lifeCycleHooks[o].forEach(r=>{n=this._chainOrCall(n,()=>r(this,t))}),n}_parseCommand(e,t){let o=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(o.operands),t=o.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(o.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=l(()=>{o.unknown.length>0&&this.unknownOption(o.unknown[0])},"checkForUnknownOptions"),r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(r,e,t)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,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(o=>{let n=o.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(o=>o.conflictsWith.length>0).forEach(o=>{let n=e.find(r=>o.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(o,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],o=[],n=t,r=e.slice();function i(u){return u.length>1&&u[0]==="-"}l(i,"maybeOption");let c=null;for(;r.length;){let u=r.shift();if(u==="--"){n===o&&n.push(u),n.push(...r);break}if(c&&!i(u)){this.emit(`option:${c.name()}`,u);continue}if(c=null,i(u)){let d=this._findOption(u);if(d){if(d.required){let p=r.shift();p===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,p)}else if(d.optional){let p=null;r.length>0&&!i(r[0])&&(p=r.shift()),this.emit(`option:${d.name()}`,p)}else this.emit(`option:${d.name()}`);c=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,u.slice(2)):(this.emit(`option:${d.name()}`),r.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),p=this._findOption(u.slice(0,d));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,u.slice(d+1));continue}}if(i(u)&&(n=o),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&o.length===0){if(this._findCommand(u)){t.push(u),r.length>0&&o.push(...r);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),r.length>0&&t.push(...r);break}else if(this._defaultCommandName){o.push(u),r.length>0&&o.push(...r);break}}if(this._passThroughOptions){n.push(u),r.length>0&&n.push(...r);break}n.push(u)}return{operands:t,unknown:o}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let o=0;o<t;o++){let n=this.options[o].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}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0}));let o=t||{},n=o.exitCode||1,r=o.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
26
|
-
`),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 o=this.parent?._findCommand(e);if(o){let n=[o.name()].concat(o.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(o=>
|
|
25
|
+
`),this.outputHelp({error:!0}));let o=t||{},n=o.exitCode||1,r=o.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in Z.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()}`,Z.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Zg(this.options),t=l(o=>this.getOptionValue(o)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(o)),"hasCustomOptionValue");this.options.filter(o=>o.implied!==void 0&&t(o.attributeName())&&e.valueFromOption(this.getOptionValue(o.attributeName()),o)).forEach(o=>{Object.keys(o.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,o.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 o=l(i=>{let c=i.attributeName(),u=this.getOptionValue(c),d=this.options.find(f=>f.negate&&c===f.attributeName()),p=this.options.find(f=>!f.negate&&c===f.attributeName());return d&&(d.presetArg===void 0&&u===!1||d.presetArg!==void 0&&u===d.presetArg)?d:p||i},"findBestOptionFromValue"),n=l(i=>{let c=o(i),u=c.attributeName();return this.getOptionValueSource(u)==="env"?`environment variable '${c.envVar}'`:`option '${c.flags}'`},"getErrorMessage"),r=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let i=r.createHelp().visibleOptions(r).filter(c=>c.long).map(c=>c.long);n=n.concat(i),r=r.parent}while(r&&!r._enablePositionalOptions);t=Dl(e,n)}let o=`error: unknown option '${e}'${t}`;this.error(o,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,o=t===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${o} but got ${e.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),t=Dl(e,n)}let o=`error: unknown command '${e}'${t}`;this.error(o,{code:"commander.unknownCommand"})}version(e,t,o){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",o=o||"output the version number";let n=this.createOption(t,o);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
|
+
`),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 o=this.parent?._findCommand(e);if(o){let n=[o.name()].concat(o.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(o=>Yg(o));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=Tt.basename(e,Tt.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),o=this._getOutputContext(e);t.prepareContext({error:o.error,helpWidth:o.helpWidth,outputHasColors:o.hasColors});let n=t.formatHelp(this,t);return o.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,o,n,r;return t?(o=l(c=>this._outputConfiguration.writeErr(c),"baseWrite"),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(o=l(c=>this._outputConfiguration.writeOut(c),"baseWrite"),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l(c=>(n||(c=this._outputConfiguration.stripColor(c)),o(c)),"write"),hasColors:n,helpWidth:r}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let o=this._getOutputContext(e),n={error:o.error,write:o.write,command:this};this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:o.error});if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");o.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(Z.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let o=["beforeAll","before","after","afterAll"];if(!o.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${o.join("', '")}'`);let n=`${e}Help`;return this.on(n,r=>{let i;typeof t=="function"?i=t({error:r.error,command:r.command}):i=t,i&&r.write(`${i}
|
|
28
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function vl(s){return s.map(e=>{if(!e.startsWith("--inspect"))return e;let t,o="127.0.0.1",n="9229",r;return(r=e.match(/^(--inspect(-brk)?)$/))!==null?t=r[1]:(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=r[1],/^\d+$/.test(r[3])?n=r[3]:o=r[3]):(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=r[1],o=r[3],n=r[4]),t&&n!=="0"?`${t}=${o}:${parseInt(n)+1}`:e})}l(vl,"incrementNodeInspectorPort");function Fi(){if(Z.env.NO_COLOR||Z.env.FORCE_COLOR==="0"||Z.env.FORCE_COLOR==="false")return!1;if(Z.env.FORCE_COLOR||Z.env.CLICOLOR_FORCE!==void 0)return!0}l(Fi,"useColor");Ti.Command=Ei;Ti.useColor=Fi});var _l=ce(qe=>{var{Argument:xl}=Ln(),{Command:Ri}=Sl(),{CommanderError:eh,InvalidArgumentError:$l}=Ms(),{Help:th}=Di(),{Option:Cl}=$i();qe.program=new Ri;qe.createCommand=s=>new Ri(s);qe.createOption=(s,e)=>new Cl(s,e);qe.createArgument=(s,e)=>new xl(s,e);qe.Command=Ri;qe.Option=Cl;qe.Argument=xl;qe.Help=th;qe.CommanderError=eh;qe.InvalidArgumentError=$l;qe.InvalidOptionArgumentError=$l});function nh(){let s=new Map;for(let[e,t]of Object.entries(re)){for(let[o,n]of Object.entries(t))re[o]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[o]=re[o],s.set(n[0],n[1]);Object.defineProperty(re,e,{value:t,enumerable:!1})}return Object.defineProperty(re,"codes",{value:s,enumerable:!1}),re.color.close="\x1B[39m",re.bgColor.close="\x1B[49m",re.color.ansi=Tl(),re.color.ansi256=Rl(),re.color.ansi16m=Al(),re.bgColor.ansi=Tl(10),re.bgColor.ansi256=Rl(10),re.bgColor.ansi16m=Al(10),Object.defineProperties(re,{rgbToAnsi256:{value(e,t,o){return e===t&&t===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[o]=t;o.length===3&&(o=[...o].map(r=>r+r).join(""));let n=Number.parseInt(o,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:l(e=>re.rgbToAnsi256(...re.hexToRgb(e)),"value"),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,o,n;if(e>=232)t=((e-232)*10+8)/255,o=t,n=t;else{e-=16;let c=e%36;t=Math.floor(e/36)/5,o=Math.floor(c/6)/5,n=c%6/5}let r=Math.max(t,o,n)*2;if(r===0)return 30;let i=30+(Math.round(n)<<2|Math.round(o)<<1|Math.round(t));return r===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:l((e,t,o)=>re.ansi256ToAnsi(re.rgbToAnsi256(e,t,o)),"value"),enumerable:!1},hexToAnsi:{value:l(e=>re.ansi256ToAnsi(re.hexToAnsi256(e)),"value"),enumerable:!1}}),re}var Tl,Rl,Al,re,yD,oh,sh,bD,rh,st,Pl=G(()=>{Tl=l((s=0)=>e=>`\x1B[${e+s}m`,"wrapAnsi16"),Rl=l((s=0)=>e=>`\x1B[${38+s};5;${e}m`,"wrapAnsi256"),Al=l((s=0)=>(e,t,o)=>`\x1B[${38+s};2;${e};${t};${o}m`,"wrapAnsi16m"),re={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},yD=Object.keys(re.modifier),oh=Object.keys(re.color),sh=Object.keys(re.bgColor),bD=[...oh,...sh];l(nh,"assembleStyles");rh=nh(),st=rh});function Ve(s,e=globalThis.Deno?globalThis.Deno.args:Wn.default.argv){let t=s.startsWith("-")?"":s.length===1?"-":"--",o=e.indexOf(t+s),n=e.indexOf("--");return o!==-1&&(n===-1||o<n)}function ih(){if("FORCE_COLOR"in ie)return ie.FORCE_COLOR==="true"?1:ie.FORCE_COLOR==="false"?0:ie.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ie.FORCE_COLOR,10),3)}function ah(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function ch(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let o=ih();o!==void 0&&(Un=o);let n=t?Un:o;if(n===0)return 0;if(t){if(Ve("color=16m")||Ve("color=full")||Ve("color=truecolor"))return 3;if(Ve("color=256"))return 2}if("TF_BUILD"in ie&&"AGENT_NAME"in ie)return 1;if(s&&!e&&n===void 0)return 0;let r=n||0;if(ie.TERM==="dumb")return r;if(Wn.default.platform==="win32"){let i=Ol.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ie)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in ie)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in ie)||ie.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in ie)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ie.TEAMCITY_VERSION)?1:0;if(ie.COLORTERM==="truecolor"||ie.TERM==="xterm-kitty"||ie.TERM==="xterm-ghostty"||ie.TERM==="wezterm")return 3;if("TERM_PROGRAM"in ie){let i=Number.parseInt((ie.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ie.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ie.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ie.TERM)||"COLORTERM"in ie?1:r}function Ml(s,e={}){let t=ch(s,{streamIsTTY:s&&s.isTTY,...e});return ah(t)}var Wn,Ol,Ai,ie,Un,lh,Il,jl=G(()=>{Wn=b(require("node:process"),1),Ol=b(require("node:os"),1),Ai=b(require("node:tty"),1);l(Ve,"hasFlag");({env:ie}=Wn.default);Ve("no-color")||Ve("no-colors")||Ve("color=false")||Ve("color=never")?Un=0:(Ve("color")||Ve("colors")||Ve("color=true")||Ve("color=always"))&&(Un=1);l(ih,"envForceColor");l(ah,"translateLevel");l(ch,"_supportsColor");l(Ml,"createSupportsColor");lh={stdout:Ml({isTTY:Ai.default.isatty(1)}),stderr:Ml({isTTY:Ai.default.isatty(2)})},Il=lh});function Nl(s,e,t){let o=s.indexOf(e);if(o===-1)return s;let n=e.length,r=0,i="";do i+=s.slice(r,o)+e+t,r=o+n,o=s.indexOf(e,r);while(o!==-1);return i+=s.slice(r),i}function Ll(s,e,t,o){let n=0,r="";do{let i=s[o-1]==="\r";r+=s.slice(n,i?o-1:o)+e+(i?`\r
|
|
29
29
|
`:`
|
|
30
30
|
`)+t,n=o+1,o=s.indexOf(`
|
|
31
|
-
`,n)}while(o!==-1);return r+=s.slice(n),r}var
|
|
32
|
-
`);return r!==-1&&(e=jl(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Ms.prototype,Ko);hh=Ms(),ED=Ms({level:Bl?Bl.level:0}),a=hh});var zl=ce((zD,_h)=>{_h.exports={dots:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{interval:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{interval:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{interval:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{interval:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{interval:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{interval:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{interval:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{interval:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{interval:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{interval:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{interval:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{interval:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots8Bit:{interval:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},sand:{interval:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},pipe:{interval:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{interval:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{interval:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{interval:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","\xB0","O","o","."]},noise:{interval:100,frames:["\u2593","\u2592","\u2591"]},bounce:{interval:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{interval:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{interval:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{interval:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{interval:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{interval:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{interval:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{interval:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{interval:100,frames:["\u256B","\u256A"]},toggle:{interval:250,frames:["\u22B6","\u22B7"]},toggle2:{interval:80,frames:["\u25AB","\u25AA"]},toggle3:{interval:120,frames:["\u25A1","\u25A0"]},toggle4:{interval:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{interval:100,frames:["\u25AE","\u25AF"]},toggle6:{interval:300,frames:["\u101D","\u1040"]},toggle7:{interval:80,frames:["\u29BE","\u29BF"]},toggle8:{interval:100,frames:["\u25CD","\u25CC"]},toggle9:{interval:100,frames:["\u25C9","\u25CE"]},toggle10:{interval:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{interval:50,frames:["\u29C7","\u29C6"]},toggle12:{interval:120,frames:["\u2617","\u2616"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{interval:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{interval:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{interval:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{interval:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{interval:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u2764\uFE0F "]},clock:{interval:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{interval:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{interval:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{interval:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{interval:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{interval:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{interval:120,frames:["\u2590|\\____________\u258C","\u2590_|\\___________\u258C","\u2590__|\\__________\u258C","\u2590___|\\_________\u258C","\u2590____|\\________\u258C","\u2590_____|\\_______\u258C","\u2590______|\\______\u258C","\u2590_______|\\_____\u258C","\u2590________|\\____\u258C","\u2590_________|\\___\u258C","\u2590__________|\\__\u258C","\u2590___________|\\_\u258C","\u2590____________|\\\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{interval:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{interval:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{interval:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{interval:150,frames:["-","=","\u2261"]},betaWave:{interval:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{interval:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{interval:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{interval:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{interval:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{interval:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{interval:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{interval:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{interval:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{interval:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]}}});var Vi=ce((JD,Kl)=>{"use strict";var Vn=Object.assign({},zl()),Jl=Object.keys(Vn);Object.defineProperty(Vn,"random",{get(){let s=Math.floor(Math.random()*Jl.length),e=Jl[s];return Vn[e]}});Kl.exports=Vn});var cu=ce((vv,au)=>{au.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var $o={};Re($o,{detectPlatform:()=>De,ensureDir:()=>Jn,getPlatformInfo:()=>$e,getPlatformPaths:()=>P,isLocalModel:()=>Kh,isUNCPath:()=>zh,normalizePath:()=>Vh,resolveSymlinks:()=>Jh});function De(){switch(Pt.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function P(s){switch(s??De()){case"macos":{let t=Pt.homedir(),o=se.join(t,".monkeyscode");return{config:o,data:o,pidFile:se.join(o,"daemon.pid"),socketFile:se.join(o,"daemon.sock"),credentialBackend:"macOS Keychain",logs:se.join(o,"logs")}}case"linux":{let t=Pt.homedir(),o=process.env.XDG_CONFIG_HOME||se.join(t,".config"),n=process.env.XDG_DATA_HOME||se.join(t,".local","share"),r=process.env.XDG_STATE_HOME||se.join(t,".local","state"),i=xo.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=xo.existsSync(n)?se.join(n,"monkeyscode"):se.join(t,".monkeyscode");return{config:i,data:c,pidFile:se.join(r,"monkeyscode","daemon.pid"),socketFile:se.join(r,"monkeyscode","daemon.sock"),credentialBackend:"libsecret / gnome-keyring",logs:se.join(r,"monkeyscode","logs")}}case"windows":{let t=process.env.APPDATA||se.join(Pt.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(Pt.homedir(),"AppData","Local");return{config:se.join(t,"monkeyscode"),data:se.join(o,"monkeyscode"),pidFile:se.join(o,"monkeyscode","daemon.pid"),socketFile:se.join(o,"monkeyscode","daemon.sock"),credentialBackend:"Windows Credential Manager",logs:se.join(o,"monkeyscode","logs")}}}}function $e(){let s=De();return{os:s,arch:Pt.arch(),shell:Hh(s),supportsColor:Gh(),supportsUnicode:qh(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Hh(s){return s==="windows"?process.env.PSModulePath?"powershell":process.env.SHELL?se.basename(process.env.SHELL):"cmd":process.env.SHELL?se.basename(process.env.SHELL):"sh"}function Gh(){return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:process.stdout.isTTY?process.env.WT_SESSION?!0:(process.env.TERM||"")!=="dumb":!1}function qh(s){if(s==="windows")return!!(process.env.WT_SESSION||process.env.ConEmuPID);let e=process.env.LANG||process.env.LC_ALL||"";return e.includes("UTF-8")||e.includes("utf-8")||e.includes("UTF8")}function Jn(s){xo.mkdirSync(s,{recursive:!0})}function Vh(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function zh(s){return s.startsWith("\\\\")||s.startsWith("//")}function Jh(s){try{return xo.realpathSync(s)}catch{return s}}function Kh(s,e){if(s.startsWith("local:")||s.startsWith("ollama:"))return!0;if(e)try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}return!1}var Pt,se,xo,Q=G(()=>{"use strict";Pt=y(require("node:os"),1),se=y(require("node:path"),1),xo=y(require("node:fs"),1);l(De,"detectPlatform");l(P,"getPlatformPaths");l($e,"getPlatformInfo");l(Hh,"detectShell");l(Gh,"detectColorSupport");l(qh,"detectUnicodeSupport");l(Jn,"ensureDir");l(Vh,"normalizePath");l(zh,"isUNCPath");l(Jh,"resolveSymlinks");l(Kh,"isLocalModel")});function ty(){if(process.env.NERD_FONT==="1"||process.env.MC_ICONS==="nerd")return!0;if(process.env.NERD_FONT==="0"||process.env.MC_ICONS==="unicode"||process.env.MC_ICONS==="ascii")return!1;let s=(process.env.TERM_PROGRAM||"").toLowerCase();return!!(["wezterm","kitty","alacritty","ghostty","rio","hyper"].some(t=>s.includes(t))||process.env.WT_SESSION||s==="vscode")}function O(){let s=$e(),e=process.env.NO_COLOR!==void 0,t=process.env.FORCE_COLOR!==void 0,o=!!process.stdout.isTTY,n=!!process.stdin.isTTY,r=o&&!e,i=r,c=!1,u=!1;if(t&&(r=!0,i=!0),r){let p=process.env.TERM||"",f=process.env.COLORTERM||"";(p.includes("256color")||p==="xterm-kitty"||f)&&(c=!0),(f==="truecolor"||f==="24bit")&&(u=!0),process.env.WT_SESSION&&(c=!0,u=!0)}let d=ty();return{ansi:r,color16:i,color256:c,trueColor:u,unicode:s.supportsUnicode,nerdFont:d,emoji:s.supportsUnicode&&s.os!=="windows",columns:process.stdout.columns||80,rows:process.stdout.rows||24,interactive:n,stdoutTTY:o}}function W(s){let e=s??O();return e.nerdFont?Yh:e.unicode?Xh:Qh}function Me(s){return(s??O()).unicode?Zh:ey}var Yh,Xh,Qh,Zh,ey,Ce=G(()=>{"use strict";Q();Yh={file:"\uF0F6",folder:"\uF07B",tool:"\uF0AD",search:"\uF002",git:"\uE725",browser:"\uF0AC",mcp:"\uF1E6",web:"\uF0AC",success:"\uF058",error:"\uF057",warning:"\uF071",info:"\uF05A",spinner:"\u28FB",arrow:"\uF061",bullet:"\u25CF",checkmark:"\uF00C",cross:"\uF00D",lock:"\uF023",unlock:"\uF09C",message:"\uF075",rocket:"\uF135",thinking:"\uF0EB",terminal:"\uF120",edit:"\uF044",delete:"\uF1F8",add:"\uF055",cost:"\uF155",model:"\uF544",branch:"\uE725",hook:"\uF0C1",skill:"\uF0EB",sandbox:"\uF132",prompt:"\uF054"},Xh={file:"\u25C7",folder:"\u25C6",tool:"\u2699",search:"\u25CE",git:"\u2325",browser:"\u25C9",mcp:"\u2299",web:"\u25C9",success:"\u2713",error:"\u2717",warning:"\u25B2",info:"\u25CF",spinner:"\u280B",arrow:"\u2192",bullet:"\u2022",checkmark:"\u2713",cross:"\u2717",lock:"\u25C6",unlock:"\u25C7",message:"\u25B8",rocket:"\u27EB",thinking:"\u25CC",terminal:"\u25B6",edit:"\u270E",delete:"\u2715",add:"+",cost:"$",model:"\u25C8",branch:"\u2442",hook:"\u27F3",skill:"\u2605",sandbox:"\u25C6",prompt:"\u276F"},Qh={file:"[F]",folder:"[D]",tool:"[T]",search:"[S]",git:"[G]",browser:"[W]",mcp:"[M]",web:"[W]",success:"[OK]",error:"[ERR]",warning:"[!]",info:"[i]",spinner:"|",arrow:"->",bullet:"*",checkmark:"+",cross:"x",lock:"[LOCKED]",unlock:"[OPEN]",message:"[MSG]",rocket:"[>>]",thinking:"[...]",terminal:"[$]",edit:"[E]",delete:"[-]",add:"[+]",cost:"[$]",model:"[M]",branch:"[B]",hook:"[H]",skill:"[S]",sandbox:"[S]",prompt:">"},Zh={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},ey={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(ty,"detectNerdFont");l(O,"detectCapabilities");l(W,"getIcons");l(Me,"getBoxChars")});function Qn(){if(yt)return yt;let s=process.platform;return s==="darwin"&&Su("security")?(yt=new ca,yt):s==="linux"&&Su("secret-tool")?(yt=new la,yt):s==="win32"?(yt=new ua,yt):(yt=new da,yt)}function Su(s){try{return(0,rt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function xu(s){return s.replace(/[\\"$`!]/g,"\\$&")}function Dy(){try{if(process.platform==="linux")return pe.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,rt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${Xo.hostname()}-${Xo.userInfo().username}-${Xo.homedir()}`}var pe,to,Xo,Mt,rt,eo,ca,la,ua,da,yt,$u=G(()=>{"use strict";pe=y(require("node:fs"),1),to=y(require("node:path"),1),Xo=y(require("node:os"),1),Mt=y(require("node:crypto"),1),rt=require("node:child_process");Q();eo="monkeyscode-cli",ca=class{static{l(this,"KeychainStore")}get(e){try{return(0,rt.execSync)(`security find-generic-password -s "${eo}" -a "${e}" -w 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){this.delete(e);try{(0,rt.execSync)(`security add-generic-password -s "${eo}" -a "${e}" -w "${xu(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,rt.execSync)(`security delete-generic-password -s "${eo}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},la=class{static{l(this,"SecretToolStore")}get(e){try{return(0,rt.execSync)(`secret-tool lookup service "${eo}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,rt.execSync)(`echo -n "${xu(t)}" | secret-tool store --label="${eo}:${e}" service "${eo}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,rt.execSync)(`secret-tool clear service "${eo}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ua=class{static{l(this,"WinCredStore")}get(e){try{let t=`${eo}:${e}`,o=`
|
|
31
|
+
`,n)}while(o!==-1);return r+=s.slice(n),r}var Bl=G(()=>{l(Nl,"stringReplaceAll");l(Ll,"stringEncaseCRLFWithFirstIndex")});function Is(s){return dh(s)}var Ul,Wl,Pi,Ko,Os,Hl,Yo,uh,dh,Mi,ph,mh,Oi,Hn,fh,gh,ED,a,W=G(()=>{Pl();jl();Bl();({stdout:Ul,stderr:Wl}=Il),Pi=Symbol("GENERATOR"),Ko=Symbol("STYLER"),Os=Symbol("IS_EMPTY"),Hl=["ansi","ansi","ansi256","ansi16m"],Yo=Object.create(null),uh=l((s,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");let t=Ul?Ul.level:0;s.level=e.level===void 0?t:e.level},"applyOptions"),dh=l(s=>{let e=l((...t)=>t.join(" "),"chalk");return uh(e,s),Object.setPrototypeOf(e,Is.prototype),e},"chalkFactory");l(Is,"createChalk");Object.setPrototypeOf(Is.prototype,Function.prototype);for(let[s,e]of Object.entries(st))Yo[s]={get(){let t=Hn(this,Oi(e.open,e.close,this[Ko]),this[Os]);return Object.defineProperty(this,s,{value:t}),t}};Yo.visible={get(){let s=Hn(this,this[Ko],!0);return Object.defineProperty(this,"visible",{value:s}),s}};Mi=l((s,e,t,...o)=>s==="rgb"?e==="ansi16m"?st[t].ansi16m(...o):e==="ansi256"?st[t].ansi256(st.rgbToAnsi256(...o)):st[t].ansi(st.rgbToAnsi(...o)):s==="hex"?Mi("rgb",e,t,...st.hexToRgb(...o)):st[t][s](...o),"getModelAnsi"),ph=["rgb","hex","ansi256"];for(let s of ph){Yo[s]={get(){let{level:t}=this;return function(...o){let n=Oi(Mi(s,Hl[t],"color",...o),st.color.close,this[Ko]);return Hn(this,n,this[Os])}}};let e="bg"+s[0].toUpperCase()+s.slice(1);Yo[e]={get(){let{level:t}=this;return function(...o){let n=Oi(Mi(s,Hl[t],"bgColor",...o),st.bgColor.close,this[Ko]);return Hn(this,n,this[Os])}}}}mh=Object.defineProperties(()=>{},{...Yo,level:{enumerable:!0,get(){return this[Pi].level},set(s){this[Pi].level=s}}}),Oi=l((s,e,t)=>{let o,n;return t===void 0?(o=s,n=e):(o=t.openAll+s,n=e+t.closeAll),{open:s,close:e,openAll:o,closeAll:n,parent:t}},"createStyler"),Hn=l((s,e,t)=>{let o=l((...n)=>fh(o,n.length===1?""+n[0]:n.join(" ")),"builder");return Object.setPrototypeOf(o,mh),o[Pi]=s,o[Ko]=e,o[Os]=t,o},"createBuilder"),fh=l((s,e)=>{if(s.level<=0||!e)return s[Os]?"":e;let t=s[Ko];if(t===void 0)return e;let{openAll:o,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Nl(e,t.close,t.open),t=t.parent;let r=e.indexOf(`
|
|
32
|
+
`);return r!==-1&&(e=Ll(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Is.prototype,Yo);gh=Is(),ED=Is({level:Wl?Wl.level:0}),a=gh});var Kl=ce((zD,Ch)=>{Ch.exports={dots:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{interval:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{interval:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{interval:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{interval:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{interval:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{interval:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{interval:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{interval:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{interval:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{interval:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{interval:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{interval:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots8Bit:{interval:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},sand:{interval:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},pipe:{interval:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{interval:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{interval:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{interval:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","\xB0","O","o","."]},noise:{interval:100,frames:["\u2593","\u2592","\u2591"]},bounce:{interval:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{interval:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{interval:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{interval:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{interval:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{interval:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{interval:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{interval:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{interval:100,frames:["\u256B","\u256A"]},toggle:{interval:250,frames:["\u22B6","\u22B7"]},toggle2:{interval:80,frames:["\u25AB","\u25AA"]},toggle3:{interval:120,frames:["\u25A1","\u25A0"]},toggle4:{interval:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{interval:100,frames:["\u25AE","\u25AF"]},toggle6:{interval:300,frames:["\u101D","\u1040"]},toggle7:{interval:80,frames:["\u29BE","\u29BF"]},toggle8:{interval:100,frames:["\u25CD","\u25CC"]},toggle9:{interval:100,frames:["\u25C9","\u25CE"]},toggle10:{interval:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{interval:50,frames:["\u29C7","\u29C6"]},toggle12:{interval:120,frames:["\u2617","\u2616"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{interval:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{interval:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{interval:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{interval:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{interval:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u2764\uFE0F "]},clock:{interval:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{interval:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{interval:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{interval:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{interval:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{interval:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{interval:120,frames:["\u2590|\\____________\u258C","\u2590_|\\___________\u258C","\u2590__|\\__________\u258C","\u2590___|\\_________\u258C","\u2590____|\\________\u258C","\u2590_____|\\_______\u258C","\u2590______|\\______\u258C","\u2590_______|\\_____\u258C","\u2590________|\\____\u258C","\u2590_________|\\___\u258C","\u2590__________|\\__\u258C","\u2590___________|\\_\u258C","\u2590____________|\\\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{interval:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{interval:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{interval:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{interval:150,frames:["-","=","\u2261"]},betaWave:{interval:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{interval:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{interval:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{interval:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{interval:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{interval:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{interval:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{interval:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{interval:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{interval:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]}}});var qi=ce((JD,Xl)=>{"use strict";var Jn=Object.assign({},Kl()),Yl=Object.keys(Jn);Object.defineProperty(Jn,"random",{get(){let s=Math.floor(Math.random()*Yl.length),e=Yl[s];return Jn[e]}});Xl.exports=Jn});var uu=ce((vv,lu)=>{lu.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var $o={};Ae($o,{detectPlatform:()=>ve,ensureDir:()=>Yn,getPlatformInfo:()=>Ce,getPlatformPaths:()=>A,isLocalModel:()=>Jh,isUNCPath:()=>Vh,normalizePath:()=>qh,resolveSymlinks:()=>zh});function ve(){switch(At.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function A(s){switch(s??ve()){case"macos":{let t=At.homedir(),o=se.join(t,".monkeyscode");return{config:o,data:o,pidFile:se.join(o,"daemon.pid"),socketFile:se.join(o,"daemon.sock"),credentialBackend:"macOS Keychain",logs:se.join(o,"logs")}}case"linux":{let t=At.homedir(),o=process.env.XDG_CONFIG_HOME||se.join(t,".config"),n=process.env.XDG_DATA_HOME||se.join(t,".local","share"),r=process.env.XDG_STATE_HOME||se.join(t,".local","state"),i=xo.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=xo.existsSync(n)?se.join(n,"monkeyscode"):se.join(t,".monkeyscode");return{config:i,data:c,pidFile:se.join(r,"monkeyscode","daemon.pid"),socketFile:se.join(r,"monkeyscode","daemon.sock"),credentialBackend:"libsecret / gnome-keyring",logs:se.join(r,"monkeyscode","logs")}}case"windows":{let t=process.env.APPDATA||se.join(At.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(At.homedir(),"AppData","Local");return{config:se.join(t,"monkeyscode"),data:se.join(o,"monkeyscode"),pidFile:se.join(o,"monkeyscode","daemon.pid"),socketFile:se.join(o,"monkeyscode","daemon.sock"),credentialBackend:"Windows Credential Manager",logs:se.join(o,"monkeyscode","logs")}}}}function Ce(){let s=ve();return{os:s,arch:At.arch(),shell:Wh(s),supportsColor:Hh(),supportsUnicode:Gh(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Wh(s){return s==="windows"?process.env.PSModulePath?"powershell":process.env.SHELL?se.basename(process.env.SHELL):"cmd":process.env.SHELL?se.basename(process.env.SHELL):"sh"}function Hh(){return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:process.stdout.isTTY?process.env.WT_SESSION?!0:(process.env.TERM||"")!=="dumb":!1}function Gh(s){if(s==="windows")return!!(process.env.WT_SESSION||process.env.ConEmuPID);let e=process.env.LANG||process.env.LC_ALL||"";return e.includes("UTF-8")||e.includes("utf-8")||e.includes("UTF8")}function Yn(s){xo.mkdirSync(s,{recursive:!0})}function qh(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function Vh(s){return s.startsWith("\\\\")||s.startsWith("//")}function zh(s){try{return xo.realpathSync(s)}catch{return s}}function Jh(s,e){if(s.startsWith("local:")||s.startsWith("ollama:"))return!0;if(e)try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}return!1}var At,se,xo,X=G(()=>{"use strict";At=b(require("node:os"),1),se=b(require("node:path"),1),xo=b(require("node:fs"),1);l(ve,"detectPlatform");l(A,"getPlatformPaths");l(Ce,"getPlatformInfo");l(Wh,"detectShell");l(Hh,"detectColorSupport");l(Gh,"detectUnicodeSupport");l(Yn,"ensureDir");l(qh,"normalizePath");l(Vh,"isUNCPath");l(zh,"resolveSymlinks");l(Jh,"isLocalModel")});function ey(){if(process.env.NERD_FONT==="1"||process.env.MC_ICONS==="nerd")return!0;if(process.env.NERD_FONT==="0"||process.env.MC_ICONS==="unicode"||process.env.MC_ICONS==="ascii")return!1;let s=(process.env.TERM_PROGRAM||"").toLowerCase();return!!(["wezterm","kitty","alacritty","ghostty","rio","hyper"].some(t=>s.includes(t))||process.env.WT_SESSION||s==="vscode")}function I(){let s=Ce(),e=process.env.NO_COLOR!==void 0,t=process.env.FORCE_COLOR!==void 0,o=!!process.stdout.isTTY,n=!!process.stdin.isTTY,r=o&&!e,i=r,c=!1,u=!1;if(t&&(r=!0,i=!0),r){let p=process.env.TERM||"",f=process.env.COLORTERM||"";(p.includes("256color")||p==="xterm-kitty"||f)&&(c=!0),(f==="truecolor"||f==="24bit")&&(u=!0),process.env.WT_SESSION&&(c=!0,u=!0)}let d=ey();return{ansi:r,color16:i,color256:c,trueColor:u,unicode:s.supportsUnicode,nerdFont:d,emoji:s.supportsUnicode&&s.os!=="windows",columns:process.stdout.columns||80,rows:process.stdout.rows||24,interactive:n,stdoutTTY:o}}function H(s){let e=s??I();return e.nerdFont?Kh:e.unicode?Yh:Xh}function Oe(s){return(s??I()).unicode?Qh:Zh}var Kh,Yh,Xh,Qh,Zh,_e=G(()=>{"use strict";X();Kh={file:"\uF0F6",folder:"\uF07B",tool:"\uF0AD",search:"\uF002",git:"\uE725",browser:"\uF0AC",mcp:"\uF1E6",web:"\uF0AC",success:"\uF058",error:"\uF057",warning:"\uF071",info:"\uF05A",spinner:"\u28FB",arrow:"\uF061",bullet:"\u25CF",checkmark:"\uF00C",cross:"\uF00D",lock:"\uF023",unlock:"\uF09C",message:"\uF075",rocket:"\uF135",thinking:"\uF0EB",terminal:"\uF120",edit:"\uF044",delete:"\uF1F8",add:"\uF055",cost:"\uF155",model:"\uF544",branch:"\uE725",hook:"\uF0C1",skill:"\uF0EB",sandbox:"\uF132",prompt:"\uF054"},Yh={file:"\u25C7",folder:"\u25C6",tool:"\u2699",search:"\u25CE",git:"\u2325",browser:"\u25C9",mcp:"\u2299",web:"\u25C9",success:"\u2713",error:"\u2717",warning:"\u25B2",info:"\u25CF",spinner:"\u280B",arrow:"\u2192",bullet:"\u2022",checkmark:"\u2713",cross:"\u2717",lock:"\u25C6",unlock:"\u25C7",message:"\u25B8",rocket:"\u27EB",thinking:"\u25CC",terminal:"\u25B6",edit:"\u270E",delete:"\u2715",add:"+",cost:"$",model:"\u25C8",branch:"\u2442",hook:"\u27F3",skill:"\u2605",sandbox:"\u25C6",prompt:"\u276F"},Xh={file:"[F]",folder:"[D]",tool:"[T]",search:"[S]",git:"[G]",browser:"[W]",mcp:"[M]",web:"[W]",success:"[OK]",error:"[ERR]",warning:"[!]",info:"[i]",spinner:"|",arrow:"->",bullet:"*",checkmark:"+",cross:"x",lock:"[LOCKED]",unlock:"[OPEN]",message:"[MSG]",rocket:"[>>]",thinking:"[...]",terminal:"[$]",edit:"[E]",delete:"[-]",add:"[+]",cost:"[$]",model:"[M]",branch:"[B]",hook:"[H]",skill:"[S]",sandbox:"[S]",prompt:">"},Qh={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Zh={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(ey,"detectNerdFont");l(I,"detectCapabilities");l(H,"getIcons");l(Oe,"getBoxChars")});function Hs(){if(yt)return yt;let s=process.platform;return s==="darwin"&&$u("security")?(yt=new aa,yt):s==="linux"&&$u("secret-tool")?(yt=new ca,yt):s==="win32"?(yt=new la,yt):(yt=new ua,yt)}function $u(s){try{return(0,rt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function Cu(s){return s.replace(/[\\"$`!]/g,"\\$&")}function ky(){try{if(process.platform==="linux")return me.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,rt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${Qo.hostname()}-${Qo.userInfo().username}-${Qo.homedir()}`}var me,oo,Qo,Pt,rt,to,aa,ca,la,ua,yt,_u=G(()=>{"use strict";me=b(require("node:fs"),1),oo=b(require("node:path"),1),Qo=b(require("node:os"),1),Pt=b(require("node:crypto"),1),rt=require("node:child_process");X();to="monkeyscode-cli",aa=class{static{l(this,"KeychainStore")}get(e){try{return(0,rt.execSync)(`security find-generic-password -s "${to}" -a "${e}" -w 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){this.delete(e);try{(0,rt.execSync)(`security add-generic-password -s "${to}" -a "${e}" -w "${Cu(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,rt.execSync)(`security delete-generic-password -s "${to}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ca=class{static{l(this,"SecretToolStore")}get(e){try{return(0,rt.execSync)(`secret-tool lookup service "${to}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,rt.execSync)(`echo -n "${Cu(t)}" | secret-tool store --label="${to}:${e}" service "${to}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,rt.execSync)(`secret-tool clear service "${to}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},la=class{static{l(this,"WinCredStore")}get(e){try{let t=`${to}:${e}`,o=`
|
|
33
33
|
$cred = cmdkey /list:${t} 2>$null;
|
|
34
34
|
if ($LASTEXITCODE -eq 0) {
|
|
35
35
|
# cmdkey can't read passwords. Use CredRead via .NET
|
|
@@ -38,27 +38,33 @@ Expecting one of '${o.join("', '")}'`);let n=`${e}Help`;return this.on(n,r=>{let
|
|
|
38
38
|
$result = [AdvApi32]::CredRead("${t}", 1, 0, [ref]$credPtr);
|
|
39
39
|
# Fallback: read from encrypted file
|
|
40
40
|
}
|
|
41
|
-
`;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{
|
|
42
|
-
${p}`)}let n=await o.json(),r=n.user_code||"\u2014",i=n.verification_uri;console.log(t?` ${e.info} Open this URL in your browser:`:" Open this URL in your browser:"),console.log(""),console.log(t?` ${a.underline.cyan(i)}`:` ${i}`),console.log("")
|
|
43
|
-
`);try{let t=await fetch(`${
|
|
44
|
-
`:case"":o.isTTY&&o.setRawMode(!1),o.removeListener("data",r),o.pause(),t(n);break;case"":o.isTTY&&o.setRawMode(!1),process.exit(1);break;case"\x7F":n.length>0&&(n=n.slice(0,-1),process.stdout.write("\b \b"));break;default:n+=c,process.stdout.write("*");break}},"onData");o.on("data",r)})}async function wa(s){let e=
|
|
45
|
-
`);o=i.pop();for(let c of i){let u=c.trim();if(!(!u||u.startsWith(":"))&&u.startsWith("data: ")){let d=u.slice(6).trim();if(d==="[DONE]")return;try{yield JSON.parse(d)}catch{}}}}if(o.trim()){let n=o.trim();if(n.startsWith("data: ")){let r=n.slice(6).trim();if(r!=="[DONE]")try{yield JSON.parse(r)}catch{}}}}finally{e.releaseLock()}}var er,Fu=G(()=>{"use strict";l(Eu,"parseSSEStream");er=class{static{l(this,"ToolCallAccumulator")}_calls=new Map;feed(e){for(let t of e){let o=this._calls.get(t.index);t.id&&t.function?.name?this._calls.set(t.index,{id:t.id,name:t.function.name,arguments:t.function.arguments||""}):o&&t.function?.arguments&&(o.arguments+=t.function.arguments)}}flush(){let e=Array.from(this._calls.values());return this._calls.clear(),e}get hasPending(){return this._calls.size>0}}});function Ru(s=!0){return s?Tu:Tu.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var Tu,Au=G(()=>{"use strict";Tu=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files longer than 2000 lines are truncated (head + tail) by default \u2014 use start_line/end_line to read a specific range, or full:true to read everything. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(Ru,"getToolSchemas")});var ve={};Re(ve,{getSetting:()=>$y,loadSettings:()=>J,saveSettings:()=>xy});function J(){let s=P(),e=Da.join(s.config,"settings.json");try{if(oo.existsSync(e)){let t=JSON.parse(oo.readFileSync(e,"utf8"));return{...Pu,...t}}}catch{}return{...Pu}}function xy(s){let e=P();oo.mkdirSync(e.config,{recursive:!0});let t=Da.join(e.config,"settings.json"),n={...J(),...s};oo.writeFileSync(t,JSON.stringify(n,null,2))}function $y(s){return J()[s]}var oo,Da,Pu,Z=G(()=>{"use strict";oo=y(require("node:fs"),1),Da=y(require("node:path"),1);Q();Pu={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(J,"loadSettings");l(xy,"saveSettings");l($y,"getSetting")});var L,le,Ue,va,Cy,tr,Mu=G(()=>{"use strict";L=y(require("node:fs"),1),le=y(require("node:path"),1),Ue=require("node:child_process"),va=require("node:fs"),Cy={write_file:"create_file",list_files:"list_dir",list_directory:"list_dir",search_code:"grep_search",execute_command:"run_command",view_file:"read_file",str_replace:"replace_in_file",str_replace_editor:"replace_in_file",str_replace_based_edit_tool:"replace_in_file",bash:"run_command",bash_tool:"run_command",shell:"run_command",terminal:"run_command",text_editor:"edit_file",apply_patch:"patch_file",container_exec:"run_command",file_search:"search_files",codebase_search:"grep_search",semantic_search:"grep_search",grep:"grep_search",ripgrep:"grep_search",find_files:"search_files",glob:"search_files",glob_file_search:"search_files",ls:"list_dir",read:"read_file",cat:"read_file",write:"create_file",edit:"edit_file",multi_edit:"edit_file",search_replace:"replace_in_file",run_terminal_cmd:"run_command",run_in_terminal:"run_command",web_fetch:"read_url",fetch_webpage:"read_url",search_web:"web_search",google_search:"web_search",move_file:"rename_file",remove_file:"delete_file",task:"spawn_subagent",subagent:"spawn_subagent"},tr=class{static{l(this,"ToolExecutor")}workspace;platformUrl;token;signal;_checkpoints=new Map;_runId="";_mcpClient;_sandbox;constructor(e){this.workspace=e.workspace,this.platformUrl=e.platformUrl,this.token=e.token,this.signal=e.signal}setRunId(e){this._runId=e,this._checkpoints.clear()}setMCPClient(e){this._mcpClient=e}setSandbox(e){this._sandbox=e}async execute(e,t){let o=Cy[e]||e;switch(o){case"read_file":return this.readFile(t);case"create_file":return this.createFile(t);case"edit_file":return this.editFile(t);case"delete_file":return this.deleteFile(t);case"rename_file":return this.renameFile(t);case"list_dir":return this.listDir(t);case"grep_search":return this.grepSearch(t);case"glob_files":return this.globFiles(t);case"search_files":return this.searchFiles(t);case"replace_in_file":return this.replaceInFile(t);case"patch_file":return this.patchFile(t);case"run_command":return this.runCommand(t);case"run_tests":return this.runTests(t);case"web_search":return this.webSearch(t);case"read_url":return this.readUrl(t);case"git_status":return this.gitExec("status",t);case"git_diff":return this.gitDiff(t);case"git_log":return this.gitLog(t);case"git_commit":return this.gitCommit(t);case"git_stash":return this.gitExec("stash",t);case"git_stash_pop":return this.gitExec("stash pop",t);case"todo_write":return this.todoWrite(t);case"spawn_subagent":return this.spawnSubagent(t);case"remember":return this.remember(t);default:return o.startsWith("mcp_")&&this._mcpClient?this._executeMCPTool(o,t):{output:`Unknown tool: ${e}. Use one of: read_file, create_file, edit_file, replace_in_file, patch_file, run_command, run_tests, grep_search, search_files, list_dir, git_status, git_commit, web_search, read_url, ask_user, todo_write, spawn_subagent, remember, or mcp_<server>_<tool>`}}}getCheckpoints(){return this._checkpoints}readFile(e){let t=this.resolve(e.path);if(!L.existsSync(t))return{output:`Error: File not found: ${e.path}`};if(L.statSync(t).isDirectory())return{output:`Error: ${e.path} is a directory. Use list_dir instead.`};let r=L.readFileSync(t,"utf8").split(`
|
|
46
|
-
`),i=
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
${
|
|
50
|
-
`)}`}}
|
|
51
|
-
|
|
41
|
+
`;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{me.existsSync(t)&&me.unlinkSync(t)}catch{}}getFilePath(e){let t=A();return oo.join(t.config,`cred-${e}.enc`)}getDpapi(e){let t=this.getFilePath(e);try{if(!me.existsSync(t))return null;let o=me.readFileSync(t,"utf8");return(0,rt.execSync)(`powershell -NoProfile -Command "[System.Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect([System.Convert]::FromBase64String('${o}'), $null, 'CurrentUser'))"`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}setDpapi(e,t){let o=this.getFilePath(e);try{let n=(0,rt.execSync)(`powershell -NoProfile -Command "Add-Type -AssemblyName System.Security; [System.Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF8.GetBytes('${t.replace(/'/g,"''")}'), $null, 'CurrentUser'))"`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"});me.mkdirSync(oo.dirname(o),{recursive:!0}),me.writeFileSync(o,n.trim(),{mode:384})}catch{throw new Error("Failed to encrypt credential via DPAPI")}}},ua=class{static{l(this,"EncryptedFileStore")}keyPath;storePath;constructor(){let e=A();this.keyPath=oo.join(e.config,".cred-key"),this.storePath=oo.join(e.config,"credentials.enc")}get(e){return this.loadStore()[e]||null}set(e,t){let o=this.loadStore();o[e]=t,this.saveStore(o)}delete(e){let t=this.loadStore();delete t[e],this.saveStore(t)}getOrCreateKey(){try{if(me.existsSync(this.keyPath))return Buffer.from(me.readFileSync(this.keyPath,"utf8"),"hex")}catch{}let e=ky(),t=Pt.randomBytes(16),o=Pt.scryptSync(e,t,32),n=t.toString("hex")+":"+o.toString("hex");return me.mkdirSync(oo.dirname(this.keyPath),{recursive:!0}),me.writeFileSync(this.keyPath,n,{mode:384}),o}loadStore(){try{if(!me.existsSync(this.storePath))return{};let e=me.readFileSync(this.storePath,"utf8"),[t,o]=e.split(":"),n=this.getOrCreateKey(),r=Buffer.from(t,"hex"),i=Pt.createDecipheriv("aes-256-cbc",n,r),c=i.update(o,"hex","utf8");return c+=i.final("utf8"),JSON.parse(c)}catch{return{}}}saveStore(e){let t=this.getOrCreateKey(),o=Pt.randomBytes(16),n=Pt.createCipheriv("aes-256-cbc",t,o),r=n.update(JSON.stringify(e),"utf8","hex");r+=n.final("hex"),me.mkdirSync(oo.dirname(this.storePath),{recursive:!0}),me.writeFileSync(this.storePath,o.toString("hex")+":"+r,{mode:384})}},yt=null;l(Hs,"getCredentialStore");l($u,"hasCommand");l(Cu,"escapeShellArg");l(ky,"getMachineId")});var ge={};Ae(ge,{authLogin:()=>pa,authLoginEmail:()=>ma,authLoginSSO:()=>wa,authLogout:()=>fa,authLogoutProfile:()=>ka,authRefresh:()=>ha,authSetToken:()=>ga,authStatus:()=>er,getAccessToken:()=>Fe,isAuthenticated:()=>ba,loadAuth:()=>fe});async function pa(){let s=I(),e=H(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Device Authentication"):" Device Authentication"),console.log(t?a.dim(` API: ${Ie}`):` API: ${Ie}`),console.log("");try{let o=await fetch(`${Ie}/v1/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"monkeyscode-cli"})});if(!o.ok){let p=await o.text().catch(()=>"");throw new Error(`Auth server returned ${o.status}: ${o.statusText}
|
|
42
|
+
${p}`)}let n=await o.json(),r=n.user_code||"\u2014",i=n.verification_uri;console.log(t?` ${e.info} Open this URL in your browser:`:" Open this URL in your browser:"),console.log(""),console.log(t?` ${a.underline.cyan(i)}`:` ${i}`),console.log("");try{let{exec:p}=await import("node:child_process"),f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";p(`${f} "${i}"`),console.log(t?a.dim(" Browser opened automatically."):" Browser opened automatically.")}catch{}console.log(""),console.log(" Waiting for approval...");let c=(n.interval||5)*1e3,u=Date.now()+(n.expires_in||600)*1e3,d=0;for(;Date.now()<u;){await Dy(c);try{let f=await(await fetch(`${Ie}/v1/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_code:n.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(f.access_token){let m=await ya(f.access_token),g=Date.now()+(f.expires_in||172800)*1e3;Zo({access_token:f.access_token,refresh_token:f.refresh_token,expires_at:g,auth_method:"oauth",user:m?{id:m.id?.toString(),email:m.email,name:m.name,avatar_url:m.avatar_url??void 0}:f.user?{id:f.user.id?.toString(),email:f.user.email,name:f.user.name}:void 0,org:m?.orgs?.[0]?{id:m.orgs[0].id?.toString(),name:m.orgs[0].name,plan:m.orgs[0].plan_code}:void 0}),console.log(""),console.log(` ${e.success} Logged in successfully!`),m?console.log(` ${e.info} ${m.email} (${m.orgs?.[0]?.plan_code||"free"})`):f.user&&console.log(` ${e.info} ${f.user.email}`),console.log("");return}if(f.error==="expired_token"){console.log(""),console.log(` ${e.warning} Device code expired. Please try again.`),console.log("");return}d++,process.stdout.write(t?a.dim("."):"."),d%60===0&&console.log("")}catch{process.stdout.write(t?a.red("!"):"!")}}console.log(""),console.log(` ${e.warning} Login timed out. Please try again.`),console.log("")}catch(o){console.error(""),console.error(` ${e.error} Login failed: ${o instanceof Error?o.message:o}`),console.error("")}}async function ma(){let s=I(),e=H(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Email Login"):" Email Login"),console.log(t?a.dim(` API: ${Ie}`):` API: ${Ie}`),console.log("");let o=Eu.createInterface({input:process.stdin,output:process.stdout}),n=l(r=>new Promise(i=>o.question(r,i)),"ask");try{let r=await n(" Email: "),i=await vy(" Password: ",o);if(console.log(""),console.log(""),o.close(),!r||!i){console.log(` ${e.error} Email and password are required.`),console.log("");return}console.log(" Authenticating...");let c=await fetch(`${Ie}/v1/auth/login`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:r,password:i})});if(!c.ok){let f=await c.json().catch(()=>({message:c.statusText}));throw new Error(f.message||`HTTP ${c.status}`)}let u=await c.json();if(!u.access_token)throw new Error("No access token received");let d=await ya(u.access_token),p=Date.now()+(u.expires_in||172800)*1e3;Zo({access_token:u.access_token,refresh_token:u.refresh_token,expires_at:p,auth_method:"email",user:d?{id:d.id?.toString(),email:d.email,name:d.name,avatar_url:d.avatar_url??void 0}:u.user?{id:u.user.id?.toString(),email:u.user.email,name:u.user.name}:void 0,org:d?.orgs?.[0]?{id:d.orgs[0].id?.toString(),name:d.orgs[0].name,plan:d.orgs[0].plan_code}:void 0}),console.log(""),console.log(` ${e.success} Logged in successfully!`),d?console.log(` ${e.info} ${d.email} (${d.orgs?.[0]?.plan_code||"free"})`):u.user&&console.log(` ${e.info} ${u.user.email}`),console.log("")}catch(r){o.close(),console.error(""),console.error(` ${e.error} Login failed: ${r instanceof Error?r.message:r}`),console.error("")}}function fa(){let s=H(),e=A();try{let o=Hs(),n=`${da}-default`;o.delete(n)}catch{}let t=Mt.join(e.config,"auth.json");Ee.existsSync(t)&&Ee.unlinkSync(t),console.log(` ${s.success} Logged out.`),console.log("")}function ga(s,e){let t=H();Zo({access_token:s,auth_method:"apikey",profile:e},e),console.log(` ${t.success} Token saved${e?` (profile: ${e})`:""}.`),console.log("")}async function er(s){let e=I(),t=H(e),o=e.ansi,n=fe(s);if(console.log(""),n){let r=n.auth_method||"unknown",i={oauth:"\u{1F510} OAuth (browser)",apikey:"\u{1F511} API Key",email:"\u{1F4E7} Email/Password",sso:"\u{1F3E2} Enterprise SSO",env:"\u{1F30D} Environment Variable",unknown:"\u2753 Unknown"};if(console.log(` Auth: ${t.success} logged in`),console.log(` Method: ${i[r]||r}`),s&&s!=="default"&&console.log(` Profile: ${s}`),n.user?.email&&console.log(` User: ${n.user.email}`),n.user?.name&&console.log(` Name: ${n.user.name}`),n.org?.name&&console.log(` Org: ${n.org.name} (${n.org.plan||"free"})`),n.expires_at){let u=n.expires_at-Date.now();if(u>0){let d=Math.floor(u/36e5),p=Math.floor(d/24),f=p>0?`${p}d ${d%24}h`:`${d}h`;console.log(o?a.dim(` Expires: ${f}`):` Expires: ${f}`)}else console.log(o?a.yellow(` ${t.warning} Token expired \u2014 run: mc auth refresh`):` ${t.warning} Token expired`)}try{let u=await Fe(s);if(u){let d=await fetch(`${Ie}/v1/usage/summary`,{headers:{Authorization:`Bearer ${u}`}});if(d.ok){let p=await d.json();(p.tokensUsed||p.costUsd)&&(console.log(o?a.dim(" "+"\u2500".repeat(36)):" "+"-".repeat(36)),console.log(o?a.dim(" This month:"):" This month:"),p.sessionsCount&&console.log(` Sessions: ${p.sessionsCount}`),p.tokensUsed&&console.log(` Tokens: ${p.tokensUsed.toLocaleString()}`),p.costUsd&&console.log(` Cost: $${p.costUsd.toFixed(2)}`))}}}catch{}let c=n.access_token.length>20?`${n.access_token.slice(0,10)}...${n.access_token.slice(-6)}`:"****";console.log(o?a.dim(` Token: ${c}`):` Token: ${c}`),console.log(o?a.dim(` API: ${Ie}`):` API: ${Ie}`)}else console.log(` Auth: ${t.error} not logged in`),console.log(` Run: ${o?a.cyan("mc auth login"):"mc auth login"}`),console.log(` Or: ${o?a.cyan("mc auth login --email"):"mc auth login --email"} (email/password)`);console.log("")}async function ha(){let s=I(),e=H(s),t=fe();if(!t?.refresh_token){console.log(` ${e.error} No refresh token found. Run: mc auth login`);return}console.log(" Refreshing token...");try{let o=await fetch(`${Ie}/v1/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t.refresh_token})});if(!o.ok)throw new Error(`Refresh failed: HTTP ${o.status}`);let n=await o.json();if(!n.access_token)throw new Error("No access token in refresh response");let r=Date.now()+(n.expires_in||172800)*1e3;Zo({...t,access_token:n.access_token,refresh_token:n.refresh_token||t.refresh_token,expires_at:r}),console.log(` ${e.success} Token refreshed.`)}catch(o){console.error(` ${e.error} Refresh failed: ${o instanceof Error?o.message:o}`),console.error(" Run: mc auth login")}console.log("")}async function ya(s){try{let e=await fetch(`${Ie}/v1/auth/me`,{headers:{Authorization:`Bearer ${s}`}});if(e.ok)return await e.json()}catch{}return null}function fe(s){let e=process.env.MONKEYSCODE_API_KEY||process.env.MC_TOKEN||process.env.MONKEYSCODE_AUTH_TOKEN;if(e)return{access_token:e,auth_method:"env"};let t=s||"default",o=`${da}-${t}`;try{let c=Hs().get(o);if(c)return JSON.parse(c)}catch{}let n=A(),r=t==="default"?Mt.join(n.config,"auth.json"):Mt.join(n.config,`auth-${t}.json`);try{if(Ee.existsSync(r)){let i=JSON.parse(Ee.readFileSync(r,"utf8"));try{Hs().set(o,JSON.stringify(i)),Ee.unlinkSync(r)}catch{}return i}}catch{}return null}function ba(){return fe()!==null}async function Fe(s){let e=fe(s);if(!e?.access_token)return null;if(e.expires_at&&e.expires_at<Date.now()&&e.refresh_token){process.stderr.write(` \u{1F504} Refreshing auth token...
|
|
43
|
+
`);try{let t=await fetch(`${Ie}/v1/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:e.refresh_token})});if(t.ok){let o=await t.json();if(o.access_token){let n=Date.now()+(o.expires_in||172800)*1e3;return Zo({...e,access_token:o.access_token,refresh_token:o.refresh_token||e.refresh_token,expires_at:n}),o.access_token}}}catch{}}return e.access_token}function Zo(s,e){let t=e||s.profile||"default",o=`${da}-${t}`;try{Hs().set(o,JSON.stringify({...s,profile:t}))}catch{let n=A();Ee.mkdirSync(n.config,{recursive:!0});let r=t==="default"?Mt.join(n.config,"auth.json"):Mt.join(n.config,`auth-${t}.json`);Ee.writeFileSync(r,JSON.stringify({...s,profile:t},null,2),{mode:384})}}function Dy(s){return new Promise(e=>setTimeout(e,s))}function vy(s,e){return new Promise(t=>{let o=process.stdin;process.stdout.write(s),o.isTTY&&o.setRawMode(!0),o.resume();let n="",r=l(i=>{let c=i.toString();switch(c){case"\r":case`
|
|
44
|
+
`:case"":o.isTTY&&o.setRawMode(!1),o.removeListener("data",r),o.pause(),t(n);break;case"":o.isTTY&&o.setRawMode(!1),process.exit(1);break;case"\x7F":n.length>0&&(n=n.slice(0,-1),process.stdout.write("\b \b"));break;default:n+=c,process.stdout.write("*");break}},"onData");o.on("data",r)})}async function wa(s){let e=I(),t=H(e),o=e.ansi,n=A(),r=Mt.join(n.config,"config.json"),i={};try{Ee.existsSync(r)&&(i=JSON.parse(Ee.readFileSync(r,"utf8")))}catch{}let c=i.auth?.ssoUrl,u=i.auth?.ssoClientId,d=i.auth?.ssoProvider||"OIDC";if(!c){console.log(""),console.log(` ${t.error} SSO not configured.`),console.log(""),console.log(" Add SSO configuration to your global config:"),console.log(o?a.dim(` ${r}`):` ${r}`),console.log(""),console.log(" {"),console.log(' "auth": {'),console.log(' "method": "sso",'),console.log(' "ssoProvider": "okta",'),console.log(' "ssoUrl": "https://myorg.okta.com/app/monkeyscode/sso",'),console.log(' "ssoClientId": "0oaXXXXXX"'),console.log(" }"),console.log(" }"),console.log("");return}console.log(""),console.log(o?a.bold(` \u{1F3E2} Enterprise SSO (${d})`):` Enterprise SSO (${d})`),console.log("");let p=9876,f=`http://localhost:${p}/callback`,m=Math.random().toString(36).slice(2),g=new URL(c);g.searchParams.set("client_id",u||"monkeyscode-cli"),g.searchParams.set("redirect_uri",f),g.searchParams.set("response_type","code"),g.searchParams.set("scope","openid profile email"),g.searchParams.set("state",m),console.log(o?` ${t.info} Opening SSO login page...`:" Opening SSO login page..."),console.log(""),console.log(o?` ${a.underline.cyan(g.toString())}`:` ${g.toString()}`),console.log("");try{let{exec:D}=await import("node:child_process"),C=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";D(`${C} "${g.toString()}"`)}catch{}let{createServer:h}=await import("node:http"),S=await new Promise(D=>{let C=h((x,v)=>{let E=new URL(x.url||"/",`http://localhost:${p}`);if(E.pathname==="/callback"){let oe=E.searchParams.get("code");if(E.searchParams.get("state")!==m){v.writeHead(400,{"Content-Type":"text/html"}),v.end("<html><body><h2>\u274C State mismatch. Please try again.</h2></body></html>"),C.close(),D(null);return}v.writeHead(200,{"Content-Type":"text/html"}),v.end("<html><body><h2>\u2705 Authentication successful!</h2><p>You can close this tab.</p></body></html>"),C.close(),D(oe)}else v.writeHead(404),v.end()});C.listen(p,()=>{console.log(o?a.dim(` Listening on http://localhost:${p}/callback ...`):` Listening on http://localhost:${p}/callback ...`)}),setTimeout(()=>{C.close(),D(null)},3e5)});if(!S){console.log(` ${t.error} SSO login failed or timed out.`),console.log("");return}try{let D=await fetch(`${Ie}/v1/auth/sso/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:S,redirect_uri:f,client_id:u||"monkeyscode-cli"})});if(!D.ok)throw new Error(`Token exchange failed: HTTP ${D.status}`);let C=await D.json(),x=await ya(C.access_token),v=Date.now()+(C.expires_in||172800)*1e3;Zo({access_token:C.access_token,refresh_token:C.refresh_token,expires_at:v,auth_method:"sso",user:x?{id:x.id?.toString(),email:x.email,name:x.name,avatar_url:x.avatar_url??void 0}:void 0,org:x?.orgs?.[0]?{id:x.orgs[0].id?.toString(),name:x.orgs[0].name,plan:x.orgs[0].plan_code}:void 0},s),console.log(""),console.log(` ${t.success} SSO login successful!`),x&&console.log(` ${t.info} ${x.email} (${x.orgs?.[0]?.plan_code||"enterprise"})`),console.log("")}catch(D){console.error(` ${t.error} SSO token exchange failed: ${D instanceof Error?D.message:D}`),console.log("")}}function ka(s){let e=H(),t=A(),o=s||"default",n=o==="default"?Mt.join(t.config,"auth.json"):Mt.join(t.config,`auth-${o}.json`);Ee.existsSync(n)&&Ee.unlinkSync(n),console.log(` ${e.success} Logged out${o!=="default"?` (profile: ${o})`:""}.`),console.log("")}var Ee,Mt,Eu,Ie,da,ee=G(()=>{"use strict";Ee=b(require("node:fs"),1),Mt=b(require("node:path"),1),Eu=b(require("node:readline"),1);W();X();_e();_u();Ie=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com",da="auth";l(pa,"authLogin");l(ma,"authLoginEmail");l(fa,"authLogout");l(ga,"authSetToken");l(er,"authStatus");l(ha,"authRefresh");l(ya,"fetchProfile");l(fe,"loadAuth");l(ba,"isAuthenticated");l(Fe,"getAccessToken");l(Zo,"saveAuth");l(Dy,"sleep");l(vy,"askPassword");l(wa,"authLoginSSO");l(ka,"authLogoutProfile")});async function*Fu(s){if(!s.body)throw new Error("Response body is null \u2014 streaming not supported");let e=s.body.getReader(),t=new TextDecoder,o="";try{for(;;){let{done:n,value:r}=await e.read();if(n)break;o+=t.decode(r,{stream:!0});let i=o.split(`
|
|
45
|
+
`);o=i.pop();for(let c of i){let u=c.trim();if(!(!u||u.startsWith(":"))&&u.startsWith("data: ")){let d=u.slice(6).trim();if(d==="[DONE]")return;try{yield JSON.parse(d)}catch{}}}}if(o.trim()){let n=o.trim();if(n.startsWith("data: ")){let r=n.slice(6).trim();if(r!=="[DONE]")try{yield JSON.parse(r)}catch{}}}}finally{e.releaseLock()}}var tr,Tu=G(()=>{"use strict";l(Fu,"parseSSEStream");tr=class{static{l(this,"ToolCallAccumulator")}_calls=new Map;feed(e){for(let t of e){let o=this._calls.get(t.index);t.id&&t.function?.name?this._calls.set(t.index,{id:t.id,name:t.function.name,arguments:t.function.arguments||""}):o&&t.function?.arguments&&(o.arguments+=t.function.arguments)}}flush(){let e=Array.from(this._calls.values());return this._calls.clear(),e}get hasPending(){return this._calls.size>0}}});function Au(s=!0){return s?Ru:Ru.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var Ru,Pu=G(()=>{"use strict";Ru=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files are returned WHOLE unless they exceed ~200K chars or 6000 lines, in which case you get head + tail with an exact pointer to the omitted span. PREFER ONE LARGE READ over several ranged reads \u2014 reading a whole file once is far cheaper than probing it with multiple range calls. Use start_line/end_line only when you already know the exact span you need, or full:true to force the entire file. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(Au,"getToolSchemas")});var Se={};Ae(Se,{getSetting:()=>xy,loadSettings:()=>K,saveSettings:()=>Sy});function K(){let s=A(),e=Da.join(s.config,"settings.json");try{if(so.existsSync(e)){let t=JSON.parse(so.readFileSync(e,"utf8"));return{...Mu,...t}}}catch{}return{...Mu}}function Sy(s){let e=A();so.mkdirSync(e.config,{recursive:!0});let t=Da.join(e.config,"settings.json"),n={...K(),...s};so.writeFileSync(t,JSON.stringify(n,null,2))}function xy(s){return K()[s]}var so,Da,Mu,Q=G(()=>{"use strict";so=b(require("node:fs"),1),Da=b(require("node:path"),1);X();Mu={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(K,"loadSettings");l(Sy,"saveSettings");l(xy,"getSetting")});var B,le,Ue,va,$y,or,Ou=G(()=>{"use strict";B=b(require("node:fs"),1),le=b(require("node:path"),1),Ue=require("node:child_process"),va=require("node:fs"),$y={write_file:"create_file",list_files:"list_dir",list_directory:"list_dir",search_code:"grep_search",execute_command:"run_command",view_file:"read_file",str_replace:"replace_in_file",str_replace_editor:"replace_in_file",str_replace_based_edit_tool:"replace_in_file",bash:"run_command",bash_tool:"run_command",shell:"run_command",terminal:"run_command",text_editor:"edit_file",apply_patch:"patch_file",container_exec:"run_command",file_search:"search_files",codebase_search:"grep_search",semantic_search:"grep_search",grep:"grep_search",ripgrep:"grep_search",find_files:"search_files",glob:"search_files",glob_file_search:"search_files",ls:"list_dir",read:"read_file",cat:"read_file",write:"create_file",edit:"edit_file",multi_edit:"edit_file",search_replace:"replace_in_file",run_terminal_cmd:"run_command",run_in_terminal:"run_command",web_fetch:"read_url",fetch_webpage:"read_url",search_web:"web_search",google_search:"web_search",move_file:"rename_file",remove_file:"delete_file",task:"spawn_subagent",subagent:"spawn_subagent"},or=class{static{l(this,"ToolExecutor")}workspace;platformUrl;token;signal;_checkpoints=new Map;_runId="";_mcpClient;_sandbox;constructor(e){this.workspace=e.workspace,this.platformUrl=e.platformUrl,this.token=e.token,this.signal=e.signal}setRunId(e){this._runId=e,this._checkpoints.clear()}setMCPClient(e){this._mcpClient=e}setSandbox(e){this._sandbox=e}async execute(e,t){let o=$y[e]||e;switch(o){case"read_file":return this.readFile(t);case"create_file":return this.createFile(t);case"edit_file":return this.editFile(t);case"delete_file":return this.deleteFile(t);case"rename_file":return this.renameFile(t);case"list_dir":return this.listDir(t);case"grep_search":return this.grepSearch(t);case"glob_files":return this.globFiles(t);case"search_files":return this.searchFiles(t);case"replace_in_file":return this.replaceInFile(t);case"patch_file":return this.patchFile(t);case"run_command":return this.runCommand(t);case"run_tests":return this.runTests(t);case"web_search":return this.webSearch(t);case"read_url":return this.readUrl(t);case"git_status":return this.gitExec("status",t);case"git_diff":return this.gitDiff(t);case"git_log":return this.gitLog(t);case"git_commit":return this.gitCommit(t);case"git_stash":return this.gitExec("stash",t);case"git_stash_pop":return this.gitExec("stash pop",t);case"todo_write":return this.todoWrite(t);case"spawn_subagent":return this.spawnSubagent(t);case"remember":return this.remember(t);default:return o.startsWith("mcp_")&&this._mcpClient?this._executeMCPTool(o,t):{output:`Unknown tool: ${e}. Use one of: read_file, create_file, edit_file, replace_in_file, patch_file, run_command, run_tests, grep_search, search_files, list_dir, git_status, git_commit, web_search, read_url, ask_user, todo_write, spawn_subagent, remember, or mcp_<server>_<tool>`}}}getCheckpoints(){return this._checkpoints}readFile(e){let t=this.resolve(e.path);if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}`};if(B.statSync(t).isDirectory())return{output:`Error: ${e.path} is a directory. Use list_dir instead.`};let n=B.readFileSync(t,"utf8"),r=n.split(`
|
|
46
|
+
`),i=r.length,c=e.full,u=2e5,d=6e3,p=4e3,f=2e3,m=l((C,x)=>C.map((v,E)=>`${String(x+E).padStart(5)} ${v}`),"numberFrom");if(e.start_line!==void 0||e.end_line!==void 0){let C=Math.max(1,e.start_line||1),x=Math.min(i,e.end_line||i);if(C>i)return{output:`Error: start_line ${C} is beyond end of file (${i} lines)`};let v=m(r.slice(C-1,x),C);return{output:`File: ${e.path} \u2014 lines ${C}-${x} of ${i}
|
|
47
|
+
${v.join(`
|
|
48
|
+
`)}`}}if(c||i<=d&&n.length<=u){let C=m(r,1);return{output:`File: ${e.path} (${i} lines)
|
|
49
|
+
${C.join(`
|
|
50
|
+
`)}`}}let h=p+1,y=i-f,S=y-h+1,D=[...m(r.slice(0,p),1),`
|
|
51
|
+
... lines ${h}-${y} omitted (${S} lines) \u2014 read them with read_file(path:"${e.path}", start_line:${h}, end_line:${y}), or full:true for the entire file ...
|
|
52
|
+
`,...m(r.slice(i-f),y+1)];return{output:`File: ${e.path} (${i} lines, truncated: showing 1-${p} and ${y+1}-${i})
|
|
53
|
+
${D.join(`
|
|
54
|
+
`)}`}}createFile(e){let t=this.resolve(e.path);if(B.existsSync(t))return{output:`Error: File already exists: ${e.path}. Use edit_file to modify it.`};this._checkpoints.set(t,null),B.mkdirSync(le.dirname(t),{recursive:!0}),B.writeFileSync(t,e.content);let o=e.content.split(`
|
|
55
|
+
`).length;return{output:`Created ${e.path} (${o} lines)`,wroteFiles:!0,touchedFiles:[e.path]}}editFile(e){let t=this.resolve(e.path);if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}. Use create_file to create it.`};let o=B.readFileSync(t,"utf8"),n=e.old_string,r=e.new_string;if(!o.includes(n))return{output:`Error: old_string not found in ${e.path}. Make sure the string matches EXACTLY including whitespace and indentation. Read the file first to see current content.`};let i=o.split(n).length-1;if(i>1)return{output:`Error: old_string found ${i} times in ${e.path}. Provide a more specific/longer string to match exactly one occurrence.`};this._checkpoints.has(t)||this._checkpoints.set(t,o);let c=o.replace(n,r);B.writeFileSync(t,c);let u=n.split(`
|
|
52
56
|
`).length,d=r.split(`
|
|
53
|
-
`).length;return{output:`Edited ${e.path}: replaced ${u} line(s) with ${d} line(s)`,wroteFiles:!0,touchedFiles:[e.path]}}deleteFile(e){let t=this.resolve(e.path);return
|
|
54
|
-
`)}}listEntries(e,t,o){let n=[],r;try{r=
|
|
55
|
-
`).filter(Boolean);return
|
|
56
|
-
${
|
|
57
|
-
`)}`}:{output:`Found ${
|
|
58
|
-
${
|
|
59
|
-
`)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let
|
|
60
|
-
`).filter(Boolean);return{output:`Found ${
|
|
61
|
-
|
|
57
|
+
`).length;return{output:`Edited ${e.path}: replaced ${u} line(s) with ${d} line(s)`,wroteFiles:!0,touchedFiles:[e.path]}}deleteFile(e){let t=this.resolve(e.path);return B.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,B.readFileSync(t,"utf8")),B.unlinkSync(t),{output:`Deleted ${e.path}`,wroteFiles:!0,touchedFiles:[e.path]}):{output:`Error: File not found: ${e.path}`}}renameFile(e){let t=this.resolve(e.from),o=this.resolve(e.to);return B.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,B.readFileSync(t,"utf8")),this._checkpoints.set(o,null),B.mkdirSync(le.dirname(o),{recursive:!0}),B.renameSync(t,o),{output:`Renamed ${e.from} \u2192 ${e.to}`,wroteFiles:!0,touchedFiles:[e.from,e.to]}):{output:`Error: Source file not found: ${e.from}`}}listDir(e){let t=this.resolve(e.path||".");if(!B.existsSync(t))return{output:`Error: Directory not found: ${e.path}`};let o=e.recursive,n=this.listEntries(t,o?3:0,"");return n.length===0?{output:`Directory ${e.path||"."} is empty`}:{output:n.join(`
|
|
58
|
+
`)}}listEntries(e,t,o){let n=[],r;try{r=B.readdirSync(e,{withFileTypes:!0})}catch{return[` ${o}(permission denied)`]}r.sort((c,u)=>c.isDirectory()&&!u.isDirectory()?-1:!c.isDirectory()&&u.isDirectory()?1:c.name.localeCompare(u.name));let i=new Set(["node_modules",".git","__pycache__",".next","dist",".turbo",".cache"]);for(let c of r)if(!(i.has(c.name)&&!o))if(c.isDirectory()){if(n.push(` ${o}${c.name}/`),t>0){let u=this.listEntries(le.join(e,c.name),t-1,o+" ");n.push(...u)}}else{let u=B.statSync(le.join(e,c.name)).size,d=u<1024?`${u}B`:u<1048576?`${(u/1024).toFixed(1)}K`:`${(u/1048576).toFixed(1)}M`;n.push(` ${o}${c.name} (${d})`)}return n}grepSearch(e){let t=e.pattern,o=this.resolve(e.path||"."),n=e.include,r=e.fixed_strings,i=e.case_insensitive,c=e.max_count,u=["--line-number","--no-heading","--color=never"];r&&u.push("--fixed-strings"),i&&u.push("--ignore-case"),c&&u.push("--max-count",String(c)),n&&u.push("--glob",n),u.push("--",t,o);try{let d=(0,Ue.spawnSync)("rg",u,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1048576}),p=200;if(d.status===0&&d.stdout){let f=d.stdout.split(`
|
|
59
|
+
`).filter(Boolean);return f.length>p?{output:`Found ${f.length} matches (showing first ${p} \u2014 narrow with include/path, or set max_count per file):
|
|
60
|
+
${f.slice(0,p).join(`
|
|
61
|
+
`)}`}:{output:`Found ${f.length} match(es):
|
|
62
|
+
${f.join(`
|
|
63
|
+
`)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let p=["-rn","--color=never"];r&&p.push("-F"),i&&p.push("-i"),n&&p.push("--include",n),p.push("--",t,o);let f=(0,Ue.spawnSync)("grep",p,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1024*1024});if(f.stdout){let m=f.stdout.split(`
|
|
64
|
+
`).filter(Boolean);return m.length>200?{output:`Found ${m.length} matches (showing first 200 \u2014 narrow with include/path):
|
|
65
|
+
`+m.slice(0,200).join(`
|
|
66
|
+
`)}:{output:`Found ${m.length} match(es):
|
|
67
|
+
${m.join(`
|
|
62
68
|
`)}`}}return{output:"No matches found."}}catch(d){return{output:`Search error: ${d instanceof Error?d.message:d}`}}}globFiles(e){let t=e.pattern,o=this.resolve(e.path||".");try{let n=(0,Ue.spawnSync)("find",[o,"-type","f","-name",t.replace("**/","")],{cwd:this.workspace,encoding:"utf8",timeout:1e4});if(n.stdout){let r=n.stdout.split(`
|
|
63
69
|
`).filter(Boolean).map(i=>le.relative(this.workspace,i)).sort();return{output:r.length>0?`Found ${r.length} file(s):
|
|
64
70
|
${r.join(`
|
|
@@ -75,21 +81,21 @@ ${m}`,c({output:m})}),u.on("error",f=>{c({output:`Command failed: ${f.message}`}
|
|
|
75
81
|
|
|
76
82
|
... (truncated)`),{output:r}}catch(n){return{output:`Fetch failed: ${n instanceof Error?n.message:n}`}}}gitExec(e,t){try{let o=t.message||void 0,n=`git ${e}`;return o&&(n+=` -m ${JSON.stringify(o)}`),{output:(0,Ue.execSync)(n,{cwd:this.workspace,encoding:"utf8",timeout:15e3,maxBuffer:512*1024})||"(no output)"}}catch(o){return{output:`Git error: ${o.stderr||o.message}`}}}gitDiff(e){let t=e.target||"",o=e.path,n="git diff";t==="staged"?n="git diff --cached":t&&(n=`git diff ${t}`),o&&(n+=` -- ${o}`);try{return{output:(0,Ue.execSync)(n,{cwd:this.workspace,encoding:"utf8",timeout:15e3,maxBuffer:524288})||"(no changes)"}}catch(r){return{output:`Git error: ${r.stderr||r.message}`}}}gitLog(e){let t=e.max_count||10,o=e.path,n=e.oneline,r=`git log -n ${t}`;n?r+=" --oneline":r+=' --format=format:"%h %s (%an, %ar)"',o&&(r+=` -- ${o}`);try{return{output:(0,Ue.execSync)(r,{cwd:this.workspace,encoding:"utf8",timeout:15e3})||"(no commits)"}}catch(i){return{output:`Git error: ${i.stderr||i.message}`}}}gitCommit(e){let t=e.message,o=e.add_all;try{return o&&(0,Ue.execSync)("git add -A",{cwd:this.workspace,encoding:"utf8",timeout:1e4}),{output:(0,Ue.execSync)(`git commit -m ${JSON.stringify(t)}`,{cwd:this.workspace,encoding:"utf8",timeout:15e3}),wroteFiles:!0}}catch(n){return{output:`Git commit error: ${n.stderr||n.message}`}}}todoWrite(e){let t=e.todos;return!t||!Array.isArray(t)?{output:"Error: todos must be an array of {id, content, status}"}:{output:`Task plan updated:
|
|
77
83
|
${t.map(n=>` ${n.status==="done"?"\u2705":n.status==="in_progress"?"\u{1F504}":"\u2B1C"} [${n.status}] ${n.content}`).join(`
|
|
78
|
-
`)}`}}searchFiles(e){let t=e.pattern,o=e.path||".",n=e.max_results||50;try{let r=this.resolve(o),c=(0,va.globSync)(t,{cwd:r}).filter(p=>{try{return
|
|
84
|
+
`)}`}}searchFiles(e){let t=e.pattern,o=e.path||".",n=e.max_results||50;try{let r=this.resolve(o),c=(0,va.globSync)(t,{cwd:r}).filter(p=>{try{return B.statSync(le.join(r,p)).isFile()}catch{return!1}}),u=c.slice(0,n);return u.length===0?{output:`No files matching "${t}" in ${o}`}:{output:`Found ${c.length} file(s)${c.length>n?` (showing first ${n})`:""}:`+`
|
|
79
85
|
`+u.join(`
|
|
80
|
-
`)}}catch(r){return{output:`Error searching files: ${r.message}`}}}replaceInFile(e){let t=this.resolve(e.path),o=e.old_string,n=e.new_string,r=e.allow_multiple||!1;if(!
|
|
86
|
+
`)}}catch(r){return{output:`Error searching files: ${r.message}`}}}replaceInFile(e){let t=this.resolve(e.path),o=e.old_string,n=e.new_string,r=e.allow_multiple||!1;if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}`};let i=B.readFileSync(t,"utf8");this._checkpoints.has(t)||this._checkpoints.set(t,i);let c=i.split(o).length-1;if(c===0)return{output:`Error: String not found in ${e.path}. Make sure old_string matches exactly (including whitespace and indentation).`};if(c>1&&!r)return{output:`Error: Found ${c} occurrences of the search string in ${e.path}. Set allow_multiple:true to replace all, or use a more specific string.`};let u=r?i.replaceAll(o,n):i.replace(o,n);return B.writeFileSync(t,u,"utf8"),{output:`Replaced ${r?c:1} occurrence(s) in ${e.path}`,wroteFiles:!0,touchedFiles:[t]}}patchFile(e){let t=this.resolve(e.path),o=e.patch;if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}`};let n=B.readFileSync(t,"utf8");this._checkpoints.has(t)||this._checkpoints.set(t,n);try{let r=n.split(`
|
|
81
87
|
`),i=o.split(`
|
|
82
|
-
`),c=[],u=0;for(let d of i)d.startsWith("---")||d.startsWith("+++")||d.startsWith("@@")||(d.startsWith("-")?u++:d.startsWith("+")?c.push(d.slice(1)):(d.startsWith(" ")||d==="")&&u<r.length&&(c.push(r[u]),u++));for(;u<r.length;)c.push(r[u]),u++;return
|
|
88
|
+
`),c=[],u=0;for(let d of i)d.startsWith("---")||d.startsWith("+++")||d.startsWith("@@")||(d.startsWith("-")?u++:d.startsWith("+")?c.push(d.slice(1)):(d.startsWith(" ")||d==="")&&u<r.length&&(c.push(r[u]),u++));for(;u<r.length;)c.push(r[u]),u++;return B.writeFileSync(t,c.join(`
|
|
83
89
|
`),"utf8"),{output:`Patch applied to ${e.path}`,wroteFiles:!0,touchedFiles:[t]}}catch(r){return{output:`Error applying patch: ${r.message}`}}}runTests(e){let t=e.path,o=e.pattern,n=e.framework||"auto";n==="auto"&&(n=this.detectTestFramework());let r;switch(n){case"jest":r="npx jest --no-coverage",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"vitest":r="npx vitest run",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"mocha":r="npx mocha",t&&(r+=` ${t}`),o&&(r+=` --grep ${JSON.stringify(o)}`);break;case"pytest":r="python -m pytest -v",t&&(r+=` ${t}`),o&&(r+=` -k ${JSON.stringify(o)}`);break;case"go":r="go test -v",t?r+=` ./${t}/...`:r+=" ./...",o&&(r+=` -run ${JSON.stringify(o)}`);break;case"cargo":r="cargo test",o&&(r+=` ${o}`),r+=" -- --nocapture";break;case"dotnet":r="dotnet test --verbosity normal",t&&(r+=` ${t}`),o&&(r+=` --filter ${JSON.stringify(o)}`);break;case"rspec":r="bundle exec rspec",t&&(r+=` ${t}`);break;default:return{output:`Unknown test framework: ${n}. Supported: jest, vitest, mocha, pytest, go, cargo, dotnet, rspec`}}try{let i=(0,Ue.execSync)(r,{cwd:this.workspace,encoding:"utf8",timeout:12e4,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0",CI:"1"}});return{output:`[${n}] Tests passed:
|
|
84
90
|
${i.slice(0,8e3)}`}}catch(i){let c=i.stdout||i.stderr||i.message;return{output:`[${n}] Tests failed:
|
|
85
|
-
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=le.join(this.workspace,"package.json");if(
|
|
86
|
-
`),wroteFiles:p.filesModified.length>0,touchedFiles:p.filesModified}}catch(n){return{output:`Subagent error: ${n.message}`}}}remember(e){let t=e.content,o=e.category||"general";try{let n=le.join(this.workspace,".monkeyscode");
|
|
91
|
+
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=le.join(this.workspace,"package.json");if(B.existsSync(e)){try{let t=JSON.parse(B.readFileSync(e,"utf8")),o={...t.dependencies,...t.devDependencies};if(o.vitest)return"vitest";if(o.jest)return"jest";if(o.mocha)return"mocha"}catch{}return"jest"}return B.existsSync(le.join(this.workspace,"pyproject.toml"))||B.existsSync(le.join(this.workspace,"setup.py"))||B.existsSync(le.join(this.workspace,"pytest.ini"))?"pytest":B.existsSync(le.join(this.workspace,"go.mod"))?"go":B.existsSync(le.join(this.workspace,"Cargo.toml"))?"cargo":B.existsSync(le.join(this.workspace,"Gemfile"))?"rspec":(0,va.globSync)("**/*.csproj",{cwd:this.workspace}).length>0?"dotnet":"jest"}async spawnSubagent(e){let t=e.task,o=e.model;try{let n=(await Promise.resolve().then(()=>(Q(),Se))).loadSettings(),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),ge)),{AgentLoop:i}=await Promise.resolve().then(()=>(Ke(),es)),c=await r();if(!c)return{output:"Error: Not authenticated. Cannot spawn subagent."};let u=new i({platformUrl:n.platformUrl,token:c,model:o||n.defaultModel,workspace:this.workspace,mode:"auto",maxTurns:30,userId:void 0,orgId:void 0}),d=`subagent-${Date.now().toString(36)}`,p=await u.run(t);return{output:[`Subagent ${d} completed:`,` Turns: ${p.turns}`,` Tokens: ${p.tokensIn+p.tokensOut}`,` Files modified: ${p.filesModified.join(", ")||"none"}`,` Duration: ${Math.round(p.duration/1e3)}s`].join(`
|
|
92
|
+
`),wroteFiles:p.filesModified.length>0,touchedFiles:p.filesModified}}catch(n){return{output:`Subagent error: ${n.message}`}}}remember(e){let t=e.content,o=e.category||"general";try{let n=le.join(this.workspace,".monkeyscode");B.existsSync(n)||B.mkdirSync(n,{recursive:!0});let r=le.join(n,"MEMORY.md"),i=new Date().toISOString().split("T")[0],c=`
|
|
87
93
|
- [${o}] ${t} _(${i})_
|
|
88
|
-
`,u="";return
|
|
94
|
+
`,u="";return B.existsSync(r)?u=B.readFileSync(r,"utf8"):u=`# Project Memory
|
|
89
95
|
|
|
90
96
|
Facts, conventions, and decisions learned during sessions.
|
|
91
|
-
`,
|
|
92
|
-
`)}}});var xa,
|
|
97
|
+
`,B.writeFileSync(r,u+c,"utf8"),{output:`Remembered: [${o}] ${t}`,wroteFiles:!0,touchedFiles:[r]}}catch(n){return{output:`Error saving memory: ${n.message}`}}}async _executeMCPTool(e,t){if(!this._mcpClient)return{output:"Error: MCP client not initialized. Configure MCP servers in .monkeyscode/mcp.json"};let o=e.slice(4).split("_");if(o.length<2)return{output:`Error: Invalid MCP tool name "${e}". Expected format: mcp_<server>_<tool>`};let n=o[0],r=o.slice(1).join("_");try{let i=await this._mcpClient.callTool(n,r,t);return{output:i.isError?`MCP Error (${n}/${r}): ${i.content}`:i.content}}catch(i){return{output:`MCP tool error: ${i.message}`}}}resolve(e){return le.isAbsolute(e)?e:le.resolve(this.workspace,e)}}});var sr,Sa=G(()=>{"use strict";sr=["~/.ssh","~/.aws","~/.config/gcloud","~/.config/gh","~/.azure","~/.kube","~/.docker/config.json","~/.npmrc","~/.pypirc","~/.env","~/.netrc","~/.gnupg"]});var Iu,ju,Gs,qs,Nu=G(()=>{"use strict";Iu=require("node:child_process"),ju=b(require("node:os"),1),Gs=b(require("node:path"),1);Sa();qs=class{static{l(this,"BubblewrapProvider")}name="bubblewrap";async isAvailable(){try{return(0,Iu.execSync)("which bwrap",{stdio:"pipe"}),{available:!0}}catch{return{available:!1,reason:"bubblewrap (bwrap) not found. Install with: apt install bubblewrap (Debian/Ubuntu) or dnf install bubblewrap (Fedora)"}}}async wrapCommand(e,t,o){let n=ju.homedir(),r=[];r.push("--ro-bind","/","/");let i=Gs.resolve(o.workspace);r.push("--bind",i,i),r.push("--tmpfs","/tmp"),r.push("--dev","/dev"),r.push("--proc","/proc");for(let c of sr){let u=c.replace("~",n);r.push("--tmpfs",u)}return r.push("--tmpfs",Gs.join(n,".env")),r.push("--tmpfs",Gs.join(n,".env.local")),(o.network==="none"||o.network==="local")&&r.push("--unshare-net"),r.push("--unshare-pid"),r.push("--unshare-ipc"),r.push("--die-with-parent"),r.push("--chdir",i),r.push("--",e,...t),{command:"bwrap",args:r}}async setup(e){}async teardown(){}}});var Lu,Vs,nr,ts,zs,Bu=G(()=>{"use strict";Lu=require("node:child_process"),Vs=b(require("node:os"),1),nr=b(require("node:path"),1),ts=b(require("node:fs"),1);Sa();zs=class{static{l(this,"SandboxExecProvider")}name="sandbox-exec";profilePath=null;async isAvailable(){try{return(0,Lu.execSync)("which sandbox-exec",{stdio:"pipe"}),{available:!0}}catch{return{available:!1,reason:"sandbox-exec not found. Consider using Docker sandbox instead (--sandbox docker)."}}}async wrapCommand(e,t,o){let n=this.generateProfile(o),r=nr.join(Vs.tmpdir(),`mc-sandbox-${process.pid}.sb`);return ts.writeFileSync(r,n,"utf-8"),this.profilePath=r,{command:"sandbox-exec",args:["-f",r,e,...t]}}async setup(e){}async teardown(){this.profilePath&&ts.existsSync(this.profilePath)&&(ts.unlinkSync(this.profilePath),this.profilePath=null)}generateProfile(e){let t=Vs.homedir(),o=nr.resolve(e.workspace),n=["(version 1)","","; Default: deny everything","(deny default)","","; Allow basic process operations","(allow process-exec)","(allow process-fork)","(allow signal)","(allow sysctl-read)","(allow mach-lookup)","","; Allow read access to system libraries and binaries","(allow file-read*",' (subpath "/usr")',' (subpath "/bin")',' (subpath "/sbin")',' (subpath "/Library")',' (subpath "/System")',' (subpath "/private/var/db")',' (subpath "/private/etc")',' (subpath "/dev")',' (subpath "/opt/homebrew")',' (subpath "/usr/local")',")","","; Allow read access to temp directories","(allow file-read* file-write*",' (subpath "/tmp")',' (subpath "/private/tmp")',` (subpath "${Vs.tmpdir()}")`,")","","; Allow read-write access to the workspace",`(allow file-read* file-write* (subpath "${o}"))`,"","; Allow read access to home directory basics",`(allow file-read* (subpath "${t}/.nvm"))`,`(allow file-read* (subpath "${t}/.volta"))`,`(allow file-read* (subpath "${t}/.cargo"))`,`(allow file-read* (subpath "${t}/.rustup"))`,`(allow file-read* (subpath "${t}/.local"))`,""];for(let r of sr){let i=r.replace("~",t);n.push(`; Block credential: ${r}`),n.push(`(deny file-read* file-write* (subpath "${i}"))`)}return n.push(""),e.network==="none"?(n.push("; Block all network access"),n.push("(deny network*)")):e.network==="local"?(n.push("; Allow localhost only"),n.push('(allow network* (local ip "localhost:*"))'),n.push("(deny network*)")):(n.push("; Full network access"),n.push("(allow network*)")),n.join(`
|
|
98
|
+
`)}}});var xa,rr,ir,os,Js,Uu=G(()=>{"use strict";xa=require("node:child_process"),rr=b(require("node:os"),1),ir=b(require("node:path"),1),os=b(require("node:fs"),1),Js=class{static{l(this,"WindowsSandboxProvider")}name="windows-sandbox";wsbConfigPath=null;mode=null;async isAvailable(){if(rr.platform()!=="win32")return{available:!1,reason:"Not running on Windows"};try{return(0,xa.execSync)("where WindowsSandbox.exe",{stdio:"pipe"}),this.mode="windows-sandbox",{available:!0}}catch{}try{return(0,xa.execSync)("where icacls.exe",{stdio:"pipe"}),this.mode="appcontainer",{available:!0}}catch{return{available:!1,reason:"Neither Windows Sandbox nor AppContainer available. Enable Windows Sandbox in Windows Features, or use Docker (--sandbox docker)."}}}async wrapCommand(e,t,o){return this.mode==="windows-sandbox"?this.wrapWithWindowsSandbox(e,t,o):this.wrapWithAppContainer(e,t,o)}async setup(e){if(this.mode==="windows-sandbox"){let t=ir.resolve(e.workspace),o=this.generateWsbConfig(t,e);this.wsbConfigPath=ir.join(rr.tmpdir(),`mc-sandbox-${process.pid}.wsb`),os.writeFileSync(this.wsbConfigPath,o,"utf-8")}}async teardown(){this.wsbConfigPath&&os.existsSync(this.wsbConfigPath)&&(os.unlinkSync(this.wsbConfigPath),this.wsbConfigPath=null)}wrapWithWindowsSandbox(e,t,o){let n=[e,...t].join(" ");return{command:"cmd.exe",args:["/c",`start /wait WindowsSandbox.exe "${this.wsbConfigPath}" && cmd /c "${n}"`]}}generateWsbConfig(e,t){return`
|
|
93
99
|
<Configuration>
|
|
94
100
|
<VGpu>Disable</VGpu>
|
|
95
101
|
<Networking>${t.network==="none"?"Disable":"Default"}</Networking>
|
|
@@ -104,7 +110,7 @@ Facts, conventions, and decisions learned during sessions.
|
|
|
104
110
|
<Command>cmd.exe /k cd C:\\Workspace</Command>
|
|
105
111
|
</LogonCommand>
|
|
106
112
|
<MemoryInMB>2048</MemoryInMB>
|
|
107
|
-
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var
|
|
113
|
+
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var no,_o,ro,Hu,Wu,Ks,Eo,Gu=G(()=>{"use strict";no=require("node:child_process"),_o=b(require("node:path"),1),ro=b(require("node:fs"),1),Hu=b(require("node:crypto"),1),Wu="monkeyscode-sandbox",Ks="/workspace",Eo=class{static{l(this,"DockerSandboxProvider")}name="docker";containerId=null;imageName=Wu;async isAvailable(){try{return(0,no.execSync)("docker info",{stdio:"pipe",timeout:5e3}),{available:!0}}catch{return{available:!1,reason:"Docker not available. Install Docker Desktop (macOS/Windows) or Docker Engine (Linux)."}}}async wrapCommand(e,t,o){let n=["exec"];if(this.containerId)n.push("-w",Ks),n.push(this.containerId),n.push(e,...t);else{n.splice(0),n.push("run","--rm"),n.push("-w",Ks);let r=_o.resolve(o.workspace);n.push("-v",`${r}:${Ks}`),o.network==="none"?n.push("--network","none"):o.network==="local"&&n.push("--network","host"),n.push("--memory","2g"),n.push("--cpus","2"),n.push("--cap-drop","ALL"),n.push("--security-opt","no-new-privileges"),n.push(this.imageName),n.push(e,...t)}return{command:"docker",args:n}}async setup(e){this.imageName=e.dockerImage||Wu;let t=_o.resolve(e.workspace),o=e.dockerfilePath||_o.join(t,".monkeyscode","Dockerfile.sandbox");if(ro.existsSync(o)){let c=(0,no.spawnSync)("docker",["build","-t",this.imageName,"-f",o,t],{stdio:"pipe",timeout:12e4});if(c.status!==0)throw new Error(`Failed to build sandbox image: ${c.stderr?.toString()}`)}else await this.ensureBaseImage();let r=["run","-d","--name",`mc-sandbox-${Hu.randomUUID().substring(0,8)}`,"-w",Ks,"-v",`${t}:${Ks}`];e.network==="none"?r.push("--network","none"):e.network==="local"&&r.push("--network","host"),r.push("--memory","2g"),r.push("--cpus","2"),r.push("--cap-drop","ALL"),r.push("--security-opt","no-new-privileges"),r.push(this.imageName,"sleep","infinity");let i=(0,no.spawnSync)("docker",r,{stdio:"pipe"});i.status===0&&(this.containerId=i.stdout.toString().trim().substring(0,12))}async teardown(){if(this.containerId){try{(0,no.execSync)(`docker rm -f ${this.containerId}`,{stdio:"pipe",timeout:1e4})}catch{}this.containerId=null}}async ensureBaseImage(){try{(0,no.execSync)(`docker image inspect ${this.imageName}`,{stdio:"pipe"});return}catch{}let e=`
|
|
108
114
|
FROM ubuntu:22.04
|
|
109
115
|
RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
110
116
|
git curl wget ca-certificates \\
|
|
@@ -115,13 +121,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
|
115
121
|
RUN useradd -m -s /bin/bash sandbox
|
|
116
122
|
USER sandbox
|
|
117
123
|
WORKDIR /workspace
|
|
118
|
-
`.trim(),t=_o.join(require("node:os").tmpdir(),"mc-sandbox-build");
|
|
124
|
+
`.trim(),t=_o.join(require("node:os").tmpdir(),"mc-sandbox-build");ro.mkdirSync(t,{recursive:!0}),ro.writeFileSync(_o.join(t,"Dockerfile"),e);let o=(0,no.spawnSync)("docker",["build","-t",this.imageName,t],{stdio:"pipe",timeout:3e5});if(ro.rmSync(t,{recursive:!0,force:!0}),o.status!==0)throw new Error(`Failed to build sandbox base image: ${o.stderr?.toString()}`)}}});function qu(s){switch(s){case"linux":return[new qs,new Eo];case"macos":return[new zs,new Eo];case"windows":return[new Js,new Eo]}}function ar(s,e={}){return{enabled:!1,provider:"auto",network:"none",workspace:s,...e}}var ss,$a=G(()=>{"use strict";X();Nu();Bu();Uu();Gu();l(qu,"getProviderCandidates");ss=class{static{l(this,"SandboxManager")}config;provider=null;platform;initialized=!1;constructor(e){this.config=e,this.platform=ve()}async initialize(){if(!this.config.enabled)return this.initialized=!0,{status:"disabled",provider:"none",description:"Sandbox disabled (--no-sandbox)",network:this.config.network};if(this.config.provider!=="auto"&&(this.provider=this.getExplicitProvider(this.config.provider),this.provider)){let t=await this.provider.isAvailable();return t.available?(await this.provider.setup(this.config),this.initialized=!0,{status:"active",provider:this.provider.name,description:`Sandboxed via ${this.provider.name}`,network:this.config.network}):{status:"unavailable",provider:this.config.provider,description:`${this.config.provider} not available: ${t.reason}`,network:this.config.network}}let e=qu(this.platform);for(let t of e)if((await t.isAvailable()).available)return this.provider=t,await this.provider.setup(this.config),this.initialized=!0,{status:"active",provider:this.provider.name,description:`Sandboxed via ${this.provider.name}`,network:this.config.network};return this.initialized=!0,{status:"unavailable",provider:"none",description:"No sandbox provider available. Install bubblewrap (Linux), or Docker.",network:this.config.network}}async wrapCommand(e,t){return!this.provider||!this.config.enabled?{command:e,args:t}:this.provider.wrapCommand(e,t,this.config)}getStatus(){return this.config.enabled?this.provider?{status:"active",provider:this.provider.name,description:`Sandboxed via ${this.provider.name}`,network:this.config.network}:{status:"unavailable",provider:"none",description:"No sandbox provider detected",network:this.config.network}:{status:"disabled",provider:"none",description:"Sandbox disabled",network:this.config.network}}async teardown(){this.provider&&(await this.provider.teardown(),this.provider=null),this.initialized=!1}async checkAllProviders(){let e=qu(this.platform),t=[];for(let o of e){let n=await o.isAvailable();t.push({name:o.name,available:n.available,reason:n.reason})}return t}getExplicitProvider(e){switch(e){case"bubblewrap":return new qs;case"sandbox-exec":return new zs;case"windows-sandbox":case"appcontainer":return new Js;case"docker":return new Eo;default:return null}}};l(ar,"createDefaultSandboxConfig")});function Vu(s){switch(s){case 0:return"allow";case 1:return"deny";case 2:return"modify";default:return"allow"}}var zu,Ju=G(()=>{"use strict";l(Vu,"exitCodeToAction");zu={enabled:!0,timeoutMs:1e4}});function Fo(s){let e=A(),t=bt.join(s,".monkeyscode","hooks"),o=bt.join(e.config,"hooks"),n=Ku(t,"project"),r=Ku(o,"global"),i=new Map;for(let c of r)i.set(c.event,c);for(let c of n)i.set(c.event,c);return Array.from(i.values())}function Ku(s,e){if(!ns.existsSync(s))return[];let t=[];try{let o=ns.readdirSync(s,{withFileTypes:!0});for(let n of o){if(!n.isFile())continue;let r=bt.extname(n.name).toLowerCase(),i=_y[r];if(!i)continue;let c=bt.basename(n.name,r).toLowerCase(),u=Cy[c];u&&t.push({event:u,scriptPath:bt.join(s,n.name),source:e,scriptType:i})}}catch{}return t}function Yu(s){let e=A(),t=bt.join(s,".monkeyscode","hooks"),o=bt.join(e.config,"hooks");return[{path:t,source:"project",exists:ns.existsSync(t)},{path:o,source:"global",exists:ns.existsSync(o)}]}var ns,bt,Cy,_y,cr=G(()=>{"use strict";ns=b(require("node:fs"),1),bt=b(require("node:path"),1);X();Cy={"session-start":"SessionStart","pre-tool-use":"PreToolUse","post-tool-use":"PostToolUse","pre-edit":"PreEdit","post-edit":"PostEdit",stop:"Stop","headless-start":"HeadlessStart","headless-stop":"HeadlessStop","subagent-start":"SubagentStart","subagent-stop":"SubagentStop"},_y={".sh":"sh",".bash":"sh",".ps1":"ps1",".cmd":"cmd",".bat":"cmd",".js":"js",".mjs":"js",".py":"py"};l(Fo,"loadHooks");l(Ku,"scanHookDirectory");l(Yu,"getHookDirectories")});var Xu,To,Ca=G(()=>{"use strict";Xu=require("node:child_process");X();Ju();cr();To=class{static{l(this,"HookRunner")}hooks;config;platform=ve();constructor(e,t={}){this.config={...zu,...t},this.hooks=this.config.enabled?Fo(e):[]}async fire(e,t){if(!this.config.enabled)return[];let o=this.hooks.filter(i=>i.event===e);if(o.length===0)return[];let n={event:e,...t},r=[];for(let i of o){let c=await this.executeHook(i,n);if(r.push(c),c.action==="deny")break}return r}async shouldAllow(e,t){return!(await this.fire(e,t)).some(n=>n.action==="deny")}getHooks(){return[...this.hooks]}reload(e){this.hooks=this.config.enabled?Fo(e):[]}async executeHook(e,t){let o=Date.now();return new Promise(n=>{let{command:r,args:i}=this.getExecutor(e),c=(0,Xu.spawn)(r,[...i,e.scriptPath],{stdio:["pipe","pipe","pipe"],timeout:this.config.timeoutMs,env:{...process.env,MC_HOOK_EVENT:t.event,MC_WORKSPACE:t.workspace,MC_SESSION_ID:t.sessionId||""}}),u="",d="",p=!1;c.stdout?.on("data",m=>{u+=m.toString()}),c.stderr?.on("data",m=>{d+=m.toString()});let f=JSON.stringify(t);c.stdin?.write(f),c.stdin?.end(),c.on("error",m=>{n({hook:e,exitCode:-1,action:"allow",stdout:u,stderr:m.message,durationMs:Date.now()-o,timedOut:!1})}),c.on("close",m=>{let g=m??0;n({hook:e,exitCode:g,action:p?"allow":Vu(g),stdout:u,stderr:d,durationMs:Date.now()-o,timedOut:p})}),setTimeout(()=>{c.killed||(p=!0,c.kill("SIGTERM"),setTimeout(()=>{c.killed||c.kill("SIGKILL")},2e3))},this.config.timeoutMs)})}getExecutor(e){switch(e.scriptType){case"sh":return{command:"/bin/sh",args:[]};case"ps1":return{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","Bypass","-File"]};case"cmd":return{command:"cmd.exe",args:["/c"]};case"js":return{command:"node",args:[]};case"py":return{command:this.platform==="windows"?"python":"python3",args:[]};default:return{command:e.scriptPath,args:[]}}}}});function Zu(s,e=60){if(!Ot.ansi){console.log(`
|
|
119
125
|
${s}
|
|
120
|
-
${"\u2500".repeat(e)}`);return}let t="\u2500".repeat(Math.max(0,e-s.length-4));console.log(""),console.log(` ${be.accent("\u2500\u2500")} ${be.bold(s)} ${be.accent(t)}`)}function
|
|
121
|
-
`)){let n=o.match(/^(\w+)\s*:\s*(.+)$/);if(!n)continue;let[,r,i]=n;switch(r){case"name":t.name=i.trim();break;case"description":t.description=i.trim();break;case"trigger":t.trigger=i.trim();break;case"priority":t.priority=parseInt(i.trim(),10);break;case"enabled":t.enabled=i.trim().toLowerCase()!=="false";break}}return{meta:t,body:e[2].trim()}}function
|
|
126
|
+
${"\u2500".repeat(e)}`);return}let t="\u2500".repeat(Math.max(0,e-s.length-4));console.log(""),console.log(` ${be.accent("\u2500\u2500")} ${be.bold(s)} ${be.accent(t)}`)}function ed(s,e){let t=" "+s.map(n=>{let r=n.header;return Qu(r,n.width,n.align||"left")}).join(" ");console.log(Ot.ansi?be.dim(t):t);let o=" "+s.map(n=>"\u2500".repeat(n.width)).join("\u2500\u2500");console.log(Ot.ansi?be.dim(o):o);for(let n of e){let r=" "+n.cells.map((i,c)=>{let u=s[c];return Qu(i,u.width,u.align||"left")}).join(" ");n.dim&&Ot.ansi?r=be.dim(r):n.highlight&&Ot.ansi&&(r=be.accent(r)),console.log(r)}}function Qu(s,e,t){let o=Fy(s),n=Math.max(0,e-o.length);switch(t){case"right":return" ".repeat(n)+s;case"center":return" ".repeat(Math.floor(n/2))+s+" ".repeat(Math.ceil(n/2));default:return s+" ".repeat(n)}}function _a(s){console.log(Ot.ansi?` ${be.dim(s)}`:` ${s}`)}function td(s){return s>=1e6?`${(s/1e6).toFixed(s%1e6===0?0:1)}M`:s>=1e3?`${(s/1e3).toFixed(s%1e3===0?0:1)}K`:s.toString()}function Ea(s){return s===0?Ot.ansi?be.success("Free"):"Free":`$${s.toFixed(s<1?4:2)}`}function Fy(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}function Ys(){console.log("")}var Ey,be,Ot,mx,fx,od=G(()=>{"use strict";W();_e();Ey=b(require("node:readline"),1),be={navy:a.hex("#051E50"),teal:a.hex("#A3CAD3"),accent:a.hex("#6B8DD6"),success:a.hex("#4ADE80"),warning:a.hex("#FBBF24"),error:a.hex("#F87171"),dim:a.dim,bold:a.bold,muted:a.gray},Ot=I(),mx=H(Ot),fx=Oe(Ot);l(Zu,"sectionHeader");l(ed,"printTable");l(Qu,"padCell");l(_a,"hint");l(td,"formatTokens");l(Ea,"formatCost");l(Fy,"stripAnsi");l(Ys,"blank")});function wt(s){if(s==="auto")return"auto";let e=s.toLowerCase(),t=It.find(r=>r.id===e);if(t)return t.id;let o=It.find(r=>r.aliases.some(i=>i.toLowerCase()===e));if(o)return o.id;let n=It.find(r=>r.displayName.toLowerCase().includes(e));return n?n.id:s}function lr(s){let e=wt(s);return It.find(t=>t.id===e)??null}function Ty(s,e){let t=wt(s),o=It.find(u=>u.id===t);if(!o)return{allowed:!0,model:t};if(!o.requiredPlan)return{allowed:!0,model:t};let n=(e||"free").toLowerCase(),r=["free","pro","team","enterprise"],i=r.indexOf(n),c=r.indexOf(o.requiredPlan);return{allowed:i>=c,requiredPlan:o.requiredPlan,model:t}}function Xs(s,e,t,o=0){let n=It.find(u=>u.id===s);if(!n)return 0;let r=e/1e6*n.costInputPerM,i=t/1e6*n.costOutputPerM,c=o/1e6*n.costOutputPerM;return r+i+c}function Fa(s){let e=I().ansi,t=I().emoji;Zu("Available Models"),Ys();let o=[{header:"Model",width:24},{header:"Provider",width:12},{header:"Context",width:10,align:"right"},{header:"Speed",width:10},{header:"In / Out",width:16},{header:"Features",width:14}],n=It.map(r=>{let i=Ty(r.id,s),c=!i.allowed,d={monkeyscode:e?be.accent("MonkeysCode"):"MonkeysCode",anthropic:e?a.hex("#D97757")("Anthropic"):"Anthropic",google:e?a.hex("#4285F4")("Google"):"Google",openai:e?a.hex("#74AA9C")("OpenAI"):"OpenAI"}[r.provider]||r.provider,p=r.speed==="fast"?t?"\u26A1 Fast":"Fast":t?"\u{1F9E0} Deep":"Deep",f=r.costInputPerM===0?e?be.success("Free"):"Free":`${Ea(r.costInputPerM)} / ${Ea(r.costOutputPerM)}`,m=[];r.thinking&&m.push(t?"\u{1F4AD} Think":"Think"),c&&m.push(e?be.warning(`\u{1F512} ${i.requiredPlan}+`):`[${i.requiredPlan}+]`);let g=m.join(" ");return{cells:[e?c?be.dim(r.displayName):a.bold(r.displayName):r.displayName,d,td(r.contextWindow),p,f,g],dim:c}});if(ed(o,n),Ys(),e){console.log(` ${be.dim("Aliases:")}`);for(let r of It)if(r.aliases.length>0){let i=r.aliases.map(c=>be.accent(c)).join(be.dim(", "));console.log(` ${be.dim(" "+r.displayName+":")} ${i}`)}}else{console.log(" Aliases:");for(let r of It)r.aliases.length>0&&console.log(` ${r.displayName}: ${r.aliases.join(", ")}`)}Ys(),_a("Use --model <name|alias> to select a model"),_a("Use --model auto for smart routing based on task complexity"),Ys()}var It,ur=G(()=>{"use strict";W();_e();od();It=[{id:"capuchin-reason",displayName:"monkeyscode-default",aliases:["default","capuchin","mc"],contextWindow:2e5,speed:"fast",costInputPerM:0,costOutputPerM:0,thinking:!1,requiredPlan:null,provider:"monkeyscode"},{id:"claude-sonnet-4-20250514",displayName:"claude-sonnet-4",aliases:["sonnet","claude-sonnet","sonnet4"],contextWindow:2e5,speed:"fast",costInputPerM:3,costOutputPerM:15,thinking:!1,requiredPlan:null,provider:"anthropic"},{id:"claude-opus-4-6-thinking",displayName:"claude-opus-4",aliases:["opus","claude-opus","opus4"],contextWindow:2e5,speed:"slow",costInputPerM:15,costOutputPerM:75,thinking:!0,requiredPlan:"pro",provider:"anthropic"},{id:"gemini-2.5-pro",displayName:"gemini-2.5-pro",aliases:["gemini","gemini-pro","gemini25"],contextWindow:1e6,speed:"fast",costInputPerM:1.25,costOutputPerM:10,thinking:!0,requiredPlan:null,provider:"google"},{id:"gpt-4.1",displayName:"gpt-4.1",aliases:["gpt4","gpt","gpt41"],contextWindow:1e6,speed:"fast",costInputPerM:2,costOutputPerM:8,thinking:!1,requiredPlan:null,provider:"openai"}];l(wt,"resolveModelAlias");l(lr,"getModelInfo");l(Ty,"checkModelAccess");l(Xs,"estimateCost");l(Fa,"printModelList")});function sd(s,e,t){let o=lr(s),n=o?.provider||"monkeyscode",r=e.providerKeys||{};return!o&&e.customEndpoint?{url:`${e.customEndpoint.replace(/\/$/,"")}/v1/chat/completions`,headers:{"Content-Type":"application/json",...e.customEndpointKey?{Authorization:`Bearer ${e.customEndpointKey}`}:{}},isDirect:!0,provider:"custom",isAnthropicFormat:!1}:n==="anthropic"&&r.anthropic?{url:`${Ta.anthropic}/v1/messages`,headers:{"Content-Type":"application/json","x-api-key":r.anthropic,"anthropic-version":"2023-06-01"},isDirect:!0,provider:"anthropic",isAnthropicFormat:!0}:n==="openai"&&r.openai?{url:`${Ta.openai}/v1/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.openai}`},isDirect:!0,provider:"openai",isAnthropicFormat:!1}:n==="google"&&r.google?{url:`${Ta.google}/v1beta/openai/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.google}`},isDirect:!0,provider:"google",isAnthropicFormat:!1}:{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...t},isDirect:!1,provider:n==="monkeyscode"?"proxy":`proxy (${n})`,isAnthropicFormat:!1}}var Ta,nd=G(()=>{"use strict";ur();Ta={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"};l(sd,"resolveModelRoute")});var rd=G(()=>{"use strict"});var Pa={};Ae(Pa,{buildSkillsContext:()=>Aa,listAllSkills:()=>Oy,loadSkills:()=>id});function Ay(s){let e=s.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!e)return{meta:{},body:s.trim()};let t={};for(let o of e[1].split(`
|
|
127
|
+
`)){let n=o.match(/^(\w+)\s*:\s*(.+)$/);if(!n)continue;let[,r,i]=n;switch(r){case"name":t.name=i.trim();break;case"description":t.description=i.trim();break;case"trigger":t.trigger=i.trim();break;case"priority":t.priority=parseInt(i.trim(),10);break;case"enabled":t.enabled=i.trim().toLowerCase()!=="false";break}}return{meta:t,body:e[2].trim()}}function Py(s){return!s||s==="always"?{type:"always"}:s==="manual"?{type:"manual"}:s.startsWith("language:")?{type:"language",languages:s.slice(9).split(",").map(e=>e.trim())}:s.startsWith("framework:")?{type:"framework",frameworks:s.slice(10).split(",").map(e=>e.trim())}:s.startsWith("file:")?{type:"file_pattern",patterns:s.slice(5).split(",").map(e=>e.trim())}:s.startsWith("command:")?{type:"command",commands:s.slice(8).split(",").map(e=>e.trim())}:{type:"always"}}function My(s,e,t){let o=io.join(s,"skill.md");if(!jt.existsSync(o))return null;try{let n=jt.readFileSync(o,"utf8"),{meta:r,body:i}=Ay(n);return i?{id:`${t}:${e}`,name:r.name||e.replace(/[-_]/g," ").replace(/\b\w/g,c=>c.toUpperCase()),description:r.description||`Skill loaded from ${t} directory.`,source:t,systemPrompt:i,trigger:Py(r.trigger),enabled:r.enabled!==!1,priority:r.priority??50,filePath:o}:null}catch{return null}}function dr(s,e){if(!jt.existsSync(s))return[];try{return jt.readdirSync(s).filter(t=>{let o=io.join(s,t);return jt.statSync(o).isDirectory()}).map(t=>My(io.join(s,t),t,e)).filter(t=>t!==null)}catch{return[]}}function id(s){let e=io.join(s,".monkeyscode","skills"),t=io.join(Ra.homedir(),".monkeyscode","skills"),o=dr(t,"global"),n=dr(e,"project"),r=new Map;for(let i of o)r.set(i.name.toLowerCase(),i);for(let i of n)r.set(i.name.toLowerCase(),i);return Array.from(r.values()).filter(i=>i.enabled).sort((i,c)=>c.priority-i.priority)}function Aa(s){let e=id(s);if(e.length===0)return null;let t=[],o=0;for(let n of e){let r=Math.ceil(n.systemPrompt.length/4);if(o+r>2e3)break;t.push(`### Skill: ${n.name}
|
|
122
128
|
${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
123
129
|
|
|
124
|
-
`):null}function
|
|
130
|
+
`):null}function Oy(s){let e=io.join(s,".monkeyscode","skills"),t=io.join(Ra.homedir(),".monkeyscode","skills"),o=dr(t,"global"),n=dr(e,"project"),r=new Map;for(let i of o)r.set(i.name.toLowerCase(),i);for(let i of n)r.set(i.name.toLowerCase(),i);return Array.from(r.values()).sort((i,c)=>c.priority-i.priority)}var jt,io,Ra,pr=G(()=>{"use strict";jt=b(require("node:fs"),1),io=b(require("node:path"),1),Ra=b(require("node:os"),1);rd();l(Ay,"parseFrontmatter");l(Py,"parseTrigger");l(My,"loadSkillFromDir");l(dr,"scanSkillsDir");l(id,"loadSkills");l(Aa,"buildSkillsContext");l(Oy,"listAllSkills")});function ad(s){let e=Date.now(),t=[],o=[];switch(o.push("You are MonkeysCode, an expert AI coding assistant running in a terminal (CLI mode)."),o.push("You help developers by reading, writing, and modifying code files, running commands, and answering questions."),o.push(`
|
|
125
131
|
## Available Tools`),o.push("You have access to file operations (read, edit, create, delete, rename, list, search), shell commands, and git operations."),o.push("Always use the appropriate tool rather than guessing file contents. Always read a file before editing it."),o.push(`
|
|
126
132
|
## Task Tracking`),o.push("For any task with 3+ steps, maintain a checklist with todo_write: send the full list every time, keep exactly one item in_progress, and update it immediately after finishing each step."),o.push("Use ask_user when blocked on a genuine decision."),s.webEnabled&&(o.push(`
|
|
127
133
|
## Web Search`),o.push("You can search the web with web_search and fetch URL content with read_url. Use these when you need documentation, error solutions, or information not available in the workspace.")),s.mode){case"plan":o.push(`
|
|
@@ -130,44 +136,47 @@ ${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
|
130
136
|
## Mode: Accept Edits`),o.push("You may make file changes without asking. Be efficient and direct.");break;case"auto":default:o.push(`
|
|
131
137
|
## Mode: Auto`),o.push("Use your judgment on when to proceed and when to ask. For safe, reversible operations, proceed directly.");break}o.push(`
|
|
132
138
|
## Important Guidelines`),o.push("- Be concise in responses. Show code changes, not lengthy explanations."),o.push("- When editing files, use edit_file with the EXACT current content as old_string."),o.push("- When running commands, prefer non-interactive commands (add -y, --yes, etc.)."),o.push(`- Today's date: ${new Date().toISOString().split("T")[0]}`),t.push({role:"system",content:o.join(`
|
|
133
|
-
`),timestamp:e});let n=[];n.push("## Workspace Context"),n.push(`- Path: ${s.workspace}`),n.push(`- Execution: Local terminal (Node.js ${process.version})`),s.sandboxed&&n.push("- Sandbox: Active \u2014 commands run in an isolated environment");let r=
|
|
134
|
-
`),timestamp:e});let c=
|
|
139
|
+
`),timestamp:e});let n=[];n.push("## Workspace Context"),n.push(`- Path: ${s.workspace}`),n.push(`- Execution: Local terminal (Node.js ${process.version})`),s.sandboxed&&n.push("- Sandbox: Active \u2014 commands run in an isolated environment");let r=Nt.basename(s.workspace);n.push(`- Project: ${r}`);let i=Iy(s.workspace);i&&n.push(`- Stack: ${i}`),t.push({role:"system",content:n.join(`
|
|
140
|
+
`),timestamp:e});let c=Ny(s.workspace);c&&t.push({role:"system",content:`## Workspace Rules
|
|
135
141
|
|
|
136
142
|
${c}`,timestamp:e});let u=Aa(s.workspace);u&&t.push({role:"system",content:`## Active Skills
|
|
137
143
|
|
|
138
|
-
${u}`,timestamp:e});let d=
|
|
139
|
-
`),timestamp:e})}return t}function
|
|
144
|
+
${u}`,timestamp:e});let d=jy(s.workspace);if(d){let p=[];p.push("## Current State"),p.push(`- Branch: ${d.branch}${d.dirty?" (uncommitted changes)":""}`),t.push({role:"system",content:p.join(`
|
|
145
|
+
`),timestamp:e})}return t}function Iy(s){let e=[["package.json","Node.js"],["Cargo.toml","Rust"],["go.mod","Go"],["pyproject.toml","Python"],["requirements.txt","Python"],["pom.xml","Java (Maven)"],["build.gradle","Java (Gradle)"],["composer.json","PHP"],["Gemfile","Ruby"],["Package.swift","Swift"],["pubspec.yaml","Dart/Flutter"]],t=[];for(let[o,n]of e)it.existsSync(Nt.join(s,o))&&t.push(n);if(it.existsSync(Nt.join(s,"package.json")))try{let o=JSON.parse(it.readFileSync(Nt.join(s,"package.json"),"utf8")),n={...o.dependencies,...o.devDependencies};n.next?t.push("Next.js"):n.react?t.push("React"):n.vue?t.push("Vue"):n["@angular/core"]&&t.push("Angular"),n.typescript&&t.push("TypeScript")}catch{}return t.length>0?t.join(", "):null}function jy(s){try{let e=(0,Ma.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",timeout:3e3,stdio:["pipe","pipe","pipe"]}).trim(),t=(0,Ma.execSync)("git status --porcelain",{cwd:s,encoding:"utf8",timeout:3e3,stdio:["pipe","pipe","pipe"]}).trim();return{branch:e,dirty:t.length>0}}catch{return null}}function Ny(s){let e=[];for(let o of["AGENTS.md","CLAUDE.md","GEMINI.md",".monkeyscode/AGENTS.md"]){let n=Nt.join(s,o);if(it.existsSync(n))try{let r=it.readFileSync(n,"utf8");r.trim()&&e.push(`### ${o}
|
|
140
146
|
|
|
141
|
-
${r}`)}catch{}}let t=
|
|
147
|
+
${r}`)}catch{}}let t=Nt.join(s,".monkeyscode","rules");if(it.existsSync(t))try{let o=it.readdirSync(t).filter(n=>n.endsWith(".md")).sort();for(let n of o){let r=it.readFileSync(Nt.join(t,n),"utf8");r.trim()&&e.push(`### ${n}
|
|
142
148
|
|
|
143
149
|
${r}`)}}catch{}return e.length>0?e.join(`
|
|
144
150
|
|
|
145
151
|
---
|
|
146
152
|
|
|
147
|
-
`):null}var it,
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
...[
|
|
152
|
-
`)[0].slice(0,
|
|
153
|
-
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-io(u)}}function pr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var Ia,fr=G(()=>{"use strict";l(Oa,"estimateTokens");l(io,"estimateContextTokens");l(mr,"resolveContextWindow");Ia=new Map;l(cd,"updateModelCatalog");l(ld,"shouldCompact");l(ja,"compactMessages");l(pr,"totalChars")});var Zo={};Re(Zo,{AgentLoop:()=>Se});var ud,By,Se,Je=G(()=>{"use strict";ud=require("node:events");Fu();Au();Mu();$a();Ca();sd();Z();ad();fr();By=1/0,Se=class extends ud.EventEmitter{static{l(this,"AgentLoop")}opts;toolExecutor;abortController;state;messages=[];filesModified=new Set;contextWindow;_approvalResolve=null;_userInputResolve=null;_hookRunner;_insideThinkTag=!1;constructor(e){if(super(),this.opts=e,this.abortController=new AbortController,this.toolExecutor=new tr({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new os(ir(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new To(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=mr(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||By;this.updateState({status:"streaming"}),this._hookRunner.fire("SessionStart",{workspace:this.opts.workspace,data:{prompt:e,model:this.opts.model,mode:this.opts.mode}}).catch(()=>{}),this.messages=id({workspace:this.opts.workspace,mode:this.opts.mode,model:this.opts.model,sandboxed:this.opts.sandboxed||!1,webEnabled:this.opts.webEnabled!==!1}),this.messages.push({role:"user",content:e,timestamp:Date.now()});try{for(let r=0;r<o;r++){if(this.abortController.signal.aborted){this.updateState({status:"cancelled"});break}this.updateState({status:"streaming",turns:r+1}),this.emitEvent({type:"streaming_start"});let i=io(this.messages);if(ld(i,this.contextWindow)){let u=ja(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=io(this.messages);this.emitEvent({type:"context_compacted",elided:u.elided,savedTokens:u.savedTokens,contextUsed:d,contextWindow:this.contextWindow})}}let c=await this.streamCompletion();if(!c){this.emitEvent({type:"run_error",error:"No response from model"}),this.updateState({status:"error",error:"No response from model"});break}if(this.messages.push(c),this.emitEvent({type:"streaming_end",content:c.content}),c.tool_calls&&c.tool_calls.length>0){let u=new Set(["read_file","list_dir","grep_search","web_search","read_url","get_file_info","codebase_search","find_symbol"]),d=c.tool_calls.filter(m=>m.name==="ask_user"),p=c.tool_calls.filter(m=>m.name!=="ask_user"&&u.has(m.name)),f=c.tool_calls.filter(m=>m.name!=="ask_user"&&!u.has(m.name));for(let m of d){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments});let g=m.arguments.question||"What would you like to do?";this.updateState({status:"waiting_user_input"}),this.emitEvent({type:"ask_user",question:g});let h=await this.waitForUserInput();this.messages.push({role:"tool",content:`User response: ${h}`,tool_call_id:m.id,name:m.name,timestamp:Date.now()}),this.emitEvent({type:"tool_call_result",name:m.name,result:`User: ${h}`})}if(p.length>0){for(let g of p)this.emitEvent({type:"tool_call_start",name:g.name,args:g.arguments});this.updateState({status:"tool_executing",currentToolCall:`${p.length} parallel reads`});let m=await Promise.all(p.map(async g=>{let h=await this.toolExecutor.execute(g.name,g.arguments);return{toolCall:g,result:h}}));for(let{toolCall:g,result:h}of m)g.result=h.output,this.emitEvent({type:"tool_call_result",name:g.name,result:h.output}),this.messages.push({role:"tool",content:h.output,tool_call_id:g.id,name:g.name,timestamp:Date.now()})}for(let m of f){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments}),m.name==="todo_write"&&m.arguments.todos&&this.emitEvent({type:"todo_update",todos:m.arguments.todos});let g=await this._hookRunner.fire("PreToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments}});if(g.some(k=>k.action==="deny")){let k=g.find(S=>S.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${k}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let b=await this.toolExecutor.execute(m.name,m.arguments);if(b.wroteFiles&&b.touchedFiles)for(let k of b.touchedFiles)this.filesModified.add(k);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:b.output.slice(0,1e3),wroteFiles:b.wroteFiles}}).catch(()=>{}),m.result=b.output,this.emitEvent({type:"tool_call_result",name:m.name,result:b.output}),this.messages.push({role:"tool",content:b.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=ja(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=io(this.messages);return{used:e,window:this.contextWindow,pct:this.contextWindow>0?Math.min(100,Math.round(e/this.contextWindow*100)):0,messageCount:this.messages.length}}getConversationHistory(){return this.messages.map(e=>({role:e.role,content:e.content}))}async streamCompletion(){let e=Ru(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map($=>({role:$.role,content:$.content,...$.tool_calls?{tool_calls:$.tool_calls.map(F=>({id:F.id,type:"function",function:{name:F.name,arguments:JSON.stringify(F.arguments)}}))}:{},...$.tool_call_id?{tool_call_id:$.tool_call_id}:{},...$.name?{name:$.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=J(),i=od(this.opts.model,r,t),c;try{c=await fetch(i.url,{method:"POST",headers:i.headers,body:JSON.stringify(o),signal:this.abortController.signal})}catch($){if($ instanceof Error&&$.name==="AbortError")return null;throw $}if(!c.ok){let $=await c.text();throw c.status===401?new Error("Authentication failed \u2014 run `mc auth login` to authenticate."):c.status===403?new Error("Access denied \u2014 your plan may not include this model, or your quota is exhausted."):c.status===429?new Error("Rate limited \u2014 please wait a moment and try again."):new Error(`Model API error ${c.status}: ${$}`)}let u="",d=new er,p="",f=!1,m="",g="<think>",h="</think>",b=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),k=l($=>{f?(m+=$,h.startsWith(m)?m===h&&(f=!1,m=""):(m="",$==="<"&&(m="<"))):$==="<"&&!m?m="<":m?(m+=$,g.startsWith(m)?m===g&&(f=!0,m=""):h.startsWith(m)?m===h&&(m=""):(p+=m,m="")):p+=$},"feedChar");for await(let $ of Eu(c)){if(!$.choices||$.choices.length===0){$.usage&&this.updateState({tokensIn:this.state.tokensIn+($.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+($.usage.completion_tokens||0),tokensCached:this.state.tokensCached+($.usage.prompt_tokens_details?.cached_tokens||0)});continue}let F=$.choices[0];if(F.delta?.content){u+=F.delta.content;for(let j of F.delta.content)k(j);b()}if(F.delta?.tool_calls&&d.feed(F.delta.tool_calls),F.finish_reason==="tool_calls"||F.finish_reason==="stop")break}m&&!f&&(p+=m),b();let S=d.flush(),E={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return S.length>0&&(E.tool_calls=S.map($=>{let F={};try{F=JSON.parse($.arguments)}catch{F={_raw:$.arguments}}return{id:$.id,name:$.name,arguments:F}})),E}getAuthHeaders(){let e={Authorization:`Bearer ${this.opts.token}`};return this.opts.userId&&(e["X-User-Id"]=this.opts.userId),this.opts.orgId&&(e["X-Org-Id"]=this.opts.orgId),e}async waitForUserInput(){return new Promise(e=>{this._userInputResolve=e})}updateState(e){Object.assign(this.state,e),this.emitEvent({type:"state_update",state:{...this.state}})}emitEvent(e){this.emit("event",e)}}});var Ut=ce((C$,xd)=>{"use strict";var vd=["nodebuffer","arraybuffer","fragments"],Sd=typeof Blob<"u";Sd&&vd.push("blob");xd.exports={BINARY_TYPES:vd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Sd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var Ys=ce((E$,xr)=>{"use strict";var{EMPTY_BUFFER:n0}=Ut(),Wa=Buffer[Symbol.species];function r0(s,e){if(s.length===0)return n0;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),o=0;for(let n=0;n<s.length;n++){let r=s[n];t.set(r,o),o+=r.length}return o<e?new Wa(t.buffer,t.byteOffset,o):t}l(r0,"concat");function $d(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l($d,"_mask");function Cd(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(Cd,"_unmask");function i0(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(i0,"toArrayBuffer");function Ha(s){if(Ha.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Wa(s):ArrayBuffer.isView(s)?e=new Wa(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ha.readOnly=!1),e}l(Ha,"toBuffer");xr.exports={concat:r0,mask:$d,toArrayBuffer:i0,toBuffer:Ha,unmask:Cd};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");xr.exports.mask=function(e,t,o,n,r){r<48?$d(e,t,o,n,r):s.mask(e,t,o,n,r)},xr.exports.unmask=function(e,t){e.length<32?Cd(e,t):s.unmask(e,t)}}catch{}});var Fd=ce((T$,Ed)=>{"use strict";var _d=Symbol("kDone"),Ga=Symbol("kRun"),qa=class{static{l(this,"Limiter")}constructor(e){this[_d]=()=>{this.pending--,this[Ga]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ga]()}[Ga](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[_d])}}};Ed.exports=qa});var as=ce((A$,Pd)=>{"use strict";var Xs=require("zlib"),Td=Ys(),a0=Fd(),{kStatusCode:Rd}=Ut(),c0=Buffer[Symbol.species],l0=Buffer.from([0,0,255,255]),Cr=Symbol("permessage-deflate"),Wt=Symbol("total-length"),rs=Symbol("callback"),co=Symbol("buffers"),is=Symbol("error"),$r,Va=class{static{l(this,"PerMessageDeflate")}constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!$r){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;$r=new a0(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[rs];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,o=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&(typeof n.client_max_window_bits=="number"?t.clientMaxWindowBits>n.client_max_window_bits:!n.client_max_window_bits)));if(!o)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(o.server_no_context_takeover=!0),t.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(o.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?o.client_max_window_bits=t.clientMaxWindowBits:(o.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(o=>{let n=t[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);t[o]=n})}),e}decompress(e,t,o){$r.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){$r.add(n=>{this._compress(e,t,(r,i)=>{n(),o(r,i)})})}_decompress(e,t,o){let n=this._isServer?"client":"server";if(!this._inflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?Xs.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=Xs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Cr]=this,this._inflate[Wt]=0,this._inflate[co]=[],this._inflate.on("error",d0),this._inflate.on("data",Ad)}this._inflate[rs]=o,this._inflate.write(e),t&&this._inflate.write(l0),this._inflate.flush(()=>{let r=this._inflate[is];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Td.concat(this._inflate[co],this._inflate[Wt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Wt]=0,this._inflate[co]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(e,t,o){let n=this._isServer?"server":"client";if(!this._deflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?Xs.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=Xs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Wt]=0,this._deflate[co]=[],this._deflate.on("data",u0)}this._deflate[rs]=o,this._deflate.write(e),this._deflate.flush(Xs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Td.concat(this._deflate[co],this._deflate[Wt]);t&&(r=new c0(r.buffer,r.byteOffset,r.length-4)),this._deflate[rs]=null,this._deflate[Wt]=0,this._deflate[co]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Pd.exports=Va;function u0(s){this[co].push(s),this[Wt]+=s.length}l(u0,"deflateOnData");function Ad(s){if(this[Wt]+=s.length,this[Cr]._maxPayload<1||this[Wt]<=this[Cr]._maxPayload){this[co].push(s);return}this[is]=new RangeError("Max payload size exceeded"),this[is].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[is][Rd]=1009,this.removeListener("data",Ad),this.reset()}l(Ad,"inflateOnData");function d0(s){if(this[Cr]._inflate=null,this[is]){this[rs](this[is]);return}s[Rd]=1007,this[rs](s)}l(d0,"inflateOnError")});var cs=ce((M$,_r)=>{"use strict";var{isUtf8:Md}=require("buffer"),{hasBlob:p0}=Ut(),m0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function f0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(f0,"isValidStatusCode");function za(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}l(za,"_isValidUTF8");function g0(s){return p0&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(g0,"isBlob");_r.exports={isBlob:g0,isValidStatusCode:f0,isValidUTF8:za,tokenChars:m0};if(Md)_r.exports.isValidUTF8=function(s){return s.length<24?za(s):Md(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");_r.exports.isValidUTF8=function(e){return e.length<32?za(e):s(e)}}catch{}});var Qa=ce((I$,Ud)=>{"use strict";var{Writable:h0}=require("stream"),Od=as(),{BINARY_TYPES:y0,EMPTY_BUFFER:Id,kStatusCode:b0,kWebSocket:w0}=Ut(),{concat:Ja,toArrayBuffer:k0,unmask:D0}=Ys(),{isValidStatusCode:v0,isValidUTF8:jd}=cs(),Er=Buffer[Symbol.species],Ke=0,Nd=1,Ld=2,Bd=3,Ka=4,Ya=5,Fr=6,Xa=class extends h0{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||y0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[w0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ke}_write(e,t,o){if(this._opcode===8&&this._state==Ke)return o();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){o(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(o)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new Er(o.buffer,o.byteOffset+e,o.length-e),new Er(o.buffer,o.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let o=this._buffers[0],n=t.length-e;e>=o.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(o.buffer,o.byteOffset,e),n),this._buffers[0]=new Er(o.buffer,o.byteOffset+e,o.length-e)),e-=o.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ke:this.getInfo(e);break;case Nd:this.getPayloadLength16(e);break;case Ld:this.getPayloadLength64(e);break;case Bd:this.getMask();break;case Ka:this.getData(e);break;case Ya:case Fr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let o=(t[0]&64)===64;if(o&&!this._extensions[Od.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Nd:this._payloadLength===127?this._state=Ld:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),o=t.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=o*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Bd:this._state=Ka}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ka}getData(e){let t=Id;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&D0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(o);return}if(this._compressed){this._state=Ya,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Od.extensionName].decompress(e,this._fin,(n,r)=>{if(n)return t(n);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(i);return}this._fragments.push(r)}this.dataMessage(t),this._state===Ke&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ke;return}let t=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Ja(o,t):this._binaryType==="arraybuffer"?n=k0(Ja(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Ke):(this._state=Fr,setImmediate(()=>{this.emit("message",n,!0),this._state=Ke,this.startLoop(e)}))}else{let n=Ja(o,t);if(!this._skipUTF8Validation&&!jd(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===Ya||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Ke):(this._state=Fr,setImmediate(()=>{this.emit("message",n,!1),this._state=Ke,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Id),this.end();else{let o=e.readUInt16BE(0);if(!v0(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new Er(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!jd(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(r);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=Ke;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ke):(this._state=Fr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ke,this.startLoop(t)}))}createError(e,t,o,n,r){this._loop=!1,this._errored=!0;let i=new e(o?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=r,i[b0]=n,i}};Ud.exports=Xa});var tc=ce((L$,Gd)=>{"use strict";var{Duplex:N$}=require("stream"),{randomFillSync:S0}=require("crypto"),{types:{isUint8Array:x0}}=require("util"),Wd=as(),{EMPTY_BUFFER:$0,kWebSocket:C0,NOOP:_0}=Ut(),{isBlob:ls,isValidStatusCode:E0}=cs(),{mask:Hd,toBuffer:Ao}=Ys(),Ye=Symbol("kByteLength"),F0=Buffer.alloc(4),Tr=8*1024,Po,us=Tr,ct=0,T0=1,R0=2,Za=class s{static{l(this,"Sender")}constructor(e,t,o){this._extensions=t||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=_0,this[C0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||F0,t.generateMask?t.generateMask(o):(us===Tr&&(Po===void 0&&(Po=Buffer.alloc(Tr)),S0(Po,0,Tr),us=0),o[0]=Po[us++],o[1]=Po[us++],o[2]=Po[us++],o[3]=Po[us++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Ye]!==void 0?c=t[Ye]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!i);let u=c;c>=65536?(r+=8,u=127):c>125&&(r+=2,u=126);let d=Buffer.allocUnsafe(n?c+r:r);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[r-4]=o[0],d[r-3]=o[1],d[r-2]=o[2],d[r-1]=o[3],i?[d,e]:n?(Hd(e,o,d,r,c),[d]):(Hd(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=$0;else{if(typeof e!="number"||!E0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)r=Buffer.allocUnsafe(2),r.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(r=Buffer.allocUnsafe(2+c),r.writeUInt16BE(e,0),typeof t=="string")r.write(t,2);else if(x0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Ye]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,r,!1,i,n]):this.sendFrame(s.frame(r,i),n)}ping(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):ls(e)?(n=e.size,r=!1):(e=Ao(e),n=e.length,r=Ao.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ye]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};ls(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ct?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}pong(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):ls(e)?(n=e.size,r=!1):(e=Ao(e),n=e.length,r=Ao.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ye]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};ls(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ct?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[Wd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):ls(e)?(c=e.size,u=!1):(e=Ao(e),c=e.length,u=Ao.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=n._threshold),this._compress=i):(i=!1,r=0),t.fin&&(this._firstFragment=!0);let d={[Ye]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};ls(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Ye],this._state=R0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(ec,this,c,n);return}this._bufferedBytes-=o[Ye];let i=Ao(r);t?this.dispatch(i,t,o,n):(this._state=ct,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(A0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[Wd.extensionName];this._bufferedBytes+=o[Ye],this._state=T0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");ec(this,u,n);return}this._bufferedBytes-=o[Ye],this._state=ct,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ye],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ye],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Gd.exports=Za;function ec(s,e,t){typeof t=="function"&&t(e);for(let o=0;o<s._queue.length;o++){let n=s._queue[o],r=n[n.length-1];typeof r=="function"&&r(e)}}l(ec,"callCallbacks");function A0(s,e,t){ec(s,e,t),s.onerror(e)}l(A0,"onError")});var Zd=ce((U$,Qd)=>{"use strict";var{kForOnEventAttribute:Qs,kListener:oc}=Ut(),qd=Symbol("kCode"),Vd=Symbol("kData"),zd=Symbol("kError"),Jd=Symbol("kMessage"),Kd=Symbol("kReason"),ds=Symbol("kTarget"),Yd=Symbol("kType"),Xd=Symbol("kWasClean"),Ht=class{static{l(this,"Event")}constructor(e){this[ds]=null,this[Yd]=e}get target(){return this[ds]}get type(){return this[Yd]}};Object.defineProperty(Ht.prototype,"target",{enumerable:!0});Object.defineProperty(Ht.prototype,"type",{enumerable:!0});var Mo=class extends Ht{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[qd]=t.code===void 0?0:t.code,this[Kd]=t.reason===void 0?"":t.reason,this[Xd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[qd]}get reason(){return this[Kd]}get wasClean(){return this[Xd]}};Object.defineProperty(Mo.prototype,"code",{enumerable:!0});Object.defineProperty(Mo.prototype,"reason",{enumerable:!0});Object.defineProperty(Mo.prototype,"wasClean",{enumerable:!0});var ps=class extends Ht{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[zd]=t.error===void 0?null:t.error,this[Jd]=t.message===void 0?"":t.message}get error(){return this[zd]}get message(){return this[Jd]}};Object.defineProperty(ps.prototype,"error",{enumerable:!0});Object.defineProperty(ps.prototype,"message",{enumerable:!0});var Zs=class extends Ht{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[Vd]=t.data===void 0?null:t.data}get data(){return this[Vd]}};Object.defineProperty(Zs.prototype,"data",{enumerable:!0});var P0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[Qs]&&n[oc]===e&&!n[Qs])return;let o;if(s==="message")o=l(function(r,i){let c=new Zs("message",{data:i?r:r.toString()});c[ds]=this,Rr(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new Mo("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ds]=this,Rr(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new ps("error",{error:r,message:r.message});i[ds]=this,Rr(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Ht("open");r[ds]=this,Rr(e,this,r)},"onOpen");else return;o[Qs]=!!t[Qs],o[oc]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[oc]===e&&!t[Qs]){this.removeListener(s,t);break}}};Qd.exports={CloseEvent:Mo,ErrorEvent:ps,Event:Ht,EventTarget:P0,MessageEvent:Zs};function Rr(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(Rr,"callListener")});var Ar=ce((H$,ep)=>{"use strict";var{tokenChars:en}=cs();function kt(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(kt,"push");function M0(s){let e=Object.create(null),t=Object.create(null),o=!1,n=!1,r=!1,i,c,u=-1,d=-1,p=-1,f=0;for(;f<s.length;f++)if(d=s.charCodeAt(f),i===void 0)if(p===-1&&en[d]===1)u===-1&&(u=f);else if(f!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);d===44?(kt(e,g,t),t=Object.create(null)):i=g,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&en[d]===1)u===-1&&(u=f);else if(d===32||d===9)p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),kt(t,s.slice(u,p),!0),d===44&&(kt(e,i,t),t=Object.create(null),i=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=s.slice(u,f),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(n){if(en[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(en[d]===1)u===-1&&(u=f);else if(d===34&&u!==-1)r=!1,p=f;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&s.charCodeAt(f-1)===61)r=!0;else if(p===-1&&en[d]===1)u===-1&&(u=f);else if(u!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);o&&(g=g.replace(/\\/g,""),o=!1),kt(t,c,g),d===44&&(kt(e,i,t),t=Object.create(null),i=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(u===-1||r||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=s.slice(u,p);return i===void 0?kt(e,m,t):(c===void 0?kt(t,m,!0):o?kt(t,c,m.replace(/\\/g,"")):kt(t,c,m),kt(e,i,t)),e}l(M0,"parse");function O0(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(o=>[e].concat(Object.keys(o).map(n=>{let r=o[n];return Array.isArray(r)||(r=[r]),r.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}l(O0,"format");ep.exports={format:O0,parse:M0}});var Ir=ce((z$,pp)=>{"use strict";var I0=require("events"),j0=require("https"),N0=require("http"),sp=require("net"),L0=require("tls"),{randomBytes:B0,createHash:U0}=require("crypto"),{Duplex:q$,Readable:V$}=require("stream"),{URL:sc}=require("url"),lo=as(),W0=Qa(),H0=tc(),{isBlob:G0}=cs(),{BINARY_TYPES:tp,CLOSE_TIMEOUT:q0,EMPTY_BUFFER:Pr,GUID:V0,kForOnEventAttribute:nc,kListener:z0,kStatusCode:J0,kWebSocket:we,NOOP:np}=Ut(),{EventTarget:{addEventListener:K0,removeEventListener:Y0}}=Zd(),{format:X0,parse:Q0}=Ar(),{toBuffer:Z0}=Ys(),rp=Symbol("kAborted"),rc=[8,13],Gt=["CONNECTING","OPEN","CLOSING","CLOSED"],eb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends I0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=tp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(o=t,t=[]):t=[t]),ip(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){tp.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,o){let n=new W0({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),r=new H0(e,this._extensions,o.generateMask);this._receiver=n,this._sender=r,this._socket=e,n[we]=this,r[we]=this,e[we]=this,n.on("conclude",sb),n.on("drain",nb),n.on("error",rb),n.on("message",ib),n.on("ping",ab),n.on("pong",cb),r.onerror=lb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",lp),e.on("data",Or),e.on("end",up),e.on("error",dp),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[lo.extensionName]&&this._extensions[lo.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),cp(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Pr,t,o)}pong(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Pr,t,o)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(o=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[lo.extensionName]||(n.compress=!1),this._sender.send(e||Pr,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ie,"CONNECTING",{enumerable:!0,value:Gt.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:Gt.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:Gt.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:Gt.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:Gt.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:Gt.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:Gt.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:Gt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ie.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ie.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[nc])return e[z0];return null},set(e){for(let t of this.listeners(s))if(t[nc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[nc]:!0})}})});ie.prototype.addEventListener=K0;ie.prototype.removeEventListener=Y0;pp.exports=ie;function ip(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:q0,protocolVersion:rc[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=n.autoPong,s._closeTimeout=n.closeTimeout,!rc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${rc.join(", ")})`);let r;if(e instanceof sc)r=e;else try{r=new sc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let b=new SyntaxError(u);if(s._redirects===0)throw b;Mr(s,b);return}let d=i?443:80,p=B0(16).toString("base64"),f=i?j0.request:N0.request,m=new Set,g;if(n.createConnection=n.createConnection||(i?ob:tb),n.defaultPort=n.defaultPort||d,n.port=r.port||d,n.host=r.hostname.startsWith("[")?r.hostname.slice(1,-1):r.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=r.pathname+r.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(g=new lo({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=X0({[lo.extensionName]:g.offer()})),t.length){for(let b of t){if(typeof b!="string"||!eb.test(b)||m.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(b)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let b=n.path.split(":");n.socketPath=b[0],n.path=b[1]}let h;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let b=o&&o.headers;if(o={...o,headers:{}},b)for(let[k,S]of Object.entries(b))o.headers[k.toLowerCase()]=S}else if(s.listenerCount("redirect")===0){let b=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!b||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,b||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),h=s._req=f(n),s._redirects&&s.emit("redirect",s.url,h)}else h=s._req=f(n);n.timeout&&h.on("timeout",()=>{We(s,h,"Opening handshake has timed out")}),h.on("error",b=>{h===null||h[rp]||(h=s._req=null,Mr(s,b))}),h.on("response",b=>{let k=b.headers.location,S=b.statusCode;if(k&&n.followRedirects&&S>=300&&S<400){if(++s._redirects>n.maxRedirects){We(s,h,"Maximum redirects exceeded");return}h.abort();let x;try{x=new sc(k,e)}catch{let $=new SyntaxError(`Invalid URL: ${k}`);Mr(s,$);return}ip(s,x,t,o)}else s.emit("unexpected-response",h,b)||We(s,h,`Unexpected server response: ${b.statusCode}`)}),h.on("upgrade",(b,k,S)=>{if(s.emit("upgrade",b),s.readyState!==ie.CONNECTING)return;h=s._req=null;let x=b.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){We(s,k,"Invalid Upgrade header");return}let E=U0("sha1").update(p+V0).digest("base64");if(b.headers["sec-websocket-accept"]!==E){We(s,k,"Invalid Sec-WebSocket-Accept header");return}let $=b.headers["sec-websocket-protocol"],F;if($!==void 0?m.size?m.has($)||(F="Server sent an invalid subprotocol"):F="Server sent a subprotocol but none was requested":m.size&&(F="Server sent no subprotocol"),F){We(s,k,F);return}$&&(s._protocol=$);let j=b.headers["sec-websocket-extensions"];if(j!==void 0){if(!g){We(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=Q0(j)}catch{We(s,k,"Invalid Sec-WebSocket-Extensions header");return}let Y=Object.keys(ae);if(Y.length!==1||Y[0]!==lo.extensionName){We(s,k,"Server indicated an extension that was not requested");return}try{g.accept(ae[lo.extensionName])}catch{We(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[lo.extensionName]=g}s.setSocket(k,S,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(h,s):h.end()}l(ip,"initAsClient");function Mr(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Mr,"emitErrorAndClose");function tb(s){return s.path=s.socketPath,sp.connect(s)}l(tb,"netConnect");function ob(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=sp.isIP(s.host)?"":s.host),L0.connect(s)}l(ob,"tlsConnect");function We(s,e,t){s._readyState=ie.CLOSING;let o=new Error(t);Error.captureStackTrace(o,We),e.setHeader?(e[rp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Mr,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(We,"abortHandshake");function ic(s,e,t){if(e){let o=G0(e)?e.size:Z0(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Gt[s.readyState]})`);process.nextTick(t,o)}}l(ic,"sendAfterClose");function sb(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Or),process.nextTick(ap,t._socket),s===1005?t.close():t.close(s,e))}l(sb,"receiverOnConclude");function nb(){let s=this[we];s.isPaused||s._socket.resume()}l(nb,"receiverOnDrain");function rb(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Or),process.nextTick(ap,e._socket),e.close(s[J0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(rb,"receiverOnError");function op(){this[we].emitClose()}l(op,"receiverOnFinish");function ib(s,e){this[we].emit("message",s,e)}l(ib,"receiverOnMessage");function ab(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,np),e.emit("ping",s)}l(ab,"receiverOnPing");function cb(s){this[we].emit("pong",s)}l(cb,"receiverOnPong");function ap(s){s.resume()}l(ap,"resume");function lb(s){let e=this[we];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,cp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(lb,"senderOnError");function cp(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(cp,"setCloseTimer");function lp(){let s=this[we];if(this.removeListener("close",lp),this.removeListener("data",Or),this.removeListener("end",up),s._readyState=ie.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[we]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",op),s._receiver.on("finish",op))}l(lp,"socketOnClose");function Or(s){this[we]._receiver.write(s)||this.pause()}l(Or,"socketOnData");function up(){let s=this[we];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}l(up,"socketOnEnd");function dp(){let s=this[we];this.removeListener("error",dp),this.on("error",np),s&&(s._readyState=ie.CLOSING,this.destroy())}l(dp,"socketOnError")});var hp=ce((Y$,gp)=>{"use strict";var K$=Ir(),{Duplex:ub}=require("stream");function mp(s){s.emit("close")}l(mp,"emitClose");function db(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(db,"duplexOnEnd");function fp(s){this.removeListener("error",fp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(fp,"duplexOnError");function pb(s,e){let t=!0,o=new ub({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",l(function(r,i){let c=!i&&o._readableState.objectMode?r.toString():r;o.push(c)||s.pause()},"message")),s.once("error",l(function(r){o.destroyed||(t=!1,o.destroy(r))},"error")),s.once("close",l(function(){o.destroyed||o.push(null)},"close")),o._destroy=function(n,r){if(s.readyState===s.CLOSED){r(n),process.nextTick(mp,o);return}let i=!1;s.once("error",l(function(u){i=!0,r(u)},"error")),s.once("close",l(function(){i||r(n),process.nextTick(mp,o)},"close")),t&&s.terminate()},o._final=function(n){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._final(n)},"open"));return}s._socket!==null&&(s._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(s._socket.once("finish",l(function(){n()},"finish")),s.close()))},o._read=function(){s.isPaused&&s.resume()},o._write=function(n,r,i){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._write(n,r,i)},"open"));return}s.send(n,i)},o.on("end",db),o.on("error",fp),o}l(pb,"createWebSocketStream");gp.exports=pb});var ac=ce((Q$,yp)=>{"use strict";var{tokenChars:mb}=cs();function fb(s){let e=new Set,t=-1,o=-1,n=0;for(n;n<s.length;n++){let i=s.charCodeAt(n);if(o===-1&&mb[i]===1)t===-1&&(t=n);else if(n!==0&&(i===32||i===9))o===-1&&t!==-1&&(o=n);else if(i===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let c=s.slice(t,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(t===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let r=s.slice(t,n);if(e.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);return e.add(r),e}l(fb,"parse");yp.exports={parse:fb}});var xp=ce((tC,Sp)=>{"use strict";var gb=require("events"),jr=require("http"),{Duplex:eC}=require("stream"),{createHash:hb}=require("crypto"),bp=Ar(),Oo=as(),yb=ac(),bb=Ir(),{CLOSE_TIMEOUT:wb,GUID:kb,kWebSocket:Db}=Ut(),vb=/^[+/0-9A-Za-z]{22}==$/,wp=0,kp=1,vp=2,cc=class extends gb{static{l(this,"WebSocketServer")}constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:wb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=jr.createServer((o,n)=>{let r=jr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),n.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=Sb(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:l((n,r,i)=>{this.handleUpgrade(n,r,i,o)},"upgrade")})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=wp}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===vp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(tn,this);return}if(e&&this.once("close",e),this._state!==kp)if(this._state=kp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(tn,this):process.nextTick(tn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{tn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,o,n){t.on("error",Dp);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Io(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Io(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!vb.test(r)){Io(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Io(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){on(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=yb.parse(u)}catch{Io(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let m=new Oo({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=bp.parse(p);g[Oo.extensionName]&&(m.accept(g[Oo.extensionName]),f[Oo.extensionName]=m)}catch{Io(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(g,h,b,k)=>{if(!g)return on(t,h||401,b,k);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return on(t,401)}this.completeUpgrade(f,r,d,e,t,o,n)}completeUpgrade(e,t,o,n,r,i,c){if(!r.readable||!r.writable)return r.destroy();if(r[Db])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>wp)return on(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hb("sha1").update(t+kb).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(o.size){let f=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Oo.extensionName]){let f=e[Oo.extensionName].params,m=bp.format({[Oo.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
153
|
+
`):null}var it,Nt,Ma,cd=G(()=>{"use strict";it=b(require("node:fs"),1),Nt=b(require("node:path"),1),Ma=require("node:child_process");pr();l(ad,"buildSystemMessages");l(Iy,"detectProjectType");l(jy,"getGitInfo");l(Ny,"loadWorkspaceRules")});function Oa(s){return Math.ceil(s.length/4)}function ao(s,e=6e3){let t=e;for(let o of s)if(t+=Oa(o.content),o.tool_calls)for(let n of o.tool_calls)t+=Oa(JSON.stringify(n.arguments)),n.result&&(t+=Oa(n.result));return t}function fr(s,e){if(e&&e>0)return e;let t=Ia.get(s);if(t&&t>0)return t;let o=s.toLowerCase();return o.includes("capuchin")||o.includes("claude-opus")||o.includes("claude-sonnet")||o.includes("claude-haiku")||o.includes("claude-fable")||o.includes("claude")?2e5:o.includes("gpt-4o")?128e3:o.includes("gpt-4.1")?1e6:o.includes("gpt-6")||o.includes("gpt-5")||o.includes("o3")||o.includes("o4-mini")||o.includes("o4")?2e5:o.includes("gemini-3")||o.includes("gemini-2.5")||o.includes("gemini")?1e6:o.includes("codestral")?256e3:o.includes("mistral")||o.includes("llama")?128e3:o.includes("deepseek")?131072:128e3}function ld(s){Ia.clear();for(let e of s)e.id&&e.contextWindow>0&&Ia.set(e.id,e.contextWindow)}function ud(s,e,t=.85){return s>=e*t}function Ly(s,e){let t=s.split(`
|
|
154
|
+
`),o=Math.floor(e*.7),n=e-o,r=[],i=0;for(let p of t){if(i+p.length+1>o)break;r.push(p),i+=p.length+1}let c=[],u=0;for(let p=t.length-1;p>=r.length&&!(u+t[p].length+1>n);p--)c.unshift(t[p]),u+=t[p].length+1;let d=t.length-r.length-c.length;return d<=0?s:[...r,`
|
|
155
|
+
... [${d} lines trimmed from an older tool result to fit the context window \u2014 re-read the file if you still need this content] ...
|
|
156
|
+
`,...c].join(`
|
|
157
|
+
`)}function ja(s,e,t){let r=Math.max(4e3,(e||128e3)-(t||15e3)),i=Math.floor(r*.9)*4;if(mr(s)<=i)return{messages:s,elided:0,savedTokens:0};let u=s.map(D=>({...D})),d=0,p=ao(s),f=u.length-1-12;for(let D=0;D<=f;D++){let C=u[D];C.role==="tool"&&C.content&&C.content.length>6e4&&(C.content=Ly(C.content,6e4),d++)}if(mr(u)<=i)return{messages:u,elided:d,savedTokens:p-ao(u)};let m=u.filter(D=>D.role!=="system").length,g=Math.max(10,Math.floor(m*.2)),h=Math.floor((m-g)/20)*20;if(h>0){let D=0;for(let C=0;C<u.length;C++){if(u[C].role==="system")continue;if(D++,D>h)break;let x=u[C];if(D<=Math.floor(h*.75)){if(x.role==="tool"&&x.content&&x.content.length>150){let v=x.content.includes("Error")||x.content.includes("error"),E=x.content.split(`
|
|
158
|
+
`)[0].slice(0,100);x.content=v?`[error] ${E}`:`[ok] ${E}`,d++}if(x.role==="assistant"&&x.content&&x.content.length>300&&!x.tool_calls?.length&&(x.content=x.content.slice(0,200)+`
|
|
159
|
+
...[summarized]`),x.role==="assistant"&&x.tool_calls?.length){let v=x.tool_calls.map(E=>`[called ${E.name||"unknown"}]`);x.content||(x.content=v.join(", "))}}else if(x.role==="assistant"&&x.content&&x.content.length>500&&!x.tool_calls?.length&&(x.content=x.content.slice(0,400)+`
|
|
160
|
+
...[truncated]`),x.role==="tool"&&x.content&&x.content.length>500){let v=x.content.includes("Error")||x.content.includes("error"),E=x.content.split(`
|
|
161
|
+
`)[0].slice(0,150);x.content=v?`[error] ${E}`:`[ok] ${E}`,d++}}}if(mr(u)<=i)return{messages:u,elided:d,savedTokens:p-ao(u)};let y=Math.floor(i*.85),S=mr(u);for(;S>y&&u.length>6;){let D=u.findIndex(v=>v.role==="user");if(D<0)break;let C=D;for(let v=D+1;v<u.length;v++){let E=u[v];if(E.role==="user"&&!("tool_call_id"in E))break;C=v}let x=u.splice(D,C-D+1);for(let v of x)S-=v.content?.length||0,v.tool_calls&&(S-=JSON.stringify(v.tool_calls).length);d+=x.length}if(u.length<s.length){let D=["[CONVERSATION CONTEXT \u2014 older messages were summarized to fit within the token limit]","Continue working with the remaining context."],C=u[0]?.role==="system"?1:0;u.splice(C,0,{role:"user",content:D.join(`
|
|
162
|
+
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-ao(u)}}function mr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var Ia,gr=G(()=>{"use strict";l(Oa,"estimateTokens");l(ao,"estimateContextTokens");l(fr,"resolveContextWindow");Ia=new Map;l(ld,"updateModelCatalog");l(ud,"shouldCompact");l(Ly,"trimToolResult");l(ja,"compactMessages");l(mr,"totalChars")});var es={};Ae(es,{AgentLoop:()=>xe});var dd,By,xe,Ke=G(()=>{"use strict";dd=require("node:events");Tu();Pu();Ou();$a();Ca();nd();Q();cd();gr();By=1/0,xe=class extends dd.EventEmitter{static{l(this,"AgentLoop")}opts;toolExecutor;abortController;state;messages=[];filesModified=new Set;contextWindow;_approvalResolve=null;_userInputResolve=null;_hookRunner;_insideThinkTag=!1;constructor(e){if(super(),this.opts=e,this.abortController=new AbortController,this.toolExecutor=new or({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new ss(ar(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new To(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=fr(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||By;this.updateState({status:"streaming"}),this._hookRunner.fire("SessionStart",{workspace:this.opts.workspace,data:{prompt:e,model:this.opts.model,mode:this.opts.mode}}).catch(()=>{}),this.messages=ad({workspace:this.opts.workspace,mode:this.opts.mode,model:this.opts.model,sandboxed:this.opts.sandboxed||!1,webEnabled:this.opts.webEnabled!==!1}),this.messages.push({role:"user",content:e,timestamp:Date.now()});try{for(let r=0;r<o;r++){if(this.abortController.signal.aborted){this.updateState({status:"cancelled"});break}this.updateState({status:"streaming",turns:r+1}),this.emitEvent({type:"streaming_start"});let i=ao(this.messages);if(ud(i,this.contextWindow)){let u=ja(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=ao(this.messages);this.emitEvent({type:"context_compacted",elided:u.elided,savedTokens:u.savedTokens,contextUsed:d,contextWindow:this.contextWindow})}}let c=await this.streamCompletion();if(!c){this.emitEvent({type:"run_error",error:"No response from model"}),this.updateState({status:"error",error:"No response from model"});break}if(this.messages.push(c),this.emitEvent({type:"streaming_end",content:c.content}),c.tool_calls&&c.tool_calls.length>0){let u=new Set(["read_file","list_dir","grep_search","web_search","read_url","get_file_info","codebase_search","find_symbol"]),d=c.tool_calls.filter(m=>m.name==="ask_user"),p=c.tool_calls.filter(m=>m.name!=="ask_user"&&u.has(m.name)),f=c.tool_calls.filter(m=>m.name!=="ask_user"&&!u.has(m.name));for(let m of d){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments});let g=m.arguments.question||"What would you like to do?";this.updateState({status:"waiting_user_input"}),this.emitEvent({type:"ask_user",question:g});let h=await this.waitForUserInput();this.messages.push({role:"tool",content:`User response: ${h}`,tool_call_id:m.id,name:m.name,timestamp:Date.now()}),this.emitEvent({type:"tool_call_result",name:m.name,result:`User: ${h}`})}if(p.length>0){for(let g of p)this.emitEvent({type:"tool_call_start",name:g.name,args:g.arguments});this.updateState({status:"tool_executing",currentToolCall:`${p.length} parallel reads`});let m=await Promise.all(p.map(async g=>{let h=await this.toolExecutor.execute(g.name,g.arguments);return{toolCall:g,result:h}}));for(let{toolCall:g,result:h}of m)g.result=h.output,this.emitEvent({type:"tool_call_result",name:g.name,result:h.output}),this.messages.push({role:"tool",content:h.output,tool_call_id:g.id,name:g.name,timestamp:Date.now()})}for(let m of f){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments}),m.name==="todo_write"&&m.arguments.todos&&this.emitEvent({type:"todo_update",todos:m.arguments.todos});let g=await this._hookRunner.fire("PreToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments}});if(g.some(S=>S.action==="deny")){let S=g.find(D=>D.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${S}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let y=await this.toolExecutor.execute(m.name,m.arguments);if(y.wroteFiles&&y.touchedFiles)for(let S of y.touchedFiles)this.filesModified.add(S);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:y.output.slice(0,1e3),wroteFiles:y.wroteFiles}}).catch(()=>{}),m.result=y.output,this.emitEvent({type:"tool_call_result",name:m.name,result:y.output}),this.messages.push({role:"tool",content:y.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=ja(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=ao(this.messages);return{used:e,window:this.contextWindow,pct:this.contextWindow>0?Math.min(100,Math.round(e/this.contextWindow*100)):0,messageCount:this.messages.length}}getConversationHistory(){return this.messages.map(e=>({role:e.role,content:e.content}))}async streamCompletion(){let e=Au(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(v=>({role:v.role,content:v.content,...v.tool_calls?{tool_calls:v.tool_calls.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))}:{},...v.tool_call_id?{tool_call_id:v.tool_call_id}:{},...v.name?{name:v.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=K(),i=sd(this.opts.model,r,t),c;try{c=await fetch(i.url,{method:"POST",headers:i.headers,body:JSON.stringify(o),signal:this.abortController.signal})}catch(v){if(v instanceof Error&&v.name==="AbortError")return null;throw v}if(!c.ok){let v=await c.text();throw c.status===401?new Error("Authentication failed \u2014 run `mc auth login` to authenticate."):c.status===403?new Error("Access denied \u2014 your plan may not include this model, or your quota is exhausted."):c.status===429?new Error("Rate limited \u2014 please wait a moment and try again."):new Error(`Model API error ${c.status}: ${v}`)}let u="",d=new tr,p="",f=!1,m="",g="<think>",h="</think>",y=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),S=l(v=>{f?(m+=v,h.startsWith(m)?m===h&&(f=!1,m=""):(m="",v==="<"&&(m="<"))):v==="<"&&!m?m="<":m?(m+=v,g.startsWith(m)?m===g&&(f=!0,m=""):h.startsWith(m)?m===h&&(m=""):(p+=m,m="")):p+=v},"feedChar");for await(let v of Fu(c)){if(!v.choices||v.choices.length===0){v.usage&&this.updateState({tokensIn:this.state.tokensIn+(v.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(v.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(v.usage.prompt_tokens_details?.cached_tokens||0)});continue}let E=v.choices[0];if(E.delta?.content){u+=E.delta.content;for(let oe of E.delta.content)S(oe);y()}if(E.delta?.tool_calls&&d.feed(E.delta.tool_calls),E.finish_reason==="tool_calls"||E.finish_reason==="stop")break}m&&!f&&(p+=m),y();let D=d.flush(),x={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return D.length>0&&(x.tool_calls=D.map(v=>{let E={};try{E=JSON.parse(v.arguments)}catch{E={_raw:v.arguments}}return{id:v.id,name:v.name,arguments:E}})),x}getAuthHeaders(){let e={Authorization:`Bearer ${this.opts.token}`};return this.opts.userId&&(e["X-User-Id"]=this.opts.userId),this.opts.orgId&&(e["X-Org-Id"]=this.opts.orgId),e}async waitForUserInput(){return new Promise(e=>{this._userInputResolve=e})}updateState(e){Object.assign(this.state,e),this.emitEvent({type:"state_update",state:{...this.state}})}emitEvent(e){this.emit("event",e)}}});var Bt=ce((C$,$d)=>{"use strict";var Sd=["nodebuffer","arraybuffer","fragments"],xd=typeof Blob<"u";xd&&Sd.push("blob");$d.exports={BINARY_TYPES:Sd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:xd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var Zs=ce((E$,$r)=>{"use strict";var{EMPTY_BUFFER:n0}=Bt(),Wa=Buffer[Symbol.species];function r0(s,e){if(s.length===0)return n0;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),o=0;for(let n=0;n<s.length;n++){let r=s[n];t.set(r,o),o+=r.length}return o<e?new Wa(t.buffer,t.byteOffset,o):t}l(r0,"concat");function Cd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(Cd,"_mask");function _d(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(_d,"_unmask");function i0(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(i0,"toArrayBuffer");function Ha(s){if(Ha.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Wa(s):ArrayBuffer.isView(s)?e=new Wa(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ha.readOnly=!1),e}l(Ha,"toBuffer");$r.exports={concat:r0,mask:Cd,toArrayBuffer:i0,toBuffer:Ha,unmask:_d};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");$r.exports.mask=function(e,t,o,n,r){r<48?Cd(e,t,o,n,r):s.mask(e,t,o,n,r)},$r.exports.unmask=function(e,t){e.length<32?_d(e,t):s.unmask(e,t)}}catch{}});var Td=ce((T$,Fd)=>{"use strict";var Ed=Symbol("kDone"),Ga=Symbol("kRun"),qa=class{static{l(this,"Limiter")}constructor(e){this[Ed]=()=>{this.pending--,this[Ga]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ga]()}[Ga](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ed])}}};Fd.exports=qa});var cs=ce((A$,Md)=>{"use strict";var en=require("zlib"),Rd=Zs(),a0=Td(),{kStatusCode:Ad}=Bt(),c0=Buffer[Symbol.species],l0=Buffer.from([0,0,255,255]),_r=Symbol("permessage-deflate"),Ut=Symbol("total-length"),is=Symbol("callback"),lo=Symbol("buffers"),as=Symbol("error"),Cr,Va=class{static{l(this,"PerMessageDeflate")}constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Cr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cr=new a0(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[is];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,o=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&(typeof n.client_max_window_bits=="number"?t.clientMaxWindowBits>n.client_max_window_bits:!n.client_max_window_bits)));if(!o)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(o.server_no_context_takeover=!0),t.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(o.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?o.client_max_window_bits=t.clientMaxWindowBits:(o.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(o=>{let n=t[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);t[o]=n})}),e}decompress(e,t,o){Cr.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){Cr.add(n=>{this._compress(e,t,(r,i)=>{n(),o(r,i)})})}_decompress(e,t,o){let n=this._isServer?"client":"server";if(!this._inflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=en.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[_r]=this,this._inflate[Ut]=0,this._inflate[lo]=[],this._inflate.on("error",d0),this._inflate.on("data",Pd)}this._inflate[is]=o,this._inflate.write(e),t&&this._inflate.write(l0),this._inflate.flush(()=>{let r=this._inflate[as];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Rd.concat(this._inflate[lo],this._inflate[Ut]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ut]=0,this._inflate[lo]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(e,t,o){let n=this._isServer?"server":"client";if(!this._deflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=en.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Ut]=0,this._deflate[lo]=[],this._deflate.on("data",u0)}this._deflate[is]=o,this._deflate.write(e),this._deflate.flush(en.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Rd.concat(this._deflate[lo],this._deflate[Ut]);t&&(r=new c0(r.buffer,r.byteOffset,r.length-4)),this._deflate[is]=null,this._deflate[Ut]=0,this._deflate[lo]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Md.exports=Va;function u0(s){this[lo].push(s),this[Ut]+=s.length}l(u0,"deflateOnData");function Pd(s){if(this[Ut]+=s.length,this[_r]._maxPayload<1||this[Ut]<=this[_r]._maxPayload){this[lo].push(s);return}this[as]=new RangeError("Max payload size exceeded"),this[as].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[as][Ad]=1009,this.removeListener("data",Pd),this.reset()}l(Pd,"inflateOnData");function d0(s){if(this[_r]._inflate=null,this[as]){this[is](this[as]);return}s[Ad]=1007,this[is](s)}l(d0,"inflateOnError")});var ls=ce((M$,Er)=>{"use strict";var{isUtf8:Od}=require("buffer"),{hasBlob:p0}=Bt(),m0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function f0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(f0,"isValidStatusCode");function za(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}l(za,"_isValidUTF8");function g0(s){return p0&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(g0,"isBlob");Er.exports={isBlob:g0,isValidStatusCode:f0,isValidUTF8:za,tokenChars:m0};if(Od)Er.exports.isValidUTF8=function(s){return s.length<24?za(s):Od(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");Er.exports.isValidUTF8=function(e){return e.length<32?za(e):s(e)}}catch{}});var Qa=ce((I$,Wd)=>{"use strict";var{Writable:h0}=require("stream"),Id=cs(),{BINARY_TYPES:y0,EMPTY_BUFFER:jd,kStatusCode:b0,kWebSocket:w0}=Bt(),{concat:Ja,toArrayBuffer:k0,unmask:D0}=Zs(),{isValidStatusCode:v0,isValidUTF8:Nd}=ls(),Fr=Buffer[Symbol.species],Ye=0,Ld=1,Bd=2,Ud=3,Ka=4,Ya=5,Tr=6,Xa=class extends h0{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||y0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[w0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ye}_write(e,t,o){if(this._opcode===8&&this._state==Ye)return o();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){o(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(o)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new Fr(o.buffer,o.byteOffset+e,o.length-e),new Fr(o.buffer,o.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let o=this._buffers[0],n=t.length-e;e>=o.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(o.buffer,o.byteOffset,e),n),this._buffers[0]=new Fr(o.buffer,o.byteOffset+e,o.length-e)),e-=o.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ye:this.getInfo(e);break;case Ld:this.getPayloadLength16(e);break;case Bd:this.getPayloadLength64(e);break;case Ud:this.getMask();break;case Ka:this.getData(e);break;case Ya:case Tr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let o=(t[0]&64)===64;if(o&&!this._extensions[Id.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Ld:this._payloadLength===127?this._state=Bd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),o=t.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=o*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ud:this._state=Ka}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ka}getData(e){let t=jd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&D0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(o);return}if(this._compressed){this._state=Ya,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Id.extensionName].decompress(e,this._fin,(n,r)=>{if(n)return t(n);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(i);return}this._fragments.push(r)}this.dataMessage(t),this._state===Ye&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ye;return}let t=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Ja(o,t):this._binaryType==="arraybuffer"?n=k0(Ja(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Ye):(this._state=Tr,setImmediate(()=>{this.emit("message",n,!0),this._state=Ye,this.startLoop(e)}))}else{let n=Ja(o,t);if(!this._skipUTF8Validation&&!Nd(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===Ya||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Ye):(this._state=Tr,setImmediate(()=>{this.emit("message",n,!1),this._state=Ye,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,jd),this.end();else{let o=e.readUInt16BE(0);if(!v0(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new Fr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Nd(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(r);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=Ye;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ye):(this._state=Tr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ye,this.startLoop(t)}))}createError(e,t,o,n,r){this._loop=!1,this._errored=!0;let i=new e(o?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=r,i[b0]=n,i}};Wd.exports=Xa});var tc=ce((L$,qd)=>{"use strict";var{Duplex:N$}=require("stream"),{randomFillSync:S0}=require("crypto"),{types:{isUint8Array:x0}}=require("util"),Hd=cs(),{EMPTY_BUFFER:$0,kWebSocket:C0,NOOP:_0}=Bt(),{isBlob:us,isValidStatusCode:E0}=ls(),{mask:Gd,toBuffer:Ao}=Zs(),Xe=Symbol("kByteLength"),F0=Buffer.alloc(4),Rr=8*1024,Po,ds=Rr,ct=0,T0=1,R0=2,Za=class s{static{l(this,"Sender")}constructor(e,t,o){this._extensions=t||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=_0,this[C0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||F0,t.generateMask?t.generateMask(o):(ds===Rr&&(Po===void 0&&(Po=Buffer.alloc(Rr)),S0(Po,0,Rr),ds=0),o[0]=Po[ds++],o[1]=Po[ds++],o[2]=Po[ds++],o[3]=Po[ds++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Xe]!==void 0?c=t[Xe]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!i);let u=c;c>=65536?(r+=8,u=127):c>125&&(r+=2,u=126);let d=Buffer.allocUnsafe(n?c+r:r);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[r-4]=o[0],d[r-3]=o[1],d[r-2]=o[2],d[r-1]=o[3],i?[d,e]:n?(Gd(e,o,d,r,c),[d]):(Gd(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=$0;else{if(typeof e!="number"||!E0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)r=Buffer.allocUnsafe(2),r.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(r=Buffer.allocUnsafe(2+c),r.writeUInt16BE(e,0),typeof t=="string")r.write(t,2);else if(x0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Xe]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,r,!1,i,n]):this.sendFrame(s.frame(r,i),n)}ping(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):us(e)?(n=e.size,r=!1):(e=Ao(e),n=e.length,r=Ao.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Xe]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};us(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ct?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}pong(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):us(e)?(n=e.size,r=!1):(e=Ao(e),n=e.length,r=Ao.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Xe]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};us(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ct?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[Hd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):us(e)?(c=e.size,u=!1):(e=Ao(e),c=e.length,u=Ao.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=n._threshold),this._compress=i):(i=!1,r=0),t.fin&&(this._firstFragment=!0);let d={[Xe]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};us(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Xe],this._state=R0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(ec,this,c,n);return}this._bufferedBytes-=o[Xe];let i=Ao(r);t?this.dispatch(i,t,o,n):(this._state=ct,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(A0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[Hd.extensionName];this._bufferedBytes+=o[Xe],this._state=T0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");ec(this,u,n);return}this._bufferedBytes-=o[Xe],this._state=ct,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Xe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Xe],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};qd.exports=Za;function ec(s,e,t){typeof t=="function"&&t(e);for(let o=0;o<s._queue.length;o++){let n=s._queue[o],r=n[n.length-1];typeof r=="function"&&r(e)}}l(ec,"callCallbacks");function A0(s,e,t){ec(s,e,t),s.onerror(e)}l(A0,"onError")});var ep=ce((U$,Zd)=>{"use strict";var{kForOnEventAttribute:tn,kListener:oc}=Bt(),Vd=Symbol("kCode"),zd=Symbol("kData"),Jd=Symbol("kError"),Kd=Symbol("kMessage"),Yd=Symbol("kReason"),ps=Symbol("kTarget"),Xd=Symbol("kType"),Qd=Symbol("kWasClean"),Wt=class{static{l(this,"Event")}constructor(e){this[ps]=null,this[Xd]=e}get target(){return this[ps]}get type(){return this[Xd]}};Object.defineProperty(Wt.prototype,"target",{enumerable:!0});Object.defineProperty(Wt.prototype,"type",{enumerable:!0});var Mo=class extends Wt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[Vd]=t.code===void 0?0:t.code,this[Yd]=t.reason===void 0?"":t.reason,this[Qd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Vd]}get reason(){return this[Yd]}get wasClean(){return this[Qd]}};Object.defineProperty(Mo.prototype,"code",{enumerable:!0});Object.defineProperty(Mo.prototype,"reason",{enumerable:!0});Object.defineProperty(Mo.prototype,"wasClean",{enumerable:!0});var ms=class extends Wt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[Jd]=t.error===void 0?null:t.error,this[Kd]=t.message===void 0?"":t.message}get error(){return this[Jd]}get message(){return this[Kd]}};Object.defineProperty(ms.prototype,"error",{enumerable:!0});Object.defineProperty(ms.prototype,"message",{enumerable:!0});var on=class extends Wt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[zd]=t.data===void 0?null:t.data}get data(){return this[zd]}};Object.defineProperty(on.prototype,"data",{enumerable:!0});var P0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[tn]&&n[oc]===e&&!n[tn])return;let o;if(s==="message")o=l(function(r,i){let c=new on("message",{data:i?r:r.toString()});c[ps]=this,Ar(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new Mo("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ps]=this,Ar(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new ms("error",{error:r,message:r.message});i[ps]=this,Ar(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Wt("open");r[ps]=this,Ar(e,this,r)},"onOpen");else return;o[tn]=!!t[tn],o[oc]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[oc]===e&&!t[tn]){this.removeListener(s,t);break}}};Zd.exports={CloseEvent:Mo,ErrorEvent:ms,Event:Wt,EventTarget:P0,MessageEvent:on};function Ar(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(Ar,"callListener")});var Pr=ce((H$,tp)=>{"use strict";var{tokenChars:sn}=ls();function kt(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(kt,"push");function M0(s){let e=Object.create(null),t=Object.create(null),o=!1,n=!1,r=!1,i,c,u=-1,d=-1,p=-1,f=0;for(;f<s.length;f++)if(d=s.charCodeAt(f),i===void 0)if(p===-1&&sn[d]===1)u===-1&&(u=f);else if(f!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);d===44?(kt(e,g,t),t=Object.create(null)):i=g,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&sn[d]===1)u===-1&&(u=f);else if(d===32||d===9)p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),kt(t,s.slice(u,p),!0),d===44&&(kt(e,i,t),t=Object.create(null),i=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=s.slice(u,f),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(n){if(sn[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(sn[d]===1)u===-1&&(u=f);else if(d===34&&u!==-1)r=!1,p=f;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&s.charCodeAt(f-1)===61)r=!0;else if(p===-1&&sn[d]===1)u===-1&&(u=f);else if(u!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);o&&(g=g.replace(/\\/g,""),o=!1),kt(t,c,g),d===44&&(kt(e,i,t),t=Object.create(null),i=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(u===-1||r||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=s.slice(u,p);return i===void 0?kt(e,m,t):(c===void 0?kt(t,m,!0):o?kt(t,c,m.replace(/\\/g,"")):kt(t,c,m),kt(e,i,t)),e}l(M0,"parse");function O0(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(o=>[e].concat(Object.keys(o).map(n=>{let r=o[n];return Array.isArray(r)||(r=[r]),r.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}l(O0,"format");tp.exports={format:O0,parse:M0}});var jr=ce((z$,mp)=>{"use strict";var I0=require("events"),j0=require("https"),N0=require("http"),np=require("net"),L0=require("tls"),{randomBytes:B0,createHash:U0}=require("crypto"),{Duplex:q$,Readable:V$}=require("stream"),{URL:sc}=require("url"),uo=cs(),W0=Qa(),H0=tc(),{isBlob:G0}=ls(),{BINARY_TYPES:op,CLOSE_TIMEOUT:q0,EMPTY_BUFFER:Mr,GUID:V0,kForOnEventAttribute:nc,kListener:z0,kStatusCode:J0,kWebSocket:we,NOOP:rp}=Bt(),{EventTarget:{addEventListener:K0,removeEventListener:Y0}}=ep(),{format:X0,parse:Q0}=Pr(),{toBuffer:Z0}=Zs(),ip=Symbol("kAborted"),rc=[8,13],Ht=["CONNECTING","OPEN","CLOSING","CLOSED"],eb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ae=class s extends I0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=op[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Mr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(o=t,t=[]):t=[t]),ap(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){op.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,o){let n=new W0({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),r=new H0(e,this._extensions,o.generateMask);this._receiver=n,this._sender=r,this._socket=e,n[we]=this,r[we]=this,e[we]=this,n.on("conclude",sb),n.on("drain",nb),n.on("error",rb),n.on("message",ib),n.on("ping",ab),n.on("pong",cb),r.onerror=lb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",up),e.on("data",Ir),e.on("end",dp),e.on("error",pp),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[uo.extensionName]&&this._extensions[uo.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),lp(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Mr,t,o)}pong(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Mr,t,o)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(o=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[uo.extensionName]||(n.compress=!1),this._sender.send(e||Mr,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,"CONNECTING",{enumerable:!0,value:Ht.indexOf("CONNECTING")});Object.defineProperty(ae.prototype,"CONNECTING",{enumerable:!0,value:Ht.indexOf("CONNECTING")});Object.defineProperty(ae,"OPEN",{enumerable:!0,value:Ht.indexOf("OPEN")});Object.defineProperty(ae.prototype,"OPEN",{enumerable:!0,value:Ht.indexOf("OPEN")});Object.defineProperty(ae,"CLOSING",{enumerable:!0,value:Ht.indexOf("CLOSING")});Object.defineProperty(ae.prototype,"CLOSING",{enumerable:!0,value:Ht.indexOf("CLOSING")});Object.defineProperty(ae,"CLOSED",{enumerable:!0,value:Ht.indexOf("CLOSED")});Object.defineProperty(ae.prototype,"CLOSED",{enumerable:!0,value:Ht.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ae.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ae.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[nc])return e[z0];return null},set(e){for(let t of this.listeners(s))if(t[nc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[nc]:!0})}})});ae.prototype.addEventListener=K0;ae.prototype.removeEventListener=Y0;mp.exports=ae;function ap(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:q0,protocolVersion:rc[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=n.autoPong,s._closeTimeout=n.closeTimeout,!rc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${rc.join(", ")})`);let r;if(e instanceof sc)r=e;else try{r=new sc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let y=new SyntaxError(u);if(s._redirects===0)throw y;Or(s,y);return}let d=i?443:80,p=B0(16).toString("base64"),f=i?j0.request:N0.request,m=new Set,g;if(n.createConnection=n.createConnection||(i?ob:tb),n.defaultPort=n.defaultPort||d,n.port=r.port||d,n.host=r.hostname.startsWith("[")?r.hostname.slice(1,-1):r.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=r.pathname+r.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(g=new uo({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=X0({[uo.extensionName]:g.offer()})),t.length){for(let y of t){if(typeof y!="string"||!eb.test(y)||m.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(y)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let y=n.path.split(":");n.socketPath=y[0],n.path=y[1]}let h;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let y=o&&o.headers;if(o={...o,headers:{}},y)for(let[S,D]of Object.entries(y))o.headers[S.toLowerCase()]=D}else if(s.listenerCount("redirect")===0){let y=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!y||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,y||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),h=s._req=f(n),s._redirects&&s.emit("redirect",s.url,h)}else h=s._req=f(n);n.timeout&&h.on("timeout",()=>{We(s,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[ip]||(h=s._req=null,Or(s,y))}),h.on("response",y=>{let S=y.headers.location,D=y.statusCode;if(S&&n.followRedirects&&D>=300&&D<400){if(++s._redirects>n.maxRedirects){We(s,h,"Maximum redirects exceeded");return}h.abort();let C;try{C=new sc(S,e)}catch{let v=new SyntaxError(`Invalid URL: ${S}`);Or(s,v);return}ap(s,C,t,o)}else s.emit("unexpected-response",h,y)||We(s,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,S,D)=>{if(s.emit("upgrade",y),s.readyState!==ae.CONNECTING)return;h=s._req=null;let C=y.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){We(s,S,"Invalid Upgrade header");return}let x=U0("sha1").update(p+V0).digest("base64");if(y.headers["sec-websocket-accept"]!==x){We(s,S,"Invalid Sec-WebSocket-Accept header");return}let v=y.headers["sec-websocket-protocol"],E;if(v!==void 0?m.size?m.has(v)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){We(s,S,E);return}v&&(s._protocol=v);let oe=y.headers["sec-websocket-extensions"];if(oe!==void 0){if(!g){We(s,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Q0(oe)}catch{We(s,S,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(U);if(pe.length!==1||pe[0]!==uo.extensionName){We(s,S,"Server indicated an extension that was not requested");return}try{g.accept(U[uo.extensionName])}catch{We(s,S,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[uo.extensionName]=g}s.setSocket(S,D,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(h,s):h.end()}l(ap,"initAsClient");function Or(s,e){s._readyState=ae.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Or,"emitErrorAndClose");function tb(s){return s.path=s.socketPath,np.connect(s)}l(tb,"netConnect");function ob(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=np.isIP(s.host)?"":s.host),L0.connect(s)}l(ob,"tlsConnect");function We(s,e,t){s._readyState=ae.CLOSING;let o=new Error(t);Error.captureStackTrace(o,We),e.setHeader?(e[ip]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Or,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(We,"abortHandshake");function ic(s,e,t){if(e){let o=G0(e)?e.size:Z0(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Ht[s.readyState]})`);process.nextTick(t,o)}}l(ic,"sendAfterClose");function sb(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Ir),process.nextTick(cp,t._socket),s===1005?t.close():t.close(s,e))}l(sb,"receiverOnConclude");function nb(){let s=this[we];s.isPaused||s._socket.resume()}l(nb,"receiverOnDrain");function rb(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Ir),process.nextTick(cp,e._socket),e.close(s[J0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(rb,"receiverOnError");function sp(){this[we].emitClose()}l(sp,"receiverOnFinish");function ib(s,e){this[we].emit("message",s,e)}l(ib,"receiverOnMessage");function ab(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,rp),e.emit("ping",s)}l(ab,"receiverOnPing");function cb(s){this[we].emit("pong",s)}l(cb,"receiverOnPong");function cp(s){s.resume()}l(cp,"resume");function lb(s){let e=this[we];e.readyState!==ae.CLOSED&&(e.readyState===ae.OPEN&&(e._readyState=ae.CLOSING,lp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(lb,"senderOnError");function lp(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(lp,"setCloseTimer");function up(){let s=this[we];if(this.removeListener("close",up),this.removeListener("data",Ir),this.removeListener("end",dp),s._readyState=ae.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[we]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",sp),s._receiver.on("finish",sp))}l(up,"socketOnClose");function Ir(s){this[we]._receiver.write(s)||this.pause()}l(Ir,"socketOnData");function dp(){let s=this[we];s._readyState=ae.CLOSING,s._receiver.end(),this.end()}l(dp,"socketOnEnd");function pp(){let s=this[we];this.removeListener("error",pp),this.on("error",rp),s&&(s._readyState=ae.CLOSING,this.destroy())}l(pp,"socketOnError")});var yp=ce((Y$,hp)=>{"use strict";var K$=jr(),{Duplex:ub}=require("stream");function fp(s){s.emit("close")}l(fp,"emitClose");function db(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(db,"duplexOnEnd");function gp(s){this.removeListener("error",gp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(gp,"duplexOnError");function pb(s,e){let t=!0,o=new ub({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",l(function(r,i){let c=!i&&o._readableState.objectMode?r.toString():r;o.push(c)||s.pause()},"message")),s.once("error",l(function(r){o.destroyed||(t=!1,o.destroy(r))},"error")),s.once("close",l(function(){o.destroyed||o.push(null)},"close")),o._destroy=function(n,r){if(s.readyState===s.CLOSED){r(n),process.nextTick(fp,o);return}let i=!1;s.once("error",l(function(u){i=!0,r(u)},"error")),s.once("close",l(function(){i||r(n),process.nextTick(fp,o)},"close")),t&&s.terminate()},o._final=function(n){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._final(n)},"open"));return}s._socket!==null&&(s._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(s._socket.once("finish",l(function(){n()},"finish")),s.close()))},o._read=function(){s.isPaused&&s.resume()},o._write=function(n,r,i){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._write(n,r,i)},"open"));return}s.send(n,i)},o.on("end",db),o.on("error",gp),o}l(pb,"createWebSocketStream");hp.exports=pb});var ac=ce((Q$,bp)=>{"use strict";var{tokenChars:mb}=ls();function fb(s){let e=new Set,t=-1,o=-1,n=0;for(n;n<s.length;n++){let i=s.charCodeAt(n);if(o===-1&&mb[i]===1)t===-1&&(t=n);else if(n!==0&&(i===32||i===9))o===-1&&t!==-1&&(o=n);else if(i===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let c=s.slice(t,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(t===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let r=s.slice(t,n);if(e.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);return e.add(r),e}l(fb,"parse");bp.exports={parse:fb}});var $p=ce((tC,xp)=>{"use strict";var gb=require("events"),Nr=require("http"),{Duplex:eC}=require("stream"),{createHash:hb}=require("crypto"),wp=Pr(),Oo=cs(),yb=ac(),bb=jr(),{CLOSE_TIMEOUT:wb,GUID:kb,kWebSocket:Db}=Bt(),vb=/^[+/0-9A-Za-z]{22}==$/,kp=0,Dp=1,Sp=2,cc=class extends gb{static{l(this,"WebSocketServer")}constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:wb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Nr.createServer((o,n)=>{let r=Nr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),n.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=Sb(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:l((n,r,i)=>{this.handleUpgrade(n,r,i,o)},"upgrade")})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=kp}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Sp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(nn,this);return}if(e&&this.once("close",e),this._state!==Dp)if(this._state=Dp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(nn,this):process.nextTick(nn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{nn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,o,n){t.on("error",vp);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Io(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Io(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!vb.test(r)){Io(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Io(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){rn(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=yb.parse(u)}catch{Io(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let m=new Oo({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=wp.parse(p);g[Oo.extensionName]&&(m.accept(g[Oo.extensionName]),f[Oo.extensionName]=m)}catch{Io(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(g,h,y,S)=>{if(!g)return rn(t,h||401,y,S);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return rn(t,401)}this.completeUpgrade(f,r,d,e,t,o,n)}completeUpgrade(e,t,o,n,r,i,c){if(!r.readable||!r.writable)return r.destroy();if(r[Db])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>kp)return rn(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hb("sha1").update(t+kb).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(o.size){let f=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Oo.extensionName]){let f=e[Oo.extensionName].params,m=wp.format({[Oo.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
154
163
|
`).join(`\r
|
|
155
|
-
`)),r.removeListener("error",
|
|
164
|
+
`)),r.removeListener("error",vp),p.setSocket(r,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(nn,this)})),c(p,n)}};xp.exports=cc;function Sb(s,e){for(let t of Object.keys(e))s.on(t,e[t]);return l(function(){for(let o of Object.keys(e))s.removeListener(o,e[o])},"removeListeners")}l(Sb,"addListeners");function nn(s){s._state=Sp,s.emit("close")}l(nn,"emitClose");function vp(){this.destroy()}l(vp,"socketOnError");function rn(s,e,t,o){t=t||Nr.STATUS_CODES[e],o={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...o},s.once("finish",s.destroy),s.end(`HTTP/1.1 ${e} ${Nr.STATUS_CODES[e]}\r
|
|
156
165
|
`+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
|
|
157
166
|
`)+`\r
|
|
158
167
|
\r
|
|
159
|
-
`+t)}l(
|
|
160
|
-
`),u="";try{let p=
|
|
161
|
-
`).filter(Boolean).map(n=>{let r=JSON.parse(n);return{timestamp:new Date(r.timestamp),level:r.level||"info",message:r.message||""}}):[]}catch{return[]}}function Dc(s,e,t){try{console.log(a.dim(` \u{1F4E5} Fetching branch ${t}...`)),(0,jo.execSync)(`git fetch origin "${t}"`,{cwd:s,stdio:"pipe"}),console.log(a.dim(` \u{1F500} Merging ${t} into current branch...`)),(0,jo.execSync)(`git merge --no-ff "origin/${t}" -m "merge: background job ${e}"`,{cwd:s,stdio:"inherit"}),console.log(a.green(` \u2705 Changes from job ${e} merged successfully.`))}catch(o){console.error(a.red(` \u274C Merge failed: ${o instanceof Error?o.message:o}`)),console.log(a.dim(" Resolve conflicts manually, then run: git merge --continue")),process.exit(1)}}function
|
|
162
|
-
`);r=u.pop()||"";for(let d of u)if(d.startsWith("data: "))try{let p=JSON.parse(d.substring(6));yield{timestamp:new Date(p.timestamp),level:p.level||"info",message:p.message||""}}catch{}}}catch{}}async cancel(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});if(!t.ok){let o=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${o}`}}return{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async retry(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/retry`,{method:"POST",headers:this.headers(),body:JSON.stringify(t||{}),signal:AbortSignal.timeout(15e3)});if(!o.ok){let r=await o.text().catch(()=>"");return{success:!1,error:`HTTP ${o.status}: ${r}`}}let n=await o.json();return{success:!0,jobId:n.id||n.jobId,branch:n.branch,dashboardUrl:n.dashboardUrl}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}async diff(e){try{let t=await fetch(`${this.baseUrl}/${e}/diff`,{headers:{...this.headers(),Accept:"text/plain"},signal:AbortSignal.timeout(15e3)});return t.ok?await t.text():""}catch{return""}}};l(
|
|
163
|
-
`).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,
|
|
164
|
-
`).filter(Boolean);t.push(`${c.length} staged file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}}catch{t.push("Unable to check git status (not a git repository?)")}return{compatible:t.length===0,reasons:t}}var
|
|
168
|
+
`+t)}l(rn,"abortHandshake");function Io(s,e,t,o,n,r){if(s.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Io),s.emit("wsClientError",i,t,e)}else rn(t,o,n,r)}l(Io,"abortHandshakeOrEmitwsClientError")});var xb,$b,Cb,_b,Eb,Fb,Cp,lc,lt,an=G(()=>{xb=b(yp(),1),$b=b(Pr(),1),Cb=b(cs(),1),_b=b(Qa(),1),Eb=b(tc(),1),Fb=b(ac(),1),Cp=b(jr(),1),lc=b($p(),1),lt=Cp.default});var Sc={};Ae(Sc,{JobsApiClient:()=>Ne,captureWorkspaceSnapshot:()=>Vp,createSnapshotArchive:()=>zp,getLocalJobLogs:()=>kc,getLocalJobStatus:()=>wc,getLocalJobs:()=>bc,printJobStatus:()=>Wr,printJobsTable:()=>vc,printLogEntry:()=>Hr,pullJobChanges:()=>Dc,runLocalBackgroundJob:()=>Jp,submitBackgroundJob:()=>Pb});function Vp(s){let e=l(p=>{try{return(0,jo.execSync)(p,{cwd:s,encoding:"utf8"}).trim()}catch{return""}},"git"),t=e("git remote get-url origin");process.platform==="win32"&&(t=t.replace(/\\/g,"/"));let o=e("git rev-parse --abbrev-ref HEAD"),n=e("git rev-parse HEAD"),r=e("git diff"),i=e("git diff --cached"),c=[r,i].filter(Boolean).join(`
|
|
169
|
+
`),u="";try{let p=te.join(s,".monkeyscode","rules.md");V.existsSync(p)&&(u=V.readFileSync(p,"utf8"))}catch{}let d="";try{let p=te.join(s,".monkeyscode","config.json");V.existsSync(p)&&(d=V.readFileSync(p,"utf8"))}catch{}return{repo:t,branch:o,commit:n,dirtyDiff:c,rules:u,config:d}}function zp(s,e){let t=V.mkdtempSync(te.join(Gp.tmpdir(),"mc-archive-")),o=te.join(t,"snapshot");V.mkdirSync(o,{recursive:!0}),s.dirtyDiff&&V.writeFileSync(te.join(o,"dirty.diff"),s.dirtyDiff,"utf8"),s.rules&&V.writeFileSync(te.join(o,"rules.md"),s.rules,"utf8"),s.config&&V.writeFileSync(te.join(o,"config.json"),s.config,"utf8"),e&&e.length>0&&V.writeFileSync(te.join(o,"conversation.json"),JSON.stringify(e,null,2),"utf8"),V.writeFileSync(te.join(o,"metadata.json"),JSON.stringify({repo:s.repo,branch:s.branch,commit:s.commit,createdAt:new Date().toISOString()},null,2),"utf8");let n=te.join(t,"snapshot.tar.gz");try{(0,jo.execSync)(`tar -czf "${n}" -C "${t}" snapshot`,{stdio:"pipe",timeout:3e4})}catch{let r=JSON.stringify({dirtyDiff:s.dirtyDiff,rules:s.rules,config:s.config,conversationHistory:e,metadata:{repo:s.repo,branch:s.branch,commit:s.commit}}),i=qp.gzipSync(Buffer.from(r,"utf8"));V.writeFileSync(n,i)}return n}async function Pb(s){let e=K(),o=fe()?.access_token;o||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),console.log(a.dim(" \u{1F4F8} Capturing workspace snapshot..."));let n=Vp(s.workspace);n.repo||(console.error(a.red(" \u274C No git remote found. Background jobs require a git repository.")),process.exit(4));let r=new Ne(e.platformUrl,o),i=null;try{console.log(a.dim(" \u{1F4E6} Creating compressed archive...")),i=zp(n,s.conversationHistory);let u=V.statSync(i).size;console.log(a.dim(` \u{1F4E6} Archive: ${(u/1024).toFixed(1)} KB`));let d=await r.requestUploadUrl();d?(console.log(a.dim(" \u2601\uFE0F Uploading to GCS...")),await r.uploadArchive(d.uploadUrl,i)?(n.archiveId=d.archiveId,n.dirtyDiff="",n.rules="",n.config="",console.log(a.dim(" \u2705 Archive uploaded successfully"))):console.log(a.dim(" \u26A0\uFE0F Archive upload failed \u2014 falling back to inline JSON"))):console.log(a.dim(" \u26A0\uFE0F Server does not support archive uploads \u2014 using inline JSON"))}catch{console.log(a.dim(" \u26A0\uFE0F Archive creation failed \u2014 falling back to inline JSON"))}finally{if(i)try{let u=te.dirname(i);V.rmSync(u,{recursive:!0,force:!0})}catch{}}console.log(a.dim(" \u{1F680} Submitting background job..."));let c=await r.submit({prompt:s.prompt,model:s.model,mode:s.mode,workspace:n,autoBranch:s.autoBranch,autoCommit:s.autoCommit,autoPR:s.autoPR,maxCost:s.maxCost,timeout:s.timeout,conversationHistory:s.conversationHistory});if(!c.success){if(c.error?.includes("ECONNREFUSED")||c.error?.includes("ENOTFOUND")||c.error?.includes("ETIMEDOUT")||c.error?.includes("fetch failed")){console.log(a.yellow(" \u26A0\uFE0F Cloud API unavailable \u2014 running locally in background")),await Jp({...s,token:o});return}console.error(a.red(` \u274C Submission failed: ${c.error}`)),process.exit(1)}console.log(""),console.log(a.bold(" \u{1F680} Background job submitted (cloud)")),console.log(a.dim(" "+"\u2500".repeat(38))),console.log(` Job ID: ${a.cyan(c.jobId)}`),console.log(` Prompt: "${s.prompt.substring(0,60)}${s.prompt.length>60?"...":""}"`),console.log(` Model: ${s.model}`),c.branch&&console.log(` Branch: ${a.green(c.branch)}`),console.log(` Auto-PR: ${s.autoPR?a.green("Yes"):"No"}`),console.log(a.dim(" "+"\u2500".repeat(38))),console.log(` Track: ${a.dim(`mc jobs status ${c.jobId}`)}`),c.dashboardUrl&&console.log(` Dashboard: ${a.dim(c.dashboardUrl)}`),console.log("")}async function Jp(s){let e=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,{getPlatformPaths:t}=await Promise.resolve().then(()=>(X(),$o)),o=t(),n=te.join(o.data,"jobs",e);V.mkdirSync(n,{recursive:!0});let r={jobId:e,prompt:s.prompt,workspace:te.resolve(s.workspace),model:s.model,mode:s.mode,token:s.token,autoBranch:s.autoBranch,autoCommit:s.autoCommit,autoPR:s.autoPR,maxCost:s.maxCost,timeout:s.timeout};V.writeFileSync(te.join(n,"config.json"),JSON.stringify(r,null,2),"utf8"),V.writeFileSync(te.join(n,"status.json"),JSON.stringify({status:"queued",progress:0,message:"Starting...",updatedAt:new Date().toISOString()},null,2),"utf8");let i=new URL("../agent/local-job-runner.js",Ib.url).pathname,c=(0,jo.fork)(i,[],{detached:!0,stdio:["ignore","ignore","ignore","ipc"],env:{...process.env}});await new Promise((u,d)=>{let p=setTimeout(()=>d(new Error("Runner startup timeout")),1e4);c.on("message",f=>{f?.type==="ready"&&(c.send({type:"start",config:r}),clearTimeout(p),u())}),c.on("error",f=>{clearTimeout(p),d(f)})}),c.unref(),c.disconnect(),console.log(""),console.log(a.bold(" \u{1F5A5}\uFE0F Background job started (local)")),console.log(a.dim(" "+"\u2500".repeat(38))),console.log(` Job ID: ${a.cyan(e)}`),console.log(` Prompt: "${s.prompt.substring(0,60)}${s.prompt.length>60?"...":""}"`),console.log(` Model: ${s.model}`),console.log(` Location: ${a.yellow("local")} (cloud unavailable)`),console.log(a.dim(" "+"\u2500".repeat(38))),console.log(` Logs: ${a.dim(te.join(n,"log.jsonl"))}`),console.log(` Status: ${a.dim(`mc jobs status ${e}`)}`),console.log("")}function bc(s){try{let{getPlatformPaths:e}=(X(),Ps($o)),t=e(),o=te.join(t.data,"jobs");if(!V.existsSync(o))return[];let n=V.readdirSync(o,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name.startsWith("local-")).sort((i,c)=>c.name.localeCompare(i.name)),r=[];for(let i of n){if(s?.limit&&r.length>=s.limit)break;let c=te.join(o,i.name);try{let u=JSON.parse(V.readFileSync(te.join(c,"status.json"),"utf8")),d=JSON.parse(V.readFileSync(te.join(c,"config.json"),"utf8"));if(s?.status&&u.status!==s.status)continue;let p,f,m,g,h,y=te.join(c,"result.json");if(V.existsSync(y)){let S=JSON.parse(V.readFileSync(y,"utf8"));p=S.duration,f=S.filesChanged?.length,m=S.tokensUsed,g=S.costUsd,(S.status==="completed"||S.status==="failed")&&(h=new Date(Date.parse(u.updatedAt)))}r.push({id:i.name,status:u.status,prompt:d.prompt||"",model:d.model||"unknown",branch:void 0,duration:p,filesChanged:f,tokensUsed:m,cost:g,createdAt:new Date(V.statSync(te.join(c,"config.json")).birthtimeMs),completedAt:h,currentStep:u.message})}catch{}}return r}catch{return[]}}function wc(s){try{let{getPlatformPaths:e}=(X(),Ps($o)),t=e(),o=te.join(t.data,"jobs",s);if(!V.existsSync(o))return null;let n=JSON.parse(V.readFileSync(te.join(o,"status.json"),"utf8")),r=JSON.parse(V.readFileSync(te.join(o,"config.json"),"utf8")),i={id:s,status:n.status,prompt:r.prompt||"",model:r.model||"unknown",createdAt:new Date(V.statSync(te.join(o,"config.json")).birthtimeMs),currentStep:n.message},c=te.join(o,"result.json");if(V.existsSync(c)){let u=JSON.parse(V.readFileSync(c,"utf8"));i.duration=u.duration,i.filesChanged=u.filesChanged?.length,i.tokensUsed=u.tokensUsed,i.cost=u.costUsd,i.branch=u.gitBranch,i.error=u.error,u.status!=="running"&&(i.completedAt=new Date(Date.parse(n.updatedAt)))}return i}catch{return null}}function kc(s){try{let{getPlatformPaths:e}=(X(),Ps($o)),t=e(),o=te.join(t.data,"jobs",s,"log.jsonl");return V.existsSync(o)?V.readFileSync(o,"utf8").split(`
|
|
170
|
+
`).filter(Boolean).map(n=>{let r=JSON.parse(n);return{timestamp:new Date(r.timestamp),level:r.level||"info",message:r.message||""}}):[]}catch{return[]}}function Dc(s,e,t){try{console.log(a.dim(` \u{1F4E5} Fetching branch ${t}...`)),(0,jo.execSync)(`git fetch origin "${t}"`,{cwd:s,stdio:"pipe"}),console.log(a.dim(` \u{1F500} Merging ${t} into current branch...`)),(0,jo.execSync)(`git merge --no-ff "origin/${t}" -m "merge: background job ${e}"`,{cwd:s,stdio:"inherit"}),console.log(a.green(` \u2705 Changes from job ${e} merged successfully.`))}catch(o){console.error(a.red(` \u274C Merge failed: ${o instanceof Error?o.message:o}`)),console.log(a.dim(" Resolve conflicts manually, then run: git merge --continue")),process.exit(1)}}function Kp(){return process.platform!=="win32"||!!process.env.WT_SESSION}function Yp(s){return(Kp()?Mb:Ob)[s]||"?"}function vc(s){if(s.length===0){console.log(a.dim(" No background jobs found."));return}let e=process.platform!=="win32"||process.env.WT_SESSION,t=` ${"ID".padEnd(16)} ${"Status".padEnd(12)} ${"Prompt".padEnd(36)} ${"Duration".padEnd(10)} Branch`,o=e?" "+"\u2500".repeat(96):" "+"-".repeat(96);console.log(o),console.log(a.bold(t)),console.log(o);for(let n of s){let i=`${Yp(n.status)} ${Xp(n.status)}`,c=n.prompt.length>34?`"${n.prompt.substring(0,32)}..."`:`"${n.prompt}"`,u=n.duration?yc(n.duration):"\u2014",d=n.branch||"\u2014";console.log(` ${n.id.padEnd(16)} ${i.padEnd(12)} ${c.padEnd(36)} ${u.padEnd(10)} ${d}`)}console.log(o)}function Wr(s,e){let t=Kp();if(console.log(""),console.log(a.bold(` ${t?"\u{1F4CB}":">>"} Job: ${s.id}`)),console.log(a.dim(" "+(t?"\u2500":"-").repeat(50))),console.log(` Status: ${Yp(s.status)} ${Xp(s.status)}`),console.log(` Prompt: "${s.prompt}"`),console.log(` Model: ${s.model}`),s.branch&&console.log(` Branch: ${a.green(s.branch)}`),s.currentStep&&console.log(` Step: ${s.currentStep}`),s.filesChanged!=null&&console.log(` Files: ${s.filesChanged} changed`),s.tokensUsed!=null&&console.log(` Tokens: ${s.tokensUsed.toLocaleString()}`),s.cost!=null&&console.log(` Cost: $${s.cost.toFixed(4)}`),s.duration!=null&&console.log(` Duration: ${yc(s.duration)}`),s.estimatedTimeRemaining!=null&&console.log(` ETA: ~${yc(s.estimatedTimeRemaining)}`),s.prUrl&&console.log(` PR: ${a.cyan(s.prUrl)}`),s.error&&console.log(` Error: ${a.red(s.error)}`),console.log(` Created: ${s.createdAt.toLocaleString()}`),s.completedAt&&console.log(` Completed: ${s.completedAt.toLocaleString()}`),console.log(a.dim(" "+"\u2500".repeat(50))),e.length>0){console.log(""),console.log(a.bold(" \u{1F4DC} Recent Logs"));let o=e.slice(-20);for(let n of o){let r=n.timestamp.toLocaleTimeString(),i=n.level==="error"?a.red:n.level==="tool"?a.cyan:a.dim;console.log(` ${a.dim(r)} ${i(`[${n.level}]`)} ${n.message}`)}}console.log("")}function Hr(s){let e=s.timestamp.toLocaleTimeString(),t=s.level==="error"?a.red:s.level==="tool"?a.cyan:a.dim;console.log(`${a.dim(e)} ${t(`[${s.level}]`)} ${s.message}`)}function Hp(s){return{id:s.id||s.jobId,status:s.status||"queued",prompt:s.prompt||"",model:s.model||"unknown",branch:s.branch,duration:s.duration,filesChanged:s.filesChanged,tokensUsed:s.tokensUsed||s.tokens,cost:s.cost,createdAt:new Date(s.createdAt||s.created),completedAt:s.completedAt?new Date(s.completedAt):void 0,error:s.error,prUrl:s.prUrl,currentStep:s.currentStep,estimatedTimeRemaining:s.estimatedTimeRemaining||s.eta}}function yc(s){if(s<1e3)return`${s}ms`;let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;if(t<60)return`${t}m ${o}s`;let n=Math.floor(t/60),r=t%60;return`${n}h ${r}m`}function Xp(s){return s.charAt(0).toUpperCase()+s.slice(1)}var V,te,Gp,qp,jo,Ib,Ne,Mb,Ob,un=G(()=>{"use strict";V=b(require("node:fs"),1),te=b(require("node:path"),1),Gp=b(require("node:os"),1),qp=b(require("node:zlib"),1),jo=require("node:child_process");W();Q();ee();Ib={},Ne=class{static{l(this,"JobsApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/jobs`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async submit(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,jobId:o.id||o.jobId,branch:o.branch,dashboardUrl:o.dashboardUrl}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async requestUploadUrl(){try{let e=await fetch(`${this.baseUrl}/upload-url`,{method:"POST",headers:this.headers(),body:JSON.stringify({contentType:"application/gzip"}),signal:AbortSignal.timeout(1e4)});if(!e.ok)return null;let t=await e.json();return{uploadUrl:t.uploadUrl,archiveId:t.archiveId}}catch{return null}}async uploadArchive(e,t){try{let o=V.readFileSync(t);return(await fetch(e,{method:"PUT",headers:{"Content-Type":"application/gzip","Content-Length":String(o.byteLength)},body:o,signal:AbortSignal.timeout(6e4)})).ok}catch{return!1}}async list(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.since&&t.set("since",e.since),e?.limit&&t.set("limit",String(e.limit));let o=t.toString()?`${this.baseUrl}?${t}`:this.baseUrl;try{let n=await fetch(o,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});return n.ok?((await n.json()).jobs||[]).map(Hp):[]}catch{return[]}}async status(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});if(!t.ok)return null;let o=await t.json();return Hp(o)}catch{return null}}async logs(e){try{let t=await fetch(`${this.baseUrl}/${e}/logs`,{headers:this.headers(),signal:AbortSignal.timeout(15e3)});return t.ok?((await t.json()).logs||[]).map(n=>({timestamp:new Date(n.timestamp),level:n.level||"info",message:n.message||n.text||""})):[]}catch{return[]}}async*followLogs(e){try{let t=await fetch(`${this.baseUrl}/${e}/logs/stream`,{headers:{...this.headers(),Accept:"text/event-stream"}});if(!t.ok||!t.body)return;let o=t.body.getReader(),n=new TextDecoder,r="";for(;;){let{done:i,value:c}=await o.read();if(i)break;r+=n.decode(c,{stream:!0});let u=r.split(`
|
|
171
|
+
`);r=u.pop()||"";for(let d of u)if(d.startsWith("data: "))try{let p=JSON.parse(d.substring(6));yield{timestamp:new Date(p.timestamp),level:p.level||"info",message:p.message||""}}catch{}}}catch{}}async cancel(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});if(!t.ok){let o=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${o}`}}return{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async retry(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/retry`,{method:"POST",headers:this.headers(),body:JSON.stringify(t||{}),signal:AbortSignal.timeout(15e3)});if(!o.ok){let r=await o.text().catch(()=>"");return{success:!1,error:`HTTP ${o.status}: ${r}`}}let n=await o.json();return{success:!0,jobId:n.id||n.jobId,branch:n.branch,dashboardUrl:n.dashboardUrl}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}async diff(e){try{let t=await fetch(`${this.baseUrl}/${e}/diff`,{headers:{...this.headers(),Accept:"text/plain"},signal:AbortSignal.timeout(15e3)});return t.ok?await t.text():""}catch{return""}}};l(Vp,"captureWorkspaceSnapshot");l(zp,"createSnapshotArchive");l(Pb,"submitBackgroundJob");l(Jp,"runLocalBackgroundJob");l(bc,"getLocalJobs");l(wc,"getLocalJobStatus");l(kc,"getLocalJobLogs");l(Dc,"pullJobChanges");l(Kp,"shouldUseUnicode");Mb={queued:"\u23F3",running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u{1F6AB}"},Ob={queued:"[Q]",running:"[~]",completed:"[+]",failed:"[X]",cancelled:"[-]"};l(Yp,"getStatusIcon");l(vc,"printJobsTable");l(Wr,"printJobStatus");l(Hr,"printLogEntry");l(Hp,"parseJobInfo");l(yc,"formatDuration");l(Xp,"capitalize")});var Qp={};Ae(Qp,{resumeFromJob:()=>jb});async function jb(s){let e=K(),o=fe()?.access_token;if(!o)return console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Not authenticated"};let n=new Ne(e.platformUrl,o);console.log(a.dim(` \u{1F4CB} Fetching job ${s.jobId}...`));let r=await n.status(s.jobId);if(!r)return console.error(a.red(` \u274C Job ${s.jobId} not found.`)),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Job not found"};if(r.status!=="completed"&&r.status!=="failed")return console.error(a.yellow(` \u26A0 Job is still ${r.status}. Wait for it to complete or cancel it.`)),console.log(a.dim(` Track: mc jobs status ${s.jobId}`)),{success:!1,filesApplied:0,conversationLoaded:!1,error:`Job is ${r.status}`};if(!s.force){let d=Nb(s.workspace,r);if(!d.compatible){console.error(a.red(" \u274C Workspace is not compatible with this job."));for(let p of d.reasons)console.error(a.yellow(` \u2022 ${p}`));return console.log(""),console.log(a.dim(" Use --force to skip sync checks, or resolve the issues above.")),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Sync check failed"}}}console.log(a.dim(" \u{1F4E5} Downloading changes..."));let i=await n.diff(s.jobId),c=0;if(i.trim()){let d=process.platform==="win32"?i:i;console.log(a.dim(" \u{1F500} Applying changes..."));try{(0,hs.execSync)("git apply --check -",{cwd:s.workspace,input:d,stdio:["pipe","pipe","pipe"]}),(0,hs.execSync)("git apply -",{cwd:s.workspace,input:d,stdio:["pipe","pipe","pipe"]}),c=(d.match(/^diff --git/gm)||[]).length,console.log(a.green(` \u2705 Applied ${c} file(s).`))}catch(p){console.error(a.red(` \u274C Failed to apply changes: ${p instanceof Error?p.message:p}`)),console.log(a.dim(" The diff has been saved to .monkeyscode/resume-diff.patch")),console.log(a.dim(" Apply manually: git apply .monkeyscode/resume-diff.patch"));let f=dn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");return m(f,{recursive:!0}),g(dn.join(f,"resume-diff.patch"),d),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Diff application failed"}}}else console.log(a.dim(" No changes to apply (job may have failed before making changes)."));let u=!1;try{let d=await fetch(`${e.platformUrl}/api/jobs/${s.jobId}/conversation`,{headers:{Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(1e4)});if(d.ok){let p=await d.json();if(p.history&&p.history.length>0){let f=dn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");m(f,{recursive:!0}),g(dn.join(f,"resume-conversation.json"),JSON.stringify(p.history,null,2)),u=!0,console.log(a.dim(` \u{1F4AC} Conversation history loaded (${p.history.length} messages).`))}}}catch{}return console.log(""),console.log(a.bold(` \u2705 Resume from job ${s.jobId} complete`)),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Status: ${r.status}`),console.log(` Files applied: ${c}`),console.log(` Conversation: ${u?"loaded":"not available"}`),r.prUrl&&console.log(` PR: ${a.cyan(r.prUrl)}`),console.log(""),console.log(a.dim(" Continue working in interactive mode.")),console.log(""),{success:!0,filesApplied:c,conversationLoaded:u}}function Nb(s,e){let t=[];try{let o=(0,hs.execSync)("git rev-parse HEAD",{cwd:s,encoding:"utf8"}).trim(),n=e.workspace?.commit||e.commit;n&&o!==n&&t.push(`Local commit (${o.substring(0,8)}) differs from job commit (${n.substring(0,8)})`);let r=(0,hs.execSync)("git diff --name-only",{cwd:s,encoding:"utf8"}).trim();if(r){let c=r.split(`
|
|
172
|
+
`).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,hs.execSync)("git diff --cached --name-only",{cwd:s,encoding:"utf8"}).trim();if(i){let c=i.split(`
|
|
173
|
+
`).filter(Boolean);t.push(`${c.length} staged file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}}catch{t.push("Unable to check git status (not a git repository?)")}return{compatible:t.length===0,reasons:t}}var dn,hs,Zp=G(()=>{"use strict";dn=b(require("node:path"),1),hs=require("node:child_process");W();un();Q();ee();l(jb,"resumeFromJob");l(Nb,"checkSyncCompatibility")});function $c(s){let e=Dt.join(s.workspace,pn,s.teamId,s.taskSlug),t=`monkeyscode/team-${s.teamId}/${s.taskSlug}`;dt.mkdirSync(Dt.dirname(e),{recursive:!0});let o=s.baseBranch||(0,qt.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s.workspace,encoding:"utf8"}).trim();try{(0,qt.execSync)(`git worktree add -b "${t}" "${e}" "${o}"`,{cwd:s.workspace,encoding:"utf8",stdio:"pipe"})}catch{try{(0,qt.execSync)(`git worktree add "${e}" "${t}"`,{cwd:s.workspace,encoding:"utf8",stdio:"pipe"})}catch(i){throw new Error(`Failed to create worktree: ${i instanceof Error?i.message:i}`)}}let n=(0,qt.execSync)("git rev-parse HEAD",{cwd:e,encoding:"utf8"}).trim();return{path:e,branch:t,commit:n,isMain:!1,createdAt:new Date,label:s.taskSlug}}function Cc(s,e,t=!1){let o=t?" --force":"",n=l(()=>{(0,qt.execSync)(`git worktree remove "${e}"${o}`,{cwd:s,encoding:"utf8",stdio:"pipe"})},"tryRemove");if(process.platform==="win32")for(let r=0;r<xc;r++)try{n();return}catch(i){if(r<xc-1)(0,qt.execSync)(`timeout /t ${Math.ceil(Bb/1e3)}`,{stdio:"ignore"});else throw new Error(`Failed to remove worktree after ${xc} attempts (files may be locked by another process): ${i instanceof Error?i.message:i}`)}else n();try{(0,qt.execSync)("git worktree prune",{cwd:s,stdio:"pipe"})}catch{}}function Ub(s){let e;try{e=(0,qt.execSync)("git worktree list --porcelain",{cwd:s,encoding:"utf8"})}catch{return[]}let t=[],o=e.split(`
|
|
165
174
|
|
|
166
175
|
`).filter(Boolean);for(let n of o){let r=n.split(`
|
|
167
|
-
`),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=dt.statSync(i).birthtime}catch{}let f=i.split(Dt.sep),m=f.indexOf(ln.replace(/\//g,Dt.sep).split(Dt.sep)[0]),g=m>=0?f.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(ln),createdAt:p,label:g})}return t}function hs(s){return Ub(s).filter(e=>e.path.includes(ln))}function Zp(s){let e=s.ttlMs??Lb,t=Date.now(),o=[],n=[],r=hs(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Cc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=Dt.join(s.workspace,ln);try{em(i)}catch{}return{removed:o,errors:n}}function em(s){if(!dt.existsSync(s))return;let e=dt.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&em(Dt.join(s,t.name));dt.readdirSync(s).length===0&&dt.rmdirSync(s)}function _c(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var dt,Dt,Vt,ln,Lb,Bb,xc,Ec=G(()=>{"use strict";dt=y(require("node:fs"),1),Dt=y(require("node:path"),1),Vt=require("node:child_process"),ln=".monkeyscode-worktrees",Lb=24*60*60*1e3,Bb=500,xc=3;l($c,"createWorktree");l(Cc,"removeWorktree");l(Ub,"listWorktrees");l(hs,"listManagedWorktrees");l(Zp,"cleanStaleWorktrees");l(em,"cleanEmptyDirs");l(_c,"slugify")});var om={};Re(om,{mergeTeam:()=>Tc,runInWorktree:()=>Hb,showTeamStatus:()=>Fc,spawnTeam:()=>Hr});async function Hr(s){let e=Gb(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:_c(m),status:"queued"}));console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Spawning Agent Team: ${e}`)),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(` Tasks: ${t.length}`),console.log(` Max agents: ${s.maxAgents}`),console.log(` Model: ${s.model}`),console.log(a.dim(" "+"\u2500".repeat(50))),console.log("");for(let m of t)try{console.log(a.dim(` \u{1F4C1} Creating worktree for agent #${m.index}: "${m.task.substring(0,40)}..."`)),m.worktree=$c({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(g){m.status="failed",m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=J(),r=me()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let g=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let h=(0,mo.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let b=JSON.parse(h);m.filesChanged=b.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-g;try{(0,mo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,mo.execSync)(`git commit -m "feat: ${m.task.substring(0,72)}" --allow-empty`,{cwd:m.worktree.path,stdio:"pipe"})}catch{}console.log(a.green(` \u2705 Agent #${m.index} completed (${tm(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-g,m.error=h instanceof Error?h.message:String(h),console.error(a.red(` \u274C Agent #${m.index} failed: ${m.error.substring(0,80)}`))}},"runAgent");await l(async()=>{let m=[];for(let g of i){for(;c.size>=s.maxAgents;)await new Promise(b=>setTimeout(b,500));c.add(g.index);let h=u(g).finally(()=>c.delete(g.index));m.push(h)}await Promise.all(m)},"processQueue")();try{let m=un.join(s.workspace,".monkeyscode-worktrees",e);pt.mkdirSync(m,{recursive:!0});let g=un.join(m,"state.json");pt.writeFileSync(g,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(h=>({index:h.index,task:h.task,slug:h.slug,status:h.status,duration:h.duration,filesChanged:h.filesChanged,error:h.error,branch:h.worktree?.branch}))},null,2))}catch{}let p=t.filter(m=>m.status==="completed").length,f=t.filter(m=>m.status==="failed").length;return console.log(""),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(a.bold(` Team ${e}: ${p} completed, ${f} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function Fc(s){let e=un.join(s,".monkeyscode-worktrees");if(!pt.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=pt.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=un.join(e,u.name,"state.json");if(pt.existsSync(d))try{t.push(JSON.parse(pt.readFileSync(d,"utf8")))}catch{}}}catch{}let o=hs(s),n=new Set(t.map(c=>c.teamId)),r=new Map;for(let c of o){let d=(c.label?.split("/")||[])[0]||"unknown";n.has(d)||(r.has(d)||r.set(d,[]),r.get(d).push(c))}if(t.length===0&&r.size===0){console.log(a.dim(" No active agent teams found."));return}let i=l(c=>{switch(c){case"completed":return"\u2705";case"running":return"\u{1F504}";case"queued":return"\u23F3";case"failed":return"\u274C";default:return"?"}},"statusIcon");for(let c of t){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c.teamId}`));let u=" "+"\u2500".repeat(76);console.log(u),console.log(a.bold(` ${"Agent".padEnd(8)} ${"Task".padEnd(34)} ${"Status".padEnd(12)} ${"Duration".padEnd(10)} ${"Files".padEnd(6)}`)),console.log(u);for(let d of c.agents){let p=i(d.status),f=d.duration?tm(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",g=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+g+'"').padEnd(34)} ${(p+" "+Wb(d.status)).padEnd(12)} ${f.padEnd(10)} ${m.padEnd(6)}`)}console.log(u)}for(let[c,u]of r){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c}`)+a.dim(" (no state file)"));let d=" "+"\u2500".repeat(70);console.log(d);for(let p=0;p<u.length;p++){let f=u[p],m=f.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${f.branch.padEnd(30)}`)}console.log(d)}console.log("")}function Wb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Tc(s,e){let t=hs(s).filter(r=>r.label?.startsWith(e));if(t.length===0){console.error(a.red(` \u274C No worktrees found for team ${e}.`));return}console.log(""),console.log(a.bold(` \u{1F500} Merging team ${e} (${t.length} branches)`));let o=0,n=0;for(let r of t){let i=r.label?.split("/").slice(1).join("/")||"?";console.log(a.dim(` Merging: ${r.branch} (${i})`));try{(0,mo.execSync)(`git merge --no-ff "${r.branch}" -m "merge: team ${e} \u2014 ${i}"`,{cwd:s,stdio:"inherit"}),o++,console.log(a.green(` \u2705 Merged ${r.branch}`))}catch{n++,console.error(a.yellow(` \u26A0 Merge conflict on ${r.branch}. Resolve and continue.`)),console.log(a.dim(" After resolving: git merge --continue")),console.log(a.dim(" Then re-run: mc team merge "+e));return}}if(n===0){console.log(a.dim(" \u{1F9F9} Cleaning up worktrees..."));for(let r of t)try{Cc(s,r.path,!0)}catch{}}console.log(""),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.bold(` Merged: ${o}, Conflicts: ${n}`)),console.log("")}async function Hb(s,e,t){let o=_c(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=$c({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,mo.execSync)(`node "${process.argv[1]}" -p "${s.replace(/"/g,'\\"')}" --headless --auto-approve --model "${t}" --workspace "${r.path}" -o json`,{cwd:r.path,encoding:"utf8",timeout:6e5,env:{...process.env},stdio:"inherit"});try{(0,mo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,mo.execSync)(`git commit -m "feat: ${s.substring(0,72)}"`,{cwd:r.path,stdio:"pipe"})}catch{}console.log(a.green(" \u2705 Worktree task completed.")),console.log(a.dim(` Merge: git merge --no-ff ${r.branch}`))}catch(i){console.error(a.red(` \u274C Worktree task failed: ${i instanceof Error?i.message:i}`))}}function Gb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function tm(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var pt,un,mo,Rc=G(()=>{"use strict";pt=y(require("node:fs"),1),un=y(require("node:path"),1),mo=require("node:child_process");U();Ec();Z();te();l(Hr,"spawnTeam");l(Fc,"showTeamStatus");l(Wb,"capitalize");l(Tc,"mergeTeam");l(Hb,"runInWorktree");l(Gb,"generateTeamId");l(tm,"formatDuration")});var Gr={};Re(Gr,{MessageBroker:()=>dn});function qb(){try{let s=nm.join(rm.homedir(),".monkeyscode","daemon.port"),e=sm.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var sm,nm,rm,Ac,Pc,dn,pn=G(()=>{"use strict";sm=y(require("node:fs"),1),nm=y(require("node:path"),1),rm=y(require("node:os"),1);sn();Ac=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new lt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},Pc=class{constructor(e,t){this.platformUrl=e;this.token=t}static{l(this,"CloudTransport")}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async sendMessage(e,t,o){try{let n=await fetch(`${this.platformUrl}/api/messages`,{method:"POST",headers:this.headers(),body:JSON.stringify({from:e,to:t,content:o,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(!n.ok){let i=await n.text().catch(()=>"");return{success:!1,error:`HTTP ${n.status}: ${i}`}}return{success:!0,messageId:(await n.json()).messageId}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{let e=await fetch(`${this.platformUrl}/api/sessions`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).sessions||[]).map(o=>({id:o.id,task:o.task||o.prompt?.substring(0,80)||"(no task)",status:o.status||"running",type:o.type||"interactive",workspace:o.workspace||"",startedAt:new Date(o.startedAt||o.createdAt),model:o.model||"unknown"})):[]}catch{return[]}}async pollMessages(e){try{let t=await fetch(`${this.platformUrl}/api/messages/pending?session=${e}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)});if(!t.ok)return[];let n=((await t.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:!1}));for(let r of n)try{await fetch(`${this.platformUrl}/api/messages/${r.id}/ack`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)})}catch{}return n}catch{return[]}}async getMessageHistory(e,t){try{let o=await fetch(`${this.platformUrl}/api/messages?session=${e}&limit=${t}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return o.ok?((await o.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:r.delivered??!0})):[]}catch{return[]}}async register(){}async unregister(){}};l(qb,"readDaemonPort");dn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=qb();n?this.transport=new Ac(n):this.transport=new Pc(e,t)}async init(e,t,o){await this.transport.register(this.sessionId,e,t,o)}async dispose(){await this.transport.unregister(this.sessionId)}async sendMessage(e,t){return this.transport.sendMessage(this.sessionId,e,t)}async broadcast(e){return this.sendMessage("broadcast",e)}async listAgents(){return this.transport.listAgents()}async getMessageHistory(e=50){return this.transport.getMessageHistory(this.sessionId,e)}async checkPendingMessages(){return this.transport.pollMessages(this.sessionId)}onMessage(e){this.onMessageCallback=e}async pollMessages(){let e=await this.checkPendingMessages();if(this.onMessageCallback)for(let t of e)this.onMessageCallback(t);return e}static getToolSchemas(){return[{name:"SendMessage",description:"Send a message to another active agent session. Use when you make changes that affect shared code and other agents need to know.",parameters:{type:"object",properties:{target:{type:"string",description:'Target session ID (from ListAgents) or "broadcast" to notify all.'},message:{type:"string",description:"Message content describing what changed and what other agents should do."}},required:["target","message"]}},{name:"ListAgents",description:"List all active agent sessions on the current machine. Returns session IDs, tasks, and status.",parameters:{type:"object",properties:{}}}]}}});var am={};Re(am,{analyzeImpact:()=>im,notifyAffectedSessions:()=>zb});function im(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=vt.basename(d).toLowerCase(),f=d.toLowerCase();if(i.includes(p)&&.9>u&&(u=.9,c=`Task mentions "${p}" which was modified`),r.workspace){let m=vt.relative(r.workspace,d),g=vt.dirname(m).split(vt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Vb)if(m.pathPattern.test(f))for(let g of m.keywords)i.includes(g)&&.6>u&&(u=.6,c=`Modified ${p} (${g}-related) \u2014 task mentions "${g}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function zb(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=im(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>vt.basename(p)).join(", "):`${e.slice(0,3).map(p=>vt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
168
|
-
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var vt,Vb,
|
|
169
|
-
`);await i.run(c),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(c){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:c instanceof Error?c.message:String(c)})}finally{this.activeRuns.delete(e.name)}}updateState(e,t){let o=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};o.lastFired=Date.now(),o.fireCount++,o.lastResult=t,this.state.set(e,o),this.saveState()}saveState(){try{let e=
|
|
170
|
-
`),!0}function Bk(s){let e=[s.title,s.body,"--app-name=MonkeysCode",`--expire-time=${s.urgency==="critical"?0:1e4}`],t=s.urgency||"normal";e.push(`--urgency=${t}`);let o=["/usr/share/icons/hicolor/48x48/apps/monkeyscode.png","/usr/share/pixmaps/monkeyscode.png","dialog-information"];for(let n of o)if(n.startsWith("/")){if(
|
|
176
|
+
`),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=dt.statSync(i).birthtime}catch{}let f=i.split(Dt.sep),m=f.indexOf(pn.replace(/\//g,Dt.sep).split(Dt.sep)[0]),g=m>=0?f.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(pn),createdAt:p,label:g})}return t}function ys(s){return Ub(s).filter(e=>e.path.includes(pn))}function em(s){let e=s.ttlMs??Lb,t=Date.now(),o=[],n=[],r=ys(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Cc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=Dt.join(s.workspace,pn);try{tm(i)}catch{}return{removed:o,errors:n}}function tm(s){if(!dt.existsSync(s))return;let e=dt.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&tm(Dt.join(s,t.name));dt.readdirSync(s).length===0&&dt.rmdirSync(s)}function _c(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var dt,Dt,qt,pn,Lb,Bb,xc,Ec=G(()=>{"use strict";dt=b(require("node:fs"),1),Dt=b(require("node:path"),1),qt=require("node:child_process"),pn=".monkeyscode-worktrees",Lb=24*60*60*1e3,Bb=500,xc=3;l($c,"createWorktree");l(Cc,"removeWorktree");l(Ub,"listWorktrees");l(ys,"listManagedWorktrees");l(em,"cleanStaleWorktrees");l(tm,"cleanEmptyDirs");l(_c,"slugify")});var sm={};Ae(sm,{mergeTeam:()=>Tc,runInWorktree:()=>Hb,showTeamStatus:()=>Fc,spawnTeam:()=>Gr});async function Gr(s){let e=Gb(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:_c(m),status:"queued"}));console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Spawning Agent Team: ${e}`)),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(` Tasks: ${t.length}`),console.log(` Max agents: ${s.maxAgents}`),console.log(` Model: ${s.model}`),console.log(a.dim(" "+"\u2500".repeat(50))),console.log("");for(let m of t)try{console.log(a.dim(` \u{1F4C1} Creating worktree for agent #${m.index}: "${m.task.substring(0,40)}..."`)),m.worktree=$c({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(g){m.status="failed",m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=K(),r=fe()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let g=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let h=(0,fo.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let y=JSON.parse(h);m.filesChanged=y.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-g;try{(0,fo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,fo.execSync)(`git commit -m "feat: ${m.task.substring(0,72)}" --allow-empty`,{cwd:m.worktree.path,stdio:"pipe"})}catch{}console.log(a.green(` \u2705 Agent #${m.index} completed (${om(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-g,m.error=h instanceof Error?h.message:String(h),console.error(a.red(` \u274C Agent #${m.index} failed: ${m.error.substring(0,80)}`))}},"runAgent");await l(async()=>{let m=[];for(let g of i){for(;c.size>=s.maxAgents;)await new Promise(y=>setTimeout(y,500));c.add(g.index);let h=u(g).finally(()=>c.delete(g.index));m.push(h)}await Promise.all(m)},"processQueue")();try{let m=mn.join(s.workspace,".monkeyscode-worktrees",e);pt.mkdirSync(m,{recursive:!0});let g=mn.join(m,"state.json");pt.writeFileSync(g,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(h=>({index:h.index,task:h.task,slug:h.slug,status:h.status,duration:h.duration,filesChanged:h.filesChanged,error:h.error,branch:h.worktree?.branch}))},null,2))}catch{}let p=t.filter(m=>m.status==="completed").length,f=t.filter(m=>m.status==="failed").length;return console.log(""),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(a.bold(` Team ${e}: ${p} completed, ${f} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function Fc(s){let e=mn.join(s,".monkeyscode-worktrees");if(!pt.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=pt.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=mn.join(e,u.name,"state.json");if(pt.existsSync(d))try{t.push(JSON.parse(pt.readFileSync(d,"utf8")))}catch{}}}catch{}let o=ys(s),n=new Set(t.map(c=>c.teamId)),r=new Map;for(let c of o){let d=(c.label?.split("/")||[])[0]||"unknown";n.has(d)||(r.has(d)||r.set(d,[]),r.get(d).push(c))}if(t.length===0&&r.size===0){console.log(a.dim(" No active agent teams found."));return}let i=l(c=>{switch(c){case"completed":return"\u2705";case"running":return"\u{1F504}";case"queued":return"\u23F3";case"failed":return"\u274C";default:return"?"}},"statusIcon");for(let c of t){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c.teamId}`));let u=" "+"\u2500".repeat(76);console.log(u),console.log(a.bold(` ${"Agent".padEnd(8)} ${"Task".padEnd(34)} ${"Status".padEnd(12)} ${"Duration".padEnd(10)} ${"Files".padEnd(6)}`)),console.log(u);for(let d of c.agents){let p=i(d.status),f=d.duration?om(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",g=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+g+'"').padEnd(34)} ${(p+" "+Wb(d.status)).padEnd(12)} ${f.padEnd(10)} ${m.padEnd(6)}`)}console.log(u)}for(let[c,u]of r){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c}`)+a.dim(" (no state file)"));let d=" "+"\u2500".repeat(70);console.log(d);for(let p=0;p<u.length;p++){let f=u[p],m=f.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${f.branch.padEnd(30)}`)}console.log(d)}console.log("")}function Wb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Tc(s,e){let t=ys(s).filter(r=>r.label?.startsWith(e));if(t.length===0){console.error(a.red(` \u274C No worktrees found for team ${e}.`));return}console.log(""),console.log(a.bold(` \u{1F500} Merging team ${e} (${t.length} branches)`));let o=0,n=0;for(let r of t){let i=r.label?.split("/").slice(1).join("/")||"?";console.log(a.dim(` Merging: ${r.branch} (${i})`));try{(0,fo.execSync)(`git merge --no-ff "${r.branch}" -m "merge: team ${e} \u2014 ${i}"`,{cwd:s,stdio:"inherit"}),o++,console.log(a.green(` \u2705 Merged ${r.branch}`))}catch{n++,console.error(a.yellow(` \u26A0 Merge conflict on ${r.branch}. Resolve and continue.`)),console.log(a.dim(" After resolving: git merge --continue")),console.log(a.dim(" Then re-run: mc team merge "+e));return}}if(n===0){console.log(a.dim(" \u{1F9F9} Cleaning up worktrees..."));for(let r of t)try{Cc(s,r.path,!0)}catch{}}console.log(""),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.bold(` Merged: ${o}, Conflicts: ${n}`)),console.log("")}async function Hb(s,e,t){let o=_c(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=$c({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,fo.execSync)(`node "${process.argv[1]}" -p "${s.replace(/"/g,'\\"')}" --headless --auto-approve --model "${t}" --workspace "${r.path}" -o json`,{cwd:r.path,encoding:"utf8",timeout:6e5,env:{...process.env},stdio:"inherit"});try{(0,fo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,fo.execSync)(`git commit -m "feat: ${s.substring(0,72)}"`,{cwd:r.path,stdio:"pipe"})}catch{}console.log(a.green(" \u2705 Worktree task completed.")),console.log(a.dim(` Merge: git merge --no-ff ${r.branch}`))}catch(i){console.error(a.red(` \u274C Worktree task failed: ${i instanceof Error?i.message:i}`))}}function Gb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function om(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var pt,mn,fo,Rc=G(()=>{"use strict";pt=b(require("node:fs"),1),mn=b(require("node:path"),1),fo=require("node:child_process");W();Ec();Q();ee();l(Gr,"spawnTeam");l(Fc,"showTeamStatus");l(Wb,"capitalize");l(Tc,"mergeTeam");l(Hb,"runInWorktree");l(Gb,"generateTeamId");l(om,"formatDuration")});var qr={};Ae(qr,{MessageBroker:()=>fn});function qb(){try{let s=rm.join(im.homedir(),".monkeyscode","daemon.port"),e=nm.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var nm,rm,im,Ac,Pc,fn,gn=G(()=>{"use strict";nm=b(require("node:fs"),1),rm=b(require("node:path"),1),im=b(require("node:os"),1);an();Ac=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new lt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},Pc=class{constructor(e,t){this.platformUrl=e;this.token=t}static{l(this,"CloudTransport")}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async sendMessage(e,t,o){try{let n=await fetch(`${this.platformUrl}/api/messages`,{method:"POST",headers:this.headers(),body:JSON.stringify({from:e,to:t,content:o,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(!n.ok){let i=await n.text().catch(()=>"");return{success:!1,error:`HTTP ${n.status}: ${i}`}}return{success:!0,messageId:(await n.json()).messageId}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{let e=await fetch(`${this.platformUrl}/api/sessions`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).sessions||[]).map(o=>({id:o.id,task:o.task||o.prompt?.substring(0,80)||"(no task)",status:o.status||"running",type:o.type||"interactive",workspace:o.workspace||"",startedAt:new Date(o.startedAt||o.createdAt),model:o.model||"unknown"})):[]}catch{return[]}}async pollMessages(e){try{let t=await fetch(`${this.platformUrl}/api/messages/pending?session=${e}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)});if(!t.ok)return[];let n=((await t.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:!1}));for(let r of n)try{await fetch(`${this.platformUrl}/api/messages/${r.id}/ack`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)})}catch{}return n}catch{return[]}}async getMessageHistory(e,t){try{let o=await fetch(`${this.platformUrl}/api/messages?session=${e}&limit=${t}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return o.ok?((await o.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:r.delivered??!0})):[]}catch{return[]}}async register(){}async unregister(){}};l(qb,"readDaemonPort");fn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=qb();n?this.transport=new Ac(n):this.transport=new Pc(e,t)}async init(e,t,o){await this.transport.register(this.sessionId,e,t,o)}async dispose(){await this.transport.unregister(this.sessionId)}async sendMessage(e,t){return this.transport.sendMessage(this.sessionId,e,t)}async broadcast(e){return this.sendMessage("broadcast",e)}async listAgents(){return this.transport.listAgents()}async getMessageHistory(e=50){return this.transport.getMessageHistory(this.sessionId,e)}async checkPendingMessages(){return this.transport.pollMessages(this.sessionId)}onMessage(e){this.onMessageCallback=e}async pollMessages(){let e=await this.checkPendingMessages();if(this.onMessageCallback)for(let t of e)this.onMessageCallback(t);return e}static getToolSchemas(){return[{name:"SendMessage",description:"Send a message to another active agent session. Use when you make changes that affect shared code and other agents need to know.",parameters:{type:"object",properties:{target:{type:"string",description:'Target session ID (from ListAgents) or "broadcast" to notify all.'},message:{type:"string",description:"Message content describing what changed and what other agents should do."}},required:["target","message"]}},{name:"ListAgents",description:"List all active agent sessions on the current machine. Returns session IDs, tasks, and status.",parameters:{type:"object",properties:{}}}]}}});var cm={};Ae(cm,{analyzeImpact:()=>am,notifyAffectedSessions:()=>zb});function am(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=vt.basename(d).toLowerCase(),f=d.toLowerCase();if(i.includes(p)&&.9>u&&(u=.9,c=`Task mentions "${p}" which was modified`),r.workspace){let m=vt.relative(r.workspace,d),g=vt.dirname(m).split(vt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Vb)if(m.pathPattern.test(f))for(let g of m.keywords)i.includes(g)&&.6>u&&(u=.6,c=`Modified ${p} (${g}-related) \u2014 task mentions "${g}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function zb(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=am(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>vt.basename(p)).join(", "):`${e.slice(0,3).map(p=>vt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
177
|
+
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var vt,Vb,lm=G(()=>{"use strict";vt=b(require("node:path"),1),Vb=[{pathPattern:/\bauth\b/i,keywords:["auth","login","session","token","jwt","permission"]},{pathPattern:/\bapi\b/i,keywords:["api","endpoint","route","handler","rest","graphql"]},{pathPattern:/\bmodel\b|\btypes?\b|\binterface\b/i,keywords:["model","type","interface","schema","struct"]},{pathPattern:/\bconfig\b|\bsettings?\b/i,keywords:["config","settings","env","environment"]},{pathPattern:/\btest\b|\bspec\b/i,keywords:["test","spec","assert","mock","fixture"]},{pathPattern:/\bdatabase\b|\bdb\b|\bstore\b/i,keywords:["database","migration","schema","query","sql"]},{pathPattern:/\butils?\b|\bhelpers?\b|\blib\b|\bshared\b|\bcommon\b/i,keywords:["util","helper","shared","common","lib"]},{pathPattern:/\bstyle\b|\bcss\b|\btheme\b/i,keywords:["style","css","theme","layout","design"]},{pathPattern:/package\.json|cargo\.toml|go\.mod/i,keywords:["dependency","package","install","version"]}];l(am,"analyzeImpact");l(zb,"notifyAffectedSessions")});var dm={};Ae(dm,{fetchModels:()=>um,getModelInfo:()=>Jb});async function um(){let s=K(),e=await Fe(),t={};e&&(t.Authorization=`Bearer ${e}`);let o=await fetch(`${s.platformUrl}/v1/models`,{headers:t});if(!o.ok)throw o.status===401?new Error("Authentication expired \u2014 run `mc auth login`."):new Error(`Failed to fetch models: ${o.status} ${o.statusText}`);let n=await o.json(),r,i=n.flat;if(Array.isArray(i)&&i.length>0)r=i.map(c=>({id:c.id,name:c.display_name||c.id,contextWindow:c.context_window||128e3,supportsReasoning:c.supports_thinking||!1,supportsTools:!0,inputCostPer1M:c.cost_input_micros?c.cost_input_micros/1e6:void 0,outputCostPer1M:c.cost_output_micros?c.cost_output_micros/1e6:void 0}));else{let c=n.data;if(!Array.isArray(c))return[];r=c.map(u=>{let d=u.capabilities,p=u.pricing;return{id:u.id,name:u.name||u.id,contextWindow:u.context_window||128e3,supportsReasoning:d?.reasoning||!1,supportsTools:d?.tools!==!1,inputCostPer1M:p?.input_per_1m,outputCostPer1M:p?.output_per_1m}})}return ld(r),r}async function Jb(s){try{return(await um()).find(t=>t.id===s)||null}catch{return null}}var pm=G(()=>{"use strict";ee();Q();gr();l(um,"fetchModels");l(Jb,"getModelInfo")});var Om={};Ae(Om,{default:()=>pw});var pw,Im=G(()=>{pw={name:"monkeyscode-cli",version:"0.1.8",description:"MonkeysCode CLI \u2014 standalone terminal coding agent. Works independently of the IDE and Agent Manager.",license:"MIT",type:"module",main:"dist/monkeyscode-cli.cjs",bin:{mc:"dist/monkeyscode-cli.cjs",mcode:"dist/monkeyscode-cli.cjs",monkeyscode:"dist/monkeyscode-cli.cjs"},files:["dist/monkeyscode-cli.cjs","README.md","LICENSE"],scripts:{build:"tsc","build:watch":"tsc --watch",bundle:"node esbuild.config.mjs","bundle:prod":"node esbuild.config.mjs --prod","build:sea":"bash scripts/build.sh --sea",release:"bash scripts/build.sh --all --checksums",dev:"tsx src/main.ts",start:"node dist/main.js",lint:"eslint src/",test:"node --import tsx --test tests/**/*.test.ts","test:watch":"node --import tsx --test --watch tests/**/*.test.ts",clean:"rm -rf dist",prepublishOnly:"npm run clean && npm run bundle:prod"},keywords:["monkeyscode","cli","coding-agent","terminal","ai","standalone"],dependencies:{chalk:"^5.4.0","cli-highlight":"^2.1.11",commander:"^13.0.0",diff:"^7.0.0",marked:"^18.0.11",ora:"^8.1.0",ws:"^8.18.0"},devDependencies:{"@types/diff":"^6.0.0","@types/node":"^22.0.0","@types/ws":"^8.5.0",esbuild:"^0.24.0",tsx:"^4.19.0",typescript:"^5.7.0"},engines:{node:">=20.0.0"}}});var ti,cf=G(()=>{"use strict";ti=class{static{l(this,"CronScheduler")}jobs=new Map;running=!1;add(e){let t={...e,timer:null,runCount:0,nextRunAt:null,active:!1};this.jobs.set(e.id,t),this.running&&this.scheduleNext(t)}remove(e){let t=this.jobs.get(e);return t?(t.timer&&clearTimeout(t.timer),this.jobs.delete(e),!0):!1}start(){this.running=!0;for(let e of this.jobs.values())this.scheduleNext(e)}stop(){this.running=!1;for(let e of this.jobs.values())e.timer&&(clearTimeout(e.timer),e.timer=null),e.active=!1}list(){return[...this.jobs.values()].map(e=>({id:e.id,expression:e.expression,nextRunAt:e.nextRunAt,runCount:e.runCount,active:e.active}))}scheduleNext(e){if(!this.running||e.maxRuns&&e.runCount>=e.maxRuns)return;let t=this.getNextCronTime(e.expression);if(!t)return;e.nextRunAt=t,e.active=!0;let o=t.getTime()-Date.now();e.timer=setTimeout(async()=>{e.runCount++;try{await e.callback()}catch{}this.scheduleNext(e)},Math.max(o,0)),e.timer&&typeof e.timer.unref=="function"&&e.timer.unref()}getNextCronTime(e){let t=e.trim().split(/\s+/);if(t.length!==5)return null;let[o,n,r,i,c]=t,u=new Date;for(let d=0;d<366*24*60;d++){let p=new Date(u.getTime()+d*6e4);if(p.setSeconds(0,0),!(p.getTime()<=u.getTime())&&this.matchesCronField(p.getMinutes(),o,0,59)&&this.matchesCronField(p.getHours(),n,0,23)&&this.matchesCronField(p.getDate(),r,1,31)&&this.matchesCronField(p.getMonth()+1,i,1,12)&&this.matchesCronField(p.getDay(),c,0,6))return p}return null}matchesCronField(e,t,o,n){if(t==="*")return!0;let r=t.split(",");for(let i of r)if(i.includes("/")){let[c,u]=i.split("/"),d=parseInt(u,10);if(c==="*"){if((e-o)%d===0)return!0}else if(c.includes("-")){let[p,f]=c.split("-").map(Number);if(e>=p&&e<=f&&(e-p)%d===0)return!0}}else if(i.includes("-")){let[c,u]=i.split("-").map(Number);if(e>=c&&e<=u)return!0}else if(parseInt(i,10)===e)return!0;return!1}}});var $n,Yc,oi,lf=G(()=>{"use strict";$n=b(require("node:fs"),1),Yc=b(require("node:path"),1),oi=class{static{l(this,"FileWatcher")}workspace;rules=[];watchers=[];pendingChanges=new Map;debounceMs=500;running=!1;constructor(e,t=500){this.workspace=e,this.debounceMs=t}watch(e,t){this.rules.push({patterns:e,callback:t})}start(){if(!this.running){this.running=!0;try{let e=$n.watch(this.workspace,{recursive:!0},(t,o)=>{!o||!this.running||o.startsWith(".git/")||o.includes("node_modules/")||this.onFileChange(o)});this.watchers.push(e)}catch{this.watchDirectories(this.workspace)}}}stop(){this.running=!1;for(let e of this.watchers)try{e.close()}catch{}this.watchers=[];for(let e of this.pendingChanges.values())clearTimeout(e);this.pendingChanges.clear()}onFileChange(e){let t=this.pendingChanges.get(e);t&&clearTimeout(t),this.pendingChanges.set(e,setTimeout(()=>{this.pendingChanges.delete(e),this.fireRules(e)},this.debounceMs))}fireRules(e){for(let t of this.rules)if(this.matchesAny(e,t.patterns))try{t.callback([e])}catch{}}matchesAny(e,t){for(let o of t)if(o==="**/*"||this.globMatch(e,o))return!0;return!1}globMatch(e,t){let o=t.replace(/\./g,"\\.").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/{{DOUBLESTAR}}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${o}$`).test(e)}watchDirectories(e,t=0){if(!(t>3))try{let o=$n.readdirSync(e,{withFileTypes:!0});for(let n of o){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let r=Yc.join(e,n.name);try{let i=$n.watch(r,(c,u)=>{!u||!this.running||this.onFileChange(Yc.join(n.name,u))});this.watchers.push(i),this.watchDirectories(r,t+1)}catch{}}}catch{}}}});var df={};Ae(df,{TriggerEngine:()=>Xc});var $t,Cn,uf,Xc,pf=G(()=>{"use strict";$t=b(require("node:fs"),1),Cn=b(require("node:path"),1),uf=require("node:events");Ke();Q();cf();lf();Xc=class extends uf.EventEmitter{static{l(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=Cn.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new ti,this.fileWatcher=new oi(e.workspace),this.loadState()}loadTriggers(){let e=Cn.join(this.opts.workspace,".monkeyscode","triggers.json");if(!$t.existsSync(e))return this.triggers=[],[];try{let t=JSON.parse($t.readFileSync(e,"utf8"));return this.triggers=(t.triggers||[]).filter(o=>o.enabled!==!1),this.triggers}catch{return[]}}start(){this.loadTriggers();for(let e of this.triggers)e.event==="cron"&&e.schedule&&this.cronScheduler.add({id:e.name,expression:e.schedule,callback:l(()=>this.fire(e,{type:"cron",payload:{schedule:e.schedule},source:"cron-scheduler",timestamp:Date.now()}),"callback")}),e.event==="file.changed"&&this.fileWatcher.watch(e.watchPatterns||["**/*"],t=>{this.fire(e,{type:"file.changed",payload:{files:t},source:"file-watcher",timestamp:Date.now()})});this.cronScheduler.start(),this.fileWatcher.start(),this.emit("started",{triggerCount:this.triggers.length})}stop(){this.cronScheduler.stop(),this.fileWatcher.stop();for(let e of this.activeRuns.values())e.cancel();this.activeRuns.clear(),this.saveState()}async processEvent(e){for(let t of this.triggers)this.matches(t,e)&&await this.fire(t,e)}listTriggers(){return this.triggers.map(e=>({...e,state:this.state.get(e.name)||{name:e.name,lastFired:0,fireCount:0,lastResult:null}}))}dryRun(e){let t=this.triggers.find(o=>o.name===e);return t?{matched:!0,prompt:t.prompt,model:t.model||"default"}:{matched:!1,prompt:"",model:""}}matches(e,t){if(e.event!==t.type)return!1;if(e.filter){for(let[o,n]of Object.entries(e.filter))if(t.payload[o]!==n)return!1}return!0}async fire(e,t){let o=this.state.get(e.name),n=(e.cooldownSeconds||300)*1e3;if(o&&Date.now()-o.lastFired<n){this.emit("cooldown",{trigger:e.name,remaining:n-(Date.now()-o.lastFired)});return}if(this.activeRuns.has(e.name))return;this.emit("firing",{trigger:e.name,event:t.type});let r=K(),i=new xe({platformUrl:r.platformUrl,token:this.opts.token,model:e.model||r.defaultModel||"capuchin-reason",workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!0,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeRuns.set(e.name,i);try{let c=[`[Trigger: ${e.name}]`,`Event: ${t.type}`,t.payload?`Payload: ${JSON.stringify(t.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
|
|
178
|
+
`);await i.run(c),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(c){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:c instanceof Error?c.message:String(c)})}finally{this.activeRuns.delete(e.name)}}updateState(e,t){let o=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};o.lastFired=Date.now(),o.fireCount++,o.lastResult=t,this.state.set(e,o),this.saveState()}saveState(){try{let e=Cn.dirname(this.statePath);$t.mkdirSync(e,{recursive:!0}),$t.writeFileSync(this.statePath,JSON.stringify(Object.fromEntries(this.state),null,2))}catch{}}loadState(){try{if($t.existsSync(this.statePath)){let e=JSON.parse($t.readFileSync(this.statePath,"utf8"));this.state=new Map(Object.entries(e))}}catch{this.state=new Map}}}});var ff={};Ae(ff,{GitHubWebhookServer:()=>Qc});var mf,vs,Qc,gf=G(()=>{"use strict";mf=b(require("node:http"),1),vs=b(require("node:crypto"),1),Qc=class s{static{l(this,"GitHubWebhookServer")}server=null;opts;constructor(e){this.opts={port:9122,...e}}async start(){return new Promise((e,t)=>{this.server=mf.createServer(async(o,n)=>{if(o.method!=="POST"||o.url!=="/webhook"){n.writeHead(404),n.end("Not Found");return}try{let r=await this.readBody(o),i=o.headers["x-github-event"],c=o.headers["x-hub-signature-256"],u=o.headers["x-github-delivery"]||vs.randomUUID();if(this.opts.secret&&!this.validateSignature(r,c,this.opts.secret)){n.writeHead(401),n.end("Invalid signature");return}let d=JSON.parse(r),p={event:i||"unknown",payload:d,deliveryId:u};await this.opts.onEvent(p),n.writeHead(200,{"Content-Type":"application/json"}),n.end(JSON.stringify({ok:!0,event:i,deliveryId:u}))}catch{n.writeHead(500),n.end("Internal Server Error")}}),this.server.listen(this.opts.port,()=>{e(this.opts.port)}),this.server.on("error",t)})}stop(){return new Promise(e=>{this.server?(this.server.close(()=>e()),this.server=null):e()})}static eventMappings(){return{push:"github.push",pull_request:"github.pull_request","pull_request.opened":"github.pull_request.opened","pull_request.closed":"github.pull_request.closed","pull_request.merged":"github.pull_request.merged",check_run:"github.check_run","check_run.completed":"github.check_run.completed","check_run.failed":"github.check_run.failed",issue_comment:"github.issue_comment","issue_comment.created":"github.issue_comment.created",issues:"github.issues","issues.opened":"github.issues.opened",workflow_run:"github.workflow_run","workflow_run.completed":"github.workflow_run.completed"}}static mapEventType(e,t){if(t){let o=`github.${e}.${t}`,n=`github.${e}`,r=s.eventMappings();return o in r?o:n}return`github.${e}`}readBody(e){return new Promise((t,o)=>{let n=[];e.on("data",r=>n.push(r)),e.on("end",()=>t(Buffer.concat(n).toString())),e.on("error",o)})}validateSignature(e,t,o){if(!t)return!1;let n="sha256="+vs.createHmac("sha256",o).update(e).digest("hex");return vs.timingSafeEqual(Buffer.from(t),Buffer.from(n))}}});var Sg={};Ae(Sg,{getNotificationBackend:()=>jk,notifyJobComplete:()=>Mk,notifyUpdateAvailable:()=>Ok,sendNotification:()=>dl,supportsNotifications:()=>Ik});function dl(s){if(process.env.CI==="true"||process.env.CI==="1")return!1;try{switch(process.platform){case"darwin":return Nk(s);case"linux":return Lk(s);case"win32":return Hk(s);default:return!1}}catch{return!1}}function Mk(s,e,t){return dl({title:t?"\u2705 Job Complete":"\u274C Job Failed",body:`Job ${s}: ${e}`,subtitle:"MonkeysCode",sound:t?"Glass":"Basso",urgency:t?"normal":"critical"})}function Ok(s){return dl({title:"\u{1F504} Update Available",body:`MonkeysCode v${s} is available. Run: mc update`,subtitle:"MonkeysCode",urgency:"low"})}function Ik(){if(process.env.CI==="true"||process.env.CI==="1")return!1;switch(process.platform){case"darwin":return Et("osascript");case"linux":return!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY?!1:Et("notify-send")||Et("kdialog")||Et("zenity");case"win32":return!0;default:return!1}}function jk(){switch(process.platform){case"darwin":return"macOS (osascript)";case"linux":return Et("notify-send")?"Linux (notify-send)":Et("kdialog")?"Linux (kdialog)":Et("zenity")?"Linux (zenity)":"Linux (terminal bell)";case"win32":return"Windows (PowerShell toast)";default:return"Unsupported"}}function Nk(s){let e=ui(s.title),o=`display notification "${ui(s.body)}" with title "${e}"`;s.subtitle&&(o+=` subtitle "${ui(s.subtitle)}"`),s.sound&&(o+=` sound name "${ui(s.sound)}"`);let n=ll.join(ul.tmpdir(),`mc-notify-${process.pid}.scpt`);try{return Do.writeFileSync(n,o,"utf8"),(0,Xt.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{Do.unlinkSync(n)}catch{}}}function ui(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Lk(s){if(!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)){if(Et("notify-send"))return Bk(s);if(Et("kdialog"))return Uk(s);if(Et("zenity"))return Wk(s)}return process.stderr.write("\x07"),process.stderr.write(`[Notification] ${s.title}: ${s.body}
|
|
179
|
+
`),!0}function Bk(s){let e=[s.title,s.body,"--app-name=MonkeysCode",`--expire-time=${s.urgency==="critical"?0:1e4}`],t=s.urgency||"normal";e.push(`--urgency=${t}`);let o=["/usr/share/icons/hicolor/48x48/apps/monkeyscode.png","/usr/share/pixmaps/monkeyscode.png","dialog-information"];for(let n of o)if(n.startsWith("/")){if(Do.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,Xt.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Uk(s){try{return(0,Xt.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Wk(s){try{return(0,Xt.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Hk(s){let e=vg(s.title),t=vg(s.body),o=`
|
|
171
180
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
172
181
|
|
|
173
182
|
# Try WinRT Toast (Windows 10 1709+)
|
|
@@ -231,55 +240,55 @@ try {
|
|
|
231
240
|
catch {}
|
|
232
241
|
|
|
233
242
|
exit 1
|
|
234
|
-
`,n=
|
|
235
|
-
${e}`,"wrappedToString"),Dh=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),vh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),Sh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=kh.bind(null,o,e.toString());Object.defineProperty(n,"name",vh);let{writable:r,enumerable:i,configurable:c}=Dh;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function ji(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))yh(s,e,n,t);return wh(s,e),Sh(s,e,o),s}l(ji,"mimicFunction");var Wn=new WeakMap,Wl=l((s,e={})=>{if(typeof s!="function")throw new TypeError("Expected a function");let t,o=0,n=s.displayName||s.name||"<anonymous>",r=l(function(...i){if(Wn.set(r,++o),o===1)t=s.apply(this,i),s=void 0;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return t},"onetime");return ji(r,s),Wn.set(r,o),r},"onetime");Wl.callCount=s=>{if(!Wn.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Wn.get(s)};var Hl=Wl;var So=[];So.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&So.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&So.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Hn=l(s=>!!s&&typeof s=="object"&&typeof s.removeListener=="function"&&typeof s.emit=="function"&&typeof s.reallyExit=="function"&&typeof s.listeners=="function"&&typeof s.kill=="function"&&typeof s.pid=="number"&&typeof s.on=="function","processOk"),Ni=Symbol.for("signal-exit emitter"),Li=globalThis,xh=Object.defineProperty.bind(Object),Bi=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Li[Ni])return Li[Ni];xh(Li,Ni,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let o=this.listeners[e],n=o.indexOf(t);n!==-1&&(n===0&&o.length===1?o.length=0:o.splice(n,1))}emit(e,t,o){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,o)===!0||n;return e==="exit"&&(n=this.emit("afterExit",t,o)||n),n}},Gn=class{static{l(this,"SignalExitBase")}},$h=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Ui=class extends Gn{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Wi=class extends Gn{static{l(this,"SignalExit")}#i=Hi.platform==="win32"?"SIGINT":"SIGHUP";#o=new Bi;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of So)this.#t[t]=()=>{let o=this.#e.listeners(t),{count:n}=this.#o,r=e;if(typeof r.__signal_exit_emitter__=="object"&&typeof r.__signal_exit_emitter__.count=="number"&&(n+=r.__signal_exit_emitter__.count),o.length===n){this.unload();let i=this.#o.emit("exit",null,t),c=t==="SIGHUP"?this.#i:t;i||e.kill(e.pid,c)}};this.#p=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Hn(this.#e))return()=>{};this.#r===!1&&this.load();let o=t?.alwaysLast?"afterExit":"exit";return this.#o.on(o,e),()=>{this.#o.removeListener(o,e),this.#o.listeners.exit.length===0&&this.#o.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#r){this.#r=!0,this.#o.count+=1;for(let e of So)try{let t=this.#t[e];t&&this.#e.on(e,t)}catch{}this.#e.emit=(e,...t)=>this.#m(e,...t),this.#e.reallyExit=e=>this.#s(e)}}unload(){this.#r&&(this.#r=!1,So.forEach(e=>{let t=this.#t[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch{}}),this.#e.emit=this.#n,this.#e.reallyExit=this.#p,this.#o.count-=1)}#s(e){return Hn(this.#e)?(this.#e.exitCode=e||0,this.#o.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...t){let o=this.#n;if(e==="exit"&&Hn(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);let n=o.call(this.#e,e,...t);return this.#o.emit("exit",this.#e.exitCode,null),n}else return o.call(this.#e,e,...t)}},Hi=globalThis.process,{onExit:Gl,load:ND,unload:LD}=$h(Hn(Hi)?new Wi(Hi):new Ui);var ql=Os.default.stderr.isTTY?Os.default.stderr:Os.default.stdout.isTTY?Os.default.stdout:void 0,Ch=ql?Hl(()=>{Gl(()=>{ql.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Vl=Ch;var qn=!1,Yo={};Yo.show=(s=Gi.default.stderr)=>{s.isTTY&&(qn=!1,s.write("\x1B[?25h"))};Yo.hide=(s=Gi.default.stderr)=>{s.isTTY&&(Vl(),qn=!0,s.write("\x1B[?25l"))};Yo.toggle=(s,e)=>{s!==void 0&&(qn=s),qn?Yo.show(e):Yo.hide(e)};var qi=Yo;var Ls=y(Vi(),1);U();var ze=y(require("node:process"),1);function zi(){return ze.default.platform!=="win32"?ze.default.env.TERM!=="linux":!!ze.default.env.CI||!!ze.default.env.WT_SESSION||!!ze.default.env.TERMINUS_SUBLIME||ze.default.env.ConEmuTask==="{cmd::Cmder}"||ze.default.env.TERM_PROGRAM==="Terminus-Sublime"||ze.default.env.TERM_PROGRAM==="vscode"||ze.default.env.TERM==="xterm-256color"||ze.default.env.TERM==="alacritty"||ze.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(zi,"isUnicodeSupported");var Eh={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},Fh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},Th=zi()?Eh:Fh,Is=Th;function Ji({onlyFirst:s=!1}={}){let n="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(n,s?void 0:"g")}l(Ji,"ansiRegex");var Rh=Ji();function js(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(Rh,"")}l(js,"stripAnsi");var Yl=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Xl=12288,Ql=65510,Zl=[12288,12288,65281,65376,65504,65510];var eu=4352,tu=262141,Ki=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var zn=l((s,e)=>{let t=0,o=Math.floor(s.length/2)-1;for(;t<=o;){let n=Math.floor((t+o)/2),r=n*2;if(e<s[r])o=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1},"isInRange");var ou=19968,[Mh,Oh]=Ih(Ki);function Ih(s){let e=s[0],t=s[1];for(let o=0;o<s.length;o+=2){let n=s[o],r=s[o+1];if(ou>=n&&ou<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(Ih,"findWideFastPathRange");var su=l(s=>s<161||s>1114109?!1:zn(Yl,s),"isAmbiguous"),nu=l(s=>s<Xl||s>Ql?!1:zn(Zl,s),"isFullWidth");var ru=l(s=>s>=Mh&&s<=Oh?!0:s<eu||s>tu?!1:zn(Ki,s),"isWide");function jh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(jh,"validate");function iu(s,{ambiguousAsWide:e=!1}={}){return jh(s),nu(s)||ru(s)||e&&su(s)?2:1}l(iu,"eastAsianWidth");var lu=y(cu(),1);var Nh=new Intl.Segmenter,Lh=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Yi(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=js(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of Nh.segment(s)){let c=i.codePointAt(0);if(!(c<=31||c>=127&&c<=159)&&!(c>=8203&&c<=8207||c===65279)&&!(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)&&!(c>=55296&&c<=57343)&&!(c>=65024&&c<=65039)&&!Lh.test(i)){if((0,lu.default)().test(i)){n+=2;continue}n+=iu(c,r)}}return n}l(Yi,"stringWidth");function Xi({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(Xi,"isInteractive");var Qi=y(require("node:process"),1);function Zi(){let{env:s}=Qi.default,{TERM:e,TERM_PROGRAM:t}=s;return Qi.default.platform!=="win32"?e!=="linux":!!s.WT_SESSION||!!s.TERMINUS_SUBLIME||s.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||s.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Zi,"isUnicodeSupported");var st=y(require("node:process"),1);var Bh=3,ea=class{static{l(this,"StdinDiscarder")}#i=0;start(){this.#i++,this.#i===1&&this.#o()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#o(){st.default.platform==="win32"||!st.default.stdin.isTTY||(st.default.stdin.setRawMode(!0),st.default.stdin.on("data",this.#n),st.default.stdin.resume())}#e(){st.default.stdin.isTTY&&(st.default.stdin.off("data",this.#n),st.default.stdin.pause(),st.default.stdin.setRawMode(!1))}#n(e){e[0]===Bh&&st.default.emit("SIGINT")}},Uh=new ea,ta=Uh;var Wh=y(Vi(),1);var oa=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#g;#l;#u;#d;#h;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Ns.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Xi({stream:this.#s}),this.#u=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Ns.default.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(t){this.#i=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#n}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#f()}get interval(){return this.#g??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#g=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!Zi())this.#r=Ls.default.line;else if(e===void 0)this.#r=Ls.default.dots;else if(e!=="default"&&Ls.default[e])this.#r=Ls.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#h}set text(e=""){this.#h=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#f()}get isSpinning(){return this.#m!==void 0}#y(e=this.#a,t=" "){return typeof e=="string"&&e!==""?e+t:typeof e=="function"?e()+t:""}#b(e=this.#c,t=" "){return typeof e=="string"&&e!==""?t+e:typeof e=="function"?t+e():""}#f(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),o=this.#b(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#h+"--"+o;this.#e=0;for(let r of js(n).split(`
|
|
236
|
-
`))this.#e+=Math.max(1,Math.ceil(
|
|
237
|
-
`),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&
|
|
238
|
-
`;return this.stop(),this.#s.write(p),this}};function
|
|
239
|
-
`),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,f=n.horizontal.repeat(Math.max(0,i-
|
|
240
|
-
`)}l(
|
|
243
|
+
`,n=ll.join(ul.tmpdir(),`mc-notify-${process.pid}.ps1`);try{let r=Buffer.from([239,187,191]),i=Buffer.concat([r,Buffer.from(o,"utf8")]);return Do.writeFileSync(n,i),(0,Xt.execSync)(`powershell -NoProfile -ExecutionPolicy Bypass -File "${n}"`,{stdio:"pipe",timeout:15e3}),!0}catch{return!1}finally{try{Do.unlinkSync(n)}catch{}}}function vg(s){return s.replace(/'/g,"''")}function Et(s){try{return process.platform==="win32"?(0,Xt.execSync)(`where ${s} 2>NUL`,{stdio:"pipe"}):(0,Xt.execSync)(`command -v ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}var Do,ll,ul,Xt,xg=G(()=>{"use strict";Do=b(require("node:fs"),1),ll=b(require("node:path"),1),ul=b(require("node:os"),1),Xt=require("node:child_process");l(dl,"sendNotification");l(Mk,"notifyJobComplete");l(Ok,"notifyUpdateAvailable");l(Ik,"supportsNotifications");l(jk,"getNotificationBackend");l(Nk,"notifyMac");l(ui,"escapeAS");l(Lk,"notifyLinux");l(Bk,"notifyLinuxLibnotify");l(Uk,"notifyLinuxKdialog");l(Wk,"notifyLinuxZenity");l(Hk,"notifyWindows");l(vg,"escapePowerShell");l(Et,"commandExists")});var El=b(_l(),1),{program:aD,createCommand:cD,createArgument:lD,createOption:uD,CommanderError:dD,InvalidArgumentError:pD,InvalidOptionArgumentError:mD,Command:Fl,Argument:fD,Option:Rt,Help:gD}=El.default;var L=b(require("node:path"),1),Y=b(require("node:fs"),1);var fm=b(require("node:readline"),1),J=b(require("node:path"),1),j=b(require("node:fs"),1),Qe=require("node:child_process");W();W();var Bs=b(require("node:process"),1);W();var Hi=b(require("node:process"),1);var js=b(require("node:process"),1);var hh=l((s,e,t,o)=>{if(t==="length"||t==="prototype"||t==="arguments"||t==="caller")return;let n=Object.getOwnPropertyDescriptor(s,t),r=Object.getOwnPropertyDescriptor(e,t);!yh(n,r)&&o||Object.defineProperty(s,t,r)},"copyProperty"),yh=l(function(s,e){return s===void 0||s.configurable||s.writable===e.writable&&s.enumerable===e.enumerable&&s.configurable===e.configurable&&(s.writable||s.value===e.value)},"canCopyProperty"),bh=l((s,e)=>{let t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(s)&&Object.setPrototypeOf(s,t)},"changePrototype"),wh=l((s,e)=>`/* Wrapped ${s}*/
|
|
244
|
+
${e}`,"wrappedToString"),kh=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Dh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),vh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=wh.bind(null,o,e.toString());Object.defineProperty(n,"name",Dh);let{writable:r,enumerable:i,configurable:c}=kh;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Ii(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))hh(s,e,n,t);return bh(s,e),vh(s,e,o),s}l(Ii,"mimicFunction");var Gn=new WeakMap,Gl=l((s,e={})=>{if(typeof s!="function")throw new TypeError("Expected a function");let t,o=0,n=s.displayName||s.name||"<anonymous>",r=l(function(...i){if(Gn.set(r,++o),o===1)t=s.apply(this,i),s=void 0;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return t},"onetime");return Ii(r,s),Gn.set(r,o),r},"onetime");Gl.callCount=s=>{if(!Gn.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Gn.get(s)};var ql=Gl;var So=[];So.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&So.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&So.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var qn=l(s=>!!s&&typeof s=="object"&&typeof s.removeListener=="function"&&typeof s.emit=="function"&&typeof s.reallyExit=="function"&&typeof s.listeners=="function"&&typeof s.kill=="function"&&typeof s.pid=="number"&&typeof s.on=="function","processOk"),ji=Symbol.for("signal-exit emitter"),Ni=globalThis,Sh=Object.defineProperty.bind(Object),Li=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ni[ji])return Ni[ji];Sh(Ni,ji,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let o=this.listeners[e],n=o.indexOf(t);n!==-1&&(n===0&&o.length===1?o.length=0:o.splice(n,1))}emit(e,t,o){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,o)===!0||n;return e==="exit"&&(n=this.emit("afterExit",t,o)||n),n}},Vn=class{static{l(this,"SignalExitBase")}},xh=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Bi=class extends Vn{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Ui=class extends Vn{static{l(this,"SignalExit")}#i=Wi.platform==="win32"?"SIGINT":"SIGHUP";#o=new Li;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of So)this.#t[t]=()=>{let o=this.#e.listeners(t),{count:n}=this.#o,r=e;if(typeof r.__signal_exit_emitter__=="object"&&typeof r.__signal_exit_emitter__.count=="number"&&(n+=r.__signal_exit_emitter__.count),o.length===n){this.unload();let i=this.#o.emit("exit",null,t),c=t==="SIGHUP"?this.#i:t;i||e.kill(e.pid,c)}};this.#p=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!qn(this.#e))return()=>{};this.#r===!1&&this.load();let o=t?.alwaysLast?"afterExit":"exit";return this.#o.on(o,e),()=>{this.#o.removeListener(o,e),this.#o.listeners.exit.length===0&&this.#o.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#r){this.#r=!0,this.#o.count+=1;for(let e of So)try{let t=this.#t[e];t&&this.#e.on(e,t)}catch{}this.#e.emit=(e,...t)=>this.#m(e,...t),this.#e.reallyExit=e=>this.#s(e)}}unload(){this.#r&&(this.#r=!1,So.forEach(e=>{let t=this.#t[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch{}}),this.#e.emit=this.#n,this.#e.reallyExit=this.#p,this.#o.count-=1)}#s(e){return qn(this.#e)?(this.#e.exitCode=e||0,this.#o.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...t){let o=this.#n;if(e==="exit"&&qn(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);let n=o.call(this.#e,e,...t);return this.#o.emit("exit",this.#e.exitCode,null),n}else return o.call(this.#e,e,...t)}},Wi=globalThis.process,{onExit:Vl,load:ND,unload:LD}=xh(qn(Wi)?new Ui(Wi):new Bi);var zl=js.default.stderr.isTTY?js.default.stderr:js.default.stdout.isTTY?js.default.stdout:void 0,$h=zl?ql(()=>{Vl(()=>{zl.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Jl=$h;var zn=!1,Xo={};Xo.show=(s=Hi.default.stderr)=>{s.isTTY&&(zn=!1,s.write("\x1B[?25h"))};Xo.hide=(s=Hi.default.stderr)=>{s.isTTY&&(Jl(),zn=!0,s.write("\x1B[?25l"))};Xo.toggle=(s,e)=>{s!==void 0&&(zn=s),zn?Xo.show(e):Xo.hide(e)};var Gi=Xo;var Us=b(qi(),1);W();var ze=b(require("node:process"),1);function Vi(){return ze.default.platform!=="win32"?ze.default.env.TERM!=="linux":!!ze.default.env.CI||!!ze.default.env.WT_SESSION||!!ze.default.env.TERMINUS_SUBLIME||ze.default.env.ConEmuTask==="{cmd::Cmder}"||ze.default.env.TERM_PROGRAM==="Terminus-Sublime"||ze.default.env.TERM_PROGRAM==="vscode"||ze.default.env.TERM==="xterm-256color"||ze.default.env.TERM==="alacritty"||ze.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Vi,"isUnicodeSupported");var _h={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},Eh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},Fh=Vi()?_h:Eh,Ns=Fh;function zi({onlyFirst:s=!1}={}){let n="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(n,s?void 0:"g")}l(zi,"ansiRegex");var Th=zi();function Ls(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(Th,"")}l(Ls,"stripAnsi");var Ql=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Zl=12288,eu=65510,tu=[12288,12288,65281,65376,65504,65510];var ou=4352,su=262141,Ji=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Kn=l((s,e)=>{let t=0,o=Math.floor(s.length/2)-1;for(;t<=o;){let n=Math.floor((t+o)/2),r=n*2;if(e<s[r])o=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1},"isInRange");var nu=19968,[Ph,Mh]=Oh(Ji);function Oh(s){let e=s[0],t=s[1];for(let o=0;o<s.length;o+=2){let n=s[o],r=s[o+1];if(nu>=n&&nu<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(Oh,"findWideFastPathRange");var ru=l(s=>s<161||s>1114109?!1:Kn(Ql,s),"isAmbiguous"),iu=l(s=>s<Zl||s>eu?!1:Kn(tu,s),"isFullWidth");var au=l(s=>s>=Ph&&s<=Mh?!0:s<ou||s>su?!1:Kn(Ji,s),"isWide");function Ih(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(Ih,"validate");function cu(s,{ambiguousAsWide:e=!1}={}){return Ih(s),iu(s)||au(s)||e&&ru(s)?2:1}l(cu,"eastAsianWidth");var du=b(uu(),1);var jh=new Intl.Segmenter,Nh=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Ki(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=Ls(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of jh.segment(s)){let c=i.codePointAt(0);if(!(c<=31||c>=127&&c<=159)&&!(c>=8203&&c<=8207||c===65279)&&!(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)&&!(c>=55296&&c<=57343)&&!(c>=65024&&c<=65039)&&!Nh.test(i)){if((0,du.default)().test(i)){n+=2;continue}n+=cu(c,r)}}return n}l(Ki,"stringWidth");function Yi({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(Yi,"isInteractive");var Xi=b(require("node:process"),1);function Qi(){let{env:s}=Xi.default,{TERM:e,TERM_PROGRAM:t}=s;return Xi.default.platform!=="win32"?e!=="linux":!!s.WT_SESSION||!!s.TERMINUS_SUBLIME||s.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||s.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Qi,"isUnicodeSupported");var nt=b(require("node:process"),1);var Lh=3,Zi=class{static{l(this,"StdinDiscarder")}#i=0;start(){this.#i++,this.#i===1&&this.#o()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#o(){nt.default.platform==="win32"||!nt.default.stdin.isTTY||(nt.default.stdin.setRawMode(!0),nt.default.stdin.on("data",this.#n),nt.default.stdin.resume())}#e(){nt.default.stdin.isTTY&&(nt.default.stdin.off("data",this.#n),nt.default.stdin.pause(),nt.default.stdin.setRawMode(!1))}#n(e){e[0]===Lh&&nt.default.emit("SIGINT")}},Bh=new Zi,ea=Bh;var Uh=b(qi(),1);var ta=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#g;#l;#u;#d;#h;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Bs.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Yi({stream:this.#s}),this.#u=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Bs.default.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(t){this.#i=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#n}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#f()}get interval(){return this.#g??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#g=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!Qi())this.#r=Us.default.line;else if(e===void 0)this.#r=Us.default.dots;else if(e!=="default"&&Us.default[e])this.#r=Us.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#h}set text(e=""){this.#h=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#f()}get isSpinning(){return this.#m!==void 0}#y(e=this.#a,t=" "){return typeof e=="string"&&e!==""?e+t:typeof e=="function"?e()+t:""}#b(e=this.#c,t=" "){return typeof e=="string"&&e!==""?t+e:typeof e=="function"?t+e():""}#f(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),o=this.#b(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#h+"--"+o;this.#e=0;for(let r of Ls(n).split(`
|
|
245
|
+
`))this.#e+=Math.max(1,Math.ceil(Ki(r,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#l&&!this.#u}set isEnabled(e){if(typeof e!="boolean")throw new TypeError("The `isEnabled` option must be a boolean");this.#l=e}get isSilent(){return this.#u}set isSilent(e){if(typeof e!="boolean")throw new TypeError("The `isSilent` option must be a boolean");this.#u=e}frame(){let e=Date.now();(this.#n===-1||e-this.#p>=this.interval)&&(this.#n=++this.#n%this.#r.frames.length,this.#p=e);let{frames:t}=this.#r,o=t[this.#n];this.color&&(o=a[this.color](o));let n=typeof this.#a=="string"&&this.#a!==""?this.#a+" ":"",r=typeof this.text=="string"?" "+this.text:"",i=typeof this.#c=="string"&&this.#c!==""?" "+this.#c:"";return n+o+r+i}clear(){if(!this.#l||!this.#s.isTTY)return this;this.#s.cursorTo(0);for(let e=0;e<this.#i;e++)e>0&&this.#s.moveCursor(0,-1),this.#s.clearLine(1);return(this.#d||this.lastIndent!==this.#d)&&this.#s.cursorTo(this.#d),this.lastIndent=this.#d,this.#i=0,this}render(){return this.#u?this:(this.clear(),this.#s.write(this.frame()),this.#i=this.#e,this)}start(e){return e&&(this.text=e),this.#u?this:this.#l?this.isSpinning?this:(this.#t.hideCursor&&Gi.hide(this.#s),this.#t.discardStdin&&Bs.default.stdin.isTTY&&(this.#o=!0,ea.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#s.write(`- ${this.text}
|
|
246
|
+
`),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&Gi.show(this.#s),this.#t.discardStdin&&Bs.default.stdin.isTTY&&this.#o&&(ea.stop(),this.#o=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Ns.success,text:e})}fail(e){return this.stopAndPersist({symbol:Ns.error,text:e})}warn(e){return this.stopAndPersist({symbol:Ns.warning,text:e})}info(e){return this.stopAndPersist({symbol:Ns.info,text:e})}stopAndPersist(e={}){if(this.#u)return this;let t=e.prefixText??this.#a,o=this.#y(t," "),n=e.symbol??" ",r=e.text??this.text,c=typeof r=="string"?(n?" ":"")+r:"",u=e.suffixText??this.#c,d=this.#b(u," "),p=o+n+c+d+`
|
|
247
|
+
`;return this.stop(),this.#s.write(p),this}};function Ws(s){return new ta(s)}l(Ws,"ora");_e();W();_e();W();_e();function pu(s,e,t={}){let o=I(),n=Oe(o),r=H(o),i=t.maxWidth??o.columns,c=t.color??o.ansi,u=e.split(`
|
|
248
|
+
`),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,f=n.horizontal.repeat(Math.max(0,i-fu(p).length-1));d.push(c?a.cyan(p+f+n.topRight):p+f+n.topRight);let m=0,g=0;for(let D of u)if(!(D.startsWith("---")||D.startsWith("+++")||D.startsWith("diff ")||D.startsWith("index "))){if(D.startsWith("@@")){let C=`${n.vertical} ${D}`;d.push(c?a.magenta(C):C);continue}if(D.startsWith("+")){m++;let C=`${n.vertical} + ${D.slice(1)}`,x=oa(C,i);d.push(c?a.green(x):x);continue}if(D.startsWith("-")){g++;let C=`${n.vertical} - ${D.slice(1)}`,x=oa(C,i);d.push(c?a.red(x):x);continue}if(D.startsWith(" ")||D===""){let C=`${n.vertical} ${D}`,x=oa(C,i);d.push(c?a.dim(x):x)}}let h=` +${m} -${g} `,y=`${n.bottomLeft}${n.horizontal}${h}`,S=n.horizontal.repeat(Math.max(0,i-y.length-1));return d.push(c?a.cyan(y+S+n.bottomRight):y+S+n.bottomRight),d.join(`
|
|
249
|
+
`)}l(pu,"renderDiff");function mu(s,e,t){let o=I(),n=H(o),r=o.ansi,i=r?a.green(`+${e}`):`+${e}`,c=r?a.red(`-${t}`):`-${t}`;return` ${n.file} ${s} (${i} ${c})`}l(mu,"renderDiffSummary");function oa(s,e){return fu(s).length<=e?s:s.slice(0,e-3)+"..."}l(oa,"truncateLine");function fu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(fu,"stripAnsi");function na(s,e){let t=I(),o=H(t),n=t.ansi,r=ly(s,o),i=uy(s,e),c=` ${r} ${s}: ${i}`;return n?a.yellow(c):c}l(na,"renderToolStart");function ra(s,e,t={}){switch(e.type){case"file_edit":return ty(e,t);case"file_read":return oy(e);case"terminal":return sy(e,t);case"search":return ny(e,t);case"git":return ry(e);case"browser":return iy(e);case"mcp":return ay(e);case"web_search":return cy(e);case"generic":return gu(s,e);default:return gu(s,{type:"generic",summary:JSON.stringify(e)})}}l(ra,"renderToolResult");function hu(s,e){let t=I(),o=H(t),n=t.ansi,r=` ${o.error} ${s} failed: ${e}`;return n?a.red(r):r}l(hu,"renderToolError");function ty(s,e){return e.verbose&&s.diff?pu(s.filePath,s.diff):mu(s.filePath,s.linesAdded,s.linesRemoved)}l(ty,"renderFileEdit");function oy(s){let e=I();return` ${H(e).file} Read ${sa(s.filePath)} (${s.lineCount} lines)`}l(oy,"renderFileRead");function sy(s,e){let t=I(),o=Oe(t),n=H(t),r=t.ansi,i=e.maxOutputLines??50,c=[],u=s.exitCode===0?r?a.green(n.checkmark):n.checkmark:r?a.red(n.cross):n.cross,d=` ${n.tool} $ ${s.command}`;if(c.push(r?a.bold(d):d),s.stdout){let f=s.stdout.split(`
|
|
241
250
|
`),m=f.slice(0,i);for(let g of m)c.push(r?a.dim(` ${g}`):` ${g}`);if(f.length>i){let g=` [truncated ${f.length-i} lines \u2014 use --verbose for full output]`;c.push(r?a.yellow(g):g)}}if(s.stderr&&s.stderr!==s.stdout){let f=s.stderr.split(`
|
|
242
251
|
`).slice(0,10);for(let m of f)c.push(r?a.red(` ${m}`):` ${m}`)}let p=s.duration?` (${(s.duration/1e3).toFixed(1)}s)`:"";return c.push(` ${u} Exit ${s.exitCode}${p}`),c.join(`
|
|
243
|
-
`)}l(
|
|
244
|
-
`)}l(
|
|
252
|
+
`)}l(sy,"renderTerminal");function ny(s,e){let t=I(),o=H(t),n=t.ansi,r=[];r.push(` ${o.search} Search: "${s.query}" (${s.totalMatches} matches)`);let i=e.verbose?20:8,c=s.matches.slice(0,i);for(let u of c){let d=`${u.file}:${u.line}`,p=u.content.trim().slice(0,80),f=` ${d}: ${p}`;r.push(n?a.dim(f):f)}return s.matches.length>i&&r.push(n?a.yellow(` ... ${s.matches.length-i} more matches`):` ... ${s.matches.length-i} more matches`),r.join(`
|
|
253
|
+
`)}l(ny,"renderSearch");function ry(s){let e=I(),t=H(e),o=e.ansi,n=[];if(n.push(` ${t.git} git ${s.command}`),s.output){let r=s.output.split(`
|
|
245
254
|
`).slice(0,15);for(let i of r)n.push(o?a.dim(` ${i}`):` ${i}`)}return n.join(`
|
|
246
|
-
`)}l(
|
|
247
|
-
`)}l(
|
|
255
|
+
`)}l(ry,"renderGit");function iy(s){let e=I(),t=H(e),o=e.ansi,n=[];if(n.push(` ${t.browser} ${s.title||s.url}`),s.url&&n.push(o?a.dim(` ${s.url}`):` ${s.url}`),s.content){let r=s.content.slice(0,200).replace(/\n/g," ");n.push(o?a.dim(` ${r}...`):` ${r}...`)}return n.join(`
|
|
256
|
+
`)}l(iy,"renderBrowser");function ay(s){let e=I(),t=H(e),o=Oe(e),n=e.ansi,r=e.columns,i=[],c=n?a.cyan(s.server):s.server,u=n?a.bold(s.tool):s.tool,d=`${o.topLeft}${o.horizontal} ${t.mcp} ${s.server}::${s.tool} `,p=o.horizontal.repeat(Math.max(0,r-d.length-3));i.push(n?a.blue(o.topLeft+o.horizontal+" ")+`${t.mcp} ${c}::${u} `+a.blue(p+o.topRight):d+p+o.topRight);let f=typeof s.result=="string"?s.result:JSON.stringify(s.result,null,2),m=f.split(`
|
|
248
257
|
`).slice(0,10);for(let h of m)i.push(`${o.vertical} ${h}`);f.split(`
|
|
249
258
|
`).length>10&&i.push(`${o.vertical} ${n?a.dim(`... ${f.split(`
|
|
250
259
|
`).length-10} more lines`):"..."}`);let g=`${o.bottomLeft}${o.horizontal.repeat(Math.max(0,r-2))}${o.bottomRight}`;return i.push(n?a.blue(g):g),i.join(`
|
|
251
|
-
`)}l(
|
|
252
|
-
`)}l(
|
|
253
|
-
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(
|
|
254
|
-
`)}l(
|
|
255
|
-
`)}l(
|
|
256
|
-
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=O(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,b=t.dirty?a.yellow:a.green,k=t.dirty?" \u25CF":"";o.push(b(` ${h} ${t.branch}${k} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=fy(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,b=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(b(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,b=6,k=Math.round(t.contextPct/100*b),S=b-k,x=h("\u2588".repeat(k))+a.dim("\u2591".repeat(S));r.push(` ${x} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=yu(c).length,p=yu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function fy(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(fy,"formatTokensCompact");function yu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(yu,"stripAnsi");U();var nt={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},gy={width:44,height:19,glyphs:[" \u2584\u2584\u2588 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2588 "," \u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u2588\u2584 ","\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588","\u2588\u2588\u2588 \u2580\u2588\u2580\u2580 \u2584\u2588 \u2588\u2588\u2588 \u2584\u2584 \u2580\u2580\u2588\u2580 \u2588\u2588\u2588","\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2584 \u2584\u2588\u2588\u2588","\u2580\u2588\u2588\u2588\u2588\u2584\u2584 \u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588 \u2584\u2584\u2588\u2588\u2588\u2588\u2580"," \u2580\u2588\u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2588\u2580 \u2584\u2588\u2588\u2588\u2588\u2580 \u2588\u2588\u2588\u2588\u2580 "," \u2580\u2588\u2584 \u2580\u2588\u2588 \u2584\u2588\u2588\u2580 \u2588\u2588\u2580 \u2584\u2588\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2588\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["......................nnn...................","..................nnnnnnnnnn................","..............nnnnnnnnnnnnnnnn..............","...........nnnnnnnnnnnnnnnnnnnnnn...........","........nnnnnnnnnnnnnnnnnnnnnnnnnnnn........","....n...nnnnnnn....nnnnnn....nnnnnnn...n....",".nnnnnnnnnnn....................nnnnnnnnnnn.","nnnnnnnnnnnn....................nnnnnnnnnnnn","nnn....nnnn....ll......lll..ll...nnnn....nnn","nnnn........lllll.....lll...lllll.......nnnn","nnnnnnn....llll......lll.....lllll...nnnnnnn","...nnnnn...llllll...llll....llllll..nnnnn...","......nnn.....lll..llll.....lll....nnn......","........nnnnn......lll.........nnnnn........","........nnnnnnnn............nnnnnnnn........",".........nnnnnnnnn........nnnnnnnnn.........","............nnnnnnn......nnnnnnn............","................nnnnnnnnnnnn................","...................nnnnnn..................."]},hy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},yy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},by={large:gy,medium:hy,mini:yy},bu="\u25C1\u2571\u25B7",wu="</>";function ku(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(ku,"isDarkBackground");function Du(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=by[s],c=o?nt.navyOnDark:nt.navy,u=t?a.hex(c):m=>m,d=t?a.hex(nt.ice):m=>m,p=l((m,g)=>g==="n"?u(m):g==="l"?d(m):m,"paint"),f=" ".repeat(r!==void 0?Math.max(0,Math.floor((r-i.width)/2)):n);return i.glyphs.map((m,g)=>{let h=i.mask[g],b="",k="",S=h[0]??".";for(let x=0;x<m.length;x++){let E=h[x]??".";E!==S&&(b+=p(k,S),k="",S=E),k+=m[x]}return b+=p(k,S),(f+b).replace(/\s+$/,"")})}l(Du,"renderLogo");function vu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(vu,"pickLogoSize");function aa(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(aa,"visibleWidth");var wy={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Co=class{static{l(this,"TuiRenderer")}caps;icons;box;opts;spinner=null;activeToolSpinners=new Map;toolDurations=new Map;toolStartTimes=new Map;tokenBuffer="";lastWasToken=!1;statusBar=null;currentTurn=0;turnTokens=0;constructor(e={}){this.opts={...wy,...e},this.caps=O(),this.icons=W(this.caps),this.box=Me(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:l(t=>this.renderToken(t),"onToken"),onThinking:l(t=>this.renderThinking(t),"onThinking"),onRunStarted:l(t=>this.renderRunStarted(t),"onRunStarted"),onRunComplete:l(t=>this.renderRunComplete(t),"onRunComplete"),onRunError:l(t=>this.renderRunError(t),"onRunError"),onToolStart:l(t=>this.renderToolStart(t),"onToolStart"),onToolProgress:l(t=>this.renderToolProgress(t),"onToolProgress"),onToolResult:l(t=>this.renderToolResult(t),"onToolResult"),onToolError:l(t=>this.renderToolError(t),"onToolError"),onApprovalRequest:l(t=>this.renderApprovalRequest(t),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new Xn(e)),this.statusBar}printTurnBoundary(e,t,o,n){let r=this.caps.ansi,i=Math.min(60,this.caps.columns-4),c=t>=1e3?`${(t/1e3).toFixed(1)}K`:`${t}`,u=o?` ${this.icons.cost} $${o.toFixed(3)}`:"",d=n?` ${a.dim(`total: $${n.toFixed(2)}`)}`:"",p=` Turn ${e} ${a.dim("\xB7")} ${c} tokens${u}${d} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,m=Math.max(0,i-f),g=Math.floor(m/2),h=` ${this.box.horizontal.repeat(g)}${p}${this.box.horizontal.repeat(m-g)}`;console.log(""),console.log(r?a.dim(h):h),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,t={}){let o=this.caps.ansi,n=o?a.hex(nt.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.6";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?vu(this.caps.columns,this.caps.unicode):u;if(d){let f=Du(d,{color:o,dark:ku(),center:Math.min(56,this.caps.columns)});for(let m of f)console.log(m);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,f=52;console.log(n(` ${p.topLeft}${p.horizontal.repeat(f)}${p.topRight}`));let g=`${this.caps.nerdFont?"\uF120":bu} MonkeysCode`,h="CLI Agent",b=Math.max(0,f-aa(g)-h.length-2);console.log(` ${n(p.vertical)} ${i(g)}${" ".repeat(b)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let k=`${c}${e?` \xB7 ${e}`:""}`,S=Math.max(0,f-aa(k)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(S)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${wu} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let t=a.hex(nt.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
257
|
-
`+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(
|
|
258
|
-
`).slice(0,5);for(let c of i)console.log(t?a.dim(` ${c}`):` ${c}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let t=this.caps.ansi;console.log(t?a.dim(` ${e}`):` ${e}`)}printSuccess(e){let t=this.caps.ansi;console.log(t?a.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let t=this.caps.ansi;console.error(t?a.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let t=this.caps.ansi;console.log(t?a.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=
|
|
259
|
-
`).length;if(this.caps.ansi&&
|
|
260
|
+
`)}l(ay,"renderMcp");function cy(s){let e=I(),t=H(e),o=Oe(e),n=e.ansi,r=e.columns,i=[],c=`${o.topLeft}${o.horizontal} ${t.web} web_search `,u=o.horizontal.repeat(Math.max(0,r-c.length-3));i.push(n?a.cyan(c+u+o.topRight):c+u+o.topRight),i.push(`${o.vertical} Query: "${s.query}"`),i.push(`${o.vertical} Results:`);for(let p=0;p<s.results.length&&p<5;p++){let f=s.results[p],m=` ${p+1}. `;i.push(n?`${o.vertical}${m}${a.bold(f.title)} (${a.dim(f.url)})`:`${o.vertical}${m}${f.title} (${f.url})`)}i.push(`${o.vertical} Context injected: ${s.tokensInjected.toLocaleString()} tokens`);let d=`${o.bottomLeft}${o.horizontal.repeat(Math.max(0,r-2))}${o.bottomRight}`;return i.push(n?a.cyan(d):d),i.join(`
|
|
261
|
+
`)}l(cy,"renderWebSearch");function gu(s,e){let t=I();return` ${H(t).tool} ${s}: ${e.summary}`}l(gu,"renderGeneric");function ly(s,e){let t={file_edit:e.edit,edit_file:e.edit,file_read:e.file,read_file:e.file,terminal:e.terminal,bash:e.terminal,run_command:e.terminal,search:e.search,grep:e.search,grep_search:e.search,git:e.git,browser:e.browser,web_search:e.web,delete_file:e.delete,create_file:e.add};return s.includes("::")?e.mcp:t[s]||e.tool}l(ly,"getToolIcon");function uy(s,e){switch(s){case"file_edit":return sa(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return sa(String(e.file||e.filePath||e.path||"unknown file"));case"terminal":case"bash":return String(e.command||e.cmd||"");case"search":case"grep":return`"${e.query||e.pattern||""}"`;case"git":return String(e.command||e.args||"");case"browser":return String(e.url||"");case"web_search":return`"${e.query||""}"`;default:return s.includes("::")?Object.keys(e).slice(0,3).map(o=>`${o}=${JSON.stringify(e[o])}`).join(", "):JSON.stringify(e).slice(0,80)}}l(uy,"getToolArgsSummary");function sa(s){return process.platform==="win32"?s.replace(/\//g,"\\"):s}l(sa,"displayPath");W();function Qn(s,e={}){let t=e.width||process.stdout.columns||80,o=s.split(`
|
|
262
|
+
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(yu(c,i)),r=!1,c=[],i=""):(r=!0,i=d[1]||"");continue}if(r){c.push(u);continue}let p=u.match(/^# (.+)/);if(p){n.push(""),n.push(a.bold.hex("#a3cad3")(p[1])),n.push(a.dim("\u2500".repeat(Math.min(p[1].length+2,t-4))));continue}let f=u.match(/^## (.+)/);if(f){n.push(""),n.push(a.bold.hex("#6B8DD6")(f[1]));continue}let m=u.match(/^### (.+)/);if(m){n.push(a.bold(m[1]));continue}let g=u.match(/^####+ (.+)/);if(g){n.push(a.bold.dim(g[1]));continue}if(/^---+$/.test(u.trim())||/^\*\*\*+$/.test(u.trim())){n.push(a.dim("\u2500".repeat(Math.min(40,t-4))));continue}let h=u.match(/^(\s*)([-*+])\s(.+)/);if(h){let D=h[1],C=Xn(h[3]);n.push(`${D} \u2022 ${C}`);continue}let y=u.match(/^(\s*)(\d+)\.\s(.+)/);if(y){let D=y[1],C=y[2],x=Xn(y[3]);n.push(`${D} ${a.dim(C+".")} ${x}`);continue}let S=u.match(/^>\s?(.*)/);if(S){n.push(a.dim(" \u2502 ")+a.italic(Xn(S[1])));continue}if(u.trim()===""){n.push("");continue}n.push(Xn(u))}return r&&c.length>0&&n.push(yu(c,i)),n.join(`
|
|
263
|
+
`)}l(Qn,"renderMarkdown");function Xn(s){let e=s;return e=e.replace(/`([^`]+)`/g,(t,o)=>a.bgHex("#1e1e2e").hex("#f0c674")(` ${o} `)),e=e.replace(/\*\*\*(.+?)\*\*\*/g,(t,o)=>a.bold.italic(o)),e=e.replace(/\*\*(.+?)\*\*/g,(t,o)=>a.bold(o)),e=e.replace(/__(.+?)__/g,(t,o)=>a.bold(o)),e=e.replace(/\*(.+?)\*/g,(t,o)=>a.italic(o)),e=e.replace(/_(.+?)_/g,(t,o)=>a.italic(o)),e=e.replace(/~~(.+?)~~/g,(t,o)=>a.strikethrough(o)),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,o,n)=>`${a.hex("#6B8DD6")(o)} ${a.dim(`(${n})`)}`),e}l(Xn,"renderInline");function yu(s,e){let t=e?a.dim.italic(` ${e}`):"",o=a.dim(" \u2503 "),n=a.dim(` \u250F\u2501${t}${"\u2501".repeat(Math.max(0,40-e.length))}`),r=a.dim(` \u2517${"\u2501".repeat(42)}`),i=s.map(c=>`${o}${dy(c,e)}`);return[n,...i,r].join(`
|
|
264
|
+
`)}l(yu,"renderCodeBlock");function dy(s,e){if(!e)return a.hex("#c0c0c0")(s);let t=s,o=["//.*$","#.*$","--.*$"];for(let r of o)t=t.replace(new RegExp(`(${r})`),i=>a.dim.italic(i));t=t.replace(/(["'])(?:(?!\1|\\).|\\.)*\1/g,r=>a.hex("#98c379")(r)),t=t.replace(/\b(\d+\.?\d*)\b/g,r=>a.hex("#d19a66")(r));let n=py(e);if(n.length>0){let r=new RegExp(`\\b(${n.join("|")})\\b`,"g");t=t.replace(r,i=>a.hex("#c678dd")(i))}return t=t.replace(/\b([A-Z][a-zA-Z0-9]+)\b/g,r=>a.hex("#e5c07b")(r)),t}l(dy,"highlightSyntax");function py(s){let e=s.toLowerCase(),t=["const","let","var","function","return","if","else","for","while","class","extends","import","export","from","async","await","new","this","super","try","catch","throw","switch","case","break","default","interface","type","enum","typeof","instanceof","true","false","null","undefined","void","readonly"],o=["def","class","return","if","elif","else","for","while","in","import","from","as","try","except","finally","raise","with","yield","async","await","pass","break","continue","lambda","True","False","None","and","or","not","is","self"],n=["fn","let","mut","const","struct","enum","impl","trait","pub","use","mod","crate","self","super","if","else","for","while","loop","match","return","async","await","move","unsafe","where","true","false","Some","None","Ok","Err","Self"],r=["func","var","const","type","struct","interface","if","else","for","range","return","switch","case","default","break","continue","go","defer","select","chan","map","package","import","true","false","nil","error"];switch(e){case"ts":case"tsx":case"typescript":return t;case"js":case"jsx":case"javascript":return t;case"py":case"python":return o;case"rs":case"rust":return n;case"go":case"golang":return r;case"html":return["html","head","body","div","span","p","a","img","script","style","link"];case"css":return["color","background","display","flex","grid","margin","padding","border","font","width","height"];case"sql":return["SELECT","FROM","WHERE","INSERT","UPDATE","DELETE","CREATE","DROP","ALTER","JOIN","ON","AND","OR","NOT","NULL","INTO","VALUES","SET","ORDER","BY","GROUP","HAVING","LIMIT"];case"sh":case"bash":case"zsh":return["if","then","else","fi","for","do","done","while","case","esac","function","return","echo","exit","export","source","local"];default:return[]}}l(py,"getLanguageKeywords");function bu(s){return!!(/^#{1,6}\s/m.test(s)||/```/m.test(s)||/\*\*.+\*\*/m.test(s)||/^\s*[-*+]\s/m.test(s)||/^\s*\d+\.\s/m.test(s)||/^>/m.test(s)||/\[.+\]\(.+\)/m.test(s))}l(bu,"containsMarkdown");W();_e();var Zn=class{static{l(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=I(),this.icons=H(this.caps),this.data={model:"",mode:"code",branch:"",dirty:!1,sandbox:!1,tokensIn:0,tokensOut:0,cost:0,turn:0,contextPct:0,activity:"",busy:!1,budgetUsd:0,...e}}start(){!this.caps.stdoutTTY||!this.caps.ansi||(this.enabled=!0,process.stdout.write(`
|
|
265
|
+
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=I(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,y=t.dirty?a.yellow:a.green,S=t.dirty?" \u25CF":"";o.push(y(` ${h} ${t.branch}${S} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=my(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,y=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(y(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,y=6,S=Math.round(t.contextPct/100*y),D=y-S,C=h("\u2588".repeat(S))+a.dim("\u2591".repeat(D));r.push(` ${C} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=wu(c).length,p=wu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function my(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(my,"formatTokensCompact");function wu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(wu,"stripAnsi");W();var Je={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},fy={width:44,height:19,glyphs:[" \u2584\u2584\u2588 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2588 "," \u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u2588\u2584 ","\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588","\u2588\u2588\u2588 \u2580\u2588\u2580\u2580 \u2584\u2588 \u2588\u2588\u2588 \u2584\u2584 \u2580\u2580\u2588\u2580 \u2588\u2588\u2588","\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2584 \u2584\u2588\u2588\u2588","\u2580\u2588\u2588\u2588\u2588\u2584\u2584 \u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588 \u2584\u2584\u2588\u2588\u2588\u2588\u2580"," \u2580\u2588\u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2588\u2580 \u2584\u2588\u2588\u2588\u2588\u2580 \u2588\u2588\u2588\u2588\u2580 "," \u2580\u2588\u2584 \u2580\u2588\u2588 \u2584\u2588\u2588\u2580 \u2588\u2588\u2580 \u2584\u2588\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2588\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["......................nnn...................","..................nnnnnnnnnn................","..............nnnnnnnnnnnnnnnn..............","...........nnnnnnnnnnnnnnnnnnnnnn...........","........nnnnnnnnnnnnnnnnnnnnnnnnnnnn........","....n...nnnnnnn....nnnnnn....nnnnnnn...n....",".nnnnnnnnnnn....................nnnnnnnnnnn.","nnnnnnnnnnnn....................nnnnnnnnnnnn","nnn....nnnn....ll......lll..ll...nnnn....nnn","nnnn........lllll.....lll...lllll.......nnnn","nnnnnnn....llll......lll.....lllll...nnnnnnn","...nnnnn...llllll...llll....llllll..nnnnn...","......nnn.....lll..llll.....lll....nnn......","........nnnnn......lll.........nnnnn........","........nnnnnnnn............nnnnnnnn........",".........nnnnnnnnn........nnnnnnnnn.........","............nnnnnnn......nnnnnnn............","................nnnnnnnnnnnn................","...................nnnnnn..................."]},gy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},hy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},yy={large:fy,medium:gy,mini:hy},ku="\u25C1\u2571\u25B7",Du="</>";function vu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(vu,"isDarkBackground");function Su(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=yy[s],c=o?Je.navyOnDark:Je.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Je.ice):m=>m,p=l((m,g)=>g==="n"?u(m):g==="l"?d(m):m,"paint"),f=" ".repeat(r!==void 0?Math.max(0,Math.floor((r-i.width)/2)):n);return i.glyphs.map((m,g)=>{let h=i.mask[g],y="",S="",D=h[0]??".";for(let C=0;C<m.length;C++){let x=h[C]??".";x!==D&&(y+=p(S,D),S="",D=x),S+=m[C]}return y+=p(S,D),(f+y).replace(/\s+$/,"")})}l(Su,"renderLogo");function xu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(xu,"pickLogoSize");function ia(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(ia,"visibleWidth");var by={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Co=class{static{l(this,"TuiRenderer")}caps;icons;box;opts;spinner=null;activeToolSpinners=new Map;toolDurations=new Map;toolStartTimes=new Map;tokenBuffer="";lastWasToken=!1;statusBar=null;currentTurn=0;turnTokens=0;constructor(e={}){this.opts={...by,...e},this.caps=I(),this.icons=H(this.caps),this.box=Oe(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:l(t=>this.renderToken(t),"onToken"),onThinking:l(t=>this.renderThinking(t),"onThinking"),onRunStarted:l(t=>this.renderRunStarted(t),"onRunStarted"),onRunComplete:l(t=>this.renderRunComplete(t),"onRunComplete"),onRunError:l(t=>this.renderRunError(t),"onRunError"),onToolStart:l(t=>this.renderToolStart(t),"onToolStart"),onToolProgress:l(t=>this.renderToolProgress(t),"onToolProgress"),onToolResult:l(t=>this.renderToolResult(t),"onToolResult"),onToolError:l(t=>this.renderToolError(t),"onToolError"),onApprovalRequest:l(t=>this.renderApprovalRequest(t),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new Zn(e)),this.statusBar}printTurnBoundary(e,t,o,n){let r=this.caps.ansi,i=Math.min(60,this.caps.columns-4),c=t>=1e3?`${(t/1e3).toFixed(1)}K`:`${t}`,u=o?` ${this.icons.cost} $${o.toFixed(3)}`:"",d=n?` ${a.dim(`total: $${n.toFixed(2)}`)}`:"",p=` Turn ${e} ${a.dim("\xB7")} ${c} tokens${u}${d} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,m=Math.max(0,i-f),g=Math.floor(m/2),h=` ${this.box.horizontal.repeat(g)}${p}${this.box.horizontal.repeat(m-g)}`;console.log(""),console.log(r?a.dim(h):h),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,t={}){let o=this.caps.ansi,n=o?a.hex(Je.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.8";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?xu(this.caps.columns,this.caps.unicode):u;if(d){let f=Su(d,{color:o,dark:vu(),center:Math.min(56,this.caps.columns)});for(let m of f)console.log(m);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,f=52;console.log(n(` ${p.topLeft}${p.horizontal.repeat(f)}${p.topRight}`));let g=`${this.caps.nerdFont?"\uF120":ku} MonkeysCode`,h="CLI Agent",y=Math.max(0,f-ia(g)-h.length-2);console.log(` ${n(p.vertical)} ${i(g)}${" ".repeat(y)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let S=`${c}${e?` \xB7 ${e}`:""}`,D=Math.max(0,f-ia(S)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(D)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${Du} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let t=a.hex(Je.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
266
|
+
`+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(Je.accent),c=a.green,u=a.dim,d=l((p,f)=>{let m=(p+f).replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(0,r-m.length-4);return` ${i(n.vertical)} ${p}${" ".repeat(g)}${f} ${i(n.vertical)}`},"pad");if(console.log(""),console.log(i(` ${n.topLeft}${n.horizontal} ${c(`${this.icons.success} Run Complete`)} ${n.horizontal.repeat(Math.max(0,r-17))}${n.topRight}`)),console.log(d(" Duration:",`${o}s`)),console.log(d(" Tokens:",`${e.tokensUsed.toLocaleString()}`)),console.log(d(" Tools:",`${e.toolCalls} calls`)),e.filesChanged.length>0){console.log(i(` ${n.teeRight}${n.horizontal.repeat(r)}${n.teeLeft}`)),console.log(d(" Files Changed:",`${e.filesChanged.length}`));for(let p of e.filesChanged){let f=p.split("/").slice(-2).join("/");console.log(d(` ${this.icons.edit} ${f}`,""))}}console.log(i(` ${n.bottomLeft}${n.horizontal.repeat(r)}${n.bottomRight}`)),console.log("")}else{let r=this.box.separator.repeat(Math.min(60,this.caps.columns-2)),i=[`${this.icons.success} Done`,`${e.tokensUsed.toLocaleString()} tokens`,`${e.toolCalls} tool calls`,`${e.filesChanged.length} files changed`,`${o}s`].join(" \xB7 ");if(console.log(""),console.log(r),console.log(` ${i}`),e.filesChanged.length>0){console.log(""),console.log(" Files changed:");for(let c of e.filesChanged)console.log(` ${c}`)}console.log(r),console.log("")}this.statusBar&&this.statusBar.update({busy:!1,activity:""})}renderRunError(e){this.lastWasToken&&(console.log(""),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=` ${this.icons.error} Agent error: ${e.message}`;console.log(t?a.red(o):o),e.code&&console.log(t?a.dim(` Code: ${e.code}`):` Code: ${e.code}`)}renderToolStart(e){if(this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),console.log(""),console.log(na(e.toolName,e.args)),this.toolStartTimes.set(e.toolId,Date.now()),!this.opts.accessible&&this.caps.ansi){let t=this.getToolAvgDuration(e.toolName),o=t?` (~${(t/1e3).toFixed(1)}s)`:"",n=Ws({text:`${e.toolName} executing...${o}`,indent:4,spinner:"dots"}).start();this.activeToolSpinners.set(e.toolId,n)}}renderToolProgress(e){let t=this.activeToolSpinners.get(e.toolId);if(t&&(e.progress!==void 0&&(t.text=`${e.toolName} (${e.progress}%)`),e.output)){t.stop();let o=this.caps.ansi,n=` ${e.output}`;console.log(o?a.dim(n):n),t.start()}}renderToolResult(e){let t=this.activeToolSpinners.get(e.toolId);t&&(t.stop(),this.activeToolSpinners.delete(e.toolId));let o=this.toolStartTimes.get(e.toolId);if(o){let r=Date.now()-o;this.recordToolDuration(e.toolName,r),this.toolStartTimes.delete(e.toolId)}let n={maxOutputLines:this.opts.maxToolOutputLines,verbose:this.opts.verbose};console.log(ra(e.toolName,e.result,n))}renderToolError(e){let t=this.activeToolSpinners.get(e.toolId);t?(t.fail(e.message),this.activeToolSpinners.delete(e.toolId)):console.log(hu(e.toolName,e.message))}renderApprovalRequest(e){this.lastWasToken&&(console.log(""),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=this.box,n={safe:{color:t?a.green:i=>i,icon:this.icons.success,label:"Safe"},moderate:{color:t?a.yellow:i=>i,icon:this.icons.warning,label:"Moderate"},dangerous:{color:t?a.red:i=>i,icon:this.icons.error,label:"Destructive"}},r=n[e.riskLevel]||n.moderate;if(this.caps.unicode){let i=Math.min(54,this.caps.columns-6);console.log(""),console.log(r.color(` ${o.topLeft}${o.horizontal} ${r.icon} Approval Required ${o.horizontal.repeat(Math.max(0,i-23))}${o.topRight}`)),console.log(r.color(` ${o.vertical}${" ".repeat(i)}${o.vertical}`));let c=` Tool: ${e.toolName}`,u=Math.max(0,i-c.length);console.log(r.color(` ${o.vertical}`)+` ${c}${" ".repeat(u)}`+r.color(o.vertical));let d=` ${e.description}`.slice(0,i-2),p=Math.max(0,i-d.length);console.log(r.color(` ${o.vertical}`)+` ${d}${" ".repeat(p)}`+r.color(o.vertical));let f=` Risk: ${r.icon} ${r.label}`,m=f.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(0,i-m.length);console.log(r.color(` ${o.vertical}`)+` ${f}${" ".repeat(g)}`+r.color(o.vertical)),console.log(r.color(` ${o.vertical}${" ".repeat(i)}${o.vertical}`));let y=e.riskLevel==="dangerous"?" [y] Allow once [n] Deny":" [y] Allow [n] Deny [a] Always [!] YOLO",S=Math.max(0,i-y.length);console.log(r.color(` ${o.vertical}`)+a.dim(` ${y}${" ".repeat(S)}`)+r.color(o.vertical)),console.log(r.color(` ${o.bottomLeft}${o.horizontal.repeat(i)}${o.bottomRight}`))}else{console.log(""),console.log(r.color(` ${r.icon} Permission required: ${e.toolName}`)),console.log(r.color(` ${e.description}`)),console.log(r.color(` Risk: ${r.label}`));let i=JSON.stringify(e.args,null,2).split(`
|
|
267
|
+
`).slice(0,5);for(let c of i)console.log(t?a.dim(` ${c}`):` ${c}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let t=this.caps.ansi;console.log(t?a.dim(` ${e}`):` ${e}`)}printSuccess(e){let t=this.caps.ansi;console.log(t?a.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let t=this.caps.ansi;console.error(t?a.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let t=this.caps.ansi;console.log(t?a.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=Ws({text:e,indent:2,spinner:"dots"}).start()}succeedSpinner(e){this.spinner&&(this.spinner.succeed(e),this.spinner=null)}failSpinner(e){this.spinner&&(this.spinner.fail(e),this.spinner=null)}clearSpinners(){this.spinner&&(this.spinner.stop(),this.spinner=null);for(let[e,t]of this.activeToolSpinners)t.stop();this.activeToolSpinners.clear()}getToolAvgDuration(e){let t=this.toolDurations.get(e);if(!t||t.length===0)return 0;let o=t.reduce((n,r)=>n+r,0);return Math.round(o/t.length)}recordToolDuration(e,t){let o=this.toolDurations.get(e)??[];o.push(t),o.length>10&&o.shift(),this.toolDurations.set(e,o)}printSessionSummary(e){let t=this.caps.ansi,o=e.endTime?((e.endTime-e.startTime)/1e3).toFixed(1):"?";if(this.caps.unicode){let n=this.box,r=Math.min(48,this.caps.columns-6),i=a.hex(Je.accent),c=a.dim,u=[["Duration",`${o}s`],["Tokens",e.tokensUsed.toLocaleString()],["Tools",`${e.toolCalls} calls`],["Files",`${e.filesChanged.length} changed`]];console.log(""),console.log(i(` ${n.topLeft}${n.horizontal} \u{1F4CB} Session Summary ${n.horizontal.repeat(Math.max(0,r-22))}${n.topRight}`));for(let[d,p]of u){let f=d.padEnd(12),m=`${f}${p}`,g=Math.max(0,r-m.length-4);console.log(i(` ${n.vertical}`)+` ${c(f)}${p}${" ".repeat(g)}`+i(n.vertical))}if(e.filesChanged.length>0){console.log(i(` ${n.teeRight}${n.horizontal.repeat(r)}${n.teeLeft}`));for(let d of e.filesChanged){let p=d.split("/").slice(-2).join("/"),f=` ${this.icons.edit} ${p}`,m=Math.max(0,r-f.length);console.log(i(` ${n.vertical}`)+`${f}${" ".repeat(m)}`+i(n.vertical))}}console.log(i(` ${n.bottomLeft}${n.horizontal.repeat(r)}${n.bottomRight}`)),console.log("")}else{let n=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(""),console.log(t?a.dim(n):n),console.log(" Session Summary"),console.log(` Tokens: ${e.tokensUsed.toLocaleString()}`),console.log(` Tool calls: ${e.toolCalls}`),console.log(` Files changed: ${e.filesChanged.length}`),console.log(` Duration: ${o}s`),console.log(t?a.dim(n):n),console.log("")}}printToolCallStart(e,t){if(this.lastWasToken&&(console.log(""),this.lastWasToken=!1),console.log(""),console.log(na(e,t)),!this.opts.accessible&&this.caps.ansi){let o=Ws({text:`${e} executing...`,indent:4,spinner:"dots"}).start();this.activeToolSpinners.set(e,o)}}printToolCallResult(e,t){let o=this.activeToolSpinners.get(e);o&&(o.stop(),this.activeToolSpinners.delete(e));let n={maxOutputLines:this.opts.maxToolOutputLines,verbose:this.opts.verbose},r={type:"generic",summary:t.slice(0,200),data:t};console.log(ra(e,r,n))}printTodoList(e){let t=this.caps.ansi,o=t?a.dim:r=>r,n=t?a.bold:r=>r;console.log(""),console.log(n(" \u{1F4CB} Task Plan:"));for(let r of e){let i=r.status==="done"?"\u2705":r.status==="in_progress"?"\u{1F504}":"\u2B1C",c=r.status==="done"?t?a.green:u=>u:r.status==="in_progress"?t?a.yellow:u=>u:o;console.log(c(` ${i} ${r.content}`))}console.log("")}flushTokenBuffer(){if(!this.tokenBuffer)return;let e=this.tokenBuffer.replace(/<think>[\s\S]*?<\/think>/g,"").trim();this.tokenBuffer="";let t=e.split(`
|
|
268
|
+
`).length;if(this.caps.ansi&&bu(e)){for(let n=0;n<t;n++)process.stdout.write("\x1B[2K"),n<t-1&&process.stdout.write("\x1B[1A");process.stdout.write("\r");let o=Qn(e,{caps:this.caps});if(this.caps.unicode){let n=a.dim(` ${this.box.vertical} `),r=o.split(`
|
|
260
269
|
`).map(i=>n+i).join(`
|
|
261
|
-
`);process.stdout.write(r)}else process.stdout.write(o)}else console.log("");if(this.caps.unicode){let o=a.hex(
|
|
262
|
-
`).filter(t=>t.trim().length>0).slice(-Na):[]}catch{return[]}}append(e){let t=e.trim();if(t&&!t.startsWith("/"))try{let o=
|
|
270
|
+
`);process.stdout.write(r)}else process.stdout.write(o)}else console.log("");if(this.caps.unicode){let o=a.hex(Je.accent),n=Math.min(56,this.caps.columns-6);console.log(""),console.log(o(` ${this.box.bottomLeft}${this.box.horizontal.repeat(n)}${this.box.bottomRight}`))}}renderMessageCard(e){let t=this.box,o=this.caps.emoji?"\u{1F4E8}":">>",n=Math.min(60,Math.max(40,e.content.length+6)),r=` ${o} Message from ${e.from} `,i=e.timestamp.toLocaleTimeString(),c=Math.max(0,n-r.length-2),u=` ${t.topLeft}${t.horizontal}${r}${t.horizontal.repeat(c)}${t.topRight}`,d=n-4,p=wy(e.content,d),f=` ${t.bottomLeft}${t.horizontal.repeat(n)}${t.bottomRight}`;console.log(""),console.log(this.caps.ansi?a.cyan(u):u);for(let y of p){let S=y.padEnd(d);console.log(this.caps.ansi?` ${a.cyan(t.vertical)} ${S} ${a.cyan(t.vertical)}`:` ${t.vertical} ${S} ${t.vertical}`)}let m=`${i} `,g=Math.max(0,n-m.length),h=` ${t.bottomLeft}${t.horizontal.repeat(g)}${m}${t.bottomRight}`;console.log(this.caps.ansi?a.cyan(h):h),console.log("")}};function wy(s,e){if(s.length<=e)return[s];let t=[],o=s;for(;o.length>0;){if(o.length<=e){t.push(o);break}let n=o.lastIndexOf(" ",e);n<=0&&(n=e),t.push(o.substring(0,n)),o=o.substring(n).trimStart()}return t}l(wy,"wrapText");_e();ee();Ke();Q();var ue=b(require("node:fs"),1),je=b(require("node:path"),1);X();var Uy=20;function pd(s,e,t,o){if(o.size===0)return;let n=A(),r=je.join(n.data,"checkpoints");ue.mkdirSync(r,{recursive:!0});let i={runId:s,prompt:e,workspace:t,timestamp:Date.now(),snapshots:Object.fromEntries(o)},c=je.join(r,`${s}.json`);ue.writeFileSync(c,JSON.stringify(i,null,2)),Wy(r)}l(pd,"saveCheckpoint");function md(){let s=A(),e=je.join(s.data,"checkpoints");return ue.existsSync(e)?ue.readdirSync(e).filter(o=>o.endsWith(".json")).sort().reverse().map(o=>{try{return JSON.parse(ue.readFileSync(je.join(e,o),"utf8"))}catch{return null}}).filter(Boolean):[]}l(md,"listCheckpoints");function fd(s){let e=A(),t=je.join(e.data,"checkpoints",`${s}.json`);if(!ue.existsSync(t))throw new Error(`Checkpoint not found: ${s}`);let o=JSON.parse(ue.readFileSync(t,"utf8")),n=[];for(let[r,i]of Object.entries(o.snapshots))try{i===null?ue.existsSync(r)&&(ue.unlinkSync(r),n.push(`deleted ${je.relative(o.workspace,r)}`)):(ue.mkdirSync(je.dirname(r),{recursive:!0}),ue.writeFileSync(r,i),n.push(`restored ${je.relative(o.workspace,r)}`))}catch(c){n.push(`FAILED ${je.relative(o.workspace,r)}: ${c instanceof Error?c.message:c}`)}return ue.unlinkSync(t),n}l(fd,"revertCheckpoint");function Wy(s){let e=ue.readdirSync(s).filter(t=>t.endsWith(".json")).map(t=>({name:t,mtime:ue.statSync(je.join(s,t)).mtime.getTime()})).sort((t,o)=>o.mtime-t.mtime);for(let t of e.slice(Uy))try{ue.unlinkSync(je.join(s,t.name))}catch{}}l(Wy,"pruneCheckpoints");var he=b(require("node:fs"),1),co=b(require("node:path"),1),gd=b(require("node:crypto"),1);X();var Hy="sessions",Gy=20,qy=30*24*60*60*1e3,Lt=class{static{l(this,"SessionStore")}sessionsDir;constructor(){let e=A();this.sessionsDir=co.join(e.data,Hy),this.ensureDir()}save(e){this.ensureDir();let t=this.sessionPath(e.id),o=JSON.stringify(e,null,2);he.writeFileSync(t,o,"utf-8")}create(e,t,o){let n={id:gd.randomUUID(),workspace:co.resolve(e),startTime:Date.now(),lastActive:Date.now(),turnCount:0,model:t,mode:o,messages:[],stats:{tokensUsed:0,toolCalls:0,filesChanged:[]}};return this.save(n),n}addMessage(e,t,o){e.messages.push({role:t,content:o,timestamp:Date.now()}),e.lastActive=Date.now(),t==="user"&&e.turnCount++,this.save(e)}updateStats(e,t,o,n){e.stats.tokensUsed+=t,e.stats.toolCalls+=o;for(let r of n)e.stats.filesChanged.includes(r)||e.stats.filesChanged.push(r);e.lastActive=Date.now(),this.save(e)}load(e){let t=this.sessionPath(e);if(!he.existsSync(t))return null;try{let o=he.readFileSync(t,"utf-8");return JSON.parse(o)}catch{return null}}loadLatest(e){let t=this.list(),o=e?t.filter(n=>n.workspace===co.resolve(e)):t;return o.length===0?null:this.load(o[0].id)}list(){this.ensureDir();let e=he.readdirSync(this.sessionsDir).filter(o=>o.endsWith(".json")).map(o=>co.join(this.sessionsDir,o)),t=[];for(let o of e)try{let n=he.readFileSync(o,"utf-8"),r=JSON.parse(n),i=r.messages.find(c=>c.role==="user");t.push({id:r.id,workspace:r.workspace,startTime:r.startTime,lastActive:r.lastActive,turnCount:r.turnCount,model:r.model,preview:i?i.content.substring(0,80).replace(/\n/g," "):"(empty)"})}catch{}return t.sort((o,n)=>n.lastActive-o.lastActive),t.slice(0,Gy)}delete(e){let t=this.sessionPath(e);return he.existsSync(t)?(he.unlinkSync(t),!0):!1}prune(e=qy){this.ensureDir();let t=Date.now(),o=0,n=he.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).map(i=>co.join(this.sessionsDir,i));for(let i of n)try{let c=he.readFileSync(i,"utf-8"),u=JSON.parse(c);t-u.lastActive>e&&(he.unlinkSync(i),o++)}catch{}let r=he.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).length;return{deleted:o,remaining:r}}sessionPath(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"");return co.join(this.sessionsDir,`${t}.json`)}ensureDir(){he.existsSync(this.sessionsDir)||he.mkdirSync(this.sessionsDir,{recursive:!0})}};Ca();var at=b(require("node:fs"),1),yr=b(require("node:path"),1);X();var Na=1e3,Vy="history",hr=class{static{l(this,"HistoryManager")}historyFile;constructor(){let e=A();this.historyFile=yr.join(e.data,Vy)}load(){try{return at.existsSync(this.historyFile)?at.readFileSync(this.historyFile,"utf-8").split(`
|
|
271
|
+
`).filter(t=>t.trim().length>0).slice(-Na):[]}catch{return[]}}append(e){let t=e.trim();if(t&&!t.startsWith("/"))try{let o=yr.dirname(this.historyFile);at.existsSync(o)||at.mkdirSync(o,{recursive:!0});let n=[];if(at.existsSync(this.historyFile)&&(n=at.readFileSync(this.historyFile,"utf-8").split(`
|
|
263
272
|
`).filter(r=>r.trim().length>0)),n.length>0&&n[n.length-1]===t)return;n.push(t),n.length>Na&&(n=n.slice(-Na)),at.writeFileSync(this.historyFile,n.join(`
|
|
264
273
|
`)+`
|
|
265
|
-
`,"utf-8")}catch{}}wire(e){let t=this.load(),o=e;o.history&&Array.isArray(o.history)&&(o.history=[...t.reverse(),...o.history],o.history.length>e.historySize&&(o.history=o.history.slice(0,e.historySize))),e.on("line",n=>{this.append(n)})}getPath(){return this.historyFile}};
|
|
266
|
-
`)[0],h=e.find(
|
|
267
|
-
`)[0])}return
|
|
268
|
-
`);for(let o of t)/\bFAIL\b|✕|✗|ERROR|BROKEN/.test(o)&&e.push({suite:"unknown",name:o.trim().substring(0,100),status:"fail"});return
|
|
274
|
+
`,"utf-8")}catch{}}wire(e){let t=this.load(),o=e;o.history&&Array.isArray(o.history)&&(o.history=[...t.reverse(),...o.history],o.history.length>e.historySize&&(o.history=o.history.slice(0,e.historySize))),e.on("line",n=>{this.append(n)})}getPath(){return this.historyFile}};W();var br=require("node:child_process");Ke();Q();function La(s){return zy(s)?Qy(s):Jy(s)?Zy(s):Ky(s)?e0(s):Yy(s)?t0(s):Xy(s)?o0(s):s0(s)}l(La,"parseTestOutput");function hd(s){let e=require("node:fs"),t=require("node:path"),o=[{file:"package.json",command:"npm test"},{file:"Cargo.toml",command:"cargo test"},{file:"pyproject.toml",command:"pytest"},{file:"go.mod",command:"go test ./..."},{file:"Makefile",command:"make test"},{file:"CMakeLists.txt",command:"ctest"},{file:"build.gradle",command:"./gradlew test"},{file:"pom.xml",command:"mvn test"}];for(let n of o)if(e.existsSync(t.join(s,n.file)))if(n.file==="package.json")try{let r=JSON.parse(e.readFileSync(t.join(s,n.file),"utf8"));if(r.scripts?.test&&r.scripts.test!=='echo "Error: no test specified" && exit 1')return n.command}catch{continue}else return n.command;return null}l(hd,"detectVerifyCommand");function zy(s){return/Tests?:\s+\d+ (?:passed|failed)/.test(s)||/PASS|FAIL/.test(s)&&/Test Suites:/.test(s)}l(zy,"isJest");function Jy(s){return s.includes("vitest")||/✓|×/.test(s)&&/Tests\s+\d+/.test(s)}l(Jy,"isVitest");function Ky(s){return/={3,}\s*(?:FAILURES|ERRORS|short test summary)/.test(s)||/\d+ passed/.test(s)&&/pytest/.test(s)}l(Ky,"isPytest");function Yy(s){return/test result:/.test(s)&&/ok|FAILED/.test(s)}l(Yy,"isCargoTest");function Xy(s){return/^(?:ok|FAIL)\s+\S+/.test(s)||/--- FAIL:/.test(s)}l(Xy,"isGoTest");function Qy(s){let e=[],t=/✓|✔|√|PASS/,o=/✕|✖|×|✗|FAIL/,n=/FAIL\s+(\S+)\n([\s\S]*?)(?=\n(?:PASS|FAIL|Test Suites:)|\z)/g,r;for(;(r=n.exec(s))!==null;){let m=r[1],g=r[2],h=/(?:✕|✖|×|✗)\s+(.+?)(?:\s+\((\d+)\s*ms\))?$/gm,y;for(;(y=h.exec(g))!==null;)e.push({suite:m,name:y[1].trim(),status:"fail",file:m,durationMs:y[2]?parseInt(y[2],10):void 0})}let i=/●\s+(.+?)\s*\n\s*\n\s*([\s\S]*?)(?=\n\s*●|\n\s*Test Suites:)/g;for(;(r=i.exec(s))!==null;){let m=r[1].trim(),g=r[2].trim().split(`
|
|
275
|
+
`)[0],h=e.find(y=>m.includes(y.name));h&&(h.error=g)}let c=s.match(/Tests:\s+(?:(\d+) failed,?\s*)?(?:(\d+) skipped,?\s*)?(?:(\d+) passed,?\s*)?(\d+) total/),u=c?parseInt(c[1]||"0",10):e.filter(m=>m.status==="fail").length,d=c?parseInt(c[2]||"0",10):0,p=c?parseInt(c[3]||"0",10):0,f=c?parseInt(c[4]||"0",10):e.length;return rs("jest",e,{total:f,passed:p,failed:u,skipped:d})}l(Qy,"parseJest");function Zy(s){let e=[],t=/^\s*(✓|×|↓)\s+(.+?)(?:\s+(\d+)ms)?$/gm,o;for(;(o=t.exec(s))!==null;){let n=o[1],i=o[2].trim().split(" > ");e.push({suite:i.length>1?i[0]:"default",name:i[i.length-1],status:n==="\u2713"?"pass":n==="\xD7"?"fail":"skip",durationMs:o[3]?parseInt(o[3],10):void 0})}return rs("vitest",e)}l(Zy,"parseVitest");function e0(s){let e=[],t=/FAILED\s+(\S+?)::(\S+?)(?:\s+-\s+(.+))?$/gm,o;for(;(o=t.exec(s))!==null;)e.push({suite:o[1],name:o[2],status:"fail",file:o[1],error:o[3]});let n=s.match(/=+\s+(?:(\d+) failed,?\s*)?(?:(\d+) passed,?\s*)?(?:(\d+) error,?\s*)?/);return rs("pytest",e,{failed:n?parseInt(n[1]||"0",10):e.filter(r=>r.status==="fail").length,passed:n?parseInt(n[2]||"0",10):0})}l(e0,"parsePytest");function t0(s){let e=[],t=/^test\s+(\S+)\s+\.\.\.\s+(ok|FAILED|ignored)/gm,o;for(;(o=t.exec(s))!==null;){let i=o[1].split("::");e.push({suite:i.slice(0,-1).join("::")||"default",name:i[i.length-1],status:o[2]==="ok"?"pass":o[2]==="ignored"?"skip":"fail"})}let n=/---- (\S+) stdout ----\n([\s\S]*?)(?=\n---- |\nfailures:)/g;for(;(o=n.exec(s))!==null;){let r=o[1],i=e.find(c=>`${c.suite}::${c.name}`===r||c.name===r);i&&(i.error=o[2].trim().split(`
|
|
276
|
+
`)[0])}return rs("cargo",e)}l(t0,"parseCargoTest");function o0(s){let e=[],t=/---\s+(FAIL|PASS|SKIP):\s+(\S+)\s+\((\d+\.?\d*)s\)/gm,o;for(;(o=t.exec(s))!==null;)e.push({suite:"default",name:o[2],status:o[1]==="PASS"?"pass":o[1]==="SKIP"?"skip":"fail",durationMs:Math.round(parseFloat(o[3])*1e3)});let n=/(\S+\.go):(\d+):\s+(.+)/g;for(;(o=n.exec(s))!==null;){let r=e.filter(i=>i.status==="fail").pop();r&&!r.file&&(r.file=o[1],r.line=parseInt(o[2],10),r.error=o[3])}return rs("go",e)}l(o0,"parseGoTest");function s0(s){let e=[],t=s.split(`
|
|
277
|
+
`);for(let o of t)/\bFAIL\b|✕|✗|ERROR|BROKEN/.test(o)&&e.push({suite:"unknown",name:o.trim().substring(0,100),status:"fail"});return rs("unknown",e)}l(s0,"parseGeneric");function rs(s,e,t){let o=t?.failed??e.filter(u=>u.status==="fail").length,n=t?.passed??e.filter(u=>u.status==="pass").length,r=t?.skipped??e.filter(u=>u.status==="skip").length,i=e.filter(u=>u.status==="error").length,c=t?.total??e.length;return{runner:s,total:c,passed:n,failed:o,skipped:r,errors:i,duration:0,results:e,failingTests:e.filter(u=>u.status==="fail")}}l(rs,"buildSummary");var yd=10,bd=1800,wd=5,wr=class{static{l(this,"GoalLoop")}opts;renderer;cancelled=!1;progress;startTime=0;prevFailCount=1/0;checkpointStash=null;lastTestSummary=null;constructor(e,t){this.opts=e,this.renderer=t,this.progress={iteration:0,maxIterations:e.maxIterations||yd,status:"planning",subtasks:[],elapsed:0,totalTokens:0,totalCost:0}}async run(){this.startTime=Date.now();let e=this.opts.maxIterations||yd,t=(this.opts.timeoutSeconds||bd)*1e3,o=this.opts.maxCostUsd||wd,n=K();if(this.printGoalHeader(),!this.opts.verifyCommand){let r=hd(this.opts.workspace);r&&(this.opts.verifyCommand=r,console.log(a.dim(` Auto-detected verify command: ${r}`)))}for(let r=1;r<=e;r++){if(this.cancelled){this.progress.status="cancelled",this.printGoalStatus("cancelled");break}let i=Date.now()-this.startTime;if(i>t){this.progress.status="limit_reached",this.printGoalStatus("timeout");break}if(this.progress.totalCost>o){this.progress.status="limit_reached",this.printGoalStatus("cost_limit");break}this.progress.iteration=r,this.progress.elapsed=i;let c=this.buildIterationPrompt(r,e);this.progress.status="executing",this.printIterationHeader(r,e);let u=new xe({platformUrl:n.platformUrl,token:this.opts.token,model:this.opts.model,workspace:this.opts.workspace,mode:"auto",maxTurns:20,sandboxed:!1,webEnabled:n.webEnabled,effort:"reasoning",userId:this.opts.userId,orgId:this.opts.orgId}),d="";u.on("event",f=>{switch(f.type){case"streaming_chunk":d+=f.content,process.stdout.write(f.content);break;case"streaming_end":console.log("");break;case"tool_call_start":this.renderer.printToolCallStart(f.name,f.args);break;case"tool_call_result":this.renderer.printToolCallResult(f.name,f.result);break;case"run_complete":this.progress.totalTokens+=f.summary.tokensIn+f.summary.tokensOut,this.progress.totalCost+=f.summary.costUsd;break}});try{await u.run(c)}catch(f){this.renderer.printError(`Iteration ${r} error: ${f instanceof Error?f.message:f}`)}if(this.evaluateGoalCompletion(d)){this.progress.status="completed",this.printGoalStatus("completed");break}this.lastTestSummary&&this.lastTestSummary.failed>this.prevFailCount&&(console.log(a.yellow(` \u26A0\uFE0F Failures increased (${this.prevFailCount} \u2192 ${this.lastTestSummary.failed}). Rolling back...`)),this.rollbackCheckpoint()),this.prevFailCount=this.lastTestSummary?.failed??1/0,this.saveCheckpoint(),r===e&&(this.progress.status="limit_reached",this.printGoalStatus("max_iterations"))}return this.progress.elapsed=Date.now()-this.startTime,this.progress}cancel(){this.cancelled=!0}getProgress(){return this.progress.elapsed=Date.now()-this.startTime,{...this.progress}}buildIterationPrompt(e,t){if(e===1)return[`AUTONOMOUS GOAL MODE \u2014 Iteration ${e}/${t}`,"",`Goal: ${this.opts.goal}`,"","You are running in autonomous goal mode. Your job:","1. Plan: Break the goal into concrete sub-tasks","2. Execute: Implement the changes needed","3. Verify: Run tests, lint, or type-check to confirm the goal is met",this.opts.verifyCommand?`4. After you finish, I will automatically run: \`${this.opts.verifyCommand}\`. If it fails, you will get another iteration to fix the issues.`:'4. Report: End your response with "GOAL_STATUS: COMPLETE" if done, or "GOAL_STATUS: IN_PROGRESS" if more work is needed',"","Work autonomously \u2014 do not ask for user input. Make decisions yourself.","If you encounter errors, fix them and continue."].join(`
|
|
269
278
|
`);let o=[`AUTONOMOUS GOAL MODE \u2014 Iteration ${e}/${t}`,"",`Goal: ${this.opts.goal}`,"",`This is iteration ${e}. Previous iterations did not fully complete the goal.`,"Review the current state of the workspace and continue working toward the goal."];if(this.lastTestSummary&&this.lastTestSummary.failingTests.length>0){o.push(""),o.push("The following tests are still failing \u2014 focus on these:");for(let n of this.lastTestSummary.failingTests.slice(0,10)){let r=n.file?` (${n.file}${n.line?`:${n.line}`:""})`:"";o.push(` \u2717 ${n.suite}::${n.name}${r}${n.error?` \u2014 ${n.error.substring(0,80)}`:""}`)}o.push(""),o.push("Fix ONLY these specific failures. Do not refactor unrelated code.")}return o.push(""),o.push('End your response with "GOAL_STATUS: COMPLETE" if the goal is fully met,'),o.push('or "GOAL_STATUS: IN_PROGRESS" if more work is needed.'),o.join(`
|
|
270
279
|
`)}evaluateGoalCompletion(e){return this.opts.verifyCommand?this.runVerifyCommand():!!(e.includes("GOAL_STATUS: COMPLETE")||e.includes("GOAL_STATUS: DONE")||e.includes("All tests pass")&&e.includes("GOAL_STATUS"))}runVerifyCommand(){let e=this.opts.verifyCommand;console.log(a.dim(`
|
|
271
|
-
\u{1F50D} Running verification: ${e}`));try{let o=(0,
|
|
280
|
+
\u{1F50D} Running verification: ${e}`));try{let o=(0,br.execSync)(e,{cwd:this.opts.workspace,timeout:12e4,stdio:["pipe","pipe","pipe"],env:{...process.env,TERM:"dumb",CI:"1"}}).toString().slice(-500);return this.lastTestSummary=La(o),console.log(a.green(" \u2713 Verification passed")),this.lastTestSummary.total>0&&console.log(a.dim(` ${this.lastTestSummary.passed}/${this.lastTestSummary.total} tests passed`)),o.trim()&&console.log(a.dim(` ${o.trim().split(`
|
|
272
281
|
`).slice(-3).join(`
|
|
273
282
|
`)}`)),!0}catch(t){let o=t.stderr?.toString().slice(-500)||"",n=t.stdout?.toString().slice(-500)||"",r=n+`
|
|
274
283
|
`+o;if(this.lastTestSummary=La(r),console.log(a.red(` \u2717 Verification failed (exit ${t.status||"?"}):`)),this.lastTestSummary.failingTests.length>0){console.log(a.red(` ${this.lastTestSummary.failingTests.length} failing test(s):`));for(let i of this.lastTestSummary.failingTests.slice(0,5))console.log(a.red(` \u2717 ${i.suite}::${i.name}${i.error?` \u2014 ${i.error.substring(0,60)}`:""}`))}else o.trim()?console.log(a.dim(` ${o.trim().split(`
|
|
275
284
|
`).slice(-3).join(`
|
|
276
285
|
`)}`)):n.trim()&&console.log(a.dim(` ${n.trim().split(`
|
|
277
286
|
`).slice(-3).join(`
|
|
278
|
-
`)}`));return!1}}saveCheckpoint(){try{(0,
|
|
287
|
+
`)}`));return!1}}saveCheckpoint(){try{(0,br.execSync)('git stash push -m "mc-goal-checkpoint" --include-untracked',{cwd:this.opts.workspace,stdio:"pipe"}),this.checkpointStash="stash@{0}"}catch{this.checkpointStash=null}}rollbackCheckpoint(){if(this.checkpointStash){try{(0,br.execSync)("git stash pop",{cwd:this.opts.workspace,stdio:"pipe"}),console.log(a.dim(" \u21A9 Rolled back to previous checkpoint"))}catch{}this.checkpointStash=null}}printGoalHeader(){console.log(""),console.log(a.bold(` \u{1F3AF} Goal: "${this.opts.goal}"`)),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log(a.dim(` Max iterations: ${this.progress.maxIterations} \xB7 Timeout: ${(this.opts.timeoutSeconds||bd)/60}min \xB7 Max cost: $${(this.opts.maxCostUsd||wd).toFixed(2)}`)),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}printIterationHeader(e,t){let o=((Date.now()-this.startTime)/1e3).toFixed(0);console.log(""),console.log(a.hex("#6B8DD6")(` \u2501\u2501\u2501 Iteration ${e}/${t} \u2501\u2501\u2501 ${o}s elapsed \u2501\u2501\u2501 ${this.progress.totalTokens.toLocaleString()} tokens \u2501\u2501\u2501`)),console.log("")}printGoalStatus(e){let t=((Date.now()-this.startTime)/1e3).toFixed(0);switch(console.log(""),console.log(a.dim(` ${"\u2500".repeat(50)}`)),e){case"completed":console.log(a.green.bold(" \u2705 Goal completed!"));break;case"cancelled":console.log(a.yellow(" \u26A0\uFE0F Goal cancelled by user."));break;case"timeout":console.log(a.yellow(" \u23F1 Goal stopped: timeout reached."));break;case"cost_limit":console.log(a.yellow(` \u{1F4B0} Goal stopped: cost limit reached ($${this.progress.totalCost.toFixed(2)}).`));break;case"max_iterations":console.log(a.yellow(` \u{1F504} Goal stopped: max iterations reached (${this.progress.maxIterations}).`));break}console.log(a.dim(` Iterations: ${this.progress.iteration}`)),console.log(a.dim(` Elapsed: ${t}s`)),console.log(a.dim(` Tokens: ${this.progress.totalTokens.toLocaleString()}`)),console.log(a.dim(` Est. cost: $${this.progress.totalCost.toFixed(4)}`)),e!=="completed"&&console.log(a.dim(" Resume: mc --continue")),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}};W();var kd=b(require("node:crypto"),1);Ke();Q();var kr=class{static{l(this,"SubtaskManager")}subtasks=new Map;loops=new Map;opts;renderer;constructor(e,t){this.opts=e,this.renderer=t}async spawn(e){let t=kd.randomUUID().slice(0,8),o=K(),n={id:t,description:e,status:"running",startTime:Date.now(),tokensUsed:0};this.subtasks.set(t,n),this.renderer.printSuccess(`Subtask ${a.bold(t)} spawned: "${e}"`),console.log(a.dim(` Track: /subtask status \xB7 Cancel: /subtask cancel ${t}`));let r=new xe({platformUrl:o.platformUrl,token:this.opts.token,model:this.opts.model,workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:o.webEnabled,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.loops.set(t,r);let i="";return r.on("event",c=>{switch(c.type){case"streaming_chunk":i+=c.content;break;case"run_complete":n.tokensUsed+=c.summary.tokensIn+c.summary.tokensOut;break}}),this.executeSubtask(t,r,e,n,i).catch(()=>{}),t}cancel(e){let t=this.subtasks.get(e),o=this.loops.get(e);return!t||t.status!=="running"?(this.renderer.printError(`Subtask ${e} not found or not running.`),!1):(o&&o.cancel(),t.status="cancelled",t.endTime=Date.now(),this.loops.delete(e),this.renderer.printSuccess(`Subtask ${e} cancelled.`),!0)}getStatus(){return[...this.subtasks.values()].sort((e,t)=>t.startTime-e.startTime)}printStatus(){let e=this.getStatus();if(e.length===0){console.log(a.dim(" No subtasks."));return}console.log(""),console.log(a.bold(" Subtasks:")),console.log(` ${"\u2500".repeat(70)}`);for(let t of e){let o=((t.endTime||Date.now())-t.startTime)/1e3,n={running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u23F9"}[t.status],r={running:a.cyan,completed:a.green,failed:a.red,cancelled:a.yellow}[t.status];if(console.log(` ${n} ${a.bold(t.id)} ${r(t.status.padEnd(10))} ${t.description.substring(0,40).padEnd(42)} ${a.dim(`${o.toFixed(0)}s ${t.tokensUsed.toLocaleString()} tok`)}`),t.status==="completed"&&t.result){let i=t.result.split(`
|
|
279
288
|
`)[0].substring(0,70);console.log(a.dim(` \u2514\u2500 ${i}`))}t.status==="failed"&&t.error&&console.log(a.red(` \u2514\u2500 ${t.error.substring(0,70)}`))}console.log(` ${"\u2500".repeat(70)}`),console.log("")}async executeSubtask(e,t,o,n,r){try{let i=["You are running as an isolated subtask. Your task:","",`${o}`,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished."].join(`
|
|
280
289
|
`);await t.run(i),n.status="completed",n.endTime=Date.now(),n.result=r;let c=((n.endTime-n.startTime)/1e3).toFixed(0);if(console.log(""),console.log(a.green(` \u2705 Subtask ${a.bold(e)} completed (${c}s, ${n.tokensUsed.toLocaleString()} tokens)`)),console.log(a.dim(` "${o}"`)),r.trim()){let u=r.trim().split(`
|
|
281
290
|
`).slice(0,3).join(`
|
|
282
|
-
`);console.log(a.dim(` ${u}`))}console.log("")}catch(i){n.status="failed",n.endTime=Date.now(),n.error=i instanceof Error?i.message:String(i),console.log(""),console.log(a.red(` \u274C Subtask ${a.bold(e)} failed: ${n.error}`)),console.log("")}finally{this.loops.delete(e)}}};var Ua=
|
|
291
|
+
`);console.log(a.dim(` ${u}`))}console.log("")}catch(i){n.status="failed",n.endTime=Date.now(),n.error=i instanceof Error?i.message:String(i),console.log(""),console.log(a.red(` \u274C Subtask ${a.bold(e)} failed: ${n.error}`)),console.log("")}finally{this.loops.delete(e)}}};var Ua=b(require("node:path"),1),Qs=require("node:child_process"),vd=require("node:events");Ke();var Dr=require("node:child_process"),Pe=b(require("node:fs"),1),Ro=b(require("node:path"),1);var vr=class{constructor(e){this.workspace=e}static{l(this,"ConflictResolver")}async resolve(e,t){if(t.length<2)return this.noConflict(e);try{let o=this.getBaseBranch(),n=this.getFileAtBranch(e,o),r=this.getFileAtBranch(e,t[0]),i=this.getFileAtBranch(e,t[1]),c=Ro.join(this.workspace,".git","mc-merge-tmp");Pe.mkdirSync(c,{recursive:!0});let u=Ro.join(c,"base"),d=Ro.join(c,"ours"),p=Ro.join(c,"theirs");Pe.writeFileSync(u,n),Pe.writeFileSync(d,r),Pe.writeFileSync(p,i);try{(0,Dr.execSync)(`git merge-file ${d} ${u} ${p}`,{cwd:this.workspace,stdio:"pipe"});let f=Pe.readFileSync(d,"utf8");return this.cleanup(c),{file:e,success:!0,hadConflicts:!1,mergedContent:f,conflictMarkers:[]}}catch{let f=Pe.readFileSync(d,"utf8"),m=this.parseConflictMarkers(f,t[1]);if(this.cleanup(c),m.length>0){let g=this.autoResolveMarkers(f);return{file:e,success:g.resolved,hadConflicts:!0,mergedContent:g.content,conflictMarkers:g.resolved?[]:m}}return{file:e,success:!1,hadConflicts:!0,mergedContent:f,conflictMarkers:m}}}catch{return this.noConflict(e)}}async mergeAll(e,t){let o=await this.resolve(e,[t[0],t[1]]);for(let n=2;n<t.length&&o.success;n++){let r=Ro.join(this.workspace,e);Pe.writeFileSync(r,o.mergedContent),o=await this.resolve(e,["HEAD",t[n]])}return o}noConflict(e){let t=Ro.join(this.workspace,e);return{file:e,success:!0,hadConflicts:!1,mergedContent:Pe.existsSync(t)?Pe.readFileSync(t,"utf8"):"",conflictMarkers:[]}}getBaseBranch(){try{return(0,Dr.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:this.workspace,encoding:"utf8"}).trim()}catch{return"HEAD"}}getFileAtBranch(e,t){try{return(0,Dr.execSync)(`git show ${t}:${e}`,{cwd:this.workspace,encoding:"utf8"})}catch{return""}}parseConflictMarkers(e,t){let o=[],n=e.split(`
|
|
283
292
|
`),r=0;for(;r<n.length;){if(n[r].startsWith("<<<<<<<")){let i=r+1,c="",u="",d=!1;for(r++;r<n.length&&!n[r].startsWith(">>>>>>>");)n[r].startsWith("=======")?d=!0:d?u+=n[r]+`
|
|
284
293
|
`:c+=n[r]+`
|
|
285
294
|
`,r++;o.push({startLine:i,endLine:r+1,ours:c.trimEnd(),theirs:u.trimEnd(),branchName:t})}r++}return o}async autoResolveMarkers(e){let t=e.split(`
|
|
@@ -287,84 +296,84 @@ ${e}`,"wrappedToString"),Dh=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
287
296
|
`:c+=t[n]+`
|
|
288
297
|
`,n++;if(n++,c.trim()===u.trim())o.push(c.trimEnd());else if(c.trim()==="")o.push(u.trimEnd());else if(u.trim()==="")o.push(c.trimEnd());else{let p=`__CONFLICT_${i.length}__`;i.push({ours:c.trimEnd(),theirs:u.trimEnd(),index:i.length}),o.push(p),r=!1}}else o.push(t[n]),n++;if(i.length>0){let c=o.join(`
|
|
289
298
|
`);for(let d of i){let p=await this.llmMerge(d.ours,d.theirs);p?c=c.replace(`__CONFLICT_${d.index}__`,p):c=c.replace(`__CONFLICT_${d.index}__`,d.ours)}let u=/__CONFLICT_\d+__/.test(c);return{content:c,resolved:!u}}return{content:o.join(`
|
|
290
|
-
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(
|
|
291
|
-
`);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{
|
|
299
|
+
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(Ke(),es)),{loadSettings:n}=await Promise.resolve().then(()=>(Q(),Se)),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),ge)),i=n(),c=await r()||process.env.MC_API_KEY||"";if(!c)return null;let u=new o({platformUrl:i.platformUrl,token:c,model:i.defaultModel||"capuchin-reason",workspace:this.workspace,mode:"auto",maxTurns:1,sandboxed:!0,webEnabled:!1,effort:"fast"}),d="";u.on("event",m=>{m.type==="streaming_chunk"&&(d+=m.content)});let p=["You are merging two versions of a code section that were edited by different agents.","Combine both changes intelligently, preserving the intent of each.","Return ONLY the merged code. No explanations, no markdown fences.","","=== Version A (ours) ===",e,"","=== Version B (theirs) ===",t,"","=== Merged result ==="].join(`
|
|
300
|
+
`);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{Pe.rmSync(e,{recursive:!0,force:!0})}catch{}}};Q();var Dd=require("node:events"),Ba=b(require("node:crypto"),1);var Sr=class extends Dd.EventEmitter{static{l(this,"MessagingBroker")}subscriptions=new Map;messageLog=[];maxLogSize=1e3;subscribe(e,t){return this.subscriptions.has(e)||this.subscriptions.set(e,new Set),this.subscriptions.get(e).add(t),()=>{this.subscriptions.get(e)?.delete(t)}}publish(e,t){let o={id:Ba.randomUUID(),timestamp:Date.now(),...t};this.messageLog.push({...o,channel:e}),this.messageLog.length>this.maxLogSize&&(this.messageLog=this.messageLog.slice(-this.maxLogSize));let n=this.subscriptions.get(e);if(n)for(let r of n)try{let i=r(o);i instanceof Promise&&i.catch(()=>{})}catch{}this.emit("message",{channel:e,...o})}async request(e,t,o=1e4){let n=`reply.${Ba.randomUUID()}`;return new Promise(r=>{let i=setTimeout(()=>{c(),r(null)},o),c=this.subscribe(n,u=>{clearTimeout(i),c(),r(u)});this.publish(e,{...t,data:{...t.data,replyChannel:n}})})}getHistory(e){return e?this.messageLog.filter(t=>t.channel===e):[...this.messageLog]}clear(){this.subscriptions.clear(),this.messageLog=[],this.removeAllListeners()}};var xr=class extends vd.EventEmitter{static{l(this,"AgentOrchestrator")}opts;resolver;activeLoops=new Map;broker;constructor(e){super(),this.opts={maxConcurrency:5,timeoutMs:6e5,...e},this.resolver=new vr(e.workspace),this.broker=new Sr,this.broker.subscribe("orchestrator",t=>{this.emit("agent-message",t)})}async fanOut(e){let t=new Map,o=new Map(e.map(r=>[r.id,r])),n=new Map;for(;o.size>0||n.size>0;){for(let[r,i]of o){if(n.size>=(this.opts.maxConcurrency||5))break;if(!i.dependencies.every(d=>t.has(d)))continue;o.delete(r),i.status="running",this.emitEvent("task.started",r);let u=this.runIsolated(i).then(d=>(t.set(r,d),n.delete(r),i.status=d.status,this.emitEvent("task.completed",r,{filesChanged:d.filesChanged}),d)).catch(d=>{let p={taskId:r,status:"failed",output:"",filesChanged:[],tokensUsed:0,costUsd:0,durationMs:0,error:d instanceof Error?d.message:String(d)};return t.set(r,p),n.delete(r),i.status="failed",this.emitEvent("task.failed",r,{error:p.error}),p});n.set(r,u)}if(n.size>0)await Promise.race(n.values());else if(o.size>0){for(let[r]of o)t.set(r,{taskId:r,status:"failed",output:"",filesChanged:[],tokensUsed:0,costUsd:0,durationMs:0,error:"Dependency deadlock \u2014 required tasks failed or missing"});break}}return e.map(r=>t.get(r.id))}async fanIn(e){let t=new Map,o=[],n=[],r=Date.now();for(let u of e)for(let d of u.filesChanged){let p=t.get(d)||[];p.push(u.taskId),t.set(d,p)}for(let[u,d]of t)if(d.length===1){let p=e.find(f=>f.taskId===d[0]);p.worktreeBranch&&await this.cherryPickFile(u,p.worktreeBranch),n.push(u)}else{this.emitEvent("conflict.detected",d[0],{file:u,agents:d});let p=e.filter(m=>d.includes(m.taskId)&&m.worktreeBranch).map(m=>m.worktreeBranch),f=await this.resolver.resolve(u,p);o.push({file:u,agents:d,resolution:f.hadConflicts?"llm-merged":"auto-merged"}),n.push(u)}for(let u of e)u.worktreeBranch&&this.cleanupWorktree(u.worktreeBranch);let i=e.reduce((u,d)=>u+d.tokensUsed,0),c=e.reduce((u,d)=>u+d.costUsd,0);return this.emitEvent("merge.complete","orchestrator",{mergedFiles:n.length,conflicts:o.length}),{success:e.every(u=>u.status==="complete"),results:e,conflicts:o,mergedFiles:n,totalTokens:i,totalCost:c,totalDurationMs:Date.now()-r}}async pipeline(e){let t=[],o="",n=Date.now();for(let r of e){this.emitEvent("pipeline.stage",r.id,{index:e.indexOf(r)});let i=r.prompt;o&&r.inputTransform?i+=`
|
|
292
301
|
|
|
293
302
|
`+r.inputTransform(o):o&&(i+=`
|
|
294
303
|
|
|
295
304
|
--- Previous stage output ---
|
|
296
|
-
${o}`);let c={id:r.id,prompt:i,workspace:this.opts.workspace,parentId:"pipeline",dependencies:[],status:"pending",model:r.model,maxCostUsd:r.maxCostUsd},u=await this.runInline(c);if(t.push({...u,stageId:r.id}),o=u.output,u.status==="failed")break}return{stages:t,finalOutput:o,totalTokens:t.reduce((r,i)=>r+i.tokensUsed,0),totalCost:t.reduce((r,i)=>r+i.costUsd,0),totalDurationMs:Date.now()-n}}cancelAll(){for(let[e,t]of this.activeLoops)t.cancel(),this.activeLoops.delete(e)}async runIsolated(e){let t=`mc-agent-${e.id}-${Date.now()}`,o=Ua.join(this.opts.workspace,"..",`.mc-worktree-${e.id}`);try{return(0,
|
|
297
|
-
`);return await p.run(g),{taskId:e.id,status:"complete",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,worktreeBranch:o}}catch(g){return{taskId:e.id,status:"failed",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,error:g instanceof Error?g.message:String(g),worktreeBranch:o}}finally{clearTimeout(m),this.activeLoops.delete(e.id)}}async cherryPickFile(e,t){try{(0,
|
|
298
|
-
`)}l(uc,"addMcpServer");function
|
|
299
|
-
`),!0):!1}l(
|
|
300
|
-
`)[0]}catch{return null}}l(Ab,"getVersion");
|
|
301
|
-
`)}}},
|
|
305
|
+
${o}`);let c={id:r.id,prompt:i,workspace:this.opts.workspace,parentId:"pipeline",dependencies:[],status:"pending",model:r.model,maxCostUsd:r.maxCostUsd},u=await this.runInline(c);if(t.push({...u,stageId:r.id}),o=u.output,u.status==="failed")break}return{stages:t,finalOutput:o,totalTokens:t.reduce((r,i)=>r+i.tokensUsed,0),totalCost:t.reduce((r,i)=>r+i.costUsd,0),totalDurationMs:Date.now()-n}}cancelAll(){for(let[e,t]of this.activeLoops)t.cancel(),this.activeLoops.delete(e)}async runIsolated(e){let t=`mc-agent-${e.id}-${Date.now()}`,o=Ua.join(this.opts.workspace,"..",`.mc-worktree-${e.id}`);try{return(0,Qs.execSync)(`git worktree add -b ${t} ${o}`,{cwd:this.opts.workspace,stdio:"pipe"}),await this.executeAgent(e,o,t)}catch{return await this.executeAgent(e,this.opts.workspace,void 0)}}async runInline(e){return await this.executeAgent(e,this.opts.workspace,void 0)}async executeAgent(e,t,o){let n=K(),r=Date.now(),i="",c=0,u=0,d=[],p=new xe({platformUrl:n.platformUrl,token:this.opts.token,model:e.model||this.opts.model,workspace:t,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeLoops.set(e.id,p);let f=e.timeoutMs||this.opts.timeoutMs||6e5,m=setTimeout(()=>p.cancel(),f);p.on("event",g=>{switch(g.type){case"streaming_chunk":i+=g.content;break;case"tool_call_start":if(["write_file","edit_file","create_file","replace_file_content"].includes(g.name)){let h=g.args.path||g.args.file_path||g.args.target_file;h&&d.push(h)}this.broker.publish(`agent.${e.id}`,{from:e.id,type:"tool_call",data:{tool:g.name}});break;case"run_complete":c+=g.summary.tokensIn+g.summary.tokensOut,u+=g.summary.costUsd||0,this.broker.publish("orchestrator",{from:e.id,type:"complete",data:{tokensUsed:c,costUsd:u,filesChanged:[...new Set(d)]}});break}});try{let g=["You are running as a parallel subagent in an orchestrated multi-agent workflow.","","Your specific task:",e.prompt,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished concisely."].join(`
|
|
306
|
+
`);return await p.run(g),{taskId:e.id,status:"complete",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,worktreeBranch:o}}catch(g){return{taskId:e.id,status:"failed",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,error:g instanceof Error?g.message:String(g),worktreeBranch:o}}finally{clearTimeout(m),this.activeLoops.delete(e.id)}}async cherryPickFile(e,t){try{(0,Qs.execSync)(`git checkout ${t} -- ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}cleanupWorktree(e){try{let t=Ua.join(this.opts.workspace,"..",`.mc-worktree-${e.replace(/^mc-agent-/,"")}`);(0,Qs.execSync)(`git worktree remove --force ${t}`,{cwd:this.opts.workspace,stdio:"pipe"}),(0,Qs.execSync)(`git branch -D ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}emitEvent(e,t,o){let n={type:e,taskId:t,data:o};this.emit("orchestrator",n)}};var Bp=b(require("node:fs"),1),Br=require("node:child_process");W();X();_e();var Pp=require("node:child_process"),mo=b(require("node:fs"),1),Lr=b(require("node:path"),1),Mp=require("node:events");an();X();var Tb=1;function _p(s,e={}){return{jsonrpc:"2.0",id:Tb++,method:s,params:e}}l(_p,"createRequest");function Ep(s){return JSON.stringify(s)}l(Ep,"serialize");function Fp(s){try{let e=JSON.parse(s);return e.kind||e.id!==void 0||e.method?e:null}catch{return null}}l(Fp,"parseMessage");function Tp(s){return typeof s=="object"&&s!==null&&"kind"in s}l(Tp,"isDaemonEvent");function Rp(s){return typeof s=="object"&&s!==null&&"id"in s&&"jsonrpc"in s}l(Rp,"isRpcResponse");var po=class extends Mp.EventEmitter{static{l(this,"DaemonConnection")}ws=null;daemonProcess=null;pending=new Map;platform;paths;opts;reconnectAttempts=0;_connected=!1;constructor(e={}){super(),this.platform=Ce(),this.paths=A(),this.opts={daemonBinary:e.daemonBinary??process.env.MONKEYSCODE_DAEMON??this.platform.daemonBinary,port:e.port??9120,startTimeout:e.startTimeout??15e3,rpcTimeout:e.rpcTimeout??6e4,maxReconnectAttempts:e.maxReconnectAttempts??3,autoSpawn:e.autoSpawn??!0}}get connected(){return this._connected}async connect(){let e=await this.findRunningDaemon();if(e){await this.connectWebSocket(e);return}if(!this.opts.autoSpawn)throw new Error("Daemon is not running and auto-spawn is disabled. Start the daemon manually or use --auto-spawn.");let t=await this.spawnDaemon();await this.connectWebSocket(t)}async call(e,t={}){if(!this.ws||!this._connected)throw new Error("Not connected to daemon");let o=_p(e,t);return new Promise((n,r)=>{let i=setTimeout(()=>{this.pending.delete(o.id),r(new Error(`RPC timeout after ${this.opts.rpcTimeout}ms: ${e}`))},this.opts.rpcTimeout);this.pending.set(o.id,{resolve:n,reject:r,timer:i}),this.ws.send(Ep(o))})}async sendApproval(e,t,o){await this.call("approval.respond",{tool_id:e,approved:t,always_for_type:o??!1})}disconnect(){this.ws&&(this.ws.close(1e3,"CLI disconnecting"),this.ws=null),this._connected=!1}killDaemon(){this.daemonProcess&&(this.daemonProcess.kill("SIGTERM"),this.daemonProcess=null),this.disconnect()}async findRunningDaemon(){try{if(!mo.existsSync(this.paths.pidFile))return null;let e=mo.readFileSync(this.paths.pidFile,"utf8").trim(),[t,o]=e.split(":"),n=parseInt(t,10),r=parseInt(o,10);if(isNaN(n)||isNaN(r))return null;try{return process.kill(n,0),r}catch{return mo.unlinkSync(this.paths.pidFile),null}}catch{return null}}async spawnDaemon(){Yn(Lr.dirname(this.paths.pidFile)),Yn(this.paths.logs);let e=Lr.join(this.paths.logs,`daemon-${Date.now()}.log`),t=mo.createWriteStream(e,{flags:"a"}),o=this.opts.port;return this.daemonProcess=(0,Pp.spawn)(this.opts.daemonBinary,["--port",String(o),"--pid-file",this.paths.pidFile],{stdio:["ignore",t,t],detached:!0,env:{...process.env,MONKEYSCODE_DAEMON_PORT:String(o)}}),this.daemonProcess.unref(),this.daemonProcess.on("error",n=>{this.emit("error",new Error(`Failed to spawn daemon: ${n.message}`))}),this.daemonProcess.stderr?.on("data",n=>{this.emit("daemon:stderr",n.toString())}),await this.waitForDaemon(o),o}async waitForDaemon(e){let t=Date.now()+this.opts.startTimeout,o=200;for(;Date.now()<t;)try{await this.tryConnect(e);return}catch{await Ap(o)}throw new Error(`Daemon did not start within ${this.opts.startTimeout}ms. Check logs or run 'mc doctor' to diagnose.`)}tryConnect(e){return new Promise((t,o)=>{let n=new lt(`ws://127.0.0.1:${e}/cli`),r=setTimeout(()=>{n.close(),o(new Error("Connection timeout"))},3e3);n.on("open",()=>{clearTimeout(r),n.close(),t()}),n.on("error",i=>{clearTimeout(r),o(i)})})}async connectWebSocket(e){return new Promise((t,o)=>{this.ws=new lt(`ws://127.0.0.1:${e}/cli`);let n=setTimeout(()=>{o(new Error(`WebSocket connection timeout (port ${e})`))},5e3);this.ws.on("open",()=>{clearTimeout(n),this._connected=!0,this.reconnectAttempts=0,this.emit("connected"),t()}),this.ws.on("message",r=>{this.handleMessage(r.toString())}),this.ws.on("close",(r,i)=>{this._connected=!1,this.emit("disconnected",{code:r,reason:i.toString()}),this.attemptReconnect(e)}),this.ws.on("error",r=>{clearTimeout(n),this.emit("error",r),this._connected||o(r)})})}handleMessage(e){let t=Fp(e);if(t){if(Rp(t)){let o=this.pending.get(t.id);o&&(this.pending.delete(t.id),clearTimeout(o.timer),t.error?o.reject(new Error(`RPC error [${t.error.code}]: ${t.error.message}`)):o.resolve(t.result));return}if(Tp(t)){this.emit("event",t);return}}}async attemptReconnect(e){if(this.reconnectAttempts>=this.opts.maxReconnectAttempts){this.emit("error",new Error("Max reconnection attempts reached"));return}this.reconnectAttempts++;let t=Math.min(1e3*Math.pow(2,this.reconnectAttempts-1),5e3);await Ap(t);try{await this.connectWebSocket(e)}catch{}}};function Ap(s){return new Promise(e=>setTimeout(e,s))}l(Ap,"sleep");ee();$a();var He=b(require("node:fs"),1),ut=b(require("node:path"),1);X();function cn(s){let e=A(),t=ut.join(s,".monkeyscode","mcp.json"),o=ut.join(e.config,"mcp.json"),n=Op(o),r=Op(t),i=new Map;for(let c of n)i.set(c.name,c);for(let c of r)i.set(c.name,c);return Array.from(i.values())}l(cn,"loadMcpConfig");function Op(s){if(!He.existsSync(s))return[];try{let e=He.readFileSync(s,"utf-8"),t=JSON.parse(e);return!t.servers||typeof t.servers!="object"?[]:Object.entries(t.servers).map(([o,n])=>({name:o,...n,transport:Rb(n),autoStart:n.autoStart??!0}))}catch{return[]}}l(Op,"loadConfigFile");function Rb(s){return s.transport?s.transport:s.url?"sse":"stdio"}l(Rb,"detectTransport");function uc(s,e,t,o){let n=ut.join(s,".monkeyscode","mcp.json"),r=Np(n);r.servers[e]={command:t,args:o};let i=ut.dirname(n);He.mkdirSync(i,{recursive:!0}),He.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
307
|
+
`)}l(uc,"addMcpServer");function Ip(s,e){let t=ut.join(s,".monkeyscode","mcp.json"),o=Np(t);return o.servers[e]?(delete o.servers[e],He.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
308
|
+
`),!0):!1}l(Ip,"removeMcpServer");function jp(s){let e=A();return[{path:ut.join(s,".monkeyscode","mcp.json"),source:"project",exists:He.existsSync(ut.join(s,".monkeyscode","mcp.json"))},{path:ut.join(e.config,"mcp.json"),source:"global",exists:He.existsSync(ut.join(e.config,"mcp.json"))}]}l(jp,"getMcpConfigPaths");function Np(s){if(!He.existsSync(s))return{servers:{}};try{return JSON.parse(He.readFileSync(s,"utf-8"))}catch{return{servers:{}}}}l(Np,"loadConfigFileRaw");cr();async function ln(s={}){let e=I(),t=H(e),o=e.ansi,n=Ce(),r=A();console.log(""),console.log(o?a.bold(" \u{1FA7A} MonkeysCode Doctor"):" MonkeysCode Doctor"),console.log(o?a.dim(` Platform: ${n.os} (${n.arch}) \xB7 Shell: ${n.shell}`):` Platform: ${n.os} (${n.arch}) \xB7 Shell: ${n.shell}`),console.log("");let i=[],c=process.version,u=parseInt(c.slice(1).split(".")[0],10);i.push(u>=20?{name:"Node.js",status:"ok",message:`${c}`}:{name:"Node.js",status:"error",message:`${c} (requires >= 20)`,fix:"Install Node.js 20+ from https://nodejs.org"});let d=Lp(n.daemonBinary);i.push(d?{name:"Daemon binary",status:"ok",message:`${n.daemonBinary} found on PATH`}:{name:"Daemon binary",status:"warn",message:"Not found on PATH",fix:"The daemon will be downloaded on first run, or install manually"});try{let E=new po({autoSpawn:!1,startTimeout:3e3});await E.connect(),E.disconnect(),i.push({name:"Daemon connection",status:"ok",message:"Connected"})}catch{i.push({name:"Daemon connection",status:"warn",message:"Not running (will auto-start)",fix:"The daemon starts automatically when you run a command"})}i.push(ba()?{name:"Authentication",status:"ok",message:"Logged in"}:{name:"Authentication",status:"warn",message:"Not logged in",fix:"Run: mc auth login"});let p=Lp("git");i.push(p?{name:"Git",status:"ok",message:Ab("git --version")||"found"}:{name:"Git",status:"error",message:"Not found",fix:"Install git: https://git-scm.com"});let m=await new ss(ar(".")).checkAllProviders(),g=m.filter(E=>E.available);if(g.length>0)i.push({name:"Sandbox",status:"ok",message:`Available: ${g.map(E=>E.name).join(", ")}`});else{let E=n.os==="linux"?"Install bubblewrap: apt install bubblewrap":n.os==="macos"?"Install Docker Desktop":"Enable Windows Sandbox or install Docker Desktop";i.push({name:"Sandbox",status:"warn",message:"No sandbox provider available",fix:E})}for(let E of m)E.available||i.push({name:` \u2514 ${E.name}`,status:"warn",message:E.reason||"Not available"});let h=process.cwd(),y=cn(h);y.length>0?i.push({name:"MCP servers",status:"ok",message:`${y.length} configured: ${y.map(E=>E.name).join(", ")}`}):i.push({name:"MCP servers",status:"ok",message:"None configured (optional)"});let S=Fo(h);S.length>0?i.push({name:"Hooks",status:"ok",message:`${S.length} active: ${S.map(E=>E.event).join(", ")}`}):i.push({name:"Hooks",status:"ok",message:"None configured (optional)"});let D=Bp.existsSync(r.config);i.push(D?{name:"Config directory",status:"ok",message:r.config}:{name:"Config directory",status:"warn",message:`Not found: ${r.config}`,fix:"Will be created on first run"});let C=I();i.push({name:"Terminal",status:"ok",message:[C.trueColor?"24-bit color":C.color256?"256 color":C.color16?"16 color":"no color",C.unicode?"Unicode":"ASCII",C.interactive?"interactive":"non-interactive",`${C.columns}x${C.rows}`].join(" \xB7 ")});for(let E of i){let oe=E.status==="ok"?t.success:E.status==="warn"?t.warning:t.error,U=E.status==="ok"?o?a.green:pe=>pe:E.status==="warn"?o?a.yellow:pe=>pe:o?a.red:pe=>pe;console.log(` ${oe} ${U(`${E.name}`)}: ${E.message}`),E.fix&&console.log(o?a.dim(` Fix: ${E.fix}`):` Fix: ${E.fix}`)}console.log("");let x=i.filter(E=>E.status==="error").length,v=i.filter(E=>E.status==="warn").length;if(x>0?console.log(o?a.red(` ${x} error(s), ${v} warning(s)`):` ${x} error(s), ${v} warning(s)`):v>0?console.log(o?a.yellow(` All good! ${v} warning(s)`):` All good! ${v} warning(s)`):console.log(o?a.green(" \u2728 Everything looks great!"):" Everything looks great!"),console.log(""),s.fix){let E=i.filter(oe=>oe.status!=="ok"&&oe.fix);if(E.length===0)console.log(o?a.green(" Nothing to fix!"):" Nothing to fix!");else{console.log(o?a.bold(" \u{1F527} Auto-fixing issues..."):" Auto-fixing issues..."),console.log("");for(let oe of E){console.log(` \u2192 ${oe.name}: ${oe.fix}`);try{(0,Br.execSync)(oe.fix,{stdio:"inherit"}),console.log(o?a.green(" \u2705 Fixed"):" Fixed")}catch{console.log(o?a.red(" \u274C Fix failed"):" Fix failed")}}}console.log("")}}l(ln,"doctorCommand");function Lp(s){try{return(0,Br.execSync)(`which ${s} 2>/dev/null || where ${s} 2>nul`,{stdio:"pipe"}),!0}catch{return!1}}l(Lp,"checkBinary");function Ab(s){try{return(0,Br.execSync)(s,{stdio:"pipe"}).toString().trim().split(`
|
|
309
|
+
`)[0]}catch{return null}}l(Ab,"getVersion");gr();ur();var dc=b(require("node:fs"),1),pc=require("node:child_process");function Gt(s){return s.replace(/\\/g,"/")}l(Gt,"normalizePath");var fs=class{static{l(this,"JsonFormatter")}formatResult(e){let t={success:e.success,status:e.status,summary:e.summary,platform:e.platform,filesChanged:e.filesChanged.map(o=>({...o,path:Gt(o.path)})),toolCalls:e.toolCalls.map(({tool:o,args:n,duration:r})=>({tool:o,args:n,duration:r})),verification:e.verification,tokens:e.tokens,cost:e.cost,duration:e.duration,model:e.model,sessionId:e.sessionId,...e.error?{error:e.error}:{}};return JSON.stringify(t,null,2)}formatEvent(e){return null}},mc=class{static{l(this,"JsonlFormatter")}formatResult(e){let t={type:"result",timestamp:Date.now(),success:e.success,status:e.status,summary:e.summary,tokens:e.tokens,cost:e.cost,duration:e.duration,filesChanged:e.filesChanged.map(o=>({...o,path:Gt(o.path)}))};return JSON.stringify(t)}formatEvent(e){return JSON.stringify({type:e.type,timestamp:e.timestamp,...e.data})}},fc=class{static{l(this,"DiffFormatter")}workspace;constructor(e){this.workspace=e}formatResult(e){try{let t=(0,pc.execSync)("git diff",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760});return t.trim()?t:(0,pc.execSync)("git diff --cached",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760})||"# No changes detected"}catch{return e.filesChanged.map(t=>`# ${t.action}: ${Gt(t.path)} (+${t.linesAdded} -${t.linesRemoved})`).join(`
|
|
310
|
+
`)}}},Ur=class{static{l(this,"MarkdownFormatter")}formatResult(e){let t=[];if(t.push(`# ${e.success?"\u2705":"\u274C"} Agent Run ${e.status}`),t.push(""),t.push(`> ${e.summary}`),t.push(""),e.filesChanged.length>0){t.push("## Files Changed"),t.push(""),t.push("| File | Action | Lines |"),t.push("|---|---|---|");for(let o of e.filesChanged)t.push(`| \`${Gt(o.path)}\` | ${o.action} | +${o.linesAdded} -${o.linesRemoved} |`);t.push("")}if(e.toolCalls.length>0){t.push("## Tool Calls"),t.push("");for(let o of e.toolCalls)t.push(`- **${o.tool}** (${o.duration}ms)`);t.push("")}return e.verification&&(t.push("## Verification"),t.push(""),e.verification.lint&&t.push(`- Lint: ${e.verification.lint.passed?"\u2705 Passed":"\u274C Failed"}`),e.verification.typecheck&&t.push(`- Type check: ${e.verification.typecheck.passed?"\u2705 Passed":"\u274C Failed"}`),e.verification.tests&&(t.push(`- Tests: ${e.verification.tests.passed?"\u2705 Passed":"\u274C Failed"}`),e.verification.tests.output&&t.push(` ${e.verification.tests.output}`)),t.push("")),t.push("## Stats"),t.push(""),t.push(`- **Model:** ${e.model}`),t.push(`- **Tokens:** ${e.tokens.total.toLocaleString()} (${e.tokens.input.toLocaleString()} in / ${e.tokens.output.toLocaleString()} out)`),t.push(`- **Cost:** $${e.cost.toFixed(4)}`),t.push(`- **Duration:** ${(e.duration/1e3).toFixed(1)}s`),t.push(""),e.error&&(t.push("## Error"),t.push(""),t.push(`\`\`\`
|
|
302
311
|
${e.error}
|
|
303
312
|
\`\`\``),t.push("")),t.join(`
|
|
304
|
-
`)}},gc=class{static{l(this,"GitHubFormatter")}formatResult(e){let t=[],o=process.env.GITHUB_OUTPUT;if(o){let r=[`success=${e.success}`,`status=${e.status}`,`summary=${e.summary}`,`files-changed=${e.filesChanged.map(i=>
|
|
313
|
+
`)}},gc=class{static{l(this,"GitHubFormatter")}formatResult(e){let t=[],o=process.env.GITHUB_OUTPUT;if(o){let r=[`success=${e.success}`,`status=${e.status}`,`summary=${e.summary}`,`files-changed=${e.filesChanged.map(i=>Gt(i.path)).join(",")}`,`cost=${e.cost.toFixed(4)}`,`tokens=${e.tokens.total}`,`duration=${e.duration}`,`model=${e.model}`,`session-id=${e.sessionId}`];try{dc.appendFileSync(o,r.join(`
|
|
305
314
|
`)+`
|
|
306
|
-
`)}catch{}}t.push(`::set-output name=success::${e.success}`),t.push(`::set-output name=status::${e.status}`),t.push(`::set-output name=summary::${e.summary}`),t.push(`::set-output name=files-changed::${e.filesChanged.map(r=>
|
|
315
|
+
`)}catch{}}t.push(`::set-output name=success::${e.success}`),t.push(`::set-output name=status::${e.status}`),t.push(`::set-output name=summary::${e.summary}`),t.push(`::set-output name=files-changed::${e.filesChanged.map(r=>Gt(r.path)).join(",")}`),t.push(`::set-output name=cost::${e.cost.toFixed(4)}`),t.push(`::set-output name=tokens::${e.tokens.total}`),t.push(`::set-output name=duration::${e.duration}`),t.push(`::set-output name=model::${e.model}`),t.push(`::set-output name=session-id::${e.sessionId}`);let n=process.env.GITHUB_STEP_SUMMARY;if(n){let r=new Ur().formatResult(e);try{dc.appendFileSync(n,r+`
|
|
307
316
|
`)}catch{}}return!e.success&&e.error&&t.push(`::error::${e.error}`),t.join(`
|
|
308
|
-
`)}},hc=class{static{l(this,"AzureFormatter")}formatResult(e){let t=[];return t.push(`##vso[task.setvariable variable=agentSuccess]${e.success}`),t.push(`##vso[task.setvariable variable=agentStatus]${e.status}`),t.push(`##vso[task.setvariable variable=agentSummary]${e.summary}`),t.push(`##vso[task.setvariable variable=agentCost]${e.cost.toFixed(4)}`),t.push(`##vso[task.setvariable variable=agentFilesChanged]${e.filesChanged.map(o=>
|
|
309
|
-
`)}},
|
|
317
|
+
`)}},hc=class{static{l(this,"AzureFormatter")}formatResult(e){let t=[];return t.push(`##vso[task.setvariable variable=agentSuccess]${e.success}`),t.push(`##vso[task.setvariable variable=agentStatus]${e.status}`),t.push(`##vso[task.setvariable variable=agentSummary]${e.summary}`),t.push(`##vso[task.setvariable variable=agentCost]${e.cost.toFixed(4)}`),t.push(`##vso[task.setvariable variable=agentFilesChanged]${e.filesChanged.map(o=>Gt(o.path)).join(",")}`),t.push(`##vso[task.setvariable variable=agentTokens]${e.tokens.total}`),t.push(`##vso[task.setvariable variable=agentDuration]${e.duration}`),e.success?t.push(`##vso[task.complete result=Succeeded;]${e.summary}`):t.push(`##vso[task.complete result=Failed;]${e.error||e.summary}`),t.push(`##vso[task.uploadsummary]MonkeysCode: ${e.summary}`),t.join(`
|
|
318
|
+
`)}},gs=class{static{l(this,"SarifFormatter")}findings;workspace;constructor(e=[],t="."){this.findings=e,this.workspace=t}formatResult(e){return this.formatFindings(this.findings)}formatFindings(e){let t={$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"MonkeysCode",informationUri:"https://monkeyscode.com",version:"1.0.0",rules:this.extractRules(e)}},results:e.map((o,n)=>({ruleId:o.ruleId||`MC${String(n+1).padStart(3,"0")}`,level:this.mapSeverity(o.severity),message:{text:o.message},locations:[{physicalLocation:{artifactLocation:{uri:Gt(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:Gt(o.file),uriBaseId:"%SRCROOT%"},replacements:[{deletedRegion:{startLine:o.line},insertedContent:{text:o.fix}}]}]}]}:{}}))}]};return JSON.stringify(t,null,2)}extractRules(e){let t=new Set;return e.filter(o=>{let n=o.ruleId||"MC001";return t.has(n)?!1:(t.add(n),!0)}).map((o,n)=>({id:o.ruleId||`MC${String(n+1).padStart(3,"0")}`,shortDescription:{text:o.message.substring(0,100)},defaultConfiguration:{level:this.mapSeverity(o.severity)}}))}mapSeverity(e){switch(e){case"high":return"error";case"medium":return"warning";case"low":return"note";default:return"none"}}};function Up(s,e={}){switch(s){case"json":return new fs;case"jsonl":return new mc;case"diff":return new fc(e.workspace||".");case"markdown":return new Ur;case"github":return new gc;case"azure":return new hc;case"sarif":return new gs(e.findings,e.workspace);case"text":case"stream":default:return new fs}}l(Up,"createFormatter");function Wp(s,e){return{success:!1,status:"failed",summary:"",platform:process.platform,filesChanged:[],toolCalls:[],tokens:{input:0,output:0,thinking:0,total:0},cost:0,duration:0,model:s,sessionId:e}}l(Wp,"createEmptyResult");function gm(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(gm,"mapMode");async function hm(s){let e=I(),t=s.prompt;!t&&!e.interactive&&(t=await Xb());let o=await Fe();if(o||(console.error(a.red(" Error: Not authenticated. Run `mc auth login` first.")),process.exit(1)),s.model==="auto"){let r=K();s.model=r.defaultModel}let n=fe();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(Zp(),Qp));await r({jobId:s.resume,workspace:s.workspace}),await mm(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Rc(),sm));await r(s.prompt,s.workspace,s.model)}else s.headless?await Kb(t,s,o,n):s.background?await Yb(t,s):await mm(t,s,o,n)}l(hm,"runCommand");async function mm(s,e,t,o){let n=I(),r=K(),i=new Co({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new To(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new Lt,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,g=new Set,h=0,y=0,S=0,D=0,C=null,x=!1;if(e.continueSession){let M=u.loadLatest(e.workspace);if(M){d=M,D=M.turnCount;for(let N of M.stats.filesChanged)m.add(N);i.printSuccess(`Resumed session ${M.id.substring(0,8)} (${M.turnCount} turns, ${M.stats.tokensUsed.toLocaleString()} tokens)`)}else console.log(a.dim(" No previous session found \u2014 starting fresh."))}i.printBanner(`${e.mode} mode \xB7 ${e.model}`);{let M=a.dim,N=a.green,T=a.yellow,O=a.hex("#6B8DD6"),_=a.bold(e.model),w=M(e.mode);console.log(` ${O("Model:")} ${_} ${M("\xB7")} ${w} mode`);let k=(()=>{try{return(0,Qe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),$=(()=>{try{return(0,Qe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),F=k?` ${M("\xB7")} ${M("branch:")} ${k}${$?T(" \u25CF"):N(" \u2713")}`:"";console.log(` ${O("Path:")} ${M(e.workspace)}${F}`);let R=e.sandbox?N("\u{1F512} on"):T("off"),q=e.permissionMode!=="default"?` ${M("\xB7")} ${M("perm:")} ${e.permissionMode}`:"",P=e.autoApprove?` ${M("\xB7")} ${T("auto-approve")}`:e.approveForMe?` ${M("\xB7")} ${N("smart-approve")}`:"";console.log(` ${O("Sandbox:")} ${R}${q}${P}`);let tt=c.getHooks(),$e=tt.length>0?`${tt.length} hooks`:M("none"),ot=0;try{let{listAllSkills:Re}=await Promise.resolve().then(()=>(pr(),Pa));ot=Re(e.workspace).length}catch{}let Ts=ot>0?`${ot} skills`:M("none");console.log(` ${O("Plugins:")} ${$e} ${M("\xB7")} ${Ts}`);let Rs=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${O("Engine:")} ${M(Rs)}`)}console.log("");let v=i.getStatusBar({model:e.model,mode:e.mode,branch:(()=>{try{return(0,Qe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),dirty:(()=>{try{return(0,Qe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),sandbox:e.sandbox,budgetUsd:e.maxCost||0});v.start(),console.log(a.dim(" Type a prompt to start. /help for commands, /exit to quit, Ctrl+C to cancel."));let E="0.1.8";(async()=>{try{let M=await fetch("https://registry.npmjs.org/monkeyscode-cli/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!M.ok)return;let T=(await M.json()).version;if(!T)return;let O=E.split(".").map(Number),_=T.split(".").map(Number),w=!1;for(let k=0;k<3;k++){if((_[k]||0)>(O[k]||0)){w=!0;break}if((_[k]||0)<(O[k]||0))break}w&&(console.log(""),console.log(a.hex(Je.accent)(` \u2B06 Update available: ${a.dim(`v${E}`)} \u2192 ${a.bold(`v${T}`)}`)),console.log(a.dim(` Run ${a.bold("npm i -g monkeyscode-cli")} to update.`)))}catch{}})(),await c.fire("SessionStart",{workspace:e.workspace,data:{model:e.model,mode:e.mode}});let oe=["exit","quit","clear","model","mode","diff","undo","commit","files","cost","context","compact","permissions","doctor","fork","sessions","resume","continue","goal","subtask","sub","search","docs","help","init","memory","plan","ask","cloud","bug","feedback","vim","review","skill","skills","hooks","hook"],U=fm.createInterface({input:process.stdin,output:process.stdout,terminal:!0,prompt:(()=>{let M=H(n);return n.ansi?`
|
|
310
319
|
${a.hex("#6B8DD6")(M.prompt)} `:`
|
|
311
|
-
${M.prompt} `})(),historySize:200,completer:l(M=>{if(M.startsWith("/")){let
|
|
312
|
-
`).length;process.stdout.write(`\x1B[${
|
|
313
|
-
\u{1F914} ${
|
|
314
|
-
`);ht=null,
|
|
320
|
+
${M.prompt} `})(),historySize:200,completer:l(M=>{if(M.startsWith("/")){let N=M.slice(1).toLowerCase(),T=oe.filter(O=>O.startsWith(N)).map(O=>`/${O}`);return[T.length?T:oe.map(O=>`/${O}`),M]}if(M.startsWith("/context ")){let N=M.slice(9);try{let T=J.dirname(J.resolve(e.workspace,N)),O=J.basename(N);return[j.readdirSync(T).filter(k=>k.startsWith(O)).map(k=>`/context ${N.replace(O,"")}${k}`),M]}catch{return[[],M]}}return[[],M]},"completer")});new hr().wire(U);let ne=null,De=null,Jo=!1,ht=null,Zt=new kr({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),eo=null;try{let{MessageBroker:M}=await Promise.resolve().then(()=>(gn(),qr));t&&r.platformUrl&&(eo=new M(r.platformUrl,t,p))}catch{}let Es=l(async()=>{if(eo)try{let M=await eo.pollMessages();if(M&&M.length>0)for(let N of M)i.renderMessageCard({from:N.from||N.senderId||"unknown",content:N.content||N.message||"",timestamp:N.timestamp?new Date(N.timestamp):new Date})}catch{}},"pollAndRenderMessages"),Ft=l(async M=>{d||(d=u.create(e.workspace,e.model,e.mode)),u.addMessage(d,"user",M),D++,v.update({turn:D,busy:!0,activity:"thinking..."});let N=new xe({platformUrl:r.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:gm(e.mode),maxTurns:r.maxTurns,sandboxed:e.sandbox,webEnabled:r.webEnabled,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});ne=N;let T="";N.on("event",_=>{switch(_.type){case"streaming_chunk":T+=_.content,process.stdout.write(_.content);break;case"streaming_end":if(T.trim()){let k=T.split(`
|
|
321
|
+
`).length;process.stdout.write(`\x1B[${k}A\x1B[J`),console.log(Qn(T))}else console.log("");T="";break;case"tool_call_start":i.printToolCallStart(_.name,_.args),_.name==="file_read"&&_.args?.file_path&&g.add(String(_.args.file_path)),["file_edit","file_write","file_create"].includes(_.name)&&_.args?.file_path&&m.add(String(_.args.file_path));break;case"tool_call_result":i.printToolCallResult(_.name,_.result);break;case"ask_user":console.log(a.cyan(`
|
|
322
|
+
\u{1F914} ${_.question}`)),U.question(a.dim(" Answer: "),k=>{N.resolveUserInput(k)});break;case"todo_update":i.printTodoList(_.todos);break;case"run_complete":Qb(_.summary,i),h+=_.summary.tokensIn,y+=_.summary.tokensOut,S+=_.summary.tokensThinking||0,C=N.state.runId;for(let k of _.summary.filesModified)m.add(k);if(v.update({tokensIn:h,tokensOut:y,cost:Xs(e.model,h,y,S),turn:D,busy:!1,activity:""}),e.maxCost&&e.maxCost>0){let k=Xs(e.model,h,y,S),$=k/e.maxCost;$>=1?(console.log(""),console.log(a.red(` \u{1F6AB} Session budget exceeded ($${k.toFixed(2)}/$${e.maxCost.toFixed(2)}). Stopping.`)),console.log(a.dim(" Use --max-cost to increase the budget.")),console.log(""),x=!0):$>=.8&&console.log(a.yellow(` \u26A0\uFE0F 80% of session budget used ($${k.toFixed(2)}/$${e.maxCost.toFixed(2)})`))}let w=N.getCheckpoints();w.size>0&&pd(N.state.runId,M,e.workspace,w),d&&u.updateStats(d,_.summary.tokensIn+_.summary.tokensOut,0,_.summary.filesModified);break;case"context_compacted":i.printSuccess(`Context auto-compacted: ${_.elided} tool result${_.elided===1?"":"s"} summarized (${Math.round(_.savedTokens/1e3)}K tokens saved, now ${Math.round(_.contextUsed/_.contextWindow*100)}% full)`);break;case"run_error":i.printError(_.error);break}});let O=[];N.on("run_complete",_=>{_?.summary?.filesModified&&(O=_.summary.filesModified)});try{await N.run(M)}catch(_){i.printError(_ instanceof Error?_.message:String(_))}if(O.length>0&&eo)try{let{notifyAffectedSessions:_}=await Promise.resolve().then(()=>(lm(),cm));await _(eo,O,p)}catch{}ne=null},"executePrompt");s&&await Ft(s),await Es(),U.prompt(),U.on("line",async M=>{let N=M.trim();if(x){U.close();return}if(!ht&&(N==="<<EOF"||N.endsWith("<<EOF"))){let T=N.replace(/<<EOF$/,"").trim();ht=T?[T]:[],U.setPrompt(a.dim(" ... ")),U.prompt();return}if(ht!==null){if(N==="EOF"){let T=ht.join(`
|
|
323
|
+
`);ht=null,U.setPrompt(n.emoji?`
|
|
315
324
|
\u{1F435} > `:`
|
|
316
|
-
> `),
|
|
325
|
+
> `),T.trim()&&await Ft(T),U.prompt();return}ht.push(M),U.setPrompt(a.dim(" ... ")),U.prompt();return}if(N.endsWith("\\")){ht=[N.slice(0,-1)],U.setPrompt(a.dim(" ... ")),U.prompt();return}if(!N){U.prompt();return}if(N.startsWith("/")){let[T,...O]=N.slice(1).split(" "),_=O.join(" ");switch(T){case"exit":case"quit":case"q":c.fire("Stop",{workspace:e.workspace,data:{}}),v.stop(),U.close();return;case"clear":case"cls":console.clear();break;case"model":case"models":if(_)e.model=_,i.printSuccess(`Model changed to: ${_}`),v.update({model:_});else try{let{fetchModels:w}=await Promise.resolve().then(()=>(pm(),dm)),k=await w();if(k.length===0)console.log(a.yellow(" No models returned from the API."));else{let $=I(),F=Oe($),R=$.ansi,q=R?a.hex(Je.accent):$e=>$e,P=R?a.dim:$e=>$e,tt=R?a.green:$e=>$e;if($.unicode){console.log(""),console.log(q(` ${F.topLeft}${F.horizontal} Available Models ${F.horizontal.repeat(Math.max(0,32))}${F.topRight}`)),console.log(q(` ${F.vertical}${" ".repeat(52)}${F.vertical}`));let ot=` Current: ${a.bold(e.model)}`,Ts=ot.replace(/\x1b\[[0-9;]*m/g,""),Rs=Math.max(0,52-Ts.length);console.log(q(` ${F.vertical}`)+tt(ot)+" ".repeat(Rs)+q(F.vertical)),console.log(q(` ${F.teeRight}${F.horizontal.repeat(52)}${F.teeLeft}`));for(let vo of k){let fi=vo.id===e.model,Rg=fi?tt("\u25CF"):P("\u25CB"),Ag=((fi?a.bold(vo.name||vo.id):vo.name||vo.id)+(fi?" \u25C0":"")).padEnd(26),Pg=vo.contextWindow?P(`${Math.round(vo.contextWindow/1e3)}k`.padEnd(8)):"".padEnd(8),fl=` ${Rg} ${Ag}${Pg}`,Mg=fl.replace(/\x1b\[[0-9;]*m/g,""),Og=Math.max(0,52-Mg.length);console.log(q(` ${F.vertical}`)+`${fl}${" ".repeat(Og)}`+q(F.vertical))}console.log(q(` ${F.vertical}${" ".repeat(52)}${F.vertical}`));let Re=" Usage: /model <name>",Tg=Math.max(0,52-Re.length);console.log(q(` ${F.vertical}`)+P(`${Re}${" ".repeat(Tg)}`)+q(F.vertical)),console.log(q(` ${F.bottomLeft}${F.horizontal.repeat(52)}${F.bottomRight}`)),console.log("")}else{console.log(`
|
|
317
326
|
Current model: ${e.model}
|
|
318
|
-
`);for(let
|
|
327
|
+
`);for(let $e of k){let ot=$e.id===e.model?" <-- current":"";console.log(` ${$e.name||$e.id}${ot}`)}console.log(`
|
|
319
328
|
Usage: /model <name>
|
|
320
|
-
`)}}}catch(w){i.printError(`Could not fetch models: ${w.message||w}`)}break;case"mode":["plan","fast","thinking"].includes(
|
|
321
|
-
`).length;g.add(w),i.printSuccess(`Added ${
|
|
322
|
-
\u{1F50D} Reviewing ${w}...`)),await
|
|
329
|
+
`)}}}catch(w){i.printError(`Could not fetch models: ${w.message||w}`)}break;case"mode":["plan","fast","thinking"].includes(_)?(e.mode=_,i.printSuccess(`Mode changed to: ${_}`)):i.printError("Valid modes: plan, fast, thinking");break;case"diff":try{let w=(0,Qe.execSync)("git diff",{cwd:e.workspace,encoding:"utf8"});w.trim()?(console.log(""),console.log(w)):console.log(a.dim(" No uncommitted changes."))}catch{i.printError("Failed to run git diff (is this a git repository?)")}break;case"undo":{let w=md();if(w.length===0){i.printError("Nothing to undo \u2014 no checkpoints found.");break}let k=w[0];try{let $=fd(k.runId);i.printSuccess(`Reverted ${$.length} file(s):`);for(let F of $)console.log(` \u21A9 ${F}`)}catch($){i.printError($ instanceof Error?$.message:"Undo failed")}break}case"commit":{try{(0,Qe.execSync)("git add -A",{cwd:e.workspace,stdio:"pipe"});let w=_||`mc: agent changes (${m.size} files)`,$=(0,Qe.execSync)(`git commit -m "${w.replace(/"/g,'\\"')}"`,{cwd:e.workspace,encoding:"utf8",stdio:"pipe"}).match(/\[[\w-]+\s+([a-f0-9]+)\]/),F=$?$[1]:"???";i.printSuccess(`Committed: ${F} \u2014 ${w}`)}catch(w){i.printError(w instanceof Error?w.message:"Commit failed")}break}case"files":if(m.size===0&&g.size===0)console.log(a.dim(" No files accessed in this session."));else{if(console.log(""),m.size>0){console.log(` Files modified (${m.size}):`);for(let w of m)console.log(` \u270F\uFE0F ${J.relative(e.workspace,w)||w}`)}if(g.size>0){console.log(` Files read (${g.size}):`);for(let w of[...g].slice(0,20))console.log(` \u{1F4D6} ${J.relative(e.workspace,w)||w}`);g.size>20&&console.log(a.dim(` ... and ${g.size-20} more`))}console.log("")}break;case"cost":{let w=lr(e.model),k=w?h/1e6*w.costInputPerM:0,$=w?y/1e6*w.costOutputPerM:0,F=w?S/1e6*w.costOutputPerM:0,R=k+$+F;if(console.log(""),console.log(" \u{1F4B0} Session Cost"),console.log(` ${"\u2500".repeat(36)}`),console.log(` Model: ${w?.displayName||e.model}`),console.log(` Input: ${h.toLocaleString()} tokens ($${k.toFixed(2)})`),console.log(` Output: ${y.toLocaleString()} tokens ($${$.toFixed(2)})`),S>0&&console.log(` Thinking: ${S.toLocaleString()} tokens ($${F.toFixed(2)})`),console.log(` Total: $${R.toFixed(2)}`),e.maxCost&&e.maxCost>0){let q=Math.max(0,e.maxCost-R),P=Math.round((1-R/e.maxCost)*100);console.log(` Budget: $${e.maxCost.toFixed(2)} (${P}% remaining)`)}console.log(` Turns: ${D}`),console.log(` ${"\u2500".repeat(36)}`),console.log("");break}case"context":case"ctx":if(_){let w=J.resolve(e.workspace,_);try{let $=require("node:fs").readFileSync(w,"utf8").split(`
|
|
330
|
+
`).length;g.add(w),i.printSuccess(`Added ${_} to context (${$} lines). Mention it in your next prompt.`)}catch{i.printError(`File not found: ${_}`)}}else{let w=fr(e.model),k=ne?.getContextStats();if(console.log(""),console.log(" \u{1F4CA} Context Summary"),console.log(` ${"\u2500".repeat(40)}`),console.log(` Turns: ${D}`),console.log(` Tokens in: ${h.toLocaleString()}`),console.log(` Tokens out: ${y.toLocaleString()}`),console.log(` Files read: ${g.size}`),console.log(` Files edited: ${m.size}`),console.log(` Model: ${e.model}`),console.log(` Context window: ${(w/1e3).toFixed(0)}K tokens`),k){let $=k.pct,F=30,R=Math.round($/100*F),q=F-R,P=$>=80?a.red:$>=60?a.yellow:a.green;console.log(` Context used: ${P(`${$}%`)} ${P("\u2588".repeat(R))}${a.dim("\u2591".repeat(q))}`),console.log(` Messages: ${k.messageCount}`),console.log(` Auto-compact: ${$>=85?a.yellow("will trigger"):a.green("standby")}`)}console.log(` ${"\u2500".repeat(40)}`),console.log("")}break;case"compact":{if(!ne){console.log(a.dim(" No active conversation to compact. Run a prompt first."));break}let w=_.replace(/^["']|["']$/g,"").trim(),k=ne.getContextStats();if(!w&&k.pct<50){console.log(a.dim(` Context is only ${k.pct}% full \u2014 compaction not needed.`)),console.log(a.dim(' Use /compact "retain X" to force compaction with specific focus.'));break}if(w){i.printStatus(`Compacting with focus: "${w}"`);let $=ne.manualCompact(2);if($.elided>0){let F=ne.getContextStats(),R=Math.round($.savedTokens/1e3);i.printSuccess(`Compacted: ${$.elided} tool result${$.elided===1?"":"s"} summarized (${R}K tokens saved, ${k.pct}% \u2192 ${F.pct}%)`),console.log(a.dim(` Retained focus: "${w}"`))}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}else{let $=ne.manualCompact();if($.elided>0){let F=ne.getContextStats(),R=Math.round($.savedTokens/1e3);i.printSuccess(`Compacted: ${$.elided} tool result${$.elided===1?"":"s"} summarized (${R}K tokens saved, ${k.pct}% \u2192 ${F.pct}%)`)}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}break}case"doctor":await ln();break;case"permissions":{let w=_.split(" ")[0]?.toLowerCase()||"show",k=J.join(e.workspace,".monkeyscode","permissions.json");if(w==="edit"){let $=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!j.existsSync(k))console.log(a.dim(" No permissions.json. Run /init to generate one."));else try{(0,Qe.execSync)(`${$} "${k}"`,{stdio:"inherit"}),i.printSuccess("Permissions saved.")}catch{i.printError(`Failed to open editor: ${$}`)}}else if(w==="reset")j.existsSync(k)?(j.unlinkSync(k),i.printSuccess("Deleted permissions.json. Run /init to regenerate.")):console.log(a.dim(" No permissions.json to reset."));else{if(console.log(""),console.log(a.bold(" \u{1F512} Permissions")),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(` Mode: ${a.bold(e.permissionMode)}`),console.log(` Auto-approve: ${e.autoApprove?a.green("ON"):a.dim("off")}`),console.log(` Smart-approve: ${e.approveForMe?a.green("ON"):a.dim("off")}`),console.log(` Sandbox: ${e.sandbox?a.green("ON"):a.yellow("off")}`),e.allowedTools.length&&console.log(` Allowed tools: ${e.allowedTools.join(", ")}`),e.deniedTools.length&&console.log(` Denied tools: ${e.deniedTools.join(", ")}`),j.existsSync(k))try{let $=JSON.parse(j.readFileSync(k,"utf8"));console.log(""),console.log(a.dim(` \u{1F4C4} ${J.relative(e.workspace,k)}`)),$.allow?.length&&console.log(` Allow rules: ${$.allow.length} rules`),$.deny?.length&&console.log(` Deny rules: ${$.deny.length} rules`),$.cost?.max_per_run_usd&&console.log(` Cost limit: $${$.cost.max_per_run_usd}`),$.sandbox?.enabled&&console.log(` Sandbox paths: ${$.sandbox.writable_paths?.join(", ")||"all"}`)}catch{}else console.log(a.dim(" No project permissions.json. Run /init to generate."));console.log("")}break}case"fork":{let w=_.trim()||"Continue working on the current task in the background";await Zt.spawn(w);break}case"sessions":{let w=u.list();if(w.length===0)console.log(a.dim(" No saved sessions."));else{console.log(""),console.log(a.bold(" Recent Sessions:"));for(let k of w.slice(0,10)){let $=a.hex("#6B8DD6")(k.id.substring(0,8)),F=ew(k.lastActive);console.log(` ${$} ${k.preview.substring(0,50).padEnd(52)} ${a.dim(F)}`)}console.log("")}break}case"resume":case"continue":{let w=_.trim(),k=w?u.load(w):u.loadLatest(e.workspace);if(!k)i.printError(w?`Session "${w}" not found.`:"No sessions to resume.");else{d=k,D=k.turnCount;for(let $ of k.stats.filesChanged)m.add($);i.printSuccess(`Resumed session ${k.id.substring(0,8)} (${k.turnCount} turns, ${k.stats.tokensUsed.toLocaleString()} tokens)`)}break}case"goal":{let w=_.trim().replace(/^["']|["']$/g,"");if(!w&&w!=="status"&&w!=="cancel"){i.printError('Usage: /goal "implement feature X with tests" | /goal status | /goal cancel');break}if(w==="status"){if(De){let k=De.getProgress();console.log(a.dim(` Goal: iteration ${k.iteration}/${k.maxIterations}, ${k.totalTokens.toLocaleString()} tokens, $${k.totalCost.toFixed(4)}`))}else console.log(a.dim(" No active goal."));break}if(w==="cancel"){De?(De.cancel(),i.printSuccess("Goal cancelled.")):console.log(a.dim(" No active goal."));break}De=new wr({goal:w,workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),await De.run(),De=null;break}case"subtask":case"sub":{let w=_.trim();if(w==="status")Zt.printStatus();else if(w.startsWith("cancel "))Zt.cancel(w.slice(7).trim());else if(w){let k=w.replace(/^["']|["']$/g,"");await Zt.spawn(k)}else i.printError('Usage: /subtask "task description" | /subtask status | /subtask cancel <id>');break}case"delegate":case"del":{let w=_.trim();if(!w){i.printError('Usage: /delegate "task 1" "task 2" ["task 3" ...]'),console.log(a.dim(" Spawns parallel agents for each task, merges results."));break}let k=w.match(/"([^"]+)"/g)?.map(R=>R.replace(/"/g,""))||[w];if(k.length<1){i.printError("Provide at least one task in quotes.");break}console.log(a.cyan(` \u26A1 Delegating ${k.length} task(s) to parallel agents...`));for(let R=0;R<k.length;R++)console.log(a.dim(` ${R+1}. "${k[R]}"`));console.log("");let $=new xr({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id});$.on("orchestrator",R=>{switch(R.type){case"task.started":console.log(a.cyan(` \u25B6 Started: ${R.taskId}`));break;case"task.completed":console.log(a.green(` \u2705 Completed: ${R.taskId}`));break;case"task.failed":console.log(a.red(` \u274C Failed: ${R.taskId} \u2014 ${R.data?.error||"unknown"}`));break;case"conflict.detected":console.log(a.yellow(` \u26A0\uFE0F Conflict: ${R.data?.file}`));break}});let F=k.map((R,q)=>({id:`delegate-${q+1}`,prompt:R,workspace:e.workspace,parentId:"repl",dependencies:[],status:"pending"}));try{let R=await $.fanOut(F),q=await $.fanIn(R);console.log(""),console.log(a.bold(" Delegation Results")),console.log(` ${"\u2500".repeat(50)}`),console.log(` Tasks: ${R.length}`),console.log(` Succeeded: ${a.green(String(R.filter(P=>P.status==="complete").length))}`),console.log(` Failed: ${a.red(String(R.filter(P=>P.status==="failed").length))}`),console.log(` Files: ${q.mergedFiles.length}`),console.log(` Conflicts: ${q.conflicts.length}`),console.log(` Tokens: ${q.totalTokens.toLocaleString()}`),console.log(` Cost: $${q.totalCost.toFixed(4)}`),console.log(` Duration: ${(q.totalDurationMs/1e3).toFixed(1)}s`),console.log(` ${"\u2500".repeat(50)}`),console.log("")}catch(R){i.printError(`Delegation failed: ${R.message}`)}break}case"search":_?await Ft(`Search the web for: ${_.replace(/^["']|["']$/g,"")}`):console.log(a.dim(' Usage: /search "your query" \u2014 or just type your question and the agent will search if needed.'));break;case"docs":_?await Ft(`Look up documentation for: ${_}`):console.log(a.dim(" Usage: /docs express routing \u2014 looks up documentation for a topic."));break;case"review":{let w="all changes in this session",k="git diff";_==="staged"?(k="git diff --cached",w="staged changes"):_&&(k=`git diff -- ${_}`,w=`changes in ${_}`);try{let $=(0,Qe.execSync)(k,{cwd:e.workspace,encoding:"utf8"});$.trim()?(console.log(a.bold(`
|
|
331
|
+
\u{1F50D} Reviewing ${w}...`)),await Ft(`Review the following code changes for bugs, security issues, and code quality. Provide severity ratings (HIGH/MEDIUM/LOW) for each finding.
|
|
323
332
|
|
|
324
333
|
\`\`\`diff
|
|
325
|
-
${
|
|
326
|
-
\`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let w=
|
|
327
|
-
`),"utf8"),
|
|
328
|
-
`,"utf8"),
|
|
329
|
-
`),"utf8"),
|
|
330
|
-
`),"utf8");try{
|
|
331
|
-
`;
|
|
332
|
-
- `+
|
|
333
|
-
`,"utf8"),i.printSuccess(`Added rule: ${
|
|
334
|
-
`))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(
|
|
335
|
-
`),"utf8"),i.printSuccess(`Created skill: ${
|
|
336
|
-
`),"utf8");try{
|
|
334
|
+
${$}
|
|
335
|
+
\`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let w=J.join(e.workspace,".monkeyscode"),k=J.join(w,"rules.md"),$=J.join(w,"permissions.json"),F=J.join(w,"skills"),R=J.join(w,"hooks");j.mkdirSync(w,{recursive:!0});let q=[];if(!j.existsSync(k)){let P=["# Project Conventions",""],tt=J.join(e.workspace,"package.json"),$e=J.join(e.workspace,"Cargo.toml"),ot=J.join(e.workspace,"pyproject.toml"),Ts=J.join(e.workspace,"tsconfig.json"),Rs=J.join(e.workspace,"go.mod");if(j.existsSync(tt))try{let Re=JSON.parse(j.readFileSync(tt,"utf8"));P.push(`## Language: ${Re.type==="module"?"TypeScript/ESM":"JavaScript/CJS"}`),Re.scripts?.test&&P.push(`- Test command: \`${Re.scripts.test}\``),Re.scripts?.lint&&P.push(`- Lint command: \`${Re.scripts.lint}\``),Re.scripts?.build&&P.push(`- Build command: \`${Re.scripts.build}\``),Re.dependencies?.react&&P.push("- Framework: React"),Re.dependencies?.next&&P.push("- Framework: Next.js"),Re.dependencies?.express&&P.push("- Server: Express"),P.push("")}catch{}j.existsSync(Ts)&&(P.push("## TypeScript"),P.push("- Use strict TypeScript with explicit types"),P.push("- Prefer `interface` over `type` for object shapes"),P.push("")),j.existsSync($e)&&(P.push("## Language: Rust"),P.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),P.push("")),j.existsSync(ot)&&(P.push("## Language: Python"),P.push("- Follow PEP 8 conventions"),P.push("")),j.existsSync(Rs)&&(P.push("## Language: Go"),P.push("- Follow Go conventions (gofmt, error wrapping)"),P.push("")),P.push("## Style"),P.push("- Keep functions small and focused"),P.push("- Write clear error messages"),P.push("- Add JSDoc/docstrings for public APIs"),P.push(""),P.push("## Testing"),P.push("- Write tests for all new functionality"),P.push("- Use descriptive test names"),P.push(""),j.writeFileSync(k,P.join(`
|
|
336
|
+
`),"utf8"),q.push("rules.md")}if(!j.existsSync($)){let P="",tt=J.join(e.workspace,"package.json");if(j.existsSync(tt))try{JSON.parse(j.readFileSync(tt,"utf8")).scripts?.test&&(P="npm test")}catch{}!P&&j.existsSync(J.join(e.workspace,"Cargo.toml"))&&(P="cargo test"),!P&&j.existsSync(J.join(e.workspace,"go.mod"))&&(P="go test ./..."),!P&&j.existsSync(J.join(e.workspace,"pyproject.toml"))&&(P="pytest");let $e={mode:"default",allow:["Bash(git status*)","Bash(git diff*)","Bash(git log*)"],deny:["Bash(rm -rf /)","Bash(sudo *)","/Bash\\(curl.*\\|.*sh\\)/"],smartApprove:P?[`Bash(${P}*)`]:[],sandbox:{enabled:!0,writable_paths:["src/","tests/","test/","docs/","lib/"],blocked_commands:["rm -rf /","sudo","curl | sh","chmod 777"]},cost:{max_per_run_usd:10,warn_at_usd:5}};j.writeFileSync($,JSON.stringify($e,null,2)+`
|
|
337
|
+
`,"utf8"),q.push("permissions.json")}if(j.existsSync(F)||(j.mkdirSync(F,{recursive:!0}),j.writeFileSync(J.join(F,"README.md"),["# Skills","","Place custom skills here. Each skill is a directory with a `skill.md` file.","","## Quick Start","","```bash","/skill create my-skill","```","","## Structure","","```","skills/","\u2514\u2500\u2500 my-skill/"," \u2514\u2500\u2500 skill.md # YAML frontmatter + markdown instructions","```",""].join(`
|
|
338
|
+
`),"utf8"),q.push("skills/")),!j.existsSync(R)){j.mkdirSync(R,{recursive:!0});let P=J.join(R,"pre-write-lint.sh.example");j.writeFileSync(P,["#!/bin/bash","# Example PreToolUse hook: lint before file writes.","# Remove .example extension to enable.","#","# Env vars: MC_TOOL_NAME, MC_TOOL_ARGS (JSON), MC_WORKSPACE, MC_SESSION_ID","# Exit 0=allow, 1=deny, 2=deny+message on stderr","",'if [[ "$MC_TOOL_NAME" == "edit_file" || "$MC_TOOL_NAME" == "create_file" ]]; then',` FILE=$(echo "$MC_TOOL_ARGS" | jq -r '.path // .file_path // empty')`,' if [[ "$FILE" == *.ts && -f "$FILE" ]]; then',' npx eslint "$FILE" --quiet 2>/dev/null || true'," fi","fi","","exit 0",""].join(`
|
|
339
|
+
`),"utf8");try{j.chmodSync(P,493)}catch{}q.push("hooks/")}q.length>0?(i.printSuccess(`Initialized .monkeyscode/ with: ${q.join(", ")}`),console.log(a.dim(" Edit with: /memory, /permissions, /skill"))):i.printWarning("Project already initialized. Use /memory, /permissions, /skill to manage.");break}case"memory":{let w=J.join(e.workspace,".monkeyscode","rules.md"),k=_.split(" ")[0]?.toLowerCase(),$=_.slice(k?.length||0).trim();if(k==="add"&&$){let F=$.replace(/^["']|["']$/g,"");j.mkdirSync(J.dirname(w),{recursive:!0});let R=j.existsSync(w)?j.readFileSync(w,"utf8"):`# Project Conventions
|
|
340
|
+
`;j.writeFileSync(w,R.trimEnd()+`
|
|
341
|
+
- `+F+`
|
|
342
|
+
`,"utf8"),i.printSuccess(`Added rule: ${F}`)}else if(k==="show"||!k)if(j.existsSync(w)){let F=j.readFileSync(w,"utf8");console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules")),console.log(a.dim(` ${w}`)),console.log(a.dim(" "+"\u2500".repeat(40)));for(let R of F.split(`
|
|
343
|
+
`))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(k==="edit"){let F=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!j.existsSync(w))console.log(a.dim(" No rules file. Run /init first."));else try{(0,Qe.execSync)(`${F} "${w}"`,{stdio:"inherit"}),i.printSuccess("Rules file saved.")}catch{i.printError(`Failed to open editor: ${F}`)}}else console.log(a.dim(' Usage: /memory show | /memory add "rule" | /memory edit'));break}case"skill":case"skills":{let w=_.split(" ")[0]?.toLowerCase(),k=_.slice(w?.length||0).trim();if(w==="create"&&k){let $=k.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),F=J.join(e.workspace,".monkeyscode","skills",$),R=J.join(F,"skill.md");j.existsSync(R)?console.log(a.yellow(` Skill "${$}" already exists.`)):(j.mkdirSync(F,{recursive:!0}),j.writeFileSync(R,["---",`name: ${k}`,`description: Custom skill for ${k}`,"trigger: always","priority: 50","enabled: true","---","",`# ${k}`,"","Add your skill instructions here. These will be injected into the agent's context.",""].join(`
|
|
344
|
+
`),"utf8"),i.printSuccess(`Created skill: ${J.relative(e.workspace,R)}`),console.log(a.dim(" Edit the file to add your instructions.")))}else try{let{listAllSkills:$}=await Promise.resolve().then(()=>(pr(),Pa)),F=$(e.workspace);if(F.length===0)console.log(a.dim(" No skills found.")),console.log(a.dim(" Create one with: /skill create <name>")),console.log(a.dim(" Skills directory: .monkeyscode/skills/<name>/skill.md"));else{console.log(""),console.log(a.bold(" \u{1F9E0} Skills")),console.log(a.dim(" "+"\u2500".repeat(50)));for(let R of F){let q=R.enabled?a.green("\u25CF"):a.dim("\u25CB"),P=R.source==="project"?a.cyan("proj"):a.dim("glob");console.log(` ${q} ${a.bold(R.name.padEnd(20))} ${P} P:${R.priority} ${a.dim(R.description.slice(0,40))}`)}console.log("")}}catch($){i.printError(`Failed to list skills: ${$ instanceof Error?$.message:$}`)}break}case"hooks":case"hook":{let w=_.split(" ")[0]?.toLowerCase(),k=_.slice(w?.length||0).trim();if(w==="create"&&k){let $=k.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),F=J.join(e.workspace,".monkeyscode","hooks",`${$}.sh`);if(j.existsSync(F))console.log(a.yellow(` Hook "${$}" already exists.`));else{j.mkdirSync(J.dirname(F),{recursive:!0}),j.writeFileSync(F,["#!/bin/bash",`# Hook: ${k}`,"#","# Env vars: MC_TOOL_NAME, MC_TOOL_ARGS (JSON), MC_WORKSPACE, MC_SESSION_ID","# Exit 0=allow, 1=deny, 2=deny+message on stderr","","# Add your hook logic here","","exit 0",""].join(`
|
|
345
|
+
`),"utf8");try{j.chmodSync(F,493)}catch{}i.printSuccess(`Created hook: ${J.relative(e.workspace,F)}`)}}else{let $=c.getHooks();if($.length===0)console.log(a.dim(" No active hooks.")),console.log(a.dim(" Create one with: /hooks create <name>")),console.log(a.dim(" Hooks directory: .monkeyscode/hooks/"));else{console.log(""),console.log(a.bold(" \u{1FA9D} Active Hooks")),console.log(a.dim(" "+"\u2500".repeat(50)));for(let F of $){let R=a.cyan(F.event||"PreToolUse"),q=a.bold(F.name||F.path||"hook");console.log(` ${R.padEnd(20)} ${q}`)}console.log("")}}break}case"plan":e.mode="plan",i.printSuccess("Switched to plan mode \u2014 agent will research and propose without editing.");break;case"ask":e.mode="plan",i.printSuccess("Switched to ask mode \u2014 read-only Q&A about the codebase (no edits, no commands).");break;case"cloud":{console.log(a.dim(" \u2601\uFE0F Submitting current task to cloud..."));try{let{submitBackgroundJob:w}=await Promise.resolve().then(()=>(un(),Sc)),k=e.prompt||"(continue session)",$=ne?.getConversationHistory?.()||[];await w({prompt:k.substring(0,2e3),workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:!0,autoCommit:!0,autoPR:!1,maxCost:e.maxCost,timeout:e.timeout,conversationHistory:$.length>0?$:void 0})}catch(w){console.error(a.red(` \u274C Cloud submission failed: ${w instanceof Error?w.message:w}`))}break}case"message":{let w=_.match(/^(\S+)\s+"?([^"]+)"?$/);if(!w){console.log(a.yellow(' Usage: /message <session-id> "your message"'));break}try{let{MessageBroker:k}=await Promise.resolve().then(()=>(gn(),qr)),$=(await Promise.resolve().then(()=>(Q(),Se))).loadSettings(),F=(await Promise.resolve().then(()=>(ee(),ge))).loadAuth(),q=await new k($.platformUrl,F?.access_token||"",p).sendMessage(w[1],w[2]);q.success?console.log(a.green(` \u{1F4E8} Message sent to ${w[1]}`)):console.error(a.red(` \u274C Send failed: ${q.error}`))}catch(k){console.error(a.red(` \u274C Messaging error: ${k instanceof Error?k.message:k}`))}break}case"broadcast":{let w=_.replace(/^"/,"").replace(/"$/,"").trim();if(!w){console.log(a.yellow(' Usage: /broadcast "your message to all sessions"'));break}try{let{MessageBroker:k}=await Promise.resolve().then(()=>(gn(),qr)),$=(await Promise.resolve().then(()=>(Q(),Se))).loadSettings(),F=(await Promise.resolve().then(()=>(ee(),ge))).loadAuth(),q=await new k($.platformUrl,F?.access_token||"",p).broadcast(w);q.success?console.log(a.green(" \u{1F4E2} Broadcast sent to all active sessions")):console.error(a.red(` \u274C Broadcast failed: ${q.error}`))}catch(k){console.error(a.red(` \u274C Messaging error: ${k instanceof Error?k.message:k}`))}break}case"bug":case"feedback":{let w=process.platform,k=process.version,$=ne?.getContextStats();console.log(""),console.log(a.bold(" \u{1F41B} Bug Report Context")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Platform: ${w} (${process.arch})`),console.log(` Node: ${k}`),console.log(` Model: ${e.model}`),console.log(` Mode: ${e.mode}`),console.log(` Turns: ${D}`),console.log(` Tokens: ${(h+y).toLocaleString()}`),$&&console.log(` Context: ${$.pct}% (${$.messageCount} messages)`),console.log(` Session: ${d?.id??"none"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.dim(" Copy the above and paste into: https://github.com/monkeyscloud/monkeyscode/issues/new")),console.log("");break}case"vim":{Jo=!Jo,Jo?(console.log(""),i.printSuccess("Vim mode enabled (lightweight)"),console.log(a.dim(" The prompt now shows [N] normal / [I] insert indicator.")),console.log(a.dim(" Note: Full vim keybindings require a dedicated input library.")),console.log(a.dim(" For now, this is a visual indicator. Use Escape for normal mode concept.")),U.setPrompt(n.emoji?`
|
|
337
346
|
\u{1F435} [I]> `:`
|
|
338
|
-
[I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),
|
|
347
|
+
[I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),U.setPrompt(n.emoji?`
|
|
339
348
|
\u{1F435} > `:`
|
|
340
|
-
> `));break}case"help":case"h":case"?":Zb();break;case"logout":fa(),i.printSuccess("Logged out."),process.exit(0);break;default:i.printError(`Unknown command: /${
|
|
341
|
-
Cancelling current run...`),
|
|
342
|
-
`),process.exit(4)),t||(process.stderr.write("Error: Not authenticated. Run `mc auth login` or set MONKEYSCODE_API_KEY.\n"),process.exit(3));let m=
|
|
343
|
-
`);let
|
|
344
|
-
[headless] Timeout after ${
|
|
345
|
-
`)},
|
|
349
|
+
> `));break}case"help":case"h":case"?":Zb();break;case"logout":fa(),i.printSuccess("Logged out."),process.exit(0);break;default:i.printError(`Unknown command: /${T}. Type /help for available commands.`)}U.prompt();return}await Ft(N),await Es(),U.prompt()});let Fs=l(()=>{let M=Date.now()-f,N=Math.floor(M/6e4),T=Math.floor(M%6e4/1e3),O=N>0?`${N}m ${T}s`:`${T}s`;if(console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(" \u{1F4CA} Session Summary")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Duration: ${O}`)),console.log(a.dim(` Turns: ${D}`)),console.log(a.dim(` Tokens: ${(h+y).toLocaleString()}`)),m.size>0){console.log(a.dim(` Files changed: ${m.size}`));for(let _ of m)console.log(a.dim(` \u270F\uFE0F ${J.relative(e.workspace,_)||_}`))}d&&console.log(a.dim(" Resume: mc --continue")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log("")},"printExitSummary");U.on("close",()=>{c.fire("Stop",{workspace:e.workspace,data:{}}),Fs(),process.exit(0)}),U.on("SIGINT",()=>{ne?(console.log(`
|
|
350
|
+
Cancelling current run...`),ne.cancel()):(c.fire("Stop",{workspace:e.workspace,data:{}}),U.close())}),await new Promise(M=>{U.on("close",M)})}l(mm,"runInteractive");async function Kb(s,e,t,o){s||(process.stderr.write(`Error: No prompt provided. Use -p "your prompt" or pipe via stdin.
|
|
351
|
+
`),process.exit(4)),t||(process.stderr.write("Error: Not authenticated. Run `mc auth login` or set MONKEYSCODE_API_KEY.\n"),process.exit(3));let m=K(),g=Date.now(),h=`headless-${Date.now().toString(36)}`,y="",S=!1,D=!1,C=e.output,x=Up(C,{workspace:e.workspace}),v=Wp(e.model,h),E=[],oe=[],U=0,pe=0,ne=0,De=0,Jo=process.env.CI==="true"||process.env.CI==="1"||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI;Jo&&!e.sandbox&&e.permissionMode!=="bypassPermissions"&&process.stderr.write(`[headless] CI environment detected \u2014 sandbox=auto
|
|
352
|
+
`);let ht=new To(e.workspace,{enabled:!0,timeoutMs:1e4});await ht.fire("HeadlessStart",{workspace:e.workspace,data:{prompt:s,model:e.model}});let Zt=e.timeout||3e5,eo=setTimeout(()=>{D=!0,process.stderr.write(`
|
|
353
|
+
[headless] Timeout after ${Zt}ms. Stopping gracefully.
|
|
354
|
+
`)},Zt),Es=l(()=>{S=!0,process.stderr.write(`
|
|
346
355
|
[headless] SIGINT received. Stopping.
|
|
347
|
-
`)},"sigintHandler");process.on("SIGINT",
|
|
348
|
-
`).filter(Boolean);for(let
|
|
349
|
-
`)}break;case"tool_call_start":if(
|
|
356
|
+
`)},"sigintHandler");process.on("SIGINT",Es);let Ft=await import("node:crypto"),Fs=new Map;try{let T=(0,Qe.execSync)("git ls-files -m",{cwd:e.workspace,encoding:"utf8"}).trim().split(`
|
|
357
|
+
`).filter(Boolean);for(let O of T)try{let _=j.readFileSync(J.join(e.workspace,O));Fs.set(O,Ft.createHash("sha256").update(_).digest("hex"))}catch{}}catch{}let M=new xe({platformUrl:m.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:gm(e.mode),maxTurns:m.maxTurns,sandboxed:e.sandbox||Jo,webEnabled:m.webEnabled&&!e.offline,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});M.on("event",T=>{switch(T.type){case"streaming_chunk":if(y+=T.content,C==="stream"&&process.stdout.write(T.content),C==="jsonl"&&x.formatEvent){let O=x.formatEvent({type:"chunk",timestamp:Date.now(),data:{content:T.content}});O&&process.stdout.write(O+`
|
|
358
|
+
`)}break;case"tool_call_start":if(U=Date.now(),e.mode==="plan"&&["file_edit","file_write","file_create","bash","file_delete"].includes(T.name)){process.stderr.write(`[headless] Plan mode: blocked write tool "${T.name}"
|
|
350
359
|
`);break}if(process.stderr.write(`[tool] ${T.name}(${JSON.stringify(T.args).substring(0,100)})
|
|
351
|
-
`),["file_edit","file_write","file_create"].includes(T.name)&&T.args?.file_path&&
|
|
352
|
-
`)}break;case"tool_call_result":if(
|
|
360
|
+
`),["file_edit","file_write","file_create"].includes(T.name)&&T.args?.file_path&&oe.push({path:String(T.args.file_path),action:T.name==="file_create"?"created":"modified",linesAdded:0,linesRemoved:0}),C==="jsonl"&&x.formatEvent){let O=x.formatEvent({type:"tool_start",timestamp:Date.now(),data:{tool:T.name,args:T.args}});O&&process.stdout.write(O+`
|
|
361
|
+
`)}break;case"tool_call_result":if(E.push({tool:T.name,args:{},duration:Date.now()-U,result:typeof T.result=="string"?T.result.substring(0,200):void 0}),C==="jsonl"&&x.formatEvent){let O=x.formatEvent({type:"tool_result",timestamp:Date.now(),data:{tool:T.name,duration:Date.now()-U,result:typeof T.result=="string"?T.result.substring(0,200):""}});O&&process.stdout.write(O+`
|
|
353
362
|
`)}break;case"ask_user":process.stderr.write(`[headless] Input prompt skipped (headless mode): ${T.question}
|
|
354
|
-
`),
|
|
363
|
+
`),M.resolveUserInput("");break;case"run_complete":pe+=T.summary.tokensIn,ne+=T.summary.tokensOut,De+=T.summary.tokensThinking||0;for(let O of T.summary.filesModified)oe.find(w=>w.path===O)||oe.push({path:O,action:"modified",linesAdded:0,linesRemoved:0});process.stderr.write(`[headless] Run complete: ${T.summary.filesModified.length} files, ${T.summary.tokensIn+T.summary.tokensOut} tokens
|
|
355
364
|
`);break;case"run_error":if(process.stderr.write(`[headless] Error: ${T.message||"unknown"}
|
|
356
|
-
`),
|
|
357
|
-
`)}break}});let
|
|
358
|
-
`)[0]?.substring(0,200)||"Task completed.")
|
|
359
|
-
`)
|
|
360
|
-
`);else{let T=
|
|
361
|
-
`)}await Do.fire("HeadlessStop",{workspace:e.workspace,data:{success:$.success,exitCode:X,duration:$.duration,filesChanged:j.length}}),process.removeListener("SIGINT",Tt),process.exit(X)}l(Kb,"runHeadless");async function Yb(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(an(),Sc));await t({prompt:s,workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:e.autoBranch??!0,autoCommit:e.autoCommit??!0,autoPR:e.autoPR??!1,maxCost:e.maxCost,timeout:e.timeout})}l(Yb,"runBackground");async function Xb(){return new Promise(s=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{s(e.trim())})})}l(Xb,"readStdin");function Qb(s,e){console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Turns: ${s.turns} \xB7 Tokens: ${s.tokensIn} in / ${s.tokensOut} out`)),s.tokensCached>0&&console.log(a.dim(` Cached: ${s.tokensCached}`)),s.filesModified.length>0&&console.log(a.dim(` Files modified: ${s.filesModified.length}`));let t=(s.duration/1e3).toFixed(1);console.log(a.dim(` Duration: ${t}s`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(Qb,"printRunSummary");function Zb(){let s=O(),e=W(s),t=a.hex("#6B8DD6"),o=a.dim,n=a.bold,r=l((i,c)=>{let u=i.padEnd(30);return` ${t(u)} ${o(c)}`},"cmd");if(s.unicode){let i={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",tr2:"\u251C",tl2:"\u2524"},c=Math.min(62,s.columns-4),u=` ${e.tool} MonkeysCode Commands `,d=Math.max(0,c-u.length-2);console.log(""),console.log(t(` ${i.tl}${i.h}${u}${i.h.repeat(d)}${i.tr}`)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.message} Chat`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/model <name>","Switch model")+t(i.v)),console.log(t(` ${i.v}`)+r("/mode <plan|fast>","Switch mode")+t(i.v)),console.log(t(` ${i.v}`)+r("/compact","Compact context")+t(i.v)),console.log(t(` ${i.v}`)+r('/search "query"',"Web search")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.folder} Project`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/init","Initialize .monkeyscode/")+t(i.v)),console.log(t(` ${i.v}`)+r('/memory add "rule"',"Add convention")+t(i.v)),console.log(t(` ${i.v}`)+r("/permissions","Show/edit permissions")+t(i.v)),console.log(t(` ${i.v}`)+r("/skill","List/create skills")+t(i.v)),console.log(t(` ${i.v}`)+r("/hooks","List/create hooks")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.info} Stats`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/cost","Token usage & cost")+t(i.v)),console.log(t(` ${i.v}`)+r("/context [file]","Context window usage")+t(i.v)),console.log(t(` ${i.v}`)+r("/diff","Show uncommitted changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/files","List modified files")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.rocket} Actions`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/commit [msg]","Auto-commit changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/undo","Undo last file changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/review","Run code review")+t(i.v)),console.log(t(` ${i.v}`)+r('/goal "target"',"Autonomous goal loop")+t(i.v)),console.log(t(` ${i.v}`)+r('/fork ["task"]',"Fork to background")+t(i.v)),console.log(t(` ${i.v}`)+r('/delegate "t1" "t2"',"Parallel agents")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.lock} Session`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/sessions","List saved sessions")+t(i.v)),console.log(t(` ${i.v}`)+r("/resume [id]","Resume a session")+t(i.v)),console.log(t(` ${i.v}`)+r("/exit","Exit the REPL")+t(i.v)),console.log(t(` ${i.v}`)+r("/doctor","System health check")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+o(" Press / + Tab for autocomplete").padEnd(c+12)+t(i.v)),console.log(t(` ${i.bl}${i.h.repeat(c)}${i.br}`)),console.log("")}else console.log(""),console.log(n(" Slash Commands")),console.log(o(" Tab to auto-complete")),console.log(""),console.log(t(" Chat")),console.log(r("/model <name>","Switch model")),console.log(r("/mode <plan|fast>","Switch mode")),console.log(r("/compact","Compact context")),console.log(""),console.log(t(" Project")),console.log(r("/init","Initialize .monkeyscode/")),console.log(r('/memory add "rule"',"Add convention")),console.log(r("/permissions","Show/edit permissions")),console.log(r("/skill","List/create skills")),console.log(r("/hooks","List/create hooks")),console.log(""),console.log(t(" Stats")),console.log(r("/cost","Token usage & cost")),console.log(r("/context [file]","Context window usage")),console.log(r("/diff","Show uncommitted changes")),console.log(r("/files","List modified files")),console.log(""),console.log(t(" Actions")),console.log(r("/commit [msg]","Auto-commit changes")),console.log(r("/undo","Undo last file changes")),console.log(r("/review","Run code review")),console.log(r('/goal "target"',"Autonomous goal loop")),console.log(r('/fork ["task"]',"Fork to background")),console.log(""),console.log(t(" Session")),console.log(r("/sessions","List saved sessions")),console.log(r("/resume [id]","Resume a session")),console.log(r("/exit","Exit the REPL")),console.log(r("/doctor","System health check")),console.log("")}l(Zb,"printSlashHelp");function ew(s){let e=Date.now()-s,t=Math.floor(e/6e4),o=Math.floor(e/36e5),n=Math.floor(e/864e5);return t<1?"just now":t<60?`${t}m ago`:o<24?`${o}h ago`:`${n}d ago`}l(ew,"formatAge");te();var qr=y(require("node:readline"),1);U();Ce();var Mc=class{static{l(this,"AgentsDashboard")}daemon;caps;icons;box;agents=[];selectedIndex=0;running=!1;refreshInterval=null;constructor(e){this.daemon=e,this.caps=O(),this.icons=W(this.caps),this.box=Me(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(qr.emitKeypressEvents(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume()),process.stdin.on("keypress",(e,t)=>{this.running&&this.handleKeypress(e,t)}),this.daemon.on("event",()=>{this.fetchAgents().then(()=>this.render())}),this.refreshInterval=setInterval(async()=>{await this.fetchAgents(),this.render()},5e3),this.render(),await new Promise(e=>{let t=setInterval(()=>{this.running||(clearInterval(t),e())},100)})}async list(){await this.fetchAgents();let e=this.caps.ansi;if(this.agents.length===0){console.log(" No active agents.");return}let t=`${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.bold(` ${t}`):` ${t}`),console.log(` ${"\u2500".repeat(Math.min(this.caps.columns-4,100))}`);for(let o of this.agents){let n=this.formatAgentLine(o,!1);console.log(` ${n}`)}}async fetchAgents(){try{this.agents=await this.daemon.call("agents.list",{})}catch{this.agents=[]}}render(){let e=this.caps.ansi,t=Math.min(this.caps.columns,120);console.clear();let o=`${this.icons.rocket} MonkeysCode Agents Dashboard`;if(console.log(e?a.bold(o):o),console.log(e?a.dim(` ${this.agents.length} agent(s) active`):` ${this.agents.length} agent(s) active`),console.log(`${this.box.separator.repeat(t)}`),this.agents.length===0)console.log(""),console.log(" No active agents."),console.log(""),console.log(e?a.dim(' Start one with: mc "your prompt"'):' Start one with: mc "your prompt"'),console.log("");else{let r=` ${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.dim(r):r),console.log(` ${"\u2500".repeat(t-4)}`);for(let i=0;i<this.agents.length;i++){let c=i===this.selectedIndex,u=this.formatAgentLine(this.agents[i],c);console.log(c&&e?a.bgHex("#1a1a2e").white(`\u25B6 ${u}`):` ${u}`)}}console.log(""),console.log(`${this.box.separator.repeat(t)}`);let n=e?` ${a.cyan("[j/k]")} Nav ${a.cyan("[Enter]")} Focus ${a.cyan("[m]")} Message ${a.cyan("[c]")} Cancel ${a.cyan("[l]")} Logs ${a.cyan("[r]")} Retry ${a.cyan("[q]")} Quit`:" [j/k] Nav [Enter] Focus [m] Message [c] Cancel [l] Logs [r] Retry [q] Quit";console.log(n)}formatAgentLine(e,t){let o=this.caps.ansi,n=e.id.slice(0,12).padEnd(14),r=e.type.padEnd(14),i=this.formatStatus(e.status).padEnd(12),c=`"${e.task.slice(0,33)}"`.padEnd(35),u=this.formatDuration(e.duration).padEnd(10),d=this.formatTokens(e.tokens),p=`${n} ${r} ${i} ${c} ${u} ${d}`;if(!o)return p;let f={active:a.green,running:a.green,idle:a.yellow,queued:a.blue,done:a.dim,failed:a.red,cancelled:a.dim}[e.status]||a.white;return`${a.white(n)} ${a.dim(r)} ${f(i)} ${a.white(c)} ${a.dim(u)} ${a.dim(d)}`}formatStatus(e){return{active:this.caps.emoji?"\u{1F504} Active":"[ACTIVE]",running:this.caps.emoji?"\u{1F504} Running":"[RUNNING]",idle:this.caps.emoji?"\u23F8\uFE0F Idle":"[IDLE]",queued:this.caps.emoji?"\u23F3 Queued":"[QUEUED]",done:this.caps.emoji?"\u2705 Done":"[DONE]",failed:this.caps.emoji?"\u274C Failed":"[FAILED]",cancelled:this.caps.emoji?"\u{1F6AB} Cancel":"[CANCEL]"}[e]||e}formatDuration(e){if(e<=0)return"\u2014";let t=Math.floor(e/1e3),o=Math.floor(t/60),n=Math.floor(o/60);return n>0?`${n}h ${o%60}m`:o>0?`${o}m ${t%60}s`:`${t}s`}formatTokens(e){return e<=0?"\u2014":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}handleKeypress(e,t){if(t){if(t.name==="q"||t.ctrl&&t.name==="c"){this.stop();return}if(t.name==="j"||t.name==="down"){this.selectedIndex=Math.min(this.selectedIndex+1,this.agents.length-1),this.render();return}if(t.name==="k"||t.name==="up"){this.selectedIndex=Math.max(this.selectedIndex-1,0),this.render();return}if(t.name==="return"){this.handleAction("focus");return}if(t.name==="m"){this.handleAction("message");return}if(t.name==="c"){this.handleAction("cancel");return}if(t.name==="l"){this.handleAction("logs");return}if(t.name==="r"){this.handleAction("retry");return}}}async handleAction(e){let t=this.agents[this.selectedIndex];if(t)switch(e){case"focus":console.log(`
|
|
365
|
+
`),C==="jsonl"&&x.formatEvent){let O=x.formatEvent({type:"error",timestamp:Date.now(),data:{message:T.message||"unknown"}});O&&process.stdout.write(O+`
|
|
366
|
+
`)}break}});let N=0;try{let T=M.run(s),O=new Promise(k=>{let $=setInterval(()=>{(D||S)&&(clearInterval($),k(null))},500)}),_=await Promise.race([T,O]);clearTimeout(eo);let w=Date.now()-g;if(D?(N=124,v.status="timeout",v.summary=`Timeout after ${(Zt/1e3).toFixed(0)}s. Partial result below.`):S?(N=130,v.status="interrupted",v.summary="Interrupted by SIGINT."):_&&(v.status="completed",v.success=!0,v.summary=y.split(`
|
|
367
|
+
`)[0]?.substring(0,200)||"Task completed."),v.filesChanged=oe,v.toolCalls=E,v.tokens={input:pe,output:ne,thinking:De,total:pe+ne+De},v.cost=Xs(e.model,pe,ne,De),v.duration=w,v.success&&Fs.size>0){let k=!0;for(let[$,F]of Fs)try{let R=j.readFileSync(J.join(e.workspace,$));if(Ft.createHash("sha256").update(R).digest("hex")!==F){k=!1;break}}catch{k=!1;break}k&&oe.length===0&&(process.stderr.write(`[headless] Idempotency: no files changed \u2014 edits already applied.
|
|
368
|
+
`),v.summary="No changes needed \u2014 edits already applied.")}}catch(T){clearTimeout(eo);let O=T instanceof Error?T.message:String(T);O.includes("401")||O.includes("auth")||O.includes("token")?N=3:O.includes("ECONNREFUSED")||O.includes("ENOTFOUND")||O.includes("fetch failed")?N=5:N=1,v.status="failed",v.error=O,v.summary=`Error: ${O.substring(0,200)}`,v.duration=Date.now()-g,v.tokens={input:pe,output:ne,thinking:De,total:pe+ne+De},v.cost=Xs(e.model,pe,ne,De),v.filesChanged=oe,v.toolCalls=E}if(C==="text"||C==="stream")C==="text"&&process.stdout.write(y+`
|
|
369
|
+
`);else{let T=x.formatResult(v);process.stdout.write(T+`
|
|
370
|
+
`)}await ht.fire("HeadlessStop",{workspace:e.workspace,data:{success:v.success,exitCode:N,duration:v.duration,filesChanged:oe.length}}),process.removeListener("SIGINT",Es),process.exit(N)}l(Kb,"runHeadless");async function Yb(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(un(),Sc));await t({prompt:s,workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:e.autoBranch??!0,autoCommit:e.autoCommit??!0,autoPR:e.autoPR??!1,maxCost:e.maxCost,timeout:e.timeout})}l(Yb,"runBackground");async function Xb(){return new Promise(s=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{s(e.trim())})})}l(Xb,"readStdin");function Qb(s,e){console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Turns: ${s.turns} \xB7 Tokens: ${s.tokensIn} in / ${s.tokensOut} out`)),s.tokensCached>0&&console.log(a.dim(` Cached: ${s.tokensCached}`)),s.filesModified.length>0&&console.log(a.dim(` Files modified: ${s.filesModified.length}`));let t=(s.duration/1e3).toFixed(1);console.log(a.dim(` Duration: ${t}s`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(Qb,"printRunSummary");function Zb(){let s=I(),e=H(s),t=a.hex("#6B8DD6"),o=a.dim,n=a.bold,r=l((i,c)=>{let u=i.padEnd(30);return` ${t(u)} ${o(c)}`},"cmd");if(s.unicode){let i={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",tr2:"\u251C",tl2:"\u2524"},c=Math.min(62,s.columns-4),u=` ${e.tool} MonkeysCode Commands `,d=Math.max(0,c-u.length-2);console.log(""),console.log(t(` ${i.tl}${i.h}${u}${i.h.repeat(d)}${i.tr}`)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.message} Chat`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/model <name>","Switch model")+t(i.v)),console.log(t(` ${i.v}`)+r("/mode <plan|fast>","Switch mode")+t(i.v)),console.log(t(` ${i.v}`)+r("/compact","Compact context")+t(i.v)),console.log(t(` ${i.v}`)+r('/search "query"',"Web search")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.folder} Project`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/init","Initialize .monkeyscode/")+t(i.v)),console.log(t(` ${i.v}`)+r('/memory add "rule"',"Add convention")+t(i.v)),console.log(t(` ${i.v}`)+r("/permissions","Show/edit permissions")+t(i.v)),console.log(t(` ${i.v}`)+r("/skill","List/create skills")+t(i.v)),console.log(t(` ${i.v}`)+r("/hooks","List/create hooks")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.info} Stats`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/cost","Token usage & cost")+t(i.v)),console.log(t(` ${i.v}`)+r("/context [file]","Context window usage")+t(i.v)),console.log(t(` ${i.v}`)+r("/diff","Show uncommitted changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/files","List modified files")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.rocket} Actions`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/commit [msg]","Auto-commit changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/undo","Undo last file changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/review","Run code review")+t(i.v)),console.log(t(` ${i.v}`)+r('/goal "target"',"Autonomous goal loop")+t(i.v)),console.log(t(` ${i.v}`)+r('/fork ["task"]',"Fork to background")+t(i.v)),console.log(t(` ${i.v}`)+r('/delegate "t1" "t2"',"Parallel agents")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.lock} Session`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/sessions","List saved sessions")+t(i.v)),console.log(t(` ${i.v}`)+r("/resume [id]","Resume a session")+t(i.v)),console.log(t(` ${i.v}`)+r("/exit","Exit the REPL")+t(i.v)),console.log(t(` ${i.v}`)+r("/doctor","System health check")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+o(" Press / + Tab for autocomplete").padEnd(c+12)+t(i.v)),console.log(t(` ${i.bl}${i.h.repeat(c)}${i.br}`)),console.log("")}else console.log(""),console.log(n(" Slash Commands")),console.log(o(" Tab to auto-complete")),console.log(""),console.log(t(" Chat")),console.log(r("/model <name>","Switch model")),console.log(r("/mode <plan|fast>","Switch mode")),console.log(r("/compact","Compact context")),console.log(""),console.log(t(" Project")),console.log(r("/init","Initialize .monkeyscode/")),console.log(r('/memory add "rule"',"Add convention")),console.log(r("/permissions","Show/edit permissions")),console.log(r("/skill","List/create skills")),console.log(r("/hooks","List/create hooks")),console.log(""),console.log(t(" Stats")),console.log(r("/cost","Token usage & cost")),console.log(r("/context [file]","Context window usage")),console.log(r("/diff","Show uncommitted changes")),console.log(r("/files","List modified files")),console.log(""),console.log(t(" Actions")),console.log(r("/commit [msg]","Auto-commit changes")),console.log(r("/undo","Undo last file changes")),console.log(r("/review","Run code review")),console.log(r('/goal "target"',"Autonomous goal loop")),console.log(r('/fork ["task"]',"Fork to background")),console.log(""),console.log(t(" Session")),console.log(r("/sessions","List saved sessions")),console.log(r("/resume [id]","Resume a session")),console.log(r("/exit","Exit the REPL")),console.log(r("/doctor","System health check")),console.log("")}l(Zb,"printSlashHelp");function ew(s){let e=Date.now()-s,t=Math.floor(e/6e4),o=Math.floor(e/36e5),n=Math.floor(e/864e5);return t<1?"just now":t<60?`${t}m ago`:o<24?`${o}h ago`:`${n}d ago`}l(ew,"formatAge");ee();var Vr=b(require("node:readline"),1);W();_e();var Mc=class{static{l(this,"AgentsDashboard")}daemon;caps;icons;box;agents=[];selectedIndex=0;running=!1;refreshInterval=null;constructor(e){this.daemon=e,this.caps=I(),this.icons=H(this.caps),this.box=Oe(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(Vr.emitKeypressEvents(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume()),process.stdin.on("keypress",(e,t)=>{this.running&&this.handleKeypress(e,t)}),this.daemon.on("event",()=>{this.fetchAgents().then(()=>this.render())}),this.refreshInterval=setInterval(async()=>{await this.fetchAgents(),this.render()},5e3),this.render(),await new Promise(e=>{let t=setInterval(()=>{this.running||(clearInterval(t),e())},100)})}async list(){await this.fetchAgents();let e=this.caps.ansi;if(this.agents.length===0){console.log(" No active agents.");return}let t=`${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.bold(` ${t}`):` ${t}`),console.log(` ${"\u2500".repeat(Math.min(this.caps.columns-4,100))}`);for(let o of this.agents){let n=this.formatAgentLine(o,!1);console.log(` ${n}`)}}async fetchAgents(){try{this.agents=await this.daemon.call("agents.list",{})}catch{this.agents=[]}}render(){let e=this.caps.ansi,t=Math.min(this.caps.columns,120);console.clear();let o=`${this.icons.rocket} MonkeysCode Agents Dashboard`;if(console.log(e?a.bold(o):o),console.log(e?a.dim(` ${this.agents.length} agent(s) active`):` ${this.agents.length} agent(s) active`),console.log(`${this.box.separator.repeat(t)}`),this.agents.length===0)console.log(""),console.log(" No active agents."),console.log(""),console.log(e?a.dim(' Start one with: mc "your prompt"'):' Start one with: mc "your prompt"'),console.log("");else{let r=` ${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.dim(r):r),console.log(` ${"\u2500".repeat(t-4)}`);for(let i=0;i<this.agents.length;i++){let c=i===this.selectedIndex,u=this.formatAgentLine(this.agents[i],c);console.log(c&&e?a.bgHex("#1a1a2e").white(`\u25B6 ${u}`):` ${u}`)}}console.log(""),console.log(`${this.box.separator.repeat(t)}`);let n=e?` ${a.cyan("[j/k]")} Nav ${a.cyan("[Enter]")} Focus ${a.cyan("[m]")} Message ${a.cyan("[c]")} Cancel ${a.cyan("[l]")} Logs ${a.cyan("[r]")} Retry ${a.cyan("[q]")} Quit`:" [j/k] Nav [Enter] Focus [m] Message [c] Cancel [l] Logs [r] Retry [q] Quit";console.log(n)}formatAgentLine(e,t){let o=this.caps.ansi,n=e.id.slice(0,12).padEnd(14),r=e.type.padEnd(14),i=this.formatStatus(e.status).padEnd(12),c=`"${e.task.slice(0,33)}"`.padEnd(35),u=this.formatDuration(e.duration).padEnd(10),d=this.formatTokens(e.tokens),p=`${n} ${r} ${i} ${c} ${u} ${d}`;if(!o)return p;let f={active:a.green,running:a.green,idle:a.yellow,queued:a.blue,done:a.dim,failed:a.red,cancelled:a.dim}[e.status]||a.white;return`${a.white(n)} ${a.dim(r)} ${f(i)} ${a.white(c)} ${a.dim(u)} ${a.dim(d)}`}formatStatus(e){return{active:this.caps.emoji?"\u{1F504} Active":"[ACTIVE]",running:this.caps.emoji?"\u{1F504} Running":"[RUNNING]",idle:this.caps.emoji?"\u23F8\uFE0F Idle":"[IDLE]",queued:this.caps.emoji?"\u23F3 Queued":"[QUEUED]",done:this.caps.emoji?"\u2705 Done":"[DONE]",failed:this.caps.emoji?"\u274C Failed":"[FAILED]",cancelled:this.caps.emoji?"\u{1F6AB} Cancel":"[CANCEL]"}[e]||e}formatDuration(e){if(e<=0)return"\u2014";let t=Math.floor(e/1e3),o=Math.floor(t/60),n=Math.floor(o/60);return n>0?`${n}h ${o%60}m`:o>0?`${o}m ${t%60}s`:`${t}s`}formatTokens(e){return e<=0?"\u2014":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}handleKeypress(e,t){if(t){if(t.name==="q"||t.ctrl&&t.name==="c"){this.stop();return}if(t.name==="j"||t.name==="down"){this.selectedIndex=Math.min(this.selectedIndex+1,this.agents.length-1),this.render();return}if(t.name==="k"||t.name==="up"){this.selectedIndex=Math.max(this.selectedIndex-1,0),this.render();return}if(t.name==="return"){this.handleAction("focus");return}if(t.name==="m"){this.handleAction("message");return}if(t.name==="c"){this.handleAction("cancel");return}if(t.name==="l"){this.handleAction("logs");return}if(t.name==="r"){this.handleAction("retry");return}}}async handleAction(e){let t=this.agents[this.selectedIndex];if(t)switch(e){case"focus":console.log(`
|
|
362
371
|
Focusing on ${t.id}... (press Esc to return)
|
|
363
|
-
`);try{await this.daemon.call("agents.focus",{id:t.id})}catch{console.log(" Cannot focus on this agent.")}break;case"message":if(!process.stdin.isTTY)break;process.stdin.setRawMode(!1);let o=
|
|
372
|
+
`);try{await this.daemon.call("agents.focus",{id:t.id})}catch{console.log(" Cannot focus on this agent.")}break;case"message":if(!process.stdin.isTTY)break;process.stdin.setRawMode(!1);let o=Vr.createInterface({input:process.stdin,output:process.stdout});o.question(` Message to ${t.id}: `,async n=>{if(o.close(),n.trim())try{await this.daemon.call("agents.message",{id:t.id,message:n.trim()}),console.log(" \u2705 Message sent.")}catch{console.log(" \u274C Failed to send message.")}process.stdin.isTTY&&process.stdin.setRawMode(!0),this.render()});break;case"cancel":try{await this.daemon.call("agents.cancel",{id:t.id}),console.log(` \u2705 Cancelled ${t.id}`),await this.fetchAgents(),this.render()}catch{console.log(" \u274C Failed to cancel.")}break;case"logs":try{let n=await this.daemon.call("agents.logs",{id:t.id});console.clear(),console.log(` \u{1F4CB} Logs for ${t.id}:`),console.log(` ${"\u2500".repeat(60)}`),console.log(n.content),console.log(` ${"\u2500".repeat(60)}`),console.log(" Press any key to return..."),await new Promise(r=>{let i=l(()=>{process.stdin.removeListener("keypress",i),r()},"handler");process.stdin.on("keypress",i)}),this.render()}catch{console.log(" \u274C Failed to fetch logs.")}break;case"retry":try{await this.daemon.call("agents.retry",{id:t.id}),console.log(` \u{1F504} Retrying ${t.id}`),await this.fetchAgents(),this.render()}catch{console.log(" \u274C Failed to retry.")}break}}stop(){this.running=!1,this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=null),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),console.clear(),console.log(" Dashboard closed. Agents continue running."),console.log("")}};async function Oc(s=!0){let e=new po({autoSpawn:!1});try{await e.connect()}catch{console.error(' Daemon is not running. Start it with: mc "your prompt"'),process.exit(1)}let t=new Mc(e);s&&process.stdin.isTTY?await t.start():await t.list(),e.disconnect()}l(Oc,"agentsCommand");var Vt=[{name:"auth",description:"Manage authentication",subcommands:[{name:"login",description:"Authenticate with MonkeysCode platform"},{name:"logout",description:"Remove stored credentials"},{name:"token",description:"Set API token directly (for CI)"},{name:"status",description:"Check authentication status"}]},{name:"status",description:"Show daemon and account status"},{name:"doctor",description:"Run system health checks"},{name:"config",description:"Manage CLI configuration",subcommands:[{name:"set",description:"Set a config value"},{name:"get",description:"Get a config value"},{name:"path",description:"Show config file locations"}]},{name:"index",description:"Index a workspace for context retrieval",flags:[{long:"--force",description:"Force full re-index"}]},{name:"mcp",description:"Manage MCP servers",subcommands:[{name:"list",description:"Show configured MCP servers"},{name:"add",description:"Add an MCP server"},{name:"remove",description:"Remove an MCP server"},{name:"test",description:"Test MCP server connectivity"}]},{name:"jobs",description:"Manage background agent jobs",subcommands:[{name:"list",description:"List all background jobs"},{name:"status",description:"Get detailed job status"},{name:"logs",description:"View job logs"},{name:"cancel",description:"Cancel a running job"},{name:"retry",description:"Retry a failed job"},{name:"diff",description:"Show diff of job changes"},{name:"pull",description:"Pull job changes into current branch"}]},{name:"agents",description:"View active agent sessions dashboard",subcommands:[{name:"list",description:"List active agents (non-interactive)"}]},{name:"sessions",description:"Manage conversation sessions",subcommands:[{name:"list",description:"List recent sessions"},{name:"delete",description:"Delete a session"},{name:"prune",description:"Remove old sessions"}]},{name:"completions",description:"Generate shell completion scripts"}],hn=[{long:"--prompt",short:"-p",description:"Prompt for the agent",takesValue:!0},{long:"--headless",description:"Headless mode (CI/CD)"},{long:"--background",description:"Submit as background job"},{long:"--model",description:"Model to use",takesValue:!0,values:["auto","claude-sonnet","claude-opus","capuchin-1.1"]},{long:"--mode",description:"Agent mode",takesValue:!0,values:["plan","fast","thinking"]},{long:"--workspace",description:"Workspace path",takesValue:!0},{long:"--budget",description:"Max token budget",takesValue:!0},{long:"--output",short:"-o",description:"Output format",takesValue:!0,values:["text","json","stream"]},{long:"--verbose",description:"Verbose output"},{long:"--show-thinking",description:"Show model reasoning traces"},{long:"--continue",description:"Resume last session"},{long:"--auto-approve",description:"Auto-approve all tool calls"},{long:"--approve-for-me",description:"Smart auto-approval"},{long:"--yolo",description:"Bypass all permission checks"},{long:"--sandbox",description:"Run in sandbox mode"},{long:"--no-sandbox",description:"Disable sandbox"},{long:"--auto-branch",description:"Create a new branch for changes"},{long:"--auto-commit",description:"Auto-commit changes"},{long:"--auto-pr",description:"Create PR after background job"},{long:"--accessible",description:"Screen-reader friendly output"}];function ym(s){switch(s){case"bash":return tw();case"zsh":return ow();case"fish":return sw();case"pwsh":return nw();default:throw new Error(`Unsupported shell: ${s}. Supported: bash, zsh, fish, pwsh`)}}l(ym,"generateCompletions");function bm(s){switch(s){case"bash":return["# Add to ~/.bashrc:",'eval "$(monkeyscode completions bash)"',"","# Or save to a file:","monkeyscode completions bash > /usr/local/etc/bash_completion.d/monkeyscode"].join(`
|
|
364
373
|
`);case"zsh":return["# Add to ~/.zshrc:",'eval "$(monkeyscode completions zsh)"',"","# Or save to fpath:","monkeyscode completions zsh > ~/.zsh/completions/_monkeyscode","# Then ensure ~/.zsh/completions is in your fpath"].join(`
|
|
365
374
|
`);case"fish":return["monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish"].join(`
|
|
366
375
|
`);case"pwsh":return["# Add to your PowerShell profile:","monkeyscode completions pwsh | Out-String | Invoke-Expression","","# Or save and dot-source:","monkeyscode completions pwsh > monkeyscode-completions.ps1",". ./monkeyscode-completions.ps1"].join(`
|
|
367
|
-
`)}}l(
|
|
376
|
+
`)}}l(bm,"getCompletionInstallInstructions");function tw(){let s=Vt.map(n=>n.name).join(" "),e=hn.map(n=>n.long).join(" "),t=hn.filter(n=>n.short).map(n=>n.short).join(" "),o=Vt.filter(n=>n.subcommands).map(n=>{let r=n.subcommands.map(i=>i.name).join(" ");return` ${n.name}) COMPREPLY=( $(compgen -W "${r}" -- "$cur") ) ;;`}).join(`
|
|
368
377
|
`);return`#!/bin/bash
|
|
369
378
|
# monkeyscode bash completion \u2014 generated by monkeyscode completions bash
|
|
370
379
|
# Install: eval "$(monkeyscode completions bash)"
|
|
@@ -391,9 +400,9 @@ ${o}
|
|
|
391
400
|
complete -F _monkeyscode_completions monkeyscode
|
|
392
401
|
complete -F _monkeyscode_completions mc
|
|
393
402
|
complete -F _monkeyscode_completions mcode
|
|
394
|
-
`}l(tw,"generateBashCompletions");function ow(){let s=
|
|
395
|
-
`),e=
|
|
396
|
-
`),t=
|
|
403
|
+
`}l(tw,"generateBashCompletions");function ow(){let s=Vt.map(o=>`'${o.name}:${o.description.replace(/'/g,"''")}'`).join(`
|
|
404
|
+
`),e=hn.map(o=>{let n=o.takesValue?`=${o.description}`:"";return`'${o.short?`{${o.short},${o.long}}`:o.long}[${o.description.replace(/'/g,"''")}]${n}'`}).join(`
|
|
405
|
+
`),t=Vt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>`'${r.name}:${r.description.replace(/'/g,"''")}'`).join(`
|
|
397
406
|
`);return`
|
|
398
407
|
__monkeyscode_${o.name}_commands() {
|
|
399
408
|
local commands
|
|
@@ -423,7 +432,7 @@ _monkeyscode() {
|
|
|
423
432
|
;;
|
|
424
433
|
args)
|
|
425
434
|
case "\${words[1]}" in
|
|
426
|
-
${
|
|
435
|
+
${Vt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_${o.name}_commands ;;`).join(`
|
|
427
436
|
`)}
|
|
428
437
|
esac
|
|
429
438
|
;;
|
|
@@ -432,11 +441,11 @@ ${zt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_$
|
|
|
432
441
|
${t}
|
|
433
442
|
|
|
434
443
|
compdef _monkeyscode monkeyscode mc mcode
|
|
435
|
-
`}l(ow,"generateZshCompletions");function sw(){let s=["# monkeyscode fish completion \u2014 generated by monkeyscode completions fish","# Install: monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish","","# Disable file completions by default","complete -c monkeyscode -f","complete -c mc -f","complete -c mcode -f",""];for(let e of
|
|
444
|
+
`}l(ow,"generateZshCompletions");function sw(){let s=["# monkeyscode fish completion \u2014 generated by monkeyscode completions fish","# Install: monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish","","# Disable file completions by default","complete -c monkeyscode -f","complete -c mc -f","complete -c mcode -f",""];for(let e of Vt)s.push(`complete -c monkeyscode -n '__fish_use_subcommand' -a '${e.name}' -d '${e.description}'`),s.push(`complete -c mc -n '__fish_use_subcommand' -a '${e.name}' -d '${e.description}'`);s.push("");for(let e of Vt)if(e.subcommands)for(let t of e.subcommands)s.push(`complete -c monkeyscode -n '__fish_seen_subcommand_from ${e.name}' -a '${t.name}' -d '${t.description}'`),s.push(`complete -c mc -n '__fish_seen_subcommand_from ${e.name}' -a '${t.name}' -d '${t.description}'`);s.push("");for(let e of hn){let t=e.long.replace(/^--/,""),o=e.short?` -s ${e.short.replace(/^-/,"")}`:"",n=e.takesValue?" -r":"";s.push(`complete -c monkeyscode -l ${t}${o}${n} -d '${e.description}'`),s.push(`complete -c mc -l ${t}${o}${n} -d '${e.description}'`)}return s.join(`
|
|
436
445
|
`)+`
|
|
437
|
-
`}l(sw,"generateFishCompletions");function nw(){let s=
|
|
438
|
-
`),e=
|
|
439
|
-
`),t=
|
|
446
|
+
`}l(sw,"generateFishCompletions");function nw(){let s=Vt.map(o=>` [CompletionResult]::new('${o.name}', '${o.name}', [CompletionResultType]::ParameterValue, '${o.description}')`).join(`
|
|
447
|
+
`),e=hn.map(o=>` [CompletionResult]::new('${o.long}', '${o.long}', [CompletionResultType]::ParameterName, '${o.description}')`).join(`
|
|
448
|
+
`),t=Vt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>` [CompletionResult]::new('${r.name}', '${r.name}', [CompletionResultType]::ParameterValue, '${r.description}')`).join(`
|
|
440
449
|
`);return` '${o.name}' {
|
|
441
450
|
${n}
|
|
442
451
|
}`}).join(`
|
|
@@ -462,42 +471,42 @@ ${t}
|
|
|
462
471
|
}
|
|
463
472
|
}
|
|
464
473
|
}
|
|
465
|
-
`}l(nw,"generatePowerShellCompletions");
|
|
474
|
+
`}l(nw,"generatePowerShellCompletions");W();cr();function Ic(s){let e=Fo(s),t=Yu(s);console.log(""),console.log(a.bold(" Hook Directories:"));for(let o of t){let n=o.exists?a.green("\u2713"):a.dim("\u2717");console.log(` ${n} ${a.dim(`[${o.source}]`)} ${o.path}`)}if(console.log(""),e.length===0){console.log(a.dim(" No hooks found.")),console.log(a.dim(" Create hook scripts in .monkeyscode/hooks/ or ~/.monkeyscode/hooks/")),console.log(a.dim(" Example: .monkeyscode/hooks/post-edit.sh")),console.log("");return}console.log(a.bold(" Active Hooks:")),console.log(a.dim(" \u2500".repeat(35))),console.log(" "+a.bold("Event".padEnd(20))+a.bold("Source".padEnd(10))+a.bold("Type".padEnd(6))+a.bold("Script")),console.log(a.dim(" "+"\u2500".repeat(70)));for(let o of e){let n=o.source==="project"?a.cyan:a.dim;console.log(" "+a.hex("#6B8DD6")(o.event.padEnd(20))+n(o.source.padEnd(10))+a.dim(o.scriptType.padEnd(6))+o.scriptPath)}console.log(""),console.log(a.dim(` ${e.length} hook(s) loaded. Project hooks override global hooks.`)),console.log("")}l(Ic,"hooksListCommand");W();var wm=require("node:events"),km=require("node:child_process");var zr=class extends wm.EventEmitter{static{l(this,"MCPClient")}_servers=new Map;async connect(e){if(!e.enabled)return;let t={config:e,connected:!1,tools:[],resources:[],prompts:[],requestId:0,pendingRequests:new Map,buffer:""};this._servers.set(e.name,t),e.transport==="stdio"?await this._connectStdio(t):e.transport==="sse"&&await this._connectSSE(t)}async _connectStdio(e){try{let t=(0,km.spawn)(e.config.command,e.config.args||[],{cwd:e.config.cwd,env:{...process.env,...e.config.env||{}},stdio:["pipe","pipe","pipe"]});e.process=t,t.stdout?.on("data",o=>{e.buffer+=o.toString("utf8"),this._processBuffer(e)}),t.stderr?.on("data",o=>{let n=o.toString("utf8").trim();n&&this.emit("log",`[MCP ${e.config.name}] ${n}`)}),t.on("close",o=>{e.connected=!1,this.emit("connection-changed",{server:e.config.name,connected:!1}),o!==0&&o!==null&&this.emit("error",new Error(`MCP "${e.config.name}" exited with code ${o}`))}),t.on("error",o=>{e.connected=!1,this.emit("error",new Error(`MCP "${e.config.name}" process error: ${o.message}`))}),await this._initialize(e)}catch(t){this.emit("error",new Error(`MCP "${e.config.name}" connect failed: ${t.message}`))}}async _connectSSE(e){try{let t=e.config.url,o=new AbortController;e.sseAbort=o;let n=await fetch(t,{method:"GET",headers:{Accept:"text/event-stream"},signal:o.signal});if(!n.ok)throw new Error(`SSE connection failed: ${n.status}`);let r=n.body?.getReader();if(!r)throw new Error("No response body");let i=new TextDecoder;l(async()=>{try{for(;;){let{done:u,value:d}=await r.read();if(u)break;let p=i.decode(d,{stream:!0});e.buffer+=p;let f=e.buffer.split(`
|
|
466
475
|
`);e.buffer=f.pop()||"";for(let m=0;m<f.length;m++){let g=f[m];if(g.startsWith("data: "))try{let h=JSON.parse(g.slice(6));this._handleResponse(e,h)}catch{}else if(g.startsWith("event: endpoint")){let h=f[m+1];h?.startsWith("data: ")&&(e.sseSessionUrl=h.slice(6).trim())}}}}catch(u){o.signal.aborted||(e.connected=!1,this.emit("error",new Error(`MCP SSE "${e.config.name}": ${u.message}`)))}},"processSSE")(),await new Promise(u=>setTimeout(u,500)),await this._initialize(e)}catch(t){this.emit("error",new Error(`MCP SSE "${e.config.name}" connect failed: ${t.message}`))}}async _initialize(e){try{await this._sendRequest(e,"initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0}},clientInfo:{name:"MonkeysCode-CLI",version:"1.0.0"}})&&(e.connected=!0,this.emit("connection-changed",{server:e.config.name,connected:!0}),this._sendNotification(e,"notifications/initialized",{}),await this._discoverTools(e),await this._discoverResources(e),await this._discoverPrompts(e))}catch(t){this.emit("error",new Error(`MCP "${e.config.name}" initialize failed: ${t.message}`))}}async _discoverTools(e){try{let t=await this._sendRequest(e,"tools/list",{});t?.tools&&(e.tools=t.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema||{type:"object",properties:{},required:[]},serverName:e.config.name})),this.emit("tools-discovered",e.tools))}catch(t){this.emit("log",`[MCP ${e.config.name}] tools/list failed: ${t.message}`)}}async _discoverResources(e){try{let t=await this._sendRequest(e,"resources/list",{});t?.resources&&(e.resources=t.resources.map(o=>({uri:o.uri,name:o.name,mimeType:o.mimeType,description:o.description,serverName:e.config.name})))}catch{}}async _discoverPrompts(e){try{let t=await this._sendRequest(e,"prompts/list",{});t?.prompts&&(e.prompts=t.prompts.map(o=>({name:o.name,description:o.description,arguments:o.arguments,serverName:e.config.name})))}catch{}}async callTool(e,t,o){let n=this._servers.get(e);if(!n||!n.connected)return{content:`MCP server "${e}" is not connected.`,isError:!0};try{let r=await this._sendRequest(n,"tools/call",{name:t,arguments:o});return r?.content?{content:r.content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
467
476
|
`)||"(no output)",isError:r.isError}:{content:"(no output)"}}catch(r){return{content:`MCP tool call failed: ${r.message}`,isError:!0}}}async readResource(e,t){let o=this._servers.get(e);if(!o||!o.connected)throw new Error(`MCP server "${e}" is not connected`);let n=await this._sendRequest(o,"resources/read",{uri:t});return n?.contents?n.contents.map(r=>r.text||"").join(`
|
|
468
477
|
`):""}getAllTools(){let e=[];for(let t of this._servers.values())t.connected&&e.push(...t.tools);return e}getConnectedServers(){return Array.from(this._servers.entries()).filter(([,e])=>e.connected).map(([e])=>e)}getServerInfo(e){let t=this._servers.get(e);if(t)return{connected:t.connected,tools:t.tools.length,resources:t.resources.length,prompts:t.prompts.length}}disconnect(e){let t=this._servers.get(e);if(t){if(t.process)try{t.process.kill()}catch{}t.sseAbort&&t.sseAbort.abort(),t.connected=!1,this._servers.delete(e),this.emit("connection-changed",{server:e,connected:!1})}}disconnectAll(){for(let e of[...this._servers.keys()])this.disconnect(e)}_sendRequest(e,t,o){return new Promise((n,r)=>{let i=++e.requestId,c={jsonrpc:"2.0",id:i,method:t,params:o},u=setTimeout(()=>{e.pendingRequests.delete(i),r(new Error(`MCP request timed out: ${t}`))},3e4);e.pendingRequests.set(i,{resolve:l(d=>{clearTimeout(u),n(d)},"resolve"),reject:l(d=>{clearTimeout(u),r(d)},"reject")}),this._sendMessage(e,c)})}_sendNotification(e,t,o){this._sendMessage(e,{jsonrpc:"2.0",method:t,params:o})}_sendMessage(e,t){let o=JSON.stringify(t);e.config.transport==="stdio"&&e.process?e.process.stdin?.write(o+`
|
|
469
478
|
`):e.config.transport==="sse"&&e.sseSessionUrl&&fetch(e.sseSessionUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:o}).catch(()=>{})}_processBuffer(e){let t=e.buffer.split(`
|
|
470
|
-
`);e.buffer=t.pop()||"";for(let o of t){let n=o.trim();if(n)try{let r=JSON.parse(n);this._handleResponse(e,r)}catch{}}}_handleResponse(e,t){if(t.id!==void 0){let o=e.pendingRequests.get(t.id);o&&(e.pendingRequests.delete(t.id),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result))}}};var fn=[{id:"github",name:"GitHub",description:"PRs, issues, code search, repository management",category:"dev-tools",icon:"\u{1F419}",install:{transport:"stdio",package:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],envVars:["GITHUB_PERSONAL_ACCESS_TOKEN"]},tags:["github","git","pull-request","issues","code-search"],official:!0},{id:"gitlab",name:"GitLab",description:"GitLab MRs, issues, pipelines",category:"dev-tools",icon:"\u{1F98A}",install:{transport:"stdio",package:"@modelcontextprotocol/server-gitlab",command:"npx",args:["-y","@modelcontextprotocol/server-gitlab"],envVars:["GITLAB_PERSONAL_ACCESS_TOKEN"]},tags:["gitlab","merge-request","ci-cd"],official:!0},{id:"filesystem",name:"Filesystem",description:"Read and write files, list directories",category:"filesystem",icon:"\u{1F4C1}",install:{transport:"stdio",package:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","."]},tags:["files","filesystem","read","write","directory"],official:!0},{id:"memory",name:"Memory",description:"Persistent key-value memory for agent context",category:"other",icon:"\u{1F9E0}",install:{transport:"stdio",package:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"]},tags:["memory","context","persistent","knowledge"],official:!0},{id:"postgres",name:"PostgreSQL",description:"Query PostgreSQL databases, inspect schemas",category:"database",icon:"\u{1F418}",install:{transport:"stdio",package:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],envVars:["POSTGRES_CONNECTION_STRING"]},tags:["postgres","postgresql","sql","database","query"],official:!0},{id:"mysql",name:"MySQL",description:"Query MySQL databases, inspect schemas",category:"database",icon:"\u{1F42C}",install:{transport:"stdio",package:"mcp-server-mysql",command:"npx",args:["-y","mcp-server-mysql"],envVars:["MYSQL_CONNECTION_STRING"]},tags:["mysql","sql","database","query"],official:!1},{id:"sqlite",name:"SQLite",description:"Query SQLite databases",category:"database",icon:"\u{1F4E6}",install:{transport:"stdio",package:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"]},tags:["sqlite","sql","database","local"],official:!0},{id:"mongodb",name:"MongoDB",description:"MongoDB document database queries and operations",category:"database",icon:"\u{1F343}",install:{transport:"stdio",package:"mcp-server-mongodb",command:"npx",args:["-y","mcp-server-mongodb"],envVars:["MONGODB_URI"]},tags:["mongodb","nosql","document","database"],official:!1},{id:"redis",name:"Redis",description:"Redis key-value store, caching, pub/sub",category:"database",icon:"\u{1F534}",install:{transport:"stdio",package:"mcp-server-redis",command:"npx",args:["-y","mcp-server-redis"],envVars:["REDIS_URL"]},tags:["redis","cache","key-value","pub-sub"],official:!1},{id:"supabase",name:"Supabase",description:"Supabase database, auth, storage, edge functions",category:"database",icon:"\u26A1",install:{transport:"stdio",package:"mcp-server-supabase",command:"npx",args:["-y","mcp-server-supabase"],envVars:["SUPABASE_URL","SUPABASE_SERVICE_KEY"]},tags:["supabase","postgres","auth","storage","realtime"],official:!1},{id:"neon",name:"Neon",description:"Neon serverless PostgreSQL branching and queries",category:"database",icon:"\u{1F7E2}",install:{transport:"stdio",package:"@neondatabase/mcp-server-neon",command:"npx",args:["-y","@neondatabase/mcp-server-neon"],envVars:["NEON_API_KEY"]},tags:["neon","postgres","serverless","branching"],official:!0},{id:"linear",name:"Linear",description:"Issues, projects, cycles, team management",category:"project-mgmt",icon:"\u{1F4D0}",install:{transport:"stdio",package:"mcp-server-linear",command:"npx",args:["-y","mcp-server-linear"],envVars:["LINEAR_API_KEY"]},tags:["linear","issues","project","kanban","agile"],official:!1},{id:"jira",name:"Jira",description:"Jira issues, boards, sprints",category:"project-mgmt",icon:"\u{1F535}",install:{transport:"stdio",package:"mcp-server-jira",command:"npx",args:["-y","mcp-server-jira"],envVars:["JIRA_URL","JIRA_EMAIL","JIRA_API_TOKEN"]},tags:["jira","issues","sprint","agile","atlassian"],official:!1},{id:"notion",name:"Notion",description:"Notion pages, databases, blocks, search",category:"project-mgmt",icon:"\u{1F4DD}",install:{transport:"stdio",package:"mcp-server-notion",command:"npx",args:["-y","mcp-server-notion"],envVars:["NOTION_TOKEN"]},tags:["notion","wiki","docs","database","knowledge"],official:!1},{id:"todoist",name:"Todoist",description:"Task management, projects, labels, filters",category:"project-mgmt",icon:"\u2705",install:{transport:"stdio",package:"mcp-server-todoist",command:"npx",args:["-y","mcp-server-todoist"],envVars:["TODOIST_API_TOKEN"]},tags:["todoist","tasks","todo","productivity","project"],official:!1},{id:"slack",name:"Slack",description:"Send messages, read channels, manage threads",category:"communication",icon:"\u{1F4AC}",install:{transport:"stdio",package:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],envVars:["SLACK_BOT_TOKEN"]},tags:["slack","chat","messaging","notifications"],official:!0},{id:"discord",name:"Discord",description:"Discord messaging, channels, server management",category:"communication",icon:"\u{1F3AE}",install:{transport:"stdio",package:"mcp-server-discord",command:"npx",args:["-y","mcp-server-discord"],envVars:["DISCORD_BOT_TOKEN"]},tags:["discord","chat","messaging","bot"],official:!1},{id:"email",name:"Email (SMTP)",description:"Send and read emails via SMTP/IMAP",category:"communication",icon:"\u{1F4E7}",install:{transport:"stdio",package:"mcp-server-email",command:"npx",args:["-y","mcp-server-email"],envVars:["SMTP_HOST","SMTP_USER","SMTP_PASS"]},tags:["email","smtp","imap","mail","notifications"],official:!1},{id:"puppeteer",name:"Puppeteer",description:"Browser automation, screenshots, web scraping",category:"browser",icon:"\u{1F310}",install:{transport:"stdio",package:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"]},tags:["browser","puppeteer","automation","screenshot","scraping"],official:!0},{id:"playwright",name:"Playwright",description:"Browser automation, testing, multi-browser support",category:"browser",icon:"\u{1F3AD}",install:{transport:"stdio",package:"@anthropic/mcp-server-playwright",command:"npx",args:["-y","@anthropic/mcp-server-playwright"]},tags:["browser","playwright","testing","automation","e2e"],official:!1},{id:"fetch",name:"Fetch",description:"Fetch web pages and convert to markdown",category:"browser",icon:"\u{1F517}",install:{transport:"stdio",package:"@modelcontextprotocol/server-fetch",command:"npx",args:["-y","@modelcontextprotocol/server-fetch"]},tags:["fetch","http","web","markdown","url"],official:!0},{id:"brave-search",name:"Brave Search",description:"Web search via Brave Search API",category:"browser",icon:"\u{1F981}",install:{transport:"stdio",package:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],envVars:["BRAVE_API_KEY"]},tags:["search","brave","web","query"],official:!0},{id:"tavily",name:"Tavily",description:"AI-optimized search, research, content extraction",category:"browser",icon:"\u{1F50D}",install:{transport:"stdio",package:"mcp-server-tavily",command:"npx",args:["-y","mcp-server-tavily"],envVars:["TAVILY_API_KEY"]},tags:["search","tavily","research","ai-search"],official:!1},{id:"aws",name:"AWS",description:"AWS services: S3, Lambda, DynamoDB, EC2, CloudWatch",category:"dev-tools",icon:"\u2601\uFE0F",install:{transport:"stdio",package:"mcp-server-aws",command:"npx",args:["-y","mcp-server-aws"],envVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"]},tags:["aws","amazon","s3","lambda","cloud","infrastructure"],official:!1},{id:"gcp",name:"Google Cloud",description:"GCP services: GCS, BigQuery, Cloud Run, Compute",category:"dev-tools",icon:"\u{1F324}\uFE0F",install:{transport:"stdio",package:"mcp-server-gcp",command:"npx",args:["-y","mcp-server-gcp"],envVars:["GOOGLE_APPLICATION_CREDENTIALS"]},tags:["gcp","google-cloud","bigquery","gcs","cloud"],official:!1},{id:"cloudflare",name:"Cloudflare",description:"Workers, KV, R2, D1, DNS management",category:"dev-tools",icon:"\u{1F525}",install:{transport:"stdio",package:"mcp-server-cloudflare",command:"npx",args:["-y","mcp-server-cloudflare"],envVars:["CLOUDFLARE_API_TOKEN"]},tags:["cloudflare","workers","cdn","dns","edge"],official:!1},{id:"vercel",name:"Vercel",description:"Deployments, projects, domains, environment variables",category:"dev-tools",icon:"\u25B2",install:{transport:"stdio",package:"mcp-server-vercel",command:"npx",args:["-y","mcp-server-vercel"],envVars:["VERCEL_TOKEN"]},tags:["vercel","deploy","serverless","hosting","nextjs"],official:!1},{id:"docker",name:"Docker",description:"Manage containers, images, volumes, networks",category:"dev-tools",icon:"\u{1F433}",install:{transport:"stdio",package:"mcp-server-docker",command:"npx",args:["-y","mcp-server-docker"]},tags:["docker","container","image","devops","deploy"],official:!1},{id:"kubernetes",name:"Kubernetes",description:"K8s cluster management, pods, deployments, services",category:"dev-tools",icon:"\u2388",install:{transport:"stdio",package:"mcp-server-kubernetes",command:"npx",args:["-y","mcp-server-kubernetes"]},tags:["kubernetes","k8s","pods","cluster","devops"],official:!1},{id:"sentry",name:"Sentry",description:"Error tracking, performance monitoring, issue management",category:"dev-tools",icon:"\u{1F6E1}\uFE0F",install:{transport:"stdio",package:"@sentry/mcp-server",command:"npx",args:["-y","@sentry/mcp-server"],envVars:["SENTRY_AUTH_TOKEN","SENTRY_ORG"]},tags:["sentry","errors","monitoring","debugging","performance"],official:!0},{id:"grafana",name:"Grafana",description:"Dashboards, metrics, alerting, log queries",category:"dev-tools",icon:"\u{1F4CA}",install:{transport:"stdio",package:"mcp-server-grafana",command:"npx",args:["-y","mcp-server-grafana"],envVars:["GRAFANA_URL","GRAFANA_API_KEY"]},tags:["grafana","metrics","dashboard","monitoring","observability"],official:!1},{id:"datadog",name:"Datadog",description:"Metrics, logs, traces, monitors, dashboards",category:"dev-tools",icon:"\u{1F415}",install:{transport:"stdio",package:"mcp-server-datadog",command:"npx",args:["-y","mcp-server-datadog"],envVars:["DD_API_KEY","DD_APP_KEY"]},tags:["datadog","monitoring","metrics","logs","apm","observability"],official:!1},{id:"stripe",name:"Stripe",description:"Payments, customers, subscriptions, invoices",category:"other",icon:"\u{1F4B3}",install:{transport:"stdio",package:"mcp-server-stripe",command:"npx",args:["-y","mcp-server-stripe"],envVars:["STRIPE_SECRET_KEY"]},tags:["stripe","payments","billing","subscriptions","invoices"],official:!1},{id:"figma",name:"Figma",description:"Figma designs, components, styles, variables",category:"other",icon:"\u{1F3A8}",install:{transport:"stdio",package:"mcp-server-figma",command:"npx",args:["-y","mcp-server-figma"],envVars:["FIGMA_ACCESS_TOKEN"]},tags:["figma","design","ui","components","prototype"],official:!1},{id:"google-drive",name:"Google Drive",description:"Google Drive files, Docs, Sheets, search",category:"other",icon:"\u{1F4C2}",install:{transport:"stdio",package:"@modelcontextprotocol/server-google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"]},tags:["google-drive","docs","sheets","files","storage"],official:!0}],gn=class{static{l(this,"MCPRegistry")}getAll(){return[...fn]}getByCategory(e){return fn.filter(t=>t.category===e)}search(e){let t=e.toLowerCase();return fn.filter(o=>o.name.toLowerCase().includes(t)||o.description.toLowerCase().includes(t)||o.tags.some(n=>n.includes(t)))}get(e){return fn.find(t=>t.id===e)}getCategories(){let e=new Map;for(let o of fn)e.set(o.category,(e.get(o.category)||0)+1);let t={"dev-tools":"Dev Tools & Cloud",database:"Databases","project-mgmt":"Project Management",communication:"Communication",browser:"Browser & Search",filesystem:"Filesystem",other:"Other"};return Array.from(e.entries()).map(([o,n])=>({category:o,count:n,label:t[o]||o}))}};async function km(s){let e=nn(s),t=Ip(s);console.log(""),console.log(a.bold(" MCP Configuration:"));for(let o of t){let n=o.exists?a.green("\u2713"):a.dim("\u2717");console.log(` ${n} ${a.dim(`[${o.source}]`)} ${o.path}`)}if(console.log(""),e.length===0){console.log(a.dim(" No MCP servers configured.")),console.log(a.dim(" Add one with: mc mcp add <name> <command> [args...]")),console.log(a.dim(" Or browse: mc mcp browse")),console.log("");return}console.log(a.bold(" Configured Servers:")),console.log(a.dim(" "+"\u2500".repeat(60)));for(let o of e){let n=a.dim(`[${o.transport}]`),r="\u{1F50C}",i=a.hex("#6B8DD6")(o.name);if(o.transport==="sse")console.log(` ${r} ${i} ${n} \u2192 ${o.url}`);else{let c=[o.command,...o.args||[]].join(" ");console.log(` ${r} ${i} ${n} \u2192 ${c}`)}if(o.env&&Object.keys(o.env).length>0){let c=Object.keys(o.env).join(", ");console.log(` ${a.dim(`env: ${c}`)}`)}}console.log(""),console.log(a.dim(` ${e.length} server(s) configured. Use 'mc mcp test <name>' to verify.`)),console.log("")}l(km,"mcpListCommand");function Dm(s,e,t,o){if(!t){let r=new gn,i=r.get(e);if(i){if(uc(s,i.id,i.install.command,i.install.args||[]),console.log(""),console.log(a.green(` \u2713 Added MCP server from registry: ${i.name}`)),console.log(a.dim(` Command: ${i.install.command} ${(i.install.args||[]).join(" ")}`)),console.log(a.dim(" Config: .monkeyscode/mcp.json")),i.install.envVars?.length){console.log(a.yellow(`
|
|
479
|
+
`);e.buffer=t.pop()||"";for(let o of t){let n=o.trim();if(n)try{let r=JSON.parse(n);this._handleResponse(e,r)}catch{}}}_handleResponse(e,t){if(t.id!==void 0){let o=e.pendingRequests.get(t.id);o&&(e.pendingRequests.delete(t.id),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result))}}};var yn=[{id:"github",name:"GitHub",description:"PRs, issues, code search, repository management",category:"dev-tools",icon:"\u{1F419}",install:{transport:"stdio",package:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],envVars:["GITHUB_PERSONAL_ACCESS_TOKEN"]},tags:["github","git","pull-request","issues","code-search"],official:!0},{id:"gitlab",name:"GitLab",description:"GitLab MRs, issues, pipelines",category:"dev-tools",icon:"\u{1F98A}",install:{transport:"stdio",package:"@modelcontextprotocol/server-gitlab",command:"npx",args:["-y","@modelcontextprotocol/server-gitlab"],envVars:["GITLAB_PERSONAL_ACCESS_TOKEN"]},tags:["gitlab","merge-request","ci-cd"],official:!0},{id:"filesystem",name:"Filesystem",description:"Read and write files, list directories",category:"filesystem",icon:"\u{1F4C1}",install:{transport:"stdio",package:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","."]},tags:["files","filesystem","read","write","directory"],official:!0},{id:"memory",name:"Memory",description:"Persistent key-value memory for agent context",category:"other",icon:"\u{1F9E0}",install:{transport:"stdio",package:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"]},tags:["memory","context","persistent","knowledge"],official:!0},{id:"postgres",name:"PostgreSQL",description:"Query PostgreSQL databases, inspect schemas",category:"database",icon:"\u{1F418}",install:{transport:"stdio",package:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],envVars:["POSTGRES_CONNECTION_STRING"]},tags:["postgres","postgresql","sql","database","query"],official:!0},{id:"mysql",name:"MySQL",description:"Query MySQL databases, inspect schemas",category:"database",icon:"\u{1F42C}",install:{transport:"stdio",package:"mcp-server-mysql",command:"npx",args:["-y","mcp-server-mysql"],envVars:["MYSQL_CONNECTION_STRING"]},tags:["mysql","sql","database","query"],official:!1},{id:"sqlite",name:"SQLite",description:"Query SQLite databases",category:"database",icon:"\u{1F4E6}",install:{transport:"stdio",package:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"]},tags:["sqlite","sql","database","local"],official:!0},{id:"mongodb",name:"MongoDB",description:"MongoDB document database queries and operations",category:"database",icon:"\u{1F343}",install:{transport:"stdio",package:"mcp-server-mongodb",command:"npx",args:["-y","mcp-server-mongodb"],envVars:["MONGODB_URI"]},tags:["mongodb","nosql","document","database"],official:!1},{id:"redis",name:"Redis",description:"Redis key-value store, caching, pub/sub",category:"database",icon:"\u{1F534}",install:{transport:"stdio",package:"mcp-server-redis",command:"npx",args:["-y","mcp-server-redis"],envVars:["REDIS_URL"]},tags:["redis","cache","key-value","pub-sub"],official:!1},{id:"supabase",name:"Supabase",description:"Supabase database, auth, storage, edge functions",category:"database",icon:"\u26A1",install:{transport:"stdio",package:"mcp-server-supabase",command:"npx",args:["-y","mcp-server-supabase"],envVars:["SUPABASE_URL","SUPABASE_SERVICE_KEY"]},tags:["supabase","postgres","auth","storage","realtime"],official:!1},{id:"neon",name:"Neon",description:"Neon serverless PostgreSQL branching and queries",category:"database",icon:"\u{1F7E2}",install:{transport:"stdio",package:"@neondatabase/mcp-server-neon",command:"npx",args:["-y","@neondatabase/mcp-server-neon"],envVars:["NEON_API_KEY"]},tags:["neon","postgres","serverless","branching"],official:!0},{id:"linear",name:"Linear",description:"Issues, projects, cycles, team management",category:"project-mgmt",icon:"\u{1F4D0}",install:{transport:"stdio",package:"mcp-server-linear",command:"npx",args:["-y","mcp-server-linear"],envVars:["LINEAR_API_KEY"]},tags:["linear","issues","project","kanban","agile"],official:!1},{id:"jira",name:"Jira",description:"Jira issues, boards, sprints",category:"project-mgmt",icon:"\u{1F535}",install:{transport:"stdio",package:"mcp-server-jira",command:"npx",args:["-y","mcp-server-jira"],envVars:["JIRA_URL","JIRA_EMAIL","JIRA_API_TOKEN"]},tags:["jira","issues","sprint","agile","atlassian"],official:!1},{id:"notion",name:"Notion",description:"Notion pages, databases, blocks, search",category:"project-mgmt",icon:"\u{1F4DD}",install:{transport:"stdio",package:"mcp-server-notion",command:"npx",args:["-y","mcp-server-notion"],envVars:["NOTION_TOKEN"]},tags:["notion","wiki","docs","database","knowledge"],official:!1},{id:"todoist",name:"Todoist",description:"Task management, projects, labels, filters",category:"project-mgmt",icon:"\u2705",install:{transport:"stdio",package:"mcp-server-todoist",command:"npx",args:["-y","mcp-server-todoist"],envVars:["TODOIST_API_TOKEN"]},tags:["todoist","tasks","todo","productivity","project"],official:!1},{id:"slack",name:"Slack",description:"Send messages, read channels, manage threads",category:"communication",icon:"\u{1F4AC}",install:{transport:"stdio",package:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],envVars:["SLACK_BOT_TOKEN"]},tags:["slack","chat","messaging","notifications"],official:!0},{id:"discord",name:"Discord",description:"Discord messaging, channels, server management",category:"communication",icon:"\u{1F3AE}",install:{transport:"stdio",package:"mcp-server-discord",command:"npx",args:["-y","mcp-server-discord"],envVars:["DISCORD_BOT_TOKEN"]},tags:["discord","chat","messaging","bot"],official:!1},{id:"email",name:"Email (SMTP)",description:"Send and read emails via SMTP/IMAP",category:"communication",icon:"\u{1F4E7}",install:{transport:"stdio",package:"mcp-server-email",command:"npx",args:["-y","mcp-server-email"],envVars:["SMTP_HOST","SMTP_USER","SMTP_PASS"]},tags:["email","smtp","imap","mail","notifications"],official:!1},{id:"puppeteer",name:"Puppeteer",description:"Browser automation, screenshots, web scraping",category:"browser",icon:"\u{1F310}",install:{transport:"stdio",package:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"]},tags:["browser","puppeteer","automation","screenshot","scraping"],official:!0},{id:"playwright",name:"Playwright",description:"Browser automation, testing, multi-browser support",category:"browser",icon:"\u{1F3AD}",install:{transport:"stdio",package:"@anthropic/mcp-server-playwright",command:"npx",args:["-y","@anthropic/mcp-server-playwright"]},tags:["browser","playwright","testing","automation","e2e"],official:!1},{id:"fetch",name:"Fetch",description:"Fetch web pages and convert to markdown",category:"browser",icon:"\u{1F517}",install:{transport:"stdio",package:"@modelcontextprotocol/server-fetch",command:"npx",args:["-y","@modelcontextprotocol/server-fetch"]},tags:["fetch","http","web","markdown","url"],official:!0},{id:"brave-search",name:"Brave Search",description:"Web search via Brave Search API",category:"browser",icon:"\u{1F981}",install:{transport:"stdio",package:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],envVars:["BRAVE_API_KEY"]},tags:["search","brave","web","query"],official:!0},{id:"tavily",name:"Tavily",description:"AI-optimized search, research, content extraction",category:"browser",icon:"\u{1F50D}",install:{transport:"stdio",package:"mcp-server-tavily",command:"npx",args:["-y","mcp-server-tavily"],envVars:["TAVILY_API_KEY"]},tags:["search","tavily","research","ai-search"],official:!1},{id:"aws",name:"AWS",description:"AWS services: S3, Lambda, DynamoDB, EC2, CloudWatch",category:"dev-tools",icon:"\u2601\uFE0F",install:{transport:"stdio",package:"mcp-server-aws",command:"npx",args:["-y","mcp-server-aws"],envVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"]},tags:["aws","amazon","s3","lambda","cloud","infrastructure"],official:!1},{id:"gcp",name:"Google Cloud",description:"GCP services: GCS, BigQuery, Cloud Run, Compute",category:"dev-tools",icon:"\u{1F324}\uFE0F",install:{transport:"stdio",package:"mcp-server-gcp",command:"npx",args:["-y","mcp-server-gcp"],envVars:["GOOGLE_APPLICATION_CREDENTIALS"]},tags:["gcp","google-cloud","bigquery","gcs","cloud"],official:!1},{id:"cloudflare",name:"Cloudflare",description:"Workers, KV, R2, D1, DNS management",category:"dev-tools",icon:"\u{1F525}",install:{transport:"stdio",package:"mcp-server-cloudflare",command:"npx",args:["-y","mcp-server-cloudflare"],envVars:["CLOUDFLARE_API_TOKEN"]},tags:["cloudflare","workers","cdn","dns","edge"],official:!1},{id:"vercel",name:"Vercel",description:"Deployments, projects, domains, environment variables",category:"dev-tools",icon:"\u25B2",install:{transport:"stdio",package:"mcp-server-vercel",command:"npx",args:["-y","mcp-server-vercel"],envVars:["VERCEL_TOKEN"]},tags:["vercel","deploy","serverless","hosting","nextjs"],official:!1},{id:"docker",name:"Docker",description:"Manage containers, images, volumes, networks",category:"dev-tools",icon:"\u{1F433}",install:{transport:"stdio",package:"mcp-server-docker",command:"npx",args:["-y","mcp-server-docker"]},tags:["docker","container","image","devops","deploy"],official:!1},{id:"kubernetes",name:"Kubernetes",description:"K8s cluster management, pods, deployments, services",category:"dev-tools",icon:"\u2388",install:{transport:"stdio",package:"mcp-server-kubernetes",command:"npx",args:["-y","mcp-server-kubernetes"]},tags:["kubernetes","k8s","pods","cluster","devops"],official:!1},{id:"sentry",name:"Sentry",description:"Error tracking, performance monitoring, issue management",category:"dev-tools",icon:"\u{1F6E1}\uFE0F",install:{transport:"stdio",package:"@sentry/mcp-server",command:"npx",args:["-y","@sentry/mcp-server"],envVars:["SENTRY_AUTH_TOKEN","SENTRY_ORG"]},tags:["sentry","errors","monitoring","debugging","performance"],official:!0},{id:"grafana",name:"Grafana",description:"Dashboards, metrics, alerting, log queries",category:"dev-tools",icon:"\u{1F4CA}",install:{transport:"stdio",package:"mcp-server-grafana",command:"npx",args:["-y","mcp-server-grafana"],envVars:["GRAFANA_URL","GRAFANA_API_KEY"]},tags:["grafana","metrics","dashboard","monitoring","observability"],official:!1},{id:"datadog",name:"Datadog",description:"Metrics, logs, traces, monitors, dashboards",category:"dev-tools",icon:"\u{1F415}",install:{transport:"stdio",package:"mcp-server-datadog",command:"npx",args:["-y","mcp-server-datadog"],envVars:["DD_API_KEY","DD_APP_KEY"]},tags:["datadog","monitoring","metrics","logs","apm","observability"],official:!1},{id:"stripe",name:"Stripe",description:"Payments, customers, subscriptions, invoices",category:"other",icon:"\u{1F4B3}",install:{transport:"stdio",package:"mcp-server-stripe",command:"npx",args:["-y","mcp-server-stripe"],envVars:["STRIPE_SECRET_KEY"]},tags:["stripe","payments","billing","subscriptions","invoices"],official:!1},{id:"figma",name:"Figma",description:"Figma designs, components, styles, variables",category:"other",icon:"\u{1F3A8}",install:{transport:"stdio",package:"mcp-server-figma",command:"npx",args:["-y","mcp-server-figma"],envVars:["FIGMA_ACCESS_TOKEN"]},tags:["figma","design","ui","components","prototype"],official:!1},{id:"google-drive",name:"Google Drive",description:"Google Drive files, Docs, Sheets, search",category:"other",icon:"\u{1F4C2}",install:{transport:"stdio",package:"@modelcontextprotocol/server-google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"]},tags:["google-drive","docs","sheets","files","storage"],official:!0}],bn=class{static{l(this,"MCPRegistry")}getAll(){return[...yn]}getByCategory(e){return yn.filter(t=>t.category===e)}search(e){let t=e.toLowerCase();return yn.filter(o=>o.name.toLowerCase().includes(t)||o.description.toLowerCase().includes(t)||o.tags.some(n=>n.includes(t)))}get(e){return yn.find(t=>t.id===e)}getCategories(){let e=new Map;for(let o of yn)e.set(o.category,(e.get(o.category)||0)+1);let t={"dev-tools":"Dev Tools & Cloud",database:"Databases","project-mgmt":"Project Management",communication:"Communication",browser:"Browser & Search",filesystem:"Filesystem",other:"Other"};return Array.from(e.entries()).map(([o,n])=>({category:o,count:n,label:t[o]||o}))}};async function Dm(s){let e=cn(s),t=jp(s);console.log(""),console.log(a.bold(" MCP Configuration:"));for(let o of t){let n=o.exists?a.green("\u2713"):a.dim("\u2717");console.log(` ${n} ${a.dim(`[${o.source}]`)} ${o.path}`)}if(console.log(""),e.length===0){console.log(a.dim(" No MCP servers configured.")),console.log(a.dim(" Add one with: mc mcp add <name> <command> [args...]")),console.log(a.dim(" Or browse: mc mcp browse")),console.log("");return}console.log(a.bold(" Configured Servers:")),console.log(a.dim(" "+"\u2500".repeat(60)));for(let o of e){let n=a.dim(`[${o.transport}]`),r="\u{1F50C}",i=a.hex("#6B8DD6")(o.name);if(o.transport==="sse")console.log(` ${r} ${i} ${n} \u2192 ${o.url}`);else{let c=[o.command,...o.args||[]].join(" ");console.log(` ${r} ${i} ${n} \u2192 ${c}`)}if(o.env&&Object.keys(o.env).length>0){let c=Object.keys(o.env).join(", ");console.log(` ${a.dim(`env: ${c}`)}`)}}console.log(""),console.log(a.dim(` ${e.length} server(s) configured. Use 'mc mcp test <name>' to verify.`)),console.log("")}l(Dm,"mcpListCommand");function vm(s,e,t,o){if(!t){let r=new bn,i=r.get(e);if(i){if(uc(s,i.id,i.install.command,i.install.args||[]),console.log(""),console.log(a.green(` \u2713 Added MCP server from registry: ${i.name}`)),console.log(a.dim(` Command: ${i.install.command} ${(i.install.args||[]).join(" ")}`)),console.log(a.dim(" Config: .monkeyscode/mcp.json")),i.install.envVars?.length){console.log(a.yellow(`
|
|
471
480
|
\u26A0 Required environment variables:`));for(let u of i.install.envVars)console.log(` ${a.cyan(u)}`)}console.log("");return}console.log(a.red(`
|
|
472
481
|
Usage: mc mcp add <name> <command> [args...]`)),console.log(a.dim(" Or use a registry ID: mc mcp add github"));let c=r.search(e);if(c.length>0){console.log(a.dim(`
|
|
473
|
-
Did you mean:`));for(let u of c.slice(0,5))console.log(` ${a.cyan(u.id)} \u2014 ${u.description}`)}console.log("");return}uc(s,e,t,o);let n=[t,...o].join(" ");console.log(""),console.log(a.green(` \u2713 Added MCP server: ${e}`)),console.log(a.dim(` Command: ${n}`)),console.log(a.dim(" Config: .monkeyscode/mcp.json")),console.log("")}l(
|
|
482
|
+
Did you mean:`));for(let u of c.slice(0,5))console.log(` ${a.cyan(u.id)} \u2014 ${u.description}`)}console.log("");return}uc(s,e,t,o);let n=[t,...o].join(" ");console.log(""),console.log(a.green(` \u2713 Added MCP server: ${e}`)),console.log(a.dim(` Command: ${n}`)),console.log(a.dim(" Config: .monkeyscode/mcp.json")),console.log("")}l(vm,"mcpAddCommand");function Sm(s,e){let t=Ip(s,e);console.log(""),console.log(t?a.green(` \u2713 Removed MCP server: ${e}`):a.red(` \u2717 Server not found: ${e}`)),console.log("")}l(Sm,"mcpRemoveCommand");async function xm(s,e){let t=cn(s),o=t.find(i=>i.name===e);if(!o){console.log(""),console.log(a.red(` \u2717 Server not found: ${e}`)),console.log(a.dim(` Available servers: ${t.map(i=>i.name).join(", ")||"none"}`)),console.log("");return}console.log(""),console.log(a.bold(` Testing MCP server: ${e}...`));let n=new zr;n.on("log",i=>{console.log(a.dim(` ${i}`))});let r={name:o.name,transport:o.transport||"stdio",command:o.command,args:o.args,url:o.url,env:o.env,enabled:!0};try{await n.connect(r);let i=n.getServerInfo(e);if(i?.connected){console.log(a.green(" \u2713 Connected successfully")),console.log(a.dim(` Tools: ${i.tools}`)),console.log(a.dim(` Resources: ${i.resources}`)),console.log(a.dim(` Prompts: ${i.prompts}`)),console.log("");let c=n.getAllTools();if(c.length>0){console.log(a.bold(" Available Tools:"));for(let u of c){let d=`mcp_${u.serverName}_${u.name}`;console.log(` \u{1F527} ${a.cyan(d)}${u.description?a.dim(` \u2014 ${u.description}`):""}`)}}else console.log(a.dim(" No tools exposed by this server."))}else console.log(a.red(" \u2717 Connection failed"))}catch(i){console.log(a.red(` \u2717 Connection error: ${i.message}`)),console.log(a.dim(` Transport: ${o.transport||"stdio"}`)),o.command&&console.log(a.dim(` Command: ${o.command} ${(o.args||[]).join(" ")}`)),o.url&&console.log(a.dim(` URL: ${o.url}`))}finally{n.disconnectAll()}console.log("")}l(xm,"mcpTestCommand");function $m(s){let e=new bn,t=s?e.search(s):e.getAll();if(t.length===0){console.log(a.dim(`
|
|
474
483
|
No servers matching "${s}"
|
|
475
484
|
`));return}if(s){console.log(a.bold(`
|
|
476
485
|
\u{1F50D} Search: "${s}" (${t.length} results)
|
|
477
486
|
`));for(let o of t){let n=o.official?a.green(" \u2713 official"):"";console.log(` ${o.icon} ${a.bold(o.name)}${n}`),console.log(` ${a.dim(o.description)}`),console.log(` ${a.dim("Install:")} ${a.cyan(`mc mcp add ${o.id}`)}`),o.install.envVars?.length&&console.log(` ${a.dim("Requires:")} ${o.install.envVars.join(", ")}`),console.log()}}else{let o=e.getCategories();console.log(a.bold(`
|
|
478
487
|
\u{1F50C} MCP Server Registry
|
|
479
488
|
`));for(let n of o){console.log(a.bold(` \u2500\u2500 ${n.label} (${n.count}) \u2500\u2500`));let r=e.getByCategory(n.category);for(let i of r){let c=i.official?a.green(" \u2713"):"",u=i.install.envVars?.length?a.dim(` (needs ${i.install.envVars[0]})`):"";console.log(` ${i.icon} ${a.bold(i.name)}${c}${u} \u2014 ${a.dim(i.description)}`)}console.log()}console.log(a.dim(` Add a server: ${a.cyan("mc mcp add <id>")}`)),console.log(a.dim(` Search: ${a.cyan("mc mcp browse <query>")}
|
|
480
|
-
`))}}l(xm,"mcpBrowseCommand");Q();var Qe=y(require("node:fs"),1),yn=y(require("node:path"),1);Q();U();var hn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var $m=["plan","fast","thinking"],Cm=["dark","light","auto"],_m=["text","json","stream"],Em={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>$m.includes(s)?null:`must be one of: ${$m.join(", ")}`,"defaultMode"),theme:l(s=>Cm.includes(s)?null:`must be one of: ${Cm.join(", ")}`,"theme"),outputFormat:l(s=>_m.includes(s)?null:`must be one of: ${_m.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Nc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:hn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(hn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=Em[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Qe.mkdirSync(yn.dirname(r),{recursive:!0}),Qe.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Qe.existsSync(o)&&(n=JSON.parse(Qe.readFileSync(o,"utf8")))}catch{}delete n[e],Qe.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...hn};for(let t of Object.keys(hn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=P();return yn.join(e.config,"config.json")}getProjectConfigPath(){return yn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Qe.existsSync(e)){let o=JSON.parse(Qe.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=Em[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(hn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Qe.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Fm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Fm,"printConfigList");var jc=null;function No(s){return(!jc||s)&&(jc=new Nc(s)),jc}l(No,"getConfigSystem");lr();U();Ce();te();var rw=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Tm(){let s=O(),e=W(s),t=s.ansi,o=me();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Ee();if(d){let p=await fetch(`${rw}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Lc(n.tokensIn),u=Lc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Lc(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(Tm,"usageCommand");function Lc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Lc,"formatTokenCount");var mt=y(require("node:fs"),1),Nm=y(require("node:path"),1),bs=require("node:child_process");U();var ys=y(require("node:fs"),1),zr=y(require("node:path"),1);Q();var iw="https://monkeyscode.com/api/latest-version",aw="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",cw=4*60*60*1e3;function Pm(){let s=P();return zr.join(s.config,"update-check")}l(Pm,"getCachePath");function lw(){try{let s=ys.readFileSync(Pm(),"utf8");return JSON.parse(s)}catch{return null}}l(lw,"readCache");function Bc(s){try{let e=Pm();ys.mkdirSync(zr.dirname(e),{recursive:!0}),ys.writeFileSync(e,JSON.stringify(s))}catch{}}l(Bc,"writeCache");function Rm(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Rm,"isNewerVersion");function uw(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(uw,"getAssetKey");async function Jr(s,e=!1){if(!e){let t=lw();if(t&&Date.now()-t.lastCheck<cw)return t.latestVersion&&Rm(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await Am(iw);if(t||(t=await Am(aw)),!t)return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=uw(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Bc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Rm(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Jr,"checkForUpdate");async function Am(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(Am,"fetchManifest");function Mm(s){Jr(s).then(e=>{e&&(globalThis.__mcUpdateAvailable=e)}).catch(()=>{})}l(Mm,"checkForUpdateBackground");function Om(){let s=globalThis.__mcUpdateAvailable;if(!s)return;let e=globalThis.__mcChalk,t=`\u2139\uFE0F Update available: v${s.currentVersion} \u2192 v${s.version}. Run "mc update" to upgrade.`;console.error(e?e.dim(t):t)}l(Om,"printUpdateNotice");function Uc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Uc,"detectInstallMethod");async function Lm(s){let t=(await Promise.resolve().then(()=>(jm(),Im)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.6";if(s.rollback){await Dw(t);return}if(s.check){await mw(t);return}await fw(t,s.version)}l(Lm,"updateCommand");async function mw(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Jr(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(mw,"checkOnly");async function fw(s,e){let t=Uc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await gw(e);break;case"homebrew":await hw();break;case"winget":await yw();break;case"chocolatey":await bw();break;case"scoop":await ww();break;case"binary":await kw(s,e);break;default:console.log(a.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${a.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${a.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${a.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(o){console.error(a.red(` \u274C Update failed: ${o instanceof Error?o.message:String(o)}`)),console.log(a.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}l(fw,"performUpdate");async function gw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,bs.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(gw,"updateViaNpm");async function hw(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,bs.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(hw,"updateViaHomebrew");async function yw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,bs.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(yw,"updateViaWinget");async function bw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,bs.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(bw,"updateViaChocolatey");async function ww(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,bs.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(ww,"updateViaScoop");async function kw(s,e){let t=await Jr(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{mt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${Nm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{mt.writeFileSync(n,c),mt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{mt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(kw,"updateViaBinaryDownload");async function Dw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Uc()==="binary"){let t=process.execPath+".backup";if(!mt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{mt.copyFileSync(t,process.execPath),mt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(Dw,"rollback");U();var ws=y(require("node:fs"),1),Yr=y(require("node:path"),1),Wm=y(require("node:crypto"),1);Q();var Jt=!0,Wc="",Ze=[],Bm=!1,vw="https://monkeyscode.com/api/telemetry",Kr=50,Sw=6e4;function Hm(){let s=P();return Yr.join(s.config,"telemetry.json")}l(Hm,"getConfigPath");function Hc(){try{let s=ws.readFileSync(Hm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:xw()};return Gc(s),s}}l(Hc,"loadConfig");function Gc(s){try{let e=Hm();ws.mkdirSync(Yr.dirname(e),{recursive:!0}),ws.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(Gc,"saveConfig");function xw(){return Wm.randomUUID()}l(xw,"generateClientId");function Gm(){if(Bm)return;if(Bm=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Jt=!1;return}let s=Hc();Jt=s.enabled,Wc=s.clientId,Jt&&(setInterval(()=>Um(),Sw).unref(),process.on("beforeExit",()=>Um()))}l(Gm,"initTelemetry");function qm(){return Jt}l(qm,"isTelemetryEnabled");function Vm(){Jt=!0;let s=Hc();s.enabled=!0,Gc(s)}l(Vm,"enableTelemetry");function zm(){Jt=!1,Ze=[];let s=Hc();s.enabled=!1,Gc(s)}l(zm,"disableTelemetry");function Jm(s,e={}){Jt&&(Ze.push({name:s,properties:e,timestamp:new Date().toISOString()}),Ze.length>Kr&&(Ze=Ze.slice(-Kr)))}l(Jm,"trackEvent");async function Um(){if(!Jt||Ze.length===0)return;let s=[...Ze];Ze=[];let e=$e(),o={clientId:Wc,cliVersion:"0.1.6",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(vw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{Ze.unshift(...s),Ze.length>Kr&&(Ze=Ze.slice(-Kr))}}l(Um,"flushEvents");function Km(){let s=$e();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.6",` \u2022 OS: ${s.os} (${s.arch})`,` \u2022 Shell: ${s.shell}`,` \u2022 Node.js version: ${process.version}`," \u2022 Command used (interactive, headless, background)"," \u2022 Model selected"," \u2022 Duration and token count"," \u2022 Error types (not error content)"," \u2022 Tool usage frequency","","\u274C Never collected:"," \u2022 Prompts or conversation content"," \u2022 Source code or file contents"," \u2022 File paths or project names"," \u2022 Authentication tokens or API keys"," \u2022 Personal information","",`Status: ${Jt?"ENABLED":"DISABLED"}`,`Client ID: ${Wc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
481
|
-
`)}l(
|
|
482
|
-
`)[0];t.push({name:"ripgrep",ok:!0,msg:r.replace("ripgrep ","")})}catch{t.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let n of t){let r=n.ok?a.green(" \u2705"):a.yellow(" \u26A0\uFE0F ");console.log(`${r} ${n.name}: ${a.dim(n.msg)}`)}console.log(""),console.log(a.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${a.cyan("mc auth login")}`),console.log(""),console.log(a.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${a.dim("Interactive:")} ${a.cyan("mc")} Open the REPL`),console.log(` ${a.dim("One-shot:")} ${a.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${a.dim("Background:")} ${a.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${a.dim("Health:")} ${a.cyan("mc doctor")} Check your setup`),console.log(` ${a.dim("Help:")} ${a.cyan("mc --help")} See all commands`),console.log(""),console.log(a.dim(" \u2500".repeat(30))),console.log(a.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),Ew()}l(
|
|
489
|
+
`))}}l($m,"mcpBrowseCommand");X();var Ze=b(require("node:fs"),1),kn=b(require("node:path"),1);X();W();var wn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var Cm=["plan","fast","thinking"],_m=["dark","light","auto"],Em=["text","json","stream"],Fm={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>Cm.includes(s)?null:`must be one of: ${Cm.join(", ")}`,"defaultMode"),theme:l(s=>_m.includes(s)?null:`must be one of: ${_m.join(", ")}`,"theme"),outputFormat:l(s=>Em.includes(s)?null:`must be one of: ${Em.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Nc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:wn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(wn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=Fm[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Ze.mkdirSync(kn.dirname(r),{recursive:!0}),Ze.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Ze.existsSync(o)&&(n=JSON.parse(Ze.readFileSync(o,"utf8")))}catch{}delete n[e],Ze.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...wn};for(let t of Object.keys(wn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=A();return kn.join(e.config,"config.json")}getProjectConfigPath(){return kn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Ze.existsSync(e)){let o=JSON.parse(Ze.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=Fm[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(wn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Ze.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Tm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Tm,"printConfigList");var jc=null;function No(s){return(!jc||s)&&(jc=new Nc(s)),jc}l(No,"getConfigSystem");ur();W();_e();ee();var rw=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Rm(){let s=I(),e=H(s),t=s.ansi,o=fe();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Fe();if(d){let p=await fetch(`${rw}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Lc(n.tokensIn),u=Lc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Lc(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(Rm,"usageCommand");function Lc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Lc,"formatTokenCount");var mt=b(require("node:fs"),1),jm=b(require("node:path"),1),ws=require("node:child_process");W();var bs=b(require("node:fs"),1),Jr=b(require("node:path"),1);X();var iw="https://monkeyscode.com/api/latest-version",aw="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",cw=4*60*60*1e3;function Mm(){let s=A();return Jr.join(s.config,"update-check")}l(Mm,"getCachePath");function lw(){try{let s=bs.readFileSync(Mm(),"utf8");return JSON.parse(s)}catch{return null}}l(lw,"readCache");function Bc(s){try{let e=Mm();bs.mkdirSync(Jr.dirname(e),{recursive:!0}),bs.writeFileSync(e,JSON.stringify(s))}catch{}}l(Bc,"writeCache");function Am(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Am,"isNewerVersion");function uw(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(uw,"getAssetKey");async function Uc(s,e=!1){if(!e){let t=lw();if(t&&Date.now()-t.lastCheck<cw)return t.latestVersion&&Am(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await Pm(iw);if(t||(t=await Pm(aw)),!t)return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=uw(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Bc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Am(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Uc,"checkForUpdate");async function Pm(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(Pm,"fetchManifest");function Wc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Wc,"detectInstallMethod");async function Nm(s){let t=(await Promise.resolve().then(()=>(Im(),Om)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.8";if(s.rollback){await Dw(t);return}if(s.check){await mw(t);return}await fw(t,s.version)}l(Nm,"updateCommand");async function mw(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Uc(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(mw,"checkOnly");async function fw(s,e){let t=Wc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await gw(e);break;case"homebrew":await hw();break;case"winget":await yw();break;case"chocolatey":await bw();break;case"scoop":await ww();break;case"binary":await kw(s,e);break;default:console.log(a.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${a.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${a.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${a.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(o){console.error(a.red(` \u274C Update failed: ${o instanceof Error?o.message:String(o)}`)),console.log(a.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}l(fw,"performUpdate");async function gw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,ws.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(gw,"updateViaNpm");async function hw(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,ws.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(hw,"updateViaHomebrew");async function yw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,ws.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(yw,"updateViaWinget");async function bw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,ws.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(bw,"updateViaChocolatey");async function ww(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,ws.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(ww,"updateViaScoop");async function kw(s,e){let t=await Uc(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{mt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${jm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{mt.writeFileSync(n,c),mt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{mt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(kw,"updateViaBinaryDownload");async function Dw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Wc()==="binary"){let t=process.execPath+".backup";if(!mt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{mt.copyFileSync(t,process.execPath),mt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(Dw,"rollback");W();var ks=b(require("node:fs"),1),Yr=b(require("node:path"),1),Um=b(require("node:crypto"),1);X();var zt=!0,Hc="",et=[],Lm=!1,vw="https://monkeyscode.com/api/telemetry",Kr=50,Sw=6e4;function Wm(){let s=A();return Yr.join(s.config,"telemetry.json")}l(Wm,"getConfigPath");function Gc(){try{let s=ks.readFileSync(Wm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:xw()};return qc(s),s}}l(Gc,"loadConfig");function qc(s){try{let e=Wm();ks.mkdirSync(Yr.dirname(e),{recursive:!0}),ks.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(qc,"saveConfig");function xw(){return Um.randomUUID()}l(xw,"generateClientId");function Hm(){if(Lm)return;if(Lm=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){zt=!1;return}let s=Gc();zt=s.enabled,Hc=s.clientId,zt&&(setInterval(()=>Bm(),Sw).unref(),process.on("beforeExit",()=>Bm()))}l(Hm,"initTelemetry");function Gm(){return zt}l(Gm,"isTelemetryEnabled");function qm(){zt=!0;let s=Gc();s.enabled=!0,qc(s)}l(qm,"enableTelemetry");function Vm(){zt=!1,et=[];let s=Gc();s.enabled=!1,qc(s)}l(Vm,"disableTelemetry");function zm(s,e={}){zt&&(et.push({name:s,properties:e,timestamp:new Date().toISOString()}),et.length>Kr&&(et=et.slice(-Kr)))}l(zm,"trackEvent");async function Bm(){if(!zt||et.length===0)return;let s=[...et];et=[];let e=Ce(),o={clientId:Hc,cliVersion:"0.1.8",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(vw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{et.unshift(...s),et.length>Kr&&(et=et.slice(-Kr))}}l(Bm,"flushEvents");function Jm(){let s=Ce();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.8",` \u2022 OS: ${s.os} (${s.arch})`,` \u2022 Shell: ${s.shell}`,` \u2022 Node.js version: ${process.version}`," \u2022 Command used (interactive, headless, background)"," \u2022 Model selected"," \u2022 Duration and token count"," \u2022 Error types (not error content)"," \u2022 Tool usage frequency","","\u274C Never collected:"," \u2022 Prompts or conversation content"," \u2022 Source code or file contents"," \u2022 File paths or project names"," \u2022 Authentication tokens or API keys"," \u2022 Personal information","",`Status: ${zt?"ENABLED":"DISABLED"}`,`Client ID: ${Hc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
490
|
+
`)}l(Jm,"getCollectedDataSummary");async function Km(s){switch(s){case"enable":qm(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":Vm(),console.log(""),console.log(a.yellow(" \u26A0\uFE0F Telemetry disabled")),console.log(a.dim(" No data will be collected.")),console.log("");break;case"show":console.log(""),console.log(Jm()),console.log("");break;case"status":default:console.log(""),process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"?console.log(a.yellow(" \u26A0\uFE0F Telemetry: DISABLED (DO_NOT_TRACK env var is set)")):Gm()?console.log(a.green(" \u2705 Telemetry: ENABLED")):console.log(a.dim(" \u2B55 Telemetry: DISABLED")),console.log(""),console.log(a.dim(" Commands:")),console.log(a.dim(" mc telemetry enable \u2014 enable anonymous usage data")),console.log(a.dim(" mc telemetry disable \u2014 disable all telemetry")),console.log(a.dim(" mc telemetry show \u2014 see what data is collected")),console.log("");break}}l(Km,"telemetryCommand");var St=b(require("node:fs"),1),Dn=b(require("node:path"),1);W();X();async function Ym(s,e){let t=Ce(),o="0.1.8";console.log(""),console.log(a.bold(" \u{1F41B} Bug Report")),console.log("");let n={description:s||"(no description provided)",cliVersion:o,nodeVersion:process.version,os:`${t.os} (${t.arch})`,arch:t.arch,shell:t.shell,timestamp:new Date().toISOString()};if(e?.attachCrash){let i=_w();i?(n.crashLog=i,console.log(a.dim(" \u{1F4CE} Attached latest crash report"))):console.log(a.dim(" No crash reports found"))}if(await $w(n))console.log(a.green(" \u2705 Bug report submitted")),console.log(a.dim(" Thank you! Our team will review your report."));else{let i=Cw(n);console.log(a.yellow(" \u26A0\uFE0F Could not submit online (saved locally)")),console.log(a.dim(` Report: ${i}`)),console.log(a.dim(" Submit later: mc bug --submit-local"))}console.log("")}l(Ym,"bugCommand");async function $w(s){try{return(await fetch("https://monkeyscode.com/api/bug-reports",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(1e4)})).ok}catch{return!1}}l($w,"submitReport");function Cw(s){let e=A(),t=Dn.join(e.config,"bug-reports");St.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Dn.join(t,`${o}.json`);return St.writeFileSync(n,JSON.stringify(s,null,2)),n}l(Cw,"saveReportLocally");function _w(){try{let s=A(),e=Dn.join(s.config,"crashes");if(!St.existsSync(e))return null;let t=St.readdirSync(e).filter(o=>o.endsWith(".log")).sort().reverse();return t.length===0?null:St.readFileSync(Dn.join(e,t[0]),"utf8")}catch{return null}}l(_w,"getLatestCrashLog");var Lo=b(require("node:fs"),1),Vc=b(require("node:path"),1);W();X();_e();function Xm(){let s=A(),e=Vc.join(s.config,"config.json");return!Lo.existsSync(e)}l(Xm,"isFirstRun");function Ew(){let e=A().config,t=Vc.join(e,"config.json");Lo.mkdirSync(e,{recursive:!0}),Lo.existsSync(t)||Lo.writeFileSync(t,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}l(Ew,"markOnboardingComplete");async function Qm(){let s=I(),e=Ce();console.log(""),console.log(a.bold(" \u{1F435} Welcome to MonkeysCode!")),console.log(a.dim(" \u2500".repeat(30))),console.log(""),console.log(" MonkeysCode is an AI coding agent that lives in your terminal."),console.log(" It can edit files, run commands, search code, and manage git \u2014"),console.log(" all from natural language prompts."),console.log(""),console.log(a.dim(` Platform: ${e.os} (${e.arch}) \xB7 Shell: ${e.shell}`)),console.log(""),console.log(a.bold(" \u{1FA7A} Quick Setup Check")),console.log("");let t=[],o=parseInt(process.version.slice(1).split(".")[0],10);t.push({name:"Node.js",ok:o>=20,msg:o>=20?process.version:`${process.version} (requires >= 20)`});try{let{execSync:n}=await import("node:child_process"),r=n("git --version",{encoding:"utf8"}).trim();t.push({name:"Git",ok:!0,msg:r.replace("git version ","")})}catch{t.push({name:"Git",ok:!1,msg:"not found"})}try{let{execSync:n}=await import("node:child_process"),r=n("rg --version",{encoding:"utf8"}).split(`
|
|
491
|
+
`)[0];t.push({name:"ripgrep",ok:!0,msg:r.replace("ripgrep ","")})}catch{t.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let n of t){let r=n.ok?a.green(" \u2705"):a.yellow(" \u26A0\uFE0F ");console.log(`${r} ${n.name}: ${a.dim(n.msg)}`)}console.log(""),console.log(a.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${a.cyan("mc auth login")}`),console.log(""),console.log(a.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${a.dim("Interactive:")} ${a.cyan("mc")} Open the REPL`),console.log(` ${a.dim("One-shot:")} ${a.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${a.dim("Background:")} ${a.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${a.dim("Health:")} ${a.cyan("mc doctor")} Check your setup`),console.log(` ${a.dim("Help:")} ${a.cyan("mc --help")} See all commands`),console.log(""),console.log(a.dim(" \u2500".repeat(30))),console.log(a.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),Ew()}l(Qm,"runOnboarding");var go=b(require("node:fs"),1),Xr=b(require("node:path"),1);X();var Zm=[];function tf(){process.on("uncaughtException",s=>{ef(s,"uncaughtException"),console.error(`
|
|
483
492
|
\u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${s.message}
|
|
484
|
-
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));
|
|
493
|
+
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));ef(e,"unhandledRejection")})}l(tf,"installCrashHandler");function Fw(){let s=A();return Xr.join(s.config,"crashes")}l(Fw,"getCrashDir");function ef(s,e){try{let t=Fw();go.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Xr.join(t,`${o}.log`),r=Ce(),c=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 0.1.8",`Node.js: ${process.version}`,`Platform: ${r.os} (${r.arch})`,`Shell: ${r.shell}`,`PID: ${process.pid}`,`Uptime: ${Math.round(process.uptime())}s`,`Memory: ${Math.round(process.memoryUsage().rss/1024/1024)} MB RSS`,"","\u2500\u2500 Error \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`Name: ${s.name}`,`Message: ${s.message}`,"","\u2500\u2500 Stack Trace \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",s.stack||"(no stack trace)","","\u2500\u2500 Recent Tool Calls (names only) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",Zm.length>0?Zm.map((u,d)=>` ${d+1}. ${u}`).join(`
|
|
485
494
|
`):" (none)","","\u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`TERM: ${process.env.TERM||"(not set)"}`,`CI: ${process.env.CI||"false"}`,`MONKEYSCODE_HEADLESS: ${process.env.MONKEYSCODE_HEADLESS||"false"}`,"","\u2550".repeat(60)," Submit this report: mc bug --attach-crash","\u2550".repeat(60),""].join(`
|
|
486
|
-
`);
|
|
495
|
+
`);go.writeFileSync(n,c),Tw(t,20)}catch{}}l(ef,"writeCrashReport");function Tw(s,e){try{let t=go.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)go.unlinkSync(Xr.join(s,t[o]))}catch{}}l(Tw,"pruneOldReports");var Me=b(require("node:fs"),1),Kt=b(require("node:path"),1),Rw=require("node:child_process");W();X();_e();var Aw="MEMORY.md",of=".monkeyscode";async function sf(s={}){let e=H(I()),t=A(),o=s.since||"7d";if(s.mode&&s.mode!=="consolidate"){await Ow(s.mode);return}console.log(),console.log(a.bold(" \u{1F4A4} Memory Consolidation")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let n=Kt.join(t.data,"sessions");if(!Me.existsSync(n)){console.log(` ${e.info} No sessions found. Use ${a.cyan("mc")} to create some first.`);return}let r=Pw(o),i=Me.readdirSync(n).filter(h=>h.endsWith(".json")).map(h=>({name:h,path:Kt.join(n,h),mtime:Me.statSync(Kt.join(n,h)).mtimeMs})).filter(h=>h.mtime>=r).sort((h,y)=>y.mtime-h.mtime);if(console.log(` Sessions reviewed: ${a.bold(String(i.length))} (last ${o})`),i.length===0){console.log(` ${e.info} No sessions in the last ${o}. Nothing to consolidate.`);return}let c=new Map;for(let h of i)try{let y=JSON.parse(Me.readFileSync(h.path,"utf8"));if(y.toolCalls){for(let S of y.toolCalls)if(S.tool==="file_edit"&&S.args?.path){let D=Kt.extname(S.args.path);if(D){let C=`Works primarily with ${D} files`;c.set(C,(c.get(C)||0)+1)}}}if(y.messages){let S=JSON.stringify(y.messages).toLowerCase();S.includes("vitest")&&Jt(c,"Uses vitest for testing"),S.includes("jest")&&Jt(c,"Uses jest for testing"),S.includes("mocha")&&Jt(c,"Uses mocha for testing"),S.includes("zod")&&Jt(c,"Uses Zod for runtime validation"),S.includes("joi")&&Jt(c,"Uses Joi for validation"),S.includes("tailwind")&&Jt(c,"Uses Tailwind CSS"),S.includes("styled-components")&&Jt(c,"Uses styled-components"),S.includes("result<")&&Jt(c,"Uses Result<T, E> pattern for error handling"),(S.includes("try/catch")||S.includes("try {"))&&Jt(c,"Uses try/catch for error handling")}}catch{}let u=Math.max(2,Math.floor(i.length*.3)),d=[];for(let[h,y]of c)y>=u&&d.push({rule:h,count:y});if(d.sort((h,y)=>y.count-h.count),d.length===0){console.log(` ${e.info} No strong patterns detected (need at least ${u} occurrences).`);return}console.log(" New conventions found:");for(let h of d)console.log(` ${e.success} "${h.rule}" (seen in ${h.count}/${i.length} sessions)`);if(s.review){console.log(),console.log(a.yellow(` ${e.info} Review mode \u2014 no changes written.`)),console.log(` Run ${a.cyan("mc dream")} (without --review) to write these.`);return}let p=Kt.join(process.cwd(),of,Aw);Me.mkdirSync(Kt.join(process.cwd(),of),{recursive:!0});let f="";Me.existsSync(p)&&(f=Me.readFileSync(p,"utf8"));let m=new Date().toISOString().split("T")[0],g=f.trimEnd();g||(g=`# Project Memory
|
|
487
496
|
|
|
488
497
|
> Auto-generated by \`mc dream\`. Edit freely.
|
|
489
498
|
`),g+=`
|
|
490
499
|
|
|
491
500
|
## Consolidated ${m} (${i.length} sessions)
|
|
492
501
|
|
|
493
|
-
`;for(let h of d){let
|
|
494
|
-
`)}
|
|
495
|
-
`),console.log(` Updated: ${a.cyan(p)}`),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(
|
|
502
|
+
`;for(let h of d){let y=`- ${h.rule}`;f.includes(h.rule)||(g+=y+`
|
|
503
|
+
`)}Me.writeFileSync(p,g.trimEnd()+`
|
|
504
|
+
`),console.log(` Updated: ${a.cyan(p)}`),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(sf,"dream");function Pw(s){let e=s.match(/^(\d+)([dhwm])$/);if(!e)return Date.now()-7*24*3600*1e3;let t=parseInt(e[1],10),o=e[2],n={d:24*3600*1e3,h:3600*1e3,w:7*24*3600*1e3,m:30*24*3600*1e3};return Date.now()-t*(n[o]||n.d)}l(Pw,"parseDuration");function Jt(s,e){s.set(e,(s.get(e)||0)+1)}l(Jt,"incr");var Mw={audit:{icon:"\u{1F512}",title:"Security & Dependency Audit",prompt:["Perform a comprehensive security and dependency audit of this project:","","1. Check for known vulnerabilities in dependencies (npm audit, pip audit, cargo audit)","2. Scan for hardcoded secrets, API keys, or credentials in source code","3. Identify unsafe patterns: eval(), SQL injection risks, XSS vectors, command injection","4. Check for outdated dependencies with known CVEs","5. Review file permissions and security-sensitive configurations","6. Check for insecure HTTP endpoints, missing CORS headers, etc.","","Output a structured report with severity levels (CRITICAL, HIGH, MEDIUM, LOW).","Write the report to .monkeyscode/dreams/audit-report.md"].join(`
|
|
496
505
|
`)},refactor:{icon:"\u{1F527}",title:"Refactoring Opportunities",prompt:["Analyze the codebase for refactoring opportunities:","","1. Find duplicated code (similar functions, copy-paste patterns)","2. Identify overly complex functions (high cyclomatic complexity)","3. Find god classes/modules that should be split","4. Detect dead code (unused exports, unreachable branches)","5. Identify missing abstractions (repeated patterns that could be generalized)","6. Find inconsistent naming conventions or code style","7. Suggest architectural improvements","","For each opportunity, provide: file, line range, description, suggested fix, and effort estimate.","Write the report to .monkeyscode/dreams/refactor-report.md"].join(`
|
|
497
506
|
`)},docs:{icon:"\u{1F4DD}",title:"Documentation Generation",prompt:["Analyze the codebase and generate or update documentation:","","1. Identify public APIs, exported functions, and classes that lack documentation","2. Generate JSDoc/docstrings for undocumented public interfaces","3. Update the project README if it's outdated or missing sections","4. Create a CONTRIBUTING.md if one doesn't exist","5. Generate an API reference summary","6. Document environment variables, configuration options, and CLI flags","","Write a summary of what you documented to .monkeyscode/dreams/docs-report.md","Actually update the source files with the documentation."].join(`
|
|
498
507
|
`)},"test-gaps":{icon:"\u{1F9EA}",title:"Test Coverage Gaps",prompt:["Analyze the codebase for untested code paths and missing test coverage:","","1. Find source files without corresponding test files","2. Identify exported functions/methods that are never tested","3. Find branches, edge cases, and error paths without test coverage","4. Check for missing integration tests (API endpoints, workflows)","5. Identify fragile tests (timing-dependent, order-dependent)","6. Suggest specific test cases that should be written","","For each gap, provide: source file, function, what to test, and priority (P0-P3).","Write the report to .monkeyscode/dreams/test-gaps-report.md"].join(`
|
|
499
|
-
`)}};async function Ow(s){let e=Mw[s];if(!e){console.log(a.red(` Unknown dream mode: ${s}`)),console.log(a.dim(" Available: --audit, --refactor, --docs, --test-gaps"));return}console.log(""),console.log(a.bold(` ${e.icon} Dream Mode: ${e.title}`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(" Running headless agent analysis...")),console.log("");let t=
|
|
500
|
-
`);if(t.length<=50)return[{content:s,startLine:1,endLine:t.length,type:"module"}];switch(e){case"typescript":case"javascript":case"go":case"rust":case"java":case"c":case"cpp":case"csharp":return Iw(t);case"python":return jw(t);default:return Nw(t,50)}}l(
|
|
508
|
+
`)}};async function Ow(s){let e=Mw[s];if(!e){console.log(a.red(` Unknown dream mode: ${s}`)),console.log(a.dim(" Available: --audit, --refactor, --docs, --test-gaps"));return}console.log(""),console.log(a.bold(` ${e.icon} Dream Mode: ${e.title}`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(" Running headless agent analysis...")),console.log("");let t=Kt.join(process.cwd(),".monkeyscode","dreams");Me.mkdirSync(t,{recursive:!0});let{AgentLoop:o}=await Promise.resolve().then(()=>(Ke(),es)),{loadSettings:n}=await Promise.resolve().then(()=>(Q(),Se)),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),ge)),i=n(),c=await r()||process.env.MC_API_KEY||"",u=new o({platformUrl:i.platformUrl,token:c,model:i.defaultModel||"capuchin-reason",workspace:process.cwd(),mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:!1,effort:"reasoning"}),d="",p=0;u.on("event",f=>{switch(f.type){case"streaming_chunk":d+=f.content,process.stdout.write(a.dim(f.content));break;case"run_complete":p=f.summary.tokensIn+f.summary.tokensOut;break}});try{await u.run(e.prompt),console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.green(` \u2705 Dream complete (${p.toLocaleString()} tokens)`)),console.log(a.dim(" Report: .monkeyscode/dreams/")),console.log("")}catch(f){console.log(a.red(` Dream failed: ${f instanceof Error?f.message:f}`))}}l(Ow,"dreamExtended");W();var Te=b(require("node:fs"),1),ft=b(require("node:path"),1),Zr=b(require("node:crypto"),1),zc=require("node:child_process");X();function nf(s,e){let t=s.split(`
|
|
509
|
+
`);if(t.length<=50)return[{content:s,startLine:1,endLine:t.length,type:"module"}];switch(e){case"typescript":case"javascript":case"go":case"rust":case"java":case"c":case"cpp":case"csharp":return Iw(t);case"python":return jw(t);default:return Nw(t,50)}}l(nf,"chunkCode");function Iw(s){let e=[],t=0,o=0,n="module";for(let r=0;r<s.length;r++){let i=s[r],c=i.trim();t===0&&(/^(?:export\s+)?(?:async\s+)?function\s/.test(c)||/^(?:export\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\(/.test(c)||/^\w+\s*\(/.test(c)?n="function":(/^(?:export\s+)?class\s/.test(c)||/^(?:export\s+)?interface\s/.test(c))&&(n="class"));for(let u of i)u==="{"?t++:u==="}"&&t--;if(t===0&&r>o&&(c.endsWith("}")||c==="}")){let u=s.slice(o,r+1);u.length>=5&&(e.push({content:u.join(`
|
|
501
510
|
`),startLine:o+1,endLine:r+1,type:n}),o=r+1,n="module")}r-o>=50&&t<=1&&(e.push({content:s.slice(o,r+1).join(`
|
|
502
511
|
`),startLine:o+1,endLine:r+1,type:n}),o=r+1,n="module")}if(o<s.length){let r=s.slice(o);r.some(i=>i.trim())&&e.push({content:r.join(`
|
|
503
512
|
`),startLine:o+1,endLine:s.length,type:"module"})}return e}l(Iw,"chunkByBraces");function jw(s){let e=[],t=0,o="module";for(let n=0;n<s.length;n++){let r=s[n].trim(),i=s[n].length-s[n].trimStart().length;i===0&&(r.startsWith("def ")||r.startsWith("async def "))?(n>t&&n-t>=5&&(e.push({content:s.slice(t,n).join(`
|
|
@@ -505,18 +514,18 @@ ${t}
|
|
|
505
514
|
`),startLine:t+1,endLine:n,type:o}),t=n),o="class"),n-t>=50&&(e.push({content:s.slice(t,n+1).join(`
|
|
506
515
|
`),startLine:t+1,endLine:n+1,type:o}),t=n+1,o="module")}return t<s.length&&e.push({content:s.slice(t).join(`
|
|
507
516
|
`),startLine:t+1,endLine:s.length,type:o}),e}l(jw,"chunkByIndentation");function Nw(s,e){let t=[];for(let o=0;o<s.length;o+=e){let n=s.slice(o,Math.min(o+e,s.length));t.push({content:n.join(`
|
|
508
|
-
`),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(Nw,"chunkByLines");var Qr=class{static{l(this,"EmbeddingIndex")}workspace;indexDir;opts;chunks=[];embeddings=null;embeddingDim=1536;fileShas=new Map;constructor(e,t){this.workspace=e,this.opts={embeddingModel:"text-embedding-3-small",batchSize:100,...t};let o=Zr.createHash("sha256").update(e).digest("hex").slice(0,12),n=
|
|
509
|
-
`).filter(o=>o&&t.has(ft.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,
|
|
510
|
-
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,
|
|
511
|
-
`).filter(Boolean)}catch{return this.listAllFiles()}}};var
|
|
512
|
-
`).filter(Boolean)}catch{return[]}}l(Ww,"listWorkspaceFiles");function Hw(s,e){try{let t=(0,
|
|
513
|
-
`).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(Hw,"getGitRecentFiles");function Gw(s,e){try{let t=
|
|
517
|
+
`),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(Nw,"chunkByLines");var Qr=class{static{l(this,"EmbeddingIndex")}workspace;indexDir;opts;chunks=[];embeddings=null;embeddingDim=1536;fileShas=new Map;constructor(e,t){this.workspace=e,this.opts={embeddingModel:"text-embedding-3-small",batchSize:100,...t};let o=Zr.createHash("sha256").update(e).digest("hex").slice(0,12),n=A();this.indexDir=ft.join(n.data,"indexes",o)}async index(){Te.mkdirSync(this.indexDir,{recursive:!0}),this.loadState();let e=this.listIndexableFiles(),t=e.filter(d=>this.getFileSha(d)!==this.fileShas.get(d));if(t.length===0)return this.getStats(e.length);let o=[];for(let d of t){let p=ft.join(this.workspace,d);if(!Te.existsSync(p))continue;let f=Te.readFileSync(p,"utf8"),m=this.detectLanguage(d),g=nf(f,m);for(let h of g)o.push({id:Zr.randomUUID(),file:d,startLine:h.startLine,endLine:h.endLine,content:h.content,language:m,fileSha:this.getFileSha(d)});this.fileShas.set(d,this.getFileSha(d))}let n=new Set(t);this.chunks=this.chunks.filter(d=>!n.has(d.file)),this.chunks.push(...o);let r=this.opts.batchSize||100,i=this.embeddings?this.float32ToArrays(this.embeddings,this.embeddingDim):[],c=this.chunks.map(d=>d.content),u=[];for(let d=0;d<c.length;d+=r){let p=c.slice(d,d+r),f=await this.embed(p);u.push(...f)}this.embeddings=new Float32Array(u.length*this.embeddingDim);for(let d=0;d<u.length;d++)this.embeddings.set(u[d],d*this.embeddingDim);return this.saveState(),this.getStats(e.length)}async search(e,t=10){if(!this.embeddings||this.chunks.length===0)return[];let o=await this.embed([e]);if(o.length===0)return[];let n=o[0],r=[];for(let i=0;i<this.chunks.length;i++){let c=i*this.embeddingDim,u=this.embeddings.slice(c,c+this.embeddingDim),d=this.cosineSimilarity(n,u);r.push({index:i,score:d})}return r.sort((i,c)=>c.score-i.score),r.slice(0,t).map(({index:i,score:c})=>{let u=this.chunks[i];return{file:u.file,chunk:u.content,startLine:u.startLine,endLine:u.endLine,score:c,language:u.language}})}status(){this.loadState();let e=this.listIndexableFiles();return this.getStats(e.length)}async rebuild(){return this.chunks=[],this.embeddings=null,this.fileShas.clear(),this.index()}async embed(e){try{let t=await fetch(`${this.opts.platformUrl}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.token}`},body:JSON.stringify({input:e,model:this.opts.embeddingModel})});if(!t.ok)throw new Error(`Embedding API error: ${t.status}`);let o=await t.json();return o.data.length>0&&(this.embeddingDim=o.data[0].embedding.length),o.data.map(n=>n.embedding)}catch{return e.map(()=>new Array(this.embeddingDim).fill(0))}}cosineSimilarity(e,t){let o=0,n=0,r=0;for(let c=0;c<e.length;c++)o+=e[c]*t[c],n+=e[c]*e[c],r+=t[c]*t[c];let i=Math.sqrt(n)*Math.sqrt(r);return i===0?0:o/i}float32ToArrays(e,t){let o=[];for(let n=0;n<e.length;n+=t)o.push(Array.from(e.slice(n,n+t)));return o}listIndexableFiles(){try{let e=(0,zc.execSync)("git ls-files --cached --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}),t=new Set([".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".hpp",".rb",".php",".swift",".kt",".scala",".cs",".vue",".svelte",".md",".mdx"]);return e.trim().split(`
|
|
518
|
+
`).filter(o=>o&&t.has(ft.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,zc.execSync)(`git hash-object ${e}`,{cwd:this.workspace,encoding:"utf8"}).trim()}catch{return""}}detectLanguage(e){return{".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".scala":"scala",".vue":"vue",".svelte":"svelte",".md":"markdown",".mdx":"markdown"}[ft.extname(e)]||"unknown"}saveState(){let e=ft.join(this.indexDir,"meta.json"),t=ft.join(this.indexDir,"vectors.bin");Te.writeFileSync(e,JSON.stringify({chunks:this.chunks,fileShas:Object.fromEntries(this.fileShas),embeddingDim:this.embeddingDim,lastIndexed:Date.now()})),this.embeddings&&Te.writeFileSync(t,Buffer.from(this.embeddings.buffer))}loadState(){let e=ft.join(this.indexDir,"meta.json"),t=ft.join(this.indexDir,"vectors.bin");if(Te.existsSync(e))try{let o=JSON.parse(Te.readFileSync(e,"utf8"));if(this.chunks=o.chunks||[],this.fileShas=new Map(Object.entries(o.fileShas||{})),this.embeddingDim=o.embeddingDim||1536,Te.existsSync(t)){let n=Te.readFileSync(t);this.embeddings=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4)}}catch{this.chunks=[],this.embeddings=null,this.fileShas.clear()}}getStats(e){let t=ft.join(this.indexDir,"vectors.bin"),o=Te.existsSync(t)?Te.statSync(t).size:0,n=e-this.fileShas.size;return{totalFiles:this.fileShas.size,totalChunks:this.chunks.length,indexSizeBytes:o,lastIndexed:Date.now(),pendingFiles:Math.max(0,n)}}};var xt=b(require("node:fs"),1),Le=b(require("node:path"),1),Jc=require("node:child_process");var vn=class{static{l(this,"ImportGraph")}forward=new Map;reverse=new Map;fileShas=new Map;workspace;lastUpdated=0;constructor(e){this.workspace=e}async build(){let e=this.lastUpdated===0?this.listAllFiles():this.getChangedFiles();for(let t of e)this.parseFile(t);return this.lastUpdated=Date.now(),this.getStats()}dependentsOf(e){return[...this.reverse.get(e)||[]]}dependenciesOf(e){return[...this.forward.get(e)||[]]}transitiveImports(e,t=5){let o=new Set,n=[{file:e,depth:0}];for(;n.length>0;){let{file:r,depth:i}=n.shift();if(!(o.has(r)||i>t)){o.add(r);for(let c of this.dependenciesOf(r))o.has(c)||n.push({file:c,depth:i+1})}}return o.delete(e),[...o]}relatedFiles(e,t=20){let o=new Map;for(let n of e){for(let r of this.dependenciesOf(n))o.set(r,(o.get(r)||0)+3);for(let r of this.dependentsOf(n))o.set(r,(o.get(r)||0)+2);for(let r of this.dependenciesOf(n))for(let i of this.dependenciesOf(r))e.includes(i)||o.set(i,(o.get(i)||0)+1)}for(let n of e)o.delete(n);return[...o.entries()].sort((n,r)=>r[1]-n[1]).slice(0,t).map(([n])=>n)}getStats(){let e=new Map;for(let c of this.reverse.values())for(let u of c)e.set(u,(e.get(u)||0)+1);let t=new Map;for(let[c,u]of this.reverse)t.set(c,u.size);let o=[...t.entries()].sort((c,u)=>u[1]-c[1]).slice(0,10).map(([c,u])=>({file:c,count:u})),n=new Set([...this.forward.keys(),...this.reverse.keys()]),r=[...this.forward.keys()].filter(c=>(this.forward.get(c)?.size||0)===0&&(this.reverse.get(c)?.size||0)===0).length,i=0;for(let c of this.forward.values())i+=c.size;return{totalFiles:n.size,totalEdges:i,orphanFiles:r,mostImported:o,lastUpdated:this.lastUpdated}}parseFile(e){let t=Le.join(this.workspace,e);if(!xt.existsSync(t)){this.forward.delete(e);return}let o=xt.readFileSync(t,"utf8"),n=Le.extname(e),r=[];[".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(n)?r=this.parseTsImports(e,o):n===".py"?r=this.parsePyImports(e,o):n===".go"&&(r=this.parseGoImports(e,o));let i=this.forward.get(e);if(i)for(let u of i)this.reverse.get(u)?.delete(e);let c=new Set(r);this.forward.set(e,c);for(let u of c)this.reverse.has(u)||this.reverse.set(u,new Set),this.reverse.get(u).add(e)}parseTsImports(e,t){let o=[],n=Le.dirname(e),r=/(?:import|export)\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;){let d=this.resolveTs(n,i[1]);d&&o.push(d)}let c=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(i=c.exec(t))!==null;){let d=this.resolveTs(n,i[1]);d&&o.push(d)}let u=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(i=u.exec(t))!==null;){let d=this.resolveTs(n,i[1]);d&&o.push(d)}return o}parsePyImports(e,t){let o=[],n=/^(?:from\s+(\S+)|import\s+(\S+))/gm,r;for(;(r=n.exec(t))!==null;){let i=(r[1]||r[2]).replace(/\./g,"/"),c=[`${i}.py`,`${i}/__init__.py`];for(let u of c)if(xt.existsSync(Le.join(this.workspace,u))){o.push(u);break}}return o}parseGoImports(e,t){let o=[],n=Le.dirname(e),r=this.getGoModulePath(),i=/^import\s+"([^"]+)"/gm,c;for(;(c=i.exec(t))!==null;){let d=this.resolveGoImport(c[1],r);d&&o.push(d)}let u=/^import\s*\(([\s\S]*?)\)/gm;for(;(c=u.exec(t))!==null;){let d=c[1],p=/"([^"]+)"/g,f;for(;(f=p.exec(d))!==null;){let m=this.resolveGoImport(f[1],r);m&&o.push(m)}}return o}goModulePath=void 0;getGoModulePath(){if(this.goModulePath!==void 0)return this.goModulePath;try{let e=Le.join(this.workspace,"go.mod");if(xt.existsSync(e)){let o=xt.readFileSync(e,"utf8").match(/^module\s+(\S+)/m);this.goModulePath=o?o[1]:null}else this.goModulePath=null}catch{this.goModulePath=null}return this.goModulePath}resolveGoImport(e,t){if(!e.includes(".")&&!e.includes("/"))return null;if(t&&e.startsWith(t)){let o=e.slice(t.length+1),n=Le.join(this.workspace,o);if(xt.existsSync(n))return o}return null}resolveTs(e,t){if(!t.startsWith("."))return null;let o=Le.join(e,t),n=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let r of n){let i=o+r;if(xt.existsSync(Le.join(this.workspace,i)))return i}if(t.endsWith(".js")){let r=Le.join(e,t.replace(/\.js$/,".ts"));if(xt.existsSync(Le.join(this.workspace,r)))return r}return null}listAllFiles(){try{return(0,Jc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
519
|
+
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,Jc.execSync)("git diff --name-only HEAD~5",{cwd:this.workspace,encoding:"utf8"}).trim().split(`
|
|
520
|
+
`).filter(Boolean)}catch{return this.listAllFiles()}}};var Ds=b(require("node:fs"),1),de=b(require("node:path"),1),Kc=require("node:child_process");var Sn={KEYWORD_MATCH:.3,GIT_RECENCY:.25,IMPORT_GRAPH:.2,TEST_PAIR:.15,CONFIG_PROXIMITY:.1},Lw=new Set(["package.json","tsconfig.json","tsconfig.build.json","Cargo.toml","pyproject.toml","go.mod",".eslintrc.json",".prettierrc","vite.config.ts","webpack.config.js","jest.config.ts","vitest.config.ts"]);function rf(s,e){let t=new Map,o=Bw(s),n=e.maxResults||30,r=Ww(e.workspace);for(let i of r){let c=Uw(i,o);c>0&&xn(t,i,c*Sn.KEYWORD_MATCH,`Matches: ${o.filter(u=>i.toLowerCase().includes(u)).join(", ")}`)}if(e.useGitRecency!==!1){let i=Hw(e.workspace,50);for(let c=0;c<i.length;c++){let u=1-c/i.length;xn(t,i[c],u*Sn.GIT_RECENCY,`Git recency: #${c+1}`)}}if(e.activeFiles&&e.activeFiles.length>0)for(let i of e.activeFiles){let c=Gw(e.workspace,i);for(let u of c)xn(t,u,Sn.IMPORT_GRAPH,`Imported by ${de.basename(i)}`)}for(let i of r){let c=Vw(i);c&&t.has(i)&&xn(t,c,Sn.TEST_PAIR,`Test pair of ${de.basename(i)}`)}for(let i of r)if(Lw.has(de.basename(i))){let c=de.dirname(i);[...t.keys()].some(d=>de.dirname(d)===c)&&xn(t,i,Sn.CONFIG_PROXIMITY,"Config file near relevant code")}return[...t.entries()].map(([i,{score:c,reasons:u}])=>({path:i,score:Math.min(c,1),reasons:u})).sort((i,c)=>c.score-i.score).slice(0,n)}l(rf,"rankFiles");function xn(s,e,t,o){let n=s.get(e)||{score:0,reasons:[]};n.score+=t,n.reasons.push(o),s.set(e,n)}l(xn,"addScore");function Bw(s){let e=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","this","that","it","all","and","or","but","not","no","if","then","else","when","up","so","fix","add","remove","update","change","make","create"]);return s.toLowerCase().replace(/[^a-z0-9_\-./]/g," ").split(/\s+/).filter(t=>t.length>2&&!e.has(t))}l(Bw,"extractKeywords");function Uw(s,e){let t=s.toLowerCase(),o=0;for(let n of e)t.includes(n)&&o++;return e.length>0?o/e.length:0}l(Uw,"keywordScore");function Ww(s){try{return(0,Kc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:s,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
521
|
+
`).filter(Boolean)}catch{return[]}}l(Ww,"listWorkspaceFiles");function Hw(s,e){try{let t=(0,Kc.execSync)(`git log --name-only --format="" -n ${e*2} | head -n ${e}`,{cwd:s,encoding:"utf8",maxBuffer:1e6}),o=new Set;return t.trim().split(`
|
|
522
|
+
`).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(Hw,"getGitRecentFiles");function Gw(s,e){try{let t=Ds.readFileSync(de.join(s,e),"utf8"),o=[],n=/(?:import|require)\s*\(?['"]([^'"]+)['"]\)?/g,r;for(;(r=n.exec(t))!==null;){let c=r[1];if(c.startsWith(".")){let u=de.dirname(e),d=qw(s,de.join(u,c));d&&o.push(d)}}let i=/^(?:from|import)\s+(\S+)/gm;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\./g,"/"),u=[`${c}.py`,`${c}/__init__.py`];for(let d of u)if(Ds.existsSync(de.join(s,d))){o.push(d);break}}return o}catch{return[]}}l(Gw,"parseImportsQuick");function qw(s,e){let t=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let o of t){let n=e+o;if(Ds.existsSync(de.join(s,n)))return n}return Ds.existsSync(de.join(s,e))?e:null}l(qw,"resolveImport");function Vw(s){let e=de.extname(s),t=de.basename(s,e),o=de.dirname(s);if(t.endsWith(".test")||t.endsWith(".spec")){let r=t.replace(/\.(test|spec)$/,"");return de.join(o,r+e)}return[de.join(o,`${t}.test${e}`),de.join(o,`${t}.spec${e}`),de.join(o,"__tests__",`${t}${e}`)].find(()=>!0)||null}l(Vw,"findTestPair");Q();_e();async function Bo(s,e){let t=s[0]||"status",o=process.cwd(),n=K(),r=H(I());switch(t){case"index":await zw(o,n);break;case"search":await Jw(o,n,s.slice(1).join(" "));break;case"status":await Kw(o,n);break;case"rebuild":await Yw(o,n);break;case"related":await Xw(o,s[1]);break;case"rank":Qw(o,s.slice(1).join(" "));break;default:console.log(a.red(`Unknown subcommand: ${t}`)),console.log(""),console.log("Usage:"),console.log(" mc context index Index the workspace"),console.log(' mc context search "query" Semantic search'),console.log(" mc context status Show index status"),console.log(" mc context rebuild Force full re-index"),console.log(" mc context related <file> Find related files"),console.log(' mc context rank "prompt" Rank files by relevance')}}l(Bo,"contextCommand");async function zw(s,e){console.log(a.cyan(" \u26A1 Indexing workspace...")),console.log(a.dim(` ${s}`)),console.log("");let t=Date.now(),n=await ei(s,e).index(),r=((Date.now()-t)/1e3).toFixed(1);console.log(a.green(" \u2705 Index complete")),console.log(` Files: ${a.bold(String(n.totalFiles))}`),console.log(` Chunks: ${a.bold(String(n.totalChunks))}`),console.log(` Size: ${a.bold(af(n.indexSizeBytes))}`),console.log(` Time: ${a.bold(r+"s")}`),console.log("")}l(zw,"contextIndex");async function Jw(s,e,t){if(!t){console.log(a.red(' Usage: mc context search "your query"'));return}console.log(a.cyan(` \u{1F50D} Searching: "${t}"`)),console.log("");let n=await ei(s,e).search(t,10);if(n.length===0){console.log(a.yellow(" No results found. Run `mc context index` first."));return}for(let r=0;r<n.length;r++){let i=n[r],c="\u2588".repeat(Math.round(i.score*10))+"\u2591".repeat(10-Math.round(i.score*10));console.log(` ${a.bold(`${r+1}.`)} ${a.cyan(i.file)}${a.dim(`:${i.startLine}-${i.endLine}`)}`),console.log(` ${a.dim(c)} ${(i.score*100).toFixed(0)}%`);let u=i.chunk.split(`
|
|
514
523
|
`).slice(0,2).map(d=>` ${a.dim(d.substring(0,80))}`).join(`
|
|
515
|
-
`);console.log(u),console.log("")}}l(Jw,"contextSearch");async function Kw(s,e){let o=ei(s,e).status();console.log(""),console.log(a.bold(" Context Index Status")),console.log(` ${"\u2500".repeat(50)}`),console.log(` Files indexed: ${a.bold(String(o.totalFiles))}`),console.log(` Chunks: ${a.bold(String(o.totalChunks))}`),console.log(` Index size: ${a.bold(
|
|
516
|
-
`)}l(
|
|
517
|
-
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(rk,"triggersServe");
|
|
518
|
-
`)[0].slice(0,80);console.log(` ${a.blue("\u{1F4AD}")} ${a.blue("Thinking")}${t}`),n&&console.log(` ${a.dim(n)}`);break}case"tool_call":{let n=pk(s.tool||"");console.log(` ${n} ${a.green(s.tool||"unknown")}${o}${t}`),s.resultPreview&&e&&console.log(` ${a.dim(s.resultPreview.slice(0,100))}`);break}case"context_compact":console.log(` ${a.yellow("\u{1F4E6}")} ${a.yellow("Context Compacted")}${t}`);break;case"error":console.log(` ${a.red("\u274C")} ${a.red("Error")}: ${s.content}`);break}}l(ck,"renderTurn");function lk(s){console.log(a.bold(" Decision Tree")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log();let e=0;for(let t of s.turns){let o=" "+" ".repeat(e),n=t.tokens?a.dim(` [${
|
|
519
|
-
`)[0].slice(0,70);console.log(`${o}${a.dim("\u2502 "+i)}`)}e=Math.min(e+1,4);break;case"tool_call":console.log(`${o}${a.green("\u251C\u2500 \u{1F527} "+(t.tool||"tool"))}${r}`),t.resultPreview&&console.log(`${o}${a.dim("\u2502 \u2192 "+t.resultPreview.slice(0,60))}`);break;case"context_compact":e=Math.max(0,e-1),console.log(`${o}${a.yellow("\u251C\u2500 \u{1F4E6} Compact")}${n}`);break;case"error":console.log(`${o}${a.red("\u2514\u2500 \u274C Error")}: ${t.content}`);break}}console.log()}l(lk,"renderTree");function uk(s){let e=Object.entries(s.fileAccessGraph);if(e.length!==0){console.log(a.bold(" File Access")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(),e.sort((t,o)=>o[1].reads+o[1].writes-(t[1].reads+t[1].writes));for(let[t,o]of e.slice(0,20)){let n=o.reads>0?a.blue(`${o.reads}R`):"",r=o.writes>0?a.green(`${o.writes}W`):"",i=n&&r?" ":"",c="\u2588".repeat(Math.min(o.reads+o.writes,20)),u=o.writes>0?a.green(c):a.blue(c);console.log(` ${u} ${n}${i}${r} ${a.dim(t)}`)}e.length>20&&console.log(a.dim(` ... and ${e.length-20} more files`)),console.log()}}l(uk,"renderFileGraph");function dk(s){if(s.summary){let e=s.summary.filesModified;if(e.length>0){console.log(a.bold(" Files Modified")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));for(let t of e.slice(0,15))console.log(` ${a.green("\u270F\uFE0F")} ${t}`);e.length>15&&console.log(a.dim(` ... and ${e.length-15} more`)),console.log()}}console.log(a.dim("\u2501".repeat(60))),console.log()}l(dk,"renderFooter");function pk(s){return s.includes("read")||s.includes("view")||s.includes("grep")?"\u{1F4D6}":s.includes("write")||s.includes("edit")||s.includes("create")?"\u270F\uFE0F":s.includes("bash")||s.includes("exec")||s.includes("run")?"\u26A1":s.includes("search")||s.includes("web")?"\u{1F50D}":s.includes("delete")||s.includes("remove")?"\u{1F5D1}\uFE0F":"\u{1F527}"}l(pk,"getToolIcon");function
|
|
524
|
+
`);console.log(u),console.log("")}}l(Jw,"contextSearch");async function Kw(s,e){let o=ei(s,e).status();console.log(""),console.log(a.bold(" Context Index Status")),console.log(` ${"\u2500".repeat(50)}`),console.log(` Files indexed: ${a.bold(String(o.totalFiles))}`),console.log(` Chunks: ${a.bold(String(o.totalChunks))}`),console.log(` Index size: ${a.bold(af(o.indexSizeBytes))}`),console.log(` Pending files: ${o.pendingFiles>0?a.yellow(String(o.pendingFiles)):a.green("0")}`),console.log(` Last indexed: ${o.lastIndexed?a.dim(new Date(o.lastIndexed).toLocaleString()):a.dim("never")}`),console.log(` ${"\u2500".repeat(50)}`),console.log(""),o.pendingFiles>0&&(console.log(a.dim(" Run `mc context index` to index pending files.")),console.log(""));let r=await new vn(s).build();if(console.log(a.bold(" Import Graph")),console.log(` ${"\u2500".repeat(50)}`),console.log(` Files: ${a.bold(String(r.totalFiles))}`),console.log(` Edges: ${a.bold(String(r.totalEdges))}`),console.log(` Orphans: ${a.bold(String(r.orphanFiles))}`),r.mostImported.length>0){console.log(" Most imported:");for(let i of r.mostImported.slice(0,5))console.log(` ${a.cyan(i.file)} ${a.dim(`(${i.count} importers)`)}`)}console.log(` ${"\u2500".repeat(50)}`),console.log("")}l(Kw,"contextStatus");async function Yw(s,e){console.log(a.yellow(" \u{1F504} Rebuilding index from scratch...")),console.log("");let t=Date.now(),n=await ei(s,e).rebuild(),r=((Date.now()-t)/1e3).toFixed(1);console.log(a.green(" \u2705 Rebuild complete")),console.log(` Files: ${a.bold(String(n.totalFiles))}`),console.log(` Chunks: ${a.bold(String(n.totalChunks))}`),console.log(` Time: ${a.bold(r+"s")}`),console.log("")}l(Yw,"contextRebuild");async function Xw(s,e){if(!e){console.log(a.red(" Usage: mc context related <file>"));return}let t=new vn(s);await t.build();let o=t.relatedFiles([e],15);if(console.log(""),console.log(a.bold(` Files related to ${a.cyan(e)}`)),console.log(` ${"\u2500".repeat(50)}`),o.length===0)console.log(a.dim(" No related files found."));else{let n=t.dependenciesOf(e),r=new Set(n),i=t.dependentsOf(e),c=new Set(i);for(let u of o){let d="";r.has(u)?d=a.blue("\u2190 imports"):c.has(u)?d=a.green("\u2192 imported by"):d=a.dim("\u223C related"),console.log(` ${a.cyan(u)} ${d}`)}}console.log(` ${"\u2500".repeat(50)}`),console.log("")}l(Xw,"contextRelated");function Qw(s,e){if(!e){console.log(a.red(' Usage: mc context rank "your prompt"'));return}let t=rf(e,{workspace:s,maxResults:15});console.log(""),console.log(a.bold(` File relevance for: "${e}"`)),console.log(` ${"\u2500".repeat(60)}`);for(let o of t){let n="\u2588".repeat(Math.round(o.score*20))+"\u2591".repeat(20-Math.round(o.score*20));console.log(` ${n} ${(o.score*100).toFixed(0).padStart(3)}% ${a.cyan(o.path)}`),console.log(a.dim(` ${o.reasons.join(", ")}`))}console.log(` ${"\u2500".repeat(60)}`),console.log("")}l(Qw,"contextRank");function ei(s,e){return new Qr(s,{platformUrl:e.platformUrl,token:process.env.MC_API_KEY||"",embeddingModel:"text-embedding-3-small"})}l(ei,"createIndex");function af(s){if(s===0)return"0 B";let e=["B","KB","MB","GB"],t=Math.floor(Math.log(s)/Math.log(1024));return(s/Math.pow(1024,t)).toFixed(1)+" "+e[t]}l(af,"formatBytes");var ho=b(require("node:fs"),1),_n=b(require("node:path"),1);W();_e();Q();var yf=".monkeyscode/triggers.json";async function yo(s,e){let t=s[0]||"list",o=process.cwd();switch(t){case"list":Zw(o);break;case"add":ek(o,e);break;case"remove":tk(o,s[1]);break;case"test":ok(o,s[1]);break;case"enable":hf(o,s[1],!0);break;case"disable":hf(o,s[1],!1);break;case"serve":await rk(o,e);break;default:nk()}}l(yo,"triggersCommand");function Zw(s){let e=En(s),t=H(I());if(console.log(""),console.log(a.bold(" Event Triggers")),console.log(` ${"\u2500".repeat(70)}`),e.length===0){console.log(a.dim(" No triggers configured.")),console.log(a.dim(' Add one: mc triggers add --event cron --schedule "0 9 * * *" --prompt "Run tests"')),console.log(` ${"\u2500".repeat(70)}`),console.log("");return}for(let o of e){let r=o.enabled!==!1?"\u{1F7E2}":"\u{1F534}",i=o.event==="cron"?`${o.event} (${o.schedule})`:o.event;console.log(` ${r} ${a.bold(o.name.padEnd(20))} ${a.cyan(i.padEnd(30))} ${a.dim(o.model||"default")}`),console.log(a.dim(` Prompt: "${o.prompt.substring(0,60)}${o.prompt.length>60?"...":""}"`)),o.filter&&console.log(a.dim(` Filter: ${JSON.stringify(o.filter)}`)),o.cooldownSeconds&&console.log(a.dim(` Cooldown: ${o.cooldownSeconds}s`))}console.log(` ${"\u2500".repeat(70)}`),console.log(a.dim(` ${e.length} trigger(s) configured`)),console.log("")}l(Zw,"triggersList");function ek(s,e){let t=e.event,o=e.prompt,n=e.name||sk(t,o),r=e.model,i=e.schedule,c=e.cooldown?parseInt(e.cooldown,10):void 0;if(!t||!o){console.log(a.red(" Missing required flags: --event and --prompt")),console.log(""),console.log(" Example:"),console.log(' mc triggers add --event cron --schedule "0 9 * * 1-5" --prompt "Run security audit"'),console.log(' mc triggers add --event github.check_run.failed --prompt "Fix the failing CI"');return}if(t==="cron"&&!i){console.log(a.red(" Cron triggers require --schedule"));return}let u={name:n,event:t,prompt:o,model:r,schedule:i,cooldownSeconds:c,enabled:!0},d=En(s);if(d.some(p=>p.name===n)){console.log(a.red(` Trigger "${n}" already exists. Use a different --name.`));return}d.push(u),Zc(s,d),console.log(a.green(` \u2705 Trigger "${n}" added`)),console.log(a.dim(` Event: ${t}`)),console.log(a.dim(` Prompt: "${o.substring(0,60)}"`)),i&&console.log(a.dim(` Schedule: ${i}`)),console.log("")}l(ek,"triggersAdd");function tk(s,e){if(!e){console.log(a.red(" Usage: mc triggers remove <trigger-name>"));return}let t=En(s),o=t.findIndex(n=>n.name===e);if(o===-1){console.log(a.red(` Trigger "${e}" not found.`));return}t.splice(o,1),Zc(s,t),console.log(a.green(` \u2705 Trigger "${e}" removed`)),console.log("")}l(tk,"triggersRemove");function ok(s,e){if(!e){console.log(a.red(" Usage: mc triggers test <trigger-name>"));return}let o=En(s).find(n=>n.name===e);if(!o){console.log(a.red(` Trigger "${e}" not found.`));return}console.log(""),console.log(a.bold(` \u{1F9EA} Dry Run: ${e}`)),console.log(` ${"\u2500".repeat(50)}`),console.log(` Event: ${a.cyan(o.event)}`),console.log(` Model: ${o.model||"default"}`),console.log(" Prompt:"),console.log(a.dim(` ${o.prompt}`)),o.filter&&console.log(` Filter: ${JSON.stringify(o.filter)}`),o.schedule&&console.log(` Schedule: ${o.schedule}`),console.log(` ${"\u2500".repeat(50)}`),console.log(a.green(" \u2705 Trigger would fire successfully")),console.log("")}l(ok,"triggersTest");function hf(s,e,t){if(!e){console.log(a.red(` Usage: mc triggers ${t?"enable":"disable"} <trigger-name>`));return}let o=En(s),n=o.find(r=>r.name===e);if(!n){console.log(a.red(` Trigger "${e}" not found.`));return}n.enabled=t,Zc(s,o),console.log(a.green(` \u2705 Trigger "${e}" ${t?"enabled":"disabled"}`)),console.log("")}l(hf,"triggersToggle");function En(s){let e=_n.join(s,yf);if(!ho.existsSync(e))return[];try{return JSON.parse(ho.readFileSync(e,"utf8")).triggers||[]}catch{return[]}}l(En,"loadTriggers");function Zc(s,e){let t=_n.join(s,yf),o=_n.dirname(t);ho.mkdirSync(o,{recursive:!0}),ho.writeFileSync(t,JSON.stringify({triggers:e},null,2)+`
|
|
525
|
+
`)}l(Zc,"saveTriggers");function sk(s,e){let t=e.toLowerCase().split(/\s+/).slice(0,3).join("-").replace(/[^a-z0-9-]/g,"");return`${s.replace(/\./g,"-")}-${t}`}l(sk,"generateName");function nk(){console.log(""),console.log(a.bold(" mc triggers \u2014 Event-driven agent triggers")),console.log(""),console.log(" Usage:"),console.log(" mc triggers list Show configured triggers"),console.log(" mc triggers add --event <type> --prompt Add a trigger"),console.log(" mc triggers remove <name> Remove a trigger"),console.log(" mc triggers test <name> Dry-run a trigger"),console.log(" mc triggers enable <name> Enable a trigger"),console.log(" mc triggers disable <name> Disable a trigger"),console.log(" mc triggers serve Start trigger daemon"),console.log(""),console.log(" Events:"),console.log(" cron Schedule-based (requires --schedule)"),console.log(" file.changed File system changes"),console.log(" github.push Git push events"),console.log(" github.pull_request.opened PR opened"),console.log(" github.check_run.failed CI check failed"),console.log(""),console.log(" Example:"),console.log(' mc triggers add --event cron --schedule "0 2 * * *" --prompt "Run nightly security audit"'),console.log(" mc triggers serve --port 9122"),console.log("")}l(nk,"printHelp");async function rk(s,e){let{TriggerEngine:t}=await Promise.resolve().then(()=>(pf(),df)),{GitHubWebhookServer:o}=await Promise.resolve().then(()=>(gf(),ff)),n=K(),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),ge)),i=await r()||process.env.MC_API_KEY||"",c=parseInt(String(e.port||"9122"),10);console.log(""),console.log(a.bold(" \u26A1 MonkeysCode Trigger Daemon")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let u=new t({workspace:s,token:i,model:n.defaultModel||"capuchin-reason",cooldownSeconds:300});u.on("started",f=>{console.log(a.green(` \u2713 Loaded ${f.triggerCount} trigger(s)`))}),u.on("trigger.fired",f=>{console.log(a.cyan(` \u26A1 Trigger fired: ${f.name} [${f.event}]`))}),u.on("trigger.completed",f=>{console.log(a.green(` \u2705 Completed: ${f.name}`))}),u.on("trigger.failed",f=>{console.log(a.red(` \u274C Failed: ${f.name} \u2014 ${f.error}`))}),u.start();let p=u.loadTriggers().filter(f=>f.event.startsWith("github."));if(p.length>0){let f=process.env.MC_WEBHOOK_SECRET;await new o({port:c,secret:f,onEvent:l(async g=>{console.log(a.cyan(` \u{1F514} GitHub event: ${g.event}`)),await u.processEvent({type:`github.${g.event}`,payload:g.payload,source:"github-webhook",timestamp:Date.now()})},"onEvent")}).start(),console.log(a.dim(` \u{1F514} Webhook server: http://localhost:${c} (${p.length} trigger(s))`))}console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.green(" Trigger daemon running. Press Ctrl+C to stop.")),console.log(""),await new Promise(f=>{let m=l(()=>{console.log(a.dim(`
|
|
526
|
+
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(rk,"triggersServe");W();W();var Sf=require("node:child_process");var Be=b(require("node:fs"),1),bo=b(require("node:path"),1),bf=b(require("node:crypto"),1);X();var Ss=class s{static{l(this,"TraceRecorder")}trace;turnIndex=0;currentToolStart=null;currentToolName=null;thinkingBuffer="";tracesDir;constructor(e){let t=A(ve());this.tracesDir=bo.join(t.data,"traces"),Be.mkdirSync(this.tracesDir,{recursive:!0}),this.trace={runId:e.runId||bf.randomUUID(),model:e.model,prompt:e.prompt,workspace:e.workspace,startedAt:new Date().toISOString(),durationMs:0,totalCostUsd:0,tokensIn:0,tokensOut:0,tokensCached:0,turns:[],fileAccessGraph:{}}}get runId(){return this.trace.runId}attach(e){e.on("event",t=>this.handleEvent(t))}handleEvent(e){let t=Date.now();switch(e.type){case"streaming_start":this.thinkingBuffer="";break;case"streaming_chunk":this.thinkingBuffer+=e.content||"";break;case"streaming_end":{this.thinkingBuffer.trim()&&this.trace.turns.push({index:this.turnIndex++,type:"thinking",timestamp:t,content:this.thinkingBuffer,tokens:this.estimateTokens(this.thinkingBuffer)}),this.thinkingBuffer="";break}case"tool_call_start":this.currentToolStart=t,this.currentToolName=e.name,this.trackFileAccess(e.name,e.args);break;case"tool_call_result":{let o=this.currentToolStart?t-this.currentToolStart:0,n=(e.result||"").slice(0,200);this.trace.turns.push({index:this.turnIndex++,type:"tool_call",timestamp:this.currentToolStart||t,durationMs:o,tool:e.name||this.currentToolName||"unknown",result:e.result,resultPreview:n+(e.result?.length>200?"...":"")}),this.currentToolStart=null,this.currentToolName=null;break}case"context_compacted":this.trace.turns.push({index:this.turnIndex++,type:"context_compact",timestamp:t,tokens:e.savedTokens,content:`Compacted: elided ${e.elided} messages, saved ${e.savedTokens} tokens`});break;case"state_update":e.state&&(this.trace.tokensIn=e.state.tokensIn||0,this.trace.tokensOut=e.state.tokensOut||0,this.trace.tokensCached=e.state.tokensCached||0,this.trace.totalCostUsd=e.state.costUsd||0);break;case"run_complete":this.finalize(e.summary);break;case"run_error":this.trace.turns.push({index:this.turnIndex++,type:"error",timestamp:t,content:e.error}),this.finalize();break}}finalize(e){this.trace.completedAt=new Date().toISOString(),this.trace.durationMs=Date.now()-new Date(this.trace.startedAt).getTime();let t=this.trace.turns.filter(n=>n.type==="thinking"),o=this.trace.turns.filter(n=>n.type==="tool_call");this.trace.summary={turnsCount:this.trace.turns.length,toolCallsCount:o.length,filesModified:e?.filesModified||Object.keys(this.trace.fileAccessGraph).filter(n=>this.trace.fileAccessGraph[n].writes>0),thinkingTokens:t.reduce((n,r)=>n+(r.tokens||0),0),toolTokens:o.reduce((n,r)=>n+(r.tokens||0),0)},e&&(this.trace.tokensIn=e.tokensIn||this.trace.tokensIn,this.trace.tokensOut=e.tokensOut||this.trace.tokensOut,this.trace.totalCostUsd=e.costUsd||this.trace.totalCostUsd),this.save()}save(){let e=bo.join(this.tracesDir,`${this.trace.runId}.json`);Be.writeFileSync(e,JSON.stringify(this.trace,null,2))}getTrace(){return this.trace}trackFileAccess(e,t){if(!t)return;let o=t.path||t.file||t.filePath||t.target;if(!o)return;this.trace.fileAccessGraph[o]||(this.trace.fileAccessGraph[o]={reads:0,writes:0});let n=["read_file","grep_search","view_file","list_dir"],r=["write_file","edit_file","replace_file","create_file","delete_file"];n.some(i=>e.includes(i))?this.trace.fileAccessGraph[o].reads++:r.some(i=>e.includes(i))&&this.trace.fileAccessGraph[o].writes++}estimateTokens(e){return Math.ceil(e.length/4)}static load(e){let t=A(ve()),o=bo.join(t.data,"traces"),n=bo.join(o,`${e}.json`);if(!Be.existsSync(n))return null;try{return JSON.parse(Be.readFileSync(n,"utf8"))}catch{return null}}static list(e=20){let t=A(ve()),o=bo.join(t.data,"traces");return Be.existsSync(o)?Be.readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=Be.statSync(bo.join(o,r));return{file:r,mtime:i.mtimeMs}}).sort((r,i)=>i.mtime-r.mtime).slice(0,e).map(r=>{try{let i=JSON.parse(Be.readFileSync(bo.join(o,r.file),"utf8"));return{runId:i.runId,model:i.model,prompt:i.prompt.slice(0,80),date:i.startedAt,cost:i.totalCostUsd}}catch{return null}}).filter(Boolean):[]}static lastRunId(){let e=s.list(1);return e.length>0?e[0].runId:null}};W();function wf(s,e={}){ik(s),e.tree?lk(s):ak(s,e.verbose),uk(s),dk(s)}l(wf,"renderTrace");function ik(s){let e=(s.durationMs/1e3).toFixed(1),t=s.totalCostUsd.toFixed(4),o=Object.keys(s.fileAccessGraph).length;console.log(),console.log(a.bold.cyan("\u2501".repeat(60))),console.log(a.bold.cyan(" Agent Trace")),console.log(a.bold.cyan("\u2501".repeat(60))),console.log(),console.log(` ${a.dim("Run ID:")} ${s.runId}`),console.log(` ${a.dim("Model:")} ${a.yellow(s.model)}`),console.log(` ${a.dim("Prompt:")} ${s.prompt.slice(0,60)}${s.prompt.length>60?"...":""}`),console.log(` ${a.dim("Duration:")} ${a.white(e+"s")}`),console.log(` ${a.dim("Cost:")} ${a.green("$"+t)}`),console.log(` ${a.dim("Tokens:")} ${a.white(Fn(s.tokensIn))} in / ${a.white(Fn(s.tokensOut))} out${s.tokensCached?` / ${a.dim(Fn(s.tokensCached)+" cached")}`:""}`),console.log(` ${a.dim("Files:")} ${o} accessed`),console.log(` ${a.dim("Turns:")} ${s.turns.length}`),console.log()}l(ik,"renderHeader");function ak(s,e){console.log(a.bold(" Timeline")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log();for(let t of s.turns)ck(t,e);console.log()}l(ak,"renderTimeline");function ck(s,e){let t=s.tokens?a.dim(` (${Fn(s.tokens)} tok)`):"",o=s.durationMs?a.dim(` ${s.durationMs}ms`):"";switch(s.type){case"thinking":{let n=e?s.content||"":(s.content||"").split(`
|
|
527
|
+
`)[0].slice(0,80);console.log(` ${a.blue("\u{1F4AD}")} ${a.blue("Thinking")}${t}`),n&&console.log(` ${a.dim(n)}`);break}case"tool_call":{let n=pk(s.tool||"");console.log(` ${n} ${a.green(s.tool||"unknown")}${o}${t}`),s.resultPreview&&e&&console.log(` ${a.dim(s.resultPreview.slice(0,100))}`);break}case"context_compact":console.log(` ${a.yellow("\u{1F4E6}")} ${a.yellow("Context Compacted")}${t}`);break;case"error":console.log(` ${a.red("\u274C")} ${a.red("Error")}: ${s.content}`);break}}l(ck,"renderTurn");function lk(s){console.log(a.bold(" Decision Tree")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log();let e=0;for(let t of s.turns){let o=" "+" ".repeat(e),n=t.tokens?a.dim(` [${Fn(t.tokens)} tok]`):"",r=t.durationMs?a.dim(` ${t.durationMs}ms`):"";switch(t.type){case"thinking":if(console.log(`${o}${a.blue("\u251C\u2500 \u{1F4AD} Think")}${n}`),t.content){let i=t.content.split(`
|
|
528
|
+
`)[0].slice(0,70);console.log(`${o}${a.dim("\u2502 "+i)}`)}e=Math.min(e+1,4);break;case"tool_call":console.log(`${o}${a.green("\u251C\u2500 \u{1F527} "+(t.tool||"tool"))}${r}`),t.resultPreview&&console.log(`${o}${a.dim("\u2502 \u2192 "+t.resultPreview.slice(0,60))}`);break;case"context_compact":e=Math.max(0,e-1),console.log(`${o}${a.yellow("\u251C\u2500 \u{1F4E6} Compact")}${n}`);break;case"error":console.log(`${o}${a.red("\u2514\u2500 \u274C Error")}: ${t.content}`);break}}console.log()}l(lk,"renderTree");function uk(s){let e=Object.entries(s.fileAccessGraph);if(e.length!==0){console.log(a.bold(" File Access")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(),e.sort((t,o)=>o[1].reads+o[1].writes-(t[1].reads+t[1].writes));for(let[t,o]of e.slice(0,20)){let n=o.reads>0?a.blue(`${o.reads}R`):"",r=o.writes>0?a.green(`${o.writes}W`):"",i=n&&r?" ":"",c="\u2588".repeat(Math.min(o.reads+o.writes,20)),u=o.writes>0?a.green(c):a.blue(c);console.log(` ${u} ${n}${i}${r} ${a.dim(t)}`)}e.length>20&&console.log(a.dim(` ... and ${e.length-20} more files`)),console.log()}}l(uk,"renderFileGraph");function dk(s){if(s.summary){let e=s.summary.filesModified;if(e.length>0){console.log(a.bold(" Files Modified")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));for(let t of e.slice(0,15))console.log(` ${a.green("\u270F\uFE0F")} ${t}`);e.length>15&&console.log(a.dim(` ... and ${e.length-15} more`)),console.log()}}console.log(a.dim("\u2501".repeat(60))),console.log()}l(dk,"renderFooter");function pk(s){return s.includes("read")||s.includes("view")||s.includes("grep")?"\u{1F4D6}":s.includes("write")||s.includes("edit")||s.includes("create")?"\u270F\uFE0F":s.includes("bash")||s.includes("exec")||s.includes("run")?"\u26A1":s.includes("search")||s.includes("web")?"\u{1F50D}":s.includes("delete")||s.includes("remove")?"\u{1F5D1}\uFE0F":"\u{1F527}"}l(pk,"getToolIcon");function Fn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Fn,"formatNum");var Df=b(require("node:fs"),1),tl=b(require("node:path"),1);X();var Uo={thinking:"#4A90D9",tool_call:"#2ECC71",context_compact:"#F39C12",error:"#E74C3C",root:"#34495E"};function vf(s){let e=A(ve()),t=tl.join(e.data,"traces"),o=tl.join(t,`${s.runId}.flamegraph.svg`),n=s.tokensIn+s.tokensOut;if(n===0){let r=s.turns.reduce((i,c)=>i+(c.tokens||0),0)||1;return kf(s,r,o)}return kf(s,n,o)}l(vf,"generateFlamegraph");function kf(s,e,t){let c=[];c.push({name:`Run: ${s.model} \u2014 ${s.prompt.slice(0,50)}`,tokens:e,color:Uo.root,x:0,width:1200,y:0,detail:`Total: ${el(e)} tokens, $${s.totalCostUsd.toFixed(4)}`});let u=0;for(let m of s.turns){let g=m.tokens||mk(m);if(g===0)continue;let h=Math.max(g/e*1200,2),y=Uo[m.type]||Uo.root,S=m.type==="tool_call"?m.tool||"tool":m.type==="thinking"?"Think":m.type;c.push({name:S,tokens:g,color:y,x:u,width:h,y:1,detail:`${S}: ${el(g)} tokens${m.durationMs?`, ${m.durationMs}ms`:""}`}),u+=h}let d=2,p=d*24+40*2+60,f=`<?xml version="1.0" encoding="UTF-8"?>
|
|
520
529
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 ${p}" width="1200" height="${p}">
|
|
521
530
|
<style>
|
|
522
531
|
.frame { cursor: pointer; }
|
|
@@ -531,7 +540,7 @@ ${t}
|
|
|
531
540
|
|
|
532
541
|
<!-- Title -->
|
|
533
542
|
<text x="40" y="28" class="title">Token Flamegraph \u2014 ${si(s.runId)}</text>
|
|
534
|
-
<text x="40" y="46" class="subtitle">${si(s.model)} \xB7 ${
|
|
543
|
+
<text x="40" y="46" class="subtitle">${si(s.model)} \xB7 ${el(e)} tokens \xB7 $${s.totalCostUsd.toFixed(4)} \xB7 ${(s.durationMs/1e3).toFixed(1)}s</text>
|
|
535
544
|
|
|
536
545
|
<!-- Legend -->
|
|
537
546
|
<g class="legend" transform="translate(800, 20)">
|
|
@@ -547,14 +556,14 @@ ${t}
|
|
|
547
556
|
|
|
548
557
|
<!-- Frames -->
|
|
549
558
|
<g transform="translate(0, 60)">
|
|
550
|
-
`;for(let m of c){let g=(d-1-m.y)*24,h=m.x+4,
|
|
559
|
+
`;for(let m of c){let g=(d-1-m.y)*24,h=m.x+4,y=m.width>40?fk(m.name,Math.floor(m.width/7)):"";f+=`<g class="frame">
|
|
551
560
|
<title>${si(m.detail)}</title>
|
|
552
561
|
<rect x="${m.x}" y="${g}" width="${m.width}" height="22" fill="${m.color}" rx="2"/>
|
|
553
|
-
<text x="${h}" y="${g+24-8}">${si(
|
|
562
|
+
<text x="${h}" y="${g+24-8}">${si(y)}</text>
|
|
554
563
|
</g>
|
|
555
564
|
`}return f+=`</g>
|
|
556
|
-
</svg>`,
|
|
557
|
-
`)){let c=i.match(/^(\w+):\s*(.+)$/);if(!c)continue;let[,u,d]=c;switch(u){case"name":r.name=d.trim();break;case"description":r.description=d.trim();break;case"version":r.version=d.trim();break;case"author":r.author=d.trim();break;case"category":r.category=d.trim();break;case"tags":r.tags=d.split(",").map(p=>p.trim().replace(/^\[|\]$/g,""));break}}return r}createTarball(e){let t=gt.join(e,".publish.tar.gz");try{return(0,
|
|
565
|
+
</svg>`,Df.writeFileSync(t,f),t}l(kf,"generateSvg");function mk(s){return s.tokens?s.tokens:s.content?Math.ceil(s.content.length/4):s.result?Math.ceil(s.result.length/4):10}l(mk,"estimateTurnTokens");function el(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(el,"formatTokens");function fk(s,e){return s.length>e?s.slice(0,e-1)+"\u2026":s}l(fk,"truncate");function si(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}l(si,"escapeXml");function xf(s){let e=Ss.list(s.limit||20);if(e.length===0){console.log(a.dim("No traces found. Run an agent first."));return}console.log(),console.log(a.bold(" Recent Traces")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(),console.log(" "+a.dim("Run ID".padEnd(20))+a.dim("Model".padEnd(18))+a.dim("Cost".padEnd(10))+a.dim("Date".padEnd(22))+a.dim("Prompt")),console.log(" "+a.dim("\u2500".repeat(90)));for(let t of e){let o=new Date(t.date).toLocaleString(),n="$"+t.cost.toFixed(4);console.log(" "+a.cyan(t.runId.slice(0,18).padEnd(20))+a.yellow(t.model.padEnd(18))+a.green(n.padEnd(10))+a.dim(o.padEnd(22))+t.prompt)}console.log()}l(xf,"traceList");function $f(s,e){let t=s==="last"?Ss.lastRunId():s;if(!t){console.log(a.red("No traces found. Run an agent first."));return}let o=Ss.load(t);if(!o){console.log(a.red(`Trace not found: ${t}`)),console.log(a.dim("Use `mc trace list` to see available traces."));return}if(e.flamegraph){let n=vf(o);console.log(a.green(`Flamegraph saved: ${n}`));let r=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Sf.exec)(`${r} "${n}"`,i=>{i&&console.log(a.dim(`Open manually: ${n}`))});return}wf(o,{tree:e.tree,verbose:e.verbose})}l($f,"traceShow");W();Q();ee();var Yt=class{static{l(this,"MarketplaceClient")}baseUrl;token;constructor(e){let t=K();this.baseUrl=(e?.baseUrl||t.platformUrl||"https://api.monkeyscode.com").replace(/\/$/,""),this.token=e?.token||process.env.MC_API_KEY||void 0}async search(e,t){let o=new URLSearchParams({q:e});return t?.category&&o.set("category",t.category),t?.page&&o.set("page",String(t.page)),t?.pageSize&&o.set("page_size",String(t.pageSize)),this.get(`/v1/marketplace/skills?${o}`)}async getSkill(e){return this.get(`/v1/marketplace/skills/${e}`)}async featured(){return this.get("/v1/marketplace/featured")}async getReviews(e){return this.get(`/v1/marketplace/skills/${e}/reviews`)}async addReview(e,t,o){return this.post(`/v1/marketplace/skills/${e}/reviews`,{rating:t,comment:o})}async publish(e){let t=new FormData;t.set("name",e.name),t.set("description",e.description),t.set("version",e.version),t.set("category",e.category),t.set("tags",JSON.stringify(e.tags)),t.set("tarball",new Blob([e.tarball]),`${e.name}-${e.version}.tar.gz`);let o=await fetch(`${this.baseUrl}/v1/marketplace/skills`,{method:"POST",headers:await this.authHeaders(),body:t});if(!o.ok)throw new Error(`Marketplace API error: ${o.status} ${await o.text()}`);return await o.json()}async download(e){let t=await this.getSkill(e);if(!t.downloadUrl)throw new Error(`No download URL for skill ${e}`);let o=await fetch(t.downloadUrl,{headers:await this.authHeaders()});if(!o.ok)throw new Error(`Download failed: ${o.status}`);let n=await o.arrayBuffer();return Buffer.from(n)}async get(e){let t=await fetch(`${this.baseUrl}${e}`,{headers:{...await this.authHeaders(),Accept:"application/json"}});if(!t.ok)throw new Error(`Marketplace API error: ${t.status} ${await t.text()}`);return await t.json()}async post(e,t){let o=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:{...await this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Marketplace API error: ${o.status} ${await o.text()}`);return await o.json()}async authHeaders(){let e=this.token||await Fe();return e?{Authorization:`Bearer ${e}`}:{}}};var ye=b(require("node:fs"),1),wo=b(require("node:path"),1),Cf=require("node:child_process");X();var Wo=class{static{l(this,"SkillInstaller")}client;skillsDir;registryPath;constructor(){this.client=new Yt;let e=A(ve());this.skillsDir=wo.join(e.config,"skills"),this.registryPath=wo.join(e.config,"marketplace","installed.json")}async install(e){let t=await this.client.getSkill(e),o=await this.client.download(e),{author:n,name:r}=this.parseSkillName(t.name),i=wo.join(this.skillsDir,n,r);ye.existsSync(i)&&ye.rmSync(i,{recursive:!0}),ye.mkdirSync(i,{recursive:!0});let c=wo.join(i,".tmp.tar.gz");ye.writeFileSync(c,o);try{(0,Cf.execSync)(`tar -xzf "${c}" -C "${i}" --strip-components=1`,{stdio:"pipe"})}finally{ye.unlinkSync(c)}let u=wo.join(i,"skill.md");if(!ye.existsSync(u))throw ye.rmSync(i,{recursive:!0}),new Error("Invalid skill package: missing skill.md");let d={id:t.id,name:t.name,author:n,version:t.version,installedAt:new Date().toISOString(),localPath:i};return this.addToRegistry(d),d}uninstall(e){let t=this.loadRegistry(),o=t.skills.findIndex(r=>r.id===e||r.name===e);if(o===-1)return!1;let n=t.skills[o];return ye.existsSync(n.localPath)&&ye.rmSync(n.localPath,{recursive:!0}),t.skills.splice(o,1),this.saveRegistry(t),!0}async updateAll(){let e=this.loadRegistry(),t=[];for(let o of e.skills)try{let n=await this.client.getSkill(o.id);if(n.version!==o.version){let r=o.version;await this.install(o.id),t.push({name:o.name,oldVersion:r,newVersion:n.version})}}catch{}return t}list(){return this.loadRegistry().skills}loadRegistry(){if(!ye.existsSync(this.registryPath))return{skills:[]};try{return JSON.parse(ye.readFileSync(this.registryPath,"utf8"))}catch{return{skills:[]}}}saveRegistry(e){let t=wo.dirname(this.registryPath);ye.mkdirSync(t,{recursive:!0}),ye.writeFileSync(this.registryPath,JSON.stringify(e,null,2))}addToRegistry(e){let t=this.loadRegistry(),o=t.skills.findIndex(n=>n.id===e.id);o!==-1&&t.skills.splice(o,1),t.skills.push(e),this.saveRegistry(t)}parseSkillName(e){let t=e.match(/^@?(\w+)\/(.+)$/);return t?{author:t[1],name:t[2]}:{author:"community",name:e}}};var Ct=b(require("node:fs"),1),gt=b(require("node:path"),1),_f=require("node:child_process");var ni=class{static{l(this,"SkillPublisher")}client;constructor(){this.client=new Yt}async publish(e,t){let o=gt.resolve(e);this.validate(o);let n=this.parseManifest(o);t?.name&&(n.name=t.name),t?.bump&&(n.version=this.bumpVersion(n.version,t.bump));let r=this.createTarball(o);if(r.length>10*1024*1024)throw new Error(`Package too large: ${(r.length/1024/1024).toFixed(1)}MB (max 10MB)`);return{skill:await this.client.publish({name:n.name,description:n.description,version:n.version,category:n.category,tags:n.tags,tarball:r}),tarballSize:r.length}}validate(e){if(!Ct.existsSync(e))throw new Error(`Directory not found: ${e}`);let t=gt.join(e,"skill.md");if(!Ct.existsSync(t))throw new Error("Missing required file: skill.md");let o=gt.join(e,"README.md");if(!Ct.existsSync(o))throw new Error("Missing required file: README.md");let n=this.parseManifest(e);if(!n.name)throw new Error('skill.md must have a "name" field in frontmatter');if(!n.description)throw new Error('skill.md must have a "description" field in frontmatter')}parseManifest(e){let o=Ct.readFileSync(gt.join(e,"skill.md"),"utf8").match(/^---\n([\s\S]*?)\n---/);if(!o)throw new Error("skill.md must have YAML frontmatter (between --- markers)");let n=o[1],r={name:"",description:"",version:"1.0.0",author:"",category:"general",tags:[]};for(let i of n.split(`
|
|
566
|
+
`)){let c=i.match(/^(\w+):\s*(.+)$/);if(!c)continue;let[,u,d]=c;switch(u){case"name":r.name=d.trim();break;case"description":r.description=d.trim();break;case"version":r.version=d.trim();break;case"author":r.author=d.trim();break;case"category":r.category=d.trim();break;case"tags":r.tags=d.split(",").map(p=>p.trim().replace(/^\[|\]$/g,""));break}}return r}createTarball(e){let t=gt.join(e,".publish.tar.gz");try{return(0,_f.execSync)(`tar -czf "${t}" --exclude=".*" --exclude="node_modules" --exclude="*.tar.gz" -C "${gt.dirname(e)}" "${gt.basename(e)}"`,{stdio:"pipe"}),Ct.readFileSync(t)}finally{Ct.existsSync(t)&&Ct.unlinkSync(t)}}bumpVersion(e,t){let o=e.split(".").map(Number);switch(t){case"major":return`${o[0]+1}.0.0`;case"minor":return`${o[0]}.${o[1]+1}.0`;case"patch":return`${o[0]}.${o[1]}.${o[2]+1}`}}};async function Ef(s,e){let t=new Yt;console.log(a.dim(`Searching marketplace for "${s}"...`));try{let o=await t.search(s,{category:e?.category});if(o.skills.length===0){console.log(a.dim("No skills found."));return}console.log(),console.log(a.bold(` Found ${o.total} skill${o.total===1?"":"s"}`)),console.log(a.dim(" "+"\u2500".repeat(50))),console.log();for(let n of o.skills)Of(n)}catch(o){console.log(a.red(`Search failed: ${o.message}`))}}l(Ef,"marketplaceSearch");async function Ff(s){let e=new Wo;console.log(a.dim(`Installing ${s}...`));try{let t=await e.install(s);console.log(a.green(`\u2713 Installed ${t.name}@${t.version}`)),console.log(a.dim(` Path: ${t.localPath}`))}catch(t){console.log(a.red(`Install failed: ${t.message}`))}}l(Ff,"marketplaceInstall");function Tf(s){new Wo().uninstall(s)?console.log(a.green(`\u2713 Uninstalled ${s}`)):console.log(a.red(`Skill not found: ${s}`))}l(Tf,"marketplaceUninstall");async function Rf(s,e){let t=new ni;console.log(a.dim(`Publishing skill from ${s}...`));try{t.validate(s),console.log(a.green("\u2713 Validation passed"));let o=await t.publish(s,e);console.log(),console.log(a.green(`\u2713 Published ${o.skill.name}@${o.skill.version}`)),console.log(a.dim(` Size: ${(o.tarballSize/1024).toFixed(1)}KB`)),console.log(a.dim(` ID: ${o.skill.id}`))}catch(o){console.log(a.red(`Publish failed: ${o.message}`))}}l(Rf,"marketplacePublish");async function Af(){let s=new Wo;console.log(a.dim("Checking for updates..."));try{let e=await s.updateAll();if(e.length===0){console.log(a.green("All skills are up to date."));return}for(let t of e)console.log(a.green(` \u2191 ${t.name}: ${t.oldVersion} \u2192 ${t.newVersion}`));console.log(a.green(`\u2713 Updated ${e.length} skill${e.length===1?"":"s"}`))}catch(e){console.log(a.red(`Update failed: ${e.message}`))}}l(Af,"marketplaceUpdate");function Pf(){let e=new Wo().list();if(e.length===0){console.log(a.dim("No marketplace skills installed.")),console.log(a.dim("Install one with: mc marketplace install @community/skill-name"));return}console.log(),console.log(a.bold(` Installed Skills (${e.length})`)),console.log(a.dim(" "+"\u2500".repeat(40))),console.log();for(let t of e){let o=new Date(t.installedAt).toLocaleDateString();console.log(` ${a.cyan(t.name)} ${a.dim("v"+t.version)}`),console.log(` ${a.dim("Author:")} ${t.author} ${a.dim("\u2022")} ${a.dim("Installed:")} ${o}`),console.log(` ${a.dim("Path:")} ${t.localPath}`),console.log()}}l(Pf,"marketplaceList");async function Mf(){let s=new Yt;try{let e=await s.featured();console.log(),console.log(a.bold(" \u2B50 Featured Skills")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log();for(let t of e)Of(t)}catch(e){console.log(a.red(`Failed to fetch featured: ${e.message}`))}}l(Mf,"marketplaceFeatured");function Of(s){let e=s.rating>0?a.yellow("\u2605".repeat(Math.round(s.rating))+"\u2606".repeat(5-Math.round(s.rating))):a.dim("No ratings"),t=s.downloads>1e3?`${(s.downloads/1e3).toFixed(1)}K`:String(s.downloads);console.log(` ${a.bold.cyan(s.name)} ${a.dim("v"+s.version)} ${a.dim("by")} ${s.author}`),console.log(` ${s.description}`),console.log(` ${e} ${a.dim(`(${s.reviewCount})`)} ${a.dim("\u2022")} ${a.dim(`\u2B07 ${t}`)} ${a.dim("\u2022")} ${a.dim(s.category)}`),s.tags.length>0&&console.log(` ${s.tags.map(o=>a.dim(`#${o}`)).join(" ")}`),console.log()}l(Of,"renderSkillCard");W();var ko=b(require("node:fs"),1),ri=b(require("node:path"),1);X();var gk=`You translate natural language permission rules into structured JSON policies.
|
|
558
567
|
|
|
559
568
|
Each policy has:
|
|
560
569
|
- tool: glob pattern for which tools this applies to (e.g., "delete_file", "bash", "*")
|
|
@@ -578,12 +587,12 @@ Input: "Ask before modifying any file with 'config' in the name"
|
|
|
578
587
|
Output: {"tool":"*_file","condition":"path.includes('config')","action":"prompt","message":"This file contains configuration. Proceed?"}
|
|
579
588
|
|
|
580
589
|
Input: "Block any command that uses sudo"
|
|
581
|
-
Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function hk(s){let e=yk(s);return e||await bk(s)}l(hk,"translateNaturalRule");function yk(s){let e=s.toLowerCase(),t=e.match(/(?:never|don't|block)\s+delete.*outside\s+(?:the\s+)?(\S+)/);if(t){let n=t[1].replace(/\/$/,"");return{tool:"delete_file",condition:`!path.startsWith('${n}/')`,action:"deny",message:`Cannot delete files outside ${n}/ per project policy`}}if(e.includes("sudo")&&(e.includes("block")||e.includes("never")||e.includes("don't")))return{tool:"bash",condition:"command.includes('sudo')",action:"deny",message:"sudo is not allowed per project policy"};if(e.includes("ask")&&e.includes("config"))return{tool:"*_file",condition:"path.includes('config')",action:"prompt",message:"This file contains configuration. Proceed?"};let o=e.match(/(?:never|don't)\s+(?:modify|edit|change)\s+(?:any\s+)?(?:file.*)?(?:in\s+)?(\S+)/);if(o){let n=o[1];return{tool:"*_file",condition:`path.includes('${n}')`,action:"deny",message:`Modifying files matching '${n}' is not allowed`}}return e.includes("test")&&e.includes("commit")?{tool:"bash",condition:"command.includes('git commit')",action:"warn",message:"Consider running tests before committing"}:null}l(yk,"tryLocalTranslation");async function bk(s){try{let{AgentLoop:e}=await Promise.resolve().then(()=>(
|
|
590
|
+
Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function hk(s){let e=yk(s);return e||await bk(s)}l(hk,"translateNaturalRule");function yk(s){let e=s.toLowerCase(),t=e.match(/(?:never|don't|block)\s+delete.*outside\s+(?:the\s+)?(\S+)/);if(t){let n=t[1].replace(/\/$/,"");return{tool:"delete_file",condition:`!path.startsWith('${n}/')`,action:"deny",message:`Cannot delete files outside ${n}/ per project policy`}}if(e.includes("sudo")&&(e.includes("block")||e.includes("never")||e.includes("don't")))return{tool:"bash",condition:"command.includes('sudo')",action:"deny",message:"sudo is not allowed per project policy"};if(e.includes("ask")&&e.includes("config"))return{tool:"*_file",condition:"path.includes('config')",action:"prompt",message:"This file contains configuration. Proceed?"};let o=e.match(/(?:never|don't)\s+(?:modify|edit|change)\s+(?:any\s+)?(?:file.*)?(?:in\s+)?(\S+)/);if(o){let n=o[1];return{tool:"*_file",condition:`path.includes('${n}')`,action:"deny",message:`Modifying files matching '${n}' is not allowed`}}return e.includes("test")&&e.includes("commit")?{tool:"bash",condition:"command.includes('git commit')",action:"warn",message:"Consider running tests before committing"}:null}l(yk,"tryLocalTranslation");async function bk(s){try{let{AgentLoop:e}=await Promise.resolve().then(()=>(Ke(),es)),{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{getAccessToken:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=await o()||process.env.MC_API_KEY||"";if(!r)return ol(s);let i=new e({platformUrl:n.platformUrl,token:r,model:n.defaultModel||"capuchin-reason",workspace:process.cwd(),mode:"auto",maxTurns:1,sandboxed:!0,webEnabled:!1,effort:"fast"}),c="";i.on("event",p=>{p.type==="streaming_chunk"&&(c+=p.content)}),await i.run(`${gk}
|
|
582
591
|
|
|
583
592
|
Input: "${s}"
|
|
584
|
-
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?
|
|
593
|
+
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?ol(s):d}catch{return ol(s)}}l(bk,"llmTranslation");function ol(s){return{tool:"*",condition:"true",action:"prompt",message:`Custom rule: ${s}`}}l(ol,"fallbackPolicy");function If(){let s=A(ve());return ri.join(s.config,"natural-permissions.json")}l(If,"getPermissionsPath");function Tn(){let s=If();if(!ko.existsSync(s))return{naturalRules:[]};try{return JSON.parse(ko.readFileSync(s,"utf8"))}catch{return{naturalRules:[]}}}l(Tn,"loadNaturalPermissions");function jf(s){let e=If(),t=ri.dirname(e);ko.mkdirSync(t,{recursive:!0}),ko.writeFileSync(e,JSON.stringify(s,null,2))}l(jf,"saveNaturalPermissions");async function Nf(s){let e=await hk(s),t={text:s,generatedPolicy:e,createdAt:new Date().toISOString(),enabled:!0},o=Tn();return o.naturalRules.push(t),jf(o),t}l(Nf,"addNaturalRule");function Lf(s){let e=Tn();return s<0||s>=e.naturalRules.length?!1:(e.naturalRules.splice(s,1),jf(e),!0)}l(Lf,"removeNaturalRule");function Bf(s,e){let t=Tn();for(let o of t.naturalRules){if(!o.enabled)continue;let n=o.generatedPolicy;if(!(n.tool!=="*"&&!s.includes(n.tool.replace("*",""))))try{let r=e.path||e.file||e.filePath||e.target||"",i=e.command||e.cmd||"";if(new Function("path","args","command",`return ${n.condition}`)(r,e,i))return{action:n.action,message:n.message}}catch{}}return{action:"allow"}}l(Bf,"evaluateNaturalRules");async function Uf(s){console.log(a.dim("Translating rule..."));let e=await Nf(s);console.log(),console.log(a.green("\u2713 Rule added")),console.log(),console.log(` ${a.dim("Text:")} ${e.text}`),console.log(` ${a.dim("Tool:")} ${a.yellow(e.generatedPolicy.tool)}`),console.log(` ${a.dim("Condition:")} ${a.cyan(e.generatedPolicy.condition)}`),console.log(` ${a.dim("Action:")} ${sl(e.generatedPolicy.action)}`),console.log(` ${a.dim("Message:")} ${e.generatedPolicy.message}`),console.log()}l(Uf,"permissionsSet");function Wf(){let s=Tn();if(s.naturalRules.length===0){console.log(a.dim("No natural language rules configured.")),console.log(a.dim('Add one with: mc permissions set "Never delete files outside src"'));return}console.log(),console.log(a.bold(" Natural Language Permissions")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log();for(let e=0;e<s.naturalRules.length;e++){let t=s.naturalRules[e],o=t.enabled?a.green("\u25CF"):a.dim("\u25CB"),n=sl(t.generatedPolicy.action);console.log(` ${o} ${a.dim(`[${e}]`)} ${t.text}`),console.log(` ${a.dim("\u2192")} ${a.yellow(t.generatedPolicy.tool)} | ${a.cyan(t.generatedPolicy.condition)} | ${n}`),console.log()}}l(Wf,"permissionsList");function Hf(s){let e=Lf(s);console.log(e?a.green(`\u2713 Rule ${s} removed`):a.red(`Rule ${s} not found`))}l(Hf,"permissionsRemove");function Gf(s,e){let t;try{t=JSON.parse(e)}catch{console.log(a.red("Invalid JSON for args"));return}let o=Bf(s,t);console.log(),console.log(` ${a.dim("Tool:")} ${s}`),console.log(` ${a.dim("Args:")} ${JSON.stringify(t)}`),console.log(` ${a.dim("Result:")} ${sl(o.action)}`),o.message&&console.log(` ${a.dim("Message:")} ${o.message}`),console.log()}l(Gf,"permissionsTest");function sl(s){switch(s){case"deny":return a.red("DENY");case"warn":return a.yellow("WARN");case"prompt":return a.cyan("PROMPT");case"allow":return a.green("ALLOW");default:return s}}l(sl,"colorAction");var $s=b(require("node:fs"),1),ci=b(require("node:path"),1);W();var Ge=b(require("node:fs"),1),xs=b(require("node:path"),1),ii=require("node:child_process");function wk(s){let e={name:"Unnamed Benchmark",setup:[],steps:[],score:{testsPass:50,noRegressions:30,codeQuality:20}},t=s.split(`
|
|
585
594
|
`),o="",n={};for(let r of t){let i=r.trim();if(!i||i.startsWith("#"))continue;let c=i.match(/^(\w+):\s*(.*)$/);if(c&&!r.startsWith(" ")&&!r.startsWith(" ")){let[,p,f]=c;p==="name"&&(e.name=f.replace(/^["']|["']$/g,"")),p==="description"&&(e.description=f),p==="setup"&&(o="setup"),p==="steps"&&(o="steps"),p==="score"&&(o="score");continue}let u=i.match(/^-\s+(.+)$/);if(u){o==="setup"&&e.setup.push(u[1].replace(/^["']|["']$/g,""));continue}let d=i.match(/^(\w+):\s*(.+)$/);if(d){let[,p,f]=d,m=f.replace(/^["']|["']$/g,"");o==="steps"&&(p==="prompt"&&(n.prompt&&e.steps.push(n),n={prompt:m}),p==="verify"&&(n.verify=m),p==="expected_files_changed"&&(n.expectedFilesChanged=m.replace(/^\[|\]$/g,"").split(",").map(g=>g.trim().replace(/^["']|["']$/g,""))),p==="max_tokens"&&(n.maxTokens=parseInt(m)),p==="timeout_ms"&&(n.timeoutMs=parseInt(m))),o==="score"&&(p==="tests_pass"&&(e.score.testsPass=parseInt(m)),p==="no_regressions"&&(e.score.noRegressions=parseInt(m)),p==="code_quality"&&(e.score.codeQuality=parseInt(m)))}}return n.prompt&&e.steps.push(n),e}l(wk,"parseSimpleYaml");var ai=class{static{l(this,"BenchmarkRunner")}workspace;constructor(e){this.workspace=e}loadSpec(e){let t=Ge.readFileSync(e,"utf8");return wk(t)}async run(e,t){let o=new Date().toISOString(),n=Date.now(),r=0,i=0;if(e.setup&&e.setup.length>0)for(let p of e.setup)try{(0,ii.execSync)(p,{cwd:this.workspace,stdio:"pipe",timeout:6e4})}catch(f){console.error(`Setup step failed: ${p}
|
|
586
|
-
${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop:m}=await Promise.resolve().then(()=>(
|
|
595
|
+
${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop:m}=await Promise.resolve().then(()=>(Ke(),es)),{loadSettings:g}=await Promise.resolve().then(()=>(Q(),Se)),{getAccessToken:h}=await Promise.resolve().then(()=>(ee(),ge)),y=g(),S=await h()||process.env.MC_API_KEY||"",D=new m({platformUrl:y.platformUrl,token:S,model:t,workspace:this.workspace,mode:"auto",maxTurns:p.maxTokens?Math.ceil(p.maxTokens/1e3):20,sandboxed:!0}),C=0,x=0,v=[];D.on("event",U=>{if(U.type==="state_update"&&(C=(U.state?.tokensIn||0)+(U.state?.tokensOut||0),x=U.state?.costUsd||0),U.type==="tool_call_start"&&U.name?.includes("file")){let pe=U.args?.path||U.args?.file;pe&&!v.includes(pe)&&v.push(pe)}}),await D.run(p.prompt);let E=!1,oe="";try{oe=(0,ii.execSync)(p.verify,{cwd:this.workspace,stdio:"pipe",timeout:p.timeoutMs||12e4}).toString().trim(),E=!0}catch(U){oe=U.stderr?.toString()||U.message||"Verification failed",E=!1}r+=C,i+=x,c.push({prompt:p.prompt,passed:E,verifyOutput:oe,durationMs:Date.now()-f,tokensUsed:C,filesChanged:v,score:this.scoreStep(p,E,v,e.score)})}catch(m){c.push({prompt:p.prompt,passed:!1,verifyOutput:`Agent error: ${m.message}`,durationMs:Date.now()-f,tokensUsed:0,filesChanged:[],score:0})}}let u=c.reduce((p,f)=>p+f.score,0),d=e.score.testsPass+e.score.noRegressions+e.score.codeQuality;return{name:e.name,model:t,startedAt:o,completedAt:new Date().toISOString(),durationMs:Date.now()-n,steps:c,totalScore:u,maxScore:d,tokensUsed:r,costUsd:i}}async compare(e,t){let o=[];for(let n of t){if(e.setup)for(let i of e.setup)try{(0,ii.execSync)(i,{cwd:this.workspace,stdio:"pipe",timeout:6e4})}catch{}let r=await this.run(e,n);o.push(r)}return o}scoreStep(e,t,o,n){let r=0,i=1/Math.max(1,1);if(t&&(r+=n.testsPass*i),e.expectedFilesChanged){let c=new Set(e.expectedFilesChanged);o.filter(d=>!c.has(d)&&!kk(d,e.expectedFilesChanged)).length===0&&(r+=n.noRegressions*i)}else r+=n.noRegressions*i;return t&&o.length<=10&&(r+=n.codeQuality*i),Math.round(r)}};function kk(s,e){return e.some(t=>{let o=t.replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(o).test(s)})}l(kk,"matchesGlob");function nl(s){let{getPlatformPaths:e,detectPlatform:t}=(X(),Ps($o)),o=e(t()),n=xs.join(o.data,"benchmarks");Ge.mkdirSync(n,{recursive:!0});let r=`${s.name.replace(/\s+/g,"-").toLowerCase()}-${s.model}-${Date.now()}.json`,i=xs.join(n,r);return Ge.writeFileSync(i,JSON.stringify(s,null,2)),i}l(nl,"saveBenchmarkResult");function qf(s=20){let{getPlatformPaths:e,detectPlatform:t}=(X(),Ps($o)),o=e(t()),n=xs.join(o.data,"benchmarks");return Ge.existsSync(n)?Ge.readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let i=Ge.statSync(xs.join(n,r));return{file:r,mtime:i.mtimeMs}}).sort((r,i)=>i.mtime-r.mtime).slice(0,s).map(r=>{try{return JSON.parse(Ge.readFileSync(xs.join(n,r.file),"utf8"))}catch{return null}}).filter(Boolean):[]}l(qf,"loadBenchmarkResults");W();function Vf(s){let e=(s.totalScore/s.maxScore*100).toFixed(0),t=(s.durationMs/1e3).toFixed(1);console.log(),console.log(a.bold.cyan("\u2501".repeat(60))),console.log(a.bold.cyan(` Benchmark: ${s.name}`)),console.log(a.bold.cyan("\u2501".repeat(60))),console.log(),console.log(` ${a.dim("Model:")} ${a.yellow(s.model)}`),console.log(` ${a.dim("Score:")} ${Kf(s.totalScore,s.maxScore)} ${a.dim(`(${e}%)`)}`),console.log(` ${a.dim("Duration:")} ${t}s`),console.log(` ${a.dim("Tokens:")} ${Rn(s.tokensUsed)}`),console.log(` ${a.dim("Cost:")} ${a.green("$"+s.costUsd.toFixed(4))}`),console.log(),console.log(a.bold(" Steps")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500"));for(let o=0;o<s.steps.length;o++){let n=s.steps[o],r=n.passed?a.green("\u2713"):a.red("\u2717"),i=(n.durationMs/1e3).toFixed(1);console.log(` ${r} ${a.white(`Step ${o+1}`)}: ${n.prompt.slice(0,50)}${n.prompt.length>50?"...":""}`),console.log(` ${a.dim(`Score: ${n.score}/${s.maxScore} \u2022 ${i}s \u2022 ${Rn(n.tokensUsed)} tokens`)}`),n.filesChanged.length>0&&console.log(` ${a.dim(`Files: ${n.filesChanged.slice(0,5).join(", ")}`)}`)}console.log(),console.log(a.dim("\u2501".repeat(60)))}l(Vf,"renderResult");function zf(s){if(s.length===0)return;console.log(),console.log(a.bold.cyan("\u2501".repeat(80))),console.log(a.bold.cyan(` Model Comparison: ${s[0].name}`)),console.log(a.bold.cyan("\u2501".repeat(80))),console.log();let e=18,t=" "+"Model".padEnd(e)+"Score".padEnd(10)+"Time".padEnd(10)+"Tokens".padEnd(12)+"Cost".padEnd(10)+"Steps";console.log(a.dim(t)),console.log(" "+a.dim("\u2500".repeat(78)));let o=[...s].sort((i,c)=>c.totalScore-i.totalScore);for(let i=0;i<o.length;i++){let c=o[i],u=i===0?"\u{1F947}":i===1?"\u{1F948}":i===2?"\u{1F949}":" ",d=(c.totalScore/c.maxScore*100).toFixed(0)+"%",p=c.steps.filter(m=>m.passed).length,f=c.steps.length;console.log(` ${u} ${a.yellow(c.model.padEnd(e-3))}`+Kf(c.totalScore,c.maxScore).padEnd(20)+a.dim(((c.durationMs/1e3).toFixed(1)+"s").padEnd(10))+a.dim(Rn(c.tokensUsed).padEnd(12))+a.green(("$"+c.costUsd.toFixed(4)).padEnd(10))+`${p}/${f}`)}console.log();let n=o[0],r=o[o.length-1];if(o.length>1){console.log(` ${a.green("Best:")} ${a.yellow(n.model)} \u2014 ${(n.totalScore/n.maxScore*100).toFixed(0)}% score`),console.log(` ${a.dim("Worst:")} ${a.dim(r.model)} \u2014 ${(r.totalScore/r.maxScore*100).toFixed(0)}% score`);let i=o.reduce((c,u)=>u.totalScore/Math.max(u.costUsd,1e-4)>c.totalScore/Math.max(c.costUsd,1e-4)?u:c);console.log(` ${a.blue("Most efficient:")} ${a.yellow(i.model)} \u2014 best score/cost ratio`)}console.log(),console.log(a.dim("\u2501".repeat(80)))}l(zf,"renderComparison");function Jf(s){if(s.length===0)return`# No Results
|
|
587
596
|
`;let e=`# Benchmark Report: ${s[0].name}
|
|
588
597
|
|
|
589
598
|
`;e+=`Generated: ${new Date().toISOString()}
|
|
@@ -592,21 +601,21 @@ ${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop
|
|
|
592
601
|
|
|
593
602
|
`,e+=`| Model | Score | Time | Tokens | Cost | Steps Passed |
|
|
594
603
|
`,e+=`|-------|-------|------|--------|------|--------------|
|
|
595
|
-
`;let t=[...s].sort((o,n)=>n.totalScore-o.totalScore);for(let o of t){let n=(o.totalScore/o.maxScore*100).toFixed(0)+"%",r=o.steps.filter(i=>i.passed).length;e+=`| ${o.model} | ${n} | ${(o.durationMs/1e3).toFixed(1)}s | ${
|
|
604
|
+
`;let t=[...s].sort((o,n)=>n.totalScore-o.totalScore);for(let o of t){let n=(o.totalScore/o.maxScore*100).toFixed(0)+"%",r=o.steps.filter(i=>i.passed).length;e+=`| ${o.model} | ${n} | ${(o.durationMs/1e3).toFixed(1)}s | ${Rn(o.tokensUsed)} | $${o.costUsd.toFixed(4)} | ${r}/${o.steps.length} |
|
|
596
605
|
`}e+=`
|
|
597
606
|
`;for(let o of s){e+=`### ${o.model}
|
|
598
607
|
|
|
599
608
|
`;for(let n=0;n<o.steps.length;n++){let r=o.steps[n],i=r.passed?"\u2705":"\u274C";e+=`${i} **Step ${n+1}**: ${r.prompt}
|
|
600
|
-
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${
|
|
609
|
+
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${Rn(r.tokensUsed)}
|
|
601
610
|
`,e+=`- Files: ${r.filesChanged.join(", ")||"none"}
|
|
602
611
|
|
|
603
|
-
`}}return e}l(
|
|
604
|
-
`).slice(0,10);for(let t of e)console.log(a.dim(` ${t}`))}break;case"error":console.log(a.red(` \u2717 Error: ${s.message||s.error||"unknown"}`));break;case"complete":console.log(""),console.log(a.green(" \u2713 Complete")),s.result?.summary&&console.log(a.dim(` ${s.result.summary}`));break;case"cost_update":break;default:process.env.MC_DEBUG&&console.log(a.dim(` [${s.type}] ${JSON.stringify(s).slice(0,100)}`));break}}l(
|
|
605
|
-
Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()=>{console.log(a.green("Reconnected."))}),n.on("error",r=>{console.log(a.red(`Session error: ${r.message}`))});try{await n.connect(),console.log(a.green(`\u2713 Connected to session ${s}`)),console.log(a.dim("Waiting for host activity... Press Ctrl+C to leave."));let r=
|
|
612
|
+
`}}return e}l(Jf,"generateMarkdownReport");function Kf(s,e){let t=s/e*100,o=`${s}/${e}`;return t>=80?a.green(o):t>=50?a.yellow(o):a.red(o)}l(Kf,"colorScore");function Rn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Rn,"formatNum");async function Yf(s,e){let t=ci.resolve(s),o=e.workspace||process.cwd();if(!$s.existsSync(t)){console.log(a.red(`Benchmark not found: ${t}`));return}let n=new ai(o),r=e.model||["capuchin-reason"],i=Dk(t,n);if(i.length===0){console.log(a.red("No benchmark YAML files found."));return}console.log(),console.log(a.bold.cyan(`Running ${i.length} benchmark${i.length>1?"s":""} against ${r.length} model${r.length>1?"s":""}`)),console.log();for(let c of i)if(r.length>1){console.log(a.dim(`Running benchmark: ${c.name}...`));let u=await n.compare(c,r);for(let d of u)nl(d);zf(u)}else{console.log(a.dim(`Running benchmark: ${c.name} with ${r[0]}...`));let u=await n.run(c,r[0]);nl(u),Vf(u)}}l(Yf,"benchmarkCustom");function Xf(s){let e=qf(s.limit||20);if(e.length===0){console.log(a.dim("No benchmark results found.")),console.log(a.dim("Run one with: mc benchmark custom ./benchmarks/"));return}if(s.format==="md"){console.log(Jf(e));return}console.log(),console.log(a.bold(" Recent Benchmark Results")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(),console.log(" "+a.dim("Benchmark".padEnd(25))+a.dim("Model".padEnd(20))+a.dim("Score".padEnd(12))+a.dim("Time".padEnd(10))+a.dim("Cost".padEnd(10))+a.dim("Date")),console.log(" "+a.dim("\u2500".repeat(85)));for(let t of e){let o=(t.totalScore/t.maxScore*100).toFixed(0)+"%",n=new Date(t.startedAt).toLocaleDateString();console.log(" "+t.name.slice(0,23).padEnd(25)+a.yellow(t.model.padEnd(20))+vk(o).padEnd(22)+a.dim(((t.durationMs/1e3).toFixed(1)+"s").padEnd(10))+a.green(("$"+t.costUsd.toFixed(4)).padEnd(10))+a.dim(n))}console.log()}l(Xf,"benchmarkResults");function Dk(s,e){return $s.statSync(s).isFile()?[e.loadSpec(s)]:$s.readdirSync(s).filter(o=>o.endsWith(".yaml")||o.endsWith(".yml")).map(o=>e.loadSpec(ci.join(s,o)))}l(Dk,"loadSpecs");function vk(s){let e=parseInt(s);return e>=80?a.green(s):e>=50?a.yellow(s):a.red(s)}l(vk,"colorScore");W();var tg=b(require("node:readline"),1);var Qf=b(require("node:crypto"),1),Zf=require("node:events");an();var An=class extends Zf.EventEmitter{static{l(this,"SharedSession")}sessionId;role;ws=null;participants=new Map;userId;userName;relayUrl;reconnectTimer=null;constructor(e){super(),this.sessionId=e.sessionId||this.generateSessionId(),this.role=e.sessionId?"observer":"host",this.userId=Qf.randomUUID(),this.userName=e.userName,this.relayUrl=e.relayUrl}async connect(){return new Promise((e,t)=>{let o=`${this.relayUrl}/v1/collab/${this.sessionId}?role=${this.role}&user=${encodeURIComponent(this.userName)}`;this.ws=new lt(o),this.ws.on("open",()=>{this.send({type:"join",senderId:this.userId,senderName:this.userName,data:{role:this.role},timestamp:Date.now()}),e()}),this.ws.on("message",n=>{try{let r=JSON.parse(n.toString());this.handleMessage(r)}catch{}}),this.ws.on("close",()=>{this.emit("disconnected"),this.scheduleReconnect()}),this.ws.on("error",n=>{this.ws?.readyState===lt.CONNECTING&&t(n),this.emit("error",n)})})}disconnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.ws&&(this.send({type:"leave",senderId:this.userId,senderName:this.userName,data:{},timestamp:Date.now()}),this.ws.close(),this.ws=null)}broadcastEvent(e){this.send({type:"event",senderId:this.userId,senderName:this.userName,data:e,timestamp:Date.now()})}sendPrompt(e){this.send({type:"prompt",senderId:this.userId,senderName:this.userName,data:{prompt:e},timestamp:Date.now()})}getShareUrl(){return`https://monkeyscode.com/share/${this.sessionId}`}getParticipants(){return Array.from(this.participants.values())}handleMessage(e){switch(e.type){case"join":this.participants.set(e.senderId,{id:e.senderId,name:e.senderName,role:e.data?.role||"observer",joinedAt:new Date().toISOString()}),this.emit("participant_joined",e.senderName);break;case"leave":this.participants.delete(e.senderId),this.emit("participant_left",e.senderName);break;case"event":this.emit("remote_event",e.data);break;case"prompt":this.emit("remote_prompt",{prompt:e.data?.prompt,from:e.senderName});break;case"sync":this.emit("sync",e.data);break}}send(e){this.ws?.readyState===lt.OPEN&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){this.reconnectTimer||(this.reconnectTimer=setTimeout(async()=>{this.reconnectTimer=null;try{await this.connect(),this.emit("reconnected")}catch{this.scheduleReconnect()}},3e3))}generateSessionId(){let e=["alpha","beta","gamma","delta","echo","fox","golf","hotel"],t=e[Math.floor(Math.random()*e.length)],o=e[Math.floor(Math.random()*e.length)],n=Math.floor(Math.random()*1e3).toString().padStart(3,"0");return`mc-share-${t}-${o}-${n}`}};Q();ee();W();function eg(s){if(!(!s||!s.type))switch(s.type){case"text":process.stdout.write(s.content||"");break;case"thinking":s.content&&process.stdout.write(a.dim(s.content));break;case"tool_call":console.log(a.cyan(` \u26A1 ${s.toolName||s.tool||"tool"}`)+(s.args?a.dim(` ${JSON.stringify(s.args).slice(0,80)}`):""));break;case"tool_result":s.isError&&console.log(a.red(` \u2717 Tool error: ${s.result||"unknown"}`));break;case"file_edit":console.log(a.yellow(` \u270E Edited: ${s.path||s.file||"unknown"}`));break;case"file_read":console.log(a.dim(` \u{1F4C4} Read: ${s.path||s.file||"unknown"}`));break;case"terminal_command":if(console.log(a.blue(` $ ${s.command||""}`)),s.output){let e=s.output.split(`
|
|
613
|
+
`).slice(0,10);for(let t of e)console.log(a.dim(` ${t}`))}break;case"error":console.log(a.red(` \u2717 Error: ${s.message||s.error||"unknown"}`));break;case"complete":console.log(""),console.log(a.green(" \u2713 Complete")),s.result?.summary&&console.log(a.dim(` ${s.result.summary}`));break;case"cost_update":break;default:process.env.MC_DEBUG&&console.log(a.dim(` [${s.type}] ${JSON.stringify(s).slice(0,100)}`));break}}l(eg,"renderEvent");async function og(s){console.log(a.dim(`Joining session ${s}...`));let e=K();if(!(await Fe()||process.env.MC_API_KEY)){console.log(a.red("You must be logged in to join a shared session.")),console.log(a.dim("Run `mc auth login` first."));return}let o=process.env.USER||"Observer",n=new An({relayUrl:e.platformUrl||"wss://api.monkeyscode.com",userName:o,sessionId:s});n.on("participant_joined",r=>{console.log(a.green(`\u2192 ${r} joined the session`))}),n.on("participant_left",r=>{console.log(a.dim(`\u2190 ${r} left the session`))}),n.on("remote_event",r=>{eg(r)}),n.on("remote_prompt",({prompt:r,from:i})=>{console.log(),console.log(a.cyan(`[${i}] `)+a.white(r)),console.log()}),n.on("disconnected",()=>{console.log(a.red(`
|
|
614
|
+
Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()=>{console.log(a.green("Reconnected."))}),n.on("error",r=>{console.log(a.red(`Session error: ${r.message}`))});try{await n.connect(),console.log(a.green(`\u2713 Connected to session ${s}`)),console.log(a.dim("Waiting for host activity... Press Ctrl+C to leave."));let r=tg.createInterface({input:process.stdin,output:process.stdout}),i=l(()=>{r.question(a.dim("You: "),c=>{c.trim()&&n.sendPrompt(c),i()})},"promptLoop");i()}catch(r){console.log(a.red(`Failed to join session: ${r.message}`))}}l(og,"joinSession");async function sg(){let s=K();if(!(await Fe()||process.env.MC_API_KEY))return console.log(a.red("You must be logged in to share a session.")),null;let t=process.env.USER||"Host",o=new An({relayUrl:s.platformUrl||"wss://api.monkeyscode.com",userName:t});o.on("participant_joined",n=>{console.log(a.green(`
|
|
606
615
|
\u2192 ${n} joined your session
|
|
607
616
|
`))}),o.on("participant_left",n=>{console.log(a.dim(`
|
|
608
617
|
\u2190 ${n} left your session
|
|
609
|
-
`))});try{return await o.connect(),console.log(a.bgBlue.white.bold(" LIVE SHARE ")),console.log(a.dim("Others can join this session using:")),console.log(a.cyan(`mc join ${o.sessionId}`)),console.log(a.dim(`Or via web: ${o.getShareUrl()}`)),console.log(),o}catch(n){return console.log(a.red(`Failed to start live share: ${n.message}`)),null}}l(
|
|
618
|
+
`))});try{return await o.connect(),console.log(a.bgBlue.white.bold(" LIVE SHARE ")),console.log(a.dim("Others can join this session using:")),console.log(a.cyan(`mc join ${o.sessionId}`)),console.log(a.dim(`Or via web: ${o.getShareUrl()}`)),console.log(),o}catch(n){return console.log(a.red(`Failed to start live share: ${n.message}`)),null}}l(sg,"setupSharedSession");var rg=b(require("node:http"),1);an();W();function ng(s,e="Design Preview"){return`
|
|
610
619
|
<!DOCTYPE html>
|
|
611
620
|
<html lang="en">
|
|
612
621
|
<head>
|
|
@@ -653,10 +662,10 @@ Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()
|
|
|
653
662
|
</script>
|
|
654
663
|
</body>
|
|
655
664
|
</html>
|
|
656
|
-
`.trim()}l(rg,"generateHtmlPreview");var nl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=ig.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(rg(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new lc.default({server:this.server,path:"/ws"})}start(e=3030){this.port=e,this.server.listen(e,()=>{console.log(a.green(`\u{1F3A8} Design artboard live at http://localhost:${e}`))})}stop(){this.wss.close(),this.server.close()}updateDesign(e){this.currentHtml=e;for(let t of this.wss.clients)t.readyState===lt.OPEN&&t.send("reload")}},ag=new nl;U();function Sk(s){let e=new Date(s),o=new Date().getTime()-s,n=Math.floor(o/6e4),r=Math.floor(o/36e5),i=Math.floor(o/864e5);return n<1?"just now":n<60?`${n}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:e.toLocaleDateString()}l(Sk,"formatDate");function li(s){return s.substring(0,8)}l(li,"formatShortId");function xk(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(xk,"truncatePath");function cg(){let e=new Bt().list();if(e.length===0){console.log(a.dim(" No saved sessions.")),console.log(a.dim(" Sessions are automatically saved when you use the CLI."));return}console.log(""),console.log(a.bold(" Recent Sessions")),console.log(a.dim(" \u2500".repeat(35))),console.log(""),console.log(a.dim(" ")+a.bold("ID".padEnd(10))+a.bold("Workspace".padEnd(42))+a.bold("Turns".padEnd(8))+a.bold("Last Active".padEnd(14))+a.bold("Preview")),console.log(a.dim(" "+"\u2500".repeat(90)));for(let t of e){let o=a.hex("#6B8DD6")(li(t.id)),n=xk(t.workspace),r=String(t.turnCount).padEnd(8),i=Sk(t.lastActive).padEnd(14),c=a.dim(t.preview.substring(0,30));console.log(` ${o} ${n.padEnd(40)} ${r}${i}${c}`)}console.log(""),console.log(a.dim(` ${e.length} session(s). Use "mc sessions show <id>" for details.`)),console.log("")}l(cg,"sessionsListCommand");function lg(s){let e=new Bt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.load(o.id);if(!n){console.log(a.red(` \u2717 Failed to load session "${o.id}".`));return}if(console.log(""),console.log(a.bold(` Session ${li(n.id)}`)),console.log(a.dim(" \u2500".repeat(35))),console.log(` ${a.bold("ID:")} ${n.id}`),console.log(` ${a.bold("Workspace:")} ${n.workspace}`),console.log(` ${a.bold("Model:")} ${n.model}`),console.log(` ${a.bold("Mode:")} ${n.mode}`),console.log(` ${a.bold("Started:")} ${new Date(n.startTime).toLocaleString()}`),console.log(` ${a.bold("Last active:")} ${new Date(n.lastActive).toLocaleString()}`),console.log(` ${a.bold("Turns:")} ${n.turnCount}`),console.log(` ${a.bold("Tokens:")} ${n.stats.tokensUsed.toLocaleString()}`),console.log(` ${a.bold("Tool calls:")} ${n.stats.toolCalls}`),n.stats.filesChanged.length>0){console.log(` ${a.bold("Files changed:")}`);for(let r of n.stats.filesChanged.slice(0,10))console.log(` ${r}`);n.stats.filesChanged.length>10&&console.log(a.dim(` ... and ${n.stats.filesChanged.length-10} more`))}console.log(""),console.log(a.bold(" Conversation:")),console.log(a.dim(" \u2500".repeat(35)));for(let r of n.messages.slice(-10)){let i=r.role==="user"?a.hex("#6B8DD6").bold("You"):r.role==="assistant"?a.hex("#A3CAD3").bold("MC"):a.dim("System"),c=new Date(r.timestamp).toLocaleTimeString(),u=r.content.substring(0,120).replace(/\n/g," ");console.log(` ${a.dim(c)} ${i}: ${u}`)}n.messages.length>10&&console.log(a.dim(` ... ${n.messages.length-10} earlier messages`)),console.log(""),console.log(a.dim(` Resume with: mc --continue ${li(n.id)}`)),console.log("")}l(lg,"sessionsShowCommand");function ug(s){let e=new Bt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.delete(o.id);console.log(n?a.green(` \u2713 Deleted session ${li(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(ug,"sessionsDeleteCommand");function dg(s=30){let e=new Bt,t=s*24*60*60*1e3,{deleted:o,remaining:n}=e.prune(t);console.log(o===0?a.dim(` No sessions older than ${s} days.`):a.green(` \u2713 Pruned ${o} session(s) older than ${s} days.`)),console.log(a.dim(` ${n} session(s) remaining.`))}l(dg,"sessionsPruneCommand");an();U();Z();te();var rl=class{static{l(this,"ScheduleApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/schedules`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async create(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify({prompt:e.prompt,cronExpression:e.cron,model:e.model,autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPR,workspace:e.workspace}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,scheduleId:o.id||o.scheduleId}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async list(){try{let e=await fetch(this.baseUrl,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).schedules||[]).map($k):[]}catch{return[]}}async delete(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:t.ok,error:t.ok?void 0:`HTTP ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async togglePause(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/${t?"pause":"resume"}`,{method:"POST",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:o.ok,error:o.ok?void 0:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};function Tn(){let s=J(),t=me()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new rl(s.platformUrl,t)}l(Tn,"getClient");async function il(s){Ck(s.cron)||(console.error(a.red(` \u274C Invalid cron expression: "${s.cron}"`)),console.log(a.dim(" Expected 5-field format: minute hour day-of-month month day-of-week")),console.log(a.dim(' Example: "0 9 * * 1" = Every Monday at 9:00 AM')),process.exit(4));let t=await Tn().create(s);t.success||(console.error(a.red(` \u274C Failed to create schedule: ${t.error}`)),process.exit(1)),console.log(""),console.log(a.bold(" \u23F0 Schedule created")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` ID: ${a.cyan(t.scheduleId)}`),console.log(` Prompt: "${s.prompt.substring(0,50)}${s.prompt.length>50?"...":""}"`),console.log(` Cron: ${s.cron} (${_k(s.cron)})`),console.log(` Auto-PR: ${s.autoPR?a.green("Yes"):"No"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Manage: ${a.dim("mc schedule list")}`),console.log("")}l(il,"scheduleCreate");async function pg(){let e=await Tn().list();if(e.length===0){console.log(a.dim(" No scheduled jobs found.")),console.log(a.dim(' Create one: mc schedule "your task" --cron "0 9 * * 1"'));return}let t=" "+"\u2500".repeat(90);console.log(t),console.log(a.bold(` ${"ID".padEnd(16)} ${"Status".padEnd(10)} ${"Cron".padEnd(16)} ${"Next Run".padEnd(20)} Prompt`)),console.log(t);for(let o of e){let n=o.status==="active"?a.green("\u25B6 Active"):a.yellow("\u23F8 Paused"),r=o.nextRunAt?o.nextRunAt.toLocaleString():"\u2014",i=o.prompt.length>30?`"${o.prompt.substring(0,28)}..."`:`"${o.prompt}"`;console.log(` ${o.id.padEnd(16)} ${n.padEnd(10)} ${o.cronExpression.padEnd(16)} ${r.padEnd(20)} ${i}`)}console.log(t)}l(pg,"scheduleList");async function mg(s){let t=await Tn().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(mg,"scheduleDelete");async function fg(s){let t=await Tn().togglePause(s,!0);t.success?console.log(a.yellow(` \u23F8 Schedule ${s} paused.`)):console.error(a.red(` \u274C Failed to pause schedule: ${t.error}`))}l(fg,"schedulePause");async function gg(s){let t=await Tn().togglePause(s,!1);t.success?console.log(a.green(` \u25B6 Schedule ${s} resumed.`)):console.error(a.red(` \u274C Failed to resume schedule: ${t.error}`))}l(gg,"scheduleResume");function $k(s){return{id:s.id||s.scheduleId,prompt:s.prompt||"",cronExpression:s.cronExpression||s.cron||"",model:s.model||"default",status:s.status||"active",autoBranch:s.autoBranch??!1,autoCommit:s.autoCommit??!1,autoPR:s.autoPR??!1,nextRunAt:s.nextRunAt?new Date(s.nextRunAt):void 0,lastRunAt:s.lastRunAt?new Date(s.lastRunAt):void 0,lastJobId:s.lastJobId,runCount:s.runCount||0,createdAt:new Date(s.createdAt||Date.now())}}l($k,"parseSchedule");function Ck(s){let e=s.trim().split(/\s+/);if(e.length!==5)return!1;let t=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return e.every(o=>t.test(o))}l(Ck,"validateCron");function _k(s){let e=s.trim().split(/\s+/);if(e.length!==5)return s;let[t,o,n,r,i]=e;return s==="0 * * * *"?"every hour":s==="*/5 * * * *"?"every 5 minutes":s==="*/15 * * * *"?"every 15 minutes":s==="*/30 * * * *"?"every 30 minutes":t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i==="*"?`daily at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[i]||`day ${i}`}s at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:s}l(_k,"describeCron");Rc();Ec();pn();var ke=y(require("node:fs"),1),_t=y(require("node:path"),1),Ho=require("node:child_process");U();Je();Z();te();async function hg(s){let e=await Ee(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=J(),n,r;if(s.pr?(n=await Rk(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Ho.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Ho.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Ho.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes")),!n.trim()){console.log(a.dim(" No changes to review."));return}let i=Ek(s.workspace),c=s.focus?s.focus.split(",").map(b=>b.trim()):[],u=Fk(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new Se({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",b=>{b.type==="streaming_chunk"&&(p+=b.content,s.output==="text"&&process.stdout.write(b.content))});try{await d.run(u)}catch(b){console.error(a.red(` \u274C Review failed: ${b instanceof Error?b.message:b}`)),process.exit(1)}let f=bg(p);switch(s.output){case"json":{let b=new ms;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let b=new fs(f,s.workspace);console.log(b.formatFindings(f));break}case"github":{for(let b of f){let k=b.severity==="high"?"error":b.severity==="medium"?"warning":"notice";console.log(`::${k} file=${b.file},line=${b.line}::${b.message}`)}break}case"text":default:f.length>0&&(console.log(""),wg(f));break}s.postComments&&s.pr&&await Ak(s.pr,f,s.workspace),s.autoFix&&f.some(b=>b.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),kg(f,s.workspace));let m={high:3,medium:2,low:1,info:0},g=m[s.severityThreshold]||3;f.some(b=>(m[b.severity]||0)>=g)&&process.exit(1)}l(hg,"reviewCommand");async function yg(s){let e=await Ee(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=J(),n=_t.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=Pk(n,[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java"]):r=[n]:(console.error(a.red(` \u274C Target not found: ${s.target}`)),process.exit(4)),r.length===0){console.log(a.dim(" No source files found to scan."));return}console.log(""),console.log(a.bold(` \u{1F50D} Bug Finder \u2014 scanning ${r.length} file(s)`)),console.log(a.dim(` Model: ${s.model}`)),console.log("");let i=1e5,c="",u=[];for(let S of r){let x=ke.readFileSync(S,"utf8");if(c.length+x.length>i)break;let E=_t.relative(s.workspace,S);c+=`
|
|
657
|
-
--- ${
|
|
658
|
-
${
|
|
659
|
-
`,u.push(
|
|
665
|
+
`.trim()}l(ng,"generateHtmlPreview");var rl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=rg.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(ng(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new lc.default({server:this.server,path:"/ws"})}start(e=3030){this.port=e,this.server.listen(e,()=>{console.log(a.green(`\u{1F3A8} Design artboard live at http://localhost:${e}`))})}stop(){this.wss.close(),this.server.close()}updateDesign(e){this.currentHtml=e;for(let t of this.wss.clients)t.readyState===lt.OPEN&&t.send("reload")}},ig=new rl;W();function Sk(s){let e=new Date(s),o=new Date().getTime()-s,n=Math.floor(o/6e4),r=Math.floor(o/36e5),i=Math.floor(o/864e5);return n<1?"just now":n<60?`${n}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:e.toLocaleDateString()}l(Sk,"formatDate");function li(s){return s.substring(0,8)}l(li,"formatShortId");function xk(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(xk,"truncatePath");function ag(){let e=new Lt().list();if(e.length===0){console.log(a.dim(" No saved sessions.")),console.log(a.dim(" Sessions are automatically saved when you use the CLI."));return}console.log(""),console.log(a.bold(" Recent Sessions")),console.log(a.dim(" \u2500".repeat(35))),console.log(""),console.log(a.dim(" ")+a.bold("ID".padEnd(10))+a.bold("Workspace".padEnd(42))+a.bold("Turns".padEnd(8))+a.bold("Last Active".padEnd(14))+a.bold("Preview")),console.log(a.dim(" "+"\u2500".repeat(90)));for(let t of e){let o=a.hex("#6B8DD6")(li(t.id)),n=xk(t.workspace),r=String(t.turnCount).padEnd(8),i=Sk(t.lastActive).padEnd(14),c=a.dim(t.preview.substring(0,30));console.log(` ${o} ${n.padEnd(40)} ${r}${i}${c}`)}console.log(""),console.log(a.dim(` ${e.length} session(s). Use "mc sessions show <id>" for details.`)),console.log("")}l(ag,"sessionsListCommand");function cg(s){let e=new Lt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.load(o.id);if(!n){console.log(a.red(` \u2717 Failed to load session "${o.id}".`));return}if(console.log(""),console.log(a.bold(` Session ${li(n.id)}`)),console.log(a.dim(" \u2500".repeat(35))),console.log(` ${a.bold("ID:")} ${n.id}`),console.log(` ${a.bold("Workspace:")} ${n.workspace}`),console.log(` ${a.bold("Model:")} ${n.model}`),console.log(` ${a.bold("Mode:")} ${n.mode}`),console.log(` ${a.bold("Started:")} ${new Date(n.startTime).toLocaleString()}`),console.log(` ${a.bold("Last active:")} ${new Date(n.lastActive).toLocaleString()}`),console.log(` ${a.bold("Turns:")} ${n.turnCount}`),console.log(` ${a.bold("Tokens:")} ${n.stats.tokensUsed.toLocaleString()}`),console.log(` ${a.bold("Tool calls:")} ${n.stats.toolCalls}`),n.stats.filesChanged.length>0){console.log(` ${a.bold("Files changed:")}`);for(let r of n.stats.filesChanged.slice(0,10))console.log(` ${r}`);n.stats.filesChanged.length>10&&console.log(a.dim(` ... and ${n.stats.filesChanged.length-10} more`))}console.log(""),console.log(a.bold(" Conversation:")),console.log(a.dim(" \u2500".repeat(35)));for(let r of n.messages.slice(-10)){let i=r.role==="user"?a.hex("#6B8DD6").bold("You"):r.role==="assistant"?a.hex("#A3CAD3").bold("MC"):a.dim("System"),c=new Date(r.timestamp).toLocaleTimeString(),u=r.content.substring(0,120).replace(/\n/g," ");console.log(` ${a.dim(c)} ${i}: ${u}`)}n.messages.length>10&&console.log(a.dim(` ... ${n.messages.length-10} earlier messages`)),console.log(""),console.log(a.dim(` Resume with: mc --continue ${li(n.id)}`)),console.log("")}l(cg,"sessionsShowCommand");function lg(s){let e=new Lt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.delete(o.id);console.log(n?a.green(` \u2713 Deleted session ${li(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(lg,"sessionsDeleteCommand");function ug(s=30){let e=new Lt,t=s*24*60*60*1e3,{deleted:o,remaining:n}=e.prune(t);console.log(o===0?a.dim(` No sessions older than ${s} days.`):a.green(` \u2713 Pruned ${o} session(s) older than ${s} days.`)),console.log(a.dim(` ${n} session(s) remaining.`))}l(ug,"sessionsPruneCommand");un();W();Q();ee();var il=class{static{l(this,"ScheduleApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/schedules`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async create(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify({prompt:e.prompt,cronExpression:e.cron,model:e.model,autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPR,workspace:e.workspace}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,scheduleId:o.id||o.scheduleId}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async list(){try{let e=await fetch(this.baseUrl,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).schedules||[]).map($k):[]}catch{return[]}}async delete(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:t.ok,error:t.ok?void 0:`HTTP ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async togglePause(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/${t?"pause":"resume"}`,{method:"POST",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:o.ok,error:o.ok?void 0:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};function Pn(){let s=K(),t=fe()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new il(s.platformUrl,t)}l(Pn,"getClient");async function al(s){Ck(s.cron)||(console.error(a.red(` \u274C Invalid cron expression: "${s.cron}"`)),console.log(a.dim(" Expected 5-field format: minute hour day-of-month month day-of-week")),console.log(a.dim(' Example: "0 9 * * 1" = Every Monday at 9:00 AM')),process.exit(4));let t=await Pn().create(s);t.success||(console.error(a.red(` \u274C Failed to create schedule: ${t.error}`)),process.exit(1)),console.log(""),console.log(a.bold(" \u23F0 Schedule created")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` ID: ${a.cyan(t.scheduleId)}`),console.log(` Prompt: "${s.prompt.substring(0,50)}${s.prompt.length>50?"...":""}"`),console.log(` Cron: ${s.cron} (${_k(s.cron)})`),console.log(` Auto-PR: ${s.autoPR?a.green("Yes"):"No"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Manage: ${a.dim("mc schedule list")}`),console.log("")}l(al,"scheduleCreate");async function dg(){let e=await Pn().list();if(e.length===0){console.log(a.dim(" No scheduled jobs found.")),console.log(a.dim(' Create one: mc schedule "your task" --cron "0 9 * * 1"'));return}let t=" "+"\u2500".repeat(90);console.log(t),console.log(a.bold(` ${"ID".padEnd(16)} ${"Status".padEnd(10)} ${"Cron".padEnd(16)} ${"Next Run".padEnd(20)} Prompt`)),console.log(t);for(let o of e){let n=o.status==="active"?a.green("\u25B6 Active"):a.yellow("\u23F8 Paused"),r=o.nextRunAt?o.nextRunAt.toLocaleString():"\u2014",i=o.prompt.length>30?`"${o.prompt.substring(0,28)}..."`:`"${o.prompt}"`;console.log(` ${o.id.padEnd(16)} ${n.padEnd(10)} ${o.cronExpression.padEnd(16)} ${r.padEnd(20)} ${i}`)}console.log(t)}l(dg,"scheduleList");async function pg(s){let t=await Pn().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(pg,"scheduleDelete");async function mg(s){let t=await Pn().togglePause(s,!0);t.success?console.log(a.yellow(` \u23F8 Schedule ${s} paused.`)):console.error(a.red(` \u274C Failed to pause schedule: ${t.error}`))}l(mg,"schedulePause");async function fg(s){let t=await Pn().togglePause(s,!1);t.success?console.log(a.green(` \u25B6 Schedule ${s} resumed.`)):console.error(a.red(` \u274C Failed to resume schedule: ${t.error}`))}l(fg,"scheduleResume");function $k(s){return{id:s.id||s.scheduleId,prompt:s.prompt||"",cronExpression:s.cronExpression||s.cron||"",model:s.model||"default",status:s.status||"active",autoBranch:s.autoBranch??!1,autoCommit:s.autoCommit??!1,autoPR:s.autoPR??!1,nextRunAt:s.nextRunAt?new Date(s.nextRunAt):void 0,lastRunAt:s.lastRunAt?new Date(s.lastRunAt):void 0,lastJobId:s.lastJobId,runCount:s.runCount||0,createdAt:new Date(s.createdAt||Date.now())}}l($k,"parseSchedule");function Ck(s){let e=s.trim().split(/\s+/);if(e.length!==5)return!1;let t=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return e.every(o=>t.test(o))}l(Ck,"validateCron");function _k(s){let e=s.trim().split(/\s+/);if(e.length!==5)return s;let[t,o,n,r,i]=e;return s==="0 * * * *"?"every hour":s==="*/5 * * * *"?"every 5 minutes":s==="*/15 * * * *"?"every 15 minutes":s==="*/30 * * * *"?"every 30 minutes":t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i==="*"?`daily at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[i]||`day ${i}`}s at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:s}l(_k,"describeCron");Rc();Ec();gn();var ke=b(require("node:fs"),1),_t=b(require("node:path"),1),Ho=require("node:child_process");W();Ke();Q();ee();async function gg(s){let e=await Fe(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=fe(),o=K(),n,r;if(s.pr?(n=await Rk(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Ho.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Ho.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Ho.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes")),!n.trim()){console.log(a.dim(" No changes to review."));return}let i=Ek(s.workspace),c=s.focus?s.focus.split(",").map(y=>y.trim()):[],u=Fk(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new xe({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",y=>{y.type==="streaming_chunk"&&(p+=y.content,s.output==="text"&&process.stdout.write(y.content))});try{await d.run(u)}catch(y){console.error(a.red(` \u274C Review failed: ${y instanceof Error?y.message:y}`)),process.exit(1)}let f=yg(p);switch(s.output){case"json":{let y=new fs;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let y=new gs(f,s.workspace);console.log(y.formatFindings(f));break}case"github":{for(let y of f){let S=y.severity==="high"?"error":y.severity==="medium"?"warning":"notice";console.log(`::${S} file=${y.file},line=${y.line}::${y.message}`)}break}case"text":default:f.length>0&&(console.log(""),bg(f));break}s.postComments&&s.pr&&await Ak(s.pr,f,s.workspace),s.autoFix&&f.some(y=>y.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),wg(f,s.workspace));let m={high:3,medium:2,low:1,info:0},g=m[s.severityThreshold]||3;f.some(y=>(m[y.severity]||0)>=g)&&process.exit(1)}l(gg,"reviewCommand");async function hg(s){let e=await Fe(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=fe(),o=K(),n=_t.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=Pk(n,[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java"]):r=[n]:(console.error(a.red(` \u274C Target not found: ${s.target}`)),process.exit(4)),r.length===0){console.log(a.dim(" No source files found to scan."));return}console.log(""),console.log(a.bold(` \u{1F50D} Bug Finder \u2014 scanning ${r.length} file(s)`)),console.log(a.dim(` Model: ${s.model}`)),console.log("");let i=1e5,c="",u=[];for(let D of r){let C=ke.readFileSync(D,"utf8");if(c.length+C.length>i)break;let x=_t.relative(s.workspace,D);c+=`
|
|
666
|
+
--- ${x} ---
|
|
667
|
+
${C}
|
|
668
|
+
`,u.push(x)}let d=s.focus?s.focus.split(",").map(D=>D.trim()):[],p=Tk(c,u,d),f=new xe({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),m="";f.on("event",D=>{D.type==="streaming_chunk"&&(m+=D.content)});try{await f.run(p)}catch(D){console.error(a.red(` \u274C Bug scan failed: ${D instanceof Error?D.message:D}`)),process.exit(1)}let g=yg(m);switch(s.output){case"json":console.log(JSON.stringify({scannedFiles:u,findings:g,summary:cl(g)},null,2));break;case"sarif":{let D=new gs(g,s.workspace);console.log(D.formatFindings(g));break}case"github":for(let D of g){let C=D.severity==="high"?"error":D.severity==="medium"?"warning":"notice";console.log(`::${C} file=${D.file},line=${D.line}::${D.message}`)}break;case"text":default:bg(g);break}s.autoFix&&g.some(D=>D.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),wg(g,s.workspace));let h={high:3,medium:2,low:1,info:0},y=h[s.severityThreshold]||3;g.some(D=>(h[D.severity]||0)>=y)&&process.exit(1)}l(hg,"bugfindCommand");function Ek(s){let e=_t.join(s,".monkeyscode","review-rules.md");return ke.existsSync(e)?ke.readFileSync(e,"utf8"):""}l(Ek,"loadReviewRules");function Fk(s,e,t,o){let n=`You are a senior code reviewer. Review the following ${e} for bugs, security issues, performance problems, and code quality.
|
|
660
669
|
|
|
661
670
|
For each finding, output in this EXACT format (one per line):
|
|
662
671
|
[SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
|
|
@@ -690,27 +699,27 @@ Focus on:
|
|
|
690
699
|
`),o+=`Files to scan: ${e.join(", ")}
|
|
691
700
|
|
|
692
701
|
`,o+=`Source code:
|
|
693
|
-
${s}`,o}l(Tk,"buildBugfindPrompt");function
|
|
694
|
-
`);for(let o=0;o<t.length;o++){let r=t[o].match(/\[SEVERITY:(HIGH|MEDIUM|LOW|INFO)\]\s*\[FILE:([^\]]+)\]\s*\[LINE:(\d+)\]\s*(.*)/i);if(r){let i={severity:r[1].toLowerCase(),file:r[2],line:parseInt(r[3],10),message:r[4].trim()};if(o+1<t.length){let c=t[o+1].match(/\[FIX:\d+\]\s*(.*)/);c&&(i.fix=c[1],o++)}e.push(i)}}return e}l(
|
|
702
|
+
${s}`,o}l(Tk,"buildBugfindPrompt");function yg(s){let e=[],t=s.split(`
|
|
703
|
+
`);for(let o=0;o<t.length;o++){let r=t[o].match(/\[SEVERITY:(HIGH|MEDIUM|LOW|INFO)\]\s*\[FILE:([^\]]+)\]\s*\[LINE:(\d+)\]\s*(.*)/i);if(r){let i={severity:r[1].toLowerCase(),file:r[2],line:parseInt(r[3],10),message:r[4].trim()};if(o+1<t.length){let c=t[o+1].match(/\[FIX:\d+\]\s*(.*)/);c&&(i.fix=c[1],o++)}e.push(i)}}return e}l(yg,"parseFindings");function bg(s){if(s.length===0){console.log(a.green(" \u2705 No issues found."));return}let e={high:"\u{1F534} HIGH",medium:"\u{1F7E1} MED ",low:"\u{1F7E2} LOW ",info:"\u{1F535} INFO"};console.log(` ${"\u2500".repeat(70)}`),console.log(` ${a.bold("Severity")} ${a.bold("File".padEnd(30))} ${a.bold("Line".padEnd(5))} ${a.bold("Issue")}`),console.log(` ${"\u2500".repeat(70)}`);for(let t of s){let o=e[t.severity]||t.severity,n=t.file.length>28?"\u2026"+t.file.slice(-27):t.file;console.log(` ${o} ${n.padEnd(30)} ${String(t.line).padEnd(5)} ${t.message.substring(0,50)}`)}console.log(` ${"\u2500".repeat(70)}`),console.log(` ${cl(s)}`),console.log("")}l(bg,"printFindingsTable");function cl(s){let e={high:0,medium:0,low:0,info:0};for(let t of s)e[t.severity]++;return`Found: ${e.high} high, ${e.medium} medium, ${e.low} low severity issues`}l(cl,"formatSeveritySummary");function wg(s,e){let t=0;for(let o of s){if(!o.fix)continue;let n=_t.resolve(e,o.file);if(ke.existsSync(n))try{let r=ke.readFileSync(n,"utf8").split(`
|
|
695
704
|
`);o.line>0&&o.line<=r.length&&(r[o.line-1]=o.fix,ke.writeFileSync(n,r.join(`
|
|
696
|
-
`)),t++,console.log(a.dim(` \u2713 Fixed ${o.file}:${o.line}`)))}catch{console.log(a.yellow(` \u26A0 Could not apply fix to ${o.file}:${o.line}`))}}console.log(` Applied ${t} fix(es).`)}l(
|
|
697
|
-
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(Rk,"fetchPRDiff");async function Ak(s,e,t){let o=
|
|
705
|
+
`)),t++,console.log(a.dim(` \u2713 Fixed ${o.file}:${o.line}`)))}catch{console.log(a.yellow(` \u26A0 Could not apply fix to ${o.file}:${o.line}`))}}console.log(` Applied ${t} fix(es).`)}l(wg,"applyFixes");async function Rk(s,e){let t=kg(e),o=Dg();if(!o){console.log(a.dim(" No GitHub/GitLab token found. Using local git diff against main."));try{return(0,Ho.execSync)("git diff main...HEAD",{cwd:e,encoding:"utf8"})}catch{return(0,Ho.execSync)("git diff HEAD~5...HEAD",{cwd:e,encoding:"utf8"})}}if(t.type==="github"){let n=await fetch(`https://api.github.com/repos/${t.owner}/${t.repo}/pulls/${s}`,{headers:{Authorization:`Bearer ${o}`,Accept:"application/vnd.github.v3.diff"}});if(!n.ok)throw new Error(`GitHub API error: ${n.status} ${n.statusText}`);return n.text()}if(t.type==="gitlab"){let n=await fetch(`https://gitlab.com/api/v4/projects/${encodeURIComponent(`${t.owner}/${t.repo}`)}/merge_requests/${s}/changes`,{headers:{"PRIVATE-TOKEN":o}});if(!n.ok)throw new Error(`GitLab API error: ${n.status} ${n.statusText}`);return(await n.json()).changes?.map(i=>i.diff).join(`
|
|
706
|
+
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(Rk,"fetchPRDiff");async function Ak(s,e,t){let o=kg(t),n=Dg();if(!n||o.type!=="github"){console.log(a.dim(" Review comment posting only supported for GitHub with GITHUB_TOKEN."));return}let r=e.map(i=>`**${i.severity.toUpperCase()}** \u2014 \`${i.file}:${i.line}\`: ${i.message}`).join(`
|
|
698
707
|
`);try{let i=await fetch(`https://api.github.com/repos/${o.owner}/${o.repo}/pulls/${s}/reviews`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({event:e.some(c=>c.severity==="high")?"REQUEST_CHANGES":"COMMENT",body:`## \u{1F50D} MonkeysCode Review
|
|
699
708
|
|
|
700
709
|
${r}
|
|
701
710
|
|
|
702
|
-
${
|
|
711
|
+
${cl(e)}`})});i.ok?console.log(a.green(` \u2705 Review posted on PR #${s}`)):console.log(a.yellow(` \u26A0 Failed to post review: ${i.status}`))}catch(i){console.log(a.yellow(` \u26A0 Failed to post review: ${i instanceof Error?i.message:i}`))}}l(Ak,"postReviewComments");function kg(s){try{let e=(0,Ho.execSync)("git remote get-url origin",{cwd:s,encoding:"utf8"}).trim(),t=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(t)return{type:"github",owner:t[1],repo:t[2],url:e};let o=e.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);return o?{type:"gitlab",owner:o[1],repo:o[2],url:e}:{type:"unknown",owner:"",repo:"",url:e}}catch{return{type:"unknown",owner:"",repo:"",url:""}}}l(kg,"getGitRemote");function Dg(){if(process.env.GITHUB_TOKEN)return process.env.GITHUB_TOKEN;if(process.env.GH_TOKEN)return process.env.GH_TOKEN;if(process.env.GITLAB_TOKEN)return process.env.GITLAB_TOKEN;try{let s=_t.join(process.cwd(),".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}try{let s=_t.join(process.env.HOME||process.env.USERPROFILE||"",".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}return null}l(Dg,"getGitToken");function Pk(s,e){let t=[];function n(r){if(t.length>=50)return;let i=ke.readdirSync(r,{withFileTypes:!0});for(let c of i){if(t.length>=50)return;let u=_t.join(r,c.name);if(c.isDirectory()){if(["node_modules",".git","vendor","dist","build","__pycache__",".next"].includes(c.name))continue;n(u)}else e.some(d=>c.name.endsWith(d))&&t.push(u)}}return l(n,"walk"),n(s),t}l(Pk,"collectFiles");tf();Hm();globalThis.__mcChalk=a;var ml="0.1.8",qo="auto";function $g(s){let e=No(s);return{defaultModel:e.get("model"),defaultMode:e.get("defaultMode"),maxTokens:e.get("maxTokens")}}l($g,"loadConfig");var z=new Fl;z.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
|
|
703
712
|
Runs independently of the IDE and Agent Manager.
|
|
704
|
-
Connects directly to model-proxy via SSE streaming.`).version(di);V.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",qo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new At("-o, --output <format>","Output format").choices(["text","json","jsonl","diff","markdown","github","azure","sarif","stream"]).default("text")).option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("--continue","Resume the last session",!1).option("--auto-approve","Auto-approve all tool calls",!1).option("--approve-for-me","Smart auto-approval (safe=auto, risky=prompt, dangerous=block)",!1).option("--yolo","Bypass all permission checks (requires explicit opt-in)",!1).addOption(new At("--permission-mode <mode>","Permission mode").choices(["default","plan","ask","acceptEdits","bypassPermissions"]).default("default")).option("--allowed-tools <tools>","Comma-separated list of allowed tool names","").option("--denied-tools <tools>","Comma-separated list of denied tool names","").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new At("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new At("--sandbox-provider <provider>","Sandbox provider override").choices(["auto","bubblewrap","sandbox-exec","docker","windows-sandbox"])).option("--no-hooks","Disable all lifecycle hooks").option("--hook-timeout <ms>","Hook timeout in milliseconds","10000").option("--no-web","Disable web search (air-gapped mode)").option("--auto-branch","Create a new branch for changes",!1).option("--auto-commit","Auto-commit changes after successful run",!1).option("--auto-pr","Create a pull request after background job completes",!1).option("--worktree","Run agent in an isolated git worktree",!1).option("--resume <job-id>","Resume from a completed cloud job").option("--profile <name>","Auth profile to use","default").option("--endpoint <url>","Custom model gateway URL").option("--ca-cert <path>","Custom CA certificate for corporate proxies").option("--offline","Offline mode \u2014 no internet, local models only",!1).option("--accessible","Screen reader-friendly output (no ANSI, no spinners)",!1).option("--screen-reader","Alias for --accessible",!1).option("--max-cost <dollars>","Maximum session cost in dollars (e.g. 2.00)").option("--max-tokens <count>","Maximum total tokens (input + output)").option("--timeout <ms>","Headless timeout in milliseconds (default: 300000)","300000").action(async(s,e)=>{let t=N.resolve(e.workspace),o=Cg(t),n=s||e.prompt;if(n&&n.startsWith("/"))switch(n.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":n=void 0;break;case"/version":case"/v":console.log(di),process.exit(0);break;case"/doctor":await rn(),process.exit(0);break;case"/exit":case"/quit":case"/q":process.exit(0);break;default:break}if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=wt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await gm(c)});var An=V.command("auth").description("Manage authentication");An.command("login").description("Authenticate with MonkeysCode (device code flow \u2014 opens browser)").option("--email","Use email/password login instead of browser").option("--sso","Use enterprise SSO (SAML/OIDC)").option("--profile <name>","Auth profile name","default").action(async s=>{s.sso?await wa(s.profile):s.email?await ma():await pa()});An.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ka(s.profile));An.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>ga(s,e.profile));An.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await Zn(s.profile));An.command("refresh").description("Manually refresh the access token").action(async()=>await ha());V.command("status").description("Show account and agent status").action(async()=>{let s=Cg(),e=new Co,{loadSettings:t}=await Promise.resolve().then(()=>(Z(),ve)),o=t();e.printBanner("System Status"),await Zn(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});V.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>rn(s));V.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Lm(s));V.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Ym(s));V.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Xm(s,e));V.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";nf({since:s.since,review:s.review,mode:e})});var Pn=V.command("config").description("Manage CLI configuration");Pn.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=N.resolve(t.workspace),n=No(o),r=t.project?"project":"global",i=e;e==="true"?i=!0:e==="false"?i=!1:isNaN(Number(e))||(i=Number(e));let c=n.set(s,i,r);c&&(console.error(` \u26A0\uFE0F ${c}`),process.exit(1)),console.log(` Set ${s} = ${e} [${r}]`)});Pn.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=No(N.resolve(e.workspace));if(s){let o=t.getResolved(s);console.log(` ${s} = ${JSON.stringify(o.value)} [${o.source}]`)}else console.log(JSON.stringify(t.getConfig(),null,2))});Pn.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=No(N.resolve(s.workspace));Fm(e)});Pn.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{No().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});Pn.command("path").description("Show config file locations").action(()=>{let s=P(),t=No().getPaths();console.log(` Global: ${t.global}`),console.log(` Project: ${t.project}`),console.log(` Data: ${s.data}`),console.log(` Logs: ${s.logs}`),console.log(` PID: ${s.pidFile}`)});V.command("index [path]").description("Index a workspace for context retrieval").option("--force","Force full re-index",!1).action(async(s,e)=>{let t=N.resolve(s||"."),o=new Co;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new uo;o.startSpinner("Connecting to daemon...");try{await n.connect(),o.succeedSpinner("Connected"),o.startSpinner("Indexing workspace...");let r=await n.call("index",{workspace:t,force:e.force});o.succeedSpinner("Indexing complete"),console.log(` Files scanned: ${r.files_scanned}`),console.log(` Chunks created: ${r.chunks_created}`),console.log(` Duration: ${r.duration_ms}ms`),console.log("")}catch(r){o.failSpinner("Indexing failed"),console.error(` Error: ${r instanceof Error?r.message:r}`)}finally{n.disconnect()}});var Mn=V.command("mcp").description("Manage MCP (Model Context Protocol) servers");Mn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await km(N.resolve(s.workspace))});Mn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{Dm(N.resolve(o.workspace),s,e,t||[])});Mn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{vm(N.resolve(e.workspace),s)});Mn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Sm(N.resolve(e.workspace),s)});Mn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{xm(s)});var Gk=V.command("agents").description("View active agent sessions dashboard").action(async()=>{await Oc(!0)});Gk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Oc(!1)});var $s=V.command("context").description("Semantic code search and workspace indexing");$s.command("index").description("Index the current workspace for semantic search").action(async()=>{await Bo(["index"],{})});$s.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await Bo(["search",s],{topK:e.topK})});$s.command("status").description("Show index status and statistics").action(async()=>{await Bo(["status"],{})});$s.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await Bo(["rebuild"],{})});$s.command("related <file>").description("Find files related to a given file").action(async s=>{await Bo(["related",s],{})});$s.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await Bo(["rank",s],{})});var Vo=V.command("triggers").description("Manage event-driven agent triggers");Vo.command("list").description("Show configured triggers").action(async()=>{await ho(["list"],{})});Vo.command("add").description("Add a new trigger").requiredOption("--event <type>","Event type (github.*, cron, file.changed)").requiredOption("--prompt <text>","Agent prompt when trigger fires").option("--name <name>","Trigger name").option("--schedule <cron>","Cron expression (for cron events)").option("--model <model>","Model to use").option("--filter <json>","Event filter (JSON)").action(async s=>{await ho(["add"],s)});Vo.command("remove <name>").description("Remove a trigger by name").action(async s=>{await ho(["remove",s],{})});Vo.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await ho(["test",s],{})});Vo.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await ho(["enable",s],{})});Vo.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await ho(["disable",s],{})});Vo.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await ho(["serve"],{port:s.port})});V.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish, pwsh)").option("--install","Show install instructions instead of the script").action((s,e)=>{let t=["bash","zsh","fish","pwsh"];t.includes(s)||(console.error(` Invalid shell: ${s}. Supported: ${t.join(", ")}`),process.exit(1));let o=s;e.install?(console.log(""),console.log(ym(o)),console.log("")):console.log(hm(o))});var mi=V.command("sessions").description("Manage saved conversation sessions");mi.command("list").description("List recent sessions").action(()=>cg());mi.command("show <id>").description("Show session details").action(s=>lg(s));mi.command("delete <id>").description("Delete a session").action(s=>ug(s));mi.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{dg(parseInt(s.olderThan,10))});var Zt=V.command("jobs").description("Manage background agent jobs");Zt.command("list").description("List all background jobs").option("--status <status>","Filter by status: running, queued, completed, failed").option("--since <duration>","Show jobs since (e.g., 7d, 24h)").option("--limit <n>","Max results","20").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(te(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new je(o.platformUrl,n.access_token),i=parseInt(s.limit,10),[c,u]=await Promise.all([r.list({status:s.status,since:s.since,limit:i}).catch(()=>[]),Promise.resolve(bc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);vc(d)});Zt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=wc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=kc(s);Ur(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(te(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new je(o.platformUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);Ur(i,c)});Zt.command("logs <id>").description("Full log output of a job").option("--follow","Live tail logs",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(te(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new je(n.platformUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Wr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>($g(),xg));u(s,`"${c.prompt.substring(0,60)}" \u2014 ${c.status}${c.duration?` in ${Math.round(c.duration/1e3)}s`:""}`,c.status==="completed")}}else{let c=await i.logs(s);for(let u of c)Wr(u)}});Zt.command("cancel <id>").description("Cancel a running or queued job").option("--force","Skip confirmation",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(te(),ge)),n=t(),r=o();if(r?.access_token||(console.error("Not authenticated."),process.exit(3)),!e.force){let d=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(f=>d.question(` Cancel job ${s}? [y/N] `,f));if(d.close(),p.toLowerCase()!=="y"){console.log(" Cancelled.");return}}let c=await new je(n.platformUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Zt.command("retry <id>").description("Retry a failed job").option("--model <model>","Use a different model").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(te(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new je(n.platformUrl,r.access_token).retry(s,{model:e.model});c.success?(console.log(` \u{1F504} Job retried \u2192 new ID: ${c.jobId}`),c.branch&&console.log(` Branch: ${c.branch}`)):console.error(` \u274C Retry failed: ${c.error}`)});Zt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(te(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new je(o.platformUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Zt.command("pull <id>").description("Pull changes from a completed job into current branch").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(te(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new je(n.platformUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),Dc(N.resolve(e.workspace),s,c.branch)});Zt.action(()=>{Zt.outputHelp()});var Go=V.command("schedule").description("Manage scheduled/recurring agent jobs").argument("[prompt]","Task prompt (shorthand for `schedule create`)").option("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".");Go.action(async(s,e)=>{s&&e.cron?await il({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Go.outputHelp()});Go.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await il({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)})});Go.command("list").description("List all scheduled jobs").action(async()=>{await pg()});Go.command("delete <id>").description("Delete a scheduled job").action(async s=>{await mg(s)});Go.command("pause <id>").description("Pause a scheduled job").action(async s=>{await fg(s)});Go.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await gg(s)});var Rn=V.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");Rn.action(async(s,e)=>{s.length>0?await Hr({tasks:s,workspace:N.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):Rn.outputHelp()});Rn.command("spawn").description("Spawn a team of agents, each in its own worktree").argument("<tasks...>","Task prompts for each agent").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Hr({tasks:s,workspace:N.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});Rn.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{Fc(N.resolve(s.workspace))});Rn.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{Tc(N.resolve(e.workspace),s)});var pi=V.command("worktrees").description("Manage git worktrees used by agent teams");pi.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=hs(N.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});pi.command("clean").description("Remove stale worktrees older than TTL").option("--ttl <hours>","TTL in hours (default: 24)","24").option("--force","Force removal",!1).option("--workspace <path>","Workspace path",".").action(s=>{let e=Zp({workspace:N.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});pi.action(()=>{pi.outputHelp()});var dl=V.command("messages").description("Cross-session messaging");dl.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Z(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(te(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new dn(o.platformUrl,n.access_token,"cli").getMessageHistory(parseInt(s.limit,10));if(i.length===0){console.log(" No recent messages.");return}console.log(" \u{1F4E8} Recent Messages");let c=" "+"\u2500".repeat(70);console.log(c),console.log(` ${"Time".padEnd(12)} ${"From".padEnd(16)} ${"To".padEnd(16)} Message`),console.log(c);for(let u of i){let d=u.timestamp.toLocaleTimeString(),p=u.from.substring(0,14),f=u.to==="broadcast"?"[broadcast]":u.to.substring(0,14),m=u.content.substring(0,40)+(u.content.length>40?"...":"");console.log(` ${d.padEnd(12)} ${p.padEnd(16)} ${f.padEnd(16)} "${m}"`)}console.log(c)});dl.action(()=>{dl.outputHelp()});var _g=V.command("hooks").description("Manage lifecycle hooks");_g.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Ic(N.resolve(s.workspace))});_g.action(()=>{Ic(N.resolve("."))});var Eg=V.command("models").description("Manage available models");Eg.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(te(),ge))).loadAuth();Fa(s?.org?.plan)});Eg.action(async()=>{let s=(await Promise.resolve().then(()=>(te(),ge))).loadAuth();Fa(s?.org?.plan)});V.command("usage").description("Show monthly usage breakdown").action(async()=>{await Tm()});V.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md"),o=N.join(e,".monkeyscode","config.json");if(K.existsSync(t)&&K.existsSync(o)){console.log(""),console.log(a.yellow(" \u26A0\uFE0F .monkeyscode/ already exists.")),console.log(a.dim(` ${t}`)),console.log(a.dim(` ${o}`)),console.log(" Use `mc memory` to modify rules, `mc config set` for config."),console.log("");return}console.log(""),console.log(a.bold(" \u{1F435} Initializing MonkeysCode")),console.log("");let n=["# Project Conventions",""],r=N.join(e,"package.json"),i=N.join(e,"Cargo.toml"),c=N.join(e,"pyproject.toml"),u=N.join(e,"tsconfig.json"),d=N.join(e,"go.mod"),p=K.readdirSync(e).filter(h=>h.endsWith(".csproj")),f="Unknown";if(K.existsSync(r))try{let h=JSON.parse(K.readFileSync(r,"utf8"));f=h.type==="module"?"TypeScript/ESM":"JavaScript/CJS",n.push(`## Language: ${f}`),h.scripts?.test&&n.push(`- Test command: \`${h.scripts.test}\``),h.scripts?.lint&&n.push(`- Lint command: \`${h.scripts.lint}\``),h.scripts?.build&&n.push(`- Build command: \`${h.scripts.build}\``),h.dependencies?.react&&n.push("- Framework: React"),h.dependencies?.next&&n.push("- Framework: Next.js"),h.dependencies?.express&&n.push("- Server: Express"),h.dependencies?.fastify&&n.push("- Server: Fastify"),n.push("")}catch{}K.existsSync(u)&&(n.push("## TypeScript"),n.push("- Use strict TypeScript with explicit types"),n.push("- Prefer `interface` over `type` for object shapes"),n.push(""),f="TypeScript"),K.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),K.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),K.existsSync(d)&&(n.push("## Language: Go"),n.push("- Follow Go conventions (gofmt, error wrapping)"),n.push(""),f="Go"),p.length>0&&(n.push("## Language: C# / .NET"),n.push("- Follow .NET naming conventions (PascalCase)"),n.push(""),f="C#/.NET"),n.push("## Style"),n.push("- Keep functions small and focused"),n.push("- Write clear error messages"),n.push("- Add JSDoc/docstrings for public APIs"),n.push(""),n.push("## Testing"),n.push("- Write tests for all new functionality"),n.push("- Use descriptive test names"),n.push("");let m=n.join(`
|
|
705
|
-
`),g=Math.ceil(m.length/4);g>2e3&&console.log(a.yellow(` \u26A0\uFE0F Rules file is ~${g} tokens. Consider keeping it under 2000 for optimal context usage.`)),
|
|
713
|
+
Connects directly to model-proxy via SSE streaming.`).version(ml);z.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",qo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Rt("-o, --output <format>","Output format").choices(["text","json","jsonl","diff","markdown","github","azure","sarif","stream"]).default("text")).option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("--continue","Resume the last session",!1).option("--auto-approve","Auto-approve all tool calls",!1).option("--approve-for-me","Smart auto-approval (safe=auto, risky=prompt, dangerous=block)",!1).option("--yolo","Bypass all permission checks (requires explicit opt-in)",!1).addOption(new Rt("--permission-mode <mode>","Permission mode").choices(["default","plan","ask","acceptEdits","bypassPermissions"]).default("default")).option("--allowed-tools <tools>","Comma-separated list of allowed tool names","").option("--denied-tools <tools>","Comma-separated list of denied tool names","").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new Rt("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Rt("--sandbox-provider <provider>","Sandbox provider override").choices(["auto","bubblewrap","sandbox-exec","docker","windows-sandbox"])).option("--no-hooks","Disable all lifecycle hooks").option("--hook-timeout <ms>","Hook timeout in milliseconds","10000").option("--no-web","Disable web search (air-gapped mode)").option("--auto-branch","Create a new branch for changes",!1).option("--auto-commit","Auto-commit changes after successful run",!1).option("--auto-pr","Create a pull request after background job completes",!1).option("--worktree","Run agent in an isolated git worktree",!1).option("--resume <job-id>","Resume from a completed cloud job").option("--profile <name>","Auth profile to use","default").option("--endpoint <url>","Custom model gateway URL").option("--ca-cert <path>","Custom CA certificate for corporate proxies").option("--offline","Offline mode \u2014 no internet, local models only",!1).option("--accessible","Screen reader-friendly output (no ANSI, no spinners)",!1).option("--screen-reader","Alias for --accessible",!1).option("--max-cost <dollars>","Maximum session cost in dollars (e.g. 2.00)").option("--max-tokens <count>","Maximum total tokens (input + output)").option("--timeout <ms>","Headless timeout in milliseconds (default: 300000)","300000").action(async(s,e)=>{let t=L.resolve(e.workspace),o=$g(t),n=s||e.prompt;if(n&&n.startsWith("/"))switch(n.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":n=void 0;break;case"/version":case"/v":console.log(ml),process.exit(0);break;case"/doctor":await ln(),process.exit(0);break;case"/exit":case"/quit":case"/q":process.exit(0);break;default:break}if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=wt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await hm(c)});var On=z.command("auth").description("Manage authentication");On.command("login").description("Authenticate with MonkeysCode (device code flow \u2014 opens browser)").option("--email","Use email/password login instead of browser").option("--sso","Use enterprise SSO (SAML/OIDC)").option("--profile <name>","Auth profile name","default").action(async s=>{s.sso?await wa(s.profile):s.email?await ma():await pa()});On.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ka(s.profile));On.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>ga(s,e.profile));On.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await er(s.profile));On.command("refresh").description("Manually refresh the access token").action(async()=>await ha());z.command("status").description("Show account and agent status").action(async()=>{let s=$g(),e=new Co,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),o=t();e.printBanner("System Status"),await er(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});z.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>ln(s));z.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Nm(s));z.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Km(s));z.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Ym(s,e));z.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";sf({since:s.since,review:s.review,mode:e})});var In=z.command("config").description("Manage CLI configuration");In.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=L.resolve(t.workspace),n=No(o),r=t.project?"project":"global",i=e;e==="true"?i=!0:e==="false"?i=!1:isNaN(Number(e))||(i=Number(e));let c=n.set(s,i,r);c&&(console.error(` \u26A0\uFE0F ${c}`),process.exit(1)),console.log(` Set ${s} = ${e} [${r}]`)});In.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=No(L.resolve(e.workspace));if(s){let o=t.getResolved(s);console.log(` ${s} = ${JSON.stringify(o.value)} [${o.source}]`)}else console.log(JSON.stringify(t.getConfig(),null,2))});In.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=No(L.resolve(s.workspace));Tm(e)});In.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{No().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});In.command("path").description("Show config file locations").action(()=>{let s=A(),t=No().getPaths();console.log(` Global: ${t.global}`),console.log(` Project: ${t.project}`),console.log(` Data: ${s.data}`),console.log(` Logs: ${s.logs}`),console.log(` PID: ${s.pidFile}`)});z.command("index [path]").description("Index a workspace for context retrieval").option("--force","Force full re-index",!1).action(async(s,e)=>{let t=L.resolve(s||"."),o=new Co;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new po;o.startSpinner("Connecting to daemon...");try{await n.connect(),o.succeedSpinner("Connected"),o.startSpinner("Indexing workspace...");let r=await n.call("index",{workspace:t,force:e.force});o.succeedSpinner("Indexing complete"),console.log(` Files scanned: ${r.files_scanned}`),console.log(` Chunks created: ${r.chunks_created}`),console.log(` Duration: ${r.duration_ms}ms`),console.log("")}catch(r){o.failSpinner("Indexing failed"),console.error(` Error: ${r instanceof Error?r.message:r}`)}finally{n.disconnect()}});var jn=z.command("mcp").description("Manage MCP (Model Context Protocol) servers");jn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await Dm(L.resolve(s.workspace))});jn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{vm(L.resolve(o.workspace),s,e,t||[])});jn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{Sm(L.resolve(e.workspace),s)});jn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await xm(L.resolve(e.workspace),s)});jn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{$m(s)});var Gk=z.command("agents").description("View active agent sessions dashboard").action(async()=>{await Oc(!0)});Gk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Oc(!1)});var Cs=z.command("context").description("Semantic code search and workspace indexing");Cs.command("index").description("Index the current workspace for semantic search").action(async()=>{await Bo(["index"],{})});Cs.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await Bo(["search",s],{topK:e.topK})});Cs.command("status").description("Show index status and statistics").action(async()=>{await Bo(["status"],{})});Cs.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await Bo(["rebuild"],{})});Cs.command("related <file>").description("Find files related to a given file").action(async s=>{await Bo(["related",s],{})});Cs.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await Bo(["rank",s],{})});var Vo=z.command("triggers").description("Manage event-driven agent triggers");Vo.command("list").description("Show configured triggers").action(async()=>{await yo(["list"],{})});Vo.command("add").description("Add a new trigger").requiredOption("--event <type>","Event type (github.*, cron, file.changed)").requiredOption("--prompt <text>","Agent prompt when trigger fires").option("--name <name>","Trigger name").option("--schedule <cron>","Cron expression (for cron events)").option("--model <model>","Model to use").option("--filter <json>","Event filter (JSON)").action(async s=>{await yo(["add"],s)});Vo.command("remove <name>").description("Remove a trigger by name").action(async s=>{await yo(["remove",s],{})});Vo.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await yo(["test",s],{})});Vo.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await yo(["enable",s],{})});Vo.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await yo(["disable",s],{})});Vo.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await yo(["serve"],{port:s.port})});z.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish, pwsh)").option("--install","Show install instructions instead of the script").action((s,e)=>{let t=["bash","zsh","fish","pwsh"];t.includes(s)||(console.error(` Invalid shell: ${s}. Supported: ${t.join(", ")}`),process.exit(1));let o=s;e.install?(console.log(""),console.log(bm(o)),console.log("")):console.log(ym(o))});var pi=z.command("sessions").description("Manage saved conversation sessions");pi.command("list").description("List recent sessions").action(()=>ag());pi.command("show <id>").description("Show session details").action(s=>cg(s));pi.command("delete <id>").description("Delete a session").action(s=>lg(s));pi.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{ug(parseInt(s.olderThan,10))});var Qt=z.command("jobs").description("Manage background agent jobs");Qt.command("list").description("List all background jobs").option("--status <status>","Filter by status: running, queued, completed, failed").option("--since <duration>","Show jobs since (e.g., 7d, 24h)").option("--limit <n>","Max results","20").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Ne(o.platformUrl,n.access_token),i=parseInt(s.limit,10),[c,u]=await Promise.all([r.list({status:s.status,since:s.since,limit:i}).catch(()=>[]),Promise.resolve(bc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);vc(d)});Qt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=wc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=kc(s);Wr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Ne(o.platformUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);Wr(i,c)});Qt.command("logs <id>").description("Full log output of a job").option("--follow","Live tail logs",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Ne(n.platformUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Hr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(xg(),Sg));u(s,`"${c.prompt.substring(0,60)}" \u2014 ${c.status}${c.duration?` in ${Math.round(c.duration/1e3)}s`:""}`,c.status==="completed")}}else{let c=await i.logs(s);for(let u of c)Hr(u)}});Qt.command("cancel <id>").description("Cancel a running or queued job").option("--force","Skip confirmation",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();if(r?.access_token||(console.error("Not authenticated."),process.exit(3)),!e.force){let d=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(f=>d.question(` Cancel job ${s}? [y/N] `,f));if(d.close(),p.toLowerCase()!=="y"){console.log(" Cancelled.");return}}let c=await new Ne(n.platformUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Qt.command("retry <id>").description("Retry a failed job").option("--model <model>","Use a different model").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.platformUrl,r.access_token).retry(s,{model:e.model});c.success?(console.log(` \u{1F504} Job retried \u2192 new ID: ${c.jobId}`),c.branch&&console.log(` Branch: ${c.branch}`)):console.error(` \u274C Retry failed: ${c.error}`)});Qt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Ne(o.platformUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Qt.command("pull <id>").description("Pull changes from a completed job into current branch").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.platformUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),Dc(L.resolve(e.workspace),s,c.branch)});Qt.action(()=>{Qt.outputHelp()});var Go=z.command("schedule").description("Manage scheduled/recurring agent jobs").argument("[prompt]","Task prompt (shorthand for `schedule create`)").option("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".");Go.action(async(s,e)=>{s&&e.cron?await al({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:L.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Go.outputHelp()});Go.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await al({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:L.resolve(e.workspace)})});Go.command("list").description("List all scheduled jobs").action(async()=>{await dg()});Go.command("delete <id>").description("Delete a scheduled job").action(async s=>{await pg(s)});Go.command("pause <id>").description("Pause a scheduled job").action(async s=>{await mg(s)});Go.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await fg(s)});var Mn=z.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");Mn.action(async(s,e)=>{s.length>0?await Gr({tasks:s,workspace:L.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):Mn.outputHelp()});Mn.command("spawn").description("Spawn a team of agents, each in its own worktree").argument("<tasks...>","Task prompts for each agent").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Gr({tasks:s,workspace:L.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});Mn.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{Fc(L.resolve(s.workspace))});Mn.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{Tc(L.resolve(e.workspace),s)});var di=z.command("worktrees").description("Manage git worktrees used by agent teams");di.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=ys(L.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});di.command("clean").description("Remove stale worktrees older than TTL").option("--ttl <hours>","TTL in hours (default: 24)","24").option("--force","Force removal",!1).option("--workspace <path>","Workspace path",".").action(s=>{let e=em({workspace:L.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});di.action(()=>{di.outputHelp()});var pl=z.command("messages").description("Cross-session messaging");pl.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new fn(o.platformUrl,n.access_token,"cli").getMessageHistory(parseInt(s.limit,10));if(i.length===0){console.log(" No recent messages.");return}console.log(" \u{1F4E8} Recent Messages");let c=" "+"\u2500".repeat(70);console.log(c),console.log(` ${"Time".padEnd(12)} ${"From".padEnd(16)} ${"To".padEnd(16)} Message`),console.log(c);for(let u of i){let d=u.timestamp.toLocaleTimeString(),p=u.from.substring(0,14),f=u.to==="broadcast"?"[broadcast]":u.to.substring(0,14),m=u.content.substring(0,40)+(u.content.length>40?"...":"");console.log(` ${d.padEnd(12)} ${p.padEnd(16)} ${f.padEnd(16)} "${m}"`)}console.log(c)});pl.action(()=>{pl.outputHelp()});var Cg=z.command("hooks").description("Manage lifecycle hooks");Cg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Ic(L.resolve(s.workspace))});Cg.action(()=>{Ic(L.resolve("."))});var _g=z.command("models").description("Manage available models");_g.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),ge))).loadAuth();Fa(s?.org?.plan)});_g.action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),ge))).loadAuth();Fa(s?.org?.plan)});z.command("usage").description("Show monthly usage breakdown").action(async()=>{await Rm()});z.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=L.resolve(s.workspace),t=L.join(e,".monkeyscode","rules.md"),o=L.join(e,".monkeyscode","config.json");if(Y.existsSync(t)&&Y.existsSync(o)){console.log(""),console.log(a.yellow(" \u26A0\uFE0F .monkeyscode/ already exists.")),console.log(a.dim(` ${t}`)),console.log(a.dim(` ${o}`)),console.log(" Use `mc memory` to modify rules, `mc config set` for config."),console.log("");return}console.log(""),console.log(a.bold(" \u{1F435} Initializing MonkeysCode")),console.log("");let n=["# Project Conventions",""],r=L.join(e,"package.json"),i=L.join(e,"Cargo.toml"),c=L.join(e,"pyproject.toml"),u=L.join(e,"tsconfig.json"),d=L.join(e,"go.mod"),p=Y.readdirSync(e).filter(h=>h.endsWith(".csproj")),f="Unknown";if(Y.existsSync(r))try{let h=JSON.parse(Y.readFileSync(r,"utf8"));f=h.type==="module"?"TypeScript/ESM":"JavaScript/CJS",n.push(`## Language: ${f}`),h.scripts?.test&&n.push(`- Test command: \`${h.scripts.test}\``),h.scripts?.lint&&n.push(`- Lint command: \`${h.scripts.lint}\``),h.scripts?.build&&n.push(`- Build command: \`${h.scripts.build}\``),h.dependencies?.react&&n.push("- Framework: React"),h.dependencies?.next&&n.push("- Framework: Next.js"),h.dependencies?.express&&n.push("- Server: Express"),h.dependencies?.fastify&&n.push("- Server: Fastify"),n.push("")}catch{}Y.existsSync(u)&&(n.push("## TypeScript"),n.push("- Use strict TypeScript with explicit types"),n.push("- Prefer `interface` over `type` for object shapes"),n.push(""),f="TypeScript"),Y.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),Y.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),Y.existsSync(d)&&(n.push("## Language: Go"),n.push("- Follow Go conventions (gofmt, error wrapping)"),n.push(""),f="Go"),p.length>0&&(n.push("## Language: C# / .NET"),n.push("- Follow .NET naming conventions (PascalCase)"),n.push(""),f="C#/.NET"),n.push("## Style"),n.push("- Keep functions small and focused"),n.push("- Write clear error messages"),n.push("- Add JSDoc/docstrings for public APIs"),n.push(""),n.push("## Testing"),n.push("- Write tests for all new functionality"),n.push("- Use descriptive test names"),n.push("");let m=n.join(`
|
|
714
|
+
`),g=Math.ceil(m.length/4);g>2e3&&console.log(a.yellow(` \u26A0\uFE0F Rules file is ~${g} tokens. Consider keeping it under 2000 for optimal context usage.`)),Y.mkdirSync(L.join(e,".monkeyscode"),{recursive:!0}),Y.writeFileSync(t,m,"utf8"),Y.existsSync(o)||Y.writeFileSync(o,JSON.stringify({model:"auto",defaultMode:"fast"},null,2),"utf8"),console.log(` Detected: ${f}`),console.log(" Created: .monkeyscode/rules.md"),console.log(" Created: .monkeyscode/config.json"),console.log(""),console.log(a.dim(" Edit rules with: mc memory edit")),console.log(a.dim(" Edit config with: mc config set <key> <value> --project")),console.log("")});var _s=z.command("memory").description("Manage project conventions and rules");_s.command("show").description("Show resolved rules from all sources").option("--workspace <path>","Workspace path",".").action(s=>{let e=L.resolve(s.workspace),t=A(),o=L.join(e,".monkeyscode","rules.md"),n=L.join(t.config,"rules.md"),r=L.join(e,".monkeyscode","MEMORY.md");if(console.log(""),console.log(a.bold(" \u{1F4DD} Resolved Rules")),console.log(a.dim(" "+"\u2500".repeat(50))),Y.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=Y.readFileSync(o,"utf8");for(let u of i.split(`
|
|
706
715
|
`))console.log(` ${u}`);let c=Math.ceil(i.length/4);c>2e3&&console.log(a.yellow(`
|
|
707
|
-
\u26A0\uFE0F ~${c} tokens \u2014 consider shortening for better context usage.`)),console.log("")}else console.log(a.dim(" No project rules. Run: mc init")),console.log("");if(
|
|
708
|
-
`))console.log(` ${i}`);console.log("")}if(
|
|
709
|
-
`))console.log(` ${i}`);console.log("")}console.log("")});
|
|
710
|
-
`,r=s.replace(/^["']|["']$/g,"");
|
|
716
|
+
\u26A0\uFE0F ~${c} tokens \u2014 consider shortening for better context usage.`)),console.log("")}else console.log(a.dim(" No project rules. Run: mc init")),console.log("");if(Y.existsSync(n)){console.log(a.cyan(" [global]")+a.dim(` ${n}`));for(let i of Y.readFileSync(n,"utf8").split(`
|
|
717
|
+
`))console.log(` ${i}`);console.log("")}if(Y.existsSync(r)){console.log(a.magenta(" [memory]")+a.dim(` ${r}`));for(let i of Y.readFileSync(r,"utf8").split(`
|
|
718
|
+
`))console.log(` ${i}`);console.log("")}console.log("")});_s.command("add <rule>").description("Add a convention rule").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=L.resolve(e.workspace),o=L.join(t,".monkeyscode","rules.md");Y.mkdirSync(L.dirname(o),{recursive:!0});let n=Y.existsSync(o)?Y.readFileSync(o,"utf8"):`# Project Conventions
|
|
719
|
+
`,r=s.replace(/^["']|["']$/g,"");Y.writeFileSync(o,n.trimEnd()+`
|
|
711
720
|
- `+r+`
|
|
712
|
-
`,"utf8"),console.log(` \u2705 Added: ${r}`)});
|
|
713
|
-
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&
|
|
714
|
-
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});
|
|
715
|
-
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});
|
|
716
|
-
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});
|
|
721
|
+
`,"utf8"),console.log(` \u2705 Added: ${r}`)});_s.command("edit").description("Open rules in $EDITOR").option("--workspace <path>","Workspace path",".").action(s=>{let e=L.resolve(s.workspace),t=L.join(e,".monkeyscode","rules.md"),o=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!Y.existsSync(t)){console.log(a.dim(" No rules file. Run: mc init"));return}try{let{execSync:n}=require("node:child_process");n(`${o} "${t}"`,{stdio:"inherit"}),console.log(" \u2705 Rules file saved.")}catch{console.error(` \u274C Failed to open editor: ${o}`)}});_s.command("forget <pattern>").description("Remove a learned convention matching the pattern").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=L.resolve(e.workspace),o=L.join(t,".monkeyscode","MEMORY.md"),n=L.join(t,".monkeyscode","rules.md"),r=0,i=s.replace(/^["']|["']$/g,"");for(let c of[o,n]){if(!Y.existsSync(c))continue;let d=Y.readFileSync(c,"utf8").split(`
|
|
722
|
+
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&Y.writeFileSync(c,d.join(`
|
|
723
|
+
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});_s.command("consolidate").description("Consolidate sessions into memory (alias for mc dream)").option("--since <duration>","Review sessions from the last N days","7").option("--review","Show proposed updates for approval before writing").option("--workspace <path>","Workspace path",".").action(async s=>{console.log(a.dim(" \u2192 Delegating to `mc dream`...")),console.log(""),await z.parseAsync(["node","mc","dream","--since",s.since,...s.review?["--review"]:[],"--workspace",s.workspace])});_s.action(s=>{let e=process.cwd(),t=L.join(e,".monkeyscode","rules.md");if(Y.existsSync(t)){console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules")),console.log(a.dim(` ${t}`)),console.log(a.dim(" "+"\u2500".repeat(40)));for(let o of Y.readFileSync(t,"utf8").split(`
|
|
724
|
+
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});z.command("rules").description("Show resolved rules (alias for mc memory show)").option("--workspace <path>","Workspace path",".").action(s=>{let e=L.resolve(s.workspace),t=L.join(e,".monkeyscode","rules.md");if(Y.existsSync(t)){console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules"));for(let o of Y.readFileSync(t,"utf8").split(`
|
|
725
|
+
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});z.command("review").description("Review code changes for bugs, security issues, and code quality").option("--staged","Review only staged changes",!1).option("--pr <number>","Review a specific PR number").option("--focus <areas>","Focus on specific areas (comma-separated: security, performance, a11y)").addOption(new Rt("-o, --output <format>","Output format").choices(["text","json","github","sarif"]).default("text")).option("--post-comments","Post review comments on the PR",!1).option("--suggest","Include fix suggestions",!1).option("--auto-fix","Automatically apply suggested fixes",!1).addOption(new Rt("--severity-threshold <level>","Minimum severity to fail CI").choices(["high","medium","low"]).default("high")).option("--model <model>","Model to use",qo).option("--workspace <path>","Workspace path",".").action(async s=>{let e=wt(s.model);await gg({workspace:L.resolve(s.workspace),model:e,staged:s.staged,pr:s.pr?parseInt(s.pr,10):void 0,focus:s.focus,output:s.output,postComments:s.postComments,suggest:s.suggest,autoFix:s.autoFix,severityThreshold:s.severityThreshold})});z.command("bugfind [target]").description("Scan files for potential bugs with severity ratings").addOption(new Rt("-o, --output <format>","Output format").choices(["text","json","github","sarif"]).default("text")).option("--auto-fix","Automatically apply suggested fixes",!1).option("--focus <areas>","Focus on specific areas (comma-separated: security, performance)").addOption(new Rt("--severity-threshold <level>","Minimum severity to fail CI").choices(["high","medium","low"]).default("high")).option("--model <model>","Model to use",qo).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let t=wt(e.model);await hg({workspace:L.resolve(e.workspace),model:t,target:s||".",output:e.output,autoFix:e.autoFix,focus:e.focus,severityThreshold:e.severityThreshold})});var Eg=z.command("trace").description("Inspect agent execution traces");Eg.command("list").action(async s=>{xf(s)});Eg.command("show <id>").option("--tree").option("--flamegraph").option("--verbose").action(async(s,e)=>{$f(s,e)});var zo=z.command("marketplace").description("Browse and manage agent skills");zo.command("search <query>").option("--category <cat>").action(async(s,e)=>{await Ef(s,e)});zo.command("install <id>").action(async s=>{await Ff(s)});zo.command("uninstall <id>").action(async s=>{Tf(s)});zo.command("publish <dir>").option("--name <name>").option("--bump <bump>").action(async(s,e)=>{await Rf(s,e)});zo.command("update").action(async()=>{await Af()});zo.command("list").action(()=>{Pf()});zo.command("featured").action(async()=>{await Mf()});z.command("join <sessionId>").description("Join a live collaboration session").action(async s=>{await og(s)});z.command("share").description("Start a new live collaboration session").action(async()=>{await sg()&&console.log(a.dim("Host session running..."))});var mi=z.command("permissions").description("Manage natural language policies");mi.command("set <text>").action(async s=>{await Uf(s)});mi.command("list").action(()=>{Wf()});mi.command("remove <index>").action(s=>{Hf(parseInt(s,10))});mi.command("test <tool> <args>").action((s,e)=>{Gf(s,e)});var Fg=z.command("benchmark").description("Run agent benchmarks");Fg.command("custom <path>").option("--model [models...]").option("--workspace <dir>").action(async(s,e)=>{await Yf(s,e)});Fg.command("results").option("--limit <n>").option("--format <fmt>").action(s=>{Xf(s)});z.command("design").description("Start the local design artboard server").option("--port <p>").action(s=>{ig.start(s.port?parseInt(s.port,10):void 0)});Xm()&&process.argv.length<=2?Qm().then(()=>z.parse()).catch(()=>z.parse()):(zm("cli_start",{version:ml}),z.parse());
|