monkeyscode-cli 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/monkeyscode-cli.cjs +224 -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 jg=Object.create;var Ts=Object.defineProperty;var Ng=Object.getOwnPropertyDescriptor;var Lg=Object.getOwnPropertyNames;var Bg=Object.getPrototypeOf,Ug=Object.prototype.hasOwnProperty;var l=(s,e)=>Ts(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),Re=(s,e)=>{for(var t in e)Ts(s,t,{get:e[t],enumerable:!0})},ml=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Lg(e))!Ug.call(s,n)&&n!==t&&Ts(s,n,{get:()=>e[n],enumerable:!(o=Ng(e,n))||o.enumerable});return s};var y=(s,e,t)=>(t=s!=null?jg(Bg(s)):{},ml(e||!s||!s.__esModule?Ts(t,"default",{value:s,enumerable:!0}):t,s)),Rs=s=>ml(Ts({},"__esModule",{value:!0}),s);var As=ce(yi=>{var In=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}},hi=class extends In{static{l(this,"InvalidArgumentError")}constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};yi.CommanderError=In;yi.InvalidArgumentError=hi});var jn=ce(wi=>{var{InvalidArgumentError:Wg}=As(),bi=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 Wg(`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 Hg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}l(Hg,"humanReadableArgName");wi.Argument=bi;wi.humanReadableArgName=Hg});var vi=ce(Di=>{var{humanReadableArgName:Gg}=jn(),ki=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=>Gg(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 fl(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 fl(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}l(fl,"stripColor");Di.Help=ki;Di.stripColor=fl});var Ci=ce($i=>{var{InvalidArgumentError:qg}=As(),Si=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=Vg(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 qg(`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?gl(this.name().replace(/^no-/,"")):gl(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},xi=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 gl(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(gl,"camelcase");function Vg(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(Vg,"splitOptionFlags");$i.Option=Si;$i.DualOptions=xi});var yl=ce(hl=>{function zg(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(zg,"editDistance");function Jg(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=zg(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(Jg,"suggestSimilar");hl.suggestSimilar=Jg});var Dl=ce(Ri=>{var Kg=require("node:events").EventEmitter,_i=require("node:child_process"),Rt=require("node:path"),Nn=require("node:fs"),ee=require("node:process"),{Argument:Yg,humanReadableArgName:Xg}=jn(),{CommanderError:Ei}=As(),{Help:Qg,stripColor:Zg}=vi(),{Option:bl,DualOptions:eh}=Ci(),{suggestSimilar:wl}=yl(),Fi=class s extends Kg{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=>ee.stdout.write(t),"writeOut"),writeErr:l(t=>ee.stderr.write(t),"writeErr"),outputError:l((t,o)=>o(t),"outputError"),getOutHelpWidth:l(()=>ee.stdout.isTTY?ee.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>ee.stderr.isTTY?ee.stderr.columns:void 0,"getErrHelpWidth"),getOutHasColors:l(()=>Ti()??(ee.stdout.isTTY&&ee.stdout.hasColors?.()),"getOutHasColors"),getErrHasColors:l(()=>Ti()??(ee.stderr.isTTY&&ee.stderr.hasColors?.()),"getErrHasColors"),stripColor:l(t=>Zg(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 Qg,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 Yg(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 Ei(e,t,o)),ee.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 bl(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 bl)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){ee.versions?.electron&&(t.from="electron");let n=ee.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=ee.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":ee.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(Nn.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=Rt.resolve(p,f);if(Nn.existsSync(m))return m;if(n.includes(Rt.extname(f)))return;let g=n.find(h=>Nn.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=Nn.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=Rt.resolve(Rt.dirname(p),c)}if(c){let p=r(c,i);if(!p&&!e._executableFile&&this._scriptPath){let f=Rt.basename(this._scriptPath,Rt.extname(this._scriptPath));f!==this._name&&(p=r(c,`${f}-${e._name}`))}i=p||i}o=n.includes(Rt.extname(i));let u;ee.platform!=="win32"?o?(t.unshift(i),t=kl(ee.execArgv).concat(t),u=_i.spawn(ee.argv[0],t,{stdio:"inherit"})):u=_i.spawn(i,t,{stdio:"inherit"}):(this._checkForMissingExecutable(i,c,e._name),t.unshift(i),t=kl(ee.execArgv).concat(t),u=_i.spawn(ee.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{ee.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 Ei(p,"commander.executeSubCommandAsync","(close)")):ee.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)ee.exit(1);else{let f=new Ei(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 ee.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()}`,ee.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new
|
|
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 ee.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()}`,ee.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new eh(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=wl(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=wl(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=>Xg(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=Rt.basename(e,Rt.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(ee.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 kl(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(kl,"incrementNodeInspectorPort");function Ti(){if(ee.env.NO_COLOR||ee.env.FORCE_COLOR==="0"||ee.env.FORCE_COLOR==="false")return!1;if(ee.env.FORCE_COLOR||ee.env.CLICOLOR_FORCE!==void 0)return!0}l(Ti,"useColor");Ri.Command=Fi;Ri.useColor=Ti});var $l=ce(qe=>{var{Argument:vl}=jn(),{Command:Ai}=Dl(),{CommanderError:th,InvalidArgumentError:Sl}=As(),{Help:oh}=vi(),{Option:xl}=Ci();qe.program=new Ai;qe.createCommand=s=>new Ai(s);qe.createOption=(s,e)=>new xl(s,e);qe.createArgument=(s,e)=>new vl(s,e);qe.Command=Ai;qe.Option=xl;qe.Argument=vl;qe.Help=oh;qe.CommanderError=th;qe.InvalidArgumentError=Sl;qe.InvalidOptionArgumentError=Sl});function rh(){let s=new Map;for(let[e,t]of Object.entries(ne)){for(let[o,n]of Object.entries(t))ne[o]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[o]=ne[o],s.set(n[0],n[1]);Object.defineProperty(ne,e,{value:t,enumerable:!1})}return Object.defineProperty(ne,"codes",{value:s,enumerable:!1}),ne.color.close="\x1B[39m",ne.bgColor.close="\x1B[49m",ne.color.ansi=El(),ne.color.ansi256=Fl(),ne.color.ansi16m=Tl(),ne.bgColor.ansi=El(10),ne.bgColor.ansi256=Fl(10),ne.bgColor.ansi16m=Tl(10),Object.defineProperties(ne,{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=>ne.rgbToAnsi256(...ne.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)=>ne.ansi256ToAnsi(ne.rgbToAnsi256(e,t,o)),"value"),enumerable:!1},hexToAnsi:{value:l(e=>ne.ansi256ToAnsi(ne.hexToAnsi256(e)),"value"),enumerable:!1}}),ne}var El,Fl,Tl,ne,yD,sh,nh,bD,ih,ot,Rl=G(()=>{El=l((s=0)=>e=>`\x1B[${e+s}m`,"wrapAnsi16"),Fl=l((s=0)=>e=>`\x1B[${38+s};5;${e}m`,"wrapAnsi256"),Tl=l((s=0)=>(e,t,o)=>`\x1B[${38+s};2;${e};${t};${o}m`,"wrapAnsi16m"),ne={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(ne.modifier),sh=Object.keys(ne.color),nh=Object.keys(ne.bgColor),bD=[...sh,...nh];l(rh,"assembleStyles");ih=rh(),ot=ih});function Ve(s,e=globalThis.Deno?globalThis.Deno.args:Bn.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 ah(){if("FORCE_COLOR"in re)return re.FORCE_COLOR==="true"?1:re.FORCE_COLOR==="false"?0:re.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(re.FORCE_COLOR,10),3)}function ch(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function lh(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let o=ah();o!==void 0&&(Ln=o);let n=t?Ln: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 re&&"AGENT_NAME"in re)return 1;if(s&&!e&&n===void 0)return 0;let r=n||0;if(re.TERM==="dumb")return r;if(Bn.default.platform==="win32"){let i=Pl.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in re)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in re)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in re)||re.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in re)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(re.TEAMCITY_VERSION)?1:0;if(re.COLORTERM==="truecolor"||re.TERM==="xterm-kitty"||re.TERM==="xterm-ghostty"||re.TERM==="wezterm")return 3;if("TERM_PROGRAM"in re){let i=Number.parseInt((re.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(re.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(re.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(re.TERM)||"COLORTERM"in re?1:r}function Al(s,e={}){let t=lh(s,{streamIsTTY:s&&s.isTTY,...e});return ch(t)}var Bn,Pl,Pi,re,Ln,uh,Ml,Ol=G(()=>{Bn=y(require("node:process"),1),Pl=y(require("node:os"),1),Pi=y(require("node:tty"),1);l(Ve,"hasFlag");({env:re}=Bn.default);Ve("no-color")||Ve("no-colors")||Ve("color=false")||Ve("color=never")?Ln=0:(Ve("color")||Ve("colors")||Ve("color=true")||Ve("color=always"))&&(Ln=1);l(ah,"envForceColor");l(ch,"translateLevel");l(lh,"_supportsColor");l(Al,"createSupportsColor");uh={stdout:Al({isTTY:Pi.default.isatty(1)}),stderr:Al({isTTY:Pi.default.isatty(2)})},Ml=uh});function Il(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 jl(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=Pl(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Rs.prototype,zo);oh=Rs(),pD=Rs({level:Il?Il.level:0}),a=oh});var Hl=ce((RD,mh)=>{mh.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 Hi=ce((AD,ql)=>{"use strict";var Hn=Object.assign({},Hl()),Gl=Object.keys(Hn);Object.defineProperty(Hn,"random",{get(){let s=Math.floor(Math.random()*Gl.length),e=Gl[s];return Hn[e]}});ql.exports=Hn});var nu=ce((iv,su)=>{su.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 vo={};Te(vo,{detectPlatform:()=>De,ensureDir:()=>qn,getPlatformInfo:()=>xe,getPlatformPaths:()=>T,isLocalModel:()=>Mh,isUNCPath:()=>Ph,normalizePath:()=>Ah,resolveSymlinks:()=>Oh});function De(){switch(Ft.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function T(s){switch(s??De()){case"macos":{let t=Ft.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=Ft.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=Do.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=Do.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(Ft.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(Ft.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 xe(){let s=De();return{os:s,arch:Ft.arch(),shell:Fh(s),supportsColor:Th(),supportsUnicode:Rh(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Fh(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 Th(){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 Rh(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 qn(s){Do.mkdirSync(s,{recursive:!0})}function Ah(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function Ph(s){return s.startsWith("\\\\")||s.startsWith("//")}function Oh(s){try{return Do.realpathSync(s)}catch{return s}}function Mh(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 Ft,se,Do,X=H(()=>{"use strict";Ft=y(require("node:os"),1),se=y(require("node:path"),1),Do=y(require("node:fs"),1);l(De,"detectPlatform");l(T,"getPlatformPaths");l(xe,"getPlatformInfo");l(Fh,"detectShell");l(Th,"detectColorSupport");l(Rh,"detectUnicodeSupport");l(qn,"ensureDir");l(Ah,"normalizePath");l(Ph,"isUNCPath");l(Oh,"resolveSymlinks");l(Mh,"isLocalModel")});function Uh(){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 j(){let s=xe(),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=Uh();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??j();return e.nerdFont?Ih:e.unicode?jh:Nh}function Ve(s){return(s??j()).unicode?Lh:Bh}var Ih,jh,Nh,Lh,Bh,Ce=H(()=>{"use strict";X();Ih={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"},jh={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"},Nh={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:">"},Lh={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Bh={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(Uh,"detectNerdFont");l(j,"detectCapabilities");l(W,"getIcons");l(Ve,"getBoxChars")});function Kn(){if(mt)return mt;let s=process.platform;return s==="darwin"&&wu("security")?(mt=new ra,mt):s==="linux"&&wu("secret-tool")?(mt=new ia,mt):s==="win32"?(mt=new aa,mt):(mt=new ca,mt)}function wu(s){try{return(0,tt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function ku(s){return s.replace(/[\\"$`!]/g,"\\$&")}function ay(){try{if(process.platform==="linux")return pe.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,tt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${Ko.hostname()}-${Ko.userInfo().username}-${Ko.homedir()}`}var pe,Zt,Ko,Rt,tt,Qt,ra,ia,aa,ca,mt,Du=H(()=>{"use strict";pe=y(require("node:fs"),1),Zt=y(require("node:path"),1),Ko=y(require("node:os"),1),Rt=y(require("node:crypto"),1),tt=require("node:child_process");X();Qt="monkeyscode-cli",ra=class{static{l(this,"KeychainStore")}get(e){try{return(0,tt.execSync)(`security find-generic-password -s "${Qt}" -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,tt.execSync)(`security add-generic-password -s "${Qt}" -a "${e}" -w "${ku(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,tt.execSync)(`security delete-generic-password -s "${Qt}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ia=class{static{l(this,"SecretToolStore")}get(e){try{return(0,tt.execSync)(`secret-tool lookup service "${Qt}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,tt.execSync)(`echo -n "${ku(t)}" | secret-tool store --label="${Qt}:${e}" service "${Qt}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,tt.execSync)(`secret-tool clear service "${Qt}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},aa=class{static{l(this,"WinCredStore")}get(e){try{let t=`${Qt}:${e}`,o=`
|
|
31
|
+
`,n)}while(o!==-1);return r+=s.slice(n),r}var Nl=G(()=>{l(Il,"stringReplaceAll");l(jl,"stringEncaseCRLFWithFirstIndex")});function Ms(s){return ph(s)}var Ll,Bl,Mi,Jo,Ps,Ul,Ko,dh,ph,Oi,mh,fh,Ii,Un,gh,hh,ED,a,U=G(()=>{Rl();Ol();Nl();({stdout:Ll,stderr:Bl}=Ml),Mi=Symbol("GENERATOR"),Jo=Symbol("STYLER"),Ps=Symbol("IS_EMPTY"),Ul=["ansi","ansi","ansi256","ansi16m"],Ko=Object.create(null),dh=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=Ll?Ll.level:0;s.level=e.level===void 0?t:e.level},"applyOptions"),ph=l(s=>{let e=l((...t)=>t.join(" "),"chalk");return dh(e,s),Object.setPrototypeOf(e,Ms.prototype),e},"chalkFactory");l(Ms,"createChalk");Object.setPrototypeOf(Ms.prototype,Function.prototype);for(let[s,e]of Object.entries(ot))Ko[s]={get(){let t=Un(this,Ii(e.open,e.close,this[Jo]),this[Ps]);return Object.defineProperty(this,s,{value:t}),t}};Ko.visible={get(){let s=Un(this,this[Jo],!0);return Object.defineProperty(this,"visible",{value:s}),s}};Oi=l((s,e,t,...o)=>s==="rgb"?e==="ansi16m"?ot[t].ansi16m(...o):e==="ansi256"?ot[t].ansi256(ot.rgbToAnsi256(...o)):ot[t].ansi(ot.rgbToAnsi(...o)):s==="hex"?Oi("rgb",e,t,...ot.hexToRgb(...o)):ot[t][s](...o),"getModelAnsi"),mh=["rgb","hex","ansi256"];for(let s of mh){Ko[s]={get(){let{level:t}=this;return function(...o){let n=Ii(Oi(s,Ul[t],"color",...o),ot.color.close,this[Jo]);return Un(this,n,this[Ps])}}};let e="bg"+s[0].toUpperCase()+s.slice(1);Ko[e]={get(){let{level:t}=this;return function(...o){let n=Ii(Oi(s,Ul[t],"bgColor",...o),ot.bgColor.close,this[Jo]);return Un(this,n,this[Ps])}}}}fh=Object.defineProperties(()=>{},{...Ko,level:{enumerable:!0,get(){return this[Mi].level},set(s){this[Mi].level=s}}}),Ii=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"),Un=l((s,e,t)=>{let o=l((...n)=>gh(o,n.length===1?""+n[0]:n.join(" ")),"builder");return Object.setPrototypeOf(o,fh),o[Mi]=s,o[Jo]=e,o[Ps]=t,o},"createBuilder"),gh=l((s,e)=>{if(s.level<=0||!e)return s[Ps]?"":e;let t=s[Jo];if(t===void 0)return e;let{openAll:o,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Il(e,t.close,t.open),t=t.parent;let r=e.indexOf(`
|
|
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=`
|
|
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,11 +38,11 @@ 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{pe.existsSync(t)&&pe.unlinkSync(t)}catch{}}getFilePath(e){let t=
|
|
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(""),n.user_code&&(console.log(t?` Your code: ${a.bold.bgBlue.white(` ${r} `)}`:` Your code: ${r}`),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
|
|
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
|
|
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 Xn,Cu=H(()=>{"use strict";l(xu,"parseSSEStream");Xn=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 _u(s=!0){return s?$u:$u.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var $u,Eu=H(()=>{"use strict";$u=[{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(_u,"getToolSchemas")});var ve={};Te(ve,{getSetting:()=>dy,loadSettings:()=>z,saveSettings:()=>uy});function z(){let s=T(),e=ba.join(s.config,"settings.json");try{if(eo.existsSync(e)){let t=JSON.parse(eo.readFileSync(e,"utf8"));return{...Fu,...t}}}catch{}return{...Fu}}function uy(s){let e=T();eo.mkdirSync(e.config,{recursive:!0});let t=ba.join(e.config,"settings.json"),n={...z(),...s};eo.writeFileSync(t,JSON.stringify(n,null,2))}function dy(s){return z()[s]}var eo,ba,Fu,Q=H(()=>{"use strict";eo=y(require("node:fs"),1),ba=y(require("node:path"),1);X();Fu={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(z,"loadSettings");l(uy,"saveSettings");l(dy,"getSetting")});var L,le,Ne,wa,py,Qn,Tu=H(()=>{"use strict";L=y(require("node:fs"),1),le=y(require("node:path"),1),Ne=require("node:child_process"),wa=require("node:fs"),py={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"},Qn=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=py[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(`
|
|
41
|
+
`;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{pe.existsSync(t)&&pe.unlinkSync(t)}catch{}}getFilePath(e){let t=P();return to.join(t.config,`cred-${e}.enc`)}getDpapi(e){let t=this.getFilePath(e);try{if(!pe.existsSync(t))return null;let o=pe.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"});pe.mkdirSync(to.dirname(o),{recursive:!0}),pe.writeFileSync(o,n.trim(),{mode:384})}catch{throw new Error("Failed to encrypt credential via DPAPI")}}},da=class{static{l(this,"EncryptedFileStore")}keyPath;storePath;constructor(){let e=P();this.keyPath=to.join(e.config,".cred-key"),this.storePath=to.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(pe.existsSync(this.keyPath))return Buffer.from(pe.readFileSync(this.keyPath,"utf8"),"hex")}catch{}let e=Dy(),t=Mt.randomBytes(16),o=Mt.scryptSync(e,t,32),n=t.toString("hex")+":"+o.toString("hex");return pe.mkdirSync(to.dirname(this.keyPath),{recursive:!0}),pe.writeFileSync(this.keyPath,n,{mode:384}),o}loadStore(){try{if(!pe.existsSync(this.storePath))return{};let e=pe.readFileSync(this.storePath,"utf8"),[t,o]=e.split(":"),n=this.getOrCreateKey(),r=Buffer.from(t,"hex"),i=Mt.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=Mt.randomBytes(16),n=Mt.createCipheriv("aes-256-cbc",t,o),r=n.update(JSON.stringify(e),"utf8","hex");r+=n.final("hex"),pe.mkdirSync(to.dirname(this.storePath),{recursive:!0}),pe.writeFileSync(this.storePath,o.toString("hex")+":"+r,{mode:384})}},yt=null;l(Qn,"getCredentialStore");l(Su,"hasCommand");l(xu,"escapeShellArg");l(Dy,"getMachineId")});var ge={};Re(ge,{authLogin:()=>pa,authLoginEmail:()=>ma,authLoginSSO:()=>wa,authLogout:()=>fa,authLogoutProfile:()=>ka,authRefresh:()=>ha,authSetToken:()=>ga,authStatus:()=>Zn,getAccessToken:()=>Ee,isAuthenticated:()=>ba,loadAuth:()=>me});async function pa(){let s=O(),e=W(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Device Authentication"):" Device Authentication"),console.log(t?a.dim(` API: ${Oe}`):` API: ${Oe}`),console.log("");try{let o=await fetch(`${Oe}/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(""),n.user_code&&(console.log(t?` Your code: ${a.bold.bgBlue.white(` ${r} `)}`:` Your code: ${r}`),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 vy(c);try{let f=await(await fetch(`${Oe}/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;Qo({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=O(),e=W(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Email Login"):" Email Login"),console.log(t?a.dim(` API: ${Oe}`):` API: ${Oe}`),console.log("");let o=Cu.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 Sy(" 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(`${Oe}/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;Qo({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=W(),e=P(),t=Ot.join(e.config,"auth.json");_e.existsSync(t)&&_e.unlinkSync(t),console.log(` ${s.success} Logged out.`),console.log("")}function ga(s,e){let t=W();Qo({access_token:s,auth_method:"apikey",profile:e},e),console.log(` ${t.success} Token saved${e?` (profile: ${e})`:""}.`),console.log("")}async function Zn(s){let e=O(),t=W(e),o=e.ansi,n=me(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 Ee(s);if(u){let d=await fetch(`${Oe}/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: ${Oe}`):` API: ${Oe}`)}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=O(),e=W(s),t=me();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(`${Oe}/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;Qo({...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(`${Oe}/v1/auth/me`,{headers:{Authorization:`Bearer ${s}`}});if(e.ok)return await e.json()}catch{}return null}function me(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=`${_u}-${t}`;try{let c=Qn().get(o);if(c)return JSON.parse(c)}catch{}let n=P(),r=t==="default"?Ot.join(n.config,"auth.json"):Ot.join(n.config,`auth-${t}.json`);try{if(_e.existsSync(r)){let i=JSON.parse(_e.readFileSync(r,"utf8"));try{Qn().set(o,JSON.stringify(i)),_e.unlinkSync(r)}catch{}return i}}catch{}return null}function ba(){return me()!==null}async function Ee(s){let e=me(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(`${Oe}/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 Qo({...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 Qo(s,e){let t=e||s.profile||"default",o=`${_u}-${t}`;try{Qn().set(o,JSON.stringify({...s,profile:t}))}catch{let n=P();_e.mkdirSync(n.config,{recursive:!0});let r=t==="default"?Ot.join(n.config,"auth.json"):Ot.join(n.config,`auth-${t}.json`);_e.writeFileSync(r,JSON.stringify({...s,profile:t},null,2),{mode:384})}}function vy(s){return new Promise(e=>setTimeout(e,s))}function Sy(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=O(),t=W(e),o=e.ansi,n=P(),r=Ot.join(n.config,"config.json"),i={};try{_e.existsSync(r)&&(i=JSON.parse(_e.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:S}=await import("node:child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";S(`${x} "${g.toString()}"`)}catch{}let{createServer:h}=await import("node:http"),k=await new Promise(S=>{let x=h((E,$)=>{let F=new URL(E.url||"/",`http://localhost:${p}`);if(F.pathname==="/callback"){let j=F.searchParams.get("code");if(F.searchParams.get("state")!==m){$.writeHead(400,{"Content-Type":"text/html"}),$.end("<html><body><h2>\u274C State mismatch. Please try again.</h2></body></html>"),x.close(),S(null);return}$.writeHead(200,{"Content-Type":"text/html"}),$.end("<html><body><h2>\u2705 Authentication successful!</h2><p>You can close this tab.</p></body></html>"),x.close(),S(j)}else $.writeHead(404),$.end()});x.listen(p,()=>{console.log(o?a.dim(` Listening on http://localhost:${p}/callback ...`):` Listening on http://localhost:${p}/callback ...`)}),setTimeout(()=>{x.close(),S(null)},3e5)});if(!k){console.log(` ${t.error} SSO login failed or timed out.`),console.log("");return}try{let S=await fetch(`${Oe}/v1/auth/sso/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:k,redirect_uri:f,client_id:u||"monkeyscode-cli"})});if(!S.ok)throw new Error(`Token exchange failed: HTTP ${S.status}`);let x=await S.json(),E=await ya(x.access_token),$=Date.now()+(x.expires_in||172800)*1e3;Qo({access_token:x.access_token,refresh_token:x.refresh_token,expires_at:$,auth_method:"sso",user:E?{id:E.id?.toString(),email:E.email,name:E.name,avatar_url:E.avatar_url??void 0}:void 0,org:E?.orgs?.[0]?{id:E.orgs[0].id?.toString(),name:E.orgs[0].name,plan:E.orgs[0].plan_code}:void 0},s),console.log(""),console.log(` ${t.success} SSO login successful!`),E&&console.log(` ${t.info} ${E.email} (${E.orgs?.[0]?.plan_code||"enterprise"})`),console.log("")}catch(S){console.error(` ${t.error} SSO token exchange failed: ${S instanceof Error?S.message:S}`),console.log("")}}function ka(s){let e=W(),t=P(),o=s||"default",n=o==="default"?Ot.join(t.config,"auth.json"):Ot.join(t.config,`auth-${o}.json`);_e.existsSync(n)&&_e.unlinkSync(n),console.log(` ${e.success} Logged out${o!=="default"?` (profile: ${o})`:""}.`),console.log("")}var _e,Ot,Cu,Oe,_u,te=G(()=>{"use strict";_e=y(require("node:fs"),1),Ot=y(require("node:path"),1),Cu=y(require("node:readline"),1);U();Q();Ce();$u();Oe=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com",_u="auth";l(pa,"authLogin");l(ma,"authLoginEmail");l(fa,"authLogout");l(ga,"authSetToken");l(Zn,"authStatus");l(ha,"authRefresh");l(ya,"fetchProfile");l(me,"loadAuth");l(ba,"isAuthenticated");l(Ee,"getAccessToken");l(Qo,"saveAuth");l(vy,"sleep");l(Sy,"askPassword");l(wa,"authLoginSSO");l(ka,"authLogoutProfile")});async function*Eu(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 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
46
|
`),i=e.start_line||1,c=e.end_line||r.length,u=e.full,d;if(u||r.length<=2e3)d=r;else{let f=r.slice(0,500),m=r.slice(-500);d=[...f,`
|
|
47
47
|
... (${r.length-1e3} lines truncated \u2014 use start_line/end_line or full:true) ...
|
|
48
48
|
`,...m]}!u&&(e.start_line||e.end_line)&&(d=r.slice(i-1,c));let p=d.map((f,m)=>{let g=(e.start_line||1)+m;return`${String(g).padStart(5)} ${f}`});return{output:`File: ${e.path} (${r.length} lines)
|
|
@@ -51,18 +51,18 @@ ${p.join(`
|
|
|
51
51
|
`).length;return{output:`Created ${e.path} (${o} lines)`,wroteFiles:!0,touchedFiles:[e.path]}}editFile(e){let t=this.resolve(e.path);if(!L.existsSync(t))return{output:`Error: File not found: ${e.path}. Use create_file to create it.`};let o=L.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);L.writeFileSync(t,c);let u=n.split(`
|
|
52
52
|
`).length,d=r.split(`
|
|
53
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 L.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,L.readFileSync(t,"utf8")),L.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 L.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,L.readFileSync(t,"utf8")),this._checkpoints.set(o,null),L.mkdirSync(le.dirname(o),{recursive:!0}),L.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(!L.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(`
|
|
54
|
-
`)}}listEntries(e,t,o){let n=[],r;try{r=L.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=L.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,
|
|
54
|
+
`)}}listEntries(e,t,o){let n=[],r;try{r=L.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=L.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});if(d.status===0&&d.stdout){let p=d.stdout.split(`
|
|
55
55
|
`).filter(Boolean);return p.length>100?{output:`Found ${p.length} matches (showing first 100):
|
|
56
56
|
${p.slice(0,100).join(`
|
|
57
57
|
`)}`}:{output:`Found ${p.length} match(es):
|
|
58
58
|
${p.join(`
|
|
59
|
-
`)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let d=["-rn","--color=never"];r&&d.push("-F"),i&&d.push("-i"),n&&d.push("--include",n),d.push("--",t,o);let p=(0,
|
|
59
|
+
`)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let d=["-rn","--color=never"];r&&d.push("-F"),i&&d.push("-i"),n&&d.push("--include",n),d.push("--",t,o);let p=(0,Ue.spawnSync)("grep",d,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1024*1024});if(p.stdout){let f=p.stdout.split(`
|
|
60
60
|
`).filter(Boolean);return{output:`Found ${f.length} match(es):
|
|
61
61
|
${f.slice(0,100).join(`
|
|
62
|
-
`)}`}}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,
|
|
62
|
+
`)}`}}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
63
|
`).filter(Boolean).map(i=>le.relative(this.workspace,i)).sort();return{output:r.length>0?`Found ${r.length} file(s):
|
|
64
64
|
${r.join(`
|
|
65
|
-
`)}`:"No files found."}}return{output:"No files found."}}catch(n){return{output:`Glob error: ${n instanceof Error?n.message:n}`}}}async runCommand(e){let t=e.command,o=e.cwd?this.resolve(e.cwd):this.workspace,n=(e.timeout||120)*1e3,r="bash",i=["-c",t];if(this._sandbox)try{let c=await this._sandbox.wrapCommand("bash",["-c",t]);r=c.command,i=c.args}catch{}return new Promise(c=>{let u=(0,
|
|
65
|
+
`)}`:"No files found."}}return{output:"No files found."}}catch(n){return{output:`Glob error: ${n instanceof Error?n.message:n}`}}}async runCommand(e){let t=e.command,o=e.cwd?this.resolve(e.cwd):this.workspace,n=(e.timeout||120)*1e3,r="bash",i=["-c",t];if(this._sandbox)try{let c=await this._sandbox.wrapCommand("bash",["-c",t]);r=c.command,i=c.args}catch{}return new Promise(c=>{let u=(0,Ue.spawn)(r,i,{cwd:o,env:{...process.env,TERM:"dumb"},stdio:["pipe","pipe","pipe"],timeout:n}),d="",p="";u.stdout.on("data",f=>{d+=f.toString(),d.length>102400&&u.kill()}),u.stderr.on("data",f=>{p+=f.toString()}),u.on("close",f=>{let m="";d&&(m+=d),p&&(m+=(d?`
|
|
66
66
|
|
|
67
67
|
STDERR:
|
|
68
68
|
`:"")+p),m||(m=`(no output, exit code ${f})`),d.length>102400&&(m=m.slice(0,102400)+`
|
|
@@ -73,23 +73,23 @@ ${m}`,c({output:m})}),u.on("error",f=>{c({output:`Command failed: ${f.message}`}
|
|
|
73
73
|
|
|
74
74
|
`)}}catch(n){return{output:`Web search failed: ${n instanceof Error?n.message:n}`}}}async readUrl(e){let t=e.url,o=e.max_length||5e4;try{let n=new URL(t);if(n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname.startsWith("192.168.")||n.hostname.startsWith("10."))return{output:"Error: Cannot fetch localhost or private network URLs for security reasons."}}catch{return{output:`Error: Invalid URL: ${t}`}}try{let n=await fetch(t,{headers:{"User-Agent":"MonkeysCode-CLI/0.1"},signal:this.signal});if(!n.ok)return{output:`Error: HTTP ${n.status} from ${t}`};let r=await n.text();return r.length>o&&(r=r.slice(0,o)+`
|
|
75
75
|
|
|
76
|
-
... (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,
|
|
76
|
+
... (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
77
|
${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,
|
|
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 L.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
79
|
`+u.join(`
|
|
80
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(!L.existsSync(t))return{output:`Error: File not found: ${e.path}`};let i=L.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 L.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(!L.existsSync(t))return{output:`Error: File not found: ${e.path}`};let n=L.readFileSync(t,"utf8");this._checkpoints.has(t)||this._checkpoints.set(t,n);try{let r=n.split(`
|
|
81
81
|
`),i=o.split(`
|
|
82
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 L.writeFileSync(t,c.join(`
|
|
83
|
-
`),"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,
|
|
83
|
+
`),"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
84
|
${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(L.existsSync(e)){try{let t=JSON.parse(L.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 L.existsSync(le.join(this.workspace,"pyproject.toml"))||L.existsSync(le.join(this.workspace,"setup.py"))||L.existsSync(le.join(this.workspace,"pytest.ini"))?"pytest":L.existsSync(le.join(this.workspace,"go.mod"))?"go":L.existsSync(le.join(this.workspace,"Cargo.toml"))?"cargo":L.existsSync(le.join(this.workspace,"Gemfile"))?"rspec":(0,
|
|
85
|
+
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=le.join(this.workspace,"package.json");if(L.existsSync(e)){try{let t=JSON.parse(L.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 L.existsSync(le.join(this.workspace,"pyproject.toml"))||L.existsSync(le.join(this.workspace,"setup.py"))||L.existsSync(le.join(this.workspace,"pytest.ini"))?"pytest":L.existsSync(le.join(this.workspace,"go.mod"))?"go":L.existsSync(le.join(this.workspace,"Cargo.toml"))?"cargo":L.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(()=>(Z(),ve))).loadSettings(),{getAccessToken:r}=await Promise.resolve().then(()=>(te(),ge)),{AgentLoop:i}=await Promise.resolve().then(()=>(Je(),Zo)),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(`
|
|
86
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");L.existsSync(n)||L.mkdirSync(n,{recursive:!0});let r=le.join(n,"MEMORY.md"),i=new Date().toISOString().split("T")[0],c=`
|
|
87
87
|
- [${o}] ${t} _(${i})_
|
|
88
88
|
`,u="";return L.existsSync(r)?u=L.readFileSync(r,"utf8"):u=`# Project Memory
|
|
89
89
|
|
|
90
90
|
Facts, conventions, and decisions learned during sessions.
|
|
91
|
-
`,L.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
|
|
92
|
-
`)}}});var
|
|
91
|
+
`,L.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 or,Sa=G(()=>{"use strict";or=["~/.ssh","~/.aws","~/.config/gcloud","~/.config/gh","~/.azure","~/.kube","~/.docker/config.json","~/.npmrc","~/.pypirc","~/.env","~/.netrc","~/.gnupg"]});var Ou,Iu,Us,Ws,ju=G(()=>{"use strict";Ou=require("node:child_process"),Iu=y(require("node:os"),1),Us=y(require("node:path"),1);Sa();Ws=class{static{l(this,"BubblewrapProvider")}name="bubblewrap";async isAvailable(){try{return(0,Ou.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=Iu.homedir(),r=[];r.push("--ro-bind","/","/");let i=Us.resolve(o.workspace);r.push("--bind",i,i),r.push("--tmpfs","/tmp"),r.push("--dev","/dev"),r.push("--proc","/proc");for(let c of or){let u=c.replace("~",n);r.push("--tmpfs",u)}return r.push("--tmpfs",Us.join(n,".env")),r.push("--tmpfs",Us.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 Nu,Hs,sr,es,Gs,Lu=G(()=>{"use strict";Nu=require("node:child_process"),Hs=y(require("node:os"),1),sr=y(require("node:path"),1),es=y(require("node:fs"),1);Sa();Gs=class{static{l(this,"SandboxExecProvider")}name="sandbox-exec";profilePath=null;async isAvailable(){try{return(0,Nu.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=sr.join(Hs.tmpdir(),`mc-sandbox-${process.pid}.sb`);return es.writeFileSync(r,n,"utf-8"),this.profilePath=r,{command:"sandbox-exec",args:["-f",r,e,...t]}}async setup(e){}async teardown(){this.profilePath&&es.existsSync(this.profilePath)&&(es.unlinkSync(this.profilePath),this.profilePath=null)}generateProfile(e){let t=Hs.homedir(),o=sr.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 "${Hs.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 or){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(`
|
|
92
|
+
`)}}});var xa,nr,rr,ts,qs,Bu=G(()=>{"use strict";xa=require("node:child_process"),nr=y(require("node:os"),1),rr=y(require("node:path"),1),ts=y(require("node:fs"),1),qs=class{static{l(this,"WindowsSandboxProvider")}name="windows-sandbox";wsbConfigPath=null;mode=null;async isAvailable(){if(nr.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=rr.resolve(e.workspace),o=this.generateWsbConfig(t,e);this.wsbConfigPath=rr.join(nr.tmpdir(),`mc-sandbox-${process.pid}.wsb`),ts.writeFileSync(this.wsbConfigPath,o,"utf-8")}}async teardown(){this.wsbConfigPath&&ts.existsSync(this.wsbConfigPath)&&(ts.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
93
|
<Configuration>
|
|
94
94
|
<VGpu>Disable</VGpu>
|
|
95
95
|
<Networking>${t.network==="none"?"Disable":"Default"}</Networking>
|
|
@@ -104,7 +104,7 @@ Facts, conventions, and decisions learned during sessions.
|
|
|
104
104
|
<Command>cmd.exe /k cd C:\\Workspace</Command>
|
|
105
105
|
</LogonCommand>
|
|
106
106
|
<MemoryInMB>2048</MemoryInMB>
|
|
107
|
-
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var
|
|
107
|
+
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var so,_o,no,Wu,Uu,Vs,Eo,Hu=G(()=>{"use strict";so=require("node:child_process"),_o=y(require("node:path"),1),no=y(require("node:fs"),1),Wu=y(require("node:crypto"),1),Uu="monkeyscode-sandbox",Vs="/workspace",Eo=class{static{l(this,"DockerSandboxProvider")}name="docker";containerId=null;imageName=Uu;async isAvailable(){try{return(0,so.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",Vs),n.push(this.containerId),n.push(e,...t);else{n.splice(0),n.push("run","--rm"),n.push("-w",Vs);let r=_o.resolve(o.workspace);n.push("-v",`${r}:${Vs}`),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||Uu;let t=_o.resolve(e.workspace),o=e.dockerfilePath||_o.join(t,".monkeyscode","Dockerfile.sandbox");if(no.existsSync(o)){let c=(0,so.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-${Wu.randomUUID().substring(0,8)}`,"-w",Vs,"-v",`${t}:${Vs}`];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,so.spawnSync)("docker",r,{stdio:"pipe"});i.status===0&&(this.containerId=i.stdout.toString().trim().substring(0,12))}async teardown(){if(this.containerId){try{(0,so.execSync)(`docker rm -f ${this.containerId}`,{stdio:"pipe",timeout:1e4})}catch{}this.containerId=null}}async ensureBaseImage(){try{(0,so.execSync)(`docker image inspect ${this.imageName}`,{stdio:"pipe"});return}catch{}let e=`
|
|
108
108
|
FROM ubuntu:22.04
|
|
109
109
|
RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
110
110
|
git curl wget ca-certificates \\
|
|
@@ -115,13 +115,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
|
115
115
|
RUN useradd -m -s /bin/bash sandbox
|
|
116
116
|
USER sandbox
|
|
117
117
|
WORKDIR /workspace
|
|
118
|
-
`.trim(),t=
|
|
118
|
+
`.trim(),t=_o.join(require("node:os").tmpdir(),"mc-sandbox-build");no.mkdirSync(t,{recursive:!0}),no.writeFileSync(_o.join(t,"Dockerfile"),e);let o=(0,so.spawnSync)("docker",["build","-t",this.imageName,t],{stdio:"pipe",timeout:3e5});if(no.rmSync(t,{recursive:!0,force:!0}),o.status!==0)throw new Error(`Failed to build sandbox base image: ${o.stderr?.toString()}`)}}});function Gu(s){switch(s){case"linux":return[new Ws,new Eo];case"macos":return[new Gs,new Eo];case"windows":return[new qs,new Eo]}}function ir(s,e={}){return{enabled:!1,provider:"auto",network:"none",workspace:s,...e}}var os,$a=G(()=>{"use strict";Q();ju();Lu();Bu();Hu();l(Gu,"getProviderCandidates");os=class{static{l(this,"SandboxManager")}config;provider=null;platform;initialized=!1;constructor(e){this.config=e,this.platform=De()}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=Gu(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=Gu(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 Ws;case"sandbox-exec":return new Gs;case"windows-sandbox":case"appcontainer":return new qs;case"docker":return new Eo;default:return null}}};l(ir,"createDefaultSandboxConfig")});function qu(s){switch(s){case 0:return"allow";case 1:return"deny";case 2:return"modify";default:return"allow"}}var Vu,zu=G(()=>{"use strict";l(qu,"exitCodeToAction");Vu={enabled:!0,timeoutMs:1e4}});function Fo(s){let e=P(),t=bt.join(s,".monkeyscode","hooks"),o=bt.join(e.config,"hooks"),n=Ju(t,"project"),r=Ju(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 Ju(s,e){if(!ss.existsSync(s))return[];let t=[];try{let o=ss.readdirSync(s,{withFileTypes:!0});for(let n of o){if(!n.isFile())continue;let r=bt.extname(n.name).toLowerCase(),i=Ey[r];if(!i)continue;let c=bt.basename(n.name,r).toLowerCase(),u=_y[c];u&&t.push({event:u,scriptPath:bt.join(s,n.name),source:e,scriptType:i})}}catch{}return t}function Ku(s){let e=P(),t=bt.join(s,".monkeyscode","hooks"),o=bt.join(e.config,"hooks");return[{path:t,source:"project",exists:ss.existsSync(t)},{path:o,source:"global",exists:ss.existsSync(o)}]}var ss,bt,_y,Ey,ar=G(()=>{"use strict";ss=y(require("node:fs"),1),bt=y(require("node:path"),1);Q();_y={"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"},Ey={".sh":"sh",".bash":"sh",".ps1":"ps1",".cmd":"cmd",".bat":"cmd",".js":"js",".mjs":"js",".py":"py"};l(Fo,"loadHooks");l(Ju,"scanHookDirectory");l(Ku,"getHookDirectories")});var Yu,To,Ca=G(()=>{"use strict";Yu=require("node:child_process");Q();zu();ar();To=class{static{l(this,"HookRunner")}hooks;config;platform=De();constructor(e,t={}){this.config={...Vu,...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,Yu.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":qu(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 Qu(s,e=60){if(!It.ansi){console.log(`
|
|
119
119
|
${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
|
|
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 Zu(s,e){let t=" "+s.map(n=>{let r=n.header;return Xu(r,n.width,n.align||"left")}).join(" ");console.log(It.ansi?be.dim(t):t);let o=" "+s.map(n=>"\u2500".repeat(n.width)).join("\u2500\u2500");console.log(It.ansi?be.dim(o):o);for(let n of e){let r=" "+n.cells.map((i,c)=>{let u=s[c];return Xu(i,u.width,u.align||"left")}).join(" ");n.dim&&It.ansi?r=be.dim(r):n.highlight&&It.ansi&&(r=be.accent(r)),console.log(r)}}function Xu(s,e,t){let o=Ty(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(It.ansi?` ${be.dim(s)}`:` ${s}`)}function ed(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?It.ansi?be.success("Free"):"Free":`$${s.toFixed(s<1?4:2)}`}function Ty(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}function zs(){console.log("")}var Fy,be,It,mx,fx,td=G(()=>{"use strict";U();Ce();Fy=y(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},It=O(),mx=W(It),fx=Me(It);l(Qu,"sectionHeader");l(Zu,"printTable");l(Xu,"padCell");l(_a,"hint");l(ed,"formatTokens");l(Ea,"formatCost");l(Ty,"stripAnsi");l(zs,"blank")});function wt(s){if(s==="auto")return"auto";let e=s.toLowerCase(),t=jt.find(r=>r.id===e);if(t)return t.id;let o=jt.find(r=>r.aliases.some(i=>i.toLowerCase()===e));if(o)return o.id;let n=jt.find(r=>r.displayName.toLowerCase().includes(e));return n?n.id:s}function cr(s){let e=wt(s);return jt.find(t=>t.id===e)??null}function Ry(s,e){let t=wt(s),o=jt.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 Js(s,e,t,o=0){let n=jt.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=O().ansi,t=O().emoji;Qu("Available Models"),zs();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=jt.map(r=>{let i=Ry(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,ed(r.contextWindow),p,f,g],dim:c}});if(Zu(o,n),zs(),e){console.log(` ${be.dim("Aliases:")}`);for(let r of jt)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 jt)r.aliases.length>0&&console.log(` ${r.displayName}: ${r.aliases.join(", ")}`)}zs(),_a("Use --model <name|alias> to select a model"),_a("Use --model auto for smart routing based on task complexity"),zs()}var jt,lr=G(()=>{"use strict";U();Ce();td();jt=[{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(cr,"getModelInfo");l(Ry,"checkModelAccess");l(Js,"estimateCost");l(Fa,"printModelList")});function od(s,e,t){let o=cr(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,sd=G(()=>{"use strict";lr();Ta={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"};l(od,"resolveModelRoute")});var nd=G(()=>{"use strict"});var Pa={};Re(Pa,{buildSkillsContext:()=>Aa,listAllSkills:()=>Iy,loadSkills:()=>rd});function Py(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(`
|
|
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 My(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 Oy(s,e,t){let o=ro.join(s,"skill.md");if(!Nt.existsSync(o))return null;try{let n=Nt.readFileSync(o,"utf8"),{meta:r,body:i}=Py(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:My(r.trigger),enabled:r.enabled!==!1,priority:r.priority??50,filePath:o}:null}catch{return null}}function ur(s,e){if(!Nt.existsSync(s))return[];try{return Nt.readdirSync(s).filter(t=>{let o=ro.join(s,t);return Nt.statSync(o).isDirectory()}).map(t=>Oy(ro.join(s,t),t,e)).filter(t=>t!==null)}catch{return[]}}function rd(s){let e=ro.join(s,".monkeyscode","skills"),t=ro.join(Ra.homedir(),".monkeyscode","skills"),o=ur(t,"global"),n=ur(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=rd(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
122
|
${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
123
123
|
|
|
124
|
-
`):null}function
|
|
124
|
+
`):null}function Iy(s){let e=ro.join(s,".monkeyscode","skills"),t=ro.join(Ra.homedir(),".monkeyscode","skills"),o=ur(t,"global"),n=ur(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 Nt,ro,Ra,dr=G(()=>{"use strict";Nt=y(require("node:fs"),1),ro=y(require("node:path"),1),Ra=y(require("node:os"),1);nd();l(Py,"parseFrontmatter");l(My,"parseTrigger");l(Oy,"loadSkillFromDir");l(ur,"scanSkillsDir");l(rd,"loadSkills");l(Aa,"buildSkillsContext");l(Iy,"listAllSkills")});function id(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
125
|
## 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
126
|
## 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
127
|
## 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 +130,44 @@ ${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
|
130
130
|
## Mode: Accept Edits`),o.push("You may make file changes without asking. Be efficient and direct.");break;case"auto":default:o.push(`
|
|
131
131
|
## 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
132
|
## 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=
|
|
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=Lt.basename(s.workspace);n.push(`- Project: ${r}`);let i=jy(s.workspace);i&&n.push(`- Stack: ${i}`),t.push({role:"system",content:n.join(`
|
|
134
|
+
`),timestamp:e});let c=Ly(s.workspace);c&&t.push({role:"system",content:`## Workspace Rules
|
|
135
135
|
|
|
136
|
-
${c}`,timestamp:e});let u=
|
|
136
|
+
${c}`,timestamp:e});let u=Aa(s.workspace);u&&t.push({role:"system",content:`## Active Skills
|
|
137
137
|
|
|
138
|
-
${u}`,timestamp:e});let d=
|
|
139
|
-
`),timestamp:e})}return t}function
|
|
138
|
+
${u}`,timestamp:e});let d=Ny(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(`
|
|
139
|
+
`),timestamp:e})}return t}function jy(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(Lt.join(s,o))&&t.push(n);if(it.existsSync(Lt.join(s,"package.json")))try{let o=JSON.parse(it.readFileSync(Lt.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 Ny(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 Ly(s){let e=[];for(let o of["AGENTS.md","CLAUDE.md","GEMINI.md",".monkeyscode/AGENTS.md"]){let n=Lt.join(s,o);if(it.existsSync(n))try{let r=it.readFileSync(n,"utf8");r.trim()&&e.push(`### ${o}
|
|
140
140
|
|
|
141
|
-
${r}`)}catch{}}let t=
|
|
141
|
+
${r}`)}catch{}}let t=Lt.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(Lt.join(t,n),"utf8");r.trim()&&e.push(`### ${n}
|
|
142
142
|
|
|
143
143
|
${r}`)}}catch{}return e.length>0?e.join(`
|
|
144
144
|
|
|
145
145
|
---
|
|
146
146
|
|
|
147
|
-
`):null}var
|
|
148
|
-
... [output truncated]`,d++);if(
|
|
149
|
-
`)[0].slice(0,100);x.content=
|
|
150
|
-
...[summarized]`),x.role==="assistant"&&x.tool_calls?.length){let
|
|
151
|
-
...[truncated]`),x.role==="tool"&&x.content&&x.content.length>500){let
|
|
152
|
-
`)[0].slice(0,150);x.content=
|
|
153
|
-
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-no(u)}}function lr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var $y,Oa=H(()=>{"use strict";l(Aa,"estimateTokens");l(no,"estimateContextTokens");l(ur,"resolveContextWindow");$y=new Map;l(nd,"shouldCompact");l(Pa,"compactMessages");l(lr,"totalChars")});var Xo={};Te(Xo,{AgentLoop:()=>Se});var rd,_y,Se,ze=H(()=>{"use strict";rd=require("node:events");Cu();Eu();Tu();va();Sa();Zu();Q();sd();Oa();_y=1/0,Se=class extends rd.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 Qn({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new es(sr(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new _o(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=ur(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||_y;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=od({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=no(this.messages);if(nd(i,this.contextWindow)){let u=Pa(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=no(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(v=>v.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=Pa(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=no(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=_u(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(C=>({role:C.role,content:C.content,...C.tool_calls?{tool_calls:C.tool_calls.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))}:{},...C.tool_call_id?{tool_call_id:C.tool_call_id}:{},...C.name?{name:C.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=z(),i=Qu(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(C){if(C instanceof Error&&C.name==="AbortError")return null;throw C}if(!c.ok){let C=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}: ${C}`)}let u="",d=new Xn,p="",f=!1,m="",g="<think>",h="</think>",b=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),k=l(C=>{f?(m+=C,h.startsWith(m)?m===h&&(f=!1,m=""):(m="",C==="<"&&(m="<"))):C==="<"&&!m?m="<":m?(m+=C,g.startsWith(m)?m===g&&(f=!0,m=""):h.startsWith(m)?m===h&&(m=""):(p+=m,m="")):p+=C},"feedChar");for await(let C of xu(c)){if(!C.choices||C.choices.length===0){C.usage&&this.updateState({tokensIn:this.state.tokensIn+(C.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(C.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(C.usage.prompt_tokens_details?.cached_tokens||0)});continue}let E=C.choices[0];if(E.delta?.content){u+=E.delta.content;for(let I of E.delta.content)k(I);b()}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),b();let v=d.flush(),_={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return v.length>0&&(_.tool_calls=v.map(C=>{let E={};try{E=JSON.parse(C.arguments)}catch{E={_raw:C.arguments}}return{id:C.id,name:C.name,arguments: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 Nt=ce((uC,wd)=>{"use strict";var yd=["nodebuffer","arraybuffer","fragments"],bd=typeof Blob<"u";bd&&yd.push("blob");wd.exports={BINARY_TYPES:yd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var zs=ce((pC,kr)=>{"use strict";var{EMPTY_BUFFER:qy}=Nt(),La=Buffer[Symbol.species];function Vy(s,e){if(s.length===0)return qy;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 La(t.buffer,t.byteOffset,o):t}l(Vy,"concat");function kd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(kd,"_mask");function Dd(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(Dd,"_unmask");function zy(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(zy,"toArrayBuffer");function Ba(s){if(Ba.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new La(s):ArrayBuffer.isView(s)?e=new La(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ba.readOnly=!1),e}l(Ba,"toBuffer");kr.exports={concat:Vy,mask:kd,toArrayBuffer:zy,toBuffer:Ba,unmask:Dd};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");kr.exports.mask=function(e,t,o,n,r){r<48?kd(e,t,o,n,r):s.mask(e,t,o,n,r)},kr.exports.unmask=function(e,t){e.length<32?Dd(e,t):s.unmask(e,t)}}catch{}});var xd=ce((fC,Sd)=>{"use strict";var vd=Symbol("kDone"),Ua=Symbol("kRun"),Wa=class{static{l(this,"Limiter")}constructor(e){this[vd]=()=>{this.pending--,this[Ua]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ua]()}[Ua](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[vd])}}};Sd.exports=Wa});var rs=ce((hC,Ed)=>{"use strict";var Js=require("zlib"),Cd=zs(),Jy=xd(),{kStatusCode:$d}=Nt(),Ky=Buffer[Symbol.species],Yy=Buffer.from([0,0,255,255]),vr=Symbol("permessage-deflate"),Lt=Symbol("total-length"),ss=Symbol("callback"),io=Symbol("buffers"),ns=Symbol("error"),Dr,Ha=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,!Dr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Dr=new Jy(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[ss];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){Dr.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){Dr.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"?Js.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=Js.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[vr]=this,this._inflate[Lt]=0,this._inflate[io]=[],this._inflate.on("error",Qy),this._inflate.on("data",_d)}this._inflate[ss]=o,this._inflate.write(e),t&&this._inflate.write(Yy),this._inflate.flush(()=>{let r=this._inflate[ns];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Cd.concat(this._inflate[io],this._inflate[Lt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Lt]=0,this._inflate[io]=[],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"?Js.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=Js.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Lt]=0,this._deflate[io]=[],this._deflate.on("data",Xy)}this._deflate[ss]=o,this._deflate.write(e),this._deflate.flush(Js.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Cd.concat(this._deflate[io],this._deflate[Lt]);t&&(r=new Ky(r.buffer,r.byteOffset,r.length-4)),this._deflate[ss]=null,this._deflate[Lt]=0,this._deflate[io]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Ed.exports=Ha;function Xy(s){this[io].push(s),this[Lt]+=s.length}l(Xy,"deflateOnData");function _d(s){if(this[Lt]+=s.length,this[vr]._maxPayload<1||this[Lt]<=this[vr]._maxPayload){this[io].push(s);return}this[ns]=new RangeError("Max payload size exceeded"),this[ns].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ns][$d]=1009,this.removeListener("data",_d),this.reset()}l(_d,"inflateOnData");function Qy(s){if(this[vr]._inflate=null,this[ns]){this[ss](this[ns]);return}s[$d]=1007,this[ss](s)}l(Qy,"inflateOnError")});var is=ce((bC,Sr)=>{"use strict";var{isUtf8:Fd}=require("buffer"),{hasBlob:Zy}=Nt(),e0=[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 t0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(t0,"isValidStatusCode");function Ga(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(Ga,"_isValidUTF8");function o0(s){return Zy&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(o0,"isBlob");Sr.exports={isBlob:o0,isValidStatusCode:t0,isValidUTF8:Ga,tokenChars:e0};if(Fd)Sr.exports.isValidUTF8=function(s){return s.length<24?Ga(s):Fd(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");Sr.exports.isValidUTF8=function(e){return e.length<32?Ga(e):s(e)}}catch{}});var Ka=ce((kC,Id)=>{"use strict";var{Writable:s0}=require("stream"),Td=rs(),{BINARY_TYPES:n0,EMPTY_BUFFER:Rd,kStatusCode:r0,kWebSocket:i0}=Nt(),{concat:qa,toArrayBuffer:a0,unmask:c0}=zs(),{isValidStatusCode:l0,isValidUTF8:Ad}=is(),xr=Buffer[Symbol.species],Je=0,Pd=1,Od=2,Md=3,Va=4,za=5,Cr=6,Ja=class extends s0{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||n0[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[i0]=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=Je}_write(e,t,o){if(this._opcode===8&&this._state==Je)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 xr(o.buffer,o.byteOffset+e,o.length-e),new xr(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 xr(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 Je:this.getInfo(e);break;case Pd:this.getPayloadLength16(e);break;case Od:this.getPayloadLength64(e);break;case Md:this.getMask();break;case Va:this.getData(e);break;case za:case Cr: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[Td.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=Pd:this._payloadLength===127?this._state=Od: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=Md:this._state=Va}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Va}getData(e){let t=Rd;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]&&c0(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=za,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Td.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===Je&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Je;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=qa(o,t):this._binaryType==="arraybuffer"?n=a0(qa(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Je):(this._state=Cr,setImmediate(()=>{this.emit("message",n,!0),this._state=Je,this.startLoop(e)}))}else{let n=qa(o,t);if(!this._skipUTF8Validation&&!Ad(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===za||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Je):(this._state=Cr,setImmediate(()=>{this.emit("message",n,!1),this._state=Je,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Rd),this.end();else{let o=e.readUInt16BE(0);if(!l0(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new xr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ad(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=Je;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Je):(this._state=Cr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Je,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[r0]=n,i}};Id.exports=Ja});var Qa=ce((SC,Ld)=>{"use strict";var{Duplex:vC}=require("stream"),{randomFillSync:u0}=require("crypto"),{types:{isUint8Array:d0}}=require("util"),jd=rs(),{EMPTY_BUFFER:p0,kWebSocket:m0,NOOP:f0}=Nt(),{isBlob:as,isValidStatusCode:g0}=is(),{mask:Nd,toBuffer:Fo}=zs(),Ke=Symbol("kByteLength"),h0=Buffer.alloc(4),$r=8*1024,To,cs=$r,nt=0,y0=1,b0=2,Ya=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=nt,this.onerror=f0,this[m0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||h0,t.generateMask?t.generateMask(o):(cs===$r&&(To===void 0&&(To=Buffer.alloc($r)),u0(To,0,$r),cs=0),o[0]=To[cs++],o[1]=To[cs++],o[2]=To[cs++],o[3]=To[cs++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Ke]!==void 0?c=t[Ke]:(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?(Nd(e,o,d,r,c),[d]):(Nd(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=p0;else{if(typeof e!="number"||!g0(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(d0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Ke]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==nt?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):as(e)?(n=e.size,r=!1):(e=Fo(e),n=e.length,r=Fo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ke]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?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):as(e)?(n=e.size,r=!1):(e=Fo(e),n=e.length,r=Fo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ke]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[jd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):as(e)?(c=e.size,u=!1):(e=Fo(e),c=e.length,u=Fo.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={[Ke]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==nt?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Ke],this._state=b0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Xa,this,c,n);return}this._bufferedBytes-=o[Ke];let i=Fo(r);t?this.dispatch(i,t,o,n):(this._state=nt,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(w0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[jd.extensionName];this._bufferedBytes+=o[Ke],this._state=y0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Xa(this,u,n);return}this._bufferedBytes-=o[Ke],this._state=nt,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===nt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ke],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ke],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)}};Ld.exports=Ya;function Xa(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(Xa,"callCallbacks");function w0(s,e,t){Xa(s,e,t),s.onerror(e)}l(w0,"onError")});var Jd=ce((CC,zd)=>{"use strict";var{kForOnEventAttribute:Ks,kListener:Za}=Nt(),Bd=Symbol("kCode"),Ud=Symbol("kData"),Wd=Symbol("kError"),Hd=Symbol("kMessage"),Gd=Symbol("kReason"),ls=Symbol("kTarget"),qd=Symbol("kType"),Vd=Symbol("kWasClean"),Bt=class{static{l(this,"Event")}constructor(e){this[ls]=null,this[qd]=e}get target(){return this[ls]}get type(){return this[qd]}};Object.defineProperty(Bt.prototype,"target",{enumerable:!0});Object.defineProperty(Bt.prototype,"type",{enumerable:!0});var Ro=class extends Bt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[Bd]=t.code===void 0?0:t.code,this[Gd]=t.reason===void 0?"":t.reason,this[Vd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Bd]}get reason(){return this[Gd]}get wasClean(){return this[Vd]}};Object.defineProperty(Ro.prototype,"code",{enumerable:!0});Object.defineProperty(Ro.prototype,"reason",{enumerable:!0});Object.defineProperty(Ro.prototype,"wasClean",{enumerable:!0});var us=class extends Bt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[Wd]=t.error===void 0?null:t.error,this[Hd]=t.message===void 0?"":t.message}get error(){return this[Wd]}get message(){return this[Hd]}};Object.defineProperty(us.prototype,"error",{enumerable:!0});Object.defineProperty(us.prototype,"message",{enumerable:!0});var Ys=class extends Bt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[Ud]=t.data===void 0?null:t.data}get data(){return this[Ud]}};Object.defineProperty(Ys.prototype,"data",{enumerable:!0});var k0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[Ks]&&n[Za]===e&&!n[Ks])return;let o;if(s==="message")o=l(function(r,i){let c=new Ys("message",{data:i?r:r.toString()});c[ls]=this,_r(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new Ro("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ls]=this,_r(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new us("error",{error:r,message:r.message});i[ls]=this,_r(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Bt("open");r[ls]=this,_r(e,this,r)},"onOpen");else return;o[Ks]=!!t[Ks],o[Za]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[Za]===e&&!t[Ks]){this.removeListener(s,t);break}}};zd.exports={CloseEvent:Ro,ErrorEvent:us,Event:Bt,EventTarget:k0,MessageEvent:Ys};function _r(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(_r,"callListener")});var Er=ce((_C,Kd)=>{"use strict";var{tokenChars:Xs}=is();function ht(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(ht,"push");function D0(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&&Xs[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?(ht(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&&Xs[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),ht(t,s.slice(u,p),!0),d===44&&(ht(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(Xs[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(Xs[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&&Xs[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),ht(t,c,g),d===44&&(ht(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?ht(e,m,t):(c===void 0?ht(t,m,!0):o?ht(t,c,m.replace(/\\/g,"")):ht(t,c,m),ht(e,i,t)),e}l(D0,"parse");function v0(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(v0,"format");Kd.exports={format:v0,parse:D0}});var Ar=ce((RC,ap)=>{"use strict";var S0=require("events"),x0=require("https"),C0=require("http"),Qd=require("net"),$0=require("tls"),{randomBytes:_0,createHash:E0}=require("crypto"),{Duplex:FC,Readable:TC}=require("stream"),{URL:ec}=require("url"),ao=rs(),F0=Ka(),T0=Qa(),{isBlob:R0}=is(),{BINARY_TYPES:Yd,CLOSE_TIMEOUT:A0,EMPTY_BUFFER:Fr,GUID:P0,kForOnEventAttribute:tc,kListener:O0,kStatusCode:M0,kWebSocket:we,NOOP:Zd}=Nt(),{EventTarget:{addEventListener:I0,removeEventListener:j0}}=Jd(),{format:N0,parse:L0}=Er(),{toBuffer:B0}=zs(),ep=Symbol("kAborted"),oc=[8,13],Ut=["CONNECTING","OPEN","CLOSING","CLOSED"],U0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends S0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=Yd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fr,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]),tp(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yd.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 F0({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 T0(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",G0),n.on("drain",q0),n.on("error",V0),n.on("message",z0),n.on("ping",J0),n.on("pong",K0),r.onerror=Y0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",np),e.on("data",Rr),e.on("end",rp),e.on("error",ip),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[ao.extensionName]&&this._extensions[ao.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){Le(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())}),sp(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){sc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Fr,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){sc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Fr,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){sc(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ao.extensionName]||(n.compress=!1),this._sender.send(e||Fr,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Le(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:Ut.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:Ut.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:Ut.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:Ut.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:Ut.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:Ut.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:Ut.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:Ut.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[tc])return e[O0];return null},set(e){for(let t of this.listeners(s))if(t[tc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[tc]:!0})}})});ie.prototype.addEventListener=I0;ie.prototype.removeEventListener=j0;ap.exports=ie;function tp(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:A0,protocolVersion:oc[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,!oc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${oc.join(", ")})`);let r;if(e instanceof ec)r=e;else try{r=new ec(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;Tr(s,b);return}let d=i?443:80,p=_0(16).toString("base64"),f=i?x0.request:C0.request,m=new Set,g;if(n.createConnection=n.createConnection||(i?H0:W0),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 ao({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=N0({[ao.extensionName]:g.offer()})),t.length){for(let b of t){if(typeof b!="string"||!U0.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,v]of Object.entries(b))o.headers[k.toLowerCase()]=v}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",()=>{Le(s,h,"Opening handshake has timed out")}),h.on("error",b=>{h===null||h[ep]||(h=s._req=null,Tr(s,b))}),h.on("response",b=>{let k=b.headers.location,v=b.statusCode;if(k&&n.followRedirects&&v>=300&&v<400){if(++s._redirects>n.maxRedirects){Le(s,h,"Maximum redirects exceeded");return}h.abort();let x;try{x=new ec(k,e)}catch{let C=new SyntaxError(`Invalid URL: ${k}`);Tr(s,C);return}tp(s,x,t,o)}else s.emit("unexpected-response",h,b)||Le(s,h,`Unexpected server response: ${b.statusCode}`)}),h.on("upgrade",(b,k,v)=>{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"){Le(s,k,"Invalid Upgrade header");return}let _=E0("sha1").update(p+P0).digest("base64");if(b.headers["sec-websocket-accept"]!==_){Le(s,k,"Invalid Sec-WebSocket-Accept header");return}let C=b.headers["sec-websocket-protocol"],E;if(C!==void 0?m.size?m.has(C)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){Le(s,k,E);return}C&&(s._protocol=C);let I=b.headers["sec-websocket-extensions"];if(I!==void 0){if(!g){Le(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=L0(I)}catch{Le(s,k,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(ae);if(K.length!==1||K[0]!==ao.extensionName){Le(s,k,"Server indicated an extension that was not requested");return}try{g.accept(ae[ao.extensionName])}catch{Le(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ao.extensionName]=g}s.setSocket(k,v,{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(tp,"initAsClient");function Tr(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Tr,"emitErrorAndClose");function W0(s){return s.path=s.socketPath,Qd.connect(s)}l(W0,"netConnect");function H0(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Qd.isIP(s.host)?"":s.host),$0.connect(s)}l(H0,"tlsConnect");function Le(s,e,t){s._readyState=ie.CLOSING;let o=new Error(t);Error.captureStackTrace(o,Le),e.setHeader?(e[ep]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Tr,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(Le,"abortHandshake");function sc(s,e,t){if(e){let o=R0(e)?e.size:B0(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Ut[s.readyState]})`);process.nextTick(t,o)}}l(sc,"sendAfterClose");function G0(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Rr),process.nextTick(op,t._socket),s===1005?t.close():t.close(s,e))}l(G0,"receiverOnConclude");function q0(){let s=this[we];s.isPaused||s._socket.resume()}l(q0,"receiverOnDrain");function V0(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Rr),process.nextTick(op,e._socket),e.close(s[M0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(V0,"receiverOnError");function Xd(){this[we].emitClose()}l(Xd,"receiverOnFinish");function z0(s,e){this[we].emit("message",s,e)}l(z0,"receiverOnMessage");function J0(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,Zd),e.emit("ping",s)}l(J0,"receiverOnPing");function K0(s){this[we].emit("pong",s)}l(K0,"receiverOnPong");function op(s){s.resume()}l(op,"resume");function Y0(s){let e=this[we];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,sp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(Y0,"senderOnError");function sp(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(sp,"setCloseTimer");function np(){let s=this[we];if(this.removeListener("close",np),this.removeListener("data",Rr),this.removeListener("end",rp),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",Xd),s._receiver.on("finish",Xd))}l(np,"socketOnClose");function Rr(s){this[we]._receiver.write(s)||this.pause()}l(Rr,"socketOnData");function rp(){let s=this[we];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}l(rp,"socketOnEnd");function ip(){let s=this[we];this.removeListener("error",ip),this.on("error",Zd),s&&(s._readyState=ie.CLOSING,this.destroy())}l(ip,"socketOnError")});var dp=ce((OC,up)=>{"use strict";var PC=Ar(),{Duplex:X0}=require("stream");function cp(s){s.emit("close")}l(cp,"emitClose");function Q0(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(Q0,"duplexOnEnd");function lp(s){this.removeListener("error",lp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(lp,"duplexOnError");function Z0(s,e){let t=!0,o=new X0({...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(cp,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(cp,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",Q0),o.on("error",lp),o}l(Z0,"createWebSocketStream");up.exports=Z0});var nc=ce((IC,pp)=>{"use strict";var{tokenChars:eb}=is();function tb(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&&eb[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(tb,"parse");pp.exports={parse:tb}});var wp=ce((LC,bp)=>{"use strict";var ob=require("events"),Pr=require("http"),{Duplex:NC}=require("stream"),{createHash:sb}=require("crypto"),mp=Er(),Ao=rs(),nb=nc(),rb=Ar(),{CLOSE_TIMEOUT:ib,GUID:ab,kWebSocket:cb}=Nt(),lb=/^[+/0-9A-Za-z]{22}==$/,fp=0,gp=1,yp=2,rc=class extends ob{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:ib,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:rb,...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=Pr.createServer((o,n)=>{let r=Pr.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=ub(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=fp}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===yp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Qs,this);return}if(e&&this.once("close",e),this._state!==gp)if(this._state=gp,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(Qs,this):process.nextTick(Qs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Qs(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",hp);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Po(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Po(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!lb.test(r)){Po(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Po(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Zs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=nb.parse(u)}catch{Po(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 Ao({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=mp.parse(p);g[Ao.extensionName]&&(m.accept(g[Ao.extensionName]),f[Ao.extensionName]=m)}catch{Po(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 Zs(t,h||401,b,k);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return Zs(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[cb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fp)return Zs(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${sb("sha1").update(t+ab).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[Ao.extensionName]){let f=e[Ao.extensionName].params,m=mp.format({[Ao.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
147
|
+
`):null}var it,Lt,Ma,ad=G(()=>{"use strict";it=y(require("node:fs"),1),Lt=y(require("node:path"),1),Ma=require("node:child_process");dr();l(id,"buildSystemMessages");l(jy,"detectProjectType");l(Ny,"getGitInfo");l(Ly,"loadWorkspaceRules")});function Oa(s){return Math.ceil(s.length/4)}function io(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 mr(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 cd(s){Ia.clear();for(let e of s)e.id&&e.contextWindow>0&&Ia.set(e.id,e.contextWindow)}function ld(s,e,t=.85){return s>=e*t}function ja(s,e,t){let r=Math.max(4e3,(e||128e3)-(t||15e3)),i=Math.floor(r*.9)*4;if(pr(s)<=i)return{messages:s,elided:0,savedTokens:0};let u=s.map(k=>({...k})),d=0,p=io(s);for(let k of u)k.role==="tool"&&k.content&&k.content.length>8e3&&(k.content=k.content.slice(0,8e3)+`
|
|
148
|
+
... [output truncated]`,d++);if(pr(u)<=i)return{messages:u,elided:d,savedTokens:p-io(u)};let f=u.filter(k=>k.role!=="system").length,m=Math.max(10,Math.floor(f*.2)),g=Math.floor((f-m)/20)*20;if(g>0){let k=0;for(let S=0;S<u.length;S++){if(u[S].role==="system")continue;if(k++,k>g)break;let x=u[S];if(k<=Math.floor(g*.75)){if(x.role==="tool"&&x.content&&x.content.length>150){let E=x.content.includes("Error")||x.content.includes("error"),$=x.content.split(`
|
|
149
|
+
`)[0].slice(0,100);x.content=E?`[error] ${$}`:`[ok] ${$}`,d++}if(x.role==="assistant"&&x.content&&x.content.length>300&&!x.tool_calls?.length&&(x.content=x.content.slice(0,200)+`
|
|
150
|
+
...[summarized]`),x.role==="assistant"&&x.tool_calls?.length){let E=x.tool_calls.map($=>`[called ${$.name||"unknown"}]`);x.content||(x.content=E.join(", "))}}else if(x.role==="assistant"&&x.content&&x.content.length>500&&!x.tool_calls?.length&&(x.content=x.content.slice(0,400)+`
|
|
151
|
+
...[truncated]`),x.role==="tool"&&x.content&&x.content.length>500){let E=x.content.includes("Error")||x.content.includes("error"),$=x.content.split(`
|
|
152
|
+
`)[0].slice(0,150);x.content=E?`[error] ${$}`:`[ok] ${$}`,d++}}}if(pr(u)<=i)return{messages:u,elided:d,savedTokens:p-io(u)};let h=Math.floor(i*.85),b=pr(u);for(;b>h&&u.length>6;){let k=u.findIndex(E=>E.role==="user");if(k<0)break;let S=k;for(let E=k+1;E<u.length;E++){let $=u[E];if($.role==="user"&&!("tool_call_id"in $))break;S=E}let x=u.splice(k,S-k+1);for(let E of x)b-=E.content?.length||0,E.tool_calls&&(b-=JSON.stringify(E.tool_calls).length);d+=x.length}if(u.length<s.length){let k=["[CONVERSATION CONTEXT \u2014 older messages were summarized to fit within the token limit]","Continue working with the remaining context."],S=u[0]?.role==="system"?1:0;u.splice(S,0,{role:"user",content:k.join(`
|
|
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
|
|
154
154
|
`).join(`\r
|
|
155
|
-
`)),r.removeListener("error",
|
|
155
|
+
`)),r.removeListener("error",Dp),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(tn,this)})),c(p,n)}};Sp.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 tn(s){s._state=vp,s.emit("close")}l(tn,"emitClose");function Dp(){this.destroy()}l(Dp,"socketOnError");function on(s,e,t,o){t=t||jr.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} ${jr.STATUS_CODES[e]}\r
|
|
156
156
|
`+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
|
|
157
157
|
`)+`\r
|
|
158
158
|
\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
|
|
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
|
|
159
|
+
`+t)}l(on,"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 on(t,o,n,r)}l(Io,"abortHandshakeOrEmitwsClientError")});var xb,$b,Cb,_b,Eb,Fb,$p,lc,lt,sn=G(()=>{xb=y(hp(),1),$b=y(Ar(),1),Cb=y(as(),1),_b=y(Qa(),1),Eb=y(tc(),1),Fb=y(ac(),1),$p=y(Ir(),1),lc=y(xp(),1),lt=$p.default});var Sc={};Re(Sc,{JobsApiClient:()=>je,captureWorkspaceSnapshot:()=>qp,createSnapshotArchive:()=>Vp,getLocalJobLogs:()=>kc,getLocalJobStatus:()=>wc,getLocalJobs:()=>bc,printJobStatus:()=>Ur,printJobsTable:()=>vc,printLogEntry:()=>Wr,pullJobChanges:()=>Dc,runLocalBackgroundJob:()=>zp,submitBackgroundJob:()=>Pb});function qp(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(`
|
|
160
|
+
`),u="";try{let p=oe.join(s,".monkeyscode","rules.md");q.existsSync(p)&&(u=q.readFileSync(p,"utf8"))}catch{}let d="";try{let p=oe.join(s,".monkeyscode","config.json");q.existsSync(p)&&(d=q.readFileSync(p,"utf8"))}catch{}return{repo:t,branch:o,commit:n,dirtyDiff:c,rules:u,config:d}}function Vp(s,e){let t=q.mkdtempSync(oe.join(Hp.tmpdir(),"mc-archive-")),o=oe.join(t,"snapshot");q.mkdirSync(o,{recursive:!0}),s.dirtyDiff&&q.writeFileSync(oe.join(o,"dirty.diff"),s.dirtyDiff,"utf8"),s.rules&&q.writeFileSync(oe.join(o,"rules.md"),s.rules,"utf8"),s.config&&q.writeFileSync(oe.join(o,"config.json"),s.config,"utf8"),e&&e.length>0&&q.writeFileSync(oe.join(o,"conversation.json"),JSON.stringify(e,null,2),"utf8"),q.writeFileSync(oe.join(o,"metadata.json"),JSON.stringify({repo:s.repo,branch:s.branch,commit:s.commit,createdAt:new Date().toISOString()},null,2),"utf8");let n=oe.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=Gp.gzipSync(Buffer.from(r,"utf8"));q.writeFileSync(n,i)}return n}async function Pb(s){let e=J(),o=me()?.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=qp(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 je(e.platformUrl,o),i=null;try{console.log(a.dim(" \u{1F4E6} Creating compressed archive...")),i=Vp(n,s.conversationHistory);let u=q.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=oe.dirname(i);q.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 zp({...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 zp(s){let e=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,{getPlatformPaths:t}=await Promise.resolve().then(()=>(Q(),$o)),o=t(),n=oe.join(o.data,"jobs",e);q.mkdirSync(n,{recursive:!0});let r={jobId:e,prompt:s.prompt,workspace:oe.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};q.writeFileSync(oe.join(n,"config.json"),JSON.stringify(r,null,2),"utf8"),q.writeFileSync(oe.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(oe.join(n,"log.jsonl"))}`),console.log(` Status: ${a.dim(`mc jobs status ${e}`)}`),console.log("")}function bc(s){try{let{getPlatformPaths:e}=(Q(),Rs($o)),t=e(),o=oe.join(t.data,"jobs");if(!q.existsSync(o))return[];let n=q.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=oe.join(o,i.name);try{let u=JSON.parse(q.readFileSync(oe.join(c,"status.json"),"utf8")),d=JSON.parse(q.readFileSync(oe.join(c,"config.json"),"utf8"));if(s?.status&&u.status!==s.status)continue;let p,f,m,g,h,b=oe.join(c,"result.json");if(q.existsSync(b)){let k=JSON.parse(q.readFileSync(b,"utf8"));p=k.duration,f=k.filesChanged?.length,m=k.tokensUsed,g=k.costUsd,(k.status==="completed"||k.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(q.statSync(oe.join(c,"config.json")).birthtimeMs),completedAt:h,currentStep:u.message})}catch{}}return r}catch{return[]}}function wc(s){try{let{getPlatformPaths:e}=(Q(),Rs($o)),t=e(),o=oe.join(t.data,"jobs",s);if(!q.existsSync(o))return null;let n=JSON.parse(q.readFileSync(oe.join(o,"status.json"),"utf8")),r=JSON.parse(q.readFileSync(oe.join(o,"config.json"),"utf8")),i={id:s,status:n.status,prompt:r.prompt||"",model:r.model||"unknown",createdAt:new Date(q.statSync(oe.join(o,"config.json")).birthtimeMs),currentStep:n.message},c=oe.join(o,"result.json");if(q.existsSync(c)){let u=JSON.parse(q.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}=(Q(),Rs($o)),t=e(),o=oe.join(t.data,"jobs",s,"log.jsonl");return q.existsSync(o)?q.readFileSync(o,"utf8").split(`
|
|
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 Jp(){return process.platform!=="win32"||!!process.env.WT_SESSION}function Kp(s){return(Jp()?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=`${Kp(n.status)} ${Yp(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 Ur(s,e){let t=Jp();if(console.log(""),console.log(a.bold(` ${t?"\u{1F4CB}":">>"} Job: ${s.id}`)),console.log(a.dim(" "+(t?"\u2500":"-").repeat(50))),console.log(` Status: ${Kp(s.status)} ${Yp(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 Wr(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 Wp(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 Yp(s){return s.charAt(0).toUpperCase()+s.slice(1)}var q,oe,Hp,Gp,jo,Ib,je,Mb,Ob,an=G(()=>{"use strict";q=y(require("node:fs"),1),oe=y(require("node:path"),1),Hp=y(require("node:os"),1),Gp=y(require("node:zlib"),1),jo=require("node:child_process");U();Z();te();Ib={},je=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=q.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(Wp):[]}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 Wp(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(`
|
|
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(qp,"captureWorkspaceSnapshot");l(Vp,"createSnapshotArchive");l(Pb,"submitBackgroundJob");l(zp,"runLocalBackgroundJob");l(bc,"getLocalJobs");l(wc,"getLocalJobStatus");l(kc,"getLocalJobLogs");l(Dc,"pullJobChanges");l(Jp,"shouldUseUnicode");Mb={queued:"\u23F3",running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u{1F6AB}"},Ob={queued:"[Q]",running:"[~]",completed:"[+]",failed:"[X]",cancelled:"[-]"};l(Kp,"getStatusIcon");l(vc,"printJobsTable");l(Ur,"printJobStatus");l(Wr,"printLogEntry");l(Wp,"parseJobInfo");l(yc,"formatDuration");l(Yp,"capitalize")});var Xp={};Re(Xp,{resumeFromJob:()=>jb});async function jb(s){let e=J(),o=me()?.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 je(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,gs.execSync)("git apply --check -",{cwd:s.workspace,input:d,stdio:["pipe","pipe","pipe"]}),(0,gs.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=cn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");return m(f,{recursive:!0}),g(cn.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=cn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");m(f,{recursive:!0}),g(cn.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,gs.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,gs.execSync)("git diff --name-only",{cwd:s,encoding:"utf8"}).trim();if(r){let c=r.split(`
|
|
163
|
+
`).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,gs.execSync)("git diff --cached --name-only",{cwd:s,encoding:"utf8"}).trim();if(i){let c=i.split(`
|
|
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 cn,gs,Qp=G(()=>{"use strict";cn=y(require("node:path"),1),gs=require("node:child_process");U();an();Z();te();l(jb,"resumeFromJob");l(Nb,"checkSyncCompatibility")});function $c(s){let e=Dt.join(s.workspace,ln,s.teamId,s.taskSlug),t=`monkeyscode/team-${s.teamId}/${s.taskSlug}`;dt.mkdirSync(Dt.dirname(e),{recursive:!0});let o=s.baseBranch||(0,Vt.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s.workspace,encoding:"utf8"}).trim();try{(0,Vt.execSync)(`git worktree add -b "${t}" "${e}" "${o}"`,{cwd:s.workspace,encoding:"utf8",stdio:"pipe"})}catch{try{(0,Vt.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,Vt.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,Vt.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,Vt.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,Vt.execSync)("git worktree prune",{cwd:s,stdio:"pipe"})}catch{}}function Ub(s){let e;try{e=(0,Vt.execSync)("git worktree list --porcelain",{cwd:s,encoding:"utf8"})}catch{return[]}let t=[],o=e.split(`
|
|
165
165
|
|
|
166
166
|
`).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=at.statSync(i).birthtime}catch{}let f=i.split(yt.sep),m=f.indexOf(rn.replace(/\//g,yt.sep).split(yt.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(rn),createdAt:p,label:g})}return t}function fs(s){return Eb(s).filter(e=>e.path.includes(rn))}function Jp(s){let e=s.ttlMs??$b,t=Date.now(),o=[],n=[],r=fs(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Sc(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=yt.join(s.workspace,rn);try{Kp(i)}catch{}return{removed:o,errors:n}}function Kp(s){if(!at.existsSync(s))return;let e=at.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&Kp(yt.join(s,t.name));at.readdirSync(s).length===0&&at.rmdirSync(s)}function xc(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var at,yt,Ht,rn,$b,_b,Dc,Cc=H(()=>{"use strict";at=y(require("node:fs"),1),yt=y(require("node:path"),1),Ht=require("node:child_process"),rn=".monkeyscode-worktrees",$b=24*60*60*1e3,_b=500,Dc=3;l(vc,"createWorktree");l(Sc,"removeWorktree");l(Eb,"listWorktrees");l(fs,"listManagedWorktrees");l(Jp,"cleanStaleWorktrees");l(Kp,"cleanEmptyDirs");l(xc,"slugify")});var Xp={};Te(Xp,{mergeTeam:()=>_c,runInWorktree:()=>Tb,showTeamStatus:()=>$c,spawnTeam:()=>Lr});async function Lr(s){let e=Rb(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:xc(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=vc({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=z(),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,uo.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,uo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,uo.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 (${Yp(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=an.join(s.workspace,".monkeyscode-worktrees",e);ct.mkdirSync(m,{recursive:!0});let g=an.join(m,"state.json");ct.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 $c(s){let e=an.join(s,".monkeyscode-worktrees");if(!ct.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=ct.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=an.join(e,u.name,"state.json");if(ct.existsSync(d))try{t.push(JSON.parse(ct.readFileSync(d,"utf8")))}catch{}}}catch{}let o=fs(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?Yp(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+" "+Fb(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 Fb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function _c(s,e){let t=fs(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,uo.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{Sc(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 Tb(s,e,t){let o=xc(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=vc({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,uo.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,uo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,uo.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 Rb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function Yp(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 ct,an,uo,Ec=H(()=>{"use strict";ct=y(require("node:fs"),1),an=y(require("node:path"),1),uo=require("node:child_process");U();Cc();Q();oe();l(Lr,"spawnTeam");l($c,"showTeamStatus");l(Fb,"capitalize");l(_c,"mergeTeam");l(Tb,"runInWorktree");l(Rb,"generateTeamId");l(Yp,"formatDuration")});var Br={};Te(Br,{MessageBroker:()=>cn});function Ab(){try{let s=Zp.join(em.homedir(),".monkeyscode","daemon.port"),e=Qp.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var Qp,Zp,em,Fc,Tc,cn,ln=H(()=>{"use strict";Qp=y(require("node:fs"),1),Zp=y(require("node:path"),1),em=y(require("node:os"),1);en();Fc=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 rt(`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()}},Tc=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(Ab,"readDaemonPort");cn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=Ab();n?this.transport=new Fc(n):this.transport=new Tc(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 om={};Te(om,{analyzeImpact:()=>tm,notifyAffectedSessions:()=>Ob});function tm(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=bt.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=bt.relative(r.workspace,d),g=bt.dirname(m).split(bt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Pb)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 Ob(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=tm(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=>bt.basename(p)).join(", "):`${e.slice(0,3).map(p=>bt.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
|
|
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
|
|
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,cm=G(()=>{"use strict";vt=y(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(im,"analyzeImpact");l(zb,"notifyAffectedSessions")});var um={};Re(um,{fetchModels:()=>lm,getModelInfo:()=>Jb});async function lm(){let s=J(),e=await Ee(),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 cd(r),r}async function Jb(s){try{return(await lm()).find(t=>t.id===s)||null}catch{return null}}var dm=G(()=>{"use strict";te();Z();fr();l(lm,"fetchModels");l(Jb,"getModelInfo")});var Im={};Re(Im,{default:()=>pw});var pw,jm=G(()=>{pw={name:"monkeyscode-cli",version:"0.1.6",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,lf=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 vn,Kc,oi,uf=G(()=>{"use strict";vn=y(require("node:fs"),1),Kc=y(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=vn.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=vn.readdirSync(e,{withFileTypes:!0});for(let n of o){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let r=Kc.join(e,n.name);try{let i=vn.watch(r,(c,u)=>{!u||!this.running||this.onFileChange(Kc.join(n.name,u))});this.watchers.push(i),this.watchDirectories(r,t+1)}catch{}}}catch{}}}});var pf={};Re(pf,{TriggerEngine:()=>Yc});var $t,Sn,df,Yc,mf=G(()=>{"use strict";$t=y(require("node:fs"),1),Sn=y(require("node:path"),1),df=require("node:events");Je();Z();lf();uf();Yc=class extends df.EventEmitter{static{l(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=Sn.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new ti,this.fileWatcher=new oi(e.workspace),this.loadState()}loadTriggers(){let e=Sn.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=J(),i=new Se({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(`
|
|
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=Sn.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 gf={};Re(gf,{GitHubWebhookServer:()=>Xc});var ff,Ds,Xc,hf=G(()=>{"use strict";ff=y(require("node:http"),1),Ds=y(require("node:crypto"),1),Xc=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=ff.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"]||Ds.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="+Ds.createHmac("sha256",o).update(e).digest("hex");return Ds.timingSafeEqual(Buffer.from(t),Buffer.from(n))}}});var xg={};Re(xg,{getNotificationBackend:()=>jk,notifyJobComplete:()=>Mk,notifyUpdateAvailable:()=>Ok,sendNotification:()=>ul,supportsNotifications:()=>Ik});function ul(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 ul({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 ul({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=cl.join(ll.tmpdir(),`mc-notify-${process.pid}.scpt`);try{return ko.writeFileSync(n,o,"utf8"),(0,Qt.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{ko.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}
|
|
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(ko.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,Qt.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Uk(s){try{return(0,Qt.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Wk(s){try{return(0,Qt.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Hk(s){let e=Sg(s.title),t=Sg(s.body),o=`
|
|
171
171
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
172
172
|
|
|
173
173
|
# Try WinRT Toast (Windows 10 1709+)
|
|
@@ -231,55 +231,55 @@ try {
|
|
|
231
231
|
catch {}
|
|
232
232
|
|
|
233
233
|
exit 1
|
|
234
|
-
`,n=
|
|
235
|
-
${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ch=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),lh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=ih.bind(null,o,e.toString());Object.defineProperty(n,"name",ch);let{writable:r,enumerable:i,configurable:c}=ah;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Oi(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))sh(s,e,n,t);return rh(s,e),lh(s,e,o),s}l(Oi,"mimicFunction");var Ln=new WeakMap,Nl=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(Ln.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 Oi(r,s),Ln.set(r,o),r},"onetime");Nl.callCount=s=>{if(!Ln.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Ln.get(s)};var Ll=Nl;var ko=[];ko.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&ko.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&ko.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Bn=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"),Mi=Symbol.for("signal-exit emitter"),Ii=globalThis,uh=Object.defineProperty.bind(Object),ji=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ii[Mi])return Ii[Mi];uh(Ii,Mi,{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}},Un=class{static{l(this,"SignalExitBase")}},dh=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Ni=class extends Un{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Li=class extends Un{static{l(this,"SignalExit")}#i=Bi.platform==="win32"?"SIGINT":"SIGHUP";#o=new ji;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of ko)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(!Bn(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 ko)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,ko.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 Bn(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"&&Bn(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)}},Bi=globalThis.process,{onExit:Bl,load:vD,unload:SD}=dh(Bn(Bi)?new Li(Bi):new Ni);var Ul=As.default.stderr.isTTY?As.default.stderr:As.default.stdout.isTTY?As.default.stdout:void 0,ph=Ul?Ll(()=>{Bl(()=>{Ul.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Wl=ph;var Wn=!1,Jo={};Jo.show=(s=Ui.default.stderr)=>{s.isTTY&&(Wn=!1,s.write("\x1B[?25h"))};Jo.hide=(s=Ui.default.stderr)=>{s.isTTY&&(Wl(),Wn=!0,s.write("\x1B[?25l"))};Jo.toggle=(s,e)=>{s!==void 0&&(Wn=s),Wn?Jo.show(e):Jo.hide(e)};var Wi=Jo;var Is=y(Hi(),1);U();var qe=y(require("node:process"),1);function Gi(){return qe.default.platform!=="win32"?qe.default.env.TERM!=="linux":!!qe.default.env.CI||!!qe.default.env.WT_SESSION||!!qe.default.env.TERMINUS_SUBLIME||qe.default.env.ConEmuTask==="{cmd::Cmder}"||qe.default.env.TERM_PROGRAM==="Terminus-Sublime"||qe.default.env.TERM_PROGRAM==="vscode"||qe.default.env.TERM==="xterm-256color"||qe.default.env.TERM==="alacritty"||qe.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Gi,"isUnicodeSupported");var fh={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},gh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},hh=Gi()?fh:gh,Ps=hh;function qi({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(qi,"ansiRegex");var yh=qi();function Os(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(yh,"")}l(Os,"stripAnsi");var Vl=[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,Jl=65510,Kl=[12288,12288,65281,65376,65504,65510];var Yl=4352,Xl=262141,Vi=[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 Gn=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 Ql=19968,[kh,Dh]=vh(Vi);function vh(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(Ql>=n&&Ql<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(vh,"findWideFastPathRange");var Zl=l(s=>s<161||s>1114109?!1:Gn(Vl,s),"isAmbiguous"),eu=l(s=>s<zl||s>Jl?!1:Gn(Kl,s),"isFullWidth");var tu=l(s=>s>=kh&&s<=Dh?!0:s<Yl||s>Xl?!1:Gn(Vi,s),"isWide");function Sh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(Sh,"validate");function ou(s,{ambiguousAsWide:e=!1}={}){return Sh(s),eu(s)||tu(s)||e&&Zl(s)?2:1}l(ou,"eastAsianWidth");var ru=y(nu(),1);var xh=new Intl.Segmenter,Ch=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function zi(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=Os(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of xh.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)&&!Ch.test(i)){if((0,ru.default)().test(i)){n+=2;continue}n+=ou(c,r)}}return n}l(zi,"stringWidth");function Ji({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(Ji,"isInteractive");var Ki=y(require("node:process"),1);function Yi(){let{env:s}=Ki.default,{TERM:e,TERM_PROGRAM:t}=s;return Ki.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(Yi,"isUnicodeSupported");var et=y(require("node:process"),1);var $h=3,Xi=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(){et.default.platform==="win32"||!et.default.stdin.isTTY||(et.default.stdin.setRawMode(!0),et.default.stdin.on("data",this.#n),et.default.stdin.resume())}#e(){et.default.stdin.isTTY&&(et.default.stdin.off("data",this.#n),et.default.stdin.pause(),et.default.stdin.setRawMode(!1))}#n(e){e[0]===$h&&et.default.emit("SIGINT")}},_h=new Xi,Qi=_h;var Eh=y(Hi(),1);var Zi=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:Ms.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:Ji({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,Ms.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(!Yi())this.#r=Is.default.line;else if(e===void 0)this.#r=Is.default.dots;else if(e!=="default"&&Is.default[e])this.#r=Is.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 Os(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(
|
|
234
|
+
`,n=cl.join(ll.tmpdir(),`mc-notify-${process.pid}.ps1`);try{let r=Buffer.from([239,187,191]),i=Buffer.concat([r,Buffer.from(o,"utf8")]);return ko.writeFileSync(n,i),(0,Qt.execSync)(`powershell -NoProfile -ExecutionPolicy Bypass -File "${n}"`,{stdio:"pipe",timeout:15e3}),!0}catch{return!1}finally{try{ko.unlinkSync(n)}catch{}}}function Sg(s){return s.replace(/'/g,"''")}function Et(s){try{return process.platform==="win32"?(0,Qt.execSync)(`where ${s} 2>NUL`,{stdio:"pipe"}):(0,Qt.execSync)(`command -v ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}var ko,cl,ll,Qt,$g=G(()=>{"use strict";ko=y(require("node:fs"),1),cl=y(require("node:path"),1),ll=y(require("node:os"),1),Qt=require("node:child_process");l(ul,"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(Sg,"escapePowerShell");l(Et,"commandExists")});var Cl=y($l(),1),{program:aD,createCommand:cD,createArgument:lD,createOption:uD,CommanderError:dD,InvalidArgumentError:pD,InvalidOptionArgumentError:mD,Command:_l,Argument:fD,Option:At,Help:gD}=Cl.default;var N=y(require("node:path"),1),K=y(require("node:fs"),1);var mm=y(require("node:readline"),1),z=y(require("node:path"),1),I=y(require("node:fs"),1),Xe=require("node:child_process");U();U();var Ns=y(require("node:process"),1);U();var Gi=y(require("node:process"),1);var Os=y(require("node:process"),1);var yh=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);!bh(n,r)&&o||Object.defineProperty(s,t,r)},"copyProperty"),bh=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"),wh=l((s,e)=>{let t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(s)&&Object.setPrototypeOf(s,t)},"changePrototype"),kh=l((s,e)=>`/* Wrapped ${s}*/
|
|
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(Yi(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&&qi.hide(this.#s),this.#t.discardStdin&&Ns.default.stdin.isTTY&&(this.#o=!0,ta.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#s.write(`- ${this.text}
|
|
237
|
+
`),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&qi.show(this.#s),this.#t.discardStdin&&Ns.default.stdin.isTTY&&this.#o&&(ta.stop(),this.#o=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Is.success,text:e})}fail(e){return this.stopAndPersist({symbol:Is.error,text:e})}warn(e){return this.stopAndPersist({symbol:Is.warning,text:e})}info(e){return this.stopAndPersist({symbol:Is.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+`
|
|
238
|
+
`;return this.stop(),this.#s.write(p),this}};function Bs(s){return new oa(s)}l(Bs,"ora");Ce();U();Ce();U();Ce();function uu(s,e,t={}){let o=O(),n=Me(o),r=W(o),i=t.maxWidth??o.columns,c=t.color??o.ansi,u=e.split(`
|
|
239
|
+
`),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,f=n.horizontal.repeat(Math.max(0,i-pu(p).length-1));d.push(c?a.cyan(p+f+n.topRight):p+f+n.topRight);let m=0,g=0;for(let S of u)if(!(S.startsWith("---")||S.startsWith("+++")||S.startsWith("diff ")||S.startsWith("index "))){if(S.startsWith("@@")){let x=`${n.vertical} ${S}`;d.push(c?a.magenta(x):x);continue}if(S.startsWith("+")){m++;let x=`${n.vertical} + ${S.slice(1)}`,E=sa(x,i);d.push(c?a.green(E):E);continue}if(S.startsWith("-")){g++;let x=`${n.vertical} - ${S.slice(1)}`,E=sa(x,i);d.push(c?a.red(E):E);continue}if(S.startsWith(" ")||S===""){let x=`${n.vertical} ${S}`,E=sa(x,i);d.push(c?a.dim(E):E)}}let h=` +${m} -${g} `,b=`${n.bottomLeft}${n.horizontal}${h}`,k=n.horizontal.repeat(Math.max(0,i-b.length-1));return d.push(c?a.cyan(b+k+n.bottomRight):b+k+n.bottomRight),d.join(`
|
|
240
|
+
`)}l(uu,"renderDiff");function du(s,e,t){let o=O(),n=W(o),r=o.ansi,i=r?a.green(`+${e}`):`+${e}`,c=r?a.red(`-${t}`):`-${t}`;return` ${n.file} ${s} (${i} ${c})`}l(du,"renderDiffSummary");function sa(s,e){return pu(s).length<=e?s:s.slice(0,e-3)+"..."}l(sa,"truncateLine");function pu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(pu,"stripAnsi");function ra(s,e){let t=O(),o=W(t),n=t.ansi,r=uy(s,o),i=dy(s,e),c=` ${r} ${s}: ${i}`;return n?a.yellow(c):c}l(ra,"renderToolStart");function ia(s,e,t={}){switch(e.type){case"file_edit":return oy(e,t);case"file_read":return sy(e);case"terminal":return ny(e,t);case"search":return ry(e,t);case"git":return iy(e);case"browser":return ay(e);case"mcp":return cy(e);case"web_search":return ly(e);case"generic":return mu(s,e);default:return mu(s,{type:"generic",summary:JSON.stringify(e)})}}l(ia,"renderToolResult");function fu(s,e){let t=O(),o=W(t),n=t.ansi,r=` ${o.error} ${s} failed: ${e}`;return n?a.red(r):r}l(fu,"renderToolError");function oy(s,e){return e.verbose&&s.diff?uu(s.filePath,s.diff):du(s.filePath,s.linesAdded,s.linesRemoved)}l(oy,"renderFileEdit");function sy(s){let e=O();return` ${W(e).file} Read ${na(s.filePath)} (${s.lineCount} lines)`}l(sy,"renderFileRead");function ny(s,e){let t=O(),o=Me(t),n=W(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
241
|
`),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
242
|
`).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(
|
|
243
|
+
`)}l(ny,"renderTerminal");function ry(s,e){let t=O(),o=W(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(`
|
|
244
|
+
`)}l(ry,"renderSearch");function iy(s){let e=O(),t=W(e),o=e.ansi,n=[];if(n.push(` ${t.git} git ${s.command}`),s.output){let r=s.output.split(`
|
|
245
245
|
`).slice(0,15);for(let i of r)n.push(o?a.dim(` ${i}`):` ${i}`)}return n.join(`
|
|
246
|
-
`)}l(
|
|
247
|
-
`)}l(
|
|
246
|
+
`)}l(iy,"renderGit");function ay(s){let e=O(),t=W(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(`
|
|
247
|
+
`)}l(ay,"renderBrowser");function cy(s){let e=O(),t=W(e),o=Me(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
248
|
`).slice(0,10);for(let h of m)i.push(`${o.vertical} ${h}`);f.split(`
|
|
249
249
|
`).length>10&&i.push(`${o.vertical} ${n?a.dim(`... ${f.split(`
|
|
250
250
|
`).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=j(),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=ey(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),v=b-k,x=h("\u2588".repeat(k))+a.dim("\u2591".repeat(v));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=mu(c).length,p=mu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function ey(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(ey,"formatTokensCompact");function mu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(mu,"stripAnsi");U();var Tt={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},ty={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..................."]},oy={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............"]},sy={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..."]},ny={large:ty,medium:oy,mini:sy},fu="\u25C1\u2571\u25B7",gu="</>";function hu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(hu,"isDarkBackground");function yu(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=ny[s],c=o?Tt.navyOnDark:Tt.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Tt.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="",v=h[0]??".";for(let x=0;x<m.length;x++){let _=h[x]??".";_!==v&&(b+=p(k,v),k="",v=_),k+=m[x]}return b+=p(k,v),(f+b).replace(/\s+$/,"")})}l(yu,"renderLogo");function bu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(bu,"pickLogoSize");function na(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(na,"visibleWidth");var ry={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},So=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={...ry,...e},this.caps=j(),this.icons=W(this.caps),this.box=Ve(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 Jn(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(Tt.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.5";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?bu(this.caps.columns,this.caps.unicode):u;if(d){let f=yu(d,{color:o,dark:hu(),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":fu} MonkeysCode`,h="CLI Agent",b=Math.max(0,f-na(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}`:""}`,v=Math.max(0,f-na(k)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(v)} ${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(` ${gu} 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(Tt.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&&
|
|
251
|
+
`)}l(cy,"renderMcp");function ly(s){let e=O(),t=W(e),o=Me(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(`
|
|
252
|
+
`)}l(ly,"renderWebSearch");function mu(s,e){let t=O();return` ${W(t).tool} ${s}: ${e.summary}`}l(mu,"renderGeneric");function uy(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(uy,"getToolIcon");function dy(s,e){switch(s){case"file_edit":return na(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return na(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(dy,"getToolArgsSummary");function na(s){return process.platform==="win32"?s.replace(/\//g,"\\"):s}l(na,"displayPath");U();function Yn(s,e={}){let t=e.width||process.stdout.columns||80,o=s.split(`
|
|
253
|
+
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(gu(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 S=h[1],x=Kn(h[3]);n.push(`${S} \u2022 ${x}`);continue}let b=u.match(/^(\s*)(\d+)\.\s(.+)/);if(b){let S=b[1],x=b[2],E=Kn(b[3]);n.push(`${S} ${a.dim(x+".")} ${E}`);continue}let k=u.match(/^>\s?(.*)/);if(k){n.push(a.dim(" \u2502 ")+a.italic(Kn(k[1])));continue}if(u.trim()===""){n.push("");continue}n.push(Kn(u))}return r&&c.length>0&&n.push(gu(c,i)),n.join(`
|
|
254
|
+
`)}l(Yn,"renderMarkdown");function Kn(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(Kn,"renderInline");function gu(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}${py(c,e)}`);return[n,...i,r].join(`
|
|
255
|
+
`)}l(gu,"renderCodeBlock");function py(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=my(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(py,"highlightSyntax");function my(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(my,"getLanguageKeywords");function hu(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(hu,"containsMarkdown");U();Ce();var Xn=class{static{l(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=O(),this.icons=W(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(`
|
|
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(nt.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(ra(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=Bs({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(ia(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(fu(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 b=e.riskLevel==="dangerous"?" [y] Allow once [n] Deny":" [y] Allow [n] Deny [a] Always [!] YOLO",k=Math.max(0,i-b.length);console.log(r.color(` ${o.vertical}`)+a.dim(` ${b}${" ".repeat(k)}`)+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(`
|
|
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=Bs({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(nt.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(ra(e,t)),!this.opts.accessible&&this.caps.ansi){let o=Bs({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(ia(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(`
|
|
259
|
+
`).length;if(this.caps.ansi&&hu(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=Yn(e,{caps:this.caps});if(this.caps.unicode){let n=a.dim(` ${this.box.vertical} `),r=o.split(`
|
|
260
260
|
`).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(-
|
|
263
|
-
`).filter(r=>r.trim().length>0)),n.length>0&&n[n.length-1]===t)return;n.push(t),n.length>
|
|
261
|
+
`);process.stdout.write(r)}else process.stdout.write(o)}else console.log("");if(this.caps.unicode){let o=a.hex(nt.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=ky(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 b of p){let k=b.padEnd(d);console.log(this.caps.ansi?` ${a.cyan(t.vertical)} ${k} ${a.cyan(t.vertical)}`:` ${t.vertical} ${k} ${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 ky(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(ky,"wrapText");Ce();te();Je();Z();var ue=y(require("node:fs"),1),Ie=y(require("node:path"),1);Q();var Uy=20;function dd(s,e,t,o){if(o.size===0)return;let n=P(),r=Ie.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=Ie.join(r,`${s}.json`);ue.writeFileSync(c,JSON.stringify(i,null,2)),Wy(r)}l(dd,"saveCheckpoint");function pd(){let s=P(),e=Ie.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(Ie.join(e,o),"utf8"))}catch{return null}}).filter(Boolean):[]}l(pd,"listCheckpoints");function md(s){let e=P(),t=Ie.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 ${Ie.relative(o.workspace,r)}`)):(ue.mkdirSync(Ie.dirname(r),{recursive:!0}),ue.writeFileSync(r,i),n.push(`restored ${Ie.relative(o.workspace,r)}`))}catch(c){n.push(`FAILED ${Ie.relative(o.workspace,r)}: ${c instanceof Error?c.message:c}`)}return ue.unlinkSync(t),n}l(md,"revertCheckpoint");function Wy(s){let e=ue.readdirSync(s).filter(t=>t.endsWith(".json")).map(t=>({name:t,mtime:ue.statSync(Ie.join(s,t)).mtime.getTime()})).sort((t,o)=>o.mtime-t.mtime);for(let t of e.slice(Uy))try{ue.unlinkSync(Ie.join(s,t.name))}catch{}}l(Wy,"pruneCheckpoints");var he=y(require("node:fs"),1),ao=y(require("node:path"),1),fd=y(require("node:crypto"),1);Q();var Hy="sessions",Gy=20,qy=30*24*60*60*1e3,Bt=class{static{l(this,"SessionStore")}sessionsDir;constructor(){let e=P();this.sessionsDir=ao.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:fd.randomUUID(),workspace:ao.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===ao.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=>ao.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=>ao.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 ao.join(this.sessionsDir,`${t}.json`)}ensureDir(){he.existsSync(this.sessionsDir)||he.mkdirSync(this.sessionsDir,{recursive:!0})}};Ca();var at=y(require("node:fs"),1),hr=y(require("node:path"),1);Q();var Na=1e3,Vy="history",gr=class{static{l(this,"HistoryManager")}historyFile;constructor(){let e=P();this.historyFile=hr.join(e.data,Vy)}load(){try{return at.existsSync(this.historyFile)?at.readFileSync(this.historyFile,"utf-8").split(`
|
|
262
|
+
`).filter(t=>t.trim().length>0).slice(-Na):[]}catch{return[]}}append(e){let t=e.trim();if(t&&!t.startsWith("/"))try{let o=hr.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
|
+
`).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
264
|
`)+`
|
|
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}};U();var
|
|
266
|
-
`)[0],h=e.find(b=>m.includes(b.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
|
|
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
|
|
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}};U();var yr=require("node:child_process");Je();Z();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 gd(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(gd,"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,b;for(;(b=h.exec(g))!==null;)e.push({suite:m,name:b[1].trim(),status:"fail",file:m,durationMs:b[2]?parseInt(b[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(`
|
|
266
|
+
`)[0],h=e.find(b=>m.includes(b.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 ns("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 ns("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 ns("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(`
|
|
267
|
+
`)[0])}return ns("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 ns("go",e)}l(o0,"parseGoTest");function s0(s){let e=[],t=s.split(`
|
|
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 ns("unknown",e)}l(s0,"parseGeneric");function ns(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(ns,"buildSummary");var hd=10,yd=1800,bd=5,br=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||hd,status:"planning",subtasks:[],elapsed:0,totalTokens:0,totalCost:0}}async run(){this.startTime=Date.now();let e=this.opts.maxIterations||hd,t=(this.opts.timeoutSeconds||yd)*1e3,o=this.opts.maxCostUsd||bd,n=J();if(this.printGoalHeader(),!this.opts.verifyCommand){let r=gd(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 Se({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
269
|
`);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
270
|
`)}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,
|
|
271
|
+
\u{1F50D} Running verification: ${e}`));try{let o=(0,yr.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
272
|
`).slice(-3).join(`
|
|
273
273
|
`)}`)),!0}catch(t){let o=t.stderr?.toString().slice(-500)||"",n=t.stdout?.toString().slice(-500)||"",r=n+`
|
|
274
|
-
`+o;if(this.lastTestSummary=
|
|
274
|
+
`+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
275
|
`).slice(-3).join(`
|
|
276
276
|
`)}`)):n.trim()&&console.log(a.dim(` ${n.trim().split(`
|
|
277
277
|
`).slice(-3).join(`
|
|
278
|
-
`)}`));return!1}}saveCheckpoint(){try{(0,
|
|
278
|
+
`)}`));return!1}}saveCheckpoint(){try{(0,yr.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,yr.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||yd)/60}min \xB7 Max cost: $${(this.opts.maxCostUsd||bd).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("")}};U();var wd=y(require("node:crypto"),1);Je();Z();var wr=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=wd.randomUUID().slice(0,8),o=J(),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 Se({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
279
|
`)[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
280
|
`);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
281
|
`).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
|
|
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=y(require("node:path"),1),Ks=require("node:child_process"),Dd=require("node:events");Je();var kr=require("node:child_process"),Ae=y(require("node:fs"),1),Ro=y(require("node:path"),1);var Dr=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");Ae.mkdirSync(c,{recursive:!0});let u=Ro.join(c,"base"),d=Ro.join(c,"ours"),p=Ro.join(c,"theirs");Ae.writeFileSync(u,n),Ae.writeFileSync(d,r),Ae.writeFileSync(p,i);try{(0,kr.execSync)(`git merge-file ${d} ${u} ${p}`,{cwd:this.workspace,stdio:"pipe"});let f=Ae.readFileSync(d,"utf8");return this.cleanup(c),{file:e,success:!0,hadConflicts:!1,mergedContent:f,conflictMarkers:[]}}catch{let f=Ae.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);Ae.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:Ae.existsSync(t)?Ae.readFileSync(t,"utf8"):"",conflictMarkers:[]}}getBaseBranch(){try{return(0,kr.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:this.workspace,encoding:"utf8"}).trim()}catch{return"HEAD"}}getFileAtBranch(e,t){try{return(0,kr.execSync)(`git show ${t}:${e}`,{cwd:this.workspace,encoding:"utf8"})}catch{return""}}parseConflictMarkers(e,t){let o=[],n=e.split(`
|
|
283
283
|
`),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
284
|
`:c+=n[r]+`
|
|
285
285
|
`,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,80 +287,84 @@ ${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
287
287
|
`:c+=t[n]+`
|
|
288
288
|
`,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
289
|
`);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{
|
|
290
|
+
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(Je(),Zo)),{loadSettings:n}=await Promise.resolve().then(()=>(Z(),ve)),{getAccessToken:r}=await Promise.resolve().then(()=>(te(),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(`
|
|
291
|
+
`);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{Ae.rmSync(e,{recursive:!0,force:!0})}catch{}}};Z();var kd=require("node:events"),Ba=y(require("node:crypto"),1);var vr=class extends kd.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 Sr=class extends Dd.EventEmitter{static{l(this,"AgentOrchestrator")}opts;resolver;activeLoops=new Map;broker;constructor(e){super(),this.opts={maxConcurrency:5,timeoutMs:6e5,...e},this.resolver=new Dr(e.workspace),this.broker=new vr,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
292
|
|
|
293
293
|
`+r.inputTransform(o):o&&(i+=`
|
|
294
294
|
|
|
295
295
|
--- 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=
|
|
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(
|
|
299
|
-
`),!0):!1}l(
|
|
300
|
-
`)[0]}catch{return null}}l(
|
|
301
|
-
`)}}},
|
|
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,Ks.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=J(),r=Date.now(),i="",c=0,u=0,d=[],p=new Se({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(`
|
|
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,Ks.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,Ks.execSync)(`git worktree remove --force ${t}`,{cwd:this.opts.workspace,stdio:"pipe"}),(0,Ks.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 Lp=y(require("node:fs"),1),Lr=require("node:child_process");U();Q();Ce();var Ap=require("node:child_process"),po=y(require("node:fs"),1),Nr=y(require("node:path"),1),Pp=require("node:events");sn();Q();var Tb=1;function Cp(s,e={}){return{jsonrpc:"2.0",id:Tb++,method:s,params:e}}l(Cp,"createRequest");function _p(s){return JSON.stringify(s)}l(_p,"serialize");function Ep(s){try{let e=JSON.parse(s);return e.kind||e.id!==void 0||e.method?e:null}catch{return null}}l(Ep,"parseMessage");function Fp(s){return typeof s=="object"&&s!==null&&"kind"in s}l(Fp,"isDaemonEvent");function Tp(s){return typeof s=="object"&&s!==null&&"id"in s&&"jsonrpc"in s}l(Tp,"isRpcResponse");var uo=class extends Pp.EventEmitter{static{l(this,"DaemonConnection")}ws=null;daemonProcess=null;pending=new Map;platform;paths;opts;reconnectAttempts=0;_connected=!1;constructor(e={}){super(),this.platform=$e(),this.paths=P(),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=Cp(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(_p(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(!po.existsSync(this.paths.pidFile))return null;let e=po.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 po.unlinkSync(this.paths.pidFile),null}}catch{return null}}async spawnDaemon(){Jn(Nr.dirname(this.paths.pidFile)),Jn(this.paths.logs);let e=Nr.join(this.paths.logs,`daemon-${Date.now()}.log`),t=po.createWriteStream(e,{flags:"a"}),o=this.opts.port;return this.daemonProcess=(0,Ap.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 Rp(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=Ep(e);if(t){if(Tp(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(Fp(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 Rp(t);try{await this.connectWebSocket(e)}catch{}}};function Rp(s){return new Promise(e=>setTimeout(e,s))}l(Rp,"sleep");te();$a();var He=y(require("node:fs"),1),ut=y(require("node:path"),1);Q();function nn(s){let e=P(),t=ut.join(s,".monkeyscode","mcp.json"),o=ut.join(e.config,"mcp.json"),n=Mp(o),r=Mp(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(nn,"loadMcpConfig");function Mp(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(Mp,"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=jp(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)+`
|
|
298
|
+
`)}l(uc,"addMcpServer");function Op(s,e){let t=ut.join(s,".monkeyscode","mcp.json"),o=jp(t);return o.servers[e]?(delete o.servers[e],He.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
299
|
+
`),!0):!1}l(Op,"removeMcpServer");function Ip(s){let e=P();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(Ip,"getMcpConfigPaths");function jp(s){if(!He.existsSync(s))return{servers:{}};try{return JSON.parse(He.readFileSync(s,"utf-8"))}catch{return{servers:{}}}}l(jp,"loadConfigFileRaw");ar();async function rn(s={}){let e=O(),t=W(e),o=e.ansi,n=$e(),r=P();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=Np(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 F=new uo({autoSpawn:!1,startTimeout:3e3});await F.connect(),F.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=Np("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 os(ir(".")).checkAllProviders(),g=m.filter(F=>F.available);if(g.length>0)i.push({name:"Sandbox",status:"ok",message:`Available: ${g.map(F=>F.name).join(", ")}`});else{let F=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:F})}for(let F of m)F.available||i.push({name:` \u2514 ${F.name}`,status:"warn",message:F.reason||"Not available"});let h=process.cwd(),b=nn(h);b.length>0?i.push({name:"MCP servers",status:"ok",message:`${b.length} configured: ${b.map(F=>F.name).join(", ")}`}):i.push({name:"MCP servers",status:"ok",message:"None configured (optional)"});let k=Fo(h);k.length>0?i.push({name:"Hooks",status:"ok",message:`${k.length} active: ${k.map(F=>F.event).join(", ")}`}):i.push({name:"Hooks",status:"ok",message:"None configured (optional)"});let S=Lp.existsSync(r.config);i.push(S?{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 x=O();i.push({name:"Terminal",status:"ok",message:[x.trueColor?"24-bit color":x.color256?"256 color":x.color16?"16 color":"no color",x.unicode?"Unicode":"ASCII",x.interactive?"interactive":"non-interactive",`${x.columns}x${x.rows}`].join(" \xB7 ")});for(let F of i){let j=F.status==="ok"?t.success:F.status==="warn"?t.warning:t.error,ae=F.status==="ok"?o?a.green:Y=>Y:F.status==="warn"?o?a.yellow:Y=>Y:o?a.red:Y=>Y;console.log(` ${j} ${ae(`${F.name}`)}: ${F.message}`),F.fix&&console.log(o?a.dim(` Fix: ${F.fix}`):` Fix: ${F.fix}`)}console.log("");let E=i.filter(F=>F.status==="error").length,$=i.filter(F=>F.status==="warn").length;if(E>0?console.log(o?a.red(` ${E} error(s), ${$} warning(s)`):` ${E} error(s), ${$} warning(s)`):$>0?console.log(o?a.yellow(` All good! ${$} warning(s)`):` All good! ${$} warning(s)`):console.log(o?a.green(" \u2728 Everything looks great!"):" Everything looks great!"),console.log(""),s.fix){let F=i.filter(j=>j.status!=="ok"&&j.fix);if(F.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 j of F){console.log(` \u2192 ${j.name}: ${j.fix}`);try{(0,Lr.execSync)(j.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(rn,"doctorCommand");function Np(s){try{return(0,Lr.execSync)(`which ${s} 2>/dev/null || where ${s} 2>nul`,{stdio:"pipe"}),!0}catch{return!1}}l(Np,"checkBinary");function Ab(s){try{return(0,Lr.execSync)(s,{stdio:"pipe"}).toString().trim().split(`
|
|
300
|
+
`)[0]}catch{return null}}l(Ab,"getVersion");fr();lr();var dc=y(require("node:fs"),1),pc=require("node:child_process");function qt(s){return s.replace(/\\/g,"/")}l(qt,"normalizePath");var ms=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:qt(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:qt(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}: ${qt(t.path)} (+${t.linesAdded} -${t.linesRemoved})`).join(`
|
|
301
|
+
`)}}},Br=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(`| \`${qt(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
302
|
${e.error}
|
|
303
303
|
\`\`\``),t.push("")),t.join(`
|
|
304
|
-
`)}},
|
|
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=>qt(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
305
|
`)+`
|
|
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=>
|
|
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=>qt(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 Br().formatResult(e);try{dc.appendFileSync(n,r+`
|
|
307
307
|
`)}catch{}}return!e.success&&e.error&&t.push(`::error::${e.error}`),t.join(`
|
|
308
|
-
`)}},
|
|
309
|
-
`)}},
|
|
310
|
-
${a.hex("#6B8DD6")(
|
|
311
|
-
${
|
|
312
|
-
`).length;process.stdout.write(`\x1B[${
|
|
313
|
-
\u{1F914} ${
|
|
314
|
-
`);
|
|
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=>qt(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(`
|
|
309
|
+
`)}},fs=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:qt(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:qt(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 Bp(s,e={}){switch(s){case"json":return new ms;case"jsonl":return new mc;case"diff":return new fc(e.workspace||".");case"markdown":return new Br;case"github":return new gc;case"azure":return new hc;case"sarif":return new fs(e.findings,e.workspace);case"text":case"stream":default:return new ms}}l(Bp,"createFormatter");function Up(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(Up,"createEmptyResult");function fm(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(fm,"mapMode");async function gm(s){let e=O(),t=s.prompt;!t&&!e.interactive&&(t=await Xb());let o=await Ee();if(o||(console.error(a.red(" Error: Not authenticated. Run `mc auth login` first.")),process.exit(1)),s.model==="auto"){let r=J();s.model=r.defaultModel}let n=me();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(Qp(),Xp));await r({jobId:s.resume,workspace:s.workspace}),await pm(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Rc(),om));await r(s.prompt,s.workspace,s.model)}else s.headless?await Kb(t,s,o,n):s.background?await Yb(t,s):await pm(t,s,o,n)}l(gm,"runCommand");async function pm(s,e,t,o){let n=O(),r=J(),i=new Co({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new To(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new Bt,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,g=new Set,h=0,b=0,k=0,S=0,x=null,E=!1;if(e.continueSession){let M=u.loadLatest(e.workspace);if(M){d=M,S=M.turnCount;for(let B of M.stats.filesChanged)m.add(B);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,B=a.green,X=a.yellow,T=a.hex("#6B8DD6"),v=a.bold(e.model),w=M(e.mode);console.log(` ${T("Model:")} ${v} ${M("\xB7")} ${w} mode`);let D=(()=>{try{return(0,Xe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),C=(()=>{try{return(0,Xe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),_=D?` ${M("\xB7")} ${M("branch:")} ${D}${C?X(" \u25CF"):B(" \u2713")}`:"";console.log(` ${T("Path:")} ${M(e.workspace)}${_}`);let R=e.sandbox?B("\u{1F512} on"):X("off"),H=e.permissionMode!=="default"?` ${M("\xB7")} ${M("perm:")} ${e.permissionMode}`:"",A=e.autoApprove?` ${M("\xB7")} ${X("auto-approve")}`:e.approveForMe?` ${M("\xB7")} ${B("smart-approve")}`:"";console.log(` ${T("Sandbox:")} ${R}${H}${A}`);let et=c.getHooks(),xe=et.length>0?`${et.length} hooks`:M("none"),tt=0;try{let{listAllSkills:Te}=await Promise.resolve().then(()=>(dr(),Pa));tt=Te(e.workspace).length}catch{}let Es=tt>0?`${tt} skills`:M("none");console.log(` ${T("Plugins:")} ${xe} ${M("\xB7")} ${Es}`);let Fs=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${T("Engine:")} ${M(Fs)}`)}console.log("");let $=i.getStatusBar({model:e.model,mode:e.mode,branch:(()=>{try{return(0,Xe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),dirty:(()=>{try{return(0,Xe.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});$.start(),console.log(a.dim(" Type a prompt to start. /help for commands, /exit to quit, Ctrl+C to cancel.")),await c.fire("SessionStart",{workspace:e.workspace,data:{model:e.model,mode:e.mode}});let F=["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"],j=mm.createInterface({input:process.stdin,output:process.stdout,terminal:!0,prompt:(()=>{let M=W(n);return n.ansi?`
|
|
310
|
+
${a.hex("#6B8DD6")(M.prompt)} `:`
|
|
311
|
+
${M.prompt} `})(),historySize:200,completer:l(M=>{if(M.startsWith("/")){let B=M.slice(1).toLowerCase(),X=F.filter(T=>T.startsWith(B)).map(T=>`/${T}`);return[X.length?X:F.map(T=>`/${T}`),M]}if(M.startsWith("/context ")){let B=M.slice(9);try{let X=z.dirname(z.resolve(e.workspace,B)),T=z.basename(B);return[I.readdirSync(X).filter(D=>D.startsWith(T)).map(D=>`/context ${B.replace(T,"")}${D}`),M]}catch{return[[],M]}}return[[],M]},"completer")});new gr().wire(j);let Y=null,fe=null,Be=!1,ht=null,Do=new wr({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),Ft=null;try{let{MessageBroker:M}=await Promise.resolve().then(()=>(pn(),Gr));t&&r.platformUrl&&(Ft=new M(r.platformUrl,t,p))}catch{}let _s=l(async()=>{if(Ft)try{let M=await Ft.pollMessages();if(M&&M.length>0)for(let B of M)i.renderMessageCard({from:B.from||B.senderId||"unknown",content:B.content||B.message||"",timestamp:B.timestamp?new Date(B.timestamp):new Date})}catch{}},"pollAndRenderMessages"),Tt=l(async M=>{d||(d=u.create(e.workspace,e.model,e.mode)),u.addMessage(d,"user",M),S++,$.update({turn:S,busy:!0,activity:"thinking..."});let B=new Se({platformUrl:r.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:fm(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});Y=B;let X="";B.on("event",v=>{switch(v.type){case"streaming_chunk":X+=v.content,process.stdout.write(v.content);break;case"streaming_end":if(X.trim()){let D=X.split(`
|
|
312
|
+
`).length;process.stdout.write(`\x1B[${D}A\x1B[J`),console.log(Yn(X))}else console.log("");X="";break;case"tool_call_start":i.printToolCallStart(v.name,v.args),v.name==="file_read"&&v.args?.file_path&&g.add(String(v.args.file_path)),["file_edit","file_write","file_create"].includes(v.name)&&v.args?.file_path&&m.add(String(v.args.file_path));break;case"tool_call_result":i.printToolCallResult(v.name,v.result);break;case"ask_user":console.log(a.cyan(`
|
|
313
|
+
\u{1F914} ${v.question}`)),j.question(a.dim(" Answer: "),D=>{B.resolveUserInput(D)});break;case"todo_update":i.printTodoList(v.todos);break;case"run_complete":Qb(v.summary,i),h+=v.summary.tokensIn,b+=v.summary.tokensOut,k+=v.summary.tokensThinking||0,x=B.state.runId;for(let D of v.summary.filesModified)m.add(D);if($.update({tokensIn:h,tokensOut:b,cost:Js(e.model,h,b,k),turn:S,busy:!1,activity:""}),e.maxCost&&e.maxCost>0){let D=Js(e.model,h,b,k),C=D/e.maxCost;C>=1?(console.log(""),console.log(a.red(` \u{1F6AB} Session budget exceeded ($${D.toFixed(2)}/$${e.maxCost.toFixed(2)}). Stopping.`)),console.log(a.dim(" Use --max-cost to increase the budget.")),console.log(""),E=!0):C>=.8&&console.log(a.yellow(` \u26A0\uFE0F 80% of session budget used ($${D.toFixed(2)}/$${e.maxCost.toFixed(2)})`))}let w=B.getCheckpoints();w.size>0&&dd(B.state.runId,M,e.workspace,w),d&&u.updateStats(d,v.summary.tokensIn+v.summary.tokensOut,0,v.summary.filesModified);break;case"context_compacted":i.printSuccess(`Context auto-compacted: ${v.elided} tool result${v.elided===1?"":"s"} summarized (${Math.round(v.savedTokens/1e3)}K tokens saved, now ${Math.round(v.contextUsed/v.contextWindow*100)}% full)`);break;case"run_error":i.printError(v.error);break}});let T=[];B.on("run_complete",v=>{v?.summary?.filesModified&&(T=v.summary.filesModified)});try{await B.run(M)}catch(v){i.printError(v instanceof Error?v.message:String(v))}if(T.length>0&&Ft)try{let{notifyAffectedSessions:v}=await Promise.resolve().then(()=>(cm(),am));await v(Ft,T,p)}catch{}Y=null},"executePrompt");s&&await Tt(s),await _s(),j.prompt(),j.on("line",async M=>{let B=M.trim();if(E){j.close();return}if(!ht&&(B==="<<EOF"||B.endsWith("<<EOF"))){let X=B.replace(/<<EOF$/,"").trim();ht=X?[X]:[],j.setPrompt(a.dim(" ... ")),j.prompt();return}if(ht!==null){if(B==="EOF"){let X=ht.join(`
|
|
314
|
+
`);ht=null,j.setPrompt(n.emoji?`
|
|
315
315
|
\u{1F435} > `:`
|
|
316
|
-
> `),
|
|
317
|
-
|
|
318
|
-
|
|
316
|
+
> `),X.trim()&&await Tt(X),j.prompt();return}ht.push(M),j.setPrompt(a.dim(" ... ")),j.prompt();return}if(B.endsWith("\\")){ht=[B.slice(0,-1)],j.setPrompt(a.dim(" ... ")),j.prompt();return}if(!B){j.prompt();return}if(B.startsWith("/")){let[X,...T]=B.slice(1).split(" "),v=T.join(" ");switch(X){case"exit":case"quit":case"q":c.fire("Stop",{workspace:e.workspace,data:{}}),$.stop(),j.close();return;case"clear":case"cls":console.clear();break;case"model":case"models":if(v)e.model=v,i.printSuccess(`Model changed to: ${v}`),$.update({model:v});else try{let{fetchModels:w}=await Promise.resolve().then(()=>(dm(),um)),D=await w();if(D.length===0)console.log(a.yellow(" No models returned from the API."));else{let C=O(),_=Me(C),R=C.ansi,H=R?a.hex(nt.accent):xe=>xe,A=R?a.dim:xe=>xe,et=R?a.green:xe=>xe;if(C.unicode){console.log(""),console.log(H(` ${_.topLeft}${_.horizontal} Available Models ${_.horizontal.repeat(Math.max(0,32))}${_.topRight}`)),console.log(H(` ${_.vertical}${" ".repeat(52)}${_.vertical}`));let tt=` Current: ${a.bold(e.model)}`,Es=tt.replace(/\x1b\[[0-9;]*m/g,""),Fs=Math.max(0,52-Es.length);console.log(H(` ${_.vertical}`)+et(tt)+" ".repeat(Fs)+H(_.vertical)),console.log(H(` ${_.teeRight}${_.horizontal.repeat(52)}${_.teeLeft}`));for(let vo of D){let gi=vo.id===e.model,Ag=gi?et("\u25CF"):A("\u25CB"),Pg=((gi?a.bold(vo.name||vo.id):vo.name||vo.id)+(gi?" \u25C0":"")).padEnd(26),Mg=vo.contextWindow?A(`${Math.round(vo.contextWindow/1e3)}k`.padEnd(8)):"".padEnd(8),pl=` ${Ag} ${Pg}${Mg}`,Og=pl.replace(/\x1b\[[0-9;]*m/g,""),Ig=Math.max(0,52-Og.length);console.log(H(` ${_.vertical}`)+`${pl}${" ".repeat(Ig)}`+H(_.vertical))}console.log(H(` ${_.vertical}${" ".repeat(52)}${_.vertical}`));let Te=" Usage: /model <name>",Rg=Math.max(0,52-Te.length);console.log(H(` ${_.vertical}`)+A(`${Te}${" ".repeat(Rg)}`)+H(_.vertical)),console.log(H(` ${_.bottomLeft}${_.horizontal.repeat(52)}${_.bottomRight}`)),console.log("")}else{console.log(`
|
|
317
|
+
Current model: ${e.model}
|
|
318
|
+
`);for(let xe of D){let tt=xe.id===e.model?" <-- current":"";console.log(` ${xe.name||xe.id}${tt}`)}console.log(`
|
|
319
|
+
Usage: /model <name>
|
|
320
|
+
`)}}}catch(w){i.printError(`Could not fetch models: ${w.message||w}`)}break;case"mode":["plan","fast","thinking"].includes(v)?(e.mode=v,i.printSuccess(`Mode changed to: ${v}`)):i.printError("Valid modes: plan, fast, thinking");break;case"diff":try{let w=(0,Xe.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=pd();if(w.length===0){i.printError("Nothing to undo \u2014 no checkpoints found.");break}let D=w[0];try{let C=md(D.runId);i.printSuccess(`Reverted ${C.length} file(s):`);for(let _ of C)console.log(` \u21A9 ${_}`)}catch(C){i.printError(C instanceof Error?C.message:"Undo failed")}break}case"commit":{try{(0,Xe.execSync)("git add -A",{cwd:e.workspace,stdio:"pipe"});let w=v||`mc: agent changes (${m.size} files)`,C=(0,Xe.execSync)(`git commit -m "${w.replace(/"/g,'\\"')}"`,{cwd:e.workspace,encoding:"utf8",stdio:"pipe"}).match(/\[[\w-]+\s+([a-f0-9]+)\]/),_=C?C[1]:"???";i.printSuccess(`Committed: ${_} \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 ${z.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} ${z.relative(e.workspace,w)||w}`);g.size>20&&console.log(a.dim(` ... and ${g.size-20} more`))}console.log("")}break;case"cost":{let w=cr(e.model),D=w?h/1e6*w.costInputPerM:0,C=w?b/1e6*w.costOutputPerM:0,_=w?k/1e6*w.costOutputPerM:0,R=D+C+_;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 ($${D.toFixed(2)})`),console.log(` Output: ${b.toLocaleString()} tokens ($${C.toFixed(2)})`),k>0&&console.log(` Thinking: ${k.toLocaleString()} tokens ($${_.toFixed(2)})`),console.log(` Total: $${R.toFixed(2)}`),e.maxCost&&e.maxCost>0){let H=Math.max(0,e.maxCost-R),A=Math.round((1-R/e.maxCost)*100);console.log(` Budget: $${e.maxCost.toFixed(2)} (${A}% remaining)`)}console.log(` Turns: ${S}`),console.log(` ${"\u2500".repeat(36)}`),console.log("");break}case"context":case"ctx":if(v){let w=z.resolve(e.workspace,v);try{let C=require("node:fs").readFileSync(w,"utf8").split(`
|
|
321
|
+
`).length;g.add(w),i.printSuccess(`Added ${v} to context (${C} lines). Mention it in your next prompt.`)}catch{i.printError(`File not found: ${v}`)}}else{let w=mr(e.model),D=Y?.getContextStats();if(console.log(""),console.log(" \u{1F4CA} Context Summary"),console.log(` ${"\u2500".repeat(40)}`),console.log(` Turns: ${S}`),console.log(` Tokens in: ${h.toLocaleString()}`),console.log(` Tokens out: ${b.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`),D){let C=D.pct,_=30,R=Math.round(C/100*_),H=_-R,A=C>=80?a.red:C>=60?a.yellow:a.green;console.log(` Context used: ${A(`${C}%`)} ${A("\u2588".repeat(R))}${a.dim("\u2591".repeat(H))}`),console.log(` Messages: ${D.messageCount}`),console.log(` Auto-compact: ${C>=85?a.yellow("will trigger"):a.green("standby")}`)}console.log(` ${"\u2500".repeat(40)}`),console.log("")}break;case"compact":{if(!Y){console.log(a.dim(" No active conversation to compact. Run a prompt first."));break}let w=v.replace(/^["']|["']$/g,"").trim(),D=Y.getContextStats();if(!w&&D.pct<50){console.log(a.dim(` Context is only ${D.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 C=Y.manualCompact(2);if(C.elided>0){let _=Y.getContextStats(),R=Math.round(C.savedTokens/1e3);i.printSuccess(`Compacted: ${C.elided} tool result${C.elided===1?"":"s"} summarized (${R}K tokens saved, ${D.pct}% \u2192 ${_.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 C=Y.manualCompact();if(C.elided>0){let _=Y.getContextStats(),R=Math.round(C.savedTokens/1e3);i.printSuccess(`Compacted: ${C.elided} tool result${C.elided===1?"":"s"} summarized (${R}K tokens saved, ${D.pct}% \u2192 ${_.pct}%)`)}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}break}case"doctor":await rn();break;case"permissions":{let w=v.split(" ")[0]?.toLowerCase()||"show",D=z.join(e.workspace,".monkeyscode","permissions.json");if(w==="edit"){let C=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!I.existsSync(D))console.log(a.dim(" No permissions.json. Run /init to generate one."));else try{(0,Xe.execSync)(`${C} "${D}"`,{stdio:"inherit"}),i.printSuccess("Permissions saved.")}catch{i.printError(`Failed to open editor: ${C}`)}}else if(w==="reset")I.existsSync(D)?(I.unlinkSync(D),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(", ")}`),I.existsSync(D))try{let C=JSON.parse(I.readFileSync(D,"utf8"));console.log(""),console.log(a.dim(` \u{1F4C4} ${z.relative(e.workspace,D)}`)),C.allow?.length&&console.log(` Allow rules: ${C.allow.length} rules`),C.deny?.length&&console.log(` Deny rules: ${C.deny.length} rules`),C.cost?.max_per_run_usd&&console.log(` Cost limit: $${C.cost.max_per_run_usd}`),C.sandbox?.enabled&&console.log(` Sandbox paths: ${C.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=v.trim()||"Continue working on the current task in the background";await Do.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 D of w.slice(0,10)){let C=a.hex("#6B8DD6")(D.id.substring(0,8)),_=ew(D.lastActive);console.log(` ${C} ${D.preview.substring(0,50).padEnd(52)} ${a.dim(_)}`)}console.log("")}break}case"resume":case"continue":{let w=v.trim(),D=w?u.load(w):u.loadLatest(e.workspace);if(!D)i.printError(w?`Session "${w}" not found.`:"No sessions to resume.");else{d=D,S=D.turnCount;for(let C of D.stats.filesChanged)m.add(C);i.printSuccess(`Resumed session ${D.id.substring(0,8)} (${D.turnCount} turns, ${D.stats.tokensUsed.toLocaleString()} tokens)`)}break}case"goal":{let w=v.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(fe){let D=fe.getProgress();console.log(a.dim(` Goal: iteration ${D.iteration}/${D.maxIterations}, ${D.totalTokens.toLocaleString()} tokens, $${D.totalCost.toFixed(4)}`))}else console.log(a.dim(" No active goal."));break}if(w==="cancel"){fe?(fe.cancel(),i.printSuccess("Goal cancelled.")):console.log(a.dim(" No active goal."));break}fe=new br({goal:w,workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),await fe.run(),fe=null;break}case"subtask":case"sub":{let w=v.trim();if(w==="status")Do.printStatus();else if(w.startsWith("cancel "))Do.cancel(w.slice(7).trim());else if(w){let D=w.replace(/^["']|["']$/g,"");await Do.spawn(D)}else i.printError('Usage: /subtask "task description" | /subtask status | /subtask cancel <id>');break}case"delegate":case"del":{let w=v.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 D=w.match(/"([^"]+)"/g)?.map(R=>R.replace(/"/g,""))||[w];if(D.length<1){i.printError("Provide at least one task in quotes.");break}console.log(a.cyan(` \u26A1 Delegating ${D.length} task(s) to parallel agents...`));for(let R=0;R<D.length;R++)console.log(a.dim(` ${R+1}. "${D[R]}"`));console.log("");let C=new Sr({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id});C.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 _=D.map((R,H)=>({id:`delegate-${H+1}`,prompt:R,workspace:e.workspace,parentId:"repl",dependencies:[],status:"pending"}));try{let R=await C.fanOut(_),H=await C.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(A=>A.status==="complete").length))}`),console.log(` Failed: ${a.red(String(R.filter(A=>A.status==="failed").length))}`),console.log(` Files: ${H.mergedFiles.length}`),console.log(` Conflicts: ${H.conflicts.length}`),console.log(` Tokens: ${H.totalTokens.toLocaleString()}`),console.log(` Cost: $${H.totalCost.toFixed(4)}`),console.log(` Duration: ${(H.totalDurationMs/1e3).toFixed(1)}s`),console.log(` ${"\u2500".repeat(50)}`),console.log("")}catch(R){i.printError(`Delegation failed: ${R.message}`)}break}case"search":v?await Tt(`Search the web for: ${v.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":v?await Tt(`Look up documentation for: ${v}`):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",D="git diff";v==="staged"?(D="git diff --cached",w="staged changes"):v&&(D=`git diff -- ${v}`,w=`changes in ${v}`);try{let C=(0,Xe.execSync)(D,{cwd:e.workspace,encoding:"utf8"});C.trim()?(console.log(a.bold(`
|
|
322
|
+
\u{1F50D} Reviewing ${w}...`)),await Tt(`Review the following code changes for bugs, security issues, and code quality. Provide severity ratings (HIGH/MEDIUM/LOW) for each finding.
|
|
319
323
|
|
|
320
324
|
\`\`\`diff
|
|
321
|
-
${
|
|
322
|
-
\`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let w=
|
|
323
|
-
`),"utf8"),
|
|
324
|
-
`,"utf8"),
|
|
325
|
-
`),"utf8"),
|
|
326
|
-
`),"utf8");try{
|
|
327
|
-
`;
|
|
328
|
-
- `+
|
|
329
|
-
`,"utf8"),i.printSuccess(`Added rule: ${
|
|
330
|
-
`))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(
|
|
331
|
-
`),"utf8"),i.printSuccess(`Created skill: ${
|
|
332
|
-
`),"utf8");try{
|
|
325
|
+
${C}
|
|
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=z.join(e.workspace,".monkeyscode"),D=z.join(w,"rules.md"),C=z.join(w,"permissions.json"),_=z.join(w,"skills"),R=z.join(w,"hooks");I.mkdirSync(w,{recursive:!0});let H=[];if(!I.existsSync(D)){let A=["# Project Conventions",""],et=z.join(e.workspace,"package.json"),xe=z.join(e.workspace,"Cargo.toml"),tt=z.join(e.workspace,"pyproject.toml"),Es=z.join(e.workspace,"tsconfig.json"),Fs=z.join(e.workspace,"go.mod");if(I.existsSync(et))try{let Te=JSON.parse(I.readFileSync(et,"utf8"));A.push(`## Language: ${Te.type==="module"?"TypeScript/ESM":"JavaScript/CJS"}`),Te.scripts?.test&&A.push(`- Test command: \`${Te.scripts.test}\``),Te.scripts?.lint&&A.push(`- Lint command: \`${Te.scripts.lint}\``),Te.scripts?.build&&A.push(`- Build command: \`${Te.scripts.build}\``),Te.dependencies?.react&&A.push("- Framework: React"),Te.dependencies?.next&&A.push("- Framework: Next.js"),Te.dependencies?.express&&A.push("- Server: Express"),A.push("")}catch{}I.existsSync(Es)&&(A.push("## TypeScript"),A.push("- Use strict TypeScript with explicit types"),A.push("- Prefer `interface` over `type` for object shapes"),A.push("")),I.existsSync(xe)&&(A.push("## Language: Rust"),A.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),A.push("")),I.existsSync(tt)&&(A.push("## Language: Python"),A.push("- Follow PEP 8 conventions"),A.push("")),I.existsSync(Fs)&&(A.push("## Language: Go"),A.push("- Follow Go conventions (gofmt, error wrapping)"),A.push("")),A.push("## Style"),A.push("- Keep functions small and focused"),A.push("- Write clear error messages"),A.push("- Add JSDoc/docstrings for public APIs"),A.push(""),A.push("## Testing"),A.push("- Write tests for all new functionality"),A.push("- Use descriptive test names"),A.push(""),I.writeFileSync(D,A.join(`
|
|
327
|
+
`),"utf8"),H.push("rules.md")}if(!I.existsSync(C)){let A="",et=z.join(e.workspace,"package.json");if(I.existsSync(et))try{JSON.parse(I.readFileSync(et,"utf8")).scripts?.test&&(A="npm test")}catch{}!A&&I.existsSync(z.join(e.workspace,"Cargo.toml"))&&(A="cargo test"),!A&&I.existsSync(z.join(e.workspace,"go.mod"))&&(A="go test ./..."),!A&&I.existsSync(z.join(e.workspace,"pyproject.toml"))&&(A="pytest");let xe={mode:"default",allow:["Bash(git status*)","Bash(git diff*)","Bash(git log*)"],deny:["Bash(rm -rf /)","Bash(sudo *)","/Bash\\(curl.*\\|.*sh\\)/"],smartApprove:A?[`Bash(${A}*)`]:[],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}};I.writeFileSync(C,JSON.stringify(xe,null,2)+`
|
|
328
|
+
`,"utf8"),H.push("permissions.json")}if(I.existsSync(_)||(I.mkdirSync(_,{recursive:!0}),I.writeFileSync(z.join(_,"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(`
|
|
329
|
+
`),"utf8"),H.push("skills/")),!I.existsSync(R)){I.mkdirSync(R,{recursive:!0});let A=z.join(R,"pre-write-lint.sh.example");I.writeFileSync(A,["#!/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(`
|
|
330
|
+
`),"utf8");try{I.chmodSync(A,493)}catch{}H.push("hooks/")}H.length>0?(i.printSuccess(`Initialized .monkeyscode/ with: ${H.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=z.join(e.workspace,".monkeyscode","rules.md"),D=v.split(" ")[0]?.toLowerCase(),C=v.slice(D?.length||0).trim();if(D==="add"&&C){let _=C.replace(/^["']|["']$/g,"");I.mkdirSync(z.dirname(w),{recursive:!0});let R=I.existsSync(w)?I.readFileSync(w,"utf8"):`# Project Conventions
|
|
331
|
+
`;I.writeFileSync(w,R.trimEnd()+`
|
|
332
|
+
- `+_+`
|
|
333
|
+
`,"utf8"),i.printSuccess(`Added rule: ${_}`)}else if(D==="show"||!D)if(I.existsSync(w)){let _=I.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 _.split(`
|
|
334
|
+
`))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(D==="edit"){let _=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!I.existsSync(w))console.log(a.dim(" No rules file. Run /init first."));else try{(0,Xe.execSync)(`${_} "${w}"`,{stdio:"inherit"}),i.printSuccess("Rules file saved.")}catch{i.printError(`Failed to open editor: ${_}`)}}else console.log(a.dim(' Usage: /memory show | /memory add "rule" | /memory edit'));break}case"skill":case"skills":{let w=v.split(" ")[0]?.toLowerCase(),D=v.slice(w?.length||0).trim();if(w==="create"&&D){let C=D.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),_=z.join(e.workspace,".monkeyscode","skills",C),R=z.join(_,"skill.md");I.existsSync(R)?console.log(a.yellow(` Skill "${C}" already exists.`)):(I.mkdirSync(_,{recursive:!0}),I.writeFileSync(R,["---",`name: ${D}`,`description: Custom skill for ${D}`,"trigger: always","priority: 50","enabled: true","---","",`# ${D}`,"","Add your skill instructions here. These will be injected into the agent's context.",""].join(`
|
|
335
|
+
`),"utf8"),i.printSuccess(`Created skill: ${z.relative(e.workspace,R)}`),console.log(a.dim(" Edit the file to add your instructions.")))}else try{let{listAllSkills:C}=await Promise.resolve().then(()=>(dr(),Pa)),_=C(e.workspace);if(_.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 _){let H=R.enabled?a.green("\u25CF"):a.dim("\u25CB"),A=R.source==="project"?a.cyan("proj"):a.dim("glob");console.log(` ${H} ${a.bold(R.name.padEnd(20))} ${A} P:${R.priority} ${a.dim(R.description.slice(0,40))}`)}console.log("")}}catch(C){i.printError(`Failed to list skills: ${C instanceof Error?C.message:C}`)}break}case"hooks":case"hook":{let w=v.split(" ")[0]?.toLowerCase(),D=v.slice(w?.length||0).trim();if(w==="create"&&D){let C=D.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),_=z.join(e.workspace,".monkeyscode","hooks",`${C}.sh`);if(I.existsSync(_))console.log(a.yellow(` Hook "${C}" already exists.`));else{I.mkdirSync(z.dirname(_),{recursive:!0}),I.writeFileSync(_,["#!/bin/bash",`# Hook: ${D}`,"#","# 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(`
|
|
336
|
+
`),"utf8");try{I.chmodSync(_,493)}catch{}i.printSuccess(`Created hook: ${z.relative(e.workspace,_)}`)}}else{let C=c.getHooks();if(C.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 _ of C){let R=a.cyan(_.event||"PreToolUse"),H=a.bold(_.name||_.path||"hook");console.log(` ${R.padEnd(20)} ${H}`)}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(()=>(an(),Sc)),D=e.prompt||"(continue session)",C=Y?.getConversationHistory?.()||[];await w({prompt:D.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:C.length>0?C:void 0})}catch(w){console.error(a.red(` \u274C Cloud submission failed: ${w instanceof Error?w.message:w}`))}break}case"message":{let w=v.match(/^(\S+)\s+"?([^"]+)"?$/);if(!w){console.log(a.yellow(' Usage: /message <session-id> "your message"'));break}try{let{MessageBroker:D}=await Promise.resolve().then(()=>(pn(),Gr)),C=(await Promise.resolve().then(()=>(Z(),ve))).loadSettings(),_=(await Promise.resolve().then(()=>(te(),ge))).loadAuth(),H=await new D(C.platformUrl,_?.access_token||"",p).sendMessage(w[1],w[2]);H.success?console.log(a.green(` \u{1F4E8} Message sent to ${w[1]}`)):console.error(a.red(` \u274C Send failed: ${H.error}`))}catch(D){console.error(a.red(` \u274C Messaging error: ${D instanceof Error?D.message:D}`))}break}case"broadcast":{let w=v.replace(/^"/,"").replace(/"$/,"").trim();if(!w){console.log(a.yellow(' Usage: /broadcast "your message to all sessions"'));break}try{let{MessageBroker:D}=await Promise.resolve().then(()=>(pn(),Gr)),C=(await Promise.resolve().then(()=>(Z(),ve))).loadSettings(),_=(await Promise.resolve().then(()=>(te(),ge))).loadAuth(),H=await new D(C.platformUrl,_?.access_token||"",p).broadcast(w);H.success?console.log(a.green(" \u{1F4E2} Broadcast sent to all active sessions")):console.error(a.red(` \u274C Broadcast failed: ${H.error}`))}catch(D){console.error(a.red(` \u274C Messaging error: ${D instanceof Error?D.message:D}`))}break}case"bug":case"feedback":{let w=process.platform,D=process.version,C=Y?.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: ${D}`),console.log(` Model: ${e.model}`),console.log(` Mode: ${e.mode}`),console.log(` Turns: ${S}`),console.log(` Tokens: ${(h+b).toLocaleString()}`),C&&console.log(` Context: ${C.pct}% (${C.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":{Be=!Be,Be?(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.")),j.setPrompt(n.emoji?`
|
|
333
337
|
\u{1F435} [I]> `:`
|
|
334
|
-
[I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),
|
|
338
|
+
[I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),j.setPrompt(n.emoji?`
|
|
335
339
|
\u{1F435} > `:`
|
|
336
|
-
> `));break}case"help":case"h":case"?":
|
|
337
|
-
Cancelling current run...`),
|
|
338
|
-
`),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=
|
|
339
|
-
`);let
|
|
340
|
-
[headless] Timeout after ${
|
|
341
|
-
`)},
|
|
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: /${X}. Type /help for available commands.`)}j.prompt();return}await Tt(B),await _s(),j.prompt()});let On=l(()=>{let M=Date.now()-f,B=Math.floor(M/6e4),X=Math.floor(M%6e4/1e3),T=B>0?`${B}m ${X}s`:`${X}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: ${T}`)),console.log(a.dim(` Turns: ${S}`)),console.log(a.dim(` Tokens: ${(h+b).toLocaleString()}`)),m.size>0){console.log(a.dim(` Files changed: ${m.size}`));for(let v of m)console.log(a.dim(` \u270F\uFE0F ${z.relative(e.workspace,v)||v}`))}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");j.on("close",()=>{c.fire("Stop",{workspace:e.workspace,data:{}}),On(),process.exit(0)}),j.on("SIGINT",()=>{Y?(console.log(`
|
|
341
|
+
Cancelling current run...`),Y.cancel()):(c.fire("Stop",{workspace:e.workspace,data:{}}),j.close())}),await new Promise(M=>{j.on("close",M)})}l(pm,"runInteractive");async function Kb(s,e,t,o){s||(process.stderr.write(`Error: No prompt provided. Use -p "your prompt" or pipe via stdin.
|
|
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=J(),g=Date.now(),h=`headless-${Date.now().toString(36)}`,b="",k=!1,S=!1,x=e.output,E=Bp(x,{workspace:e.workspace}),$=Up(e.model,h),F=[],j=[],ae=0,Y=0,fe=0,Be=0,ht=process.env.CI==="true"||process.env.CI==="1"||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI;ht&&!e.sandbox&&e.permissionMode!=="bypassPermissions"&&process.stderr.write(`[headless] CI environment detected \u2014 sandbox=auto
|
|
343
|
+
`);let Do=new To(e.workspace,{enabled:!0,timeoutMs:1e4});await Do.fire("HeadlessStart",{workspace:e.workspace,data:{prompt:s,model:e.model}});let Ft=e.timeout||3e5,_s=setTimeout(()=>{S=!0,process.stderr.write(`
|
|
344
|
+
[headless] Timeout after ${Ft}ms. Stopping gracefully.
|
|
345
|
+
`)},Ft),Tt=l(()=>{k=!0,process.stderr.write(`
|
|
342
346
|
[headless] SIGINT received. Stopping.
|
|
343
|
-
`)},"sigintHandler");process.on("SIGINT"
|
|
344
|
-
`).filter(Boolean);for(let
|
|
345
|
-
`)}break;case"tool_call_start":if(ae=Date.now(),e.mode==="plan"&&["file_edit","file_write","file_create","bash","file_delete"].includes(
|
|
346
|
-
`);break}if(process.stderr.write(`[tool] ${
|
|
347
|
-
`),["file_edit","file_write","file_create"].includes(
|
|
348
|
-
`)}break;case"tool_call_result":if(
|
|
349
|
-
`)}break;case"ask_user":process.stderr.write(`[headless] Input prompt skipped (headless mode): ${
|
|
350
|
-
`),B.resolveUserInput("");break;case"run_complete":
|
|
351
|
-
`);break;case"run_error":if(process.stderr.write(`[headless] Error: ${
|
|
352
|
-
`),x==="jsonl"&&
|
|
353
|
-
`)}break}});let
|
|
354
|
-
`)[0]?.substring(0,200)||"Task completed.")
|
|
355
|
-
`)
|
|
356
|
-
`);else{let
|
|
357
|
-
`)}await wo.fire("HeadlessStop",{workspace:e.workspace,data:{success:C.success,exitCode:Y,duration:C.duration,filesChanged:I.length}}),process.removeListener("SIGINT",$t),process.exit(Y)}l(Mb,"runHeadless");async function Ib(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(sn(),kc));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(Ib,"runBackground");async function jb(){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(jb,"readStdin");function Nb(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(Nb,"printRunSummary");function Lb(){let s=j(),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(Lb,"printSlashHelp");function Bb(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(Bb,"formatAge");oe();var Ur=y(require("node:readline"),1);U();Ce();var Rc=class{static{l(this,"AgentsDashboard")}daemon;caps;icons;box;agents=[];selectedIndex=0;running=!1;refreshInterval=null;constructor(e){this.daemon=e,this.caps=j(),this.icons=W(this.caps),this.box=Ve(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(Ur.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(`
|
|
347
|
+
`)},"sigintHandler");process.on("SIGINT",Tt);let On=await import("node:crypto"),M=new Map;try{let T=(0,Xe.execSync)("git ls-files -m",{cwd:e.workspace,encoding:"utf8"}).trim().split(`
|
|
348
|
+
`).filter(Boolean);for(let v of T)try{let w=I.readFileSync(z.join(e.workspace,v));M.set(v,On.createHash("sha256").update(w).digest("hex"))}catch{}}catch{}let B=new Se({platformUrl:m.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:fm(e.mode),maxTurns:m.maxTurns,sandboxed:e.sandbox||ht,webEnabled:m.webEnabled&&!e.offline,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});B.on("event",T=>{switch(T.type){case"streaming_chunk":if(b+=T.content,x==="stream"&&process.stdout.write(T.content),x==="jsonl"&&E.formatEvent){let v=E.formatEvent({type:"chunk",timestamp:Date.now(),data:{content:T.content}});v&&process.stdout.write(v+`
|
|
349
|
+
`)}break;case"tool_call_start":if(ae=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
|
+
`);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&&j.push({path:String(T.args.file_path),action:T.name==="file_create"?"created":"modified",linesAdded:0,linesRemoved:0}),x==="jsonl"&&E.formatEvent){let v=E.formatEvent({type:"tool_start",timestamp:Date.now(),data:{tool:T.name,args:T.args}});v&&process.stdout.write(v+`
|
|
352
|
+
`)}break;case"tool_call_result":if(F.push({tool:T.name,args:{},duration:Date.now()-ae,result:typeof T.result=="string"?T.result.substring(0,200):void 0}),x==="jsonl"&&E.formatEvent){let v=E.formatEvent({type:"tool_result",timestamp:Date.now(),data:{tool:T.name,duration:Date.now()-ae,result:typeof T.result=="string"?T.result.substring(0,200):""}});v&&process.stdout.write(v+`
|
|
353
|
+
`)}break;case"ask_user":process.stderr.write(`[headless] Input prompt skipped (headless mode): ${T.question}
|
|
354
|
+
`),B.resolveUserInput("");break;case"run_complete":Y+=T.summary.tokensIn,fe+=T.summary.tokensOut,Be+=T.summary.tokensThinking||0;for(let v of T.summary.filesModified)j.find(D=>D.path===v)||j.push({path:v,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
|
+
`);break;case"run_error":if(process.stderr.write(`[headless] Error: ${T.message||"unknown"}
|
|
356
|
+
`),x==="jsonl"&&E.formatEvent){let v=E.formatEvent({type:"error",timestamp:Date.now(),data:{message:T.message||"unknown"}});v&&process.stdout.write(v+`
|
|
357
|
+
`)}break}});let X=0;try{let T=B.run(s),v=new Promise(C=>{let _=setInterval(()=>{(S||k)&&(clearInterval(_),C(null))},500)}),w=await Promise.race([T,v]);clearTimeout(_s);let D=Date.now()-g;if(S?(X=124,$.status="timeout",$.summary=`Timeout after ${(Ft/1e3).toFixed(0)}s. Partial result below.`):k?(X=130,$.status="interrupted",$.summary="Interrupted by SIGINT."):w&&($.status="completed",$.success=!0,$.summary=b.split(`
|
|
358
|
+
`)[0]?.substring(0,200)||"Task completed."),$.filesChanged=j,$.toolCalls=F,$.tokens={input:Y,output:fe,thinking:Be,total:Y+fe+Be},$.cost=Js(e.model,Y,fe,Be),$.duration=D,$.success&&M.size>0){let C=!0;for(let[_,R]of M)try{let H=I.readFileSync(z.join(e.workspace,_));if(On.createHash("sha256").update(H).digest("hex")!==R){C=!1;break}}catch{C=!1;break}C&&j.length===0&&(process.stderr.write(`[headless] Idempotency: no files changed \u2014 edits already applied.
|
|
359
|
+
`),$.summary="No changes needed \u2014 edits already applied.")}}catch(T){clearTimeout(_s);let v=T instanceof Error?T.message:String(T);v.includes("401")||v.includes("auth")||v.includes("token")?X=3:v.includes("ECONNREFUSED")||v.includes("ENOTFOUND")||v.includes("fetch failed")?X=5:X=1,$.status="failed",$.error=v,$.summary=`Error: ${v.substring(0,200)}`,$.duration=Date.now()-g,$.tokens={input:Y,output:fe,thinking:Be,total:Y+fe+Be},$.cost=Js(e.model,Y,fe,Be),$.filesChanged=j,$.toolCalls=F}if(x==="text"||x==="stream")x==="text"&&process.stdout.write(b+`
|
|
360
|
+
`);else{let T=E.formatResult($);process.stdout.write(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(`
|
|
358
362
|
Focusing on ${t.id}... (press Esc to return)
|
|
359
|
-
`);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=
|
|
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=qr.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 uo({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 zt=[{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"}],mn=[{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 hm(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(hm,"generateCompletions");function ym(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(`
|
|
360
364
|
`);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(`
|
|
361
365
|
`);case"fish":return["monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish"].join(`
|
|
362
366
|
`);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(`
|
|
363
|
-
`)}}l(
|
|
367
|
+
`)}}l(ym,"getCompletionInstallInstructions");function tw(){let s=zt.map(n=>n.name).join(" "),e=mn.map(n=>n.long).join(" "),t=mn.filter(n=>n.short).map(n=>n.short).join(" "),o=zt.filter(n=>n.subcommands).map(n=>{let r=n.subcommands.map(i=>i.name).join(" ");return` ${n.name}) COMPREPLY=( $(compgen -W "${r}" -- "$cur") ) ;;`}).join(`
|
|
364
368
|
`);return`#!/bin/bash
|
|
365
369
|
# monkeyscode bash completion \u2014 generated by monkeyscode completions bash
|
|
366
370
|
# Install: eval "$(monkeyscode completions bash)"
|
|
@@ -387,9 +391,9 @@ ${o}
|
|
|
387
391
|
complete -F _monkeyscode_completions monkeyscode
|
|
388
392
|
complete -F _monkeyscode_completions mc
|
|
389
393
|
complete -F _monkeyscode_completions mcode
|
|
390
|
-
`}l(
|
|
391
|
-
`),e=
|
|
392
|
-
`),t=
|
|
394
|
+
`}l(tw,"generateBashCompletions");function ow(){let s=zt.map(o=>`'${o.name}:${o.description.replace(/'/g,"''")}'`).join(`
|
|
395
|
+
`),e=mn.map(o=>{let n=o.takesValue?`=${o.description}`:"";return`'${o.short?`{${o.short},${o.long}}`:o.long}[${o.description.replace(/'/g,"''")}]${n}'`}).join(`
|
|
396
|
+
`),t=zt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>`'${r.name}:${r.description.replace(/'/g,"''")}'`).join(`
|
|
393
397
|
`);return`
|
|
394
398
|
__monkeyscode_${o.name}_commands() {
|
|
395
399
|
local commands
|
|
@@ -419,7 +423,7 @@ _monkeyscode() {
|
|
|
419
423
|
;;
|
|
420
424
|
args)
|
|
421
425
|
case "\${words[1]}" in
|
|
422
|
-
${
|
|
426
|
+
${zt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_${o.name}_commands ;;`).join(`
|
|
423
427
|
`)}
|
|
424
428
|
esac
|
|
425
429
|
;;
|
|
@@ -428,11 +432,11 @@ ${Gt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_$
|
|
|
428
432
|
${t}
|
|
429
433
|
|
|
430
434
|
compdef _monkeyscode monkeyscode mc mcode
|
|
431
|
-
`}l(
|
|
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 zt)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 zt)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 mn){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(`
|
|
432
436
|
`)+`
|
|
433
|
-
`}l(
|
|
434
|
-
`),e=
|
|
435
|
-
`),t=
|
|
437
|
+
`}l(sw,"generateFishCompletions");function nw(){let s=zt.map(o=>` [CompletionResult]::new('${o.name}', '${o.name}', [CompletionResultType]::ParameterValue, '${o.description}')`).join(`
|
|
438
|
+
`),e=mn.map(o=>` [CompletionResult]::new('${o.long}', '${o.long}', [CompletionResultType]::ParameterName, '${o.description}')`).join(`
|
|
439
|
+
`),t=zt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>` [CompletionResult]::new('${r.name}', '${r.name}', [CompletionResultType]::ParameterValue, '${r.description}')`).join(`
|
|
436
440
|
`);return` '${o.name}' {
|
|
437
441
|
${n}
|
|
438
442
|
}`}).join(`
|
|
@@ -458,28 +462,28 @@ ${t}
|
|
|
458
462
|
}
|
|
459
463
|
}
|
|
460
464
|
}
|
|
461
|
-
`}l(
|
|
465
|
+
`}l(nw,"generatePowerShellCompletions");U();ar();function Ic(s){let e=Fo(s),t=Ku(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");U();var bm=require("node:events"),wm=require("node:child_process");var Vr=class extends bm.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,wm.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(`
|
|
462
466
|
`);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(`
|
|
463
467
|
`)||"(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(`
|
|
464
468
|
`):""}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+`
|
|
465
469
|
`):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(`
|
|
466
|
-
`);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 dn=[{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}],pn=class{static{l(this,"MCPRegistry")}getAll(){return[...dn]}getByCategory(e){return dn.filter(t=>t.category===e)}search(e){let t=e.toLowerCase();return dn.filter(o=>o.name.toLowerCase().includes(t)||o.description.toLowerCase().includes(t)||o.tags.some(n=>n.includes(t)))}get(e){return dn.find(t=>t.id===e)}getCategories(){let e=new Map;for(let o of dn)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 pm(s){let e=tn(s),t=Rp(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(pm,"mcpListCommand");function mm(s,e,t,o){if(!t){let r=new pn,i=r.get(e);if(i){if(ac(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(`
|
|
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(`
|
|
467
471
|
\u26A0 Required environment variables:`));for(let u of i.install.envVars)console.log(` ${a.cyan(u)}`)}console.log("");return}console.log(a.red(`
|
|
468
472
|
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(`
|
|
469
|
-
Did you mean:`));for(let u of c.slice(0,5))console.log(` ${a.cyan(u.id)} \u2014 ${u.description}`)}console.log("");return}
|
|
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(Dm,"mcpAddCommand");function vm(s,e){let t=Op(s,e);console.log(""),console.log(t?a.green(` \u2713 Removed MCP server: ${e}`):a.red(` \u2717 Server not found: ${e}`)),console.log("")}l(vm,"mcpRemoveCommand");async function Sm(s,e){let t=nn(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 Vr;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(Sm,"mcpTestCommand");function xm(s){let e=new gn,t=s?e.search(s):e.getAll();if(t.length===0){console.log(a.dim(`
|
|
470
474
|
No servers matching "${s}"
|
|
471
475
|
`));return}if(s){console.log(a.bold(`
|
|
472
476
|
\u{1F50D} Search: "${s}" (${t.length} results)
|
|
473
477
|
`));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(`
|
|
474
478
|
\u{1F50C} MCP Server Registry
|
|
475
479
|
`));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>")}
|
|
476
|
-
`))}}l(hm,"mcpBrowseCommand");X();var Xe=y(require("node:fs"),1),fn=y(require("node:path"),1);X();U();var mn={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 ym=["plan","fast","thinking"],bm=["dark","light","auto"],wm=["text","json","stream"],km={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=>ym.includes(s)?null:`must be one of: ${ym.join(", ")}`,"defaultMode"),theme:l(s=>bm.includes(s)?null:`must be one of: ${bm.join(", ")}`,"theme"),outputFormat:l(s=>wm.includes(s)?null:`must be one of: ${wm.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")},Mc=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:mn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(mn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=km[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,Xe.mkdirSync(fn.dirname(r),{recursive:!0}),Xe.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Xe.existsSync(o)&&(n=JSON.parse(Xe.readFileSync(o,"utf8")))}catch{}delete n[e],Xe.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...mn};for(let t of Object.keys(mn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=T();return fn.join(e.config,"config.json")}getProjectConfigPath(){return fn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Xe.existsSync(e)){let o=JSON.parse(Xe.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=km[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(mn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Xe.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 Dm(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(Dm,"printConfigList");var Oc=null;function Mo(s){return(!Oc||s)&&(Oc=new Mc(s)),Oc}l(Mo,"getConfigSystem");ir();U();Ce();oe();var qb=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function vm(){let s=j(),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 Ae();if(d){let p=await fetch(`${qb}/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=Ic(n.tokensIn),u=Ic(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Ic(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(vm,"usageCommand");function Ic(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Ic,"formatTokenCount");var lt=y(require("node:fs"),1),Tm=y(require("node:path"),1),hs=require("node:child_process");U();var gs=y(require("node:fs"),1),Hr=y(require("node:path"),1);X();var Vb="https://monkeyscode.com/api/latest-version",zb="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",Jb=4*60*60*1e3;function Cm(){let s=T();return Hr.join(s.config,"update-check")}l(Cm,"getCachePath");function Kb(){try{let s=gs.readFileSync(Cm(),"utf8");return JSON.parse(s)}catch{return null}}l(Kb,"readCache");function jc(s){try{let e=Cm();gs.mkdirSync(Hr.dirname(e),{recursive:!0}),gs.writeFileSync(e,JSON.stringify(s))}catch{}}l(jc,"writeCache");function Sm(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(Sm,"isNewerVersion");function Yb(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(Yb,"getAssetKey");async function Gr(s,e=!1){if(!e){let t=Kb();if(t&&Date.now()-t.lastCheck<Jb)return t.latestVersion&&Sm(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await xm(Vb);if(t||(t=await xm(zb)),!t)return jc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=Yb(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return jc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Sm(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 jc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Gr,"checkForUpdate");async function xm(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(xm,"fetchManifest");function $m(s){Gr(s).then(e=>{e&&(globalThis.__mcUpdateAvailable=e)}).catch(()=>{})}l($m,"checkForUpdateBackground");function _m(){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(_m,"printUpdateNotice");function Nc(){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(Nc,"detectInstallMethod");async function Rm(s){let t=(await Promise.resolve().then(()=>(Fm(),Em)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.5";if(s.rollback){await aw(t);return}if(s.check){await Zb(t);return}await ew(t,s.version)}l(Rm,"updateCommand");async function Zb(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Gr(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(Zb,"checkOnly");async function ew(s,e){let t=Nc();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 tw(e);break;case"homebrew":await ow();break;case"winget":await sw();break;case"chocolatey":await nw();break;case"scoop":await rw();break;case"binary":await iw(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(ew,"performUpdate");async function tw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,hs.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(tw,"updateViaNpm");async function ow(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,hs.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(ow,"updateViaHomebrew");async function sw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,hs.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(sw,"updateViaWinget");async function nw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,hs.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(nw,"updateViaChocolatey");async function rw(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,hs.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(rw,"updateViaScoop");async function iw(s,e){let t=await Gr(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{lt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${Tm.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{lt.writeFileSync(n,c),lt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{lt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(iw,"updateViaBinaryDownload");async function aw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Nc()==="binary"){let t=process.execPath+".backup";if(!lt.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{lt.copyFileSync(t,process.execPath),lt.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(aw,"rollback");U();var ys=y(require("node:fs"),1),Vr=y(require("node:path"),1),Om=y(require("node:crypto"),1);X();var qt=!0,Lc="",Qe=[],Am=!1,cw="https://monkeyscode.com/api/telemetry",qr=50,lw=6e4;function Mm(){let s=T();return Vr.join(s.config,"telemetry.json")}l(Mm,"getConfigPath");function Bc(){try{let s=ys.readFileSync(Mm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:uw()};return Uc(s),s}}l(Bc,"loadConfig");function Uc(s){try{let e=Mm();ys.mkdirSync(Vr.dirname(e),{recursive:!0}),ys.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(Uc,"saveConfig");function uw(){return Om.randomUUID()}l(uw,"generateClientId");function Im(){if(Am)return;if(Am=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){qt=!1;return}let s=Bc();qt=s.enabled,Lc=s.clientId,qt&&(setInterval(()=>Pm(),lw).unref(),process.on("beforeExit",()=>Pm()))}l(Im,"initTelemetry");function jm(){return qt}l(jm,"isTelemetryEnabled");function Nm(){qt=!0;let s=Bc();s.enabled=!0,Uc(s)}l(Nm,"enableTelemetry");function Lm(){qt=!1,Qe=[];let s=Bc();s.enabled=!1,Uc(s)}l(Lm,"disableTelemetry");function Bm(s,e={}){qt&&(Qe.push({name:s,properties:e,timestamp:new Date().toISOString()}),Qe.length>qr&&(Qe=Qe.slice(-qr)))}l(Bm,"trackEvent");async function Pm(){if(!qt||Qe.length===0)return;let s=[...Qe];Qe=[];let e=xe(),o={clientId:Lc,cliVersion:"0.1.5",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(cw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{Qe.unshift(...s),Qe.length>qr&&(Qe=Qe.slice(-qr))}}l(Pm,"flushEvents");function Um(){let s=xe();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.5",` \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: ${qt?"ENABLED":"DISABLED"}`,`Client ID: ${Lc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
477
|
-
`)}l(
|
|
478
|
-
`)[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(""),
|
|
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(Km,"getCollectedDataSummary");async function Ym(s){switch(s){case"enable":Vm(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":zm(),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(Km()),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)")):qm()?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(Ym,"telemetryCommand");var St=y(require("node:fs"),1),bn=y(require("node:path"),1);U();Q();async function Xm(s,e){let t=$e(),o="0.1.6";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(Xm,"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=P(),t=bn.join(e.config,"bug-reports");St.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=bn.join(t,`${o}.json`);return St.writeFileSync(n,JSON.stringify(s,null,2)),n}l(Cw,"saveReportLocally");function _w(){try{let s=P(),e=bn.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(bn.join(e,t[0]),"utf8")}catch{return null}}l(_w,"getLatestCrashLog");var Lo=y(require("node:fs"),1),qc=y(require("node:path"),1);U();Q();Ce();function Qm(){let s=P(),e=qc.join(s.config,"config.json");return!Lo.existsSync(e)}l(Qm,"isFirstRun");function Ew(){let e=P().config,t=qc.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 Zm(){let s=O(),e=$e();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(`
|
|
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(Zm,"runOnboarding");var fo=y(require("node:fs"),1),Xr=y(require("node:path"),1);Q();var ef=[];function of(){process.on("uncaughtException",s=>{tf(s,"uncaughtException"),console.error(`
|
|
479
483
|
\u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${s.message}
|
|
480
|
-
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));
|
|
484
|
+
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));tf(e,"unhandledRejection")})}l(of,"installCrashHandler");function Fw(){let s=P();return Xr.join(s.config,"crashes")}l(Fw,"getCrashDir");function tf(s,e){try{let t=Fw();fo.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Xr.join(t,`${o}.log`),r=$e(),c=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 0.1.6",`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",ef.length>0?ef.map((u,d)=>` ${d+1}. ${u}`).join(`
|
|
481
485
|
`):" (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(`
|
|
482
|
-
`);
|
|
486
|
+
`);fo.writeFileSync(n,c),Tw(t,20)}catch{}}l(tf,"writeCrashReport");function Tw(s,e){try{let t=fo.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)fo.unlinkSync(Xr.join(s,t[o]))}catch{}}l(Tw,"pruneOldReports");var Pe=y(require("node:fs"),1),Yt=y(require("node:path"),1),Rw=require("node:child_process");U();Q();Ce();var Aw="MEMORY.md",sf=".monkeyscode";async function nf(s={}){let e=W(O()),t=P(),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=Yt.join(t.data,"sessions");if(!Pe.existsSync(n)){console.log(` ${e.info} No sessions found. Use ${a.cyan("mc")} to create some first.`);return}let r=Pw(o),i=Pe.readdirSync(n).filter(h=>h.endsWith(".json")).map(h=>({name:h,path:Yt.join(n,h),mtime:Pe.statSync(Yt.join(n,h)).mtimeMs})).filter(h=>h.mtime>=r).sort((h,b)=>b.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 b=JSON.parse(Pe.readFileSync(h.path,"utf8"));if(b.toolCalls){for(let k of b.toolCalls)if(k.tool==="file_edit"&&k.args?.path){let S=Yt.extname(k.args.path);if(S){let x=`Works primarily with ${S} files`;c.set(x,(c.get(x)||0)+1)}}}if(b.messages){let k=JSON.stringify(b.messages).toLowerCase();k.includes("vitest")&&Kt(c,"Uses vitest for testing"),k.includes("jest")&&Kt(c,"Uses jest for testing"),k.includes("mocha")&&Kt(c,"Uses mocha for testing"),k.includes("zod")&&Kt(c,"Uses Zod for runtime validation"),k.includes("joi")&&Kt(c,"Uses Joi for validation"),k.includes("tailwind")&&Kt(c,"Uses Tailwind CSS"),k.includes("styled-components")&&Kt(c,"Uses styled-components"),k.includes("result<")&&Kt(c,"Uses Result<T, E> pattern for error handling"),(k.includes("try/catch")||k.includes("try {"))&&Kt(c,"Uses try/catch for error handling")}}catch{}let u=Math.max(2,Math.floor(i.length*.3)),d=[];for(let[h,b]of c)b>=u&&d.push({rule:h,count:b});if(d.sort((h,b)=>b.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=Yt.join(process.cwd(),sf,Aw);Pe.mkdirSync(Yt.join(process.cwd(),sf),{recursive:!0});let f="";Pe.existsSync(p)&&(f=Pe.readFileSync(p,"utf8"));let m=new Date().toISOString().split("T")[0],g=f.trimEnd();g||(g=`# Project Memory
|
|
483
487
|
|
|
484
488
|
> Auto-generated by \`mc dream\`. Edit freely.
|
|
485
489
|
`),g+=`
|
|
@@ -487,32 +491,32 @@ ${t}
|
|
|
487
491
|
## Consolidated ${m} (${i.length} sessions)
|
|
488
492
|
|
|
489
493
|
`;for(let h of d){let b=`- ${h.rule}`;f.includes(h.rule)||(g+=b+`
|
|
490
|
-
`)}
|
|
491
|
-
`),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(
|
|
494
|
+
`)}Pe.writeFileSync(p,g.trimEnd()+`
|
|
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(nf,"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 Kt(s,e){s.set(e,(s.get(e)||0)+1)}l(Kt,"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(`
|
|
492
496
|
`)},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(`
|
|
493
497
|
`)},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(`
|
|
494
498
|
`)},"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(`
|
|
495
|
-
`)}};async function
|
|
496
|
-
`);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
|
|
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=Yt.join(process.cwd(),".monkeyscode","dreams");Pe.mkdirSync(t,{recursive:!0});let{AgentLoop:o}=await Promise.resolve().then(()=>(Je(),Zo)),{loadSettings:n}=await Promise.resolve().then(()=>(Z(),ve)),{getAccessToken:r}=await Promise.resolve().then(()=>(te(),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");U();var Fe=y(require("node:fs"),1),ft=y(require("node:path"),1),Zr=y(require("node:crypto"),1),Vc=require("node:child_process");Q();function rf(s,e){let t=s.split(`
|
|
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(rf,"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(`
|
|
497
501
|
`),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(`
|
|
498
502
|
`),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(`
|
|
499
|
-
`),startLine:o+1,endLine:s.length,type:"module"})}return e}l(
|
|
503
|
+
`),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(`
|
|
500
504
|
`),startLine:t+1,endLine:n,type:o}),t=n),o="function"):i===0&&r.startsWith("class ")&&(n>t&&n-t>=5&&(e.push({content:s.slice(t,n).join(`
|
|
501
505
|
`),startLine:t+1,endLine:n,type:o}),t=n),o="class"),n-t>=50&&(e.push({content:s.slice(t,n+1).join(`
|
|
502
506
|
`),startLine:t+1,endLine:n+1,type:o}),t=n+1,o="module")}return t<s.length&&e.push({content:s.slice(t).join(`
|
|
503
|
-
`),startLine:t+1,endLine:s.length,type:o}),e}l(
|
|
504
|
-
`),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(
|
|
505
|
-
`).filter(o=>o&&t.has(
|
|
506
|
-
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,
|
|
507
|
-
`).filter(Boolean)}catch{return this.listAllFiles()}}};var
|
|
508
|
-
`).filter(Boolean)}catch{return[]}}l(
|
|
509
|
-
`).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(
|
|
507
|
+
`),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=P();this.indexDir=ft.join(n.data,"indexes",o)}async index(){Fe.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(!Fe.existsSync(p))continue;let f=Fe.readFileSync(p,"utf8"),m=this.detectLanguage(d),g=rf(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,Vc.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(`
|
|
509
|
+
`).filter(o=>o&&t.has(ft.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,Vc.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");Fe.writeFileSync(e,JSON.stringify({chunks:this.chunks,fileShas:Object.fromEntries(this.fileShas),embeddingDim:this.embeddingDim,lastIndexed:Date.now()})),this.embeddings&&Fe.writeFileSync(t,Buffer.from(this.embeddings.buffer))}loadState(){let e=ft.join(this.indexDir,"meta.json"),t=ft.join(this.indexDir,"vectors.bin");if(Fe.existsSync(e))try{let o=JSON.parse(Fe.readFileSync(e,"utf8"));if(this.chunks=o.chunks||[],this.fileShas=new Map(Object.entries(o.fileShas||{})),this.embeddingDim=o.embeddingDim||1536,Fe.existsSync(t)){let n=Fe.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=Fe.existsSync(t)?Fe.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=y(require("node:fs"),1),Ne=y(require("node:path"),1),zc=require("node:child_process");var wn=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=Ne.join(this.workspace,e);if(!xt.existsSync(t)){this.forward.delete(e);return}let o=xt.readFileSync(t,"utf8"),n=Ne.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=Ne.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(Ne.join(this.workspace,u))){o.push(u);break}}return o}parseGoImports(e,t){let o=[],n=Ne.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=Ne.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=Ne.join(this.workspace,o);if(xt.existsSync(n))return o}return null}resolveTs(e,t){if(!t.startsWith("."))return null;let o=Ne.join(e,t),n=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let r of n){let i=o+r;if(xt.existsSync(Ne.join(this.workspace,i)))return i}if(t.endsWith(".js")){let r=Ne.join(e,t.replace(/\.js$/,".ts"));if(xt.existsSync(Ne.join(this.workspace,r)))return r}return null}listAllFiles(){try{return(0,zc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
510
|
+
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,zc.execSync)("git diff --name-only HEAD~5",{cwd:this.workspace,encoding:"utf8"}).trim().split(`
|
|
511
|
+
`).filter(Boolean)}catch{return this.listAllFiles()}}};var ks=y(require("node:fs"),1),de=y(require("node:path"),1),Jc=require("node:child_process");var kn={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 af(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&&Dn(t,i,c*kn.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;Dn(t,i[c],u*kn.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)Dn(t,u,kn.IMPORT_GRAPH,`Imported by ${de.basename(i)}`)}for(let i of r){let c=Vw(i);c&&t.has(i)&&Dn(t,c,kn.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)&&Dn(t,i,kn.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(af,"rankFiles");function Dn(s,e,t,o){let n=s.get(e)||{score:0,reasons:[]};n.score+=t,n.reasons.push(o),s.set(e,n)}l(Dn,"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,Jc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:s,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
512
|
+
`).filter(Boolean)}catch{return[]}}l(Ww,"listWorkspaceFiles");function Hw(s,e){try{let t=(0,Jc.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(`
|
|
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=ks.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(ks.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(ks.existsSync(de.join(s,n)))return n}return ks.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");Z();Ce();async function Bo(s,e){let t=s[0]||"status",o=process.cwd(),n=J(),r=W(O());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(cf(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(`
|
|
510
514
|
`).slice(0,2).map(d=>` ${a.dim(d.substring(0,80))}`).join(`
|
|
511
|
-
`);console.log(u),console.log("")}}l(
|
|
512
|
-
`)}l(
|
|
513
|
-
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(
|
|
514
|
-
`)[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=
|
|
515
|
-
`)[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(
|
|
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(cf(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 wn(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 wn(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=af(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 cf(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(cf,"formatBytes");var go=y(require("node:fs"),1),xn=y(require("node:path"),1);U();Ce();Z();var bf=".monkeyscode/triggers.json";async function ho(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":yf(o,s[1],!0);break;case"disable":yf(o,s[1],!1);break;case"serve":await rk(o,e);break;default:nk()}}l(ho,"triggersCommand");function Zw(s){let e=$n(s),t=W(O());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=$n(s);if(d.some(p=>p.name===n)){console.log(a.red(` Trigger "${n}" already exists. Use a different --name.`));return}d.push(u),Qc(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=$n(s),o=t.findIndex(n=>n.name===e);if(o===-1){console.log(a.red(` Trigger "${e}" not found.`));return}t.splice(o,1),Qc(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=$n(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 yf(s,e,t){if(!e){console.log(a.red(` Usage: mc triggers ${t?"enable":"disable"} <trigger-name>`));return}let o=$n(s),n=o.find(r=>r.name===e);if(!n){console.log(a.red(` Trigger "${e}" not found.`));return}n.enabled=t,Qc(s,o),console.log(a.green(` \u2705 Trigger "${e}" ${t?"enabled":"disabled"}`)),console.log("")}l(yf,"triggersToggle");function $n(s){let e=xn.join(s,bf);if(!go.existsSync(e))return[];try{return JSON.parse(go.readFileSync(e,"utf8")).triggers||[]}catch{return[]}}l($n,"loadTriggers");function Qc(s,e){let t=xn.join(s,bf),o=xn.dirname(t);go.mkdirSync(o,{recursive:!0}),go.writeFileSync(t,JSON.stringify({triggers:e},null,2)+`
|
|
516
|
+
`)}l(Qc,"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(()=>(mf(),pf)),{GitHubWebhookServer:o}=await Promise.resolve().then(()=>(hf(),gf)),n=J(),{getAccessToken:r}=await Promise.resolve().then(()=>(te(),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(`
|
|
517
|
+
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(rk,"triggersServe");U();U();var xf=require("node:child_process");var Le=y(require("node:fs"),1),yo=y(require("node:path"),1),wf=y(require("node:crypto"),1);Q();var vs=class s{static{l(this,"TraceRecorder")}trace;turnIndex=0;currentToolStart=null;currentToolName=null;thinkingBuffer="";tracesDir;constructor(e){let t=P(De());this.tracesDir=yo.join(t.data,"traces"),Le.mkdirSync(this.tracesDir,{recursive:!0}),this.trace={runId:e.runId||wf.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=yo.join(this.tracesDir,`${this.trace.runId}.json`);Le.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=P(De()),o=yo.join(t.data,"traces"),n=yo.join(o,`${e}.json`);if(!Le.existsSync(n))return null;try{return JSON.parse(Le.readFileSync(n,"utf8"))}catch{return null}}static list(e=20){let t=P(De()),o=yo.join(t.data,"traces");return Le.existsSync(o)?Le.readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=Le.statSync(yo.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(Le.readFileSync(yo.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}};U();function kf(s,e={}){ik(s),e.tree?lk(s):ak(s,e.verbose),uk(s),dk(s)}l(kf,"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(Cn(s.tokensIn))} in / ${a.white(Cn(s.tokensOut))} out${s.tokensCached?` / ${a.dim(Cn(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(` (${Cn(s.tokens)} tok)`):"",o=s.durationMs?a.dim(` ${s.durationMs}ms`):"";switch(s.type){case"thinking":{let n=e?s.content||"":(s.content||"").split(`
|
|
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(` [${Cn(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(`
|
|
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 Cn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Cn,"formatNum");var vf=y(require("node:fs"),1),el=y(require("node:path"),1);Q();var Uo={thinking:"#4A90D9",tool_call:"#2ECC71",context_compact:"#F39C12",error:"#E74C3C",root:"#34495E"};function Sf(s){let e=P(De()),t=el.join(e.data,"traces"),o=el.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 Df(s,r,o)}return Df(s,n,o)}l(Sf,"generateFlamegraph");function Df(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: ${Zc(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),b=Uo[m.type]||Uo.root,k=m.type==="tool_call"?m.tool||"tool":m.type==="thinking"?"Think":m.type;c.push({name:k,tokens:g,color:b,x:u,width:h,y:1,detail:`${k}: ${Zc(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"?>
|
|
516
520
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 ${p}" width="1200" height="${p}">
|
|
517
521
|
<style>
|
|
518
522
|
.frame { cursor: pointer; }
|
|
@@ -526,31 +530,31 @@ ${t}
|
|
|
526
530
|
<rect width="1200" height="${p}" fill="#1a1a2e" rx="8"/>
|
|
527
531
|
|
|
528
532
|
<!-- Title -->
|
|
529
|
-
<text x="40" y="28" class="title">Token Flamegraph \u2014 ${
|
|
530
|
-
<text x="40" y="46" class="subtitle">${
|
|
533
|
+
<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 ${Zc(e)} tokens \xB7 $${s.totalCostUsd.toFixed(4)} \xB7 ${(s.durationMs/1e3).toFixed(1)}s</text>
|
|
531
535
|
|
|
532
536
|
<!-- Legend -->
|
|
533
537
|
<g class="legend" transform="translate(800, 20)">
|
|
534
|
-
<rect x="0" y="0" width="12" height="12" fill="${
|
|
538
|
+
<rect x="0" y="0" width="12" height="12" fill="${Uo.thinking}"/>
|
|
535
539
|
<text x="16" y="11">Thinking</text>
|
|
536
|
-
<rect x="80" y="0" width="12" height="12" fill="${
|
|
540
|
+
<rect x="80" y="0" width="12" height="12" fill="${Uo.tool_call}"/>
|
|
537
541
|
<text x="96" y="11">Tools</text>
|
|
538
|
-
<rect x="150" y="0" width="12" height="12" fill="${
|
|
542
|
+
<rect x="150" y="0" width="12" height="12" fill="${Uo.context_compact}"/>
|
|
539
543
|
<text x="166" y="11">Compact</text>
|
|
540
|
-
<rect x="230" y="0" width="12" height="12" fill="${
|
|
544
|
+
<rect x="230" y="0" width="12" height="12" fill="${Uo.error}"/>
|
|
541
545
|
<text x="246" y="11">Error</text>
|
|
542
546
|
</g>
|
|
543
547
|
|
|
544
548
|
<!-- Frames -->
|
|
545
549
|
<g transform="translate(0, 60)">
|
|
546
|
-
`;for(let m of c){let g=(d-1-m.y)*24,h=m.x+4,b=m.width>40?
|
|
547
|
-
<title>${
|
|
550
|
+
`;for(let m of c){let g=(d-1-m.y)*24,h=m.x+4,b=m.width>40?fk(m.name,Math.floor(m.width/7)):"";f+=`<g class="frame">
|
|
551
|
+
<title>${si(m.detail)}</title>
|
|
548
552
|
<rect x="${m.x}" y="${g}" width="${m.width}" height="22" fill="${m.color}" rx="2"/>
|
|
549
|
-
<text x="${h}" y="${g+24-8}">${
|
|
553
|
+
<text x="${h}" y="${g+24-8}">${si(b)}</text>
|
|
550
554
|
</g>
|
|
551
555
|
`}return f+=`</g>
|
|
552
|
-
</svg>`,
|
|
553
|
-
`)){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=
|
|
556
|
+
</svg>`,vf.writeFileSync(t,f),t}l(Df,"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 Zc(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Zc,"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 $f(s){let e=vs.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($f,"traceList");function Cf(s,e){let t=s==="last"?vs.lastRunId():s;if(!t){console.log(a.red("No traces found. Run an agent first."));return}let o=vs.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=Sf(o);console.log(a.green(`Flamegraph saved: ${n}`));let r=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,xf.exec)(`${r} "${n}"`,i=>{i&&console.log(a.dim(`Open manually: ${n}`))});return}kf(o,{tree:e.tree,verbose:e.verbose})}l(Cf,"traceShow");U();Z();te();var Xt=class{static{l(this,"MarketplaceClient")}baseUrl;token;constructor(e){let t=J();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 Ee();return e?{Authorization:`Bearer ${e}`}:{}}};var ye=y(require("node:fs"),1),bo=y(require("node:path"),1),_f=require("node:child_process");Q();var Wo=class{static{l(this,"SkillInstaller")}client;skillsDir;registryPath;constructor(){this.client=new Xt;let e=P(De());this.skillsDir=bo.join(e.config,"skills"),this.registryPath=bo.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=bo.join(this.skillsDir,n,r);ye.existsSync(i)&&ye.rmSync(i,{recursive:!0}),ye.mkdirSync(i,{recursive:!0});let c=bo.join(i,".tmp.tar.gz");ye.writeFileSync(c,o);try{(0,_f.execSync)(`tar -xzf "${c}" -C "${i}" --strip-components=1`,{stdio:"pipe"})}finally{ye.unlinkSync(c)}let u=bo.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=bo.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=y(require("node:fs"),1),gt=y(require("node:path"),1),Ef=require("node:child_process");var ni=class{static{l(this,"SkillPublisher")}client;constructor(){this.client=new Xt}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(`
|
|
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,Ef.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 Ff(s,e){let t=new Xt;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)If(n)}catch(o){console.log(a.red(`Search failed: ${o.message}`))}}l(Ff,"marketplaceSearch");async function Tf(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(Tf,"marketplaceInstall");function Rf(s){new Wo().uninstall(s)?console.log(a.green(`\u2713 Uninstalled ${s}`)):console.log(a.red(`Skill not found: ${s}`))}l(Rf,"marketplaceUninstall");async function Af(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(Af,"marketplacePublish");async function Pf(){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(Pf,"marketplaceUpdate");function Mf(){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(Mf,"marketplaceList");async function Of(){let s=new Xt;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)If(t)}catch(e){console.log(a.red(`Failed to fetch featured: ${e.message}`))}}l(Of,"marketplaceFeatured");function If(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(If,"renderSkillCard");U();var wo=y(require("node:fs"),1),ri=y(require("node:path"),1);Q();var gk=`You translate natural language permission rules into structured JSON policies.
|
|
554
558
|
|
|
555
559
|
Each policy has:
|
|
556
560
|
- tool: glob pattern for which tools this applies to (e.g., "delete_file", "bash", "*")
|
|
@@ -574,12 +578,12 @@ Input: "Ask before modifying any file with 'config' in the name"
|
|
|
574
578
|
Output: {"tool":"*_file","condition":"path.includes('config')","action":"prompt","message":"This file contains configuration. Proceed?"}
|
|
575
579
|
|
|
576
580
|
Input: "Block any command that uses sudo"
|
|
577
|
-
Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function
|
|
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(()=>(Je(),Zo)),{loadSettings:t}=await Promise.resolve().then(()=>(Z(),ve)),{getAccessToken:o}=await Promise.resolve().then(()=>(te(),ge)),n=t(),r=await o()||process.env.MC_API_KEY||"";if(!r)return tl(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}
|
|
578
582
|
|
|
579
583
|
Input: "${s}"
|
|
580
|
-
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?
|
|
581
|
-
`),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(
|
|
582
|
-
${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop:m}=await Promise.resolve().then(()=>(
|
|
584
|
+
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?tl(s):d}catch{return tl(s)}}l(bk,"llmTranslation");function tl(s){return{tool:"*",condition:"true",action:"prompt",message:`Custom rule: ${s}`}}l(tl,"fallbackPolicy");function jf(){let s=P(De());return ri.join(s.config,"natural-permissions.json")}l(jf,"getPermissionsPath");function _n(){let s=jf();if(!wo.existsSync(s))return{naturalRules:[]};try{return JSON.parse(wo.readFileSync(s,"utf8"))}catch{return{naturalRules:[]}}}l(_n,"loadNaturalPermissions");function Nf(s){let e=jf(),t=ri.dirname(e);wo.mkdirSync(t,{recursive:!0}),wo.writeFileSync(e,JSON.stringify(s,null,2))}l(Nf,"saveNaturalPermissions");async function Lf(s){let e=await hk(s),t={text:s,generatedPolicy:e,createdAt:new Date().toISOString(),enabled:!0},o=_n();return o.naturalRules.push(t),Nf(o),t}l(Lf,"addNaturalRule");function Bf(s){let e=_n();return s<0||s>=e.naturalRules.length?!1:(e.naturalRules.splice(s,1),Nf(e),!0)}l(Bf,"removeNaturalRule");function Uf(s,e){let t=_n();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(Uf,"evaluateNaturalRules");async function Wf(s){console.log(a.dim("Translating rule..."));let e=await Lf(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:")} ${ol(e.generatedPolicy.action)}`),console.log(` ${a.dim("Message:")} ${e.generatedPolicy.message}`),console.log()}l(Wf,"permissionsSet");function Hf(){let s=_n();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=ol(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(Hf,"permissionsList");function Gf(s){let e=Bf(s);console.log(e?a.green(`\u2713 Rule ${s} removed`):a.red(`Rule ${s} not found`))}l(Gf,"permissionsRemove");function qf(s,e){let t;try{t=JSON.parse(e)}catch{console.log(a.red("Invalid JSON for args"));return}let o=Uf(s,t);console.log(),console.log(` ${a.dim("Tool:")} ${s}`),console.log(` ${a.dim("Args:")} ${JSON.stringify(t)}`),console.log(` ${a.dim("Result:")} ${ol(o.action)}`),o.message&&console.log(` ${a.dim("Message:")} ${o.message}`),console.log()}l(qf,"permissionsTest");function ol(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(ol,"colorAction");var xs=y(require("node:fs"),1),ci=y(require("node:path"),1);U();var Ge=y(require("node:fs"),1),Ss=y(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
|
+
`),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(()=>(Je(),Zo)),{loadSettings:g}=await Promise.resolve().then(()=>(Z(),ve)),{getAccessToken:h}=await Promise.resolve().then(()=>(te(),ge)),b=g(),k=await h()||process.env.MC_API_KEY||"",S=new m({platformUrl:b.platformUrl,token:k,model:t,workspace:this.workspace,mode:"auto",maxTurns:p.maxTokens?Math.ceil(p.maxTokens/1e3):20,sandboxed:!0}),x=0,E=0,$=[];S.on("event",ae=>{if(ae.type==="state_update"&&(x=(ae.state?.tokensIn||0)+(ae.state?.tokensOut||0),E=ae.state?.costUsd||0),ae.type==="tool_call_start"&&ae.name?.includes("file")){let Y=ae.args?.path||ae.args?.file;Y&&!$.includes(Y)&&$.push(Y)}}),await S.run(p.prompt);let F=!1,j="";try{j=(0,ii.execSync)(p.verify,{cwd:this.workspace,stdio:"pipe",timeout:p.timeoutMs||12e4}).toString().trim(),F=!0}catch(ae){j=ae.stderr?.toString()||ae.message||"Verification failed",F=!1}r+=x,i+=E,c.push({prompt:p.prompt,passed:F,verifyOutput:j,durationMs:Date.now()-f,tokensUsed:x,filesChanged:$,score:this.scoreStep(p,F,$,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 sl(s){let{getPlatformPaths:e,detectPlatform:t}=(Q(),Rs($o)),o=e(t()),n=Ss.join(o.data,"benchmarks");Ge.mkdirSync(n,{recursive:!0});let r=`${s.name.replace(/\s+/g,"-").toLowerCase()}-${s.model}-${Date.now()}.json`,i=Ss.join(n,r);return Ge.writeFileSync(i,JSON.stringify(s,null,2)),i}l(sl,"saveBenchmarkResult");function Vf(s=20){let{getPlatformPaths:e,detectPlatform:t}=(Q(),Rs($o)),o=e(t()),n=Ss.join(o.data,"benchmarks");return Ge.existsSync(n)?Ge.readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let i=Ge.statSync(Ss.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(Ss.join(n,r.file),"utf8"))}catch{return null}}).filter(Boolean):[]}l(Vf,"loadBenchmarkResults");U();function zf(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:")} ${Yf(s.totalScore,s.maxScore)} ${a.dim(`(${e}%)`)}`),console.log(` ${a.dim("Duration:")} ${t}s`),console.log(` ${a.dim("Tokens:")} ${En(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 ${En(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(zf,"renderResult");function Jf(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))}`+Yf(c.totalScore,c.maxScore).padEnd(20)+a.dim(((c.durationMs/1e3).toFixed(1)+"s").padEnd(10))+a.dim(En(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(Jf,"renderComparison");function Kf(s){if(s.length===0)return`# No Results
|
|
583
587
|
`;let e=`# Benchmark Report: ${s[0].name}
|
|
584
588
|
|
|
585
589
|
`;e+=`Generated: ${new Date().toISOString()}
|
|
@@ -588,21 +592,21 @@ ${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop
|
|
|
588
592
|
|
|
589
593
|
`,e+=`| Model | Score | Time | Tokens | Cost | Steps Passed |
|
|
590
594
|
`,e+=`|-------|-------|------|--------|------|--------------|
|
|
591
|
-
`;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 | ${
|
|
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 | ${En(o.tokensUsed)} | $${o.costUsd.toFixed(4)} | ${r}/${o.steps.length} |
|
|
592
596
|
`}e+=`
|
|
593
597
|
`;for(let o of s){e+=`### ${o.model}
|
|
594
598
|
|
|
595
599
|
`;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}
|
|
596
|
-
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${
|
|
600
|
+
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${En(r.tokensUsed)}
|
|
597
601
|
`,e+=`- Files: ${r.filesChanged.join(", ")||"none"}
|
|
598
602
|
|
|
599
|
-
`}}return e}l(
|
|
600
|
-
`).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(
|
|
601
|
-
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=
|
|
603
|
+
`}}return e}l(Kf,"generateMarkdownReport");function Yf(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(Yf,"colorScore");function En(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(En,"formatNum");async function Xf(s,e){let t=ci.resolve(s),o=e.workspace||process.cwd();if(!xs.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)sl(d);Jf(u)}else{console.log(a.dim(`Running benchmark: ${c.name} with ${r[0]}...`));let u=await n.run(c,r[0]);sl(u),zf(u)}}l(Xf,"benchmarkCustom");function Qf(s){let e=Vf(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(Kf(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(Qf,"benchmarkResults");function Dk(s,e){return xs.statSync(s).isFile()?[e.loadSpec(s)]:xs.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");U();var og=y(require("node:readline"),1);var Zf=y(require("node:crypto"),1),eg=require("node:events");sn();var Fn=class extends eg.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=Zf.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}`}};Z();te();U();function tg(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(`
|
|
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(tg,"renderEvent");async function sg(s){console.log(a.dim(`Joining session ${s}...`));let e=J();if(!(await Ee()||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 Fn({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=>{tg(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(`
|
|
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=og.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(sg,"joinSession");async function ng(){let s=J();if(!(await Ee()||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 Fn({relayUrl:s.platformUrl||"wss://api.monkeyscode.com",userName:t});o.on("participant_joined",n=>{console.log(a.green(`
|
|
602
606
|
\u2192 ${n} joined your session
|
|
603
607
|
`))}),o.on("participant_left",n=>{console.log(a.dim(`
|
|
604
608
|
\u2190 ${n} left your session
|
|
605
|
-
`))});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(
|
|
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(ng,"setupSharedSession");var ig=y(require("node:http"),1);sn();U();function rg(s,e="Design Preview"){return`
|
|
606
610
|
<!DOCTYPE html>
|
|
607
611
|
<html lang="en">
|
|
608
612
|
<head>
|
|
@@ -649,10 +653,10 @@ Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()
|
|
|
649
653
|
</script>
|
|
650
654
|
</body>
|
|
651
655
|
</html>
|
|
652
|
-
`.trim()}l(Xf,"generateHtmlPreview");var tl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=Qf.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(Xf(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new ic.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===rt.OPEN&&t.send("reload")}},Zf=new tl;U();function lk(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(lk,"formatDate");function ri(s){return s.substring(0,8)}l(ri,"formatShortId");function uk(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(uk,"truncatePath");function eg(){let e=new jt().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")(ri(t.id)),n=uk(t.workspace),r=String(t.turnCount).padEnd(8),i=lk(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(eg,"sessionsListCommand");function tg(s){let e=new jt,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 ${ri(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 ${ri(n.id)}`)),console.log("")}l(tg,"sessionsShowCommand");function og(s){let e=new jt,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 ${ri(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(og,"sessionsDeleteCommand");function sg(s=30){let e=new jt,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(sg,"sessionsPruneCommand");sn();U();Q();oe();var ol=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(dk):[]}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 _n(){let s=z(),t=me()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new ol(s.platformUrl,t)}l(_n,"getClient");async function sl(s){pk(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 _n().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} (${mk(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(sl,"scheduleCreate");async function ng(){let e=await _n().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(ng,"scheduleList");async function rg(s){let t=await _n().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(rg,"scheduleDelete");async function ig(s){let t=await _n().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(ig,"schedulePause");async function ag(s){let t=await _n().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(ag,"scheduleResume");function dk(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(dk,"parseSchedule");function pk(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(pk,"validateCron");function mk(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(mk,"describeCron");Ec();Cc();ln();var ke=y(require("node:fs"),1),St=y(require("node:path"),1),Bo=require("node:child_process");U();ze();Q();oe();async function cg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=z(),n,r;if(s.pr?(n=await yk(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Bo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Bo.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Bo.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=fk(s.workspace),c=s.focus?s.focus.split(",").map(b=>b.trim()):[],u=gk(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=ug(p);switch(s.output){case"json":{let b=new ds;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let b=new ps(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(""),dg(f));break}s.postComments&&s.pr&&await bk(s.pr,f,s.workspace),s.autoFix&&f.some(b=>b.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),pg(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(cg,"reviewCommand");async function lg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=z(),n=St.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=wk(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 v of r){let x=ke.readFileSync(v,"utf8");if(c.length+x.length>i)break;let _=St.relative(s.workspace,v);c+=`
|
|
653
|
-
--- ${
|
|
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
|
+
--- ${E} ---
|
|
654
658
|
${x}
|
|
655
|
-
`,u.push(
|
|
659
|
+
`,u.push(E)}let d=s.focus?s.focus.split(",").map(S=>S.trim()):[],p=Tk(c,u,d),f=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}),m="";f.on("event",S=>{S.type==="streaming_chunk"&&(m+=S.content)});try{await f.run(p)}catch(S){console.error(a.red(` \u274C Bug scan failed: ${S instanceof Error?S.message:S}`)),process.exit(1)}let g=bg(m);switch(s.output){case"json":console.log(JSON.stringify({scannedFiles:u,findings:g,summary:al(g)},null,2));break;case"sarif":{let S=new fs(g,s.workspace);console.log(S.formatFindings(g));break}case"github":for(let S of g){let x=S.severity==="high"?"error":S.severity==="medium"?"warning":"notice";console.log(`::${x} file=${S.file},line=${S.line}::${S.message}`)}break;case"text":default:wg(g);break}s.autoFix&&g.some(S=>S.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),kg(g,s.workspace));let h={high:3,medium:2,low:1,info:0},b=h[s.severityThreshold]||3;g.some(S=>(h[S.severity]||0)>=b)&&process.exit(1)}l(yg,"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.
|
|
656
660
|
|
|
657
661
|
For each finding, output in this EXACT format (one per line):
|
|
658
662
|
[SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
|
|
@@ -667,7 +671,7 @@ ${o}
|
|
|
667
671
|
`),n+=`Diff:
|
|
668
672
|
\`\`\`diff
|
|
669
673
|
${s}
|
|
670
|
-
\`\`\``,n}l(
|
|
674
|
+
\`\`\``,n}l(Fk,"buildReviewPrompt");function Tk(s,e,t){let o=`You are a senior security researcher and bug hunter. Scan the following source files for potential bugs with severity ratings.
|
|
671
675
|
|
|
672
676
|
For each finding, output in this EXACT format (one per line):
|
|
673
677
|
[SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
|
|
@@ -686,27 +690,27 @@ Focus on:
|
|
|
686
690
|
`),o+=`Files to scan: ${e.join(", ")}
|
|
687
691
|
|
|
688
692
|
`,o+=`Source code:
|
|
689
|
-
${s}`,o}l(
|
|
690
|
-
`);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(
|
|
693
|
+
${s}`,o}l(Tk,"buildBugfindPrompt");function bg(s){let e=[],t=s.split(`
|
|
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(bg,"parseFindings");function wg(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(` ${al(s)}`),console.log("")}l(wg,"printFindingsTable");function al(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(al,"formatSeveritySummary");function kg(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(`
|
|
691
695
|
`);o.line>0&&o.line<=r.length&&(r[o.line-1]=o.fix,ke.writeFileSync(n,r.join(`
|
|
692
|
-
`)),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(
|
|
693
|
-
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(
|
|
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(kg,"applyFixes");async function Rk(s,e){let t=Dg(e),o=vg();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(`
|
|
697
|
+
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(Rk,"fetchPRDiff");async function Ak(s,e,t){let o=Dg(t),n=vg();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(`
|
|
694
698
|
`);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
|
|
695
699
|
|
|
696
700
|
${r}
|
|
697
701
|
|
|
698
|
-
${
|
|
702
|
+
${al(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 Dg(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(Dg,"getGitRemote");function vg(){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(vg,"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");of();Gm();globalThis.__mcChalk=a;var di="0.1.6",qo="auto";function Cg(s){let e=No(s);return{defaultModel:e.get("model"),defaultMode:e.get("defaultMode"),maxTokens:e.get("maxTokens")}}l(Cg,"loadConfig");var V=new _l;V.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
|
|
699
703
|
Runs independently of the IDE and Agent Manager.
|
|
700
|
-
Connects directly to model-proxy via SSE streaming.`).version(ai);q.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",Wo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Et("-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 Et("--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 Et("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Et("--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=bg(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(ai),process.exit(0);break;case"/doctor":await on(),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=gt(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 am(c)});var Fn=q.command("auth").description("Manage authentication");Fn.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 ha(s.profile):s.email?await ua():await la()});Fn.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ya(s.profile));Fn.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>pa(s,e.profile));Fn.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await Yn(s.profile));Fn.command("refresh").description("Manually refresh the access token").action(async()=>await ma());q.command("status").description("Show account and agent status").action(async()=>{let s=bg(),e=new So,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),o=t();e.printBanner("System Status"),await Yn(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});q.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>on(s));q.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=>Rm(s));q.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Wm(s));q.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Hm(s,e));q.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";Ym({since:s.since,review:s.review,mode:e})});var Tn=q.command("config").description("Manage CLI configuration");Tn.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=Mo(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}]`)});Tn.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=Mo(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))});Tn.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=Mo(N.resolve(s.workspace));Dm(e)});Tn.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{Mo().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});Tn.command("path").description("Show config file locations").action(()=>{let s=T(),t=Mo().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}`)});q.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 So;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new co;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 Rn=q.command("mcp").description("Manage MCP (Model Context Protocol) servers");Rn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await pm(N.resolve(s.workspace))});Rn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{mm(N.resolve(o.workspace),s,e,t||[])});Rn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{fm(N.resolve(e.workspace),s)});Rn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await gm(N.resolve(e.workspace),s)});Rn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{hm(s)});var Tk=q.command("agents").description("View active agent sessions dashboard").action(async()=>{await Ac(!0)});Tk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Ac(!1)});var Ss=q.command("context").description("Semantic code search and workspace indexing");Ss.command("index").description("Index the current workspace for semantic search").action(async()=>{await jo(["index"],{})});Ss.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await jo(["search",s],{topK:e.topK})});Ss.command("status").description("Show index status and statistics").action(async()=>{await jo(["status"],{})});Ss.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await jo(["rebuild"],{})});Ss.command("related <file>").description("Find files related to a given file").action(async s=>{await jo(["related",s],{})});Ss.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await jo(["rank",s],{})});var Ho=q.command("triggers").description("Manage event-driven agent triggers");Ho.command("list").description("Show configured triggers").action(async()=>{await fo(["list"],{})});Ho.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 fo(["add"],s)});Ho.command("remove <name>").description("Remove a trigger by name").action(async s=>{await fo(["remove",s],{})});Ho.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await fo(["test",s],{})});Ho.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await fo(["enable",s],{})});Ho.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await fo(["disable",s],{})});Ho.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await fo(["serve"],{port:s.port})});q.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(lm(o)),console.log("")):console.log(cm(o))});var li=q.command("sessions").description("Manage saved conversation sessions");li.command("list").description("List recent sessions").action(()=>eg());li.command("show <id>").description("Show session details").action(s=>tg(s));li.command("delete <id>").description("Delete a session").action(s=>og(s));li.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{sg(parseInt(s.olderThan,10))});var Yt=q.command("jobs").description("Manage background agent jobs");Yt.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(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Oe(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(gc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);wc(d)});Yt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=hc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=yc(s);jr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Oe(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);jr(i,c)});Yt.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(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Oe(n.platformUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Nr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(yg(),hg));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)Nr(u)}});Yt.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(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),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 Oe(n.platformUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Yt.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(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Oe(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}`)});Yt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Oe(o.platformUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Yt.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(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Oe(n.platformUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),bc(N.resolve(e.workspace),s,c.branch)});Yt.action(()=>{Yt.outputHelp()});var Uo=q.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",Wo).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",".");Uo.action(async(s,e)=>{s&&e.cron?await sl({prompt:s,cron:e.cron,model:gt(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)):Uo.outputHelp()});Uo.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",Wo).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 sl({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)})});Uo.command("list").description("List all scheduled jobs").action(async()=>{await ng()});Uo.command("delete <id>").description("Delete a scheduled job").action(async s=>{await rg(s)});Uo.command("pause <id>").description("Pause a scheduled job").action(async s=>{await ig(s)});Uo.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await ag(s)});var En=q.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",Wo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");En.action(async(s,e)=>{s.length>0?await Lr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):En.outputHelp()});En.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",Wo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Lr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});En.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{$c(N.resolve(s.workspace))});En.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{_c(N.resolve(e.workspace),s)});var ci=q.command("worktrees").description("Manage git worktrees used by agent teams");ci.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=fs(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}`)}});ci.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=Jp({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}`)});ci.action(()=>{ci.outputHelp()});var cl=q.command("messages").description("Cross-session messaging");cl.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(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new cn(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)});cl.action(()=>{cl.outputHelp()});var wg=q.command("hooks").description("Manage lifecycle hooks");wg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Pc(N.resolve(s.workspace))});wg.action(()=>{Pc(N.resolve("."))});var kg=q.command("models").description("Manage available models");kg.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();$a(s?.org?.plan)});kg.action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();$a(s?.org?.plan)});q.command("usage").description("Show monthly usage breakdown").action(async()=>{await vm()});q.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(J.existsSync(t)&&J.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=J.readdirSync(e).filter(h=>h.endsWith(".csproj")),f="Unknown";if(J.existsSync(r))try{let h=JSON.parse(J.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{}J.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"),J.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),J.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),J.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(`
|
|
701
|
-
`),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.`)),
|
|
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.`)),K.mkdirSync(N.join(e,".monkeyscode"),{recursive:!0}),K.writeFileSync(t,m,"utf8"),K.existsSync(o)||K.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 Cs=V.command("memory").description("Manage project conventions and rules");Cs.command("show").description("Show resolved rules from all sources").option("--workspace <path>","Workspace path",".").action(s=>{let e=N.resolve(s.workspace),t=P(),o=N.join(e,".monkeyscode","rules.md"),n=N.join(t.config,"rules.md"),r=N.join(e,".monkeyscode","MEMORY.md");if(console.log(""),console.log(a.bold(" \u{1F4DD} Resolved Rules")),console.log(a.dim(" "+"\u2500".repeat(50))),K.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=K.readFileSync(o,"utf8");for(let u of i.split(`
|
|
702
706
|
`))console.log(` ${u}`);let c=Math.ceil(i.length/4);c>2e3&&console.log(a.yellow(`
|
|
703
|
-
\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(
|
|
704
|
-
`))console.log(` ${i}`);console.log("")}if(
|
|
705
|
-
`))console.log(` ${i}`);console.log("")}console.log("")});
|
|
706
|
-
`,r=s.replace(/^["']|["']$/g,"");
|
|
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(K.existsSync(n)){console.log(a.cyan(" [global]")+a.dim(` ${n}`));for(let i of K.readFileSync(n,"utf8").split(`
|
|
708
|
+
`))console.log(` ${i}`);console.log("")}if(K.existsSync(r)){console.log(a.magenta(" [memory]")+a.dim(` ${r}`));for(let i of K.readFileSync(r,"utf8").split(`
|
|
709
|
+
`))console.log(` ${i}`);console.log("")}console.log("")});Cs.command("add <rule>").description("Add a convention rule").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=N.resolve(e.workspace),o=N.join(t,".monkeyscode","rules.md");K.mkdirSync(N.dirname(o),{recursive:!0});let n=K.existsSync(o)?K.readFileSync(o,"utf8"):`# Project Conventions
|
|
710
|
+
`,r=s.replace(/^["']|["']$/g,"");K.writeFileSync(o,n.trimEnd()+`
|
|
707
711
|
- `+r+`
|
|
708
|
-
`,"utf8"),console.log(` \u2705 Added: ${r}`)});
|
|
709
|
-
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&
|
|
710
|
-
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});
|
|
711
|
-
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});
|
|
712
|
-
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});
|
|
712
|
+
`,"utf8"),console.log(` \u2705 Added: ${r}`)});Cs.command("edit").description("Open rules in $EDITOR").option("--workspace <path>","Workspace path",".").action(s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md"),o=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!K.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}`)}});Cs.command("forget <pattern>").description("Remove a learned convention matching the pattern").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=N.resolve(e.workspace),o=N.join(t,".monkeyscode","MEMORY.md"),n=N.join(t,".monkeyscode","rules.md"),r=0,i=s.replace(/^["']|["']$/g,"");for(let c of[o,n]){if(!K.existsSync(c))continue;let d=K.readFileSync(c,"utf8").split(`
|
|
713
|
+
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&K.writeFileSync(c,d.join(`
|
|
714
|
+
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});Cs.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 V.parseAsync(["node","mc","dream","--since",s.since,...s.review?["--review"]:[],"--workspace",s.workspace])});Cs.action(s=>{let e=process.cwd(),t=N.join(e,".monkeyscode","rules.md");if(K.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 K.readFileSync(t,"utf8").split(`
|
|
715
|
+
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});V.command("rules").description("Show resolved rules (alias for mc memory show)").option("--workspace <path>","Workspace path",".").action(s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md");if(K.existsSync(t)){console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules"));for(let o of K.readFileSync(t,"utf8").split(`
|
|
716
|
+
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});V.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 At("-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 At("--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 hg({workspace:N.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})});V.command("bugfind [target]").description("Scan files for potential bugs with severity ratings").addOption(new At("-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 At("--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 yg({workspace:N.resolve(e.workspace),model:t,target:s||".",output:e.output,autoFix:e.autoFix,focus:e.focus,severityThreshold:e.severityThreshold})});var Fg=V.command("trace").description("Inspect agent execution traces");Fg.command("list").action(async s=>{$f(s)});Fg.command("show <id>").option("--tree").option("--flamegraph").option("--verbose").action(async(s,e)=>{Cf(s,e)});var zo=V.command("marketplace").description("Browse and manage agent skills");zo.command("search <query>").option("--category <cat>").action(async(s,e)=>{await Ff(s,e)});zo.command("install <id>").action(async s=>{await Tf(s)});zo.command("uninstall <id>").action(async s=>{Rf(s)});zo.command("publish <dir>").option("--name <name>").option("--bump <bump>").action(async(s,e)=>{await Af(s,e)});zo.command("update").action(async()=>{await Pf()});zo.command("list").action(()=>{Mf()});zo.command("featured").action(async()=>{await Of()});V.command("join <sessionId>").description("Join a live collaboration session").action(async s=>{await sg(s)});V.command("share").description("Start a new live collaboration session").action(async()=>{await ng()&&console.log(a.dim("Host session running..."))});var fi=V.command("permissions").description("Manage natural language policies");fi.command("set <text>").action(async s=>{await Wf(s)});fi.command("list").action(()=>{Hf()});fi.command("remove <index>").action(s=>{Gf(parseInt(s,10))});fi.command("test <tool> <args>").action((s,e)=>{qf(s,e)});var Tg=V.command("benchmark").description("Run agent benchmarks");Tg.command("custom <path>").option("--model [models...]").option("--workspace <dir>").action(async(s,e)=>{await Xf(s,e)});Tg.command("results").option("--limit <n>").option("--format <fmt>").action(s=>{Qf(s)});V.command("design").description("Start the local design artboard server").option("--port <p>").action(s=>{ag.start(s.port?parseInt(s.port,10):void 0)});Qm()&&process.argv.length<=2?Zm().then(()=>V.parse()).catch(()=>V.parse()):(Mm(di),Jm("cli_start",{version:di}),V.parse(),process.on("beforeExit",()=>{Om()}));
|