monkeyscode-cli 0.1.10 → 0.1.11
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 +261 -253
- package/package.json +2 -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
|
|
5
|
-
`+" ".repeat(t+u)),i+c+" ".repeat(u)+
|
|
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
|
|
7
|
-
`)}};function
|
|
3
|
+
"use strict";var hg=Object.create;var Ns=Object.defineProperty;var gg=Object.getOwnPropertyDescriptor;var yg=Object.getOwnPropertyNames;var wg=Object.getPrototypeOf,bg=Object.prototype.hasOwnProperty;var l=(s,e)=>Ns(s,"name",{value:e,configurable:!0});var W=(s,e)=>()=>(s&&(e=s(s=0)),e);var le=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Ae=(s,e)=>{for(var t in e)Ns(s,t,{get:e[t],enumerable:!0})},Rl=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yg(e))!bg.call(s,n)&&n!==t&&Ns(s,n,{get:()=>e[n],enumerable:!(o=gg(e,n))||o.enumerable});return s};var w=(s,e,t)=>(t=s!=null?hg(wg(s)):{},Rl(e||!s||!s.__esModule?Ns(t,"default",{value:s,enumerable:!0}):t,s)),Ls=s=>Rl(Ns({},"__esModule",{value:!0}),s);var Bs=le($i=>{var Vn=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}},_i=class extends Vn{static{l(this,"InvalidArgumentError")}constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};$i.CommanderError=Vn;$i.InvalidArgumentError=_i});var Jn=le(Ei=>{var{InvalidArgumentError:kg}=Bs(),Ci=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 kg(`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 vg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}l(vg,"humanReadableArgName");Ei.Argument=Ci;Ei.humanReadableArgName=vg});var Ri=le(Ti=>{var{humanReadableArgName:Dg}=Jn(),Fi=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=>Dg(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 Al(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
|
+
`+" ".repeat(t+u)),i+c+" ".repeat(u)+f.replace(/\n/g,`
|
|
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 Al(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}l(Al,"stripColor");Ti.Help=Fi;Ti.stripColor=Al});var Mi=le(Ii=>{var{InvalidArgumentError:Sg}=Bs(),Ai=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=xg(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 Sg(`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?Pl(this.name().replace(/^no-/,"")):Pl(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Pi=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 Pl(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(Pl,"camelcase");function xg(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(xg,"splitOptionFlags");Ii.Option=Ai;Ii.DualOptions=Pi});var Ml=le(Il=>{function _g(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(_g,"editDistance");function $g(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=_g(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($g,"suggestSimilar");Il.suggestSimilar=$g});var Ll=le(Bi=>{var Cg=require("node:events").EventEmitter,Oi=require("node:child_process"),It=require("node:path"),zn=require("node:fs"),te=require("node:process"),{Argument:Eg,humanReadableArgName:Fg}=Jn(),{CommanderError:ji}=Bs(),{Help:Tg,stripColor:Rg}=Ri(),{Option:Ol,DualOptions:Ag}=Mi(),{suggestSimilar:jl}=Ml(),Ni=class s extends Cg{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=>te.stdout.write(t),"writeOut"),writeErr:l(t=>te.stderr.write(t),"writeErr"),outputError:l((t,o)=>o(t),"outputError"),getOutHelpWidth:l(()=>te.stdout.isTTY?te.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>te.stderr.isTTY?te.stderr.columns:void 0,"getErrHelpWidth"),getOutHasColors:l(()=>Li()??(te.stdout.isTTY&&te.stdout.hasColors?.()),"getOutHasColors"),getErrHasColors:l(()=>Li()??(te.stderr.isTTY&&te.stderr.hasColors?.()),"getErrHasColors"),stripColor:l(t=>Rg(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 Tg,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 Eg(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 ji(e,t,o)),te.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 Ol(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 Ol)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){te.versions?.electron&&(t.from="electron");let n=te.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=te.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":te.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(zn.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,
|
|
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=It.resolve(p,f);if(zn.existsSync(m))return m;if(n.includes(It.extname(f)))return;let h=n.find(g=>zn.existsSync(`${m}${g}`));if(h)return`${m}${h}`}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=zn.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=It.resolve(It.dirname(p),c)}if(c){let p=r(c,i);if(!p&&!e._executableFile&&this._scriptPath){let f=It.basename(this._scriptPath,It.extname(this._scriptPath));f!==this._name&&(p=r(c,`${f}-${e._name}`))}i=p||i}o=n.includes(It.extname(i));let u;te.platform!=="win32"?o?(t.unshift(i),t=Nl(te.execArgv).concat(t),u=Oi.spawn(te.argv[0],t,{stdio:"inherit"})):u=Oi.spawn(i,t,{stdio:"inherit"}):(this._checkForMissingExecutable(i,c,e._name),t.unshift(i),t=Nl(te.execArgv).concat(t),u=Oi.spawn(te.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{te.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 ji(p,"commander.executeSubCommandAsync","(close)")):te.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)te.exit(1);else{let f=new ji(1,"commander.executeSubCommandAsync","(error)");f.nestedError=p,d(f)}}),this.runningCommand=u}_dispatchSubcommand(e,t,o){let n=this._findCommand(e);n||this.help({error:!0}),n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(o));else return n._parseCommand(t,o)}),r}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=l((o,n,r)=>{let i=n;if(n!==null&&o.parseArg){let c=`error: command-argument value '${n}' is invalid for argument '${o.name()}'.`;i=this._callParseArg(o,n,r,c)}return i},"myParseArg");this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((o,n)=>{let r=o.defaultValue;o.variadic?n<this.args.length?(r=this.args.slice(n),o.parseArg&&(r=r.reduce((i,c)=>e(o,c,i),o.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],o.parseArg&&(r=e(o,r,o.defaultValue))),t[n]=r}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let o=e,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[t]!==void 0).forEach(r=>{r._lifeCycleHooks[t].forEach(i=>{n.push({hookedCommand:r,callback:i})})}),t==="postAction"&&n.reverse(),n.forEach(r=>{o=this._chainOrCall(o,()=>r.callback(r.hookedCommand,this))}),o}_chainOrCallSubCommandHook(e,t,o){let n=e;return this._lifeCycleHooks[o]!==void 0&&this._lifeCycleHooks[o].forEach(r=>{n=this._chainOrCall(n,()=>r(this,t))}),n}_parseCommand(e,t){let o=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(o.operands),t=o.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(o.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=l(()=>{o.unknown.length>0&&this.unknownOption(o.unknown[0])},"checkForUnknownOptions"),r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let i;return i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent&&(i=this._chainOrCall(i,()=>{this.parent.emit(r,e,t)})),i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(o=>{let n=o.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(o=>o.conflictsWith.length>0).forEach(o=>{let n=e.find(r=>o.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(o,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],o=[],n=t,r=e.slice();function i(u){return u.length>1&&u[0]==="-"}l(i,"maybeOption");let c=null;for(;r.length;){let u=r.shift();if(u==="--"){n===o&&n.push(u),n.push(...r);break}if(c&&!i(u)){this.emit(`option:${c.name()}`,u);continue}if(c=null,i(u)){let d=this._findOption(u);if(d){if(d.required){let p=r.shift();p===void 0&&this.optionMissingArgument(d),this.emit(`option:${d.name()}`,p)}else if(d.optional){let p=null;r.length>0&&!i(r[0])&&(p=r.shift()),this.emit(`option:${d.name()}`,p)}else this.emit(`option:${d.name()}`);c=d.variadic?d:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let d=this._findOption(`-${u[1]}`);if(d){d.required||d.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${d.name()}`,u.slice(2)):(this.emit(`option:${d.name()}`),r.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let d=u.indexOf("="),p=this._findOption(u.slice(0,d));if(p&&(p.required||p.optional)){this.emit(`option:${p.name()}`,u.slice(d+1));continue}}if(i(u)&&(n=o),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&o.length===0){if(this._findCommand(u)){t.push(u),r.length>0&&o.push(...r);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){t.push(u),r.length>0&&t.push(...r);break}else if(this._defaultCommandName){o.push(u),r.length>0&&o.push(...r);break}}if(this._passThroughOptions){n.push(u),r.length>0&&n.push(...r);break}n.push(u)}return{operands:t,unknown:o}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let o=0;o<t;o++){let n=this.options[o].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0}));let o=t||{},n=o.exitCode||1,r=o.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in
|
|
26
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let o=this.parent?._findCommand(e);if(o){let n=[o.name()].concat(o.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(o=>
|
|
25
|
+
`),this.outputHelp({error:!0}));let o=t||{},n=o.exitCode||1,r=o.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in te.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()}`,te.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Ag(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=jl(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=jl(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=>Fg(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=It.basename(e,It.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(te.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 Nl(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(Nl,"incrementNodeInspectorPort");function Li(){if(te.env.NO_COLOR||te.env.FORCE_COLOR==="0"||te.env.FORCE_COLOR==="false")return!1;if(te.env.FORCE_COLOR||te.env.CLICOLOR_FORCE!==void 0)return!0}l(Li,"useColor");Bi.Command=Ni;Bi.useColor=Li});var Hl=le(Je=>{var{Argument:Bl}=Jn(),{Command:Ui}=Ll(),{CommanderError:Pg,InvalidArgumentError:Ul}=Bs(),{Help:Ig}=Ri(),{Option:Wl}=Mi();Je.program=new Ui;Je.createCommand=s=>new Ui(s);Je.createOption=(s,e)=>new Wl(s,e);Je.createArgument=(s,e)=>new Bl(s,e);Je.Command=Ui;Je.Option=Wl;Je.Argument=Bl;Je.Help=Ig;Je.CommanderError=Pg;Je.InvalidArgumentError=Ul;Je.InvalidOptionArgumentError=Ul});function jg(){let s=new Map;for(let[e,t]of Object.entries(re)){for(let[o,n]of Object.entries(t))re[o]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[o]=re[o],s.set(n[0],n[1]);Object.defineProperty(re,e,{value:t,enumerable:!1})}return Object.defineProperty(re,"codes",{value:s,enumerable:!1}),re.color.close="\x1B[39m",re.bgColor.close="\x1B[49m",re.color.ansi=Vl(),re.color.ansi256=Jl(),re.color.ansi16m=zl(),re.bgColor.ansi=Vl(10),re.bgColor.ansi256=Jl(10),re.bgColor.ansi16m=zl(10),Object.defineProperties(re,{rgbToAnsi256:{value(e,t,o){return e===t&&t===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[o]=t;o.length===3&&(o=[...o].map(r=>r+r).join(""));let n=Number.parseInt(o,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:l(e=>re.rgbToAnsi256(...re.hexToRgb(e)),"value"),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,o,n;if(e>=232)t=((e-232)*10+8)/255,o=t,n=t;else{e-=16;let c=e%36;t=Math.floor(e/36)/5,o=Math.floor(c/6)/5,n=c%6/5}let r=Math.max(t,o,n)*2;if(r===0)return 30;let i=30+(Math.round(n)<<2|Math.round(o)<<1|Math.round(t));return r===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:l((e,t,o)=>re.ansi256ToAnsi(re.rgbToAnsi256(e,t,o)),"value"),enumerable:!1},hexToAnsi:{value:l(e=>re.ansi256ToAnsi(re.hexToAnsi256(e)),"value"),enumerable:!1}}),re}var Vl,Jl,zl,re,hD,Mg,Og,gD,Ng,rt,Kl=W(()=>{Vl=l((s=0)=>e=>`\x1B[${e+s}m`,"wrapAnsi16"),Jl=l((s=0)=>e=>`\x1B[${38+s};5;${e}m`,"wrapAnsi256"),zl=l((s=0)=>(e,t,o)=>`\x1B[${38+s};2;${e};${t};${o}m`,"wrapAnsi16m"),re={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},hD=Object.keys(re.modifier),Mg=Object.keys(re.color),Og=Object.keys(re.bgColor),gD=[...Mg,...Og];l(jg,"assembleStyles");Ng=jg(),rt=Ng});function ze(s,e=globalThis.Deno?globalThis.Deno.args:Yn.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 Lg(){if("FORCE_COLOR"in ie)return ie.FORCE_COLOR==="true"?1:ie.FORCE_COLOR==="false"?0:ie.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ie.FORCE_COLOR,10),3)}function Bg(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function Ug(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let o=Lg();o!==void 0&&(Kn=o);let n=t?Kn:o;if(n===0)return 0;if(t){if(ze("color=16m")||ze("color=full")||ze("color=truecolor"))return 3;if(ze("color=256"))return 2}if("TF_BUILD"in ie&&"AGENT_NAME"in ie)return 1;if(s&&!e&&n===void 0)return 0;let r=n||0;if(ie.TERM==="dumb")return r;if(Yn.default.platform==="win32"){let i=Xl.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ie)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in ie)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in ie)||ie.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in ie)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ie.TEAMCITY_VERSION)?1:0;if(ie.COLORTERM==="truecolor"||ie.TERM==="xterm-kitty"||ie.TERM==="xterm-ghostty"||ie.TERM==="wezterm")return 3;if("TERM_PROGRAM"in ie){let i=Number.parseInt((ie.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ie.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ie.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ie.TERM)||"COLORTERM"in ie?1:r}function Yl(s,e={}){let t=Ug(s,{streamIsTTY:s&&s.isTTY,...e});return Bg(t)}var Yn,Xl,Wi,ie,Kn,Wg,Ql,Zl=W(()=>{Yn=w(require("node:process"),1),Xl=w(require("node:os"),1),Wi=w(require("node:tty"),1);l(ze,"hasFlag");({env:ie}=Yn.default);ze("no-color")||ze("no-colors")||ze("color=false")||ze("color=never")?Kn=0:(ze("color")||ze("colors")||ze("color=true")||ze("color=always"))&&(Kn=1);l(Lg,"envForceColor");l(Bg,"translateLevel");l(Ug,"_supportsColor");l(Yl,"createSupportsColor");Wg={stdout:Yl({isTTY:Wi.default.isatty(1)}),stderr:Yl({isTTY:Wi.default.isatty(2)})},Ql=Wg});function eu(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 tu(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=Ll(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Is.prototype,Yo);fh=Is(),ED=Is({level:Wl?Wl.level:0}),a=fh});var Kl=ce((zD,Ch)=>{Ch.exports={dots:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{interval:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{interval:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{interval:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{interval:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{interval:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{interval:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{interval:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{interval:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{interval:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{interval:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{interval:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{interval:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots8Bit:{interval:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},sand:{interval:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},pipe:{interval:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{interval:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{interval:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{interval:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","\xB0","O","o","."]},noise:{interval:100,frames:["\u2593","\u2592","\u2591"]},bounce:{interval:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{interval:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{interval:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{interval:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{interval:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{interval:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{interval:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{interval:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{interval:100,frames:["\u256B","\u256A"]},toggle:{interval:250,frames:["\u22B6","\u22B7"]},toggle2:{interval:80,frames:["\u25AB","\u25AA"]},toggle3:{interval:120,frames:["\u25A1","\u25A0"]},toggle4:{interval:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{interval:100,frames:["\u25AE","\u25AF"]},toggle6:{interval:300,frames:["\u101D","\u1040"]},toggle7:{interval:80,frames:["\u29BE","\u29BF"]},toggle8:{interval:100,frames:["\u25CD","\u25CC"]},toggle9:{interval:100,frames:["\u25C9","\u25CE"]},toggle10:{interval:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{interval:50,frames:["\u29C7","\u29C6"]},toggle12:{interval:120,frames:["\u2617","\u2616"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{interval:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{interval:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{interval:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{interval:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{interval:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u2764\uFE0F "]},clock:{interval:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{interval:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{interval:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{interval:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{interval:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{interval:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{interval:120,frames:["\u2590|\\____________\u258C","\u2590_|\\___________\u258C","\u2590__|\\__________\u258C","\u2590___|\\_________\u258C","\u2590____|\\________\u258C","\u2590_____|\\_______\u258C","\u2590______|\\______\u258C","\u2590_______|\\_____\u258C","\u2590________|\\____\u258C","\u2590_________|\\___\u258C","\u2590__________|\\__\u258C","\u2590___________|\\_\u258C","\u2590____________|\\\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{interval:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{interval:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{interval:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{interval:150,frames:["-","=","\u2261"]},betaWave:{interval:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{interval:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{interval:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{interval:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{interval:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{interval:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{interval:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{interval:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{interval:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{interval:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]}}});var qi=ce((JD,Xl)=>{"use strict";var Jn=Object.assign({},Kl()),Yl=Object.keys(Jn);Object.defineProperty(Jn,"random",{get(){let s=Math.floor(Math.random()*Yl.length),e=Yl[s];return Jn[e]}});Xl.exports=Jn});var uu=ce((vv,lu)=>{lu.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var $o={};Ae($o,{detectPlatform:()=>ve,ensureDir:()=>Yn,getPlatformInfo:()=>Ce,getPlatformPaths:()=>A,isLocalModel:()=>Jh,isUNCPath:()=>Vh,normalizePath:()=>qh,resolveSymlinks:()=>zh});function ve(){switch(At.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function A(s){switch(s??ve()){case"macos":{let t=At.homedir(),o=se.join(t,".monkeyscode");return{config:o,data:o,pidFile:se.join(o,"daemon.pid"),socketFile:se.join(o,"daemon.sock"),credentialBackend:"macOS Keychain",logs:se.join(o,"logs")}}case"linux":{let t=At.homedir(),o=process.env.XDG_CONFIG_HOME||se.join(t,".config"),n=process.env.XDG_DATA_HOME||se.join(t,".local","share"),r=process.env.XDG_STATE_HOME||se.join(t,".local","state"),i=xo.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=xo.existsSync(n)?se.join(n,"monkeyscode"):se.join(t,".monkeyscode");return{config:i,data:c,pidFile:se.join(r,"monkeyscode","daemon.pid"),socketFile:se.join(r,"monkeyscode","daemon.sock"),credentialBackend:"libsecret / gnome-keyring",logs:se.join(r,"monkeyscode","logs")}}case"windows":{let t=process.env.APPDATA||se.join(At.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(At.homedir(),"AppData","Local");return{config:se.join(t,"monkeyscode"),data:se.join(o,"monkeyscode"),pidFile:se.join(o,"monkeyscode","daemon.pid"),socketFile:se.join(o,"monkeyscode","daemon.sock"),credentialBackend:"Windows Credential Manager",logs:se.join(o,"monkeyscode","logs")}}}}function Ce(){let s=ve();return{os:s,arch:At.arch(),shell:Wh(s),supportsColor:Hh(),supportsUnicode:Gh(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Wh(s){return s==="windows"?process.env.PSModulePath?"powershell":process.env.SHELL?se.basename(process.env.SHELL):"cmd":process.env.SHELL?se.basename(process.env.SHELL):"sh"}function Hh(){return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:process.stdout.isTTY?process.env.WT_SESSION?!0:(process.env.TERM||"")!=="dumb":!1}function Gh(s){if(s==="windows")return!!(process.env.WT_SESSION||process.env.ConEmuPID);let e=process.env.LANG||process.env.LC_ALL||"";return e.includes("UTF-8")||e.includes("utf-8")||e.includes("UTF8")}function Yn(s){xo.mkdirSync(s,{recursive:!0})}function qh(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function Vh(s){return s.startsWith("\\\\")||s.startsWith("//")}function zh(s){try{return xo.realpathSync(s)}catch{return s}}function Jh(s,e){if(s.startsWith("local:")||s.startsWith("ollama:"))return!0;if(e)try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}return!1}var At,se,xo,X=G(()=>{"use strict";At=b(require("node:os"),1),se=b(require("node:path"),1),xo=b(require("node:fs"),1);l(ve,"detectPlatform");l(A,"getPlatformPaths");l(Ce,"getPlatformInfo");l(Wh,"detectShell");l(Hh,"detectColorSupport");l(Gh,"detectUnicodeSupport");l(Yn,"ensureDir");l(qh,"normalizePath");l(Vh,"isUNCPath");l(zh,"resolveSymlinks");l(Jh,"isLocalModel")});function ey(){if(process.env.NERD_FONT==="1"||process.env.MC_ICONS==="nerd")return!0;if(process.env.NERD_FONT==="0"||process.env.MC_ICONS==="unicode"||process.env.MC_ICONS==="ascii")return!1;let s=(process.env.TERM_PROGRAM||"").toLowerCase();return!!(["wezterm","kitty","alacritty","ghostty","rio","hyper"].some(t=>s.includes(t))||process.env.WT_SESSION||s==="vscode")}function I(){let s=Ce(),e=process.env.NO_COLOR!==void 0,t=process.env.FORCE_COLOR!==void 0,o=!!process.stdout.isTTY,n=!!process.stdin.isTTY,r=o&&!e,i=r,c=!1,u=!1;if(t&&(r=!0,i=!0),r){let p=process.env.TERM||"",g=process.env.COLORTERM||"";(p.includes("256color")||p==="xterm-kitty"||g)&&(c=!0),(g==="truecolor"||g==="24bit")&&(u=!0),process.env.WT_SESSION&&(c=!0,u=!0)}let d=ey();return{ansi:r,color16:i,color256:c,trueColor:u,unicode:s.supportsUnicode,nerdFont:d,emoji:s.supportsUnicode&&s.os!=="windows",columns:process.stdout.columns||80,rows:process.stdout.rows||24,interactive:n,stdoutTTY:o}}function H(s){let e=s??I();return e.nerdFont?Kh:e.unicode?Yh:Xh}function Me(s){return(s??I()).unicode?Qh:Zh}var Kh,Yh,Xh,Qh,Zh,_e=G(()=>{"use strict";X();Kh={file:"\uF0F6",folder:"\uF07B",tool:"\uF0AD",search:"\uF002",git:"\uE725",browser:"\uF0AC",mcp:"\uF1E6",web:"\uF0AC",success:"\uF058",error:"\uF057",warning:"\uF071",info:"\uF05A",spinner:"\u28FB",arrow:"\uF061",bullet:"\u25CF",checkmark:"\uF00C",cross:"\uF00D",lock:"\uF023",unlock:"\uF09C",message:"\uF075",rocket:"\uF135",thinking:"\uF0EB",terminal:"\uF120",edit:"\uF044",delete:"\uF1F8",add:"\uF055",cost:"\uF155",model:"\uF544",branch:"\uE725",hook:"\uF0C1",skill:"\uF0EB",sandbox:"\uF132",prompt:"\uF054"},Yh={file:"\u25C7",folder:"\u25C6",tool:"\u2699",search:"\u25CE",git:"\u2325",browser:"\u25C9",mcp:"\u2299",web:"\u25C9",success:"\u2713",error:"\u2717",warning:"\u25B2",info:"\u25CF",spinner:"\u280B",arrow:"\u2192",bullet:"\u2022",checkmark:"\u2713",cross:"\u2717",lock:"\u25C6",unlock:"\u25C7",message:"\u25B8",rocket:"\u27EB",thinking:"\u25CC",terminal:"\u25B6",edit:"\u270E",delete:"\u2715",add:"+",cost:"$",model:"\u25C8",branch:"\u2442",hook:"\u27F3",skill:"\u2605",sandbox:"\u25C6",prompt:"\u276F"},Xh={file:"[F]",folder:"[D]",tool:"[T]",search:"[S]",git:"[G]",browser:"[W]",mcp:"[M]",web:"[W]",success:"[OK]",error:"[ERR]",warning:"[!]",info:"[i]",spinner:"|",arrow:"->",bullet:"*",checkmark:"+",cross:"x",lock:"[LOCKED]",unlock:"[OPEN]",message:"[MSG]",rocket:"[>>]",thinking:"[...]",terminal:"[$]",edit:"[E]",delete:"[-]",add:"[+]",cost:"[$]",model:"[M]",branch:"[B]",hook:"[H]",skill:"[S]",sandbox:"[S]",prompt:">"},Qh={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Zh={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(ey,"detectNerdFont");l(I,"detectCapabilities");l(H,"getIcons");l(Me,"getBoxChars")});function Hs(){if(yt)return yt;let s=process.platform;return s==="darwin"&&$u("security")?(yt=new aa,yt):s==="linux"&&$u("secret-tool")?(yt=new ca,yt):s==="win32"?(yt=new la,yt):(yt=new ua,yt)}function $u(s){try{return(0,rt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function Cu(s){return s.replace(/[\\"$`!]/g,"\\$&")}function ky(){try{if(process.platform==="linux")return me.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,rt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${Qo.hostname()}-${Qo.userInfo().username}-${Qo.homedir()}`}var me,oo,Qo,Pt,rt,to,aa,ca,la,ua,yt,_u=G(()=>{"use strict";me=b(require("node:fs"),1),oo=b(require("node:path"),1),Qo=b(require("node:os"),1),Pt=b(require("node:crypto"),1),rt=require("node:child_process");X();to="monkeyscode-cli",aa=class{static{l(this,"KeychainStore")}get(e){try{return(0,rt.execSync)(`security find-generic-password -s "${to}" -a "${e}" -w 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){this.delete(e);try{(0,rt.execSync)(`security add-generic-password -s "${to}" -a "${e}" -w "${Cu(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,rt.execSync)(`security delete-generic-password -s "${to}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ca=class{static{l(this,"SecretToolStore")}get(e){try{return(0,rt.execSync)(`secret-tool lookup service "${to}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,rt.execSync)(`echo -n "${Cu(t)}" | secret-tool store --label="${to}:${e}" service "${to}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,rt.execSync)(`secret-tool clear service "${to}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},la=class{static{l(this,"WinCredStore")}get(e){try{let t=`${to}:${e}`,o=`
|
|
31
|
+
`,n)}while(o!==-1);return r+=s.slice(n),r}var ou=W(()=>{l(eu,"stringReplaceAll");l(tu,"stringEncaseCRLFWithFirstIndex")});function Ws(s){return Gg(s)}var su,nu,Hi,es,Us,ru,ts,Hg,Gg,Gi,qg,Vg,qi,Xn,Jg,zg,$D,a,H=W(()=>{Kl();Zl();ou();({stdout:su,stderr:nu}=Ql),Hi=Symbol("GENERATOR"),es=Symbol("STYLER"),Us=Symbol("IS_EMPTY"),ru=["ansi","ansi","ansi256","ansi16m"],ts=Object.create(null),Hg=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=su?su.level:0;s.level=e.level===void 0?t:e.level},"applyOptions"),Gg=l(s=>{let e=l((...t)=>t.join(" "),"chalk");return Hg(e,s),Object.setPrototypeOf(e,Ws.prototype),e},"chalkFactory");l(Ws,"createChalk");Object.setPrototypeOf(Ws.prototype,Function.prototype);for(let[s,e]of Object.entries(rt))ts[s]={get(){let t=Xn(this,qi(e.open,e.close,this[es]),this[Us]);return Object.defineProperty(this,s,{value:t}),t}};ts.visible={get(){let s=Xn(this,this[es],!0);return Object.defineProperty(this,"visible",{value:s}),s}};Gi=l((s,e,t,...o)=>s==="rgb"?e==="ansi16m"?rt[t].ansi16m(...o):e==="ansi256"?rt[t].ansi256(rt.rgbToAnsi256(...o)):rt[t].ansi(rt.rgbToAnsi(...o)):s==="hex"?Gi("rgb",e,t,...rt.hexToRgb(...o)):rt[t][s](...o),"getModelAnsi"),qg=["rgb","hex","ansi256"];for(let s of qg){ts[s]={get(){let{level:t}=this;return function(...o){let n=qi(Gi(s,ru[t],"color",...o),rt.color.close,this[es]);return Xn(this,n,this[Us])}}};let e="bg"+s[0].toUpperCase()+s.slice(1);ts[e]={get(){let{level:t}=this;return function(...o){let n=qi(Gi(s,ru[t],"bgColor",...o),rt.bgColor.close,this[es]);return Xn(this,n,this[Us])}}}}Vg=Object.defineProperties(()=>{},{...ts,level:{enumerable:!0,get(){return this[Hi].level},set(s){this[Hi].level=s}}}),qi=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"),Xn=l((s,e,t)=>{let o=l((...n)=>Jg(o,n.length===1?""+n[0]:n.join(" ")),"builder");return Object.setPrototypeOf(o,Vg),o[Hi]=s,o[es]=e,o[Us]=t,o},"createBuilder"),Jg=l((s,e)=>{if(s.level<=0||!e)return s[Us]?"":e;let t=s[es];if(t===void 0)return e;let{openAll:o,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=eu(e,t.close,t.open),t=t.parent;let r=e.indexOf(`
|
|
32
|
+
`);return r!==-1&&(e=tu(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Ws.prototype,ts);zg=Ws(),$D=Ws({level:nu?nu.level:0}),a=zg});var du=le((qD,ry)=>{ry.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 ta=le((VD,mu)=>{"use strict";var or=Object.assign({},du()),pu=Object.keys(or);Object.defineProperty(or,"random",{get(){let s=Math.floor(Math.random()*pu.length),e=pu[s];return or[e]}});mu.exports=or});var $u=le((kS,_u)=>{_u.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 To={};Ae(To,{detectPlatform:()=>Se,ensureDir:()=>nr,getPlatformInfo:()=>$e,getPlatformPaths:()=>A,isLocalModel:()=>Cy,isUNCPath:()=>_y,normalizePath:()=>xy,resolveSymlinks:()=>$y});function Se(){switch(Ot.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function A(s){switch(s??Se()){case"macos":{let t=Ot.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=Ot.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=Fo.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=Fo.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(Ot.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(Ot.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=Se();return{os:s,arch:Ot.arch(),shell:vy(s),supportsColor:Dy(),supportsUnicode:Sy(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function vy(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 Dy(){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 Sy(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 nr(s){Fo.mkdirSync(s,{recursive:!0})}function xy(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function _y(s){return s.startsWith("\\\\")||s.startsWith("//")}function $y(s){try{return Fo.realpathSync(s)}catch{return s}}function Cy(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 Ot,se,Fo,Z=W(()=>{"use strict";Ot=w(require("node:os"),1),se=w(require("node:path"),1),Fo=w(require("node:fs"),1);l(Se,"detectPlatform");l(A,"getPlatformPaths");l($e,"getPlatformInfo");l(vy,"detectShell");l(Dy,"detectColorSupport");l(Sy,"detectUnicodeSupport");l(nr,"ensureDir");l(xy,"normalizePath");l(_y,"isUNCPath");l($y,"resolveSymlinks");l(Cy,"isLocalModel")});function Py(){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=$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=Py();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 G(s){let e=s??j();return e.nerdFont?Ey:e.unicode?Fy:Ty}function Me(s){return(s??j()).unicode?Ry:Ay}var Ey,Fy,Ty,Ry,Ay,Ce=W(()=>{"use strict";Z();Ey={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"},Fy={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"},Ty={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:">"},Ry={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Ay={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(Py,"detectNerdFont");l(j,"detectCapabilities");l(G,"getIcons");l(Me,"getBoxChars")});function Ks(){if(bt)return bt;let s=process.platform;return s==="darwin"&&Uu("security")?(bt=new ya,bt):s==="linux"&&Uu("secret-tool")?(bt=new wa,bt):s==="win32"?(bt=new ba,bt):(bt=new ka,bt)}function Uu(s){try{return(0,at.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function Wu(s){return s.replace(/[\\"$`!]/g,"\\$&")}function Zy(){try{if(process.platform==="linux")return me.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,at.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${ss.hostname()}-${ss.userInfo().username}-${ss.homedir()}`}var me,ao,ss,jt,at,io,ya,wa,ba,ka,bt,Hu=W(()=>{"use strict";me=w(require("node:fs"),1),ao=w(require("node:path"),1),ss=w(require("node:os"),1),jt=w(require("node:crypto"),1),at=require("node:child_process");Z();io="monkeyscode-cli",ya=class{static{l(this,"KeychainStore")}get(e){try{return(0,at.execSync)(`security find-generic-password -s "${io}" -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,at.execSync)(`security add-generic-password -s "${io}" -a "${e}" -w "${Wu(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,at.execSync)(`security delete-generic-password -s "${io}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},wa=class{static{l(this,"SecretToolStore")}get(e){try{return(0,at.execSync)(`secret-tool lookup service "${io}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,at.execSync)(`echo -n "${Wu(t)}" | secret-tool store --label="${io}:${e}" service "${io}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,at.execSync)(`secret-tool clear service "${io}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ba=class{static{l(this,"WinCredStore")}get(e){try{let t=`${io}:${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,64 +38,64 @@ 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{me.existsSync(t)&&me.unlinkSync(t)}catch{}}getFilePath(e){let t=A();return
|
|
42
|
-
${p}`)}let n=await o.json(),r=n.user_code||"\u2014",i=n.verification_uri;console.log(t?` ${e.info} Open this URL in your browser:`:" Open this URL in your browser:"),console.log(""),console.log(t?` ${a.underline.cyan(i)}`:` ${i}`),console.log("");try{let{exec:p}=await import("node:child_process"),
|
|
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 tr,Tu=G(()=>{"use strict";l(Fu,"parseSSEStream");tr=class{static{l(this,"ToolCallAccumulator")}_calls=new Map;feed(e){for(let t of e){let o=this._calls.get(t.index);t.id&&t.function?.name?this._calls.set(t.index,{id:t.id,name:t.function.name,arguments:t.function.arguments||""}):o&&t.function?.arguments&&(o.arguments+=t.function.arguments)}}flush(){let e=Array.from(this._calls.values());return this._calls.clear(),e}get hasPending(){return this._calls.size>0}}});function Au(s=!0){return s?Ru:Ru.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var Ru,Pu=G(()=>{"use strict";Ru=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files are returned WHOLE unless they exceed ~200K chars or 6000 lines, in which case you get head + tail with an exact pointer to the omitted span. PREFER ONE LARGE READ over several ranged reads \u2014 reading a whole file once is far cheaper than probing it with multiple range calls. Use start_line/end_line only when you already know the exact span you need, or full:true to force the entire file. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(Au,"getToolSchemas")});var Se={};Ae(Se,{getSetting:()=>xy,loadSettings:()=>K,saveSettings:()=>Sy});function K(){let s=A(),e=Da.join(s.config,"settings.json");try{if(so.existsSync(e)){let t=JSON.parse(so.readFileSync(e,"utf8"));return{...Ou,...t}}}catch{}return{...Ou}}function Sy(s){let e=A();so.mkdirSync(e.config,{recursive:!0});let t=Da.join(e.config,"settings.json"),n={...K(),...s};so.writeFileSync(t,JSON.stringify(n,null,2))}function xy(s){return K()[s]}var so,Da,Ou,Q=G(()=>{"use strict";so=b(require("node:fs"),1),Da=b(require("node:path"),1);X();Ou={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",agentsUrl:process.env.MONKEYSCODE_AGENTS_URL||"https://agents.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(K,"loadSettings");l(Sy,"saveSettings");l(xy,"getSetting")});var B,le,Ue,va,$y,or,Mu=G(()=>{"use strict";B=b(require("node:fs"),1),le=b(require("node:path"),1),Ue=require("node:child_process"),va=require("node:fs"),$y={write_file:"create_file",list_files:"list_dir",list_directory:"list_dir",search_code:"grep_search",execute_command:"run_command",view_file:"read_file",str_replace:"replace_in_file",str_replace_editor:"replace_in_file",str_replace_based_edit_tool:"replace_in_file",bash:"run_command",bash_tool:"run_command",shell:"run_command",terminal:"run_command",text_editor:"edit_file",apply_patch:"patch_file",container_exec:"run_command",file_search:"search_files",codebase_search:"grep_search",semantic_search:"grep_search",grep:"grep_search",ripgrep:"grep_search",find_files:"search_files",glob:"search_files",glob_file_search:"search_files",ls:"list_dir",read:"read_file",cat:"read_file",write:"create_file",edit:"edit_file",multi_edit:"edit_file",search_replace:"replace_in_file",run_terminal_cmd:"run_command",run_in_terminal:"run_command",web_fetch:"read_url",fetch_webpage:"read_url",search_web:"web_search",google_search:"web_search",move_file:"rename_file",remove_file:"delete_file",task:"spawn_subagent",subagent:"spawn_subagent"},or=class{static{l(this,"ToolExecutor")}workspace;platformUrl;token;signal;_checkpoints=new Map;_runId="";_mcpClient;_sandbox;constructor(e){this.workspace=e.workspace,this.platformUrl=e.platformUrl,this.token=e.token,this.signal=e.signal}setRunId(e){this._runId=e,this._checkpoints.clear()}setMCPClient(e){this._mcpClient=e}setSandbox(e){this._sandbox=e}async execute(e,t){let o=$y[e]||e;switch(o){case"read_file":return this.readFile(t);case"create_file":return this.createFile(t);case"edit_file":return this.editFile(t);case"delete_file":return this.deleteFile(t);case"rename_file":return this.renameFile(t);case"list_dir":return this.listDir(t);case"grep_search":return this.grepSearch(t);case"glob_files":return this.globFiles(t);case"search_files":return this.searchFiles(t);case"replace_in_file":return this.replaceInFile(t);case"patch_file":return this.patchFile(t);case"run_command":return this.runCommand(t);case"run_tests":return this.runTests(t);case"web_search":return this.webSearch(t);case"read_url":return this.readUrl(t);case"git_status":return this.gitExec("status",t);case"git_diff":return this.gitDiff(t);case"git_log":return this.gitLog(t);case"git_commit":return this.gitCommit(t);case"git_stash":return this.gitExec("stash",t);case"git_stash_pop":return this.gitExec("stash pop",t);case"todo_write":return this.todoWrite(t);case"spawn_subagent":return this.spawnSubagent(t);case"remember":return this.remember(t);default:return o.startsWith("mcp_")&&this._mcpClient?this._executeMCPTool(o,t):{output:`Unknown tool: ${e}. Use one of: read_file, create_file, edit_file, replace_in_file, patch_file, run_command, run_tests, grep_search, search_files, list_dir, git_status, git_commit, web_search, read_url, ask_user, todo_write, spawn_subagent, remember, or mcp_<server>_<tool>`}}}getCheckpoints(){return this._checkpoints}readFile(e){let t=this.resolve(e.path);if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}`};if(B.statSync(t).isDirectory())return{output:`Error: ${e.path} is a directory. Use list_dir instead.`};let n=B.readFileSync(t,"utf8"),r=n.split(`
|
|
46
|
-
`),i=r.length,c=e.full,u=2e5,d=6e3,p=4e3,
|
|
41
|
+
`;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{me.existsSync(t)&&me.unlinkSync(t)}catch{}}getFilePath(e){let t=A();return ao.join(t.config,`cred-${e}.enc`)}getDpapi(e){let t=this.getFilePath(e);try{if(!me.existsSync(t))return null;let o=me.readFileSync(t,"utf8");return(0,at.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,at.execSync)(`powershell -NoProfile -Command "Add-Type -AssemblyName System.Security; [System.Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF8.GetBytes('${t.replace(/'/g,"''")}'), $null, 'CurrentUser'))"`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"});me.mkdirSync(ao.dirname(o),{recursive:!0}),me.writeFileSync(o,n.trim(),{mode:384})}catch{throw new Error("Failed to encrypt credential via DPAPI")}}},ka=class{static{l(this,"EncryptedFileStore")}keyPath;storePath;constructor(){let e=A();this.keyPath=ao.join(e.config,".cred-key"),this.storePath=ao.join(e.config,"credentials.enc")}get(e){return this.loadStore()[e]||null}set(e,t){let o=this.loadStore();o[e]=t,this.saveStore(o)}delete(e){let t=this.loadStore();delete t[e],this.saveStore(t)}getOrCreateKey(){try{if(me.existsSync(this.keyPath))return Buffer.from(me.readFileSync(this.keyPath,"utf8"),"hex")}catch{}let e=Zy(),t=jt.randomBytes(16),o=jt.scryptSync(e,t,32),n=t.toString("hex")+":"+o.toString("hex");return me.mkdirSync(ao.dirname(this.keyPath),{recursive:!0}),me.writeFileSync(this.keyPath,n,{mode:384}),o}loadStore(){try{if(!me.existsSync(this.storePath))return{};let e=me.readFileSync(this.storePath,"utf8"),[t,o]=e.split(":"),n=this.getOrCreateKey(),r=Buffer.from(t,"hex"),i=jt.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=jt.randomBytes(16),n=jt.createCipheriv("aes-256-cbc",t,o),r=n.update(JSON.stringify(e),"utf8","hex");r+=n.final("hex"),me.mkdirSync(ao.dirname(this.storePath),{recursive:!0}),me.writeFileSync(this.storePath,o.toString("hex")+":"+r,{mode:384})}},bt=null;l(Ks,"getCredentialStore");l(Uu,"hasCommand");l(Wu,"escapeShellArg");l(Zy,"getMachineId")});var he={};Ae(he,{authLogin:()=>Da,authLoginEmail:()=>Sa,authLoginSSO:()=>Fa,authLogout:()=>xa,authLogoutProfile:()=>Ta,authRefresh:()=>$a,authSetToken:()=>_a,authStatus:()=>cr,getAccessToken:()=>Fe,isAuthenticated:()=>Ea,loadAuth:()=>fe});async function Da(){let s=j(),e=G(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("");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 e0(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 Ca(f.access_token),h=Date.now()+(f.expires_in||172800)*1e3;ns({access_token:f.access_token,refresh_token:f.refresh_token,expires_at:h,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 Sa(){let s=j(),e=G(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=Gu.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 t0(" 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 Ca(u.access_token),p=Date.now()+(u.expires_in||172800)*1e3;ns({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 xa(){let s=G(),e=A();try{let o=Ks(),n=`${va}-default`;o.delete(n)}catch{}let t=Nt.join(e.config,"auth.json");Ee.existsSync(t)&&Ee.unlinkSync(t),console.log(` ${s.success} Logged out.`),console.log("")}function _a(s,e){let t=G();ns({access_token:s,auth_method:"apikey",profile:e},e),console.log(` ${t.success} Token saved${e?` (profile: ${e})`:""}.`),console.log("")}async function cr(s){let e=j(),t=G(e),o=e.ansi,n=fe(s);if(console.log(""),n){let r=n.auth_method||"unknown",i={oauth:"\u{1F510} OAuth (browser)",apikey:"\u{1F511} API Key",email:"\u{1F4E7} Email/Password",sso:"\u{1F3E2} Enterprise SSO",env:"\u{1F30D} Environment Variable",unknown:"\u2753 Unknown"};if(console.log(` Auth: ${t.success} logged in`),console.log(` Method: ${i[r]||r}`),s&&s!=="default"&&console.log(` Profile: ${s}`),n.user?.email&&console.log(` User: ${n.user.email}`),n.user?.name&&console.log(` Name: ${n.user.name}`),n.org?.name&&console.log(` Org: ${n.org.name} (${n.org.plan||"free"})`),n.expires_at){let u=n.expires_at-Date.now();if(u>0){let d=Math.floor(u/36e5),p=Math.floor(d/24),f=p>0?`${p}d ${d%24}h`:`${d}h`;console.log(o?a.dim(` Expires: ${f}`):` Expires: ${f}`)}else console.log(o?a.yellow(` ${t.warning} Token expired \u2014 run: mc auth refresh`):` ${t.warning} Token expired`)}try{let u=await Fe(s);if(u){let d=await fetch(`${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 $a(){let s=j(),e=G(s),t=fe();if(!t?.refresh_token){console.log(` ${e.error} No refresh token found. Run: mc auth login`);return}console.log(" Refreshing token...");try{let o=await fetch(`${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;ns({...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 Ca(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 fe(s){let e=process.env.MONKEYSCODE_API_KEY||process.env.MC_TOKEN||process.env.MONKEYSCODE_AUTH_TOKEN;if(e)return{access_token:e,auth_method:"env"};let t=s||"default",o=`${va}-${t}`;try{let c=Ks().get(o);if(c)return JSON.parse(c)}catch{}let n=A(),r=t==="default"?Nt.join(n.config,"auth.json"):Nt.join(n.config,`auth-${t}.json`);try{if(Ee.existsSync(r)){let i=JSON.parse(Ee.readFileSync(r,"utf8"));try{Ks().set(o,JSON.stringify(i)),Ee.unlinkSync(r)}catch{}return i}}catch{}return null}function Ea(){return fe()!==null}async function Fe(s){let e=fe(s);if(!e?.access_token)return null;if(e.expires_at&&e.expires_at<Date.now()&&e.refresh_token){process.stderr.write(` \u{1F504} Refreshing auth token...
|
|
43
|
+
`);try{let t=await fetch(`${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 ns({...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 ns(s,e){let t=e||s.profile||"default",o=`${va}-${t}`;try{Ks().set(o,JSON.stringify({...s,profile:t}))}catch{let n=A();Ee.mkdirSync(n.config,{recursive:!0});let r=t==="default"?Nt.join(n.config,"auth.json"):Nt.join(n.config,`auth-${t}.json`);Ee.writeFileSync(r,JSON.stringify({...s,profile:t},null,2),{mode:384})}}function e0(s){return new Promise(e=>setTimeout(e,s))}function t0(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 Fa(s){let e=j(),t=G(e),o=e.ansi,n=A(),r=Nt.join(n.config,"config.json"),i={};try{Ee.existsSync(r)&&(i=JSON.parse(Ee.readFileSync(r,"utf8")))}catch{}let c=i.auth?.ssoUrl,u=i.auth?.ssoClientId,d=i.auth?.ssoProvider||"OIDC";if(!c){console.log(""),console.log(` ${t.error} SSO not configured.`),console.log(""),console.log(" Add SSO configuration to your global config:"),console.log(o?a.dim(` ${r}`):` ${r}`),console.log(""),console.log(" {"),console.log(' "auth": {'),console.log(' "method": "sso",'),console.log(' "ssoProvider": "okta",'),console.log(' "ssoUrl": "https://myorg.okta.com/app/monkeyscode/sso",'),console.log(' "ssoClientId": "0oaXXXXXX"'),console.log(" }"),console.log(" }"),console.log("");return}console.log(""),console.log(o?a.bold(` \u{1F3E2} Enterprise SSO (${d})`):` Enterprise SSO (${d})`),console.log("");let p=9876,f=`http://localhost:${p}/callback`,m=Math.random().toString(36).slice(2),h=new URL(c);h.searchParams.set("client_id",u||"monkeyscode-cli"),h.searchParams.set("redirect_uri",f),h.searchParams.set("response_type","code"),h.searchParams.set("scope","openid profile email"),h.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(h.toString())}`:` ${h.toString()}`),console.log("");try{let{exec:v}=await import("node:child_process"),_=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";v(`${_} "${h.toString()}"`)}catch{}let{createServer:g}=await import("node:http"),x=await new Promise(v=>{let _=g((S,k)=>{let C=new URL(S.url||"/",`http://localhost:${p}`);if(C.pathname==="/callback"){let J=C.searchParams.get("code");if(C.searchParams.get("state")!==m){k.writeHead(400,{"Content-Type":"text/html"}),k.end("<html><body><h2>\u274C State mismatch. Please try again.</h2></body></html>"),_.close(),v(null);return}k.writeHead(200,{"Content-Type":"text/html"}),k.end("<html><body><h2>\u2705 Authentication successful!</h2><p>You can close this tab.</p></body></html>"),_.close(),v(J)}else k.writeHead(404),k.end()});_.listen(p,()=>{console.log(o?a.dim(` Listening on http://localhost:${p}/callback ...`):` Listening on http://localhost:${p}/callback ...`)}),setTimeout(()=>{_.close(),v(null)},3e5)});if(!x){console.log(` ${t.error} SSO login failed or timed out.`),console.log("");return}try{let v=await fetch(`${Oe}/v1/auth/sso/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,redirect_uri:f,client_id:u||"monkeyscode-cli"})});if(!v.ok)throw new Error(`Token exchange failed: HTTP ${v.status}`);let _=await v.json(),S=await Ca(_.access_token),k=Date.now()+(_.expires_in||172800)*1e3;ns({access_token:_.access_token,refresh_token:_.refresh_token,expires_at:k,auth_method:"sso",user:S?{id:S.id?.toString(),email:S.email,name:S.name,avatar_url:S.avatar_url??void 0}:void 0,org:S?.orgs?.[0]?{id:S.orgs[0].id?.toString(),name:S.orgs[0].name,plan:S.orgs[0].plan_code}:void 0},s),console.log(""),console.log(` ${t.success} SSO login successful!`),S&&console.log(` ${t.info} ${S.email} (${S.orgs?.[0]?.plan_code||"enterprise"})`),console.log("")}catch(v){console.error(` ${t.error} SSO token exchange failed: ${v instanceof Error?v.message:v}`),console.log("")}}function Ta(s){let e=G(),t=A(),o=s||"default",n=o==="default"?Nt.join(t.config,"auth.json"):Nt.join(t.config,`auth-${o}.json`);Ee.existsSync(n)&&Ee.unlinkSync(n),console.log(` ${e.success} Logged out${o!=="default"?` (profile: ${o})`:""}.`),console.log("")}var Ee,Nt,Gu,Oe,va,ee=W(()=>{"use strict";Ee=w(require("node:fs"),1),Nt=w(require("node:path"),1),Gu=w(require("node:readline"),1);H();Z();Ce();Hu();Oe=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com",va="auth";l(Da,"authLogin");l(Sa,"authLoginEmail");l(xa,"authLogout");l(_a,"authSetToken");l(cr,"authStatus");l($a,"authRefresh");l(Ca,"fetchProfile");l(fe,"loadAuth");l(Ea,"isAuthenticated");l(Fe,"getAccessToken");l(ns,"saveAuth");l(e0,"sleep");l(t0,"askPassword");l(Fa,"authLoginSSO");l(Ta,"authLogoutProfile")});async function*qu(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 lr,Vu=W(()=>{"use strict";l(qu,"parseSSEStream");lr=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 zu(s=!0){return s?Ju:Ju.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var Ju,Ku=W(()=>{"use strict";Ju=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files are returned WHOLE unless they exceed ~200K chars or 6000 lines, in which case you get head + tail with an exact pointer to the omitted span. PREFER ONE LARGE READ over several ranged reads \u2014 reading a whole file once is far cheaper than probing it with multiple range calls. Use start_line/end_line only when you already know the exact span you need, or full:true to force the entire file. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(zu,"getToolSchemas")});var we={};Ae(we,{getSetting:()=>s0,loadSettings:()=>Y,saveSettings:()=>o0});function Y(){let s=A(),e=Ra.join(s.config,"settings.json");try{if(co.existsSync(e)){let t=JSON.parse(co.readFileSync(e,"utf8"));return{...Yu,...t}}}catch{}return{...Yu}}function o0(s){let e=A();co.mkdirSync(e.config,{recursive:!0});let t=Ra.join(e.config,"settings.json"),n={...Y(),...s};co.writeFileSync(t,JSON.stringify(n,null,2))}function s0(s){return Y()[s]}var co,Ra,Yu,Q=W(()=>{"use strict";co=w(require("node:fs"),1),Ra=w(require("node:path"),1);Z();Yu={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",agentsUrl:process.env.MONKEYSCODE_AGENTS_URL||"https://agents.monkeyscode.com",apiUrl:process.env.MONKEYSCODE_API_URL||process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(Y,"loadSettings");l(o0,"saveSettings");l(s0,"getSetting")});var U,ue,We,Aa,n0,ur,Xu=W(()=>{"use strict";U=w(require("node:fs"),1),ue=w(require("node:path"),1),We=require("node:child_process"),Aa=require("node:fs"),n0={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"},ur=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=n0[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(!U.existsSync(t))return{output:`Error: File not found: ${e.path}`};if(U.statSync(t).isDirectory())return{output:`Error: ${e.path} is a directory. Use list_dir instead.`};let n=U.readFileSync(t,"utf8"),r=n.split(`
|
|
46
|
+
`),i=r.length,c=e.full,u=2e5,d=6e3,p=4e3,f=2e3,m=l((_,S)=>_.map((k,C)=>`${String(S+C).padStart(5)} ${k}`),"numberFrom");if(e.start_line!==void 0||e.end_line!==void 0){let _=Math.max(1,e.start_line||1),S=Math.min(i,e.end_line||i);if(_>i)return{output:`Error: start_line ${_} is beyond end of file (${i} lines)`};let k=m(r.slice(_-1,S),_);return{output:`File: ${e.path} \u2014 lines ${_}-${S} of ${i}
|
|
47
|
+
${k.join(`
|
|
48
|
+
`)}`}}if(c||i<=d&&n.length<=u){let _=m(r,1);return{output:`File: ${e.path} (${i} lines)
|
|
49
|
+
${_.join(`
|
|
50
|
+
`)}`}}let g=p+1,y=i-f,x=y-g+1,v=[...m(r.slice(0,p),1),`
|
|
51
|
+
... lines ${g}-${y} omitted (${x} lines) \u2014 read them with read_file(path:"${e.path}", start_line:${g}, end_line:${y}), or full:true for the entire file ...
|
|
52
|
+
`,...m(r.slice(i-f),y+1)];return{output:`File: ${e.path} (${i} lines, truncated: showing 1-${p} and ${y+1}-${i})
|
|
47
53
|
${v.join(`
|
|
48
|
-
`)}`}}
|
|
49
|
-
${
|
|
50
|
-
`)}`}}let h=p+1,y=i-g,S=y-h+1,D=[...m(r.slice(0,p),1),`
|
|
51
|
-
... lines ${h}-${y} omitted (${S} lines) \u2014 read them with read_file(path:"${e.path}", start_line:${h}, end_line:${y}), or full:true for the entire file ...
|
|
52
|
-
`,...m(r.slice(i-g),y+1)];return{output:`File: ${e.path} (${i} lines, truncated: showing 1-${p} and ${y+1}-${i})
|
|
53
|
-
${D.join(`
|
|
54
|
-
`)}`}}createFile(e){let t=this.resolve(e.path);if(B.existsSync(t))return{output:`Error: File already exists: ${e.path}. Use edit_file to modify it.`};this._checkpoints.set(t,null),B.mkdirSync(le.dirname(t),{recursive:!0}),B.writeFileSync(t,e.content);let o=e.content.split(`
|
|
55
|
-
`).length;return{output:`Created ${e.path} (${o} lines)`,wroteFiles:!0,touchedFiles:[e.path]}}editFile(e){let t=this.resolve(e.path);if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}. Use create_file to create it.`};let o=B.readFileSync(t,"utf8"),n=e.old_string,r=e.new_string;if(!o.includes(n))return{output:`Error: old_string not found in ${e.path}. Make sure the string matches EXACTLY including whitespace and indentation. Read the file first to see current content.`};let i=o.split(n).length-1;if(i>1)return{output:`Error: old_string found ${i} times in ${e.path}. Provide a more specific/longer string to match exactly one occurrence.`};this._checkpoints.has(t)||this._checkpoints.set(t,o);let c=o.replace(n,r);B.writeFileSync(t,c);let u=n.split(`
|
|
54
|
+
`)}`}}createFile(e){let t=this.resolve(e.path);if(U.existsSync(t))return{output:`Error: File already exists: ${e.path}. Use edit_file to modify it.`};this._checkpoints.set(t,null),U.mkdirSync(ue.dirname(t),{recursive:!0}),U.writeFileSync(t,e.content);let o=e.content.split(`
|
|
55
|
+
`).length;return{output:`Created ${e.path} (${o} lines)`,wroteFiles:!0,touchedFiles:[e.path]}}editFile(e){let t=this.resolve(e.path);if(!U.existsSync(t))return{output:`Error: File not found: ${e.path}. Use create_file to create it.`};let o=U.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);U.writeFileSync(t,c);let u=n.split(`
|
|
56
56
|
`).length,d=r.split(`
|
|
57
|
-
`).length;return{output:`Edited ${e.path}: replaced ${u} line(s) with ${d} line(s)`,wroteFiles:!0,touchedFiles:[e.path]}}deleteFile(e){let t=this.resolve(e.path);return
|
|
58
|
-
`)}}listEntries(e,t,o){let n=[],r;try{r=
|
|
59
|
-
`).filter(Boolean);return
|
|
60
|
-
${
|
|
61
|
-
`)}`}:{output:`Found ${
|
|
62
|
-
${
|
|
63
|
-
`)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let p=["-rn","--color=never"];r&&p.push("-F"),i&&p.push("-i"),n&&p.push("--include",n),p.push("--",t,o);let
|
|
57
|
+
`).length;return{output:`Edited ${e.path}: replaced ${u} line(s) with ${d} line(s)`,wroteFiles:!0,touchedFiles:[e.path]}}deleteFile(e){let t=this.resolve(e.path);return U.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,U.readFileSync(t,"utf8")),U.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 U.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,U.readFileSync(t,"utf8")),this._checkpoints.set(o,null),U.mkdirSync(ue.dirname(o),{recursive:!0}),U.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(!U.existsSync(t))return{output:`Error: Directory not found: ${e.path}`};let o=e.recursive,n=this.listEntries(t,o?3:0,"");return n.length===0?{output:`Directory ${e.path||"."} is empty`}:{output:n.join(`
|
|
58
|
+
`)}}listEntries(e,t,o){let n=[],r;try{r=U.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(ue.join(e,c.name),t-1,o+" ");n.push(...u)}}else{let u=U.statSync(ue.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,We.spawnSync)("rg",u,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1048576}),p=200;if(d.status===0&&d.stdout){let f=d.stdout.split(`
|
|
59
|
+
`).filter(Boolean);return f.length>p?{output:`Found ${f.length} matches (showing first ${p} \u2014 narrow with include/path, or set max_count per file):
|
|
60
|
+
${f.slice(0,p).join(`
|
|
61
|
+
`)}`}:{output:`Found ${f.length} match(es):
|
|
62
|
+
${f.join(`
|
|
63
|
+
`)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let p=["-rn","--color=never"];r&&p.push("-F"),i&&p.push("-i"),n&&p.push("--include",n),p.push("--",t,o);let f=(0,We.spawnSync)("grep",p,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1024*1024});if(f.stdout){let m=f.stdout.split(`
|
|
64
64
|
`).filter(Boolean);return m.length>200?{output:`Found ${m.length} matches (showing first 200 \u2014 narrow with include/path):
|
|
65
65
|
`+m.slice(0,200).join(`
|
|
66
66
|
`)}:{output:`Found ${m.length} match(es):
|
|
67
67
|
${m.join(`
|
|
68
|
-
`)}`}}return{output:"No matches found."}}catch(d){return{output:`Search error: ${d instanceof Error?d.message:d}`}}}globFiles(e){let t=e.pattern,o=this.resolve(e.path||".");try{let n=(0,
|
|
69
|
-
`).filter(Boolean).map(i=>
|
|
68
|
+
`)}`}}return{output:"No matches found."}}catch(d){return{output:`Search error: ${d instanceof Error?d.message:d}`}}}globFiles(e){let t=e.pattern,o=this.resolve(e.path||".");try{let n=(0,We.spawnSync)("find",[o,"-type","f","-name",t.replace("**/","")],{cwd:this.workspace,encoding:"utf8",timeout:1e4});if(n.stdout){let r=n.stdout.split(`
|
|
69
|
+
`).filter(Boolean).map(i=>ue.relative(this.workspace,i)).sort();return{output:r.length>0?`Found ${r.length} file(s):
|
|
70
70
|
${r.join(`
|
|
71
|
-
`)}`:"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,
|
|
71
|
+
`)}`:"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,We.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?`
|
|
72
72
|
|
|
73
73
|
STDERR:
|
|
74
|
-
`:"")+p),m||(m=`(no output, exit code ${
|
|
75
|
-
... (output truncated at 100KB)`),m=`Exit code: ${
|
|
76
|
-
${m}`,c({output:m})}),u.on("error",
|
|
74
|
+
`:"")+p),m||(m=`(no output, exit code ${f})`),d.length>102400&&(m=m.slice(0,102400)+`
|
|
75
|
+
... (output truncated at 100KB)`),m=`Exit code: ${f}
|
|
76
|
+
${m}`,c({output:m})}),u.on("error",f=>{c({output:`Command failed: ${f.message}`})}),this.signal&&this.signal.addEventListener("abort",()=>{u.kill("SIGTERM")},{once:!0})})}async webSearch(e){let t=e.query,o=e.max_results||5;try{let n=await fetch(`${this.platformUrl}/v1/tools/search`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify({query:t,max_results:o}),signal:this.signal});if(!n.ok)return{output:`Web search error: ${n.status} ${n.statusText}`};let r=await n.json();return!r.results||r.results.length===0?{output:"No results found."}:{output:r.results.map((c,u)=>`${u+1}. ${c.title}
|
|
77
77
|
${c.url}
|
|
78
78
|
${c.snippet}`).join(`
|
|
79
79
|
|
|
80
80
|
`)}}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)+`
|
|
81
81
|
|
|
82
|
-
... (truncated)`),{output:r}}catch(n){return{output:`Fetch failed: ${n instanceof Error?n.message:n}`}}}gitExec(e,t){try{let o=t.message||void 0,n=`git ${e}`;return o&&(n+=` -m ${JSON.stringify(o)}`),{output:(0,
|
|
82
|
+
... (truncated)`),{output:r}}catch(n){return{output:`Fetch failed: ${n instanceof Error?n.message:n}`}}}gitExec(e,t){try{let o=t.message||void 0,n=`git ${e}`;return o&&(n+=` -m ${JSON.stringify(o)}`),{output:(0,We.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,We.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,We.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,We.execSync)("git add -A",{cwd:this.workspace,encoding:"utf8",timeout:1e4}),{output:(0,We.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:
|
|
83
83
|
${t.map(n=>` ${n.status==="done"?"\u2705":n.status==="in_progress"?"\u{1F504}":"\u2B1C"} [${n.status}] ${n.content}`).join(`
|
|
84
|
-
`)}`}}searchFiles(e){let t=e.pattern,o=e.path||".",n=e.max_results||50;try{let r=this.resolve(o),c=(0,
|
|
84
|
+
`)}`}}searchFiles(e){let t=e.pattern,o=e.path||".",n=e.max_results||50;try{let r=this.resolve(o),c=(0,Aa.globSync)(t,{cwd:r}).filter(p=>{try{return U.statSync(ue.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})`:""}:`+`
|
|
85
85
|
`+u.join(`
|
|
86
|
-
`)}}catch(r){return{output:`Error searching files: ${r.message}`}}}replaceInFile(e){let t=this.resolve(e.path),o=e.old_string,n=e.new_string,r=e.allow_multiple||!1;if(!
|
|
86
|
+
`)}}catch(r){return{output:`Error searching files: ${r.message}`}}}replaceInFile(e){let t=this.resolve(e.path),o=e.old_string,n=e.new_string,r=e.allow_multiple||!1;if(!U.existsSync(t))return{output:`Error: File not found: ${e.path}`};let i=U.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 U.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(!U.existsSync(t))return{output:`Error: File not found: ${e.path}`};let n=U.readFileSync(t,"utf8");this._checkpoints.has(t)||this._checkpoints.set(t,n);try{let r=n.split(`
|
|
87
87
|
`),i=o.split(`
|
|
88
|
-
`),c=[],u=0;for(let d of i)d.startsWith("---")||d.startsWith("+++")||d.startsWith("@@")||(d.startsWith("-")?u++:d.startsWith("+")?c.push(d.slice(1)):(d.startsWith(" ")||d==="")&&u<r.length&&(c.push(r[u]),u++));for(;u<r.length;)c.push(r[u]),u++;return
|
|
89
|
-
`),"utf8"),{output:`Patch applied to ${e.path}`,wroteFiles:!0,touchedFiles:[t]}}catch(r){return{output:`Error applying patch: ${r.message}`}}}runTests(e){let t=e.path,o=e.pattern,n=e.framework||"auto";n==="auto"&&(n=this.detectTestFramework());let r;switch(n){case"jest":r="npx jest --no-coverage",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"vitest":r="npx vitest run",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"mocha":r="npx mocha",t&&(r+=` ${t}`),o&&(r+=` --grep ${JSON.stringify(o)}`);break;case"pytest":r="python -m pytest -v",t&&(r+=` ${t}`),o&&(r+=` -k ${JSON.stringify(o)}`);break;case"go":r="go test -v",t?r+=` ./${t}/...`:r+=" ./...",o&&(r+=` -run ${JSON.stringify(o)}`);break;case"cargo":r="cargo test",o&&(r+=` ${o}`),r+=" -- --nocapture";break;case"dotnet":r="dotnet test --verbosity normal",t&&(r+=` ${t}`),o&&(r+=` --filter ${JSON.stringify(o)}`);break;case"rspec":r="bundle exec rspec",t&&(r+=` ${t}`);break;default:return{output:`Unknown test framework: ${n}. Supported: jest, vitest, mocha, pytest, go, cargo, dotnet, rspec`}}try{let i=(0,
|
|
88
|
+
`),c=[],u=0;for(let d of i)d.startsWith("---")||d.startsWith("+++")||d.startsWith("@@")||(d.startsWith("-")?u++:d.startsWith("+")?c.push(d.slice(1)):(d.startsWith(" ")||d==="")&&u<r.length&&(c.push(r[u]),u++));for(;u<r.length;)c.push(r[u]),u++;return U.writeFileSync(t,c.join(`
|
|
89
|
+
`),"utf8"),{output:`Patch applied to ${e.path}`,wroteFiles:!0,touchedFiles:[t]}}catch(r){return{output:`Error applying patch: ${r.message}`}}}runTests(e){let t=e.path,o=e.pattern,n=e.framework||"auto";n==="auto"&&(n=this.detectTestFramework());let r;switch(n){case"jest":r="npx jest --no-coverage",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"vitest":r="npx vitest run",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"mocha":r="npx mocha",t&&(r+=` ${t}`),o&&(r+=` --grep ${JSON.stringify(o)}`);break;case"pytest":r="python -m pytest -v",t&&(r+=` ${t}`),o&&(r+=` -k ${JSON.stringify(o)}`);break;case"go":r="go test -v",t?r+=` ./${t}/...`:r+=" ./...",o&&(r+=` -run ${JSON.stringify(o)}`);break;case"cargo":r="cargo test",o&&(r+=` ${o}`),r+=" -- --nocapture";break;case"dotnet":r="dotnet test --verbosity normal",t&&(r+=` ${t}`),o&&(r+=` --filter ${JSON.stringify(o)}`);break;case"rspec":r="bundle exec rspec",t&&(r+=` ${t}`);break;default:return{output:`Unknown test framework: ${n}. Supported: jest, vitest, mocha, pytest, go, cargo, dotnet, rspec`}}try{let i=(0,We.execSync)(r,{cwd:this.workspace,encoding:"utf8",timeout:12e4,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0",CI:"1"}});return{output:`[${n}] Tests passed:
|
|
90
90
|
${i.slice(0,8e3)}`}}catch(i){let c=i.stdout||i.stderr||i.message;return{output:`[${n}] Tests failed:
|
|
91
|
-
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=
|
|
92
|
-
`),wroteFiles:p.filesModified.length>0,touchedFiles:p.filesModified}}catch(n){return{output:`Subagent error: ${n.message}`}}}remember(e){let t=e.content,o=e.category||"general";try{let n=
|
|
91
|
+
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=ue.join(this.workspace,"package.json");if(U.existsSync(e)){try{let t=JSON.parse(U.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 U.existsSync(ue.join(this.workspace,"pyproject.toml"))||U.existsSync(ue.join(this.workspace,"setup.py"))||U.existsSync(ue.join(this.workspace,"pytest.ini"))?"pytest":U.existsSync(ue.join(this.workspace,"go.mod"))?"go":U.existsSync(ue.join(this.workspace,"Cargo.toml"))?"cargo":U.existsSync(ue.join(this.workspace,"Gemfile"))?"rspec":(0,Aa.globSync)("**/*.csproj",{cwd:this.workspace}).length>0?"dotnet":"jest"}async spawnSubagent(e){let t=e.task,o=e.model;try{let n=(await Promise.resolve().then(()=>(Q(),we))).loadSettings(),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),he)),{AgentLoop:i}=await Promise.resolve().then(()=>(Xe(),rs)),c=await r();if(!c)return{output:"Error: Not authenticated. Cannot spawn subagent."};let u=new i({platformUrl:n.platformUrl,token:c,model:o||n.defaultModel,workspace:this.workspace,mode:"auto",maxTurns:30,userId:void 0,orgId:void 0}),d=`subagent-${Date.now().toString(36)}`,p=await u.run(t);return{output:[`Subagent ${d} completed:`,` Turns: ${p.turns}`,` Tokens: ${p.tokensIn+p.tokensOut}`,` Files modified: ${p.filesModified.join(", ")||"none"}`,` Duration: ${Math.round(p.duration/1e3)}s`].join(`
|
|
92
|
+
`),wroteFiles:p.filesModified.length>0,touchedFiles:p.filesModified}}catch(n){return{output:`Subagent error: ${n.message}`}}}remember(e){let t=e.content,o=e.category||"general";try{let n=ue.join(this.workspace,".monkeyscode");U.existsSync(n)||U.mkdirSync(n,{recursive:!0});let r=ue.join(n,"MEMORY.md"),i=new Date().toISOString().split("T")[0],c=`
|
|
93
93
|
- [${o}] ${t} _(${i})_
|
|
94
|
-
`,u="";return
|
|
94
|
+
`,u="";return U.existsSync(r)?u=U.readFileSync(r,"utf8"):u=`# Project Memory
|
|
95
95
|
|
|
96
96
|
Facts, conventions, and decisions learned during sessions.
|
|
97
|
-
`,
|
|
98
|
-
`)}}});var
|
|
97
|
+
`,U.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 ue.isAbsolute(e)?e:ue.resolve(this.workspace,e)}}});var dr,Pa=W(()=>{"use strict";dr=["~/.ssh","~/.aws","~/.config/gcloud","~/.config/gh","~/.azure","~/.kube","~/.docker/config.json","~/.npmrc","~/.pypirc","~/.env","~/.netrc","~/.gnupg"]});var Qu,Zu,Ys,Xs,ed=W(()=>{"use strict";Qu=require("node:child_process"),Zu=w(require("node:os"),1),Ys=w(require("node:path"),1);Pa();Xs=class{static{l(this,"BubblewrapProvider")}name="bubblewrap";async isAvailable(){try{return(0,Qu.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=Zu.homedir(),r=[];r.push("--ro-bind","/","/");let i=Ys.resolve(o.workspace);r.push("--bind",i,i),r.push("--tmpfs","/tmp"),r.push("--dev","/dev"),r.push("--proc","/proc");for(let c of dr){let u=c.replace("~",n);r.push("--tmpfs",u)}return r.push("--tmpfs",Ys.join(n,".env")),r.push("--tmpfs",Ys.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 td,Qs,pr,is,Zs,od=W(()=>{"use strict";td=require("node:child_process"),Qs=w(require("node:os"),1),pr=w(require("node:path"),1),is=w(require("node:fs"),1);Pa();Zs=class{static{l(this,"SandboxExecProvider")}name="sandbox-exec";profilePath=null;async isAvailable(){try{return(0,td.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=pr.join(Qs.tmpdir(),`mc-sandbox-${process.pid}.sb`);return is.writeFileSync(r,n,"utf-8"),this.profilePath=r,{command:"sandbox-exec",args:["-f",r,e,...t]}}async setup(e){}async teardown(){this.profilePath&&is.existsSync(this.profilePath)&&(is.unlinkSync(this.profilePath),this.profilePath=null)}generateProfile(e){let t=Qs.homedir(),o=pr.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 "${Qs.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 dr){let i=r.replace("~",t);n.push(`; Block credential: ${r}`),n.push(`(deny file-read* file-write* (subpath "${i}"))`)}return n.push(""),e.network==="none"?(n.push("; Block all network access"),n.push("(deny network*)")):e.network==="local"?(n.push("; Allow localhost only"),n.push('(allow network* (local ip "localhost:*"))'),n.push("(deny network*)")):(n.push("; Full network access"),n.push("(allow network*)")),n.join(`
|
|
98
|
+
`)}}});var Ia,mr,fr,as,en,sd=W(()=>{"use strict";Ia=require("node:child_process"),mr=w(require("node:os"),1),fr=w(require("node:path"),1),as=w(require("node:fs"),1),en=class{static{l(this,"WindowsSandboxProvider")}name="windows-sandbox";wsbConfigPath=null;mode=null;async isAvailable(){if(mr.platform()!=="win32")return{available:!1,reason:"Not running on Windows"};try{return(0,Ia.execSync)("where WindowsSandbox.exe",{stdio:"pipe"}),this.mode="windows-sandbox",{available:!0}}catch{}try{return(0,Ia.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=fr.resolve(e.workspace),o=this.generateWsbConfig(t,e);this.wsbConfigPath=fr.join(mr.tmpdir(),`mc-sandbox-${process.pid}.wsb`),as.writeFileSync(this.wsbConfigPath,o,"utf-8")}}async teardown(){this.wsbConfigPath&&as.existsSync(this.wsbConfigPath)&&(as.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`
|
|
99
99
|
<Configuration>
|
|
100
100
|
<VGpu>Disable</VGpu>
|
|
101
101
|
<Networking>${t.network==="none"?"Disable":"Default"}</Networking>
|
|
@@ -110,7 +110,7 @@ Facts, conventions, and decisions learned during sessions.
|
|
|
110
110
|
<Command>cmd.exe /k cd C:\\Workspace</Command>
|
|
111
111
|
</LogonCommand>
|
|
112
112
|
<MemoryInMB>2048</MemoryInMB>
|
|
113
|
-
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var
|
|
113
|
+
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var lo,Ao,uo,rd,nd,tn,Po,id=W(()=>{"use strict";lo=require("node:child_process"),Ao=w(require("node:path"),1),uo=w(require("node:fs"),1),rd=w(require("node:crypto"),1),nd="monkeyscode-sandbox",tn="/workspace",Po=class{static{l(this,"DockerSandboxProvider")}name="docker";containerId=null;imageName=nd;async isAvailable(){try{return(0,lo.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",tn),n.push(this.containerId),n.push(e,...t);else{n.splice(0),n.push("run","--rm"),n.push("-w",tn);let r=Ao.resolve(o.workspace);n.push("-v",`${r}:${tn}`),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||nd;let t=Ao.resolve(e.workspace),o=e.dockerfilePath||Ao.join(t,".monkeyscode","Dockerfile.sandbox");if(uo.existsSync(o)){let c=(0,lo.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-${rd.randomUUID().substring(0,8)}`,"-w",tn,"-v",`${t}:${tn}`];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,lo.spawnSync)("docker",r,{stdio:"pipe"});i.status===0&&(this.containerId=i.stdout.toString().trim().substring(0,12))}async teardown(){if(this.containerId){try{(0,lo.execSync)(`docker rm -f ${this.containerId}`,{stdio:"pipe",timeout:1e4})}catch{}this.containerId=null}}async ensureBaseImage(){try{(0,lo.execSync)(`docker image inspect ${this.imageName}`,{stdio:"pipe"});return}catch{}let e=`
|
|
114
114
|
FROM ubuntu:22.04
|
|
115
115
|
RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
116
116
|
git curl wget ca-certificates \\
|
|
@@ -121,13 +121,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
|
121
121
|
RUN useradd -m -s /bin/bash sandbox
|
|
122
122
|
USER sandbox
|
|
123
123
|
WORKDIR /workspace
|
|
124
|
-
`.trim(),t=
|
|
124
|
+
`.trim(),t=Ao.join(require("node:os").tmpdir(),"mc-sandbox-build");uo.mkdirSync(t,{recursive:!0}),uo.writeFileSync(Ao.join(t,"Dockerfile"),e);let o=(0,lo.spawnSync)("docker",["build","-t",this.imageName,t],{stdio:"pipe",timeout:3e5});if(uo.rmSync(t,{recursive:!0,force:!0}),o.status!==0)throw new Error(`Failed to build sandbox base image: ${o.stderr?.toString()}`)}}});function ad(s){switch(s){case"linux":return[new Xs,new Po];case"macos":return[new Zs,new Po];case"windows":return[new en,new Po]}}function hr(s,e={}){return{enabled:!1,provider:"auto",network:"none",workspace:s,...e}}var cs,Ma=W(()=>{"use strict";Z();ed();od();sd();id();l(ad,"getProviderCandidates");cs=class{static{l(this,"SandboxManager")}config;provider=null;platform;initialized=!1;constructor(e){this.config=e,this.platform=Se()}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=ad(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=ad(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 Xs;case"sandbox-exec":return new Zs;case"windows-sandbox":case"appcontainer":return new en;case"docker":return new Po;default:return null}}};l(hr,"createDefaultSandboxConfig")});function cd(s){switch(s){case 0:return"allow";case 1:return"deny";case 2:return"modify";default:return"allow"}}var ld,ud=W(()=>{"use strict";l(cd,"exitCodeToAction");ld={enabled:!0,timeoutMs:1e4}});function Io(s){let e=A(),t=kt.join(s,".monkeyscode","hooks"),o=kt.join(e.config,"hooks"),n=dd(t,"project"),r=dd(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 dd(s,e){if(!ls.existsSync(s))return[];let t=[];try{let o=ls.readdirSync(s,{withFileTypes:!0});for(let n of o){if(!n.isFile())continue;let r=kt.extname(n.name).toLowerCase(),i=i0[r];if(!i)continue;let c=kt.basename(n.name,r).toLowerCase(),u=r0[c];u&&t.push({event:u,scriptPath:kt.join(s,n.name),source:e,scriptType:i})}}catch{}return t}function pd(s){let e=A(),t=kt.join(s,".monkeyscode","hooks"),o=kt.join(e.config,"hooks");return[{path:t,source:"project",exists:ls.existsSync(t)},{path:o,source:"global",exists:ls.existsSync(o)}]}var ls,kt,r0,i0,gr=W(()=>{"use strict";ls=w(require("node:fs"),1),kt=w(require("node:path"),1);Z();r0={"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"},i0={".sh":"sh",".bash":"sh",".ps1":"ps1",".cmd":"cmd",".bat":"cmd",".js":"js",".mjs":"js",".py":"py"};l(Io,"loadHooks");l(dd,"scanHookDirectory");l(pd,"getHookDirectories")});var md,Mo,Oa=W(()=>{"use strict";md=require("node:child_process");Z();ud();gr();Mo=class{static{l(this,"HookRunner")}hooks;config;platform=Se();constructor(e,t={}){this.config={...ld,...t},this.hooks=this.config.enabled?Io(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?Io(e):[]}async executeHook(e,t){let o=Date.now();return new Promise(n=>{let{command:r,args:i}=this.getExecutor(e),c=(0,md.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 h=m??0;n({hook:e,exitCode:h,action:p?"allow":cd(h),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 hd(s,e=60){if(!Lt.ansi){console.log(`
|
|
125
125
|
${s}
|
|
126
|
-
${"\u2500".repeat(e)}`);return}let t="\u2500".repeat(Math.max(0,e-s.length-4));console.log(""),console.log(` ${be.accent("\u2500\u2500")} ${be.bold(s)} ${be.accent(t)}`)}function
|
|
127
|
-
`)){let n=o.match(/^(\w+)\s*:\s*(.+)$/);if(!n)continue;let[,r,i]=n;switch(r){case"name":t.name=i.trim();break;case"description":t.description=i.trim();break;case"trigger":t.trigger=i.trim();break;case"priority":t.priority=parseInt(i.trim(),10);break;case"enabled":t.enabled=i.trim().toLowerCase()!=="false";break}}return{meta:t,body:e[2].trim()}}function
|
|
126
|
+
${"\u2500".repeat(e)}`);return}let t="\u2500".repeat(Math.max(0,e-s.length-4));console.log(""),console.log(` ${be.accent("\u2500\u2500")} ${be.bold(s)} ${be.accent(t)}`)}function gd(s,e){let t=" "+s.map(n=>{let r=n.header;return fd(r,n.width,n.align||"left")}).join(" ");console.log(Lt.ansi?be.dim(t):t);let o=" "+s.map(n=>"\u2500".repeat(n.width)).join("\u2500\u2500");console.log(Lt.ansi?be.dim(o):o);for(let n of e){let r=" "+n.cells.map((i,c)=>{let u=s[c];return fd(i,u.width,u.align||"left")}).join(" ");n.dim&&Lt.ansi?r=be.dim(r):n.highlight&&Lt.ansi&&(r=be.accent(r)),console.log(r)}}function fd(s,e,t){let o=c0(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 ja(s){console.log(Lt.ansi?` ${be.dim(s)}`:` ${s}`)}function yd(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 Na(s){return s===0?Lt.ansi?be.success("Free"):"Free":`$${s.toFixed(s<1?4:2)}`}function c0(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}function on(){console.log("")}var a0,be,Lt,d_,p_,wd=W(()=>{"use strict";H();Ce();a0=w(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},Lt=j(),d_=G(Lt),p_=Me(Lt);l(hd,"sectionHeader");l(gd,"printTable");l(fd,"padCell");l(ja,"hint");l(yd,"formatTokens");l(Na,"formatCost");l(c0,"stripAnsi");l(on,"blank")});function vt(s){if(s==="auto")return"auto";let e=s.toLowerCase(),t=Bt.find(r=>r.id===e);if(t)return t.id;let o=Bt.find(r=>r.aliases.some(i=>i.toLowerCase()===e));if(o)return o.id;let n=Bt.find(r=>r.displayName.toLowerCase().includes(e));return n?n.id:s}function yr(s){let e=vt(s);return Bt.find(t=>t.id===e)??null}function l0(s,e){let t=vt(s),o=Bt.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 sn(s,e,t,o=0){let n=Bt.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 La(s){let e=j().ansi,t=j().emoji;hd("Available Models"),on();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=Bt.map(r=>{let i=l0(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":`${Na(r.costInputPerM)} / ${Na(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 h=m.join(" ");return{cells:[e?c?be.dim(r.displayName):a.bold(r.displayName):r.displayName,d,yd(r.contextWindow),p,f,h],dim:c}});if(gd(o,n),on(),e){console.log(` ${be.dim("Aliases:")}`);for(let r of Bt)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 Bt)r.aliases.length>0&&console.log(` ${r.displayName}: ${r.aliases.join(", ")}`)}on(),ja("Use --model <name|alias> to select a model"),ja("Use --model auto for smart routing based on task complexity"),on()}var Bt,wr=W(()=>{"use strict";H();Ce();wd();Bt=[{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(vt,"resolveModelAlias");l(yr,"getModelInfo");l(l0,"checkModelAccess");l(sn,"estimateCost");l(La,"printModelList")});function bd(s,e,t){let o=yr(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:`${Ba.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:`${Ba.openai}/v1/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.openai}`},isDirect:!0,provider:"openai",isAnthropicFormat:!1}:n==="google"&&r.google?{url:`${Ba.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 Ba,kd=W(()=>{"use strict";wr();Ba={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"};l(bd,"resolveModelRoute")});var vd=W(()=>{"use strict"});var Ha={};Ae(Ha,{buildSkillsContext:()=>Wa,listAllSkills:()=>f0,loadSkills:()=>Dd});function d0(s){let e=s.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!e)return{meta:{},body:s.trim()};let t={};for(let o of e[1].split(`
|
|
127
|
+
`)){let n=o.match(/^(\w+)\s*:\s*(.+)$/);if(!n)continue;let[,r,i]=n;switch(r){case"name":t.name=i.trim();break;case"description":t.description=i.trim();break;case"trigger":t.trigger=i.trim();break;case"priority":t.priority=parseInt(i.trim(),10);break;case"enabled":t.enabled=i.trim().toLowerCase()!=="false";break}}return{meta:t,body:e[2].trim()}}function p0(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 m0(s,e,t){let o=po.join(s,"skill.md");if(!Ut.existsSync(o))return null;try{let n=Ut.readFileSync(o,"utf8"),{meta:r,body:i}=d0(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:p0(r.trigger),enabled:r.enabled!==!1,priority:r.priority??50,filePath:o}:null}catch{return null}}function br(s,e){if(!Ut.existsSync(s))return[];try{return Ut.readdirSync(s).filter(t=>{let o=po.join(s,t);return Ut.statSync(o).isDirectory()}).map(t=>m0(po.join(s,t),t,e)).filter(t=>t!==null)}catch{return[]}}function Dd(s){let e=po.join(s,".monkeyscode","skills"),t=po.join(Ua.homedir(),".monkeyscode","skills"),o=br(t,"global"),n=br(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 Wa(s){let e=Dd(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}
|
|
128
128
|
${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
129
129
|
|
|
130
|
-
`):null}function
|
|
130
|
+
`):null}function f0(s){let e=po.join(s,".monkeyscode","skills"),t=po.join(Ua.homedir(),".monkeyscode","skills"),o=br(t,"global"),n=br(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 Ut,po,Ua,kr=W(()=>{"use strict";Ut=w(require("node:fs"),1),po=w(require("node:path"),1),Ua=w(require("node:os"),1);vd();l(d0,"parseFrontmatter");l(p0,"parseTrigger");l(m0,"loadSkillFromDir");l(br,"scanSkillsDir");l(Dd,"loadSkills");l(Wa,"buildSkillsContext");l(f0,"listAllSkills")});function Sd(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(`
|
|
131
131
|
## Available Tools`),o.push("You have access to file operations (read, edit, create, delete, rename, list, search), shell commands, and git operations."),o.push("Always use the appropriate tool rather than guessing file contents. Always read a file before editing it."),o.push(`
|
|
132
132
|
## Task Tracking`),o.push("For any task with 3+ steps, maintain a checklist with todo_write: send the full list every time, keep exactly one item in_progress, and update it immediately after finishing each step."),o.push("Use ask_user when blocked on a genuine decision."),s.webEnabled&&(o.push(`
|
|
133
133
|
## Web Search`),o.push("You can search the web with web_search and fetch URL content with read_url. Use these when you need documentation, error solutions, or information not available in the workspace.")),s.mode){case"plan":o.push(`
|
|
@@ -136,47 +136,47 @@ ${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
|
136
136
|
## Mode: Accept Edits`),o.push("You may make file changes without asking. Be efficient and direct.");break;case"auto":default:o.push(`
|
|
137
137
|
## Mode: Auto`),o.push("Use your judgment on when to proceed and when to ask. For safe, reversible operations, proceed directly.");break}o.push(`
|
|
138
138
|
## Important Guidelines`),o.push("- Be concise in responses. Show code changes, not lengthy explanations."),o.push("- When editing files, use edit_file with the EXACT current content as old_string."),o.push("- When running commands, prefer non-interactive commands (add -y, --yes, etc.)."),o.push(`- Today's date: ${new Date().toISOString().split("T")[0]}`),t.push({role:"system",content:o.join(`
|
|
139
|
-
`),timestamp:e});let n=[];n.push("## Workspace Context"),n.push(`- Path: ${s.workspace}`),n.push(`- Execution: Local terminal (Node.js ${process.version})`),s.sandboxed&&n.push("- Sandbox: Active \u2014 commands run in an isolated environment");let r=
|
|
140
|
-
`),timestamp:e});let c=
|
|
139
|
+
`),timestamp:e});let n=[];n.push("## Workspace Context"),n.push(`- Path: ${s.workspace}`),n.push(`- Execution: Local terminal (Node.js ${process.version})`),s.sandboxed&&n.push("- Sandbox: Active \u2014 commands run in an isolated environment");let r=Wt.basename(s.workspace);n.push(`- Project: ${r}`);let i=h0(s.workspace);i&&n.push(`- Stack: ${i}`),t.push({role:"system",content:n.join(`
|
|
140
|
+
`),timestamp:e});let c=y0(s.workspace);c&&t.push({role:"system",content:`## Workspace Rules
|
|
141
141
|
|
|
142
|
-
${c}`,timestamp:e});let u=
|
|
142
|
+
${c}`,timestamp:e});let u=Wa(s.workspace);u&&t.push({role:"system",content:`## Active Skills
|
|
143
143
|
|
|
144
|
-
${u}`,timestamp:e});let d=
|
|
145
|
-
`),timestamp:e})}return t}function
|
|
144
|
+
${u}`,timestamp:e});let d=g0(s.workspace);if(d){let p=[];p.push("## Current State"),p.push(`- Branch: ${d.branch}${d.dirty?" (uncommitted changes)":""}`),t.push({role:"system",content:p.join(`
|
|
145
|
+
`),timestamp:e})}return t}function h0(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)ct.existsSync(Wt.join(s,o))&&t.push(n);if(ct.existsSync(Wt.join(s,"package.json")))try{let o=JSON.parse(ct.readFileSync(Wt.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 g0(s){try{let e=(0,Ga.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",timeout:3e3,stdio:["pipe","pipe","pipe"]}).trim(),t=(0,Ga.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 y0(s){let e=[];for(let o of["AGENTS.md","CLAUDE.md","GEMINI.md",".monkeyscode/AGENTS.md"]){let n=Wt.join(s,o);if(ct.existsSync(n))try{let r=ct.readFileSync(n,"utf8");r.trim()&&e.push(`### ${o}
|
|
146
146
|
|
|
147
|
-
${r}`)}catch{}}let t=
|
|
147
|
+
${r}`)}catch{}}let t=Wt.join(s,".monkeyscode","rules");if(ct.existsSync(t))try{let o=ct.readdirSync(t).filter(n=>n.endsWith(".md")).sort();for(let n of o){let r=ct.readFileSync(Wt.join(t,n),"utf8");r.trim()&&e.push(`### ${n}
|
|
148
148
|
|
|
149
149
|
${r}`)}}catch{}return e.length>0?e.join(`
|
|
150
150
|
|
|
151
151
|
---
|
|
152
152
|
|
|
153
|
-
`):null}var
|
|
153
|
+
`):null}var ct,Wt,Ga,xd=W(()=>{"use strict";ct=w(require("node:fs"),1),Wt=w(require("node:path"),1),Ga=require("node:child_process");kr();l(Sd,"buildSystemMessages");l(h0,"detectProjectType");l(g0,"getGitInfo");l(y0,"loadWorkspaceRules")});function qa(s){return Math.ceil(s.length/4)}function mo(s,e=6e3){let t=e;for(let o of s)if(t+=qa(o.content),o.tool_calls)for(let n of o.tool_calls)t+=qa(JSON.stringify(n.arguments)),n.result&&(t+=qa(n.result));return t}function Dr(s,e){if(e&&e>0)return e;let t=Va.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 _d(s){Va.clear();for(let e of s)e.id&&e.contextWindow>0&&Va.set(e.id,e.contextWindow)}function $d(s,e,t=.85){return s>=e*t}function w0(s,e){let t=s.split(`
|
|
154
154
|
`),o=Math.floor(e*.7),n=e-o,r=[],i=0;for(let p of t){if(i+p.length+1>o)break;r.push(p),i+=p.length+1}let c=[],u=0;for(let p=t.length-1;p>=r.length&&!(u+t[p].length+1>n);p--)c.unshift(t[p]),u+=t[p].length+1;let d=t.length-r.length-c.length;return d<=0?s:[...r,`
|
|
155
155
|
... [${d} lines trimmed from an older tool result to fit the context window \u2014 re-read the file if you still need this content] ...
|
|
156
156
|
`,...c].join(`
|
|
157
|
-
`)}function
|
|
158
|
-
`)[0].slice(0,100);
|
|
159
|
-
...[summarized]`),
|
|
160
|
-
...[truncated]`),
|
|
161
|
-
`)[0].slice(0,150);
|
|
162
|
-
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-ao(u)}}function mr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var Ia,fr=G(()=>{"use strict";l(Ma,"estimateTokens");l(ao,"estimateContextTokens");l(gr,"resolveContextWindow");Ia=new Map;l(ld,"updateModelCatalog");l(ud,"shouldCompact");l(Ly,"trimToolResult");l(ja,"compactMessages");l(mr,"totalChars")});var es={};Ae(es,{AgentLoop:()=>xe});var dd,By,xe,Ke=G(()=>{"use strict";dd=require("node:events");Tu();Pu();Mu();$a();Ca();nd();Q();cd();fr();By=1/0,xe=class extends dd.EventEmitter{static{l(this,"AgentLoop")}opts;toolExecutor;abortController;state;messages=[];filesModified=new Set;contextWindow;_approvalResolve=null;_userInputResolve=null;_hookRunner;_insideThinkTag=!1;constructor(e){if(super(),this.opts=e,this.abortController=new AbortController,this.toolExecutor=new or({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new ss(ar(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new To(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=gr(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||By;this.updateState({status:"streaming"}),this._hookRunner.fire("SessionStart",{workspace:this.opts.workspace,data:{prompt:e,model:this.opts.model,mode:this.opts.mode}}).catch(()=>{}),this.messages=ad({workspace:this.opts.workspace,mode:this.opts.mode,model:this.opts.model,sandboxed:this.opts.sandboxed||!1,webEnabled:this.opts.webEnabled!==!1}),this.messages.push({role:"user",content:e,timestamp:Date.now()});try{for(let r=0;r<o;r++){if(this.abortController.signal.aborted){this.updateState({status:"cancelled"});break}this.updateState({status:"streaming",turns:r+1}),this.emitEvent({type:"streaming_start"});let i=ao(this.messages);if(ud(i,this.contextWindow)){let u=ja(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=ao(this.messages);this.emitEvent({type:"context_compacted",elided:u.elided,savedTokens:u.savedTokens,contextUsed:d,contextWindow:this.contextWindow})}}let c=await this.streamCompletion();if(!c){this.emitEvent({type:"run_error",error:"No response from model"}),this.updateState({status:"error",error:"No response from model"});break}if(this.messages.push(c),this.emitEvent({type:"streaming_end",content:c.content}),c.tool_calls&&c.tool_calls.length>0){let u=new Set(["read_file","list_dir","grep_search","web_search","read_url","get_file_info","codebase_search","find_symbol"]),d=c.tool_calls.filter(m=>m.name==="ask_user"),p=c.tool_calls.filter(m=>m.name!=="ask_user"&&u.has(m.name)),g=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 f=m.arguments.question||"What would you like to do?";this.updateState({status:"waiting_user_input"}),this.emitEvent({type:"ask_user",question:f});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 f of p)this.emitEvent({type:"tool_call_start",name:f.name,args:f.arguments});this.updateState({status:"tool_executing",currentToolCall:`${p.length} parallel reads`});let m=await Promise.all(p.map(async f=>{let h=await this.toolExecutor.execute(f.name,f.arguments);return{toolCall:f,result:h}}));for(let{toolCall:f,result:h}of m)f.result=h.output,this.emitEvent({type:"tool_call_result",name:f.name,result:h.output}),this.messages.push({role:"tool",content:h.output,tool_call_id:f.id,name:f.name,timestamp:Date.now()})}for(let m of g){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 f=await this._hookRunner.fire("PreToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments}});if(f.some(S=>S.action==="deny")){let S=f.find(D=>D.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${S}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let y=await this.toolExecutor.execute(m.name,m.arguments);if(y.wroteFiles&&y.touchedFiles)for(let S of y.touchedFiles)this.filesModified.add(S);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:y.output.slice(0,1e3),wroteFiles:y.wroteFiles}}).catch(()=>{}),m.result=y.output,this.emitEvent({type:"tool_call_result",name:m.name,result:y.output}),this.messages.push({role:"tool",content:y.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=ja(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=ao(this.messages);return{used:e,window:this.contextWindow,pct:this.contextWindow>0?Math.min(100,Math.round(e/this.contextWindow*100)):0,messageCount:this.messages.length}}getConversationHistory(){return this.messages.map(e=>({role:e.role,content:e.content}))}async streamCompletion(){let e=Au(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(v=>({role:v.role,content:v.content,...v.tool_calls?{tool_calls:v.tool_calls.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))}:{},...v.tool_call_id?{tool_call_id:v.tool_call_id}:{},...v.name?{name:v.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=K(),i=sd(this.opts.model,r,t),c;try{c=await fetch(i.url,{method:"POST",headers:i.headers,body:JSON.stringify(o),signal:this.abortController.signal})}catch(v){if(v instanceof Error&&v.name==="AbortError")return null;throw v}if(!c.ok){let v=await c.text();throw c.status===401?new Error("Authentication failed \u2014 run `mc auth login` to authenticate."):c.status===403?new Error("Access denied \u2014 your plan may not include this model, or your quota is exhausted."):c.status===429?new Error("Rate limited \u2014 please wait a moment and try again."):new Error(`Model API error ${c.status}: ${v}`)}let u="",d=new tr,p="",g=!1,m="",f="<think>",h="</think>",y=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),S=l(v=>{g?(m+=v,h.startsWith(m)?m===h&&(g=!1,m=""):(m="",v==="<"&&(m="<"))):v==="<"&&!m?m="<":m?(m+=v,f.startsWith(m)?m===f&&(g=!0,m=""):h.startsWith(m)?m===h&&(m=""):(p+=m,m="")):p+=v},"feedChar");for await(let v of Fu(c)){if(!v.choices||v.choices.length===0){v.usage&&this.updateState({tokensIn:this.state.tokensIn+(v.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(v.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(v.usage.prompt_tokens_details?.cached_tokens||0)});continue}let E=v.choices[0];if(E.delta?.content){u+=E.delta.content;for(let oe of E.delta.content)S(oe);y()}if(E.delta?.tool_calls&&d.feed(E.delta.tool_calls),E.finish_reason==="tool_calls"||E.finish_reason==="stop")break}m&&!g&&(p+=m),y();let D=d.flush(),x={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return D.length>0&&(x.tool_calls=D.map(v=>{let E={};try{E=JSON.parse(v.arguments)}catch{E={_raw:v.arguments}}return{id:v.id,name:v.name,arguments:E}})),x}getAuthHeaders(){let e={Authorization:`Bearer ${this.opts.token}`};return this.opts.userId&&(e["X-User-Id"]=this.opts.userId),this.opts.orgId&&(e["X-Org-Id"]=this.opts.orgId),e}async waitForUserInput(){return new Promise(e=>{this._userInputResolve=e})}updateState(e){Object.assign(this.state,e),this.emitEvent({type:"state_update",state:{...this.state}})}emitEvent(e){this.emit("event",e)}}});var Bt=ce((C$,$d)=>{"use strict";var Sd=["nodebuffer","arraybuffer","fragments"],xd=typeof Blob<"u";xd&&Sd.push("blob");$d.exports={BINARY_TYPES:Sd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:xd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var Zs=ce((E$,$r)=>{"use strict";var{EMPTY_BUFFER:n0}=Bt(),Wa=Buffer[Symbol.species];function r0(s,e){if(s.length===0)return n0;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),o=0;for(let n=0;n<s.length;n++){let r=s[n];t.set(r,o),o+=r.length}return o<e?new Wa(t.buffer,t.byteOffset,o):t}l(r0,"concat");function Cd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(Cd,"_mask");function _d(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(_d,"_unmask");function i0(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(i0,"toArrayBuffer");function Ha(s){if(Ha.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Wa(s):ArrayBuffer.isView(s)?e=new Wa(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ha.readOnly=!1),e}l(Ha,"toBuffer");$r.exports={concat:r0,mask:Cd,toArrayBuffer:i0,toBuffer:Ha,unmask:_d};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");$r.exports.mask=function(e,t,o,n,r){r<48?Cd(e,t,o,n,r):s.mask(e,t,o,n,r)},$r.exports.unmask=function(e,t){e.length<32?_d(e,t):s.unmask(e,t)}}catch{}});var Td=ce((T$,Fd)=>{"use strict";var Ed=Symbol("kDone"),Ga=Symbol("kRun"),qa=class{static{l(this,"Limiter")}constructor(e){this[Ed]=()=>{this.pending--,this[Ga]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ga]()}[Ga](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ed])}}};Fd.exports=qa});var cs=ce((A$,Od)=>{"use strict";var en=require("zlib"),Rd=Zs(),a0=Td(),{kStatusCode:Ad}=Bt(),c0=Buffer[Symbol.species],l0=Buffer.from([0,0,255,255]),_r=Symbol("permessage-deflate"),Ut=Symbol("total-length"),is=Symbol("callback"),lo=Symbol("buffers"),as=Symbol("error"),Cr,Va=class{static{l(this,"PerMessageDeflate")}constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Cr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cr=new a0(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[is];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,o=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&(typeof n.client_max_window_bits=="number"?t.clientMaxWindowBits>n.client_max_window_bits:!n.client_max_window_bits)));if(!o)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(o.server_no_context_takeover=!0),t.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(o.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?o.client_max_window_bits=t.clientMaxWindowBits:(o.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(o=>{let n=t[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);t[o]=n})}),e}decompress(e,t,o){Cr.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){Cr.add(n=>{this._compress(e,t,(r,i)=>{n(),o(r,i)})})}_decompress(e,t,o){let n=this._isServer?"client":"server";if(!this._inflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=en.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[_r]=this,this._inflate[Ut]=0,this._inflate[lo]=[],this._inflate.on("error",d0),this._inflate.on("data",Pd)}this._inflate[is]=o,this._inflate.write(e),t&&this._inflate.write(l0),this._inflate.flush(()=>{let r=this._inflate[as];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Rd.concat(this._inflate[lo],this._inflate[Ut]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ut]=0,this._inflate[lo]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(e,t,o){let n=this._isServer?"server":"client";if(!this._deflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=en.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Ut]=0,this._deflate[lo]=[],this._deflate.on("data",u0)}this._deflate[is]=o,this._deflate.write(e),this._deflate.flush(en.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Rd.concat(this._deflate[lo],this._deflate[Ut]);t&&(r=new c0(r.buffer,r.byteOffset,r.length-4)),this._deflate[is]=null,this._deflate[Ut]=0,this._deflate[lo]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Od.exports=Va;function u0(s){this[lo].push(s),this[Ut]+=s.length}l(u0,"deflateOnData");function Pd(s){if(this[Ut]+=s.length,this[_r]._maxPayload<1||this[Ut]<=this[_r]._maxPayload){this[lo].push(s);return}this[as]=new RangeError("Max payload size exceeded"),this[as].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[as][Ad]=1009,this.removeListener("data",Pd),this.reset()}l(Pd,"inflateOnData");function d0(s){if(this[_r]._inflate=null,this[as]){this[is](this[as]);return}s[Ad]=1007,this[is](s)}l(d0,"inflateOnError")});var ls=ce((O$,Er)=>{"use strict";var{isUtf8:Md}=require("buffer"),{hasBlob:p0}=Bt(),m0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function g0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(g0,"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 f0(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(f0,"isBlob");Er.exports={isBlob:f0,isValidStatusCode:g0,isValidUTF8:za,tokenChars:m0};if(Md)Er.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");Er.exports.isValidUTF8=function(e){return e.length<32?za(e):s(e)}}catch{}});var Qa=ce((I$,Wd)=>{"use strict";var{Writable:h0}=require("stream"),Id=cs(),{BINARY_TYPES:y0,EMPTY_BUFFER:jd,kStatusCode:b0,kWebSocket:w0}=Bt(),{concat:Ja,toArrayBuffer:k0,unmask:D0}=Zs(),{isValidStatusCode:v0,isValidUTF8:Nd}=ls(),Fr=Buffer[Symbol.species],Ye=0,Ld=1,Bd=2,Ud=3,Ka=4,Ya=5,Tr=6,Xa=class extends h0{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||y0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[w0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Ye}_write(e,t,o){if(this._opcode===8&&this._state==Ye)return o();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){o(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(o)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new Fr(o.buffer,o.byteOffset+e,o.length-e),new Fr(o.buffer,o.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let o=this._buffers[0],n=t.length-e;e>=o.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(o.buffer,o.byteOffset,e),n),this._buffers[0]=new Fr(o.buffer,o.byteOffset+e,o.length-e)),e-=o.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Ye:this.getInfo(e);break;case Ld:this.getPayloadLength16(e);break;case Bd:this.getPayloadLength64(e);break;case Ud:this.getMask();break;case Ka:this.getData(e);break;case Ya:case Tr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let o=(t[0]&64)===64;if(o&&!this._extensions[Id.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Ld:this._payloadLength===127?this._state=Bd:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),o=t.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=o*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ud:this._state=Ka}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ka}getData(e){let t=jd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&D0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(o);return}if(this._compressed){this._state=Ya,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Id.extensionName].decompress(e,this._fin,(n,r)=>{if(n)return t(n);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(i);return}this._fragments.push(r)}this.dataMessage(t),this._state===Ye&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ye;return}let t=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Ja(o,t):this._binaryType==="arraybuffer"?n=k0(Ja(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Ye):(this._state=Tr,setImmediate(()=>{this.emit("message",n,!0),this._state=Ye,this.startLoop(e)}))}else{let n=Ja(o,t);if(!this._skipUTF8Validation&&!Nd(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===Ya||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Ye):(this._state=Tr,setImmediate(()=>{this.emit("message",n,!1),this._state=Ye,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,jd),this.end();else{let o=e.readUInt16BE(0);if(!v0(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new Fr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Nd(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(r);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=Ye;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ye):(this._state=Tr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ye,this.startLoop(t)}))}createError(e,t,o,n,r){this._loop=!1,this._errored=!0;let i=new e(o?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=r,i[b0]=n,i}};Wd.exports=Xa});var tc=ce((L$,qd)=>{"use strict";var{Duplex:N$}=require("stream"),{randomFillSync:S0}=require("crypto"),{types:{isUint8Array:x0}}=require("util"),Hd=cs(),{EMPTY_BUFFER:$0,kWebSocket:C0,NOOP:_0}=Bt(),{isBlob:us,isValidStatusCode:E0}=ls(),{mask:Gd,toBuffer:Ao}=Zs(),Xe=Symbol("kByteLength"),F0=Buffer.alloc(4),Rr=8*1024,Po,ds=Rr,ct=0,T0=1,R0=2,Za=class s{static{l(this,"Sender")}constructor(e,t,o){this._extensions=t||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=ct,this.onerror=_0,this[C0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||F0,t.generateMask?t.generateMask(o):(ds===Rr&&(Po===void 0&&(Po=Buffer.alloc(Rr)),S0(Po,0,Rr),ds=0),o[0]=Po[ds++],o[1]=Po[ds++],o[2]=Po[ds++],o[3]=Po[ds++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Xe]!==void 0?c=t[Xe]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!i);let u=c;c>=65536?(r+=8,u=127):c>125&&(r+=2,u=126);let d=Buffer.allocUnsafe(n?c+r:r);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[r-4]=o[0],d[r-3]=o[1],d[r-2]=o[2],d[r-1]=o[3],i?[d,e]:n?(Gd(e,o,d,r,c),[d]):(Gd(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=$0;else{if(typeof e!="number"||!E0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)r=Buffer.allocUnsafe(2),r.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(r=Buffer.allocUnsafe(2+c),r.writeUInt16BE(e,0),typeof t=="string")r.write(t,2);else if(x0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Xe]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ct?this.enqueue([this.dispatch,r,!1,i,n]):this.sendFrame(s.frame(r,i),n)}ping(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):us(e)?(n=e.size,r=!1):(e=Ao(e),n=e.length,r=Ao.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Xe]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};us(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ct?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}pong(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):us(e)?(n=e.size,r=!1):(e=Ao(e),n=e.length,r=Ao.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Xe]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};us(e)?this._state!==ct?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ct?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[Hd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):us(e)?(c=e.size,u=!1):(e=Ao(e),c=e.length,u=Ao.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=n._threshold),this._compress=i):(i=!1,r=0),t.fin&&(this._firstFragment=!0);let d={[Xe]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};us(e)?this._state!==ct?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==ct?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Xe],this._state=R0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(ec,this,c,n);return}this._bufferedBytes-=o[Xe];let i=Ao(r);t?this.dispatch(i,t,o,n):(this._state=ct,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(A0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[Hd.extensionName];this._bufferedBytes+=o[Xe],this._state=T0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");ec(this,u,n);return}this._bufferedBytes-=o[Xe],this._state=ct,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===ct&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Xe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Xe],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};qd.exports=Za;function ec(s,e,t){typeof t=="function"&&t(e);for(let o=0;o<s._queue.length;o++){let n=s._queue[o],r=n[n.length-1];typeof r=="function"&&r(e)}}l(ec,"callCallbacks");function A0(s,e,t){ec(s,e,t),s.onerror(e)}l(A0,"onError")});var ep=ce((U$,Zd)=>{"use strict";var{kForOnEventAttribute:tn,kListener:oc}=Bt(),Vd=Symbol("kCode"),zd=Symbol("kData"),Jd=Symbol("kError"),Kd=Symbol("kMessage"),Yd=Symbol("kReason"),ps=Symbol("kTarget"),Xd=Symbol("kType"),Qd=Symbol("kWasClean"),Wt=class{static{l(this,"Event")}constructor(e){this[ps]=null,this[Xd]=e}get target(){return this[ps]}get type(){return this[Xd]}};Object.defineProperty(Wt.prototype,"target",{enumerable:!0});Object.defineProperty(Wt.prototype,"type",{enumerable:!0});var Oo=class extends Wt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[Vd]=t.code===void 0?0:t.code,this[Yd]=t.reason===void 0?"":t.reason,this[Qd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Vd]}get reason(){return this[Yd]}get wasClean(){return this[Qd]}};Object.defineProperty(Oo.prototype,"code",{enumerable:!0});Object.defineProperty(Oo.prototype,"reason",{enumerable:!0});Object.defineProperty(Oo.prototype,"wasClean",{enumerable:!0});var ms=class extends Wt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[Jd]=t.error===void 0?null:t.error,this[Kd]=t.message===void 0?"":t.message}get error(){return this[Jd]}get message(){return this[Kd]}};Object.defineProperty(ms.prototype,"error",{enumerable:!0});Object.defineProperty(ms.prototype,"message",{enumerable:!0});var on=class extends Wt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[zd]=t.data===void 0?null:t.data}get data(){return this[zd]}};Object.defineProperty(on.prototype,"data",{enumerable:!0});var P0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[tn]&&n[oc]===e&&!n[tn])return;let o;if(s==="message")o=l(function(r,i){let c=new on("message",{data:i?r:r.toString()});c[ps]=this,Ar(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new Oo("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ps]=this,Ar(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new ms("error",{error:r,message:r.message});i[ps]=this,Ar(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Wt("open");r[ps]=this,Ar(e,this,r)},"onOpen");else return;o[tn]=!!t[tn],o[oc]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[oc]===e&&!t[tn]){this.removeListener(s,t);break}}};Zd.exports={CloseEvent:Oo,ErrorEvent:ms,Event:Wt,EventTarget:P0,MessageEvent:on};function Ar(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(Ar,"callListener")});var Pr=ce((H$,tp)=>{"use strict";var{tokenChars:sn}=ls();function kt(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(kt,"push");function O0(s){let e=Object.create(null),t=Object.create(null),o=!1,n=!1,r=!1,i,c,u=-1,d=-1,p=-1,g=0;for(;g<s.length;g++)if(d=s.charCodeAt(g),i===void 0)if(p===-1&&sn[d]===1)u===-1&&(u=g);else if(g!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=g);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${g}`);p===-1&&(p=g);let f=s.slice(u,p);d===44?(kt(e,f,t),t=Object.create(null)):i=f,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${g}`);else if(c===void 0)if(p===-1&&sn[d]===1)u===-1&&(u=g);else if(d===32||d===9)p===-1&&u!==-1&&(p=g);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${g}`);p===-1&&(p=g),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,g),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(n){if(sn[d]!==1)throw new SyntaxError(`Unexpected character at index ${g}`);u===-1?u=g:o||(o=!0),n=!1}else if(r)if(sn[d]===1)u===-1&&(u=g);else if(d===34&&u!==-1)r=!1,p=g;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${g}`);else if(d===34&&s.charCodeAt(g-1)===61)r=!0;else if(p===-1&&sn[d]===1)u===-1&&(u=g);else if(u!==-1&&(d===32||d===9))p===-1&&(p=g);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${g}`);p===-1&&(p=g);let f=s.slice(u,p);o&&(f=f.replace(/\\/g,""),o=!1),kt(t,c,f),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 ${g}`);if(u===-1||r||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=g);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(O0,"parse");function M0(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(M0,"format");tp.exports={format:M0,parse:O0}});var jr=ce((z$,mp)=>{"use strict";var I0=require("events"),j0=require("https"),N0=require("http"),np=require("net"),L0=require("tls"),{randomBytes:B0,createHash:U0}=require("crypto"),{Duplex:q$,Readable:V$}=require("stream"),{URL:sc}=require("url"),uo=cs(),W0=Qa(),H0=tc(),{isBlob:G0}=ls(),{BINARY_TYPES:op,CLOSE_TIMEOUT:q0,EMPTY_BUFFER:Or,GUID:V0,kForOnEventAttribute:nc,kListener:z0,kStatusCode:J0,kWebSocket:we,NOOP:rp}=Bt(),{EventTarget:{addEventListener:K0,removeEventListener:Y0}}=ep(),{format:X0,parse:Q0}=Pr(),{toBuffer:Z0}=Zs(),ip=Symbol("kAborted"),rc=[8,13],Ht=["CONNECTING","OPEN","CLOSING","CLOSED"],eb=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ae=class s extends I0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=op[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Or,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(o=t,t=[]):t=[t]),ap(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){op.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,o){let n=new W0({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),r=new H0(e,this._extensions,o.generateMask);this._receiver=n,this._sender=r,this._socket=e,n[we]=this,r[we]=this,e[we]=this,n.on("conclude",sb),n.on("drain",nb),n.on("error",rb),n.on("message",ib),n.on("ping",ab),n.on("pong",cb),r.onerror=lb,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",up),e.on("data",Ir),e.on("end",dp),e.on("error",pp),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[uo.extensionName]&&this._extensions[uo.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),lp(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Or,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||Or,t,o)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(o=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){ic(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[uo.extensionName]||(n.compress=!1),this._sender.send(e||Or,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,"CONNECTING",{enumerable:!0,value:Ht.indexOf("CONNECTING")});Object.defineProperty(ae.prototype,"CONNECTING",{enumerable:!0,value:Ht.indexOf("CONNECTING")});Object.defineProperty(ae,"OPEN",{enumerable:!0,value:Ht.indexOf("OPEN")});Object.defineProperty(ae.prototype,"OPEN",{enumerable:!0,value:Ht.indexOf("OPEN")});Object.defineProperty(ae,"CLOSING",{enumerable:!0,value:Ht.indexOf("CLOSING")});Object.defineProperty(ae.prototype,"CLOSING",{enumerable:!0,value:Ht.indexOf("CLOSING")});Object.defineProperty(ae,"CLOSED",{enumerable:!0,value:Ht.indexOf("CLOSED")});Object.defineProperty(ae.prototype,"CLOSED",{enumerable:!0,value:Ht.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ae.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ae.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[nc])return e[z0];return null},set(e){for(let t of this.listeners(s))if(t[nc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[nc]:!0})}})});ae.prototype.addEventListener=K0;ae.prototype.removeEventListener=Y0;mp.exports=ae;function ap(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:q0,protocolVersion:rc[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=n.autoPong,s._closeTimeout=n.closeTimeout,!rc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${rc.join(", ")})`);let r;if(e instanceof sc)r=e;else try{r=new sc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let y=new SyntaxError(u);if(s._redirects===0)throw y;Mr(s,y);return}let d=i?443:80,p=B0(16).toString("base64"),g=i?j0.request:N0.request,m=new Set,f;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&&(f=new uo({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=X0({[uo.extensionName]:f.offer()})),t.length){for(let y of t){if(typeof y!="string"||!eb.test(y)||m.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(y)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let y=n.path.split(":");n.socketPath=y[0],n.path=y[1]}let h;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let y=o&&o.headers;if(o={...o,headers:{}},y)for(let[S,D]of Object.entries(y))o.headers[S.toLowerCase()]=D}else if(s.listenerCount("redirect")===0){let y=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!y||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,y||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),h=s._req=g(n),s._redirects&&s.emit("redirect",s.url,h)}else h=s._req=g(n);n.timeout&&h.on("timeout",()=>{We(s,h,"Opening handshake has timed out")}),h.on("error",y=>{h===null||h[ip]||(h=s._req=null,Mr(s,y))}),h.on("response",y=>{let S=y.headers.location,D=y.statusCode;if(S&&n.followRedirects&&D>=300&&D<400){if(++s._redirects>n.maxRedirects){We(s,h,"Maximum redirects exceeded");return}h.abort();let C;try{C=new sc(S,e)}catch{let v=new SyntaxError(`Invalid URL: ${S}`);Mr(s,v);return}ap(s,C,t,o)}else s.emit("unexpected-response",h,y)||We(s,h,`Unexpected server response: ${y.statusCode}`)}),h.on("upgrade",(y,S,D)=>{if(s.emit("upgrade",y),s.readyState!==ae.CONNECTING)return;h=s._req=null;let C=y.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){We(s,S,"Invalid Upgrade header");return}let x=U0("sha1").update(p+V0).digest("base64");if(y.headers["sec-websocket-accept"]!==x){We(s,S,"Invalid Sec-WebSocket-Accept header");return}let v=y.headers["sec-websocket-protocol"],E;if(v!==void 0?m.size?m.has(v)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){We(s,S,E);return}v&&(s._protocol=v);let oe=y.headers["sec-websocket-extensions"];if(oe!==void 0){if(!f){We(s,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let U;try{U=Q0(oe)}catch{We(s,S,"Invalid Sec-WebSocket-Extensions header");return}let pe=Object.keys(U);if(pe.length!==1||pe[0]!==uo.extensionName){We(s,S,"Server indicated an extension that was not requested");return}try{f.accept(U[uo.extensionName])}catch{We(s,S,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[uo.extensionName]=f}s.setSocket(S,D,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(h,s):h.end()}l(ap,"initAsClient");function Mr(s,e){s._readyState=ae.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Mr,"emitErrorAndClose");function tb(s){return s.path=s.socketPath,np.connect(s)}l(tb,"netConnect");function ob(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=np.isIP(s.host)?"":s.host),L0.connect(s)}l(ob,"tlsConnect");function We(s,e,t){s._readyState=ae.CLOSING;let o=new Error(t);Error.captureStackTrace(o,We),e.setHeader?(e[ip]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(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} (${Ht[s.readyState]})`);process.nextTick(t,o)}}l(ic,"sendAfterClose");function sb(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Ir),process.nextTick(cp,t._socket),s===1005?t.close():t.close(s,e))}l(sb,"receiverOnConclude");function nb(){let s=this[we];s.isPaused||s._socket.resume()}l(nb,"receiverOnDrain");function rb(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Ir),process.nextTick(cp,e._socket),e.close(s[J0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(rb,"receiverOnError");function sp(){this[we].emitClose()}l(sp,"receiverOnFinish");function ib(s,e){this[we].emit("message",s,e)}l(ib,"receiverOnMessage");function ab(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,rp),e.emit("ping",s)}l(ab,"receiverOnPing");function cb(s){this[we].emit("pong",s)}l(cb,"receiverOnPong");function cp(s){s.resume()}l(cp,"resume");function lb(s){let e=this[we];e.readyState!==ae.CLOSED&&(e.readyState===ae.OPEN&&(e._readyState=ae.CLOSING,lp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(lb,"senderOnError");function lp(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(lp,"setCloseTimer");function up(){let s=this[we];if(this.removeListener("close",up),this.removeListener("data",Ir),this.removeListener("end",dp),s._readyState=ae.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[we]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",sp),s._receiver.on("finish",sp))}l(up,"socketOnClose");function Ir(s){this[we]._receiver.write(s)||this.pause()}l(Ir,"socketOnData");function dp(){let s=this[we];s._readyState=ae.CLOSING,s._receiver.end(),this.end()}l(dp,"socketOnEnd");function pp(){let s=this[we];this.removeListener("error",pp),this.on("error",rp),s&&(s._readyState=ae.CLOSING,this.destroy())}l(pp,"socketOnError")});var yp=ce((Y$,hp)=>{"use strict";var K$=jr(),{Duplex:ub}=require("stream");function gp(s){s.emit("close")}l(gp,"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(gp,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(gp,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");hp.exports=pb});var ac=ce((Q$,bp)=>{"use strict";var{tokenChars:mb}=ls();function gb(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(gb,"parse");bp.exports={parse:gb}});var $p=ce((tC,xp)=>{"use strict";var fb=require("events"),Nr=require("http"),{Duplex:eC}=require("stream"),{createHash:hb}=require("crypto"),wp=Pr(),Mo=cs(),yb=ac(),bb=jr(),{CLOSE_TIMEOUT:wb,GUID:kb,kWebSocket:Db}=Bt(),vb=/^[+/0-9A-Za-z]{22}==$/,kp=0,Dp=1,Sp=2,cc=class extends fb{static{l(this,"WebSocketServer")}constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:wb,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Nr.createServer((o,n)=>{let r=Nr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),n.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=Sb(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:l((n,r,i)=>{this.handleUpgrade(n,r,i,o)},"upgrade")})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=kp}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Sp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(nn,this);return}if(e&&this.once("close",e),this._state!==Dp)if(this._state=Dp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(nn,this):process.nextTick(nn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{nn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,o,n){t.on("error",vp);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Io(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Io(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!vb.test(r)){Io(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Io(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){rn(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=yb.parse(u)}catch{Io(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],g={};if(this.options.perMessageDeflate&&p!==void 0){let m=new Mo({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=wp.parse(p);f[Mo.extensionName]&&(m.accept(f[Mo.extensionName]),g[Mo.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,(f,h,y,S)=>{if(!f)return rn(t,h||401,y,S);this.completeUpgrade(g,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return rn(t,401)}this.completeUpgrade(g,r,d,e,t,o,n)}completeUpgrade(e,t,o,n,r,i,c){if(!r.readable||!r.writable)return r.destroy();if(r[Db])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>kp)return rn(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hb("sha1").update(t+kb).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(o.size){let g=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;g&&(d.push(`Sec-WebSocket-Protocol: ${g}`),p._protocol=g)}if(e[Mo.extensionName]){let g=e[Mo.extensionName].params,m=wp.format({[Mo.extensionName]:[g]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
157
|
+
`)}function Ja(s,e,t){let r=Math.max(4e3,(e||128e3)-(t||15e3)),i=Math.floor(r*.9)*4;if(vr(s)<=i)return{messages:s,elided:0,savedTokens:0};let u=s.map(v=>({...v})),d=0,p=mo(s),f=u.length-1-12;for(let v=0;v<=f;v++){let _=u[v];_.role==="tool"&&_.content&&_.content.length>6e4&&(_.content=w0(_.content,6e4),d++)}if(vr(u)<=i)return{messages:u,elided:d,savedTokens:p-mo(u)};let m=u.filter(v=>v.role!=="system").length,h=Math.max(10,Math.floor(m*.2)),g=Math.floor((m-h)/20)*20;if(g>0){let v=0;for(let _=0;_<u.length;_++){if(u[_].role==="system")continue;if(v++,v>g)break;let S=u[_];if(v<=Math.floor(g*.75)){if(S.role==="tool"&&S.content&&S.content.length>150){let k=S.content.includes("Error")||S.content.includes("error"),C=S.content.split(`
|
|
158
|
+
`)[0].slice(0,100);S.content=k?`[error] ${C}`:`[ok] ${C}`,d++}if(S.role==="assistant"&&S.content&&S.content.length>300&&!S.tool_calls?.length&&(S.content=S.content.slice(0,200)+`
|
|
159
|
+
...[summarized]`),S.role==="assistant"&&S.tool_calls?.length){let k=S.tool_calls.map(C=>`[called ${C.name||"unknown"}]`);S.content||(S.content=k.join(", "))}}else if(S.role==="assistant"&&S.content&&S.content.length>500&&!S.tool_calls?.length&&(S.content=S.content.slice(0,400)+`
|
|
160
|
+
...[truncated]`),S.role==="tool"&&S.content&&S.content.length>500){let k=S.content.includes("Error")||S.content.includes("error"),C=S.content.split(`
|
|
161
|
+
`)[0].slice(0,150);S.content=k?`[error] ${C}`:`[ok] ${C}`,d++}}}if(vr(u)<=i)return{messages:u,elided:d,savedTokens:p-mo(u)};let y=Math.floor(i*.85),x=vr(u);for(;x>y&&u.length>6;){let v=u.findIndex(k=>k.role==="user");if(v<0)break;let _=v;for(let k=v+1;k<u.length;k++){let C=u[k];if(C.role==="user"&&!("tool_call_id"in C))break;_=k}let S=u.splice(v,_-v+1);for(let k of S)x-=k.content?.length||0,k.tool_calls&&(x-=JSON.stringify(k.tool_calls).length);d+=S.length}if(u.length<s.length){let v=["[CONVERSATION CONTEXT \u2014 older messages were summarized to fit within the token limit]","Continue working with the remaining context."],_=u[0]?.role==="system"?1:0;u.splice(_,0,{role:"user",content:v.join(`
|
|
162
|
+
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-mo(u)}}function vr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var Va,Sr=W(()=>{"use strict";l(qa,"estimateTokens");l(mo,"estimateContextTokens");l(Dr,"resolveContextWindow");Va=new Map;l(_d,"updateModelCatalog");l($d,"shouldCompact");l(w0,"trimToolResult");l(Ja,"compactMessages");l(vr,"totalChars")});var rs={};Ae(rs,{AgentLoop:()=>xe});var Cd,b0,xe,Xe=W(()=>{"use strict";Cd=require("node:events");Vu();Ku();Xu();Ma();Oa();kd();Q();xd();Sr();b0=1/0,xe=class extends Cd.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 ur({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new cs(hr(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new Mo(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=Dr(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||b0;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=Sd({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=mo(this.messages);if($d(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=mo(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 h=m.arguments.question||"What would you like to do?";this.updateState({status:"waiting_user_input"}),this.emitEvent({type:"ask_user",question:h});let g=await this.waitForUserInput();this.messages.push({role:"tool",content:`User response: ${g}`,tool_call_id:m.id,name:m.name,timestamp:Date.now()}),this.emitEvent({type:"tool_call_result",name:m.name,result:`User: ${g}`})}if(p.length>0){for(let h of p)this.emitEvent({type:"tool_call_start",name:h.name,args:h.arguments});this.updateState({status:"tool_executing",currentToolCall:`${p.length} parallel reads`});let m=await Promise.all(p.map(async h=>{let g=await this.toolExecutor.execute(h.name,h.arguments);return{toolCall:h,result:g}}));for(let{toolCall:h,result:g}of m)h.result=g.output,this.emitEvent({type:"tool_call_result",name:h.name,result:g.output}),this.messages.push({role:"tool",content:g.output,tool_call_id:h.id,name:h.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 h=await this._hookRunner.fire("PreToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments}});if(h.some(x=>x.action==="deny")){let x=h.find(v=>v.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${x}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let y=await this.toolExecutor.execute(m.name,m.arguments);if(y.wroteFiles&&y.touchedFiles)for(let x of y.touchedFiles)this.filesModified.add(x);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:y.output.slice(0,1e3),wroteFiles:y.wroteFiles}}).catch(()=>{}),m.result=y.output,this.emitEvent({type:"tool_call_result",name:m.name,result:y.output}),this.messages.push({role:"tool",content:y.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=Ja(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=mo(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=zu(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(k=>({role:k.role,content:k.content,...k.tool_calls?{tool_calls:k.tool_calls.map(C=>({id:C.id,type:"function",function:{name:C.name,arguments:JSON.stringify(C.arguments)}}))}:{},...k.tool_call_id?{tool_call_id:k.tool_call_id}:{},...k.name?{name:k.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=Y(),i=bd(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(k){if(k instanceof Error&&k.name==="AbortError")return null;throw k}if(!c.ok){let k=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}: ${k}`)}let u="",d=new lr,p="",f=!1,m="",h="<think>",g="</think>",y=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),x=l(k=>{f?(m+=k,g.startsWith(m)?m===g&&(f=!1,m=""):(m="",k==="<"&&(m="<"))):k==="<"&&!m?m="<":m?(m+=k,h.startsWith(m)?m===h&&(f=!0,m=""):g.startsWith(m)?m===g&&(m=""):(p+=m,m="")):p+=k},"feedChar");for await(let k of qu(c)){if(!k.choices||k.choices.length===0){k.usage&&this.updateState({tokensIn:this.state.tokensIn+(k.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(k.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(k.usage.prompt_tokens_details?.cached_tokens||0)});continue}let C=k.choices[0];if(C.delta?.content){u+=C.delta.content;for(let J of C.delta.content)x(J);y()}if(C.delta?.tool_calls&&d.feed(C.delta.tool_calls),C.finish_reason==="tool_calls"||C.finish_reason==="stop")break}m&&!f&&(p+=m),y();let v=d.flush(),S={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return v.length>0&&(S.tool_calls=v.map(k=>{let C={};try{C=JSON.parse(k.arguments)}catch{C={_raw:k.arguments}}return{id:k.id,name:k.name,arguments:C}})),S}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 Gt=le((x$,Ud)=>{"use strict";var Ld=["nodebuffer","arraybuffer","fragments"],Bd=typeof Blob<"u";Bd&&Ld.push("blob");Ud.exports={BINARY_TYPES:Ld,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 rn=le(($$,Pr)=>{"use strict";var{EMPTY_BUFFER:j0}=Gt(),Qa=Buffer[Symbol.species];function N0(s,e){if(s.length===0)return j0;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 Qa(t.buffer,t.byteOffset,o):t}l(N0,"concat");function Wd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(Wd,"_mask");function Hd(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(Hd,"_unmask");function L0(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(L0,"toArrayBuffer");function Za(s){if(Za.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Qa(s):ArrayBuffer.isView(s)?e=new Qa(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Za.readOnly=!1),e}l(Za,"toBuffer");Pr.exports={concat:N0,mask:Wd,toArrayBuffer:L0,toBuffer:Za,unmask:Hd};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");Pr.exports.mask=function(e,t,o,n,r){r<48?Wd(e,t,o,n,r):s.mask(e,t,o,n,r)},Pr.exports.unmask=function(e,t){e.length<32?Hd(e,t):s.unmask(e,t)}}catch{}});var Vd=le((E$,qd)=>{"use strict";var Gd=Symbol("kDone"),ec=Symbol("kRun"),tc=class{static{l(this,"Limiter")}constructor(e){this[Gd]=()=>{this.pending--,this[ec]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ec]()}[ec](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Gd])}}};qd.exports=tc});var ms=le((T$,Yd)=>{"use strict";var an=require("zlib"),Jd=rn(),B0=Vd(),{kStatusCode:zd}=Gt(),U0=Buffer[Symbol.species],W0=Buffer.from([0,0,255,255]),Mr=Symbol("permessage-deflate"),qt=Symbol("total-length"),ds=Symbol("callback"),ho=Symbol("buffers"),ps=Symbol("error"),Ir,oc=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,!Ir){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ir=new B0(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[ds];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){Ir.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){Ir.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"?an.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=an.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Mr]=this,this._inflate[qt]=0,this._inflate[ho]=[],this._inflate.on("error",G0),this._inflate.on("data",Kd)}this._inflate[ds]=o,this._inflate.write(e),t&&this._inflate.write(W0),this._inflate.flush(()=>{let r=this._inflate[ps];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Jd.concat(this._inflate[ho],this._inflate[qt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[qt]=0,this._inflate[ho]=[],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"?an.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=an.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[qt]=0,this._deflate[ho]=[],this._deflate.on("data",H0)}this._deflate[ds]=o,this._deflate.write(e),this._deflate.flush(an.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Jd.concat(this._deflate[ho],this._deflate[qt]);t&&(r=new U0(r.buffer,r.byteOffset,r.length-4)),this._deflate[ds]=null,this._deflate[qt]=0,this._deflate[ho]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Yd.exports=oc;function H0(s){this[ho].push(s),this[qt]+=s.length}l(H0,"deflateOnData");function Kd(s){if(this[qt]+=s.length,this[Mr]._maxPayload<1||this[qt]<=this[Mr]._maxPayload){this[ho].push(s);return}this[ps]=new RangeError("Max payload size exceeded"),this[ps].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ps][zd]=1009,this.removeListener("data",Kd),this.reset()}l(Kd,"inflateOnData");function G0(s){if(this[Mr]._inflate=null,this[ps]){this[ds](this[ps]);return}s[zd]=1007,this[ds](s)}l(G0,"inflateOnError")});var fs=le((A$,Or)=>{"use strict";var{isUtf8:Xd}=require("buffer"),{hasBlob:q0}=Gt(),V0=[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 J0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(J0,"isValidStatusCode");function sc(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(sc,"_isValidUTF8");function z0(s){return q0&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(z0,"isBlob");Or.exports={isBlob:z0,isValidStatusCode:J0,isValidUTF8:sc,tokenChars:V0};if(Xd)Or.exports.isValidUTF8=function(s){return s.length<24?sc(s):Xd(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");Or.exports.isValidUTF8=function(e){return e.length<32?sc(e):s(e)}}catch{}});var cc=le((I$,np)=>{"use strict";var{Writable:K0}=require("stream"),Qd=ms(),{BINARY_TYPES:Y0,EMPTY_BUFFER:Zd,kStatusCode:X0,kWebSocket:Q0}=Gt(),{concat:nc,toArrayBuffer:Z0,unmask:ew}=rn(),{isValidStatusCode:tw,isValidUTF8:ep}=fs(),jr=Buffer[Symbol.species],Qe=0,tp=1,op=2,sp=3,rc=4,ic=5,Nr=6,ac=class extends K0{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[Q0]=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=Qe}_write(e,t,o){if(this._opcode===8&&this._state==Qe)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 jr(o.buffer,o.byteOffset+e,o.length-e),new jr(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 jr(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 Qe:this.getInfo(e);break;case tp:this.getPayloadLength16(e);break;case op:this.getPayloadLength64(e);break;case sp:this.getMask();break;case rc:this.getData(e);break;case ic:case Nr: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[Qd.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=tp:this._payloadLength===127?this._state=op: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=sp:this._state=rc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=rc}getData(e){let t=Zd;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]&&ew(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=ic,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Qd.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===Qe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Qe;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=nc(o,t):this._binaryType==="arraybuffer"?n=Z0(nc(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Qe):(this._state=Nr,setImmediate(()=>{this.emit("message",n,!0),this._state=Qe,this.startLoop(e)}))}else{let n=nc(o,t);if(!this._skipUTF8Validation&&!ep(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===ic||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Qe):(this._state=Nr,setImmediate(()=>{this.emit("message",n,!1),this._state=Qe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Zd),this.end();else{let o=e.readUInt16BE(0);if(!tw(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new jr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!ep(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=Qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe):(this._state=Nr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Qe,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[X0]=n,i}};np.exports=ac});var dc=le((j$,ap)=>{"use strict";var{Duplex:O$}=require("stream"),{randomFillSync:ow}=require("crypto"),{types:{isUint8Array:sw}}=require("util"),rp=ms(),{EMPTY_BUFFER:nw,kWebSocket:rw,NOOP:iw}=Gt(),{isBlob:hs,isValidStatusCode:aw}=fs(),{mask:ip,toBuffer:jo}=rn(),Ze=Symbol("kByteLength"),cw=Buffer.alloc(4),Lr=8*1024,No,gs=Lr,ut=0,lw=1,uw=2,lc=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=ut,this.onerror=iw,this[rw]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||cw,t.generateMask?t.generateMask(o):(gs===Lr&&(No===void 0&&(No=Buffer.alloc(Lr)),ow(No,0,Lr),gs=0),o[0]=No[gs++],o[1]=No[gs++],o[2]=No[gs++],o[3]=No[gs++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Ze]!==void 0?c=t[Ze]:(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?(ip(e,o,d,r,c),[d]):(ip(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=nw;else{if(typeof e!="number"||!aw(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(sw(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Ze]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ut?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):hs(e)?(n=e.size,r=!1):(e=jo(e),n=e.length,r=jo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ze]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};hs(e)?this._state!==ut?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ut?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):hs(e)?(n=e.size,r=!1):(e=jo(e),n=e.length,r=jo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ze]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};hs(e)?this._state!==ut?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==ut?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[rp.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):hs(e)?(c=e.size,u=!1):(e=jo(e),c=e.length,u=jo.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={[Ze]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};hs(e)?this._state!==ut?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==ut?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Ze],this._state=uw,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(uc,this,c,n);return}this._bufferedBytes-=o[Ze];let i=jo(r);t?this.dispatch(i,t,o,n):(this._state=ut,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(dw,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[rp.extensionName];this._bufferedBytes+=o[Ze],this._state=lw,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");uc(this,u,n);return}this._bufferedBytes-=o[Ze],this._state=ut,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===ut&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ze],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ze],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)}};ap.exports=lc;function uc(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(uc,"callCallbacks");function dw(s,e,t){uc(s,e,t),s.onerror(e)}l(dw,"onError")});var gp=le((L$,hp)=>{"use strict";var{kForOnEventAttribute:cn,kListener:pc}=Gt(),cp=Symbol("kCode"),lp=Symbol("kData"),up=Symbol("kError"),dp=Symbol("kMessage"),pp=Symbol("kReason"),ys=Symbol("kTarget"),mp=Symbol("kType"),fp=Symbol("kWasClean"),Vt=class{static{l(this,"Event")}constructor(e){this[ys]=null,this[mp]=e}get target(){return this[ys]}get type(){return this[mp]}};Object.defineProperty(Vt.prototype,"target",{enumerable:!0});Object.defineProperty(Vt.prototype,"type",{enumerable:!0});var Lo=class extends Vt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[cp]=t.code===void 0?0:t.code,this[pp]=t.reason===void 0?"":t.reason,this[fp]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[cp]}get reason(){return this[pp]}get wasClean(){return this[fp]}};Object.defineProperty(Lo.prototype,"code",{enumerable:!0});Object.defineProperty(Lo.prototype,"reason",{enumerable:!0});Object.defineProperty(Lo.prototype,"wasClean",{enumerable:!0});var ws=class extends Vt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[up]=t.error===void 0?null:t.error,this[dp]=t.message===void 0?"":t.message}get error(){return this[up]}get message(){return this[dp]}};Object.defineProperty(ws.prototype,"error",{enumerable:!0});Object.defineProperty(ws.prototype,"message",{enumerable:!0});var ln=class extends Vt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[lp]=t.data===void 0?null:t.data}get data(){return this[lp]}};Object.defineProperty(ln.prototype,"data",{enumerable:!0});var pw={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[cn]&&n[pc]===e&&!n[cn])return;let o;if(s==="message")o=l(function(r,i){let c=new ln("message",{data:i?r:r.toString()});c[ys]=this,Br(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new Lo("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ys]=this,Br(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new ws("error",{error:r,message:r.message});i[ys]=this,Br(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Vt("open");r[ys]=this,Br(e,this,r)},"onOpen");else return;o[cn]=!!t[cn],o[pc]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[pc]===e&&!t[cn]){this.removeListener(s,t);break}}};hp.exports={CloseEvent:Lo,ErrorEvent:ws,Event:Vt,EventTarget:pw,MessageEvent:ln};function Br(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(Br,"callListener")});var Ur=le((U$,yp)=>{"use strict";var{tokenChars:un}=fs();function Dt(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(Dt,"push");function mw(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&&un[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 h=s.slice(u,p);d===44?(Dt(e,h,t),t=Object.create(null)):i=h,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&un[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),Dt(t,s.slice(u,p),!0),d===44&&(Dt(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(un[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(un[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&&un[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 h=s.slice(u,p);o&&(h=h.replace(/\\/g,""),o=!1),Dt(t,c,h),d===44&&(Dt(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?Dt(e,m,t):(c===void 0?Dt(t,m,!0):o?Dt(t,c,m.replace(/\\/g,"")):Dt(t,c,m),Dt(e,i,t)),e}l(mw,"parse");function fw(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(fw,"format");yp.exports={format:fw,parse:mw}});var qr=le((q$,Fp)=>{"use strict";var hw=require("events"),gw=require("https"),yw=require("http"),kp=require("net"),ww=require("tls"),{randomBytes:bw,createHash:kw}=require("crypto"),{Duplex:H$,Readable:G$}=require("stream"),{URL:mc}=require("url"),go=ms(),vw=cc(),Dw=dc(),{isBlob:Sw}=fs(),{BINARY_TYPES:wp,CLOSE_TIMEOUT:xw,EMPTY_BUFFER:Wr,GUID:_w,kForOnEventAttribute:fc,kListener:$w,kStatusCode:Cw,kWebSocket:ke,NOOP:vp}=Gt(),{EventTarget:{addEventListener:Ew,removeEventListener:Fw}}=gp(),{format:Tw,parse:Rw}=Ur(),{toBuffer:Aw}=rn(),Dp=Symbol("kAborted"),hc=[8,13],Jt=["CONNECTING","OPEN","CLOSING","CLOSED"],Pw=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ae=class s extends hw{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=wp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Wr,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]),Sp(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){wp.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 vw({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 Dw(e,this._extensions,o.generateMask);this._receiver=n,this._sender=r,this._socket=e,n[ke]=this,r[ke]=this,e[ke]=this,n.on("conclude",Ow),n.on("drain",jw),n.on("error",Nw),n.on("message",Lw),n.on("ping",Bw),n.on("pong",Uw),r.onerror=Ww,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",$p),e.on("data",Gr),e.on("end",Cp),e.on("error",Ep),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[go.extensionName]&&this._extensions[go.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){He(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())}),_p(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){gc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Wr,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){gc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Wr,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){gc(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[go.extensionName]||(n.compress=!1),this._sender.send(e||Wr,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){He(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,"CONNECTING",{enumerable:!0,value:Jt.indexOf("CONNECTING")});Object.defineProperty(ae.prototype,"CONNECTING",{enumerable:!0,value:Jt.indexOf("CONNECTING")});Object.defineProperty(ae,"OPEN",{enumerable:!0,value:Jt.indexOf("OPEN")});Object.defineProperty(ae.prototype,"OPEN",{enumerable:!0,value:Jt.indexOf("OPEN")});Object.defineProperty(ae,"CLOSING",{enumerable:!0,value:Jt.indexOf("CLOSING")});Object.defineProperty(ae.prototype,"CLOSING",{enumerable:!0,value:Jt.indexOf("CLOSING")});Object.defineProperty(ae,"CLOSED",{enumerable:!0,value:Jt.indexOf("CLOSED")});Object.defineProperty(ae.prototype,"CLOSED",{enumerable:!0,value:Jt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ae.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ae.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[fc])return e[$w];return null},set(e){for(let t of this.listeners(s))if(t[fc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[fc]:!0})}})});ae.prototype.addEventListener=Ew;ae.prototype.removeEventListener=Fw;Fp.exports=ae;function Sp(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xw,protocolVersion:hc[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,!hc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${hc.join(", ")})`);let r;if(e instanceof mc)r=e;else try{r=new mc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let y=new SyntaxError(u);if(s._redirects===0)throw y;Hr(s,y);return}let d=i?443:80,p=bw(16).toString("base64"),f=i?gw.request:yw.request,m=new Set,h;if(n.createConnection=n.createConnection||(i?Mw:Iw),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&&(h=new go({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=Tw({[go.extensionName]:h.offer()})),t.length){for(let y of t){if(typeof y!="string"||!Pw.test(y)||m.has(y))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(y)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let y=n.path.split(":");n.socketPath=y[0],n.path=y[1]}let g;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let y=o&&o.headers;if(o={...o,headers:{}},y)for(let[x,v]of Object.entries(y))o.headers[x.toLowerCase()]=v}else if(s.listenerCount("redirect")===0){let y=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!y||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,y||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=s._req=f(n),s._redirects&&s.emit("redirect",s.url,g)}else g=s._req=f(n);n.timeout&&g.on("timeout",()=>{He(s,g,"Opening handshake has timed out")}),g.on("error",y=>{g===null||g[Dp]||(g=s._req=null,Hr(s,y))}),g.on("response",y=>{let x=y.headers.location,v=y.statusCode;if(x&&n.followRedirects&&v>=300&&v<400){if(++s._redirects>n.maxRedirects){He(s,g,"Maximum redirects exceeded");return}g.abort();let _;try{_=new mc(x,e)}catch{let k=new SyntaxError(`Invalid URL: ${x}`);Hr(s,k);return}Sp(s,_,t,o)}else s.emit("unexpected-response",g,y)||He(s,g,`Unexpected server response: ${y.statusCode}`)}),g.on("upgrade",(y,x,v)=>{if(s.emit("upgrade",y),s.readyState!==ae.CONNECTING)return;g=s._req=null;let _=y.headers.upgrade;if(_===void 0||_.toLowerCase()!=="websocket"){He(s,x,"Invalid Upgrade header");return}let S=kw("sha1").update(p+_w).digest("base64");if(y.headers["sec-websocket-accept"]!==S){He(s,x,"Invalid Sec-WebSocket-Accept header");return}let k=y.headers["sec-websocket-protocol"],C;if(k!==void 0?m.size?m.has(k)||(C="Server sent an invalid subprotocol"):C="Server sent a subprotocol but none was requested":m.size&&(C="Server sent no subprotocol"),C){He(s,x,C);return}k&&(s._protocol=k);let J=y.headers["sec-websocket-extensions"];if(J!==void 0){if(!h){He(s,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=Rw(J)}catch{He(s,x,"Invalid Sec-WebSocket-Extensions header");return}let ce=Object.keys(O);if(ce.length!==1||ce[0]!==go.extensionName){He(s,x,"Server indicated an extension that was not requested");return}try{h.accept(O[go.extensionName])}catch{He(s,x,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[go.extensionName]=h}s.setSocket(x,v,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,s):g.end()}l(Sp,"initAsClient");function Hr(s,e){s._readyState=ae.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Hr,"emitErrorAndClose");function Iw(s){return s.path=s.socketPath,kp.connect(s)}l(Iw,"netConnect");function Mw(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=kp.isIP(s.host)?"":s.host),ww.connect(s)}l(Mw,"tlsConnect");function He(s,e,t){s._readyState=ae.CLOSING;let o=new Error(t);Error.captureStackTrace(o,He),e.setHeader?(e[Dp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Hr,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(He,"abortHandshake");function gc(s,e,t){if(e){let o=Sw(e)?e.size:Aw(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Jt[s.readyState]})`);process.nextTick(t,o)}}l(gc,"sendAfterClose");function Ow(s,e){let t=this[ke];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[ke]!==void 0&&(t._socket.removeListener("data",Gr),process.nextTick(xp,t._socket),s===1005?t.close():t.close(s,e))}l(Ow,"receiverOnConclude");function jw(){let s=this[ke];s.isPaused||s._socket.resume()}l(jw,"receiverOnDrain");function Nw(s){let e=this[ke];e._socket[ke]!==void 0&&(e._socket.removeListener("data",Gr),process.nextTick(xp,e._socket),e.close(s[Cw])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(Nw,"receiverOnError");function bp(){this[ke].emitClose()}l(bp,"receiverOnFinish");function Lw(s,e){this[ke].emit("message",s,e)}l(Lw,"receiverOnMessage");function Bw(s){let e=this[ke];e._autoPong&&e.pong(s,!this._isServer,vp),e.emit("ping",s)}l(Bw,"receiverOnPing");function Uw(s){this[ke].emit("pong",s)}l(Uw,"receiverOnPong");function xp(s){s.resume()}l(xp,"resume");function Ww(s){let e=this[ke];e.readyState!==ae.CLOSED&&(e.readyState===ae.OPEN&&(e._readyState=ae.CLOSING,_p(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(Ww,"senderOnError");function _p(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(_p,"setCloseTimer");function $p(){let s=this[ke];if(this.removeListener("close",$p),this.removeListener("data",Gr),this.removeListener("end",Cp),s._readyState=ae.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[ke]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",bp),s._receiver.on("finish",bp))}l($p,"socketOnClose");function Gr(s){this[ke]._receiver.write(s)||this.pause()}l(Gr,"socketOnData");function Cp(){let s=this[ke];s._readyState=ae.CLOSING,s._receiver.end(),this.end()}l(Cp,"socketOnEnd");function Ep(){let s=this[ke];this.removeListener("error",Ep),this.on("error",vp),s&&(s._readyState=ae.CLOSING,this.destroy())}l(Ep,"socketOnError")});var Pp=le((z$,Ap)=>{"use strict";var J$=qr(),{Duplex:Hw}=require("stream");function Tp(s){s.emit("close")}l(Tp,"emitClose");function Gw(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(Gw,"duplexOnEnd");function Rp(s){this.removeListener("error",Rp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(Rp,"duplexOnError");function qw(s,e){let t=!0,o=new Hw({...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(Tp,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(Tp,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",Gw),o.on("error",Rp),o}l(qw,"createWebSocketStream");Ap.exports=qw});var yc=le((Y$,Ip)=>{"use strict";var{tokenChars:Vw}=fs();function Jw(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&&Vw[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(Jw,"parse");Ip.exports={parse:Jw}});var Up=le((Z$,Bp)=>{"use strict";var zw=require("events"),Vr=require("http"),{Duplex:Q$}=require("stream"),{createHash:Kw}=require("crypto"),Mp=Ur(),Bo=ms(),Yw=yc(),Xw=qr(),{CLOSE_TIMEOUT:Qw,GUID:Zw,kWebSocket:eb}=Gt(),tb=/^[+/0-9A-Za-z]{22}==$/,Op=0,jp=1,Lp=2,wc=class extends zw{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:Qw,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Xw,...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=Vr.createServer((o,n)=>{let r=Vr.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=ob(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=Op}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===Lp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(dn,this);return}if(e&&this.once("close",e),this._state!==jp)if(this._state=jp,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(dn,this):process.nextTick(dn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{dn(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",Np);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Uo(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Uo(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!tb.test(r)){Uo(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Uo(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){pn(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=Yw.parse(u)}catch{Uo(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 Bo({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Mp.parse(p);h[Bo.extensionName]&&(m.accept(h[Bo.extensionName]),f[Bo.extensionName]=m)}catch{Uo(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,(h,g,y,x)=>{if(!h)return pn(t,g||401,y,x);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return pn(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[eb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Op)return pn(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Kw("sha1").update(t+Zw).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[Bo.extensionName]){let f=e[Bo.extensionName].params,m=Mp.format({[Bo.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
163
163
|
`).join(`\r
|
|
164
|
-
`)),r.removeListener("error",
|
|
164
|
+
`)),r.removeListener("error",Np),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(dn,this)})),c(p,n)}};Bp.exports=wc;function ob(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(ob,"addListeners");function dn(s){s._state=Lp,s.emit("close")}l(dn,"emitClose");function Np(){this.destroy()}l(Np,"socketOnError");function pn(s,e,t,o){t=t||Vr.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} ${Vr.STATUS_CODES[e]}\r
|
|
165
165
|
`+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
|
|
166
166
|
`)+`\r
|
|
167
167
|
\r
|
|
168
|
-
`+t)}l(
|
|
169
|
-
`),u="";try{let p=
|
|
170
|
-
`).filter(Boolean).map(n=>{let r=JSON.parse(n);return{timestamp:new Date(r.timestamp),level:r.level||"info",message:r.message||""}}):[]}catch{return[]}}function
|
|
171
|
-
`);r=u.pop()||"";for(let d of u)if(d.startsWith("data: "))try{let p=JSON.parse(d.substring(6));yield{timestamp:new Date(p.timestamp),level:p.level||"info",message:p.message||""}}catch{}}}catch{}}async message(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/message`,{method:"POST",headers:this.headers(),body:JSON.stringify({message:t}),signal:AbortSignal.timeout(1e4)});if(!o.ok){let n=await o.text().catch(()=>"");return o.status===409?{success:!1,error:"Job is no longer running, so it cannot be steered."}:{success:!1,error:`HTTP ${o.status}: ${n}`}}return{success:!0}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}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(
|
|
172
|
-
`).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,
|
|
173
|
-
`).filter(Boolean);t.push(`${c.length} staged file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}}catch{t.push("Unable to check git status (not a git repository?)")}return{compatible:t.length===0,reasons:t}}var
|
|
168
|
+
`+t)}l(pn,"abortHandshake");function Uo(s,e,t,o,n,r){if(s.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Uo),s.emit("wsClientError",i,t,e)}else pn(t,o,n,r)}l(Uo,"abortHandshakeOrEmitwsClientError")});var sb,nb,rb,ib,ab,cb,Wp,bc,dt,mn=W(()=>{sb=w(Pp(),1),nb=w(Ur(),1),rb=w(ms(),1),ib=w(cc(),1),ab=w(dc(),1),cb=w(yc(),1),Wp=w(qr(),1),bc=w(Up(),1),dt=Wp.default});var Pc={};Ae(Pc,{JobsApiClient:()=>Ne,captureWorkspaceSnapshot:()=>cm,createSnapshotArchive:()=>lm,getLocalJobLogs:()=>Tc,getLocalJobStatus:()=>Fc,getLocalJobs:()=>Ec,printJobStatus:()=>Yr,printJobsTable:()=>Ac,printLogEntry:()=>Xr,pullJobChanges:()=>Rc,runLocalBackgroundJob:()=>um,submitBackgroundJob:()=>pb});function cm(s){let e=l(p=>{try{return(0,Wo.execSync)(p,{cwd:s,encoding:"utf8"}).trim()}catch{return""}},"git"),t=e("git remote get-url origin");process.platform==="win32"&&(t=t.replace(/\\/g,"/"));let o=e("git rev-parse --abbrev-ref HEAD"),n=e("git rev-parse HEAD"),r=e("git diff"),i=e("git diff --cached"),c=[r,i].filter(Boolean).join(`
|
|
169
|
+
`),u="";try{let p=oe.join(s,".monkeyscode","rules.md");z.existsSync(p)&&(u=z.readFileSync(p,"utf8"))}catch{}let d="";try{let p=oe.join(s,".monkeyscode","config.json");z.existsSync(p)&&(d=z.readFileSync(p,"utf8"))}catch{}return{repo:t,branch:o,commit:n,dirtyDiff:c,rules:u,config:d}}function lm(s,e){let t=z.mkdtempSync(oe.join(im.tmpdir(),"mc-archive-")),o=oe.join(t,"snapshot");z.mkdirSync(o,{recursive:!0}),s.dirtyDiff&&z.writeFileSync(oe.join(o,"dirty.diff"),s.dirtyDiff,"utf8"),s.rules&&z.writeFileSync(oe.join(o,"rules.md"),s.rules,"utf8"),s.config&&z.writeFileSync(oe.join(o,"config.json"),s.config,"utf8"),e&&e.length>0&&z.writeFileSync(oe.join(o,"conversation.json"),JSON.stringify(e,null,2),"utf8"),z.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,Wo.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=am.gzipSync(Buffer.from(r,"utf8"));z.writeFileSync(n,i)}return n}async function pb(s){let e=Y(),o=fe()?.access_token;o||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),console.log(a.dim(" \u{1F4F8} Capturing workspace snapshot..."));let n=cm(s.workspace);n.repo||(console.error(a.red(" \u274C No git remote found. Background jobs require a git repository.")),process.exit(4));let r=new Ne(e.agentsUrl,o),i=null;try{console.log(a.dim(" \u{1F4E6} Creating compressed archive...")),i=lm(n,s.conversationHistory);let u=z.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);z.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 um({...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 um(s){let e=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,{getPlatformPaths:t}=await Promise.resolve().then(()=>(Z(),To)),o=t(),n=oe.join(o.data,"jobs",e);z.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};z.writeFileSync(oe.join(n,"config.json"),JSON.stringify(r,null,2),"utf8"),z.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",hb.url).pathname,c=(0,Wo.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 Ec(s){try{let{getPlatformPaths:e}=(Z(),Ls(To)),t=e(),o=oe.join(t.data,"jobs");if(!z.existsSync(o))return[];let n=z.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(z.readFileSync(oe.join(c,"status.json"),"utf8")),d=JSON.parse(z.readFileSync(oe.join(c,"config.json"),"utf8"));if(s?.status&&u.status!==s.status)continue;let p,f,m,h,g,y=oe.join(c,"result.json");if(z.existsSync(y)){let x=JSON.parse(z.readFileSync(y,"utf8"));p=x.duration,f=x.filesChanged?.length,m=x.tokensUsed,h=x.costUsd,(x.status==="completed"||x.status==="failed")&&(g=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:h,createdAt:new Date(z.statSync(oe.join(c,"config.json")).birthtimeMs),completedAt:g,currentStep:u.message})}catch{}}return r}catch{return[]}}function Fc(s){try{let{getPlatformPaths:e}=(Z(),Ls(To)),t=e(),o=oe.join(t.data,"jobs",s);if(!z.existsSync(o))return null;let n=JSON.parse(z.readFileSync(oe.join(o,"status.json"),"utf8")),r=JSON.parse(z.readFileSync(oe.join(o,"config.json"),"utf8")),i={id:s,status:n.status,prompt:r.prompt||"",model:r.model||"unknown",createdAt:new Date(z.statSync(oe.join(o,"config.json")).birthtimeMs),currentStep:n.message},c=oe.join(o,"result.json");if(z.existsSync(c)){let u=JSON.parse(z.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 Tc(s){try{let{getPlatformPaths:e}=(Z(),Ls(To)),t=e(),o=oe.join(t.data,"jobs",s,"log.jsonl");return z.existsSync(o)?z.readFileSync(o,"utf8").split(`
|
|
170
|
+
`).filter(Boolean).map(n=>{let r=JSON.parse(n);return{timestamp:new Date(r.timestamp),level:r.level||"info",message:r.message||""}}):[]}catch{return[]}}function Rc(s,e,t){try{console.log(a.dim(` \u{1F4E5} Fetching branch ${t}...`)),(0,Wo.execSync)(`git fetch origin "${t}"`,{cwd:s,stdio:"pipe"}),console.log(a.dim(` \u{1F500} Merging ${t} into current branch...`)),(0,Wo.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 dm(){return process.platform!=="win32"||!!process.env.WT_SESSION}function pm(s){return(dm()?mb:fb)[s]||"?"}function Ac(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=`${pm(n.status)} ${mm(n.status)}`,c=n.prompt.length>34?`"${n.prompt.substring(0,32)}..."`:`"${n.prompt}"`,u=n.duration?Cc(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 Yr(s,e){let t=dm();if(console.log(""),console.log(a.bold(` ${t?"\u{1F4CB}":">>"} Job: ${s.id}`)),console.log(a.dim(" "+(t?"\u2500":"-").repeat(50))),console.log(` Status: ${pm(s.status)} ${mm(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: ${Cc(s.duration)}`),s.estimatedTimeRemaining!=null&&console.log(` ETA: ~${Cc(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 Xr(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 rm(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 Cc(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 mm(s){return s.charAt(0).toUpperCase()+s.slice(1)}var z,oe,im,am,Wo,hb,Ne,mb,fb,gn=W(()=>{"use strict";z=w(require("node:fs"),1),oe=w(require("node:path"),1),im=w(require("node:os"),1),am=w(require("node:zlib"),1),Wo=require("node:child_process");H();Q();ee();hb={},Ne=class{static{l(this,"JobsApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/jobs`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async submit(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,jobId:o.id||o.jobId,branch:o.branch,dashboardUrl:o.dashboardUrl}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async requestUploadUrl(){try{let e=await fetch(`${this.baseUrl}/upload-url`,{method:"POST",headers:this.headers(),body:JSON.stringify({contentType:"application/gzip"}),signal:AbortSignal.timeout(1e4)});if(!e.ok)return null;let t=await e.json();return{uploadUrl:t.uploadUrl,archiveId:t.archiveId}}catch{return null}}async uploadArchive(e,t){try{let o=z.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(rm):[]}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 rm(o)}catch{return null}}async logs(e){try{let t=await fetch(`${this.baseUrl}/${e}/logs`,{headers:this.headers(),signal:AbortSignal.timeout(15e3)});return t.ok?((await t.json()).logs||[]).map(n=>({timestamp:new Date(n.timestamp),level:n.level||"info",message:n.message||n.text||""})):[]}catch{return[]}}async*followLogs(e){try{let t=await fetch(`${this.baseUrl}/${e}/logs/stream`,{headers:{...this.headers(),Accept:"text/event-stream"}});if(!t.ok||!t.body)return;let o=t.body.getReader(),n=new TextDecoder,r="";for(;;){let{done:i,value:c}=await o.read();if(i)break;r+=n.decode(c,{stream:!0});let u=r.split(`
|
|
171
|
+
`);r=u.pop()||"";for(let d of u)if(d.startsWith("data: "))try{let p=JSON.parse(d.substring(6));yield{timestamp:new Date(p.timestamp),level:p.level||"info",message:p.message||""}}catch{}}}catch{}}async message(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/message`,{method:"POST",headers:this.headers(),body:JSON.stringify({message:t}),signal:AbortSignal.timeout(1e4)});if(!o.ok){let n=await o.text().catch(()=>"");return o.status===409?{success:!1,error:"Job is no longer running, so it cannot be steered."}:{success:!1,error:`HTTP ${o.status}: ${n}`}}return{success:!0}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}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(cm,"captureWorkspaceSnapshot");l(lm,"createSnapshotArchive");l(pb,"submitBackgroundJob");l(um,"runLocalBackgroundJob");l(Ec,"getLocalJobs");l(Fc,"getLocalJobStatus");l(Tc,"getLocalJobLogs");l(Rc,"pullJobChanges");l(dm,"shouldUseUnicode");mb={queued:"\u23F3",running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u{1F6AB}"},fb={queued:"[Q]",running:"[~]",completed:"[+]",failed:"[X]",cancelled:"[-]"};l(pm,"getStatusIcon");l(Ac,"printJobsTable");l(Yr,"printJobStatus");l(Xr,"printLogEntry");l(rm,"parseJobInfo");l(Cc,"formatDuration");l(mm,"capitalize")});var fm={};Ae(fm,{resumeFromJob:()=>gb});async function gb(s){let e=Y(),o=fe()?.access_token;if(!o)return console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Not authenticated"};let n=new Ne(e.agentsUrl,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=yb(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,vs.execSync)("git apply --check -",{cwd:s.workspace,input:d,stdio:["pipe","pipe","pipe"]}),(0,vs.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=yn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:h}=await import("node:fs");return m(f,{recursive:!0}),h(yn.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.agentsUrl}/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=yn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:h}=await import("node:fs");m(f,{recursive:!0}),h(yn.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 yb(s,e){let t=[];try{let o=(0,vs.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,vs.execSync)("git diff --name-only",{cwd:s,encoding:"utf8"}).trim();if(r){let c=r.split(`
|
|
172
|
+
`).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,vs.execSync)("git diff --cached --name-only",{cwd:s,encoding:"utf8"}).trim();if(i){let c=i.split(`
|
|
173
|
+
`).filter(Boolean);t.push(`${c.length} staged file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}}catch{t.push("Unable to check git status (not a git repository?)")}return{compatible:t.length===0,reasons:t}}var yn,vs,hm=W(()=>{"use strict";yn=w(require("node:path"),1),vs=require("node:child_process");H();gn();Q();ee();l(gb,"resumeFromJob");l(yb,"checkSyncCompatibility")});function Mc(s){let e=St.join(s.workspace,wn,s.teamId,s.taskSlug),t=`monkeyscode/team-${s.teamId}/${s.taskSlug}`;mt.mkdirSync(St.dirname(e),{recursive:!0});let o=s.baseBranch||(0,Kt.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s.workspace,encoding:"utf8"}).trim();try{(0,Kt.execSync)(`git worktree add -b "${t}" "${e}" "${o}"`,{cwd:s.workspace,encoding:"utf8",stdio:"pipe"})}catch{try{(0,Kt.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,Kt.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 Oc(s,e,t=!1){let o=t?" --force":"",n=l(()=>{(0,Kt.execSync)(`git worktree remove "${e}"${o}`,{cwd:s,encoding:"utf8",stdio:"pipe"})},"tryRemove");if(process.platform==="win32")for(let r=0;r<Ic;r++)try{n();return}catch(i){if(r<Ic-1)(0,Kt.execSync)(`timeout /t ${Math.ceil(bb/1e3)}`,{stdio:"ignore"});else throw new Error(`Failed to remove worktree after ${Ic} attempts (files may be locked by another process): ${i instanceof Error?i.message:i}`)}else n();try{(0,Kt.execSync)("git worktree prune",{cwd:s,stdio:"pipe"})}catch{}}function kb(s){let e;try{e=(0,Kt.execSync)("git worktree list --porcelain",{cwd:s,encoding:"utf8"})}catch{return[]}let t=[],o=e.split(`
|
|
174
174
|
|
|
175
175
|
`).filter(Boolean);for(let n of o){let r=n.split(`
|
|
176
|
-
`),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=dt.statSync(i).birthtime}catch{}let g=i.split(Dt.sep),m=g.indexOf(pn.replace(/\//g,Dt.sep).split(Dt.sep)[0]),f=m>=0?g.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(pn),createdAt:p,label:f})}return t}function ys(s){return Ub(s).filter(e=>e.path.includes(pn))}function em(s){let e=s.ttlMs??Lb,t=Date.now(),o=[],n=[],r=ys(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Cc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=Dt.join(s.workspace,pn);try{tm(i)}catch{}return{removed:o,errors:n}}function tm(s){if(!dt.existsSync(s))return;let e=dt.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&tm(Dt.join(s,t.name));dt.readdirSync(s).length===0&&dt.rmdirSync(s)}function _c(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var dt,Dt,qt,pn,Lb,Bb,xc,Ec=G(()=>{"use strict";dt=b(require("node:fs"),1),Dt=b(require("node:path"),1),qt=require("node:child_process"),pn=".monkeyscode-worktrees",Lb=24*60*60*1e3,Bb=500,xc=3;l($c,"createWorktree");l(Cc,"removeWorktree");l(Ub,"listWorktrees");l(ys,"listManagedWorktrees");l(em,"cleanStaleWorktrees");l(tm,"cleanEmptyDirs");l(_c,"slugify")});var sm={};Ae(sm,{mergeTeam:()=>Tc,runInWorktree:()=>Hb,showTeamStatus:()=>Fc,spawnTeam:()=>Gr});async function Gr(s){let e=Gb(),t=s.tasks.map((m,f)=>({index:f+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(f){m.status="failed",m.error=f instanceof Error?f.message:String(f),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=K(),r=ge()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let f=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let h=(0,go.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let y=JSON.parse(h);m.filesChanged=y.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-f;try{(0,go.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,go.execSync)(`git commit -m "feat: ${m.task.substring(0,72)}" --allow-empty`,{cwd:m.worktree.path,stdio:"pipe"})}catch{}console.log(a.green(` \u2705 Agent #${m.index} completed (${om(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-f,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 f of i){for(;c.size>=s.maxAgents;)await new Promise(y=>setTimeout(y,500));c.add(f.index);let h=u(f).finally(()=>c.delete(f.index));m.push(h)}await Promise.all(m)},"processQueue")();try{let m=mn.join(s.workspace,".monkeyscode-worktrees",e);pt.mkdirSync(m,{recursive:!0});let f=mn.join(m,"state.json");pt.writeFileSync(f,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,g=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, ${g} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function Fc(s){let e=mn.join(s,".monkeyscode-worktrees");if(!pt.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=pt.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=mn.join(e,u.name,"state.json");if(pt.existsSync(d))try{t.push(JSON.parse(pt.readFileSync(d,"utf8")))}catch{}}}catch{}let o=ys(s),n=new Set(t.map(c=>c.teamId)),r=new Map;for(let c of o){let d=(c.label?.split("/")||[])[0]||"unknown";n.has(d)||(r.has(d)||r.set(d,[]),r.get(d).push(c))}if(t.length===0&&r.size===0){console.log(a.dim(" No active agent teams found."));return}let i=l(c=>{switch(c){case"completed":return"\u2705";case"running":return"\u{1F504}";case"queued":return"\u23F3";case"failed":return"\u274C";default:return"?"}},"statusIcon");for(let c of t){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c.teamId}`));let u=" "+"\u2500".repeat(76);console.log(u),console.log(a.bold(` ${"Agent".padEnd(8)} ${"Task".padEnd(34)} ${"Status".padEnd(12)} ${"Duration".padEnd(10)} ${"Files".padEnd(6)}`)),console.log(u);for(let d of c.agents){let p=i(d.status),g=d.duration?om(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",f=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+f+'"').padEnd(34)} ${(p+" "+Wb(d.status)).padEnd(12)} ${g.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 g=u[p],m=g.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${g.branch.padEnd(30)}`)}console.log(d)}console.log("")}function Wb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Tc(s,e){let t=ys(s).filter(r=>r.label?.startsWith(e));if(t.length===0){console.error(a.red(` \u274C No worktrees found for team ${e}.`));return}console.log(""),console.log(a.bold(` \u{1F500} Merging team ${e} (${t.length} branches)`));let o=0,n=0;for(let r of t){let i=r.label?.split("/").slice(1).join("/")||"?";console.log(a.dim(` Merging: ${r.branch} (${i})`));try{(0,go.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,go.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,go.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,go.execSync)(`git commit -m "feat: ${s.substring(0,72)}"`,{cwd:r.path,stdio:"pipe"})}catch{}console.log(a.green(" \u2705 Worktree task completed.")),console.log(a.dim(` Merge: git merge --no-ff ${r.branch}`))}catch(i){console.error(a.red(` \u274C Worktree task failed: ${i instanceof Error?i.message:i}`))}}function Gb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function om(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var pt,mn,go,Rc=G(()=>{"use strict";pt=b(require("node:fs"),1),mn=b(require("node:path"),1),go=require("node:child_process");W();Ec();Q();ee();l(Gr,"spawnTeam");l(Fc,"showTeamStatus");l(Wb,"capitalize");l(Tc,"mergeTeam");l(Hb,"runInWorktree");l(Gb,"generateTeamId");l(om,"formatDuration")});var qr={};Ae(qr,{MessageBroker:()=>gn});function qb(){try{let s=rm.join(im.homedir(),".monkeyscode","daemon.port"),e=nm.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var nm,rm,im,Ac,Pc,gn,fn=G(()=>{"use strict";nm=b(require("node:fs"),1),rm=b(require("node:path"),1),im=b(require("node:os"),1);an();Ac=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new lt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},Pc=class{constructor(e,t){this.platformUrl=e;this.token=t}static{l(this,"CloudTransport")}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async sendMessage(e,t,o){try{let n=await fetch(`${this.platformUrl}/api/messages`,{method:"POST",headers:this.headers(),body:JSON.stringify({from:e,to:t,content:o,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(!n.ok){let i=await n.text().catch(()=>"");return{success:!1,error:`HTTP ${n.status}: ${i}`}}return{success:!0,messageId:(await n.json()).messageId}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{let e=await fetch(`${this.platformUrl}/api/sessions`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).sessions||[]).map(o=>({id:o.id,task:o.task||o.prompt?.substring(0,80)||"(no task)",status:o.status||"running",type:o.type||"interactive",workspace:o.workspace||"",startedAt:new Date(o.startedAt||o.createdAt),model:o.model||"unknown"})):[]}catch{return[]}}async pollMessages(e){try{let t=await fetch(`${this.platformUrl}/api/messages/pending?session=${e}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)});if(!t.ok)return[];let n=((await t.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:!1}));for(let r of n)try{await fetch(`${this.platformUrl}/api/messages/${r.id}/ack`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)})}catch{}return n}catch{return[]}}async getMessageHistory(e,t){try{let o=await fetch(`${this.platformUrl}/api/messages?session=${e}&limit=${t}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return o.ok?((await o.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:r.delivered??!0})):[]}catch{return[]}}async register(){}async unregister(){}};l(qb,"readDaemonPort");gn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=qb();n?this.transport=new Ac(n):this.transport=new Pc(e,t)}async init(e,t,o){await this.transport.register(this.sessionId,e,t,o)}async dispose(){await this.transport.unregister(this.sessionId)}async sendMessage(e,t){return this.transport.sendMessage(this.sessionId,e,t)}async broadcast(e){return this.sendMessage("broadcast",e)}async listAgents(){return this.transport.listAgents()}async getMessageHistory(e=50){return this.transport.getMessageHistory(this.sessionId,e)}async checkPendingMessages(){return this.transport.pollMessages(this.sessionId)}onMessage(e){this.onMessageCallback=e}async pollMessages(){let e=await this.checkPendingMessages();if(this.onMessageCallback)for(let t of e)this.onMessageCallback(t);return e}static getToolSchemas(){return[{name:"SendMessage",description:"Send a message to another active agent session. Use when you make changes that affect shared code and other agents need to know.",parameters:{type:"object",properties:{target:{type:"string",description:'Target session ID (from ListAgents) or "broadcast" to notify all.'},message:{type:"string",description:"Message content describing what changed and what other agents should do."}},required:["target","message"]}},{name:"ListAgents",description:"List all active agent sessions on the current machine. Returns session IDs, tasks, and status.",parameters:{type:"object",properties:{}}}]}}});var cm={};Ae(cm,{analyzeImpact:()=>am,notifyAffectedSessions:()=>zb});function am(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=vt.basename(d).toLowerCase(),g=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),f=vt.dirname(m).split(vt.sep)[0];f&&i.includes(f.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${f}" directory where changes were made`)}for(let m of Vb)if(m.pathPattern.test(g))for(let f of m.keywords)i.includes(f)&&.6>u&&(u=.6,c=`Modified ${p} (${f}-related) \u2014 task mentions "${f}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function zb(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=am(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>vt.basename(p)).join(", "):`${e.slice(0,3).map(p=>vt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
177
|
-
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var
|
|
178
|
-
`);await i.run(c),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(c){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:c instanceof Error?c.message:String(c)})}finally{this.activeRuns.delete(e.name)}}updateState(e,t){let o=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};o.lastFired=Date.now(),o.fireCount++,o.lastResult=t,this.state.set(e,o),this.saveState()}saveState(){try{let e=
|
|
179
|
-
`),!0}function
|
|
176
|
+
`),i=r.find(g=>g.startsWith("worktree "))?.replace("worktree ",""),c=r.find(g=>g.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(g=>g.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(g=>g==="bare");if(!i||!c)continue;let p;try{p=mt.statSync(i).birthtime}catch{}let f=i.split(St.sep),m=f.indexOf(wn.replace(/\//g,St.sep).split(St.sep)[0]),h=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(wn),createdAt:p,label:h})}return t}function Ds(s){return kb(s).filter(e=>e.path.includes(wn))}function gm(s){let e=s.ttlMs??wb,t=Date.now(),o=[],n=[],r=Ds(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Oc(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=St.join(s.workspace,wn);try{ym(i)}catch{}return{removed:o,errors:n}}function ym(s){if(!mt.existsSync(s))return;let e=mt.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&ym(St.join(s,t.name));mt.readdirSync(s).length===0&&mt.rmdirSync(s)}function jc(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var mt,St,Kt,wn,wb,bb,Ic,Nc=W(()=>{"use strict";mt=w(require("node:fs"),1),St=w(require("node:path"),1),Kt=require("node:child_process"),wn=".monkeyscode-worktrees",wb=24*60*60*1e3,bb=500,Ic=3;l(Mc,"createWorktree");l(Oc,"removeWorktree");l(kb,"listWorktrees");l(Ds,"listManagedWorktrees");l(gm,"cleanStaleWorktrees");l(ym,"cleanEmptyDirs");l(jc,"slugify")});var bm={};Ae(bm,{mergeTeam:()=>Bc,runInWorktree:()=>Db,showTeamStatus:()=>Lc,spawnTeam:()=>Qr});async function Qr(s){let e=Sb(),t=s.tasks.map((m,h)=>({index:h+1,task:m,slug:jc(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=Mc({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(h){m.status="failed",m.error=h instanceof Error?h.message:String(h),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=Y(),r=fe()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let h=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let g=(0,bo.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let y=JSON.parse(g);m.filesChanged=y.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-h;try{(0,bo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,bo.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 (${wm(m.duration)}, ${m.filesChanged} files)`))}catch(g){m.status="failed",m.duration=Date.now()-h,m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Agent #${m.index} failed: ${m.error.substring(0,80)}`))}},"runAgent");await l(async()=>{let m=[];for(let h of i){for(;c.size>=s.maxAgents;)await new Promise(y=>setTimeout(y,500));c.add(h.index);let g=u(h).finally(()=>c.delete(h.index));m.push(g)}await Promise.all(m)},"processQueue")();try{let m=bn.join(s.workspace,".monkeyscode-worktrees",e);ft.mkdirSync(m,{recursive:!0});let h=bn.join(m,"state.json");ft.writeFileSync(h,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(g=>({index:g.index,task:g.task,slug:g.slug,status:g.status,duration:g.duration,filesChanged:g.filesChanged,error:g.error,branch:g.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 Lc(s){let e=bn.join(s,".monkeyscode-worktrees");if(!ft.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=ft.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=bn.join(e,u.name,"state.json");if(ft.existsSync(d))try{t.push(JSON.parse(ft.readFileSync(d,"utf8")))}catch{}}}catch{}let o=Ds(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?wm(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",h=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+h+'"').padEnd(34)} ${(p+" "+vb(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 vb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Bc(s,e){let t=Ds(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,bo.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{Oc(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 Db(s,e,t){let o=jc(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=Mc({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,bo.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,bo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,bo.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 Sb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function wm(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 ft,bn,bo,Uc=W(()=>{"use strict";ft=w(require("node:fs"),1),bn=w(require("node:path"),1),bo=require("node:child_process");H();Nc();Q();ee();l(Qr,"spawnTeam");l(Lc,"showTeamStatus");l(vb,"capitalize");l(Bc,"mergeTeam");l(Db,"runInWorktree");l(Sb,"generateTeamId");l(wm,"formatDuration")});var Zr={};Ae(Zr,{MessageBroker:()=>kn});function xb(){try{let s=vm.join(Dm.homedir(),".monkeyscode","daemon.port"),e=km.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var km,vm,Dm,Wc,Hc,kn,vn=W(()=>{"use strict";km=w(require("node:fs"),1),vm=w(require("node:path"),1),Dm=w(require("node:os"),1);mn();Wc=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 dt(`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()}},Hc=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(xb,"readDaemonPort");kn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=xb();n?this.transport=new Wc(n):this.transport=new Hc(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 xm={};Ae(xm,{analyzeImpact:()=>Sm,notifyAffectedSessions:()=>$b});function Sm(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=xt.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=xt.relative(r.workspace,d),h=xt.dirname(m).split(xt.sep)[0];h&&i.includes(h.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${h}" directory where changes were made`)}for(let m of _b)if(m.pathPattern.test(f))for(let h of m.keywords)i.includes(h)&&.6>u&&(u=.6,c=`Modified ${p} (${h}-related) \u2014 task mentions "${h}"`)}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 $b(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=Sm(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=>xt.basename(p)).join(", "):`${e.slice(0,3).map(p=>xt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
177
|
+
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var xt,_b,_m=W(()=>{"use strict";xt=w(require("node:path"),1),_b=[{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(Sm,"analyzeImpact");l($b,"notifyAffectedSessions")});var Cm={};Ae(Cm,{fetchModels:()=>$m,getModelInfo:()=>Cb});async function $m(){let s=Y(),e=await Fe(),t={};e&&(t.Authorization=`Bearer ${e}`);let o=await fetch(`${s.platformUrl}/v1/models`,{headers:t});if(!o.ok)throw o.status===401?new Error("Authentication expired \u2014 run `mc auth login`."):new Error(`Failed to fetch models: ${o.status} ${o.statusText}`);let n=await o.json(),r,i=n.flat;if(Array.isArray(i)&&i.length>0)r=i.map(c=>({id:c.id,name:c.display_name||c.id,contextWindow:c.context_window||128e3,supportsReasoning:c.supports_thinking||!1,supportsTools:!0,inputCostPer1M:c.cost_input_micros?c.cost_input_micros/1e6:void 0,outputCostPer1M:c.cost_output_micros?c.cost_output_micros/1e6:void 0}));else{let c=n.data;if(!Array.isArray(c))return[];r=c.map(u=>{let d=u.capabilities,p=u.pricing;return{id:u.id,name:u.name||u.id,contextWindow:u.context_window||128e3,supportsReasoning:d?.reasoning||!1,supportsTools:d?.tools!==!1,inputCostPer1M:p?.input_per_1m,outputCostPer1M:p?.output_per_1m}})}return _d(r),r}async function Cb(s){try{return(await $m()).find(t=>t.id===s)||null}catch{return null}}var Em=W(()=>{"use strict";ee();Q();Sr();l($m,"fetchModels");l(Cb,"getModelInfo")});var Xm={};Ae(Xm,{default:()=>qb});var qb,Qm=W(()=>{qb={name:"monkeyscode-cli",version:"0.1.11",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:{"@monkeyscode/sdk":"file:../../packages/sdk-typescript",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 li,xf=W(()=>{"use strict";li=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 Rn,il,ui,_f=W(()=>{"use strict";Rn=w(require("node:fs"),1),il=w(require("node:path"),1),ui=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=Rn.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=Rn.readdirSync(e,{withFileTypes:!0});for(let n of o){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let r=il.join(e,n.name);try{let i=Rn.watch(r,(c,u)=>{!u||!this.running||this.onFileChange(il.join(n.name,u))});this.watchers.push(i),this.watchDirectories(r,t+1)}catch{}}}catch{}}}});var Cf={};Ae(Cf,{TriggerEngine:()=>al});var Ct,An,$f,al,Ef=W(()=>{"use strict";Ct=w(require("node:fs"),1),An=w(require("node:path"),1),$f=require("node:events");Xe();Q();xf();_f();al=class extends $f.EventEmitter{static{l(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=An.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new li,this.fileWatcher=new ui(e.workspace),this.loadState()}loadTriggers(){let e=An.join(this.opts.workspace,".monkeyscode","triggers.json");if(!Ct.existsSync(e))return this.triggers=[],[];try{let t=JSON.parse(Ct.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=Y(),i=new xe({platformUrl:r.platformUrl,token:this.opts.token,model:e.model||r.defaultModel||"capuchin-reason",workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!0,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeRuns.set(e.name,i);try{let c=[`[Trigger: ${e.name}]`,`Event: ${t.type}`,t.payload?`Payload: ${JSON.stringify(t.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
|
|
178
|
+
`);await i.run(c),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(c){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:c instanceof Error?c.message:String(c)})}finally{this.activeRuns.delete(e.name)}}updateState(e,t){let o=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};o.lastFired=Date.now(),o.fireCount++,o.lastResult=t,this.state.set(e,o),this.saveState()}saveState(){try{let e=An.dirname(this.statePath);Ct.mkdirSync(e,{recursive:!0}),Ct.writeFileSync(this.statePath,JSON.stringify(Object.fromEntries(this.state),null,2))}catch{}}loadState(){try{if(Ct.existsSync(this.statePath)){let e=JSON.parse(Ct.readFileSync(this.statePath,"utf8"));this.state=new Map(Object.entries(e))}}catch{this.state=new Map}}}});var Tf={};Ae(Tf,{GitHubWebhookServer:()=>cl});var Ff,Cs,cl,Rf=W(()=>{"use strict";Ff=w(require("node:http"),1),Cs=w(require("node:crypto"),1),cl=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"]||Cs.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="+Cs.createHmac("sha256",o).update(e).digest("hex");return Cs.timingSafeEqual(Buffer.from(t),Buffer.from(n))}}});var av,Eh=W(()=>{"use strict";av=require("node:child_process")});var fv,Ph=W(()=>{"use strict";fv=require("node:crypto")});var og={};Ae(og,{getNotificationBackend:()=>Mv,notifyJobComplete:()=>Av,notifyUpdateAvailable:()=>Pv,sendNotification:()=>Cl,supportsNotifications:()=>Iv});function Cl(s){if(process.env.CI==="true"||process.env.CI==="1")return!1;try{switch(process.platform){case"darwin":return Ov(s);case"linux":return jv(s);case"win32":return Uv(s);default:return!1}}catch{return!1}}function Av(s,e,t){return Cl({title:t?"\u2705 Job Complete":"\u274C Job Failed",body:`Job ${s}: ${e}`,subtitle:"MonkeysCode",sound:t?"Glass":"Basso",urgency:t?"normal":"critical"})}function Pv(s){return Cl({title:"\u{1F504} Update Available",body:`MonkeysCode v${s} is available. Run: mc update`,subtitle:"MonkeysCode",urgency:"low"})}function Iv(){if(process.env.CI==="true"||process.env.CI==="1")return!1;switch(process.platform){case"darwin":return Rt("osascript");case"linux":return!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY?!1:Rt("notify-send")||Rt("kdialog")||Rt("zenity");case"win32":return!0;default:return!1}}function Mv(){switch(process.platform){case"darwin":return"macOS (osascript)";case"linux":return Rt("notify-send")?"Linux (notify-send)":Rt("kdialog")?"Linux (kdialog)":Rt("zenity")?"Linux (zenity)":"Linux (terminal bell)";case"win32":return"Windows (PowerShell toast)";default:return"Unsupported"}}function Ov(s){let e=ki(s.title),o=`display notification "${ki(s.body)}" with title "${e}"`;s.subtitle&&(o+=` subtitle "${ki(s.subtitle)}"`),s.sound&&(o+=` sound name "${ki(s.sound)}"`);let n=_l.join($l.tmpdir(),`mc-notify-${process.pid}.scpt`);try{return $o.writeFileSync(n,o,"utf8"),(0,oo.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{$o.unlinkSync(n)}catch{}}}function ki(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function jv(s){if(!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)){if(Rt("notify-send"))return Nv(s);if(Rt("kdialog"))return Lv(s);if(Rt("zenity"))return Bv(s)}return process.stderr.write("\x07"),process.stderr.write(`[Notification] ${s.title}: ${s.body}
|
|
179
|
+
`),!0}function Nv(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($o.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,oo.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Lv(s){try{return(0,oo.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Bv(s){try{return(0,oo.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Uv(s){let e=tg(s.title),t=tg(s.body),o=`
|
|
180
180
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
181
181
|
|
|
182
182
|
# Try WinRT Toast (Windows 10 1709+)
|
|
@@ -240,55 +240,55 @@ try {
|
|
|
240
240
|
catch {}
|
|
241
241
|
|
|
242
242
|
exit 1
|
|
243
|
-
`,n=
|
|
244
|
-
${e}`,"wrappedToString"),kh=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),Dh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),vh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=wh.bind(null,o,e.toString());Object.defineProperty(n,"name",Dh);let{writable:r,enumerable:i,configurable:c}=kh;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Ii(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))hh(s,e,n,t);return bh(s,e),vh(s,e,o),s}l(Ii,"mimicFunction");var Gn=new WeakMap,Gl=l((s,e={})=>{if(typeof s!="function")throw new TypeError("Expected a function");let t,o=0,n=s.displayName||s.name||"<anonymous>",r=l(function(...i){if(Gn.set(r,++o),o===1)t=s.apply(this,i),s=void 0;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return t},"onetime");return Ii(r,s),Gn.set(r,o),r},"onetime");Gl.callCount=s=>{if(!Gn.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Gn.get(s)};var ql=Gl;var So=[];So.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&So.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&So.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var qn=l(s=>!!s&&typeof s=="object"&&typeof s.removeListener=="function"&&typeof s.emit=="function"&&typeof s.reallyExit=="function"&&typeof s.listeners=="function"&&typeof s.kill=="function"&&typeof s.pid=="number"&&typeof s.on=="function","processOk"),ji=Symbol.for("signal-exit emitter"),Ni=globalThis,Sh=Object.defineProperty.bind(Object),Li=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ni[ji])return Ni[ji];Sh(Ni,ji,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let o=this.listeners[e],n=o.indexOf(t);n!==-1&&(n===0&&o.length===1?o.length=0:o.splice(n,1))}emit(e,t,o){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,o)===!0||n;return e==="exit"&&(n=this.emit("afterExit",t,o)||n),n}},Vn=class{static{l(this,"SignalExitBase")}},xh=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Bi=class extends Vn{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Ui=class extends Vn{static{l(this,"SignalExit")}#i=Wi.platform==="win32"?"SIGINT":"SIGHUP";#o=new Li;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of So)this.#t[t]=()=>{let o=this.#e.listeners(t),{count:n}=this.#o,r=e;if(typeof r.__signal_exit_emitter__=="object"&&typeof r.__signal_exit_emitter__.count=="number"&&(n+=r.__signal_exit_emitter__.count),o.length===n){this.unload();let i=this.#o.emit("exit",null,t),c=t==="SIGHUP"?this.#i:t;i||e.kill(e.pid,c)}};this.#p=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!qn(this.#e))return()=>{};this.#r===!1&&this.load();let o=t?.alwaysLast?"afterExit":"exit";return this.#o.on(o,e),()=>{this.#o.removeListener(o,e),this.#o.listeners.exit.length===0&&this.#o.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#r){this.#r=!0,this.#o.count+=1;for(let e of So)try{let t=this.#t[e];t&&this.#e.on(e,t)}catch{}this.#e.emit=(e,...t)=>this.#m(e,...t),this.#e.reallyExit=e=>this.#s(e)}}unload(){this.#r&&(this.#r=!1,So.forEach(e=>{let t=this.#t[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch{}}),this.#e.emit=this.#n,this.#e.reallyExit=this.#p,this.#o.count-=1)}#s(e){return qn(this.#e)?(this.#e.exitCode=e||0,this.#o.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...t){let o=this.#n;if(e==="exit"&&qn(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);let n=o.call(this.#e,e,...t);return this.#o.emit("exit",this.#e.exitCode,null),n}else return o.call(this.#e,e,...t)}},Wi=globalThis.process,{onExit:Vl,load:ND,unload:LD}=xh(qn(Wi)?new Ui(Wi):new Bi);var zl=js.default.stderr.isTTY?js.default.stderr:js.default.stdout.isTTY?js.default.stdout:void 0,$h=zl?ql(()=>{Vl(()=>{zl.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Jl=$h;var zn=!1,Xo={};Xo.show=(s=Hi.default.stderr)=>{s.isTTY&&(zn=!1,s.write("\x1B[?25h"))};Xo.hide=(s=Hi.default.stderr)=>{s.isTTY&&(Jl(),zn=!0,s.write("\x1B[?25l"))};Xo.toggle=(s,e)=>{s!==void 0&&(zn=s),zn?Xo.show(e):Xo.hide(e)};var Gi=Xo;var Us=b(qi(),1);W();var ze=b(require("node:process"),1);function Vi(){return ze.default.platform!=="win32"?ze.default.env.TERM!=="linux":!!ze.default.env.CI||!!ze.default.env.WT_SESSION||!!ze.default.env.TERMINUS_SUBLIME||ze.default.env.ConEmuTask==="{cmd::Cmder}"||ze.default.env.TERM_PROGRAM==="Terminus-Sublime"||ze.default.env.TERM_PROGRAM==="vscode"||ze.default.env.TERM==="xterm-256color"||ze.default.env.TERM==="alacritty"||ze.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Vi,"isUnicodeSupported");var _h={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},Eh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},Fh=Vi()?_h:Eh,Ns=Fh;function zi({onlyFirst:s=!1}={}){let n="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(n,s?void 0:"g")}l(zi,"ansiRegex");var Th=zi();function Ls(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(Th,"")}l(Ls,"stripAnsi");var Ql=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Zl=12288,eu=65510,tu=[12288,12288,65281,65376,65504,65510];var ou=4352,su=262141,Ji=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Kn=l((s,e)=>{let t=0,o=Math.floor(s.length/2)-1;for(;t<=o;){let n=Math.floor((t+o)/2),r=n*2;if(e<s[r])o=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1},"isInRange");var nu=19968,[Ph,Oh]=Mh(Ji);function Mh(s){let e=s[0],t=s[1];for(let o=0;o<s.length;o+=2){let n=s[o],r=s[o+1];if(nu>=n&&nu<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(Mh,"findWideFastPathRange");var ru=l(s=>s<161||s>1114109?!1:Kn(Ql,s),"isAmbiguous"),iu=l(s=>s<Zl||s>eu?!1:Kn(tu,s),"isFullWidth");var au=l(s=>s>=Ph&&s<=Oh?!0:s<ou||s>su?!1:Kn(Ji,s),"isWide");function Ih(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(Ih,"validate");function cu(s,{ambiguousAsWide:e=!1}={}){return Ih(s),iu(s)||au(s)||e&&ru(s)?2:1}l(cu,"eastAsianWidth");var du=b(uu(),1);var jh=new Intl.Segmenter,Nh=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Ki(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=Ls(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of jh.segment(s)){let c=i.codePointAt(0);if(!(c<=31||c>=127&&c<=159)&&!(c>=8203&&c<=8207||c===65279)&&!(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)&&!(c>=55296&&c<=57343)&&!(c>=65024&&c<=65039)&&!Nh.test(i)){if((0,du.default)().test(i)){n+=2;continue}n+=cu(c,r)}}return n}l(Ki,"stringWidth");function Yi({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(Yi,"isInteractive");var Xi=b(require("node:process"),1);function Qi(){let{env:s}=Xi.default,{TERM:e,TERM_PROGRAM:t}=s;return Xi.default.platform!=="win32"?e!=="linux":!!s.WT_SESSION||!!s.TERMINUS_SUBLIME||s.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||s.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Qi,"isUnicodeSupported");var nt=b(require("node:process"),1);var Lh=3,Zi=class{static{l(this,"StdinDiscarder")}#i=0;start(){this.#i++,this.#i===1&&this.#o()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#o(){nt.default.platform==="win32"||!nt.default.stdin.isTTY||(nt.default.stdin.setRawMode(!0),nt.default.stdin.on("data",this.#n),nt.default.stdin.resume())}#e(){nt.default.stdin.isTTY&&(nt.default.stdin.off("data",this.#n),nt.default.stdin.pause(),nt.default.stdin.setRawMode(!1))}#n(e){e[0]===Lh&&nt.default.emit("SIGINT")}},Bh=new Zi,ea=Bh;var Uh=b(qi(),1);var ta=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#f;#l;#u;#d;#h;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Bs.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#f=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Yi({stream:this.#s}),this.#u=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Bs.default.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(t){this.#i=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#n}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#g()}get interval(){return this.#f??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#f=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!Qi())this.#r=Us.default.line;else if(e===void 0)this.#r=Us.default.dots;else if(e!=="default"&&Us.default[e])this.#r=Us.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#h}set text(e=""){this.#h=e,this.#g()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#g()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#g()}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():""}#g(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),o=this.#b(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#h+"--"+o;this.#e=0;for(let r of Ls(n).split(`
|
|
245
|
-
`))this.#e+=Math.max(1,Math.ceil(
|
|
246
|
-
`),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&
|
|
247
|
-
`;return this.stop(),this.#s.write(p),this}};function
|
|
248
|
-
`),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,
|
|
249
|
-
`)}l(
|
|
250
|
-
`),m=
|
|
251
|
-
`).slice(0,10);for(let m of
|
|
252
|
-
`)}l(
|
|
253
|
-
`)}l(
|
|
243
|
+
`,n=_l.join($l.tmpdir(),`mc-notify-${process.pid}.ps1`);try{let r=Buffer.from([239,187,191]),i=Buffer.concat([r,Buffer.from(o,"utf8")]);return $o.writeFileSync(n,i),(0,oo.execSync)(`powershell -NoProfile -ExecutionPolicy Bypass -File "${n}"`,{stdio:"pipe",timeout:15e3}),!0}catch{return!1}finally{try{$o.unlinkSync(n)}catch{}}}function tg(s){return s.replace(/'/g,"''")}function Rt(s){try{return process.platform==="win32"?(0,oo.execSync)(`where ${s} 2>NUL`,{stdio:"pipe"}):(0,oo.execSync)(`command -v ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}var $o,_l,$l,oo,sg=W(()=>{"use strict";$o=w(require("node:fs"),1),_l=w(require("node:path"),1),$l=w(require("node:os"),1),oo=require("node:child_process");l(Cl,"sendNotification");l(Av,"notifyJobComplete");l(Pv,"notifyUpdateAvailable");l(Iv,"supportsNotifications");l(Mv,"getNotificationBackend");l(Ov,"notifyMac");l(ki,"escapeAS");l(jv,"notifyLinux");l(Nv,"notifyLinuxLibnotify");l(Lv,"notifyLinuxKdialog");l(Bv,"notifyLinuxZenity");l(Uv,"notifyWindows");l(tg,"escapePowerShell");l(Rt,"commandExists")});var Gl=w(Hl(),1),{program:rD,createCommand:iD,createArgument:aD,createOption:cD,CommanderError:lD,InvalidArgumentError:uD,InvalidOptionArgumentError:dD,Command:ql,Argument:pD,Option:Mt,Help:mD}=Gl.default;var B=w(require("node:path"),1),X=w(require("node:fs"),1);var Tm=w(require("node:readline"),1),K=w(require("node:path"),1),N=w(require("node:fs"),1),et=require("node:child_process");H();H();var Vs=w(require("node:process"),1);H();var Zi=w(require("node:process"),1);var Hs=w(require("node:process"),1);var Kg=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);!Yg(n,r)&&o||Object.defineProperty(s,t,r)},"copyProperty"),Yg=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"),Xg=l((s,e)=>{let t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(s)&&Object.setPrototypeOf(s,t)},"changePrototype"),Qg=l((s,e)=>`/* Wrapped ${s}*/
|
|
244
|
+
${e}`,"wrappedToString"),Zg=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ey=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),ty=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=Qg.bind(null,o,e.toString());Object.defineProperty(n,"name",ey);let{writable:r,enumerable:i,configurable:c}=Zg;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Vi(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))Kg(s,e,n,t);return Xg(s,e),ty(s,e,o),s}l(Vi,"mimicFunction");var Qn=new WeakMap,iu=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(Qn.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 Vi(r,s),Qn.set(r,o),r},"onetime");iu.callCount=s=>{if(!Qn.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Qn.get(s)};var au=iu;var Eo=[];Eo.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Eo.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Eo.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Zn=l(s=>!!s&&typeof s=="object"&&typeof s.removeListener=="function"&&typeof s.emit=="function"&&typeof s.reallyExit=="function"&&typeof s.listeners=="function"&&typeof s.kill=="function"&&typeof s.pid=="number"&&typeof s.on=="function","processOk"),Ji=Symbol.for("signal-exit emitter"),zi=globalThis,oy=Object.defineProperty.bind(Object),Ki=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(zi[Ji])return zi[Ji];oy(zi,Ji,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let o=this.listeners[e],n=o.indexOf(t);n!==-1&&(n===0&&o.length===1?o.length=0:o.splice(n,1))}emit(e,t,o){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,o)===!0||n;return e==="exit"&&(n=this.emit("afterExit",t,o)||n),n}},er=class{static{l(this,"SignalExitBase")}},sy=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Yi=class extends er{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Xi=class extends er{static{l(this,"SignalExit")}#i=Qi.platform==="win32"?"SIGINT":"SIGHUP";#o=new Ki;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of Eo)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(!Zn(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 Eo)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,Eo.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 Zn(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"&&Zn(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)}},Qi=globalThis.process,{onExit:cu,load:OD,unload:jD}=sy(Zn(Qi)?new Xi(Qi):new Yi);var lu=Hs.default.stderr.isTTY?Hs.default.stderr:Hs.default.stdout.isTTY?Hs.default.stdout:void 0,ny=lu?au(()=>{cu(()=>{lu.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},uu=ny;var tr=!1,os={};os.show=(s=Zi.default.stderr)=>{s.isTTY&&(tr=!1,s.write("\x1B[?25h"))};os.hide=(s=Zi.default.stderr)=>{s.isTTY&&(uu(),tr=!0,s.write("\x1B[?25l"))};os.toggle=(s,e)=>{s!==void 0&&(tr=s),tr?os.show(e):os.hide(e)};var ea=os;var Js=w(ta(),1);H();var Ke=w(require("node:process"),1);function oa(){return Ke.default.platform!=="win32"?Ke.default.env.TERM!=="linux":!!Ke.default.env.CI||!!Ke.default.env.WT_SESSION||!!Ke.default.env.TERMINUS_SUBLIME||Ke.default.env.ConEmuTask==="{cmd::Cmder}"||Ke.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ke.default.env.TERM_PROGRAM==="vscode"||Ke.default.env.TERM==="xterm-256color"||Ke.default.env.TERM==="alacritty"||Ke.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(oa,"isUnicodeSupported");var iy={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},ay={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},cy=oa()?iy:ay,Gs=cy;function sa({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(sa,"ansiRegex");var ly=sa();function qs(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(ly,"")}l(qs,"stripAnsi");var fu=[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],hu=12288,gu=65510,yu=[12288,12288,65281,65376,65504,65510];var wu=4352,bu=262141,na=[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 sr=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 ku=19968,[py,my]=fy(na);function fy(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(ku>=n&&ku<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(fy,"findWideFastPathRange");var vu=l(s=>s<161||s>1114109?!1:sr(fu,s),"isAmbiguous"),Du=l(s=>s<hu||s>gu?!1:sr(yu,s),"isFullWidth");var Su=l(s=>s>=py&&s<=my?!0:s<wu||s>bu?!1:sr(na,s),"isWide");function hy(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(hy,"validate");function xu(s,{ambiguousAsWide:e=!1}={}){return hy(s),Du(s)||Su(s)||e&&vu(s)?2:1}l(xu,"eastAsianWidth");var Cu=w($u(),1);var gy=new Intl.Segmenter,yy=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function ra(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=qs(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of gy.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)&&!yy.test(i)){if((0,Cu.default)().test(i)){n+=2;continue}n+=xu(c,r)}}return n}l(ra,"stringWidth");function ia({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(ia,"isInteractive");var aa=w(require("node:process"),1);function ca(){let{env:s}=aa.default,{TERM:e,TERM_PROGRAM:t}=s;return aa.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(ca,"isUnicodeSupported");var it=w(require("node:process"),1);var wy=3,la=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(){it.default.platform==="win32"||!it.default.stdin.isTTY||(it.default.stdin.setRawMode(!0),it.default.stdin.on("data",this.#n),it.default.stdin.resume())}#e(){it.default.stdin.isTTY&&(it.default.stdin.off("data",this.#n),it.default.stdin.pause(),it.default.stdin.setRawMode(!1))}#n(e){e[0]===wy&&it.default.emit("SIGINT")}},by=new la,ua=by;var ky=w(ta(),1);var da=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#h;#l;#u;#d;#g;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Vs.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#h=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:ia({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,Vs.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.#h??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#h=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(!ca())this.#r=Js.default.line;else if(e===void 0)this.#r=Js.default.dots;else if(e!=="default"&&Js.default[e])this.#r=Js.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.#g}set text(e=""){this.#g=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:""}#w(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.#w(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#g+"--"+o;this.#e=0;for(let r of qs(n).split(`
|
|
245
|
+
`))this.#e+=Math.max(1,Math.ceil(ra(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&&ea.hide(this.#s),this.#t.discardStdin&&Vs.default.stdin.isTTY&&(this.#o=!0,ua.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#s.write(`- ${this.text}
|
|
246
|
+
`),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&ea.show(this.#s),this.#t.discardStdin&&Vs.default.stdin.isTTY&&this.#o&&(ua.stop(),this.#o=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Gs.success,text:e})}fail(e){return this.stopAndPersist({symbol:Gs.error,text:e})}warn(e){return this.stopAndPersist({symbol:Gs.warning,text:e})}info(e){return this.stopAndPersist({symbol:Gs.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.#w(u," "),p=o+n+c+d+`
|
|
247
|
+
`;return this.stop(),this.#s.write(p),this}};function zs(s){return new da(s)}l(zs,"ora");Ce();H();Ce();H();Ce();function Eu(s,e,t={}){let o=j(),n=Me(o),r=G(o),i=t.maxWidth??o.columns,c=t.color??o.ansi,u=e.split(`
|
|
248
|
+
`),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,f=n.horizontal.repeat(Math.max(0,i-Tu(p).length-1));d.push(c?a.cyan(p+f+n.topRight):p+f+n.topRight);let m=0,h=0;for(let v of u)if(!(v.startsWith("---")||v.startsWith("+++")||v.startsWith("diff ")||v.startsWith("index "))){if(v.startsWith("@@")){let _=`${n.vertical} ${v}`;d.push(c?a.magenta(_):_);continue}if(v.startsWith("+")){m++;let _=`${n.vertical} + ${v.slice(1)}`,S=pa(_,i);d.push(c?a.green(S):S);continue}if(v.startsWith("-")){h++;let _=`${n.vertical} - ${v.slice(1)}`,S=pa(_,i);d.push(c?a.red(S):S);continue}if(v.startsWith(" ")||v===""){let _=`${n.vertical} ${v}`,S=pa(_,i);d.push(c?a.dim(S):S)}}let g=` +${m} -${h} `,y=`${n.bottomLeft}${n.horizontal}${g}`,x=n.horizontal.repeat(Math.max(0,i-y.length-1));return d.push(c?a.cyan(y+x+n.bottomRight):y+x+n.bottomRight),d.join(`
|
|
249
|
+
`)}l(Eu,"renderDiff");function Fu(s,e,t){let o=j(),n=G(o),r=o.ansi,i=r?a.green(`+${e}`):`+${e}`,c=r?a.red(`-${t}`):`-${t}`;return` ${n.file} ${s} (${i} ${c})`}l(Fu,"renderDiffSummary");function pa(s,e){return Tu(s).length<=e?s:s.slice(0,e-3)+"..."}l(pa,"truncateLine");function Tu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(Tu,"stripAnsi");function fa(s,e){let t=j(),o=G(t),n=t.ansi,r=Wy(s,o),i=Hy(s,e),c=` ${r} ${s}: ${i}`;return n?a.yellow(c):c}l(fa,"renderToolStart");function ha(s,e,t={}){switch(e.type){case"file_edit":return Iy(e,t);case"file_read":return My(e);case"terminal":return Oy(e,t);case"search":return jy(e,t);case"git":return Ny(e);case"browser":return Ly(e);case"mcp":return By(e);case"web_search":return Uy(e);case"generic":return Ru(s,e);default:return Ru(s,{type:"generic",summary:JSON.stringify(e)})}}l(ha,"renderToolResult");function Au(s,e){let t=j(),o=G(t),n=t.ansi,r=` ${o.error} ${s} failed: ${e}`;return n?a.red(r):r}l(Au,"renderToolError");function Iy(s,e){return e.verbose&&s.diff?Eu(s.filePath,s.diff):Fu(s.filePath,s.linesAdded,s.linesRemoved)}l(Iy,"renderFileEdit");function My(s){let e=j();return` ${G(e).file} Read ${ma(s.filePath)} (${s.lineCount} lines)`}l(My,"renderFileRead");function Oy(s,e){let t=j(),o=Me(t),n=G(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(`
|
|
250
|
+
`),m=f.slice(0,i);for(let h of m)c.push(r?a.dim(` ${h}`):` ${h}`);if(f.length>i){let h=` [truncated ${f.length-i} lines \u2014 use --verbose for full output]`;c.push(r?a.yellow(h):h)}}if(s.stderr&&s.stderr!==s.stdout){let f=s.stderr.split(`
|
|
251
|
+
`).slice(0,10);for(let m of f)c.push(r?a.red(` ${m}`):` ${m}`)}let p=s.duration?` (${(s.duration/1e3).toFixed(1)}s)`:"";return c.push(` ${u} Exit ${s.exitCode}${p}`),c.join(`
|
|
252
|
+
`)}l(Oy,"renderTerminal");function jy(s,e){let t=j(),o=G(t),n=t.ansi,r=[];r.push(` ${o.search} Search: "${s.query}" (${s.totalMatches} matches)`);let i=e.verbose?20:8,c=s.matches.slice(0,i);for(let u of c){let d=`${u.file}:${u.line}`,p=u.content.trim().slice(0,80),f=` ${d}: ${p}`;r.push(n?a.dim(f):f)}return s.matches.length>i&&r.push(n?a.yellow(` ... ${s.matches.length-i} more matches`):` ... ${s.matches.length-i} more matches`),r.join(`
|
|
253
|
+
`)}l(jy,"renderSearch");function Ny(s){let e=j(),t=G(e),o=e.ansi,n=[];if(n.push(` ${t.git} git ${s.command}`),s.output){let r=s.output.split(`
|
|
254
254
|
`).slice(0,15);for(let i of r)n.push(o?a.dim(` ${i}`):` ${i}`)}return n.join(`
|
|
255
|
-
`)}l(
|
|
256
|
-
`)}l(
|
|
257
|
-
`).slice(0,10);for(let
|
|
258
|
-
`).length>10&&i.push(`${o.vertical} ${n?a.dim(`... ${
|
|
259
|
-
`).length-10} more lines`):"..."}`);let
|
|
260
|
-
`)}l(
|
|
261
|
-
`)}l(
|
|
262
|
-
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(
|
|
263
|
-
`)}l(
|
|
264
|
-
`)}l(
|
|
265
|
-
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=I(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,y=t.dirty?a.yellow:a.green,S=t.dirty?" \u25CF":"";o.push(y(` ${h} ${t.branch}${S} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=my(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,y=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(y(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,y=6,S=Math.round(t.contextPct/100*y),D=y-S,C=h("\u2588".repeat(S))+a.dim("\u2591".repeat(D));r.push(` ${C} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=wu(c).length,p=wu(u).length,g=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),f=m(" ".repeat(g));return m(c)+f+m(u)}};function my(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(my,"formatTokensCompact");function wu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(wu,"stripAnsi");W();var Je={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},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..................."]},fy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},hy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},yy={large:gy,medium:fy,mini:hy},ku="\u25C1\u2571\u25B7",Du="</>";function vu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(vu,"isDarkBackground");function Su(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=yy[s],c=o?Je.navyOnDark:Je.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Je.ice):m=>m,p=l((m,f)=>f==="n"?u(m):f==="l"?d(m):m,"paint"),g=" ".repeat(r!==void 0?Math.max(0,Math.floor((r-i.width)/2)):n);return i.glyphs.map((m,f)=>{let h=i.mask[f],y="",S="",D=h[0]??".";for(let C=0;C<m.length;C++){let x=h[C]??".";x!==D&&(y+=p(S,D),S="",D=x),S+=m[C]}return y+=p(S,D),(g+y).replace(/\s+$/,"")})}l(Su,"renderLogo");function xu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(xu,"pickLogoSize");function ia(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(ia,"visibleWidth");var by={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Co=class{static{l(this,"TuiRenderer")}caps;icons;box;opts;spinner=null;activeToolSpinners=new Map;toolDurations=new Map;toolStartTimes=new Map;tokenBuffer="";lastWasToken=!1;statusBar=null;currentTurn=0;turnTokens=0;constructor(e={}){this.opts={...by,...e},this.caps=I(),this.icons=H(this.caps),this.box=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 Zn(e)),this.statusBar}printTurnBoundary(e,t,o,n){let r=this.caps.ansi,i=Math.min(60,this.caps.columns-4),c=t>=1e3?`${(t/1e3).toFixed(1)}K`:`${t}`,u=o?` ${this.icons.cost} $${o.toFixed(3)}`:"",d=n?` ${a.dim(`total: $${n.toFixed(2)}`)}`:"",p=` Turn ${e} ${a.dim("\xB7")} ${c} tokens${u}${d} `,g=p.replace(/\x1b\[[0-9;]*m/g,"").length,m=Math.max(0,i-g),f=Math.floor(m/2),h=` ${this.box.horizontal.repeat(f)}${p}${this.box.horizontal.repeat(m-f)}`;console.log(""),console.log(r?a.dim(h):h),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,t={}){let o=this.caps.ansi,n=o?a.hex(Je.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.10";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?xu(this.caps.columns,this.caps.unicode):u;if(d){let g=Su(d,{color:o,dark:vu(),center:Math.min(56,this.caps.columns)});for(let m of g)console.log(m);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,g=52;console.log(n(` ${p.topLeft}${p.horizontal.repeat(g)}${p.topRight}`));let f=`${this.caps.nerdFont?"\uF120":ku} MonkeysCode`,h="CLI Agent",y=Math.max(0,g-ia(f)-h.length-2);console.log(` ${n(p.vertical)} ${i(f)}${" ".repeat(y)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(g)}${p.teeLeft}`));let S=`${c}${e?` \xB7 ${e}`:""}`,D=Math.max(0,g-ia(S)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(D)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(g)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${Du} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let t=a.hex(Je.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
266
|
-
`+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(
|
|
267
|
-
`).slice(0,5);for(let c of i)console.log(t?a.dim(` ${c}`):` ${c}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let t=this.caps.ansi;console.log(t?a.dim(` ${e}`):` ${e}`)}printSuccess(e){let t=this.caps.ansi;console.log(t?a.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let t=this.caps.ansi;console.error(t?a.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let t=this.caps.ansi;console.log(t?a.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=
|
|
268
|
-
`).length;if(this.caps.ansi&&
|
|
255
|
+
`)}l(Ny,"renderGit");function Ly(s){let e=j(),t=G(e),o=e.ansi,n=[];if(n.push(` ${t.browser} ${s.title||s.url}`),s.url&&n.push(o?a.dim(` ${s.url}`):` ${s.url}`),s.content){let r=s.content.slice(0,200).replace(/\n/g," ");n.push(o?a.dim(` ${r}...`):` ${r}...`)}return n.join(`
|
|
256
|
+
`)}l(Ly,"renderBrowser");function By(s){let e=j(),t=G(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(`
|
|
257
|
+
`).slice(0,10);for(let g of m)i.push(`${o.vertical} ${g}`);f.split(`
|
|
258
|
+
`).length>10&&i.push(`${o.vertical} ${n?a.dim(`... ${f.split(`
|
|
259
|
+
`).length-10} more lines`):"..."}`);let h=`${o.bottomLeft}${o.horizontal.repeat(Math.max(0,r-2))}${o.bottomRight}`;return i.push(n?a.blue(h):h),i.join(`
|
|
260
|
+
`)}l(By,"renderMcp");function Uy(s){let e=j(),t=G(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(`
|
|
261
|
+
`)}l(Uy,"renderWebSearch");function Ru(s,e){let t=j();return` ${G(t).tool} ${s}: ${e.summary}`}l(Ru,"renderGeneric");function Wy(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(Wy,"getToolIcon");function Hy(s,e){switch(s){case"file_edit":return ma(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return ma(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(Hy,"getToolArgsSummary");function ma(s){return process.platform==="win32"?s.replace(/\//g,"\\"):s}l(ma,"displayPath");H();function ir(s,e={}){let t=e.width||process.stdout.columns||80,o=s.split(`
|
|
262
|
+
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(Pu(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 h=u.match(/^####+ (.+)/);if(h){n.push(a.bold.dim(h[1]));continue}if(/^---+$/.test(u.trim())||/^\*\*\*+$/.test(u.trim())){n.push(a.dim("\u2500".repeat(Math.min(40,t-4))));continue}let g=u.match(/^(\s*)([-*+])\s(.+)/);if(g){let v=g[1],_=rr(g[3]);n.push(`${v} \u2022 ${_}`);continue}let y=u.match(/^(\s*)(\d+)\.\s(.+)/);if(y){let v=y[1],_=y[2],S=rr(y[3]);n.push(`${v} ${a.dim(_+".")} ${S}`);continue}let x=u.match(/^>\s?(.*)/);if(x){n.push(a.dim(" \u2502 ")+a.italic(rr(x[1])));continue}if(u.trim()===""){n.push("");continue}n.push(rr(u))}return r&&c.length>0&&n.push(Pu(c,i)),n.join(`
|
|
263
|
+
`)}l(ir,"renderMarkdown");function rr(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(rr,"renderInline");function Pu(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}${Gy(c,e)}`);return[n,...i,r].join(`
|
|
264
|
+
`)}l(Pu,"renderCodeBlock");function Gy(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=qy(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(Gy,"highlightSyntax");function qy(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(qy,"getLanguageKeywords");function Iu(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(Iu,"containsMarkdown");H();Ce();var ar=class{static{l(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=j(),this.icons=G(this.caps),this.data={model:"",mode:"code",branch:"",dirty:!1,sandbox:!1,tokensIn:0,tokensOut:0,cost:0,turn:0,contextPct:0,activity:"",busy:!1,budgetUsd:0,...e}}start(){!this.caps.stdoutTTY||!this.caps.ansi||(this.enabled=!0,process.stdout.write(`
|
|
265
|
+
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=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 g=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${g} `))}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 g=this.icons.branch,y=t.dirty?a.yellow:a.green,x=t.dirty?" \u25CF":"";o.push(y(` ${g} ${t.branch}${x} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let g=Vy(i);r.push(a.dim(` ${g} tokens `))}if(t.cost>0){let g=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,y=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(y(` ${this.icons.cost} ${g} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let g=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,y=6,x=Math.round(t.contextPct/100*y),v=y-x,_=g("\u2588".repeat(x))+a.dim("\u2591".repeat(v));r.push(` ${_} ${g(`${t.contextPct}%`)} `)}if(t.activity){let g=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${g} `))}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"),h=m(" ".repeat(f));return m(c)+h+m(u)}};function Vy(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(Vy,"formatTokensCompact");function Mu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(Mu,"stripAnsi");H();var Ye={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},Jy={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..................."]},zy={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............"]},Ky={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},Yy={large:Jy,medium:zy,mini:Ky},Ou="\u25C1\u2571\u25B7",ju="</>";function Nu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(Nu,"isDarkBackground");function Lu(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=Yy[s],c=o?Ye.navyOnDark:Ye.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Ye.ice):m=>m,p=l((m,h)=>h==="n"?u(m):h==="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,h)=>{let g=i.mask[h],y="",x="",v=g[0]??".";for(let _=0;_<m.length;_++){let S=g[_]??".";S!==v&&(y+=p(x,v),x="",v=S),x+=m[_]}return y+=p(x,v),(f+y).replace(/\s+$/,"")})}l(Lu,"renderLogo");function Bu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(Bu,"pickLogoSize");function ga(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(ga,"visibleWidth");var Xy={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Ro=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={...Xy,...e},this.caps=j(),this.icons=G(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 ar(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),h=Math.floor(m/2),g=` ${this.box.horizontal.repeat(h)}${p}${this.box.horizontal.repeat(m-h)}`;console.log(""),console.log(r?a.dim(g):g),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,t={}){let o=this.caps.ansi,n=o?a.hex(Ye.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.11";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=Lu(d,{color:o,dark:Nu(),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 h=`${this.caps.nerdFont?"\uF120":Ou} MonkeysCode`,g="CLI Agent",y=Math.max(0,f-ga(h)-g.length-2);console.log(` ${n(p.vertical)} ${i(h)}${" ".repeat(y)}${r(g)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let x=`${c}${e?` \xB7 ${e}`:""}`,v=Math.max(0,f-ga(x)-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(` ${ju} 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(Ye.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
266
|
+
`+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(Ye.accent),c=a.green,u=a.dim,d=l((p,f)=>{let m=(p+f).replace(/\x1b\[[0-9;]*m/g,""),h=Math.max(0,r-m.length-4);return` ${i(n.vertical)} ${p}${" ".repeat(h)}${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(fa(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=zs({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(ha(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(Au(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,""),h=Math.max(0,i-m.length);console.log(r.color(` ${o.vertical}`)+` ${f}${" ".repeat(h)}`+r.color(o.vertical)),console.log(r.color(` ${o.vertical}${" ".repeat(i)}${o.vertical}`));let y=e.riskLevel==="dangerous"?" [y] Allow once [n] Deny":" [y] Allow [n] Deny [a] Always [!] YOLO",x=Math.max(0,i-y.length);console.log(r.color(` ${o.vertical}`)+a.dim(` ${y}${" ".repeat(x)}`)+r.color(o.vertical)),console.log(r.color(` ${o.bottomLeft}${o.horizontal.repeat(i)}${o.bottomRight}`))}else{console.log(""),console.log(r.color(` ${r.icon} Permission required: ${e.toolName}`)),console.log(r.color(` ${e.description}`)),console.log(r.color(` Risk: ${r.label}`));let i=JSON.stringify(e.args,null,2).split(`
|
|
267
|
+
`).slice(0,5);for(let c of i)console.log(t?a.dim(` ${c}`):` ${c}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let t=this.caps.ansi;console.log(t?a.dim(` ${e}`):` ${e}`)}printSuccess(e){let t=this.caps.ansi;console.log(t?a.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let t=this.caps.ansi;console.error(t?a.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let t=this.caps.ansi;console.log(t?a.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=zs({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(Ye.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}`,h=Math.max(0,r-m.length-4);console.log(i(` ${n.vertical}`)+` ${c(f)}${p}${" ".repeat(h)}`+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(fa(e,t)),!this.opts.accessible&&this.caps.ansi){let o=zs({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(ha(e,r,n))}printTodoList(e){let t=this.caps.ansi,o=t?a.dim:r=>r,n=t?a.bold:r=>r;console.log(""),console.log(n(" \u{1F4CB} Task Plan:"));for(let r of e){let i=r.status==="done"?"\u2705":r.status==="in_progress"?"\u{1F504}":"\u2B1C",c=r.status==="done"?t?a.green:u=>u:r.status==="in_progress"?t?a.yellow:u=>u:o;console.log(c(` ${i} ${r.content}`))}console.log("")}flushTokenBuffer(){if(!this.tokenBuffer)return;let e=this.tokenBuffer.replace(/<think>[\s\S]*?<\/think>/g,"").trim();this.tokenBuffer="";let t=e.split(`
|
|
268
|
+
`).length;if(this.caps.ansi&&Iu(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=ir(e,{caps:this.caps});if(this.caps.unicode){let n=a.dim(` ${this.box.vertical} `),r=o.split(`
|
|
269
269
|
`).map(i=>n+i).join(`
|
|
270
|
-
`);process.stdout.write(r)}else process.stdout.write(o)}else console.log("");if(this.caps.unicode){let o=a.hex(
|
|
271
|
-
`).filter(t=>t.trim().length>0).slice(-
|
|
272
|
-
`).filter(r=>r.trim().length>0)),n.length>0&&n[n.length-1]===t)return;n.push(t),n.length>
|
|
270
|
+
`);process.stdout.write(r)}else process.stdout.write(o)}else console.log("");if(this.caps.unicode){let o=a.hex(Ye.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=Qy(e.content,d),f=` ${t.bottomLeft}${t.horizontal.repeat(n)}${t.bottomRight}`;console.log(""),console.log(this.caps.ansi?a.cyan(u):u);for(let y of p){let x=y.padEnd(d);console.log(this.caps.ansi?` ${a.cyan(t.vertical)} ${x} ${a.cyan(t.vertical)}`:` ${t.vertical} ${x} ${t.vertical}`)}let m=`${i} `,h=Math.max(0,n-m.length),g=` ${t.bottomLeft}${t.horizontal.repeat(h)}${m}${t.bottomRight}`;console.log(this.caps.ansi?a.cyan(g):g),console.log("")}};function Qy(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(Qy,"wrapText");Ce();ee();Xe();Q();var de=w(require("node:fs"),1),je=w(require("node:path"),1);Z();var k0=20;function Ed(s,e,t,o){if(o.size===0)return;let n=A(),r=je.join(n.data,"checkpoints");de.mkdirSync(r,{recursive:!0});let i={runId:s,prompt:e,workspace:t,timestamp:Date.now(),snapshots:Object.fromEntries(o)},c=je.join(r,`${s}.json`);de.writeFileSync(c,JSON.stringify(i,null,2)),v0(r)}l(Ed,"saveCheckpoint");function Fd(){let s=A(),e=je.join(s.data,"checkpoints");return de.existsSync(e)?de.readdirSync(e).filter(o=>o.endsWith(".json")).sort().reverse().map(o=>{try{return JSON.parse(de.readFileSync(je.join(e,o),"utf8"))}catch{return null}}).filter(Boolean):[]}l(Fd,"listCheckpoints");function Td(s){let e=A(),t=je.join(e.data,"checkpoints",`${s}.json`);if(!de.existsSync(t))throw new Error(`Checkpoint not found: ${s}`);let o=JSON.parse(de.readFileSync(t,"utf8")),n=[];for(let[r,i]of Object.entries(o.snapshots))try{i===null?de.existsSync(r)&&(de.unlinkSync(r),n.push(`deleted ${je.relative(o.workspace,r)}`)):(de.mkdirSync(je.dirname(r),{recursive:!0}),de.writeFileSync(r,i),n.push(`restored ${je.relative(o.workspace,r)}`))}catch(c){n.push(`FAILED ${je.relative(o.workspace,r)}: ${c instanceof Error?c.message:c}`)}return de.unlinkSync(t),n}l(Td,"revertCheckpoint");function v0(s){let e=de.readdirSync(s).filter(t=>t.endsWith(".json")).map(t=>({name:t,mtime:de.statSync(je.join(s,t)).mtime.getTime()})).sort((t,o)=>o.mtime-t.mtime);for(let t of e.slice(k0))try{de.unlinkSync(je.join(s,t.name))}catch{}}l(v0,"pruneCheckpoints");var ge=w(require("node:fs"),1),fo=w(require("node:path"),1),Rd=w(require("node:crypto"),1);Z();var D0="sessions",S0=20,x0=30*24*60*60*1e3,Ht=class{static{l(this,"SessionStore")}sessionsDir;constructor(){let e=A();this.sessionsDir=fo.join(e.data,D0),this.ensureDir()}save(e){this.ensureDir();let t=this.sessionPath(e.id),o=JSON.stringify(e,null,2);ge.writeFileSync(t,o,"utf-8")}create(e,t,o){let n={id:Rd.randomUUID(),workspace:fo.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(!ge.existsSync(t))return null;try{let o=ge.readFileSync(t,"utf-8");return JSON.parse(o)}catch{return null}}loadLatest(e){let t=this.list(),o=e?t.filter(n=>n.workspace===fo.resolve(e)):t;return o.length===0?null:this.load(o[0].id)}list(){this.ensureDir();let e=ge.readdirSync(this.sessionsDir).filter(o=>o.endsWith(".json")).map(o=>fo.join(this.sessionsDir,o)),t=[];for(let o of e)try{let n=ge.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,S0)}delete(e){let t=this.sessionPath(e);return ge.existsSync(t)?(ge.unlinkSync(t),!0):!1}prune(e=x0){this.ensureDir();let t=Date.now(),o=0,n=ge.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).map(i=>fo.join(this.sessionsDir,i));for(let i of n)try{let c=ge.readFileSync(i,"utf-8"),u=JSON.parse(c);t-u.lastActive>e&&(ge.unlinkSync(i),o++)}catch{}let r=ge.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 fo.join(this.sessionsDir,`${t}.json`)}ensureDir(){ge.existsSync(this.sessionsDir)||ge.mkdirSync(this.sessionsDir,{recursive:!0})}};Oa();var lt=w(require("node:fs"),1),_r=w(require("node:path"),1);Z();var za=1e3,_0="history",xr=class{static{l(this,"HistoryManager")}historyFile;constructor(){let e=A();this.historyFile=_r.join(e.data,_0)}load(){try{return lt.existsSync(this.historyFile)?lt.readFileSync(this.historyFile,"utf-8").split(`
|
|
271
|
+
`).filter(t=>t.trim().length>0).slice(-za):[]}catch{return[]}}append(e){let t=e.trim();if(t&&!t.startsWith("/"))try{let o=_r.dirname(this.historyFile);lt.existsSync(o)||lt.mkdirSync(o,{recursive:!0});let n=[];if(lt.existsSync(this.historyFile)&&(n=lt.readFileSync(this.historyFile,"utf-8").split(`
|
|
272
|
+
`).filter(r=>r.trim().length>0)),n.length>0&&n[n.length-1]===t)return;n.push(t),n.length>za&&(n=n.slice(-za)),lt.writeFileSync(this.historyFile,n.join(`
|
|
273
273
|
`)+`
|
|
274
|
-
`,"utf-8")}catch{}}wire(e){let t=this.load(),o=e;o.history&&Array.isArray(o.history)&&(o.history=[...t.reverse(),...o.history],o.history.length>e.historySize&&(o.history=o.history.slice(0,e.historySize))),e.on("line",n=>{this.append(n)})}getPath(){return this.historyFile}};
|
|
275
|
-
`)[0],
|
|
276
|
-
`)[0])}return
|
|
277
|
-
`);for(let o of t)/\bFAIL\b|✕|✗|ERROR|BROKEN/.test(o)&&e.push({suite:"unknown",name:o.trim().substring(0,100),status:"fail"});return
|
|
274
|
+
`,"utf-8")}catch{}}wire(e){let t=this.load(),o=e;o.history&&Array.isArray(o.history)&&(o.history=[...t.reverse(),...o.history],o.history.length>e.historySize&&(o.history=o.history.slice(0,e.historySize))),e.on("line",n=>{this.append(n)})}getPath(){return this.historyFile}};H();var $r=require("node:child_process");Xe();Q();function Ka(s){return $0(s)?R0(s):C0(s)?A0(s):E0(s)?P0(s):F0(s)?I0(s):T0(s)?M0(s):O0(s)}l(Ka,"parseTestOutput");function Ad(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(Ad,"detectVerifyCommand");function $0(s){return/Tests?:\s+\d+ (?:passed|failed)/.test(s)||/PASS|FAIL/.test(s)&&/Test Suites:/.test(s)}l($0,"isJest");function C0(s){return s.includes("vitest")||/✓|×/.test(s)&&/Tests\s+\d+/.test(s)}l(C0,"isVitest");function E0(s){return/={3,}\s*(?:FAILURES|ERRORS|short test summary)/.test(s)||/\d+ passed/.test(s)&&/pytest/.test(s)}l(E0,"isPytest");function F0(s){return/test result:/.test(s)&&/ok|FAILED/.test(s)}l(F0,"isCargoTest");function T0(s){return/^(?:ok|FAIL)\s+\S+/.test(s)||/--- FAIL:/.test(s)}l(T0,"isGoTest");function R0(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],h=r[2],g=/(?:✕|✖|×|✗)\s+(.+?)(?:\s+\((\d+)\s*ms\))?$/gm,y;for(;(y=g.exec(h))!==null;)e.push({suite:m,name:y[1].trim(),status:"fail",file:m,durationMs:y[2]?parseInt(y[2],10):void 0})}let i=/●\s+(.+?)\s*\n\s*\n\s*([\s\S]*?)(?=\n\s*●|\n\s*Test Suites:)/g;for(;(r=i.exec(s))!==null;){let m=r[1].trim(),h=r[2].trim().split(`
|
|
275
|
+
`)[0],g=e.find(y=>m.includes(y.name));g&&(g.error=h)}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 us("jest",e,{total:f,passed:p,failed:u,skipped:d})}l(R0,"parseJest");function A0(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 us("vitest",e)}l(A0,"parseVitest");function P0(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 us("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(P0,"parsePytest");function I0(s){let e=[],t=/^test\s+(\S+)\s+\.\.\.\s+(ok|FAILED|ignored)/gm,o;for(;(o=t.exec(s))!==null;){let i=o[1].split("::");e.push({suite:i.slice(0,-1).join("::")||"default",name:i[i.length-1],status:o[2]==="ok"?"pass":o[2]==="ignored"?"skip":"fail"})}let n=/---- (\S+) stdout ----\n([\s\S]*?)(?=\n---- |\nfailures:)/g;for(;(o=n.exec(s))!==null;){let r=o[1],i=e.find(c=>`${c.suite}::${c.name}`===r||c.name===r);i&&(i.error=o[2].trim().split(`
|
|
276
|
+
`)[0])}return us("cargo",e)}l(I0,"parseCargoTest");function M0(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 us("go",e)}l(M0,"parseGoTest");function O0(s){let e=[],t=s.split(`
|
|
277
|
+
`);for(let o of t)/\bFAIL\b|✕|✗|ERROR|BROKEN/.test(o)&&e.push({suite:"unknown",name:o.trim().substring(0,100),status:"fail"});return us("unknown",e)}l(O0,"parseGeneric");function us(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(us,"buildSummary");var Pd=10,Id=1800,Md=5,Cr=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||Pd,status:"planning",subtasks:[],elapsed:0,totalTokens:0,totalCost:0}}async run(){this.startTime=Date.now();let e=this.opts.maxIterations||Pd,t=(this.opts.timeoutSeconds||Id)*1e3,o=this.opts.maxCostUsd||Md,n=Y();if(this.printGoalHeader(),!this.opts.verifyCommand){let r=Ad(this.opts.workspace);r&&(this.opts.verifyCommand=r,console.log(a.dim(` Auto-detected verify command: ${r}`)))}for(let r=1;r<=e;r++){if(this.cancelled){this.progress.status="cancelled",this.printGoalStatus("cancelled");break}let i=Date.now()-this.startTime;if(i>t){this.progress.status="limit_reached",this.printGoalStatus("timeout");break}if(this.progress.totalCost>o){this.progress.status="limit_reached",this.printGoalStatus("cost_limit");break}this.progress.iteration=r,this.progress.elapsed=i;let c=this.buildIterationPrompt(r,e);this.progress.status="executing",this.printIterationHeader(r,e);let u=new xe({platformUrl:n.platformUrl,token:this.opts.token,model:this.opts.model,workspace:this.opts.workspace,mode:"auto",maxTurns:20,sandboxed:!1,webEnabled:n.webEnabled,effort:"reasoning",userId:this.opts.userId,orgId:this.opts.orgId}),d="";u.on("event",f=>{switch(f.type){case"streaming_chunk":d+=f.content,process.stdout.write(f.content);break;case"streaming_end":console.log("");break;case"tool_call_start":this.renderer.printToolCallStart(f.name,f.args);break;case"tool_call_result":this.renderer.printToolCallResult(f.name,f.result);break;case"run_complete":this.progress.totalTokens+=f.summary.tokensIn+f.summary.tokensOut,this.progress.totalCost+=f.summary.costUsd;break}});try{await u.run(c)}catch(f){this.renderer.printError(`Iteration ${r} error: ${f instanceof Error?f.message:f}`)}if(this.evaluateGoalCompletion(d)){this.progress.status="completed",this.printGoalStatus("completed");break}this.lastTestSummary&&this.lastTestSummary.failed>this.prevFailCount&&(console.log(a.yellow(` \u26A0\uFE0F Failures increased (${this.prevFailCount} \u2192 ${this.lastTestSummary.failed}). Rolling back...`)),this.rollbackCheckpoint()),this.prevFailCount=this.lastTestSummary?.failed??1/0,this.saveCheckpoint(),r===e&&(this.progress.status="limit_reached",this.printGoalStatus("max_iterations"))}return this.progress.elapsed=Date.now()-this.startTime,this.progress}cancel(){this.cancelled=!0}getProgress(){return this.progress.elapsed=Date.now()-this.startTime,{...this.progress}}buildIterationPrompt(e,t){if(e===1)return[`AUTONOMOUS GOAL MODE \u2014 Iteration ${e}/${t}`,"",`Goal: ${this.opts.goal}`,"","You are running in autonomous goal mode. Your job:","1. Plan: Break the goal into concrete sub-tasks","2. Execute: Implement the changes needed","3. Verify: Run tests, lint, or type-check to confirm the goal is met",this.opts.verifyCommand?`4. After you finish, I will automatically run: \`${this.opts.verifyCommand}\`. If it fails, you will get another iteration to fix the issues.`:'4. Report: End your response with "GOAL_STATUS: COMPLETE" if done, or "GOAL_STATUS: IN_PROGRESS" if more work is needed',"","Work autonomously \u2014 do not ask for user input. Make decisions yourself.","If you encounter errors, fix them and continue."].join(`
|
|
278
278
|
`);let o=[`AUTONOMOUS GOAL MODE \u2014 Iteration ${e}/${t}`,"",`Goal: ${this.opts.goal}`,"",`This is iteration ${e}. Previous iterations did not fully complete the goal.`,"Review the current state of the workspace and continue working toward the goal."];if(this.lastTestSummary&&this.lastTestSummary.failingTests.length>0){o.push(""),o.push("The following tests are still failing \u2014 focus on these:");for(let n of this.lastTestSummary.failingTests.slice(0,10)){let r=n.file?` (${n.file}${n.line?`:${n.line}`:""})`:"";o.push(` \u2717 ${n.suite}::${n.name}${r}${n.error?` \u2014 ${n.error.substring(0,80)}`:""}`)}o.push(""),o.push("Fix ONLY these specific failures. Do not refactor unrelated code.")}return o.push(""),o.push('End your response with "GOAL_STATUS: COMPLETE" if the goal is fully met,'),o.push('or "GOAL_STATUS: IN_PROGRESS" if more work is needed.'),o.join(`
|
|
279
279
|
`)}evaluateGoalCompletion(e){return this.opts.verifyCommand?this.runVerifyCommand():!!(e.includes("GOAL_STATUS: COMPLETE")||e.includes("GOAL_STATUS: DONE")||e.includes("All tests pass")&&e.includes("GOAL_STATUS"))}runVerifyCommand(){let e=this.opts.verifyCommand;console.log(a.dim(`
|
|
280
|
-
\u{1F50D} Running verification: ${e}`));try{let o=(0
|
|
280
|
+
\u{1F50D} Running verification: ${e}`));try{let o=(0,$r.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=Ka(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(`
|
|
281
281
|
`).slice(-3).join(`
|
|
282
282
|
`)}`)),!0}catch(t){let o=t.stderr?.toString().slice(-500)||"",n=t.stdout?.toString().slice(-500)||"",r=n+`
|
|
283
|
-
`+o;if(this.lastTestSummary=
|
|
283
|
+
`+o;if(this.lastTestSummary=Ka(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(`
|
|
284
284
|
`).slice(-3).join(`
|
|
285
285
|
`)}`)):n.trim()&&console.log(a.dim(` ${n.trim().split(`
|
|
286
286
|
`).slice(-3).join(`
|
|
287
|
-
`)}`));return!1}}saveCheckpoint(){try{(0
|
|
287
|
+
`)}`));return!1}}saveCheckpoint(){try{(0,$r.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,$r.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||Id)/60}min \xB7 Max cost: $${(this.opts.maxCostUsd||Md).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("")}};H();var Od=w(require("node:crypto"),1);Xe();Q();var Er=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=Od.randomUUID().slice(0,8),o=Y(),n={id:t,description:e,status:"running",startTime:Date.now(),tokensUsed:0};this.subtasks.set(t,n),this.renderer.printSuccess(`Subtask ${a.bold(t)} spawned: "${e}"`),console.log(a.dim(` Track: /subtask status \xB7 Cancel: /subtask cancel ${t}`));let r=new xe({platformUrl:o.platformUrl,token:this.opts.token,model:this.opts.model,workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:o.webEnabled,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.loops.set(t,r);let i="";return r.on("event",c=>{switch(c.type){case"streaming_chunk":i+=c.content;break;case"run_complete":n.tokensUsed+=c.summary.tokensIn+c.summary.tokensOut;break}}),this.executeSubtask(t,r,e,n,i).catch(()=>{}),t}cancel(e){let t=this.subtasks.get(e),o=this.loops.get(e);return!t||t.status!=="running"?(this.renderer.printError(`Subtask ${e} not found or not running.`),!1):(o&&o.cancel(),t.status="cancelled",t.endTime=Date.now(),this.loops.delete(e),this.renderer.printSuccess(`Subtask ${e} cancelled.`),!0)}getStatus(){return[...this.subtasks.values()].sort((e,t)=>t.startTime-e.startTime)}printStatus(){let e=this.getStatus();if(e.length===0){console.log(a.dim(" No subtasks."));return}console.log(""),console.log(a.bold(" Subtasks:")),console.log(` ${"\u2500".repeat(70)}`);for(let t of e){let o=((t.endTime||Date.now())-t.startTime)/1e3,n={running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u23F9"}[t.status],r={running:a.cyan,completed:a.green,failed:a.red,cancelled:a.yellow}[t.status];if(console.log(` ${n} ${a.bold(t.id)} ${r(t.status.padEnd(10))} ${t.description.substring(0,40).padEnd(42)} ${a.dim(`${o.toFixed(0)}s ${t.tokensUsed.toLocaleString()} tok`)}`),t.status==="completed"&&t.result){let i=t.result.split(`
|
|
288
288
|
`)[0].substring(0,70);console.log(a.dim(` \u2514\u2500 ${i}`))}t.status==="failed"&&t.error&&console.log(a.red(` \u2514\u2500 ${t.error.substring(0,70)}`))}console.log(` ${"\u2500".repeat(70)}`),console.log("")}async executeSubtask(e,t,o,n,r){try{let i=["You are running as an isolated subtask. Your task:","",`${o}`,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished."].join(`
|
|
289
289
|
`);await t.run(i),n.status="completed",n.endTime=Date.now(),n.result=r;let c=((n.endTime-n.startTime)/1e3).toFixed(0);if(console.log(""),console.log(a.green(` \u2705 Subtask ${a.bold(e)} completed (${c}s, ${n.tokensUsed.toLocaleString()} tokens)`)),console.log(a.dim(` "${o}"`)),r.trim()){let u=r.trim().split(`
|
|
290
290
|
`).slice(0,3).join(`
|
|
291
|
-
`);console.log(a.dim(` ${u}`))}console.log("")}catch(i){n.status="failed",n.endTime=Date.now(),n.error=i instanceof Error?i.message:String(i),console.log(""),console.log(a.red(` \u274C Subtask ${a.bold(e)} failed: ${n.error}`)),console.log("")}finally{this.loops.delete(e)}}};var
|
|
291
|
+
`);console.log(a.dim(` ${u}`))}console.log("")}catch(i){n.status="failed",n.endTime=Date.now(),n.error=i instanceof Error?i.message:String(i),console.log(""),console.log(a.red(` \u274C Subtask ${a.bold(e)} failed: ${n.error}`)),console.log("")}finally{this.loops.delete(e)}}};var Xa=w(require("node:path"),1),nn=require("node:child_process"),Nd=require("node:events");Xe();var Fr=require("node:child_process"),Pe=w(require("node:fs"),1),Oo=w(require("node:path"),1);var Tr=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=Oo.join(this.workspace,".git","mc-merge-tmp");Pe.mkdirSync(c,{recursive:!0});let u=Oo.join(c,"base"),d=Oo.join(c,"ours"),p=Oo.join(c,"theirs");Pe.writeFileSync(u,n),Pe.writeFileSync(d,r),Pe.writeFileSync(p,i);try{(0,Fr.execSync)(`git merge-file ${d} ${u} ${p}`,{cwd:this.workspace,stdio:"pipe"});let f=Pe.readFileSync(d,"utf8");return this.cleanup(c),{file:e,success:!0,hadConflicts:!1,mergedContent:f,conflictMarkers:[]}}catch{let f=Pe.readFileSync(d,"utf8"),m=this.parseConflictMarkers(f,t[1]);if(this.cleanup(c),m.length>0){let h=this.autoResolveMarkers(f);return{file:e,success:h.resolved,hadConflicts:!0,mergedContent:h.content,conflictMarkers:h.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=Oo.join(this.workspace,e);Pe.writeFileSync(r,o.mergedContent),o=await this.resolve(e,["HEAD",t[n]])}return o}noConflict(e){let t=Oo.join(this.workspace,e);return{file:e,success:!0,hadConflicts:!1,mergedContent:Pe.existsSync(t)?Pe.readFileSync(t,"utf8"):"",conflictMarkers:[]}}getBaseBranch(){try{return(0,Fr.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:this.workspace,encoding:"utf8"}).trim()}catch{return"HEAD"}}getFileAtBranch(e,t){try{return(0,Fr.execSync)(`git show ${t}:${e}`,{cwd:this.workspace,encoding:"utf8"})}catch{return""}}parseConflictMarkers(e,t){let o=[],n=e.split(`
|
|
292
292
|
`),r=0;for(;r<n.length;){if(n[r].startsWith("<<<<<<<")){let i=r+1,c="",u="",d=!1;for(r++;r<n.length&&!n[r].startsWith(">>>>>>>");)n[r].startsWith("=======")?d=!0:d?u+=n[r]+`
|
|
293
293
|
`:c+=n[r]+`
|
|
294
294
|
`,r++;o.push({startLine:i,endLine:r+1,ours:c.trimEnd(),theirs:u.trimEnd(),branchName:t})}r++}return o}async autoResolveMarkers(e){let t=e.split(`
|
|
@@ -296,84 +296,84 @@ ${e}`,"wrappedToString"),kh=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
296
296
|
`:c+=t[n]+`
|
|
297
297
|
`,n++;if(n++,c.trim()===u.trim())o.push(c.trimEnd());else if(c.trim()==="")o.push(u.trimEnd());else if(u.trim()==="")o.push(c.trimEnd());else{let p=`__CONFLICT_${i.length}__`;i.push({ours:c.trimEnd(),theirs:u.trimEnd(),index:i.length}),o.push(p),r=!1}}else o.push(t[n]),n++;if(i.length>0){let c=o.join(`
|
|
298
298
|
`);for(let d of i){let p=await this.llmMerge(d.ours,d.theirs);p?c=c.replace(`__CONFLICT_${d.index}__`,p):c=c.replace(`__CONFLICT_${d.index}__`,d.ours)}let u=/__CONFLICT_\d+__/.test(c);return{content:c,resolved:!u}}return{content:o.join(`
|
|
299
|
-
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(
|
|
300
|
-
`);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{Pe.rmSync(e,{recursive:!0,force:!0})}catch{}}};Q();var
|
|
299
|
+
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(Xe(),rs)),{loadSettings:n}=await Promise.resolve().then(()=>(Q(),we)),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),he)),i=n(),c=await r()||process.env.MC_API_KEY||"";if(!c)return null;let u=new o({platformUrl:i.platformUrl,token:c,model:i.defaultModel||"capuchin-reason",workspace:this.workspace,mode:"auto",maxTurns:1,sandboxed:!0,webEnabled:!1,effort:"fast"}),d="";u.on("event",m=>{m.type==="streaming_chunk"&&(d+=m.content)});let p=["You are merging two versions of a code section that were edited by different agents.","Combine both changes intelligently, preserving the intent of each.","Return ONLY the merged code. No explanations, no markdown fences.","","=== Version A (ours) ===",e,"","=== Version B (theirs) ===",t,"","=== Merged result ==="].join(`
|
|
300
|
+
`);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{Pe.rmSync(e,{recursive:!0,force:!0})}catch{}}};Q();var jd=require("node:events"),Ya=w(require("node:crypto"),1);var Rr=class extends jd.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:Ya.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.${Ya.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 Ar=class extends Nd.EventEmitter{static{l(this,"AgentOrchestrator")}opts;resolver;activeLoops=new Map;broker;constructor(e){super(),this.opts={maxConcurrency:5,timeoutMs:6e5,...e},this.resolver=new Tr(e.workspace),this.broker=new Rr,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+=`
|
|
301
301
|
|
|
302
302
|
`+r.inputTransform(o):o&&(i+=`
|
|
303
303
|
|
|
304
304
|
--- Previous stage output ---
|
|
305
|
-
${o}`);let c={id:r.id,prompt:i,workspace:this.opts.workspace,parentId:"pipeline",dependencies:[],status:"pending",model:r.model,maxCostUsd:r.maxCostUsd},u=await this.runInline(c);if(t.push({...u,stageId:r.id}),o=u.output,u.status==="failed")break}return{stages:t,finalOutput:o,totalTokens:t.reduce((r,i)=>r+i.tokensUsed,0),totalCost:t.reduce((r,i)=>r+i.costUsd,0),totalDurationMs:Date.now()-n}}cancelAll(){for(let[e,t]of this.activeLoops)t.cancel(),this.activeLoops.delete(e)}async runIsolated(e){let t=`mc-agent-${e.id}-${Date.now()}`,o=
|
|
306
|
-
`);return await p.run(
|
|
307
|
-
`)}l(
|
|
308
|
-
`),!0):!1}l(
|
|
309
|
-
`)[0]}catch{return null}}l(
|
|
310
|
-
`)}}},
|
|
305
|
+
${o}`);let c={id:r.id,prompt:i,workspace:this.opts.workspace,parentId:"pipeline",dependencies:[],status:"pending",model:r.model,maxCostUsd:r.maxCostUsd},u=await this.runInline(c);if(t.push({...u,stageId:r.id}),o=u.output,u.status==="failed")break}return{stages:t,finalOutput:o,totalTokens:t.reduce((r,i)=>r+i.tokensUsed,0),totalCost:t.reduce((r,i)=>r+i.costUsd,0),totalDurationMs:Date.now()-n}}cancelAll(){for(let[e,t]of this.activeLoops)t.cancel(),this.activeLoops.delete(e)}async runIsolated(e){let t=`mc-agent-${e.id}-${Date.now()}`,o=Xa.join(this.opts.workspace,"..",`.mc-worktree-${e.id}`);try{return(0,nn.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=Y(),r=Date.now(),i="",c=0,u=0,d=[],p=new xe({platformUrl:n.platformUrl,token:this.opts.token,model:e.model||this.opts.model,workspace:t,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeLoops.set(e.id,p);let f=e.timeoutMs||this.opts.timeoutMs||6e5,m=setTimeout(()=>p.cancel(),f);p.on("event",h=>{switch(h.type){case"streaming_chunk":i+=h.content;break;case"tool_call_start":if(["write_file","edit_file","create_file","replace_file_content"].includes(h.name)){let g=h.args.path||h.args.file_path||h.args.target_file;g&&d.push(g)}this.broker.publish(`agent.${e.id}`,{from:e.id,type:"tool_call",data:{tool:h.name}});break;case"run_complete":c+=h.summary.tokensIn+h.summary.tokensOut,u+=h.summary.costUsd||0,this.broker.publish("orchestrator",{from:e.id,type:"complete",data:{tokensUsed:c,costUsd:u,filesChanged:[...new Set(d)]}});break}});try{let h=["You are running as a parallel subagent in an orchestrated multi-agent workflow.","","Your specific task:",e.prompt,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished concisely."].join(`
|
|
306
|
+
`);return await p.run(h),{taskId:e.id,status:"complete",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,worktreeBranch:o}}catch(h){return{taskId:e.id,status:"failed",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,error:h instanceof Error?h.message:String(h),worktreeBranch:o}}finally{clearTimeout(m),this.activeLoops.delete(e.id)}}async cherryPickFile(e,t){try{(0,nn.execSync)(`git checkout ${t} -- ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}cleanupWorktree(e){try{let t=Xa.join(this.opts.workspace,"..",`.mc-worktree-${e.replace(/^mc-agent-/,"")}`);(0,nn.execSync)(`git worktree remove --force ${t}`,{cwd:this.opts.workspace,stdio:"pipe"}),(0,nn.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 om=w(require("node:fs"),1),zr=require("node:child_process");H();Z();Ce();var Kp=require("node:child_process"),wo=w(require("node:fs"),1),Jr=w(require("node:path"),1),Yp=require("node:events");mn();Z();var lb=1;function Hp(s,e={}){return{jsonrpc:"2.0",id:lb++,method:s,params:e}}l(Hp,"createRequest");function Gp(s){return JSON.stringify(s)}l(Gp,"serialize");function qp(s){try{let e=JSON.parse(s);return e.kind||e.id!==void 0||e.method?e:null}catch{return null}}l(qp,"parseMessage");function Vp(s){return typeof s=="object"&&s!==null&&"kind"in s}l(Vp,"isDaemonEvent");function Jp(s){return typeof s=="object"&&s!==null&&"id"in s&&"jsonrpc"in s}l(Jp,"isRpcResponse");var yo=class extends Yp.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=A(),this.opts={daemonBinary:e.daemonBinary??process.env.MONKEYSCODE_DAEMON??this.platform.daemonBinary,port:e.port??9120,startTimeout:e.startTimeout??15e3,rpcTimeout:e.rpcTimeout??6e4,maxReconnectAttempts:e.maxReconnectAttempts??3,autoSpawn:e.autoSpawn??!0}}get connected(){return this._connected}async connect(){let e=await this.findRunningDaemon();if(e){await this.connectWebSocket(e);return}if(!this.opts.autoSpawn)throw new Error("Daemon is not running and auto-spawn is disabled. Start the daemon manually or use --auto-spawn.");let t=await this.spawnDaemon();await this.connectWebSocket(t)}async call(e,t={}){if(!this.ws||!this._connected)throw new Error("Not connected to daemon");let o=Hp(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(Gp(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(!wo.existsSync(this.paths.pidFile))return null;let e=wo.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 wo.unlinkSync(this.paths.pidFile),null}}catch{return null}}async spawnDaemon(){nr(Jr.dirname(this.paths.pidFile)),nr(this.paths.logs);let e=Jr.join(this.paths.logs,`daemon-${Date.now()}.log`),t=wo.createWriteStream(e,{flags:"a"}),o=this.opts.port;return this.daemonProcess=(0,Kp.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 zp(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 dt(`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 dt(`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=qp(e);if(t){if(Jp(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(Vp(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 zp(t);try{await this.connectWebSocket(e)}catch{}}};function zp(s){return new Promise(e=>setTimeout(e,s))}l(zp,"sleep");ee();Ma();var Ge=w(require("node:fs"),1),pt=w(require("node:path"),1);Z();function fn(s){let e=A(),t=pt.join(s,".monkeyscode","mcp.json"),o=pt.join(e.config,"mcp.json"),n=Xp(o),r=Xp(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(fn,"loadMcpConfig");function Xp(s){if(!Ge.existsSync(s))return[];try{let e=Ge.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:ub(n),autoStart:n.autoStart??!0}))}catch{return[]}}l(Xp,"loadConfigFile");function ub(s){return s.transport?s.transport:s.url?"sse":"stdio"}l(ub,"detectTransport");function kc(s,e,t,o){let n=pt.join(s,".monkeyscode","mcp.json"),r=em(n);r.servers[e]={command:t,args:o};let i=pt.dirname(n);Ge.mkdirSync(i,{recursive:!0}),Ge.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
307
|
+
`)}l(kc,"addMcpServer");function Qp(s,e){let t=pt.join(s,".monkeyscode","mcp.json"),o=em(t);return o.servers[e]?(delete o.servers[e],Ge.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
308
|
+
`),!0):!1}l(Qp,"removeMcpServer");function Zp(s){let e=A();return[{path:pt.join(s,".monkeyscode","mcp.json"),source:"project",exists:Ge.existsSync(pt.join(s,".monkeyscode","mcp.json"))},{path:pt.join(e.config,"mcp.json"),source:"global",exists:Ge.existsSync(pt.join(e.config,"mcp.json"))}]}l(Zp,"getMcpConfigPaths");function em(s){if(!Ge.existsSync(s))return{servers:{}};try{return JSON.parse(Ge.readFileSync(s,"utf-8"))}catch{return{servers:{}}}}l(em,"loadConfigFileRaw");gr();async function hn(s={}){let e=j(),t=G(e),o=e.ansi,n=$e(),r=A();console.log(""),console.log(o?a.bold(" \u{1FA7A} MonkeysCode Doctor"):" MonkeysCode Doctor"),console.log(o?a.dim(` Platform: ${n.os} (${n.arch}) \xB7 Shell: ${n.shell}`):` Platform: ${n.os} (${n.arch}) \xB7 Shell: ${n.shell}`),console.log("");let i=[],c=process.version,u=parseInt(c.slice(1).split(".")[0],10);i.push(u>=20?{name:"Node.js",status:"ok",message:`${c}`}:{name:"Node.js",status:"error",message:`${c} (requires >= 20)`,fix:"Install Node.js 20+ from https://nodejs.org"});let d=tm(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 C=new yo({autoSpawn:!1,startTimeout:3e3});await C.connect(),C.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(Ea()?{name:"Authentication",status:"ok",message:"Logged in"}:{name:"Authentication",status:"warn",message:"Not logged in",fix:"Run: mc auth login"});let p=tm("git");i.push(p?{name:"Git",status:"ok",message:db("git --version")||"found"}:{name:"Git",status:"error",message:"Not found",fix:"Install git: https://git-scm.com"});let m=await new cs(hr(".")).checkAllProviders(),h=m.filter(C=>C.available);if(h.length>0)i.push({name:"Sandbox",status:"ok",message:`Available: ${h.map(C=>C.name).join(", ")}`});else{let C=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:C})}for(let C of m)C.available||i.push({name:` \u2514 ${C.name}`,status:"warn",message:C.reason||"Not available"});let g=process.cwd(),y=fn(g);y.length>0?i.push({name:"MCP servers",status:"ok",message:`${y.length} configured: ${y.map(C=>C.name).join(", ")}`}):i.push({name:"MCP servers",status:"ok",message:"None configured (optional)"});let x=Io(g);x.length>0?i.push({name:"Hooks",status:"ok",message:`${x.length} active: ${x.map(C=>C.event).join(", ")}`}):i.push({name:"Hooks",status:"ok",message:"None configured (optional)"});let v=om.existsSync(r.config);i.push(v?{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 _=j();i.push({name:"Terminal",status:"ok",message:[_.trueColor?"24-bit color":_.color256?"256 color":_.color16?"16 color":"no color",_.unicode?"Unicode":"ASCII",_.interactive?"interactive":"non-interactive",`${_.columns}x${_.rows}`].join(" \xB7 ")});for(let C of i){let J=C.status==="ok"?t.success:C.status==="warn"?t.warning:t.error,O=C.status==="ok"?o?a.green:ce=>ce:C.status==="warn"?o?a.yellow:ce=>ce:o?a.red:ce=>ce;console.log(` ${J} ${O(`${C.name}`)}: ${C.message}`),C.fix&&console.log(o?a.dim(` Fix: ${C.fix}`):` Fix: ${C.fix}`)}console.log("");let S=i.filter(C=>C.status==="error").length,k=i.filter(C=>C.status==="warn").length;if(S>0?console.log(o?a.red(` ${S} error(s), ${k} warning(s)`):` ${S} error(s), ${k} warning(s)`):k>0?console.log(o?a.yellow(` All good! ${k} warning(s)`):` All good! ${k} warning(s)`):console.log(o?a.green(" \u2728 Everything looks great!"):" Everything looks great!"),console.log(""),s.fix){let C=i.filter(J=>J.status!=="ok"&&J.fix);if(C.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 C){console.log(` \u2192 ${J.name}: ${J.fix}`);try{(0,zr.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(hn,"doctorCommand");function tm(s){try{return(0,zr.execSync)(`which ${s} 2>/dev/null || where ${s} 2>nul`,{stdio:"pipe"}),!0}catch{return!1}}l(tm,"checkBinary");function db(s){try{return(0,zr.execSync)(s,{stdio:"pipe"}).toString().trim().split(`
|
|
309
|
+
`)[0]}catch{return null}}l(db,"getVersion");Sr();wr();var vc=w(require("node:fs"),1),Dc=require("node:child_process");function zt(s){return s.replace(/\\/g,"/")}l(zt,"normalizePath");var bs=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:zt(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}},Sc=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:zt(o.path)}))};return JSON.stringify(t)}formatEvent(e){return JSON.stringify({type:e.type,timestamp:e.timestamp,...e.data})}},xc=class{static{l(this,"DiffFormatter")}workspace;constructor(e){this.workspace=e}formatResult(e){try{let t=(0,Dc.execSync)("git diff",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760});return t.trim()?t:(0,Dc.execSync)("git diff --cached",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760})||"# No changes detected"}catch{return e.filesChanged.map(t=>`# ${t.action}: ${zt(t.path)} (+${t.linesAdded} -${t.linesRemoved})`).join(`
|
|
310
|
+
`)}}},Kr=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(`| \`${zt(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(`\`\`\`
|
|
311
311
|
${e.error}
|
|
312
312
|
\`\`\``),t.push("")),t.join(`
|
|
313
|
-
`)}},
|
|
313
|
+
`)}},_c=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=>zt(i.path)).join(",")}`,`cost=${e.cost.toFixed(4)}`,`tokens=${e.tokens.total}`,`duration=${e.duration}`,`model=${e.model}`,`session-id=${e.sessionId}`];try{vc.appendFileSync(o,r.join(`
|
|
314
314
|
`)+`
|
|
315
|
-
`)}catch{}}t.push(`::set-output name=success::${e.success}`),t.push(`::set-output name=status::${e.status}`),t.push(`::set-output name=summary::${e.summary}`),t.push(`::set-output name=files-changed::${e.filesChanged.map(r=>
|
|
315
|
+
`)}catch{}}t.push(`::set-output name=success::${e.success}`),t.push(`::set-output name=status::${e.status}`),t.push(`::set-output name=summary::${e.summary}`),t.push(`::set-output name=files-changed::${e.filesChanged.map(r=>zt(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 Kr().formatResult(e);try{vc.appendFileSync(n,r+`
|
|
316
316
|
`)}catch{}}return!e.success&&e.error&&t.push(`::error::${e.error}`),t.join(`
|
|
317
|
-
`)}}
|
|
318
|
-
`)}},
|
|
319
|
-
${a.hex("#6B8DD6")(
|
|
320
|
-
${
|
|
321
|
-
`).length;process.stdout.write(`\x1B[${
|
|
322
|
-
\u{1F914} ${
|
|
323
|
-
`);
|
|
317
|
+
`)}},$c=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=>zt(o.path)).join(",")}`),t.push(`##vso[task.setvariable variable=agentTokens]${e.tokens.total}`),t.push(`##vso[task.setvariable variable=agentDuration]${e.duration}`),e.success?t.push(`##vso[task.complete result=Succeeded;]${e.summary}`):t.push(`##vso[task.complete result=Failed;]${e.error||e.summary}`),t.push(`##vso[task.uploadsummary]MonkeysCode: ${e.summary}`),t.join(`
|
|
318
|
+
`)}},ks=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:zt(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:zt(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 sm(s,e={}){switch(s){case"json":return new bs;case"jsonl":return new Sc;case"diff":return new xc(e.workspace||".");case"markdown":return new Kr;case"github":return new _c;case"azure":return new $c;case"sarif":return new ks(e.findings,e.workspace);case"text":case"stream":default:return new bs}}l(sm,"createFormatter");function nm(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(nm,"createEmptyResult");function Rm(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(Rm,"mapMode");async function Am(s){let e=j(),t=s.prompt;!t&&!e.interactive&&(t=await Tb());let o=await Fe();if(o||(console.error(a.red(" Error: Not authenticated. Run `mc auth login` first.")),process.exit(1)),s.model==="auto"){let r=Y();s.model=r.defaultModel}let n=fe();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(hm(),fm));await r({jobId:s.resume,workspace:s.workspace}),await Fm(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Uc(),bm));await r(s.prompt,s.workspace,s.model)}else s.headless?await Eb(t,s,o,n):s.background?await Fb(t,s):await Fm(t,s,o,n)}l(Am,"runCommand");async function Fm(s,e,t,o){let n=j(),r=Y(),i=new Ro({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new Mo(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new Ht,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,h=new Set,g=0,y=0,x=0,v=0,_=null,S=!1;if(e.continueSession){let I=u.loadLatest(e.workspace);if(I){d=I,v=I.turnCount;for(let L of I.stats.filesChanged)m.add(L);i.printSuccess(`Resumed session ${I.id.substring(0,8)} (${I.turnCount} turns, ${I.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 I=a.dim,L=a.green,T=a.yellow,M=a.hex("#6B8DD6"),E=a.bold(e.model),b=I(e.mode);console.log(` ${M("Model:")} ${E} ${I("\xB7")} ${b} mode`);let D=(()=>{try{return(0,et.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),$=(()=>{try{return(0,et.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),F=D?` ${I("\xB7")} ${I("branch:")} ${D}${$?T(" \u25CF"):L(" \u2713")}`:"";console.log(` ${M("Path:")} ${I(e.workspace)}${F}`);let R=e.sandbox?L("\u{1F512} on"):T("off"),q=e.permissionMode!=="default"?` ${I("\xB7")} ${I("perm:")} ${e.permissionMode}`:"",P=e.autoApprove?` ${I("\xB7")} ${T("auto-approve")}`:e.approveForMe?` ${I("\xB7")} ${L("smart-approve")}`:"";console.log(` ${M("Sandbox:")} ${R}${q}${P}`);let st=c.getHooks(),_e=st.length>0?`${st.length} hooks`:I("none"),nt=0;try{let{listAllSkills:Re}=await Promise.resolve().then(()=>(kr(),Ha));nt=Re(e.workspace).length}catch{}let Os=nt>0?`${nt} skills`:I("none");console.log(` ${M("Plugins:")} ${_e} ${I("\xB7")} ${Os}`);let js=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${M("Engine:")} ${I(js)}`)}console.log("");let k=i.getStatusBar({model:e.model,mode:e.mode,branch:(()=>{try{return(0,et.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),dirty:(()=>{try{return(0,et.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});k.start(),console.log(a.dim(" Type a prompt to start. /help for commands, /exit to quit, Ctrl+C to cancel."));let C="0.1.11";(async()=>{try{let I=await fetch("https://registry.npmjs.org/monkeyscode-cli/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!I.ok)return;let T=(await I.json()).version;if(!T)return;let M=C.split(".").map(Number),E=T.split(".").map(Number),b=!1;for(let D=0;D<3;D++){if((E[D]||0)>(M[D]||0)){b=!0;break}if((E[D]||0)<(M[D]||0))break}b&&(console.log(""),console.log(a.hex(Ye.accent)(` \u2B06 Update available: ${a.dim(`v${C}`)} \u2192 ${a.bold(`v${T}`)}`)),console.log(a.dim(` Run ${a.bold("npm i -g monkeyscode-cli")} to update.`)))}catch{}})(),await c.fire("SessionStart",{workspace:e.workspace,data:{model:e.model,mode:e.mode}});let J=["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"],O=Tm.createInterface({input:process.stdin,output:process.stdout,terminal:!0,prompt:(()=>{let I=G(n);return n.ansi?`
|
|
319
|
+
${a.hex("#6B8DD6")(I.prompt)} `:`
|
|
320
|
+
${I.prompt} `})(),historySize:200,completer:l(I=>{if(I.startsWith("/")){let L=I.slice(1).toLowerCase(),T=J.filter(M=>M.startsWith(L)).map(M=>`/${M}`);return[T.length?T:J.map(M=>`/${M}`),I]}if(I.startsWith("/context ")){let L=I.slice(9);try{let T=K.dirname(K.resolve(e.workspace,L)),M=K.basename(L);return[N.readdirSync(T).filter(D=>D.startsWith(M)).map(D=>`/context ${L.replace(M,"")}${D}`),I]}catch{return[[],I]}}return[[],I]},"completer")});new xr().wire(O);let ne=null,De=null,Zo=!1,wt=null,no=new Er({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),ro=null;try{let{MessageBroker:I}=await Promise.resolve().then(()=>(vn(),Zr));t&&r.platformUrl&&(ro=new I(r.platformUrl,t,p))}catch{}let Is=l(async()=>{if(ro)try{let I=await ro.pollMessages();if(I&&I.length>0)for(let L of I)i.renderMessageCard({from:L.from||L.senderId||"unknown",content:L.content||L.message||"",timestamp:L.timestamp?new Date(L.timestamp):new Date})}catch{}},"pollAndRenderMessages"),Pt=l(async I=>{d||(d=u.create(e.workspace,e.model,e.mode)),u.addMessage(d,"user",I),v++,k.update({turn:v,busy:!0,activity:"thinking..."});let L=new xe({platformUrl:r.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:Rm(e.mode),maxTurns:r.maxTurns,sandboxed:e.sandbox,webEnabled:r.webEnabled,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});ne=L;let T="";L.on("event",E=>{switch(E.type){case"streaming_chunk":T+=E.content,process.stdout.write(E.content);break;case"streaming_end":if(T.trim()){let D=T.split(`
|
|
321
|
+
`).length;process.stdout.write(`\x1B[${D}A\x1B[J`),console.log(ir(T))}else console.log("");T="";break;case"tool_call_start":i.printToolCallStart(E.name,E.args),E.name==="file_read"&&E.args?.file_path&&h.add(String(E.args.file_path)),["file_edit","file_write","file_create"].includes(E.name)&&E.args?.file_path&&m.add(String(E.args.file_path));break;case"tool_call_result":i.printToolCallResult(E.name,E.result);break;case"ask_user":console.log(a.cyan(`
|
|
322
|
+
\u{1F914} ${E.question}`)),O.question(a.dim(" Answer: "),D=>{L.resolveUserInput(D)});break;case"todo_update":i.printTodoList(E.todos);break;case"run_complete":Rb(E.summary,i),g+=E.summary.tokensIn,y+=E.summary.tokensOut,x+=E.summary.tokensThinking||0,_=L.state.runId;for(let D of E.summary.filesModified)m.add(D);if(k.update({tokensIn:g,tokensOut:y,cost:sn(e.model,g,y,x),turn:v,busy:!1,activity:""}),e.maxCost&&e.maxCost>0){let D=sn(e.model,g,y,x),$=D/e.maxCost;$>=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(""),S=!0):$>=.8&&console.log(a.yellow(` \u26A0\uFE0F 80% of session budget used ($${D.toFixed(2)}/$${e.maxCost.toFixed(2)})`))}let b=L.getCheckpoints();b.size>0&&Ed(L.state.runId,I,e.workspace,b),d&&u.updateStats(d,E.summary.tokensIn+E.summary.tokensOut,0,E.summary.filesModified);break;case"context_compacted":i.printSuccess(`Context auto-compacted: ${E.elided} tool result${E.elided===1?"":"s"} summarized (${Math.round(E.savedTokens/1e3)}K tokens saved, now ${Math.round(E.contextUsed/E.contextWindow*100)}% full)`);break;case"run_error":i.printError(E.error);break}});let M=[];L.on("run_complete",E=>{E?.summary?.filesModified&&(M=E.summary.filesModified)});try{await L.run(I)}catch(E){i.printError(E instanceof Error?E.message:String(E))}if(M.length>0&&ro)try{let{notifyAffectedSessions:E}=await Promise.resolve().then(()=>(_m(),xm));await E(ro,M,p)}catch{}ne=null},"executePrompt");s&&await Pt(s),await Is(),O.prompt(),O.on("line",async I=>{let L=I.trim();if(S){O.close();return}if(!wt&&(L==="<<EOF"||L.endsWith("<<EOF"))){let T=L.replace(/<<EOF$/,"").trim();wt=T?[T]:[],O.setPrompt(a.dim(" ... ")),O.prompt();return}if(wt!==null){if(L==="EOF"){let T=wt.join(`
|
|
323
|
+
`);wt=null,O.setPrompt(n.emoji?`
|
|
324
324
|
\u{1F435} > `:`
|
|
325
|
-
> `),T.trim()&&await
|
|
325
|
+
> `),T.trim()&&await Pt(T),O.prompt();return}wt.push(I),O.setPrompt(a.dim(" ... ")),O.prompt();return}if(L.endsWith("\\")){wt=[L.slice(0,-1)],O.setPrompt(a.dim(" ... ")),O.prompt();return}if(!L){O.prompt();return}if(L.startsWith("/")){let[T,...M]=L.slice(1).split(" "),E=M.join(" ");switch(T){case"exit":case"quit":case"q":c.fire("Stop",{workspace:e.workspace,data:{}}),k.stop(),O.close();return;case"clear":case"cls":console.clear();break;case"model":case"models":if(E)e.model=E,i.printSuccess(`Model changed to: ${E}`),k.update({model:E});else try{let{fetchModels:b}=await Promise.resolve().then(()=>(Em(),Cm)),D=await b();if(D.length===0)console.log(a.yellow(" No models returned from the API."));else{let $=j(),F=Me($),R=$.ansi,q=R?a.hex(Ye.accent):_e=>_e,P=R?a.dim:_e=>_e,st=R?a.green:_e=>_e;if($.unicode){console.log(""),console.log(q(` ${F.topLeft}${F.horizontal} Available Models ${F.horizontal.repeat(Math.max(0,32))}${F.topRight}`)),console.log(q(` ${F.vertical}${" ".repeat(52)}${F.vertical}`));let nt=` Current: ${a.bold(e.model)}`,Os=nt.replace(/\x1b\[[0-9;]*m/g,""),js=Math.max(0,52-Os.length);console.log(q(` ${F.vertical}`)+st(nt)+" ".repeat(js)+q(F.vertical)),console.log(q(` ${F.teeRight}${F.horizontal.repeat(52)}${F.teeLeft}`));for(let Co of D){let xi=Co.id===e.model,ug=xi?st("\u25CF"):P("\u25CB"),dg=((xi?a.bold(Co.name||Co.id):Co.name||Co.id)+(xi?" \u25C0":"")).padEnd(26),pg=Co.contextWindow?P(`${Math.round(Co.contextWindow/1e3)}k`.padEnd(8)):"".padEnd(8),Tl=` ${ug} ${dg}${pg}`,mg=Tl.replace(/\x1b\[[0-9;]*m/g,""),fg=Math.max(0,52-mg.length);console.log(q(` ${F.vertical}`)+`${Tl}${" ".repeat(fg)}`+q(F.vertical))}console.log(q(` ${F.vertical}${" ".repeat(52)}${F.vertical}`));let Re=" Usage: /model <name>",lg=Math.max(0,52-Re.length);console.log(q(` ${F.vertical}`)+P(`${Re}${" ".repeat(lg)}`)+q(F.vertical)),console.log(q(` ${F.bottomLeft}${F.horizontal.repeat(52)}${F.bottomRight}`)),console.log("")}else{console.log(`
|
|
326
326
|
Current model: ${e.model}
|
|
327
|
-
`);for(let
|
|
327
|
+
`);for(let _e of D){let nt=_e.id===e.model?" <-- current":"";console.log(` ${_e.name||_e.id}${nt}`)}console.log(`
|
|
328
328
|
Usage: /model <name>
|
|
329
|
-
`)}}}catch(
|
|
330
|
-
`).length;
|
|
331
|
-
\u{1F50D} Reviewing ${
|
|
329
|
+
`)}}}catch(b){i.printError(`Could not fetch models: ${b.message||b}`)}break;case"mode":["plan","fast","thinking"].includes(E)?(e.mode=E,i.printSuccess(`Mode changed to: ${E}`)):i.printError("Valid modes: plan, fast, thinking");break;case"diff":try{let b=(0,et.execSync)("git diff",{cwd:e.workspace,encoding:"utf8"});b.trim()?(console.log(""),console.log(b)):console.log(a.dim(" No uncommitted changes."))}catch{i.printError("Failed to run git diff (is this a git repository?)")}break;case"undo":{let b=Fd();if(b.length===0){i.printError("Nothing to undo \u2014 no checkpoints found.");break}let D=b[0];try{let $=Td(D.runId);i.printSuccess(`Reverted ${$.length} file(s):`);for(let F of $)console.log(` \u21A9 ${F}`)}catch($){i.printError($ instanceof Error?$.message:"Undo failed")}break}case"commit":{try{(0,et.execSync)("git add -A",{cwd:e.workspace,stdio:"pipe"});let b=E||`mc: agent changes (${m.size} files)`,$=(0,et.execSync)(`git commit -m "${b.replace(/"/g,'\\"')}"`,{cwd:e.workspace,encoding:"utf8",stdio:"pipe"}).match(/\[[\w-]+\s+([a-f0-9]+)\]/),F=$?$[1]:"???";i.printSuccess(`Committed: ${F} \u2014 ${b}`)}catch(b){i.printError(b instanceof Error?b.message:"Commit failed")}break}case"files":if(m.size===0&&h.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 b of m)console.log(` \u270F\uFE0F ${K.relative(e.workspace,b)||b}`)}if(h.size>0){console.log(` Files read (${h.size}):`);for(let b of[...h].slice(0,20))console.log(` \u{1F4D6} ${K.relative(e.workspace,b)||b}`);h.size>20&&console.log(a.dim(` ... and ${h.size-20} more`))}console.log("")}break;case"cost":{let b=yr(e.model),D=b?g/1e6*b.costInputPerM:0,$=b?y/1e6*b.costOutputPerM:0,F=b?x/1e6*b.costOutputPerM:0,R=D+$+F;if(console.log(""),console.log(" \u{1F4B0} Session Cost"),console.log(` ${"\u2500".repeat(36)}`),console.log(` Model: ${b?.displayName||e.model}`),console.log(` Input: ${g.toLocaleString()} tokens ($${D.toFixed(2)})`),console.log(` Output: ${y.toLocaleString()} tokens ($${$.toFixed(2)})`),x>0&&console.log(` Thinking: ${x.toLocaleString()} tokens ($${F.toFixed(2)})`),console.log(` Total: $${R.toFixed(2)}`),e.maxCost&&e.maxCost>0){let q=Math.max(0,e.maxCost-R),P=Math.round((1-R/e.maxCost)*100);console.log(` Budget: $${e.maxCost.toFixed(2)} (${P}% remaining)`)}console.log(` Turns: ${v}`),console.log(` ${"\u2500".repeat(36)}`),console.log("");break}case"context":case"ctx":if(E){let b=K.resolve(e.workspace,E);try{let $=require("node:fs").readFileSync(b,"utf8").split(`
|
|
330
|
+
`).length;h.add(b),i.printSuccess(`Added ${E} to context (${$} lines). Mention it in your next prompt.`)}catch{i.printError(`File not found: ${E}`)}}else{let b=Dr(e.model),D=ne?.getContextStats();if(console.log(""),console.log(" \u{1F4CA} Context Summary"),console.log(` ${"\u2500".repeat(40)}`),console.log(` Turns: ${v}`),console.log(` Tokens in: ${g.toLocaleString()}`),console.log(` Tokens out: ${y.toLocaleString()}`),console.log(` Files read: ${h.size}`),console.log(` Files edited: ${m.size}`),console.log(` Model: ${e.model}`),console.log(` Context window: ${(b/1e3).toFixed(0)}K tokens`),D){let $=D.pct,F=30,R=Math.round($/100*F),q=F-R,P=$>=80?a.red:$>=60?a.yellow:a.green;console.log(` Context used: ${P(`${$}%`)} ${P("\u2588".repeat(R))}${a.dim("\u2591".repeat(q))}`),console.log(` Messages: ${D.messageCount}`),console.log(` Auto-compact: ${$>=85?a.yellow("will trigger"):a.green("standby")}`)}console.log(` ${"\u2500".repeat(40)}`),console.log("")}break;case"compact":{if(!ne){console.log(a.dim(" No active conversation to compact. Run a prompt first."));break}let b=E.replace(/^["']|["']$/g,"").trim(),D=ne.getContextStats();if(!b&&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(b){i.printStatus(`Compacting with focus: "${b}"`);let $=ne.manualCompact(2);if($.elided>0){let F=ne.getContextStats(),R=Math.round($.savedTokens/1e3);i.printSuccess(`Compacted: ${$.elided} tool result${$.elided===1?"":"s"} summarized (${R}K tokens saved, ${D.pct}% \u2192 ${F.pct}%)`),console.log(a.dim(` Retained focus: "${b}"`))}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}else{let $=ne.manualCompact();if($.elided>0){let F=ne.getContextStats(),R=Math.round($.savedTokens/1e3);i.printSuccess(`Compacted: ${$.elided} tool result${$.elided===1?"":"s"} summarized (${R}K tokens saved, ${D.pct}% \u2192 ${F.pct}%)`)}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}break}case"doctor":await hn();break;case"permissions":{let b=E.split(" ")[0]?.toLowerCase()||"show",D=K.join(e.workspace,".monkeyscode","permissions.json");if(b==="edit"){let $=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!N.existsSync(D))console.log(a.dim(" No permissions.json. Run /init to generate one."));else try{(0,et.execSync)(`${$} "${D}"`,{stdio:"inherit"}),i.printSuccess("Permissions saved.")}catch{i.printError(`Failed to open editor: ${$}`)}}else if(b==="reset")N.existsSync(D)?(N.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(", ")}`),N.existsSync(D))try{let $=JSON.parse(N.readFileSync(D,"utf8"));console.log(""),console.log(a.dim(` \u{1F4C4} ${K.relative(e.workspace,D)}`)),$.allow?.length&&console.log(` Allow rules: ${$.allow.length} rules`),$.deny?.length&&console.log(` Deny rules: ${$.deny.length} rules`),$.cost?.max_per_run_usd&&console.log(` Cost limit: $${$.cost.max_per_run_usd}`),$.sandbox?.enabled&&console.log(` Sandbox paths: ${$.sandbox.writable_paths?.join(", ")||"all"}`)}catch{}else console.log(a.dim(" No project permissions.json. Run /init to generate."));console.log("")}break}case"fork":{let b=E.trim()||"Continue working on the current task in the background";await no.spawn(b);break}case"sessions":{let b=u.list();if(b.length===0)console.log(a.dim(" No saved sessions."));else{console.log(""),console.log(a.bold(" Recent Sessions:"));for(let D of b.slice(0,10)){let $=a.hex("#6B8DD6")(D.id.substring(0,8)),F=Pb(D.lastActive);console.log(` ${$} ${D.preview.substring(0,50).padEnd(52)} ${a.dim(F)}`)}console.log("")}break}case"resume":case"continue":{let b=E.trim(),D=b?u.load(b):u.loadLatest(e.workspace);if(!D)i.printError(b?`Session "${b}" not found.`:"No sessions to resume.");else{d=D,v=D.turnCount;for(let $ of D.stats.filesChanged)m.add($);i.printSuccess(`Resumed session ${D.id.substring(0,8)} (${D.turnCount} turns, ${D.stats.tokensUsed.toLocaleString()} tokens)`)}break}case"goal":{let b=E.trim().replace(/^["']|["']$/g,"");if(!b&&b!=="status"&&b!=="cancel"){i.printError('Usage: /goal "implement feature X with tests" | /goal status | /goal cancel');break}if(b==="status"){if(De){let D=De.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(b==="cancel"){De?(De.cancel(),i.printSuccess("Goal cancelled.")):console.log(a.dim(" No active goal."));break}De=new Cr({goal:b,workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),await De.run(),De=null;break}case"subtask":case"sub":{let b=E.trim();if(b==="status")no.printStatus();else if(b.startsWith("cancel "))no.cancel(b.slice(7).trim());else if(b){let D=b.replace(/^["']|["']$/g,"");await no.spawn(D)}else i.printError('Usage: /subtask "task description" | /subtask status | /subtask cancel <id>');break}case"delegate":case"del":{let b=E.trim();if(!b){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=b.match(/"([^"]+)"/g)?.map(R=>R.replace(/"/g,""))||[b];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 $=new Ar({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id});$.on("orchestrator",R=>{switch(R.type){case"task.started":console.log(a.cyan(` \u25B6 Started: ${R.taskId}`));break;case"task.completed":console.log(a.green(` \u2705 Completed: ${R.taskId}`));break;case"task.failed":console.log(a.red(` \u274C Failed: ${R.taskId} \u2014 ${R.data?.error||"unknown"}`));break;case"conflict.detected":console.log(a.yellow(` \u26A0\uFE0F Conflict: ${R.data?.file}`));break}});let F=D.map((R,q)=>({id:`delegate-${q+1}`,prompt:R,workspace:e.workspace,parentId:"repl",dependencies:[],status:"pending"}));try{let R=await $.fanOut(F),q=await $.fanIn(R);console.log(""),console.log(a.bold(" Delegation Results")),console.log(` ${"\u2500".repeat(50)}`),console.log(` Tasks: ${R.length}`),console.log(` Succeeded: ${a.green(String(R.filter(P=>P.status==="complete").length))}`),console.log(` Failed: ${a.red(String(R.filter(P=>P.status==="failed").length))}`),console.log(` Files: ${q.mergedFiles.length}`),console.log(` Conflicts: ${q.conflicts.length}`),console.log(` Tokens: ${q.totalTokens.toLocaleString()}`),console.log(` Cost: $${q.totalCost.toFixed(4)}`),console.log(` Duration: ${(q.totalDurationMs/1e3).toFixed(1)}s`),console.log(` ${"\u2500".repeat(50)}`),console.log("")}catch(R){i.printError(`Delegation failed: ${R.message}`)}break}case"search":E?await Pt(`Search the web for: ${E.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":E?await Pt(`Look up documentation for: ${E}`):console.log(a.dim(" Usage: /docs express routing \u2014 looks up documentation for a topic."));break;case"review":{let b="all changes in this session",D="git diff";E==="staged"?(D="git diff --cached",b="staged changes"):E&&(D=`git diff -- ${E}`,b=`changes in ${E}`);try{let $=(0,et.execSync)(D,{cwd:e.workspace,encoding:"utf8"});$.trim()?(console.log(a.bold(`
|
|
331
|
+
\u{1F50D} Reviewing ${b}...`)),await Pt(`Review the following code changes for bugs, security issues, and code quality. Provide severity ratings (HIGH/MEDIUM/LOW) for each finding.
|
|
332
332
|
|
|
333
333
|
\`\`\`diff
|
|
334
334
|
${$}
|
|
335
|
-
\`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let
|
|
336
|
-
`),"utf8"),q.push("rules.md")}if(!
|
|
337
|
-
`,"utf8"),q.push("permissions.json")}if(
|
|
338
|
-
`),"utf8"),q.push("skills/")),!
|
|
339
|
-
`),"utf8");try{
|
|
340
|
-
`;
|
|
335
|
+
\`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let b=K.join(e.workspace,".monkeyscode"),D=K.join(b,"rules.md"),$=K.join(b,"permissions.json"),F=K.join(b,"skills"),R=K.join(b,"hooks");N.mkdirSync(b,{recursive:!0});let q=[];if(!N.existsSync(D)){let P=["# Project Conventions",""],st=K.join(e.workspace,"package.json"),_e=K.join(e.workspace,"Cargo.toml"),nt=K.join(e.workspace,"pyproject.toml"),Os=K.join(e.workspace,"tsconfig.json"),js=K.join(e.workspace,"go.mod");if(N.existsSync(st))try{let Re=JSON.parse(N.readFileSync(st,"utf8"));P.push(`## Language: ${Re.type==="module"?"TypeScript/ESM":"JavaScript/CJS"}`),Re.scripts?.test&&P.push(`- Test command: \`${Re.scripts.test}\``),Re.scripts?.lint&&P.push(`- Lint command: \`${Re.scripts.lint}\``),Re.scripts?.build&&P.push(`- Build command: \`${Re.scripts.build}\``),Re.dependencies?.react&&P.push("- Framework: React"),Re.dependencies?.next&&P.push("- Framework: Next.js"),Re.dependencies?.express&&P.push("- Server: Express"),P.push("")}catch{}N.existsSync(Os)&&(P.push("## TypeScript"),P.push("- Use strict TypeScript with explicit types"),P.push("- Prefer `interface` over `type` for object shapes"),P.push("")),N.existsSync(_e)&&(P.push("## Language: Rust"),P.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),P.push("")),N.existsSync(nt)&&(P.push("## Language: Python"),P.push("- Follow PEP 8 conventions"),P.push("")),N.existsSync(js)&&(P.push("## Language: Go"),P.push("- Follow Go conventions (gofmt, error wrapping)"),P.push("")),P.push("## Style"),P.push("- Keep functions small and focused"),P.push("- Write clear error messages"),P.push("- Add JSDoc/docstrings for public APIs"),P.push(""),P.push("## Testing"),P.push("- Write tests for all new functionality"),P.push("- Use descriptive test names"),P.push(""),N.writeFileSync(D,P.join(`
|
|
336
|
+
`),"utf8"),q.push("rules.md")}if(!N.existsSync($)){let P="",st=K.join(e.workspace,"package.json");if(N.existsSync(st))try{JSON.parse(N.readFileSync(st,"utf8")).scripts?.test&&(P="npm test")}catch{}!P&&N.existsSync(K.join(e.workspace,"Cargo.toml"))&&(P="cargo test"),!P&&N.existsSync(K.join(e.workspace,"go.mod"))&&(P="go test ./..."),!P&&N.existsSync(K.join(e.workspace,"pyproject.toml"))&&(P="pytest");let _e={mode:"default",allow:["Bash(git status*)","Bash(git diff*)","Bash(git log*)"],deny:["Bash(rm -rf /)","Bash(sudo *)","/Bash\\(curl.*\\|.*sh\\)/"],smartApprove:P?[`Bash(${P}*)`]:[],sandbox:{enabled:!0,writable_paths:["src/","tests/","test/","docs/","lib/"],blocked_commands:["rm -rf /","sudo","curl | sh","chmod 777"]},cost:{max_per_run_usd:10,warn_at_usd:5}};N.writeFileSync($,JSON.stringify(_e,null,2)+`
|
|
337
|
+
`,"utf8"),q.push("permissions.json")}if(N.existsSync(F)||(N.mkdirSync(F,{recursive:!0}),N.writeFileSync(K.join(F,"README.md"),["# Skills","","Place custom skills here. Each skill is a directory with a `skill.md` file.","","## Quick Start","","```bash","/skill create my-skill","```","","## Structure","","```","skills/","\u2514\u2500\u2500 my-skill/"," \u2514\u2500\u2500 skill.md # YAML frontmatter + markdown instructions","```",""].join(`
|
|
338
|
+
`),"utf8"),q.push("skills/")),!N.existsSync(R)){N.mkdirSync(R,{recursive:!0});let P=K.join(R,"pre-write-lint.sh.example");N.writeFileSync(P,["#!/bin/bash","# Example PreToolUse hook: lint before file writes.","# Remove .example extension to enable.","#","# Env vars: MC_TOOL_NAME, MC_TOOL_ARGS (JSON), MC_WORKSPACE, MC_SESSION_ID","# Exit 0=allow, 1=deny, 2=deny+message on stderr","",'if [[ "$MC_TOOL_NAME" == "edit_file" || "$MC_TOOL_NAME" == "create_file" ]]; then',` FILE=$(echo "$MC_TOOL_ARGS" | jq -r '.path // .file_path // empty')`,' if [[ "$FILE" == *.ts && -f "$FILE" ]]; then',' npx eslint "$FILE" --quiet 2>/dev/null || true'," fi","fi","","exit 0",""].join(`
|
|
339
|
+
`),"utf8");try{N.chmodSync(P,493)}catch{}q.push("hooks/")}q.length>0?(i.printSuccess(`Initialized .monkeyscode/ with: ${q.join(", ")}`),console.log(a.dim(" Edit with: /memory, /permissions, /skill"))):i.printWarning("Project already initialized. Use /memory, /permissions, /skill to manage.");break}case"memory":{let b=K.join(e.workspace,".monkeyscode","rules.md"),D=E.split(" ")[0]?.toLowerCase(),$=E.slice(D?.length||0).trim();if(D==="add"&&$){let F=$.replace(/^["']|["']$/g,"");N.mkdirSync(K.dirname(b),{recursive:!0});let R=N.existsSync(b)?N.readFileSync(b,"utf8"):`# Project Conventions
|
|
340
|
+
`;N.writeFileSync(b,R.trimEnd()+`
|
|
341
341
|
- `+F+`
|
|
342
|
-
`,"utf8"),i.printSuccess(`Added rule: ${F}`)}else if(
|
|
343
|
-
`))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(
|
|
344
|
-
`),"utf8"),i.printSuccess(`Created skill: ${
|
|
345
|
-
`),"utf8");try{
|
|
342
|
+
`,"utf8"),i.printSuccess(`Added rule: ${F}`)}else if(D==="show"||!D)if(N.existsSync(b)){let F=N.readFileSync(b,"utf8");console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules")),console.log(a.dim(` ${b}`)),console.log(a.dim(" "+"\u2500".repeat(40)));for(let R of F.split(`
|
|
343
|
+
`))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(D==="edit"){let F=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!N.existsSync(b))console.log(a.dim(" No rules file. Run /init first."));else try{(0,et.execSync)(`${F} "${b}"`,{stdio:"inherit"}),i.printSuccess("Rules file saved.")}catch{i.printError(`Failed to open editor: ${F}`)}}else console.log(a.dim(' Usage: /memory show | /memory add "rule" | /memory edit'));break}case"skill":case"skills":{let b=E.split(" ")[0]?.toLowerCase(),D=E.slice(b?.length||0).trim();if(b==="create"&&D){let $=D.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),F=K.join(e.workspace,".monkeyscode","skills",$),R=K.join(F,"skill.md");N.existsSync(R)?console.log(a.yellow(` Skill "${$}" already exists.`)):(N.mkdirSync(F,{recursive:!0}),N.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(`
|
|
344
|
+
`),"utf8"),i.printSuccess(`Created skill: ${K.relative(e.workspace,R)}`),console.log(a.dim(" Edit the file to add your instructions.")))}else try{let{listAllSkills:$}=await Promise.resolve().then(()=>(kr(),Ha)),F=$(e.workspace);if(F.length===0)console.log(a.dim(" No skills found.")),console.log(a.dim(" Create one with: /skill create <name>")),console.log(a.dim(" Skills directory: .monkeyscode/skills/<name>/skill.md"));else{console.log(""),console.log(a.bold(" \u{1F9E0} Skills")),console.log(a.dim(" "+"\u2500".repeat(50)));for(let R of F){let q=R.enabled?a.green("\u25CF"):a.dim("\u25CB"),P=R.source==="project"?a.cyan("proj"):a.dim("glob");console.log(` ${q} ${a.bold(R.name.padEnd(20))} ${P} P:${R.priority} ${a.dim(R.description.slice(0,40))}`)}console.log("")}}catch($){i.printError(`Failed to list skills: ${$ instanceof Error?$.message:$}`)}break}case"hooks":case"hook":{let b=E.split(" ")[0]?.toLowerCase(),D=E.slice(b?.length||0).trim();if(b==="create"&&D){let $=D.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),F=K.join(e.workspace,".monkeyscode","hooks",`${$}.sh`);if(N.existsSync(F))console.log(a.yellow(` Hook "${$}" already exists.`));else{N.mkdirSync(K.dirname(F),{recursive:!0}),N.writeFileSync(F,["#!/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(`
|
|
345
|
+
`),"utf8");try{N.chmodSync(F,493)}catch{}i.printSuccess(`Created hook: ${K.relative(e.workspace,F)}`)}}else{let $=c.getHooks();if($.length===0)console.log(a.dim(" No active hooks.")),console.log(a.dim(" Create one with: /hooks create <name>")),console.log(a.dim(" Hooks directory: .monkeyscode/hooks/"));else{console.log(""),console.log(a.bold(" \u{1FA9D} Active Hooks")),console.log(a.dim(" "+"\u2500".repeat(50)));for(let F of $){let R=a.cyan(F.event||"PreToolUse"),q=a.bold(F.name||F.path||"hook");console.log(` ${R.padEnd(20)} ${q}`)}console.log("")}}break}case"plan":e.mode="plan",i.printSuccess("Switched to plan mode \u2014 agent will research and propose without editing.");break;case"ask":e.mode="plan",i.printSuccess("Switched to ask mode \u2014 read-only Q&A about the codebase (no edits, no commands).");break;case"cloud":{console.log(a.dim(" \u2601\uFE0F Submitting current task to cloud..."));try{let{submitBackgroundJob:b}=await Promise.resolve().then(()=>(gn(),Pc)),D=e.prompt||"(continue session)",$=ne?.getConversationHistory?.()||[];await b({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:$.length>0?$:void 0})}catch(b){console.error(a.red(` \u274C Cloud submission failed: ${b instanceof Error?b.message:b}`))}break}case"message":{let b=E.match(/^(\S+)\s+"?([^"]+)"?$/);if(!b){console.log(a.yellow(' Usage: /message <session-id> "your message"'));break}try{let{MessageBroker:D}=await Promise.resolve().then(()=>(vn(),Zr)),$=(await Promise.resolve().then(()=>(Q(),we))).loadSettings(),F=(await Promise.resolve().then(()=>(ee(),he))).loadAuth(),q=await new D($.platformUrl,F?.access_token||"",p).sendMessage(b[1],b[2]);q.success?console.log(a.green(` \u{1F4E8} Message sent to ${b[1]}`)):console.error(a.red(` \u274C Send failed: ${q.error}`))}catch(D){console.error(a.red(` \u274C Messaging error: ${D instanceof Error?D.message:D}`))}break}case"broadcast":{let b=E.replace(/^"/,"").replace(/"$/,"").trim();if(!b){console.log(a.yellow(' Usage: /broadcast "your message to all sessions"'));break}try{let{MessageBroker:D}=await Promise.resolve().then(()=>(vn(),Zr)),$=(await Promise.resolve().then(()=>(Q(),we))).loadSettings(),F=(await Promise.resolve().then(()=>(ee(),he))).loadAuth(),q=await new D($.platformUrl,F?.access_token||"",p).broadcast(b);q.success?console.log(a.green(" \u{1F4E2} Broadcast sent to all active sessions")):console.error(a.red(` \u274C Broadcast failed: ${q.error}`))}catch(D){console.error(a.red(` \u274C Messaging error: ${D instanceof Error?D.message:D}`))}break}case"bug":case"feedback":{let b=process.platform,D=process.version,$=ne?.getContextStats();console.log(""),console.log(a.bold(" \u{1F41B} Bug Report Context")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Platform: ${b} (${process.arch})`),console.log(` Node: ${D}`),console.log(` Model: ${e.model}`),console.log(` Mode: ${e.mode}`),console.log(` Turns: ${v}`),console.log(` Tokens: ${(g+y).toLocaleString()}`),$&&console.log(` Context: ${$.pct}% (${$.messageCount} messages)`),console.log(` Session: ${d?.id??"none"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.dim(" Copy the above and paste into: https://github.com/monkeyscloud/monkeyscode/issues/new")),console.log("");break}case"vim":{Zo=!Zo,Zo?(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.")),O.setPrompt(n.emoji?`
|
|
346
346
|
\u{1F435} [I]> `:`
|
|
347
|
-
[I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),
|
|
347
|
+
[I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),O.setPrompt(n.emoji?`
|
|
348
348
|
\u{1F435} > `:`
|
|
349
|
-
> `));break}case"help":case"h":case"?":
|
|
350
|
-
Cancelling current run...`),ne.cancel()):(c.fire("Stop",{workspace:e.workspace,data:{}}),
|
|
351
|
-
`),process.exit(4)),t||(process.stderr.write("Error: Not authenticated. Run `mc auth login` or set MONKEYSCODE_API_KEY.\n"),process.exit(3));let m=
|
|
352
|
-
`);let
|
|
353
|
-
[headless] Timeout after ${
|
|
354
|
-
`)},
|
|
349
|
+
> `));break}case"help":case"h":case"?":Ab();break;case"logout":xa(),i.printSuccess("Logged out."),process.exit(0);break;default:i.printError(`Unknown command: /${T}. Type /help for available commands.`)}O.prompt();return}await Pt(L),await Is(),O.prompt()});let Ms=l(()=>{let I=Date.now()-f,L=Math.floor(I/6e4),T=Math.floor(I%6e4/1e3),M=L>0?`${L}m ${T}s`:`${T}s`;if(console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(" \u{1F4CA} Session Summary")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Duration: ${M}`)),console.log(a.dim(` Turns: ${v}`)),console.log(a.dim(` Tokens: ${(g+y).toLocaleString()}`)),m.size>0){console.log(a.dim(` Files changed: ${m.size}`));for(let E of m)console.log(a.dim(` \u270F\uFE0F ${K.relative(e.workspace,E)||E}`))}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");O.on("close",()=>{c.fire("Stop",{workspace:e.workspace,data:{}}),Ms(),process.exit(0)}),O.on("SIGINT",()=>{ne?(console.log(`
|
|
350
|
+
Cancelling current run...`),ne.cancel()):(c.fire("Stop",{workspace:e.workspace,data:{}}),O.close())}),await new Promise(I=>{O.on("close",I)})}l(Fm,"runInteractive");async function Eb(s,e,t,o){s||(process.stderr.write(`Error: No prompt provided. Use -p "your prompt" or pipe via stdin.
|
|
351
|
+
`),process.exit(4)),t||(process.stderr.write("Error: Not authenticated. Run `mc auth login` or set MONKEYSCODE_API_KEY.\n"),process.exit(3));let m=Y(),h=Date.now(),g=`headless-${Date.now().toString(36)}`,y="",x=!1,v=!1,_=e.output,S=sm(_,{workspace:e.workspace}),k=nm(e.model,g),C=[],J=[],O=0,ce=0,ne=0,De=0,Zo=process.env.CI==="true"||process.env.CI==="1"||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI;Zo&&!e.sandbox&&e.permissionMode!=="bypassPermissions"&&process.stderr.write(`[headless] CI environment detected \u2014 sandbox=auto
|
|
352
|
+
`);let wt=new Mo(e.workspace,{enabled:!0,timeoutMs:1e4});await wt.fire("HeadlessStart",{workspace:e.workspace,data:{prompt:s,model:e.model}});let no=e.timeout||3e5,ro=setTimeout(()=>{v=!0,process.stderr.write(`
|
|
353
|
+
[headless] Timeout after ${no}ms. Stopping gracefully.
|
|
354
|
+
`)},no),Is=l(()=>{x=!0,process.stderr.write(`
|
|
355
355
|
[headless] SIGINT received. Stopping.
|
|
356
|
-
`)},"sigintHandler");process.on("SIGINT",
|
|
357
|
-
`).filter(Boolean);for(let M of T)try{let
|
|
358
|
-
`)}break;case"tool_call_start":if(
|
|
356
|
+
`)},"sigintHandler");process.on("SIGINT",Is);let Pt=await import("node:crypto"),Ms=new Map;try{let T=(0,et.execSync)("git ls-files -m",{cwd:e.workspace,encoding:"utf8"}).trim().split(`
|
|
357
|
+
`).filter(Boolean);for(let M of T)try{let E=N.readFileSync(K.join(e.workspace,M));Ms.set(M,Pt.createHash("sha256").update(E).digest("hex"))}catch{}}catch{}let I=new xe({platformUrl:m.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:Rm(e.mode),maxTurns:m.maxTurns,sandboxed:e.sandbox||Zo,webEnabled:m.webEnabled&&!e.offline,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});I.on("event",T=>{switch(T.type){case"streaming_chunk":if(y+=T.content,_==="stream"&&process.stdout.write(T.content),_==="jsonl"&&S.formatEvent){let M=S.formatEvent({type:"chunk",timestamp:Date.now(),data:{content:T.content}});M&&process.stdout.write(M+`
|
|
358
|
+
`)}break;case"tool_call_start":if(O=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}"
|
|
359
359
|
`);break}if(process.stderr.write(`[tool] ${T.name}(${JSON.stringify(T.args).substring(0,100)})
|
|
360
|
-
`),["file_edit","file_write","file_create"].includes(T.name)&&T.args?.file_path&&
|
|
361
|
-
`)}break;case"tool_call_result":if(
|
|
360
|
+
`),["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}),_==="jsonl"&&S.formatEvent){let M=S.formatEvent({type:"tool_start",timestamp:Date.now(),data:{tool:T.name,args:T.args}});M&&process.stdout.write(M+`
|
|
361
|
+
`)}break;case"tool_call_result":if(C.push({tool:T.name,args:{},duration:Date.now()-O,result:typeof T.result=="string"?T.result.substring(0,200):void 0}),_==="jsonl"&&S.formatEvent){let M=S.formatEvent({type:"tool_result",timestamp:Date.now(),data:{tool:T.name,duration:Date.now()-O,result:typeof T.result=="string"?T.result.substring(0,200):""}});M&&process.stdout.write(M+`
|
|
362
362
|
`)}break;case"ask_user":process.stderr.write(`[headless] Input prompt skipped (headless mode): ${T.question}
|
|
363
|
-
`),
|
|
363
|
+
`),I.resolveUserInput("");break;case"run_complete":ce+=T.summary.tokensIn,ne+=T.summary.tokensOut,De+=T.summary.tokensThinking||0;for(let M of T.summary.filesModified)J.find(b=>b.path===M)||J.push({path:M,action:"modified",linesAdded:0,linesRemoved:0});process.stderr.write(`[headless] Run complete: ${T.summary.filesModified.length} files, ${T.summary.tokensIn+T.summary.tokensOut} tokens
|
|
364
364
|
`);break;case"run_error":if(process.stderr.write(`[headless] Error: ${T.message||"unknown"}
|
|
365
|
-
`),
|
|
366
|
-
`)}break}});let
|
|
367
|
-
`)[0]?.substring(0,200)||"Task completed."),
|
|
368
|
-
`),
|
|
369
|
-
`);else{let T=
|
|
370
|
-
`)}await ht.fire("HeadlessStop",{workspace:e.workspace,data:{success:v.success,exitCode:N,duration:v.duration,filesChanged:oe.length}}),process.removeListener("SIGINT",Es),process.exit(N)}l(Kb,"runHeadless");async function Yb(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(un(),Sc));await t({prompt:s,workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:e.autoBranch??!0,autoCommit:e.autoCommit??!0,autoPR:e.autoPR??!1,maxCost:e.maxCost,timeout:e.timeout})}l(Yb,"runBackground");async function Xb(){return new Promise(s=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{s(e.trim())})})}l(Xb,"readStdin");function Qb(s,e){console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Turns: ${s.turns} \xB7 Tokens: ${s.tokensIn} in / ${s.tokensOut} out`)),s.tokensCached>0&&console.log(a.dim(` Cached: ${s.tokensCached}`)),s.filesModified.length>0&&console.log(a.dim(` Files modified: ${s.filesModified.length}`));let t=(s.duration/1e3).toFixed(1);console.log(a.dim(` Duration: ${t}s`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(Qb,"printRunSummary");function Zb(){let s=I(),e=H(s),t=a.hex("#6B8DD6"),o=a.dim,n=a.bold,r=l((i,c)=>{let u=i.padEnd(30);return` ${t(u)} ${o(c)}`},"cmd");if(s.unicode){let i={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",tr2:"\u251C",tl2:"\u2524"},c=Math.min(62,s.columns-4),u=` ${e.tool} MonkeysCode Commands `,d=Math.max(0,c-u.length-2);console.log(""),console.log(t(` ${i.tl}${i.h}${u}${i.h.repeat(d)}${i.tr}`)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.message} Chat`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/model <name>","Switch model")+t(i.v)),console.log(t(` ${i.v}`)+r("/mode <plan|fast>","Switch mode")+t(i.v)),console.log(t(` ${i.v}`)+r("/compact","Compact context")+t(i.v)),console.log(t(` ${i.v}`)+r('/search "query"',"Web search")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.folder} Project`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/init","Initialize .monkeyscode/")+t(i.v)),console.log(t(` ${i.v}`)+r('/memory add "rule"',"Add convention")+t(i.v)),console.log(t(` ${i.v}`)+r("/permissions","Show/edit permissions")+t(i.v)),console.log(t(` ${i.v}`)+r("/skill","List/create skills")+t(i.v)),console.log(t(` ${i.v}`)+r("/hooks","List/create hooks")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.info} Stats`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/cost","Token usage & cost")+t(i.v)),console.log(t(` ${i.v}`)+r("/context [file]","Context window usage")+t(i.v)),console.log(t(` ${i.v}`)+r("/diff","Show uncommitted changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/files","List modified files")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.rocket} Actions`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/commit [msg]","Auto-commit changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/undo","Undo last file changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/review","Run code review")+t(i.v)),console.log(t(` ${i.v}`)+r('/goal "target"',"Autonomous goal loop")+t(i.v)),console.log(t(` ${i.v}`)+r('/fork ["task"]',"Fork to background")+t(i.v)),console.log(t(` ${i.v}`)+r('/delegate "t1" "t2"',"Parallel agents")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.lock} Session`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/sessions","List saved sessions")+t(i.v)),console.log(t(` ${i.v}`)+r("/resume [id]","Resume a session")+t(i.v)),console.log(t(` ${i.v}`)+r("/exit","Exit the REPL")+t(i.v)),console.log(t(` ${i.v}`)+r("/doctor","System health check")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+o(" Press / + Tab for autocomplete").padEnd(c+12)+t(i.v)),console.log(t(` ${i.bl}${i.h.repeat(c)}${i.br}`)),console.log("")}else console.log(""),console.log(n(" Slash Commands")),console.log(o(" Tab to auto-complete")),console.log(""),console.log(t(" Chat")),console.log(r("/model <name>","Switch model")),console.log(r("/mode <plan|fast>","Switch mode")),console.log(r("/compact","Compact context")),console.log(""),console.log(t(" Project")),console.log(r("/init","Initialize .monkeyscode/")),console.log(r('/memory add "rule"',"Add convention")),console.log(r("/permissions","Show/edit permissions")),console.log(r("/skill","List/create skills")),console.log(r("/hooks","List/create hooks")),console.log(""),console.log(t(" Stats")),console.log(r("/cost","Token usage & cost")),console.log(r("/context [file]","Context window usage")),console.log(r("/diff","Show uncommitted changes")),console.log(r("/files","List modified files")),console.log(""),console.log(t(" Actions")),console.log(r("/commit [msg]","Auto-commit changes")),console.log(r("/undo","Undo last file changes")),console.log(r("/review","Run code review")),console.log(r('/goal "target"',"Autonomous goal loop")),console.log(r('/fork ["task"]',"Fork to background")),console.log(""),console.log(t(" Session")),console.log(r("/sessions","List saved sessions")),console.log(r("/resume [id]","Resume a session")),console.log(r("/exit","Exit the REPL")),console.log(r("/doctor","System health check")),console.log("")}l(Zb,"printSlashHelp");function ew(s){let e=Date.now()-s,t=Math.floor(e/6e4),o=Math.floor(e/36e5),n=Math.floor(e/864e5);return t<1?"just now":t<60?`${t}m ago`:o<24?`${o}h ago`:`${n}d ago`}l(ew,"formatAge");ee();var Vr=b(require("node:readline"),1);W();_e();var Oc=class{static{l(this,"AgentsDashboard")}daemon;caps;icons;box;agents=[];selectedIndex=0;running=!1;refreshInterval=null;constructor(e){this.daemon=e,this.caps=I(),this.icons=H(this.caps),this.box=Me(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(Vr.emitKeypressEvents(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume()),process.stdin.on("keypress",(e,t)=>{this.running&&this.handleKeypress(e,t)}),this.daemon.on("event",()=>{this.fetchAgents().then(()=>this.render())}),this.refreshInterval=setInterval(async()=>{await this.fetchAgents(),this.render()},5e3),this.render(),await new Promise(e=>{let t=setInterval(()=>{this.running||(clearInterval(t),e())},100)})}async list(){await this.fetchAgents();let e=this.caps.ansi;if(this.agents.length===0){console.log(" No active agents.");return}let t=`${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.bold(` ${t}`):` ${t}`),console.log(` ${"\u2500".repeat(Math.min(this.caps.columns-4,100))}`);for(let o of this.agents){let n=this.formatAgentLine(o,!1);console.log(` ${n}`)}}async fetchAgents(){try{this.agents=await this.daemon.call("agents.list",{})}catch{this.agents=[]}}render(){let e=this.caps.ansi,t=Math.min(this.caps.columns,120);console.clear();let o=`${this.icons.rocket} MonkeysCode Agents Dashboard`;if(console.log(e?a.bold(o):o),console.log(e?a.dim(` ${this.agents.length} agent(s) active`):` ${this.agents.length} agent(s) active`),console.log(`${this.box.separator.repeat(t)}`),this.agents.length===0)console.log(""),console.log(" No active agents."),console.log(""),console.log(e?a.dim(' Start one with: mc "your prompt"'):' Start one with: mc "your prompt"'),console.log("");else{let r=` ${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.dim(r):r),console.log(` ${"\u2500".repeat(t-4)}`);for(let i=0;i<this.agents.length;i++){let c=i===this.selectedIndex,u=this.formatAgentLine(this.agents[i],c);console.log(c&&e?a.bgHex("#1a1a2e").white(`\u25B6 ${u}`):` ${u}`)}}console.log(""),console.log(`${this.box.separator.repeat(t)}`);let n=e?` ${a.cyan("[j/k]")} Nav ${a.cyan("[Enter]")} Focus ${a.cyan("[m]")} Message ${a.cyan("[c]")} Cancel ${a.cyan("[l]")} Logs ${a.cyan("[r]")} Retry ${a.cyan("[q]")} Quit`:" [j/k] Nav [Enter] Focus [m] Message [c] Cancel [l] Logs [r] Retry [q] Quit";console.log(n)}formatAgentLine(e,t){let o=this.caps.ansi,n=e.id.slice(0,12).padEnd(14),r=e.type.padEnd(14),i=this.formatStatus(e.status).padEnd(12),c=`"${e.task.slice(0,33)}"`.padEnd(35),u=this.formatDuration(e.duration).padEnd(10),d=this.formatTokens(e.tokens),p=`${n} ${r} ${i} ${c} ${u} ${d}`;if(!o)return p;let g={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)} ${g(i)} ${a.white(c)} ${a.dim(u)} ${a.dim(d)}`}formatStatus(e){return{active:this.caps.emoji?"\u{1F504} Active":"[ACTIVE]",running:this.caps.emoji?"\u{1F504} Running":"[RUNNING]",idle:this.caps.emoji?"\u23F8\uFE0F Idle":"[IDLE]",queued:this.caps.emoji?"\u23F3 Queued":"[QUEUED]",done:this.caps.emoji?"\u2705 Done":"[DONE]",failed:this.caps.emoji?"\u274C Failed":"[FAILED]",cancelled:this.caps.emoji?"\u{1F6AB} Cancel":"[CANCEL]"}[e]||e}formatDuration(e){if(e<=0)return"\u2014";let t=Math.floor(e/1e3),o=Math.floor(t/60),n=Math.floor(o/60);return n>0?`${n}h ${o%60}m`:o>0?`${o}m ${t%60}s`:`${t}s`}formatTokens(e){return e<=0?"\u2014":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}handleKeypress(e,t){if(t){if(t.name==="q"||t.ctrl&&t.name==="c"){this.stop();return}if(t.name==="j"||t.name==="down"){this.selectedIndex=Math.min(this.selectedIndex+1,this.agents.length-1),this.render();return}if(t.name==="k"||t.name==="up"){this.selectedIndex=Math.max(this.selectedIndex-1,0),this.render();return}if(t.name==="return"){this.handleAction("focus");return}if(t.name==="m"){this.handleAction("message");return}if(t.name==="c"){this.handleAction("cancel");return}if(t.name==="l"){this.handleAction("logs");return}if(t.name==="r"){this.handleAction("retry");return}}}async handleAction(e){let t=this.agents[this.selectedIndex];if(t)switch(e){case"focus":console.log(`
|
|
365
|
+
`),_==="jsonl"&&S.formatEvent){let M=S.formatEvent({type:"error",timestamp:Date.now(),data:{message:T.message||"unknown"}});M&&process.stdout.write(M+`
|
|
366
|
+
`)}break}});let L=0;try{let T=I.run(s),M=new Promise(D=>{let $=setInterval(()=>{(v||x)&&(clearInterval($),D(null))},500)}),E=await Promise.race([T,M]);clearTimeout(ro);let b=Date.now()-h;if(v?(L=124,k.status="timeout",k.summary=`Timeout after ${(no/1e3).toFixed(0)}s. Partial result below.`):x?(L=130,k.status="interrupted",k.summary="Interrupted by SIGINT."):E&&(k.status="completed",k.success=!0,k.summary=y.split(`
|
|
367
|
+
`)[0]?.substring(0,200)||"Task completed."),k.filesChanged=J,k.toolCalls=C,k.tokens={input:ce,output:ne,thinking:De,total:ce+ne+De},k.cost=sn(e.model,ce,ne,De),k.duration=b,k.success&&Ms.size>0){let D=!0;for(let[$,F]of Ms)try{let R=N.readFileSync(K.join(e.workspace,$));if(Pt.createHash("sha256").update(R).digest("hex")!==F){D=!1;break}}catch{D=!1;break}D&&J.length===0&&(process.stderr.write(`[headless] Idempotency: no files changed \u2014 edits already applied.
|
|
368
|
+
`),k.summary="No changes needed \u2014 edits already applied.")}}catch(T){clearTimeout(ro);let M=T instanceof Error?T.message:String(T);M.includes("401")||M.includes("auth")||M.includes("token")?L=3:M.includes("ECONNREFUSED")||M.includes("ENOTFOUND")||M.includes("fetch failed")?L=5:L=1,k.status="failed",k.error=M,k.summary=`Error: ${M.substring(0,200)}`,k.duration=Date.now()-h,k.tokens={input:ce,output:ne,thinking:De,total:ce+ne+De},k.cost=sn(e.model,ce,ne,De),k.filesChanged=J,k.toolCalls=C}if(_==="text"||_==="stream")_==="text"&&process.stdout.write(y+`
|
|
369
|
+
`);else{let T=S.formatResult(k);process.stdout.write(T+`
|
|
370
|
+
`)}await wt.fire("HeadlessStop",{workspace:e.workspace,data:{success:k.success,exitCode:L,duration:k.duration,filesChanged:J.length}}),process.removeListener("SIGINT",Is),process.exit(L)}l(Eb,"runHeadless");async function Fb(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(gn(),Pc));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(Fb,"runBackground");async function Tb(){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(Tb,"readStdin");function Rb(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(Rb,"printRunSummary");function Ab(){let s=j(),e=G(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(Ab,"printSlashHelp");function Pb(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(Pb,"formatAge");ee();var ei=w(require("node:readline"),1);H();Ce();var Gc=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=G(this.caps),this.box=Me(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(ei.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(`
|
|
371
371
|
Focusing on ${t.id}... (press Esc to return)
|
|
372
|
-
`);try{await this.daemon.call("agents.focus",{id:t.id})}catch{console.log(" Cannot focus on this agent.")}break;case"message":if(!process.stdin.isTTY)break;process.stdin.setRawMode(!1);let o=
|
|
372
|
+
`);try{await this.daemon.call("agents.focus",{id:t.id})}catch{console.log(" Cannot focus on this agent.")}break;case"message":if(!process.stdin.isTTY)break;process.stdin.setRawMode(!1);let o=ei.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 qc(s=!0){let e=new yo({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 Gc(e);s&&process.stdin.isTTY?await t.start():await t.list(),e.disconnect()}l(qc,"agentsCommand");var Yt=[{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"}],Dn=[{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 Pm(s){switch(s){case"bash":return Ib();case"zsh":return Mb();case"fish":return Ob();case"pwsh":return jb();default:throw new Error(`Unsupported shell: ${s}. Supported: bash, zsh, fish, pwsh`)}}l(Pm,"generateCompletions");function Im(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(`
|
|
373
373
|
`);case"zsh":return["# Add to ~/.zshrc:",'eval "$(monkeyscode completions zsh)"',"","# Or save to fpath:","monkeyscode completions zsh > ~/.zsh/completions/_monkeyscode","# Then ensure ~/.zsh/completions is in your fpath"].join(`
|
|
374
374
|
`);case"fish":return["monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish"].join(`
|
|
375
375
|
`);case"pwsh":return["# Add to your PowerShell profile:","monkeyscode completions pwsh | Out-String | Invoke-Expression","","# Or save and dot-source:","monkeyscode completions pwsh > monkeyscode-completions.ps1",". ./monkeyscode-completions.ps1"].join(`
|
|
376
|
-
`)}}l(
|
|
376
|
+
`)}}l(Im,"getCompletionInstallInstructions");function Ib(){let s=Yt.map(n=>n.name).join(" "),e=Dn.map(n=>n.long).join(" "),t=Dn.filter(n=>n.short).map(n=>n.short).join(" "),o=Yt.filter(n=>n.subcommands).map(n=>{let r=n.subcommands.map(i=>i.name).join(" ");return` ${n.name}) COMPREPLY=( $(compgen -W "${r}" -- "$cur") ) ;;`}).join(`
|
|
377
377
|
`);return`#!/bin/bash
|
|
378
378
|
# monkeyscode bash completion \u2014 generated by monkeyscode completions bash
|
|
379
379
|
# Install: eval "$(monkeyscode completions bash)"
|
|
@@ -400,9 +400,9 @@ ${o}
|
|
|
400
400
|
complete -F _monkeyscode_completions monkeyscode
|
|
401
401
|
complete -F _monkeyscode_completions mc
|
|
402
402
|
complete -F _monkeyscode_completions mcode
|
|
403
|
-
`}l(
|
|
404
|
-
`),e=
|
|
405
|
-
`),t=
|
|
403
|
+
`}l(Ib,"generateBashCompletions");function Mb(){let s=Yt.map(o=>`'${o.name}:${o.description.replace(/'/g,"''")}'`).join(`
|
|
404
|
+
`),e=Dn.map(o=>{let n=o.takesValue?`=${o.description}`:"";return`'${o.short?`{${o.short},${o.long}}`:o.long}[${o.description.replace(/'/g,"''")}]${n}'`}).join(`
|
|
405
|
+
`),t=Yt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>`'${r.name}:${r.description.replace(/'/g,"''")}'`).join(`
|
|
406
406
|
`);return`
|
|
407
407
|
__monkeyscode_${o.name}_commands() {
|
|
408
408
|
local commands
|
|
@@ -432,7 +432,7 @@ _monkeyscode() {
|
|
|
432
432
|
;;
|
|
433
433
|
args)
|
|
434
434
|
case "\${words[1]}" in
|
|
435
|
-
${
|
|
435
|
+
${Yt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_${o.name}_commands ;;`).join(`
|
|
436
436
|
`)}
|
|
437
437
|
esac
|
|
438
438
|
;;
|
|
@@ -441,11 +441,11 @@ ${Vt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_$
|
|
|
441
441
|
${t}
|
|
442
442
|
|
|
443
443
|
compdef _monkeyscode monkeyscode mc mcode
|
|
444
|
-
`}l(
|
|
444
|
+
`}l(Mb,"generateZshCompletions");function Ob(){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 Yt)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 Yt)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 Dn){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(`
|
|
445
445
|
`)+`
|
|
446
|
-
`}l(
|
|
447
|
-
`),e=
|
|
448
|
-
`),t=
|
|
446
|
+
`}l(Ob,"generateFishCompletions");function jb(){let s=Yt.map(o=>` [CompletionResult]::new('${o.name}', '${o.name}', [CompletionResultType]::ParameterValue, '${o.description}')`).join(`
|
|
447
|
+
`),e=Dn.map(o=>` [CompletionResult]::new('${o.long}', '${o.long}', [CompletionResultType]::ParameterName, '${o.description}')`).join(`
|
|
448
|
+
`),t=Yt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>` [CompletionResult]::new('${r.name}', '${r.name}', [CompletionResultType]::ParameterValue, '${r.description}')`).join(`
|
|
449
449
|
`);return` '${o.name}' {
|
|
450
450
|
${n}
|
|
451
451
|
}`}).join(`
|
|
@@ -471,61 +471,61 @@ ${t}
|
|
|
471
471
|
}
|
|
472
472
|
}
|
|
473
473
|
}
|
|
474
|
-
`}l(
|
|
475
|
-
`);e.buffer=
|
|
474
|
+
`}l(jb,"generatePowerShellCompletions");H();gr();function Vc(s){let e=Io(s),t=pd(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(Vc,"hooksListCommand");H();var Mm=require("node:events"),Om=require("node:child_process");var ti=class extends Mm.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,Om.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(`
|
|
475
|
+
`);e.buffer=f.pop()||"";for(let m=0;m<f.length;m++){let h=f[m];if(h.startsWith("data: "))try{let g=JSON.parse(h.slice(6));this._handleResponse(e,g)}catch{}else if(h.startsWith("event: endpoint")){let g=f[m+1];g?.startsWith("data: ")&&(e.sseSessionUrl=g.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(`
|
|
476
476
|
`)||"(no output)",isError:r.isError}:{content:"(no output)"}}catch(r){return{content:`MCP tool call failed: ${r.message}`,isError:!0}}}async readResource(e,t){let o=this._servers.get(e);if(!o||!o.connected)throw new Error(`MCP server "${e}" is not connected`);let n=await this._sendRequest(o,"resources/read",{uri:t});return n?.contents?n.contents.map(r=>r.text||"").join(`
|
|
477
477
|
`):""}getAllTools(){let e=[];for(let t of this._servers.values())t.connected&&e.push(...t.tools);return e}getConnectedServers(){return Array.from(this._servers.entries()).filter(([,e])=>e.connected).map(([e])=>e)}getServerInfo(e){let t=this._servers.get(e);if(t)return{connected:t.connected,tools:t.tools.length,resources:t.resources.length,prompts:t.prompts.length}}disconnect(e){let t=this._servers.get(e);if(t){if(t.process)try{t.process.kill()}catch{}t.sseAbort&&t.sseAbort.abort(),t.connected=!1,this._servers.delete(e),this.emit("connection-changed",{server:e,connected:!1})}}disconnectAll(){for(let e of[...this._servers.keys()])this.disconnect(e)}_sendRequest(e,t,o){return new Promise((n,r)=>{let i=++e.requestId,c={jsonrpc:"2.0",id:i,method:t,params:o},u=setTimeout(()=>{e.pendingRequests.delete(i),r(new Error(`MCP request timed out: ${t}`))},3e4);e.pendingRequests.set(i,{resolve:l(d=>{clearTimeout(u),n(d)},"resolve"),reject:l(d=>{clearTimeout(u),r(d)},"reject")}),this._sendMessage(e,c)})}_sendNotification(e,t,o){this._sendMessage(e,{jsonrpc:"2.0",method:t,params:o})}_sendMessage(e,t){let o=JSON.stringify(t);e.config.transport==="stdio"&&e.process?e.process.stdin?.write(o+`
|
|
478
478
|
`):e.config.transport==="sse"&&e.sseSessionUrl&&fetch(e.sseSessionUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:o}).catch(()=>{})}_processBuffer(e){let t=e.buffer.split(`
|
|
479
|
-
`);e.buffer=t.pop()||"";for(let o of t){let n=o.trim();if(n)try{let r=JSON.parse(n);this._handleResponse(e,r)}catch{}}}_handleResponse(e,t){if(t.id!==void 0){let o=e.pendingRequests.get(t.id);o&&(e.pendingRequests.delete(t.id),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result))}}};var yn=[{id:"github",name:"GitHub",description:"PRs, issues, code search, repository management",category:"dev-tools",icon:"\u{1F419}",install:{transport:"stdio",package:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],envVars:["GITHUB_PERSONAL_ACCESS_TOKEN"]},tags:["github","git","pull-request","issues","code-search"],official:!0},{id:"gitlab",name:"GitLab",description:"GitLab MRs, issues, pipelines",category:"dev-tools",icon:"\u{1F98A}",install:{transport:"stdio",package:"@modelcontextprotocol/server-gitlab",command:"npx",args:["-y","@modelcontextprotocol/server-gitlab"],envVars:["GITLAB_PERSONAL_ACCESS_TOKEN"]},tags:["gitlab","merge-request","ci-cd"],official:!0},{id:"filesystem",name:"Filesystem",description:"Read and write files, list directories",category:"filesystem",icon:"\u{1F4C1}",install:{transport:"stdio",package:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","."]},tags:["files","filesystem","read","write","directory"],official:!0},{id:"memory",name:"Memory",description:"Persistent key-value memory for agent context",category:"other",icon:"\u{1F9E0}",install:{transport:"stdio",package:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"]},tags:["memory","context","persistent","knowledge"],official:!0},{id:"postgres",name:"PostgreSQL",description:"Query PostgreSQL databases, inspect schemas",category:"database",icon:"\u{1F418}",install:{transport:"stdio",package:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],envVars:["POSTGRES_CONNECTION_STRING"]},tags:["postgres","postgresql","sql","database","query"],official:!0},{id:"mysql",name:"MySQL",description:"Query MySQL databases, inspect schemas",category:"database",icon:"\u{1F42C}",install:{transport:"stdio",package:"mcp-server-mysql",command:"npx",args:["-y","mcp-server-mysql"],envVars:["MYSQL_CONNECTION_STRING"]},tags:["mysql","sql","database","query"],official:!1},{id:"sqlite",name:"SQLite",description:"Query SQLite databases",category:"database",icon:"\u{1F4E6}",install:{transport:"stdio",package:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"]},tags:["sqlite","sql","database","local"],official:!0},{id:"mongodb",name:"MongoDB",description:"MongoDB document database queries and operations",category:"database",icon:"\u{1F343}",install:{transport:"stdio",package:"mcp-server-mongodb",command:"npx",args:["-y","mcp-server-mongodb"],envVars:["MONGODB_URI"]},tags:["mongodb","nosql","document","database"],official:!1},{id:"redis",name:"Redis",description:"Redis key-value store, caching, pub/sub",category:"database",icon:"\u{1F534}",install:{transport:"stdio",package:"mcp-server-redis",command:"npx",args:["-y","mcp-server-redis"],envVars:["REDIS_URL"]},tags:["redis","cache","key-value","pub-sub"],official:!1},{id:"supabase",name:"Supabase",description:"Supabase database, auth, storage, edge functions",category:"database",icon:"\u26A1",install:{transport:"stdio",package:"mcp-server-supabase",command:"npx",args:["-y","mcp-server-supabase"],envVars:["SUPABASE_URL","SUPABASE_SERVICE_KEY"]},tags:["supabase","postgres","auth","storage","realtime"],official:!1},{id:"neon",name:"Neon",description:"Neon serverless PostgreSQL branching and queries",category:"database",icon:"\u{1F7E2}",install:{transport:"stdio",package:"@neondatabase/mcp-server-neon",command:"npx",args:["-y","@neondatabase/mcp-server-neon"],envVars:["NEON_API_KEY"]},tags:["neon","postgres","serverless","branching"],official:!0},{id:"linear",name:"Linear",description:"Issues, projects, cycles, team management",category:"project-mgmt",icon:"\u{1F4D0}",install:{transport:"stdio",package:"mcp-server-linear",command:"npx",args:["-y","mcp-server-linear"],envVars:["LINEAR_API_KEY"]},tags:["linear","issues","project","kanban","agile"],official:!1},{id:"jira",name:"Jira",description:"Jira issues, boards, sprints",category:"project-mgmt",icon:"\u{1F535}",install:{transport:"stdio",package:"mcp-server-jira",command:"npx",args:["-y","mcp-server-jira"],envVars:["JIRA_URL","JIRA_EMAIL","JIRA_API_TOKEN"]},tags:["jira","issues","sprint","agile","atlassian"],official:!1},{id:"notion",name:"Notion",description:"Notion pages, databases, blocks, search",category:"project-mgmt",icon:"\u{1F4DD}",install:{transport:"stdio",package:"mcp-server-notion",command:"npx",args:["-y","mcp-server-notion"],envVars:["NOTION_TOKEN"]},tags:["notion","wiki","docs","database","knowledge"],official:!1},{id:"todoist",name:"Todoist",description:"Task management, projects, labels, filters",category:"project-mgmt",icon:"\u2705",install:{transport:"stdio",package:"mcp-server-todoist",command:"npx",args:["-y","mcp-server-todoist"],envVars:["TODOIST_API_TOKEN"]},tags:["todoist","tasks","todo","productivity","project"],official:!1},{id:"slack",name:"Slack",description:"Send messages, read channels, manage threads",category:"communication",icon:"\u{1F4AC}",install:{transport:"stdio",package:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],envVars:["SLACK_BOT_TOKEN"]},tags:["slack","chat","messaging","notifications"],official:!0},{id:"discord",name:"Discord",description:"Discord messaging, channels, server management",category:"communication",icon:"\u{1F3AE}",install:{transport:"stdio",package:"mcp-server-discord",command:"npx",args:["-y","mcp-server-discord"],envVars:["DISCORD_BOT_TOKEN"]},tags:["discord","chat","messaging","bot"],official:!1},{id:"email",name:"Email (SMTP)",description:"Send and read emails via SMTP/IMAP",category:"communication",icon:"\u{1F4E7}",install:{transport:"stdio",package:"mcp-server-email",command:"npx",args:["-y","mcp-server-email"],envVars:["SMTP_HOST","SMTP_USER","SMTP_PASS"]},tags:["email","smtp","imap","mail","notifications"],official:!1},{id:"puppeteer",name:"Puppeteer",description:"Browser automation, screenshots, web scraping",category:"browser",icon:"\u{1F310}",install:{transport:"stdio",package:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"]},tags:["browser","puppeteer","automation","screenshot","scraping"],official:!0},{id:"playwright",name:"Playwright",description:"Browser automation, testing, multi-browser support",category:"browser",icon:"\u{1F3AD}",install:{transport:"stdio",package:"@anthropic/mcp-server-playwright",command:"npx",args:["-y","@anthropic/mcp-server-playwright"]},tags:["browser","playwright","testing","automation","e2e"],official:!1},{id:"fetch",name:"Fetch",description:"Fetch web pages and convert to markdown",category:"browser",icon:"\u{1F517}",install:{transport:"stdio",package:"@modelcontextprotocol/server-fetch",command:"npx",args:["-y","@modelcontextprotocol/server-fetch"]},tags:["fetch","http","web","markdown","url"],official:!0},{id:"brave-search",name:"Brave Search",description:"Web search via Brave Search API",category:"browser",icon:"\u{1F981}",install:{transport:"stdio",package:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],envVars:["BRAVE_API_KEY"]},tags:["search","brave","web","query"],official:!0},{id:"tavily",name:"Tavily",description:"AI-optimized search, research, content extraction",category:"browser",icon:"\u{1F50D}",install:{transport:"stdio",package:"mcp-server-tavily",command:"npx",args:["-y","mcp-server-tavily"],envVars:["TAVILY_API_KEY"]},tags:["search","tavily","research","ai-search"],official:!1},{id:"aws",name:"AWS",description:"AWS services: S3, Lambda, DynamoDB, EC2, CloudWatch",category:"dev-tools",icon:"\u2601\uFE0F",install:{transport:"stdio",package:"mcp-server-aws",command:"npx",args:["-y","mcp-server-aws"],envVars:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"]},tags:["aws","amazon","s3","lambda","cloud","infrastructure"],official:!1},{id:"gcp",name:"Google Cloud",description:"GCP services: GCS, BigQuery, Cloud Run, Compute",category:"dev-tools",icon:"\u{1F324}\uFE0F",install:{transport:"stdio",package:"mcp-server-gcp",command:"npx",args:["-y","mcp-server-gcp"],envVars:["GOOGLE_APPLICATION_CREDENTIALS"]},tags:["gcp","google-cloud","bigquery","gcs","cloud"],official:!1},{id:"cloudflare",name:"Cloudflare",description:"Workers, KV, R2, D1, DNS management",category:"dev-tools",icon:"\u{1F525}",install:{transport:"stdio",package:"mcp-server-cloudflare",command:"npx",args:["-y","mcp-server-cloudflare"],envVars:["CLOUDFLARE_API_TOKEN"]},tags:["cloudflare","workers","cdn","dns","edge"],official:!1},{id:"vercel",name:"Vercel",description:"Deployments, projects, domains, environment variables",category:"dev-tools",icon:"\u25B2",install:{transport:"stdio",package:"mcp-server-vercel",command:"npx",args:["-y","mcp-server-vercel"],envVars:["VERCEL_TOKEN"]},tags:["vercel","deploy","serverless","hosting","nextjs"],official:!1},{id:"docker",name:"Docker",description:"Manage containers, images, volumes, networks",category:"dev-tools",icon:"\u{1F433}",install:{transport:"stdio",package:"mcp-server-docker",command:"npx",args:["-y","mcp-server-docker"]},tags:["docker","container","image","devops","deploy"],official:!1},{id:"kubernetes",name:"Kubernetes",description:"K8s cluster management, pods, deployments, services",category:"dev-tools",icon:"\u2388",install:{transport:"stdio",package:"mcp-server-kubernetes",command:"npx",args:["-y","mcp-server-kubernetes"]},tags:["kubernetes","k8s","pods","cluster","devops"],official:!1},{id:"sentry",name:"Sentry",description:"Error tracking, performance monitoring, issue management",category:"dev-tools",icon:"\u{1F6E1}\uFE0F",install:{transport:"stdio",package:"@sentry/mcp-server",command:"npx",args:["-y","@sentry/mcp-server"],envVars:["SENTRY_AUTH_TOKEN","SENTRY_ORG"]},tags:["sentry","errors","monitoring","debugging","performance"],official:!0},{id:"grafana",name:"Grafana",description:"Dashboards, metrics, alerting, log queries",category:"dev-tools",icon:"\u{1F4CA}",install:{transport:"stdio",package:"mcp-server-grafana",command:"npx",args:["-y","mcp-server-grafana"],envVars:["GRAFANA_URL","GRAFANA_API_KEY"]},tags:["grafana","metrics","dashboard","monitoring","observability"],official:!1},{id:"datadog",name:"Datadog",description:"Metrics, logs, traces, monitors, dashboards",category:"dev-tools",icon:"\u{1F415}",install:{transport:"stdio",package:"mcp-server-datadog",command:"npx",args:["-y","mcp-server-datadog"],envVars:["DD_API_KEY","DD_APP_KEY"]},tags:["datadog","monitoring","metrics","logs","apm","observability"],official:!1},{id:"stripe",name:"Stripe",description:"Payments, customers, subscriptions, invoices",category:"other",icon:"\u{1F4B3}",install:{transport:"stdio",package:"mcp-server-stripe",command:"npx",args:["-y","mcp-server-stripe"],envVars:["STRIPE_SECRET_KEY"]},tags:["stripe","payments","billing","subscriptions","invoices"],official:!1},{id:"figma",name:"Figma",description:"Figma designs, components, styles, variables",category:"other",icon:"\u{1F3A8}",install:{transport:"stdio",package:"mcp-server-figma",command:"npx",args:["-y","mcp-server-figma"],envVars:["FIGMA_ACCESS_TOKEN"]},tags:["figma","design","ui","components","prototype"],official:!1},{id:"google-drive",name:"Google Drive",description:"Google Drive files, Docs, Sheets, search",category:"other",icon:"\u{1F4C2}",install:{transport:"stdio",package:"@modelcontextprotocol/server-google-drive",command:"npx",args:["-y","@modelcontextprotocol/server-google-drive"]},tags:["google-drive","docs","sheets","files","storage"],official:!0}],bn=class{static{l(this,"MCPRegistry")}getAll(){return[...yn]}getByCategory(e){return yn.filter(t=>t.category===e)}search(e){let t=e.toLowerCase();return yn.filter(o=>o.name.toLowerCase().includes(t)||o.description.toLowerCase().includes(t)||o.tags.some(n=>n.includes(t)))}get(e){return yn.find(t=>t.id===e)}getCategories(){let e=new Map;for(let o of yn)e.set(o.category,(e.get(o.category)||0)+1);let t={"dev-tools":"Dev Tools & Cloud",database:"Databases","project-mgmt":"Project Management",communication:"Communication",browser:"Browser & Search",filesystem:"Filesystem",other:"Other"};return Array.from(e.entries()).map(([o,n])=>({category:o,count:n,label:t[o]||o}))}};async function Dm(s){let e=cn(s),t=jp(s);console.log(""),console.log(a.bold(" MCP Configuration:"));for(let o of t){let n=o.exists?a.green("\u2713"):a.dim("\u2717");console.log(` ${n} ${a.dim(`[${o.source}]`)} ${o.path}`)}if(console.log(""),e.length===0){console.log(a.dim(" No MCP servers configured.")),console.log(a.dim(" Add one with: mc mcp add <name> <command> [args...]")),console.log(a.dim(" Or browse: mc mcp browse")),console.log("");return}console.log(a.bold(" Configured Servers:")),console.log(a.dim(" "+"\u2500".repeat(60)));for(let o of e){let n=a.dim(`[${o.transport}]`),r="\u{1F50C}",i=a.hex("#6B8DD6")(o.name);if(o.transport==="sse")console.log(` ${r} ${i} ${n} \u2192 ${o.url}`);else{let c=[o.command,...o.args||[]].join(" ");console.log(` ${r} ${i} ${n} \u2192 ${c}`)}if(o.env&&Object.keys(o.env).length>0){let c=Object.keys(o.env).join(", ");console.log(` ${a.dim(`env: ${c}`)}`)}}console.log(""),console.log(a.dim(` ${e.length} server(s) configured. Use 'mc mcp test <name>' to verify.`)),console.log("")}l(Dm,"mcpListCommand");function vm(s,e,t,o){if(!t){let r=new bn,i=r.get(e);if(i){if(uc(s,i.id,i.install.command,i.install.args||[]),console.log(""),console.log(a.green(` \u2713 Added MCP server from registry: ${i.name}`)),console.log(a.dim(` Command: ${i.install.command} ${(i.install.args||[]).join(" ")}`)),console.log(a.dim(" Config: .monkeyscode/mcp.json")),i.install.envVars?.length){console.log(a.yellow(`
|
|
479
|
+
`);e.buffer=t.pop()||"";for(let o of t){let n=o.trim();if(n)try{let r=JSON.parse(n);this._handleResponse(e,r)}catch{}}}_handleResponse(e,t){if(t.id!==void 0){let o=e.pendingRequests.get(t.id);o&&(e.pendingRequests.delete(t.id),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result))}}};var Sn=[{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}],xn=class{static{l(this,"MCPRegistry")}getAll(){return[...Sn]}getByCategory(e){return Sn.filter(t=>t.category===e)}search(e){let t=e.toLowerCase();return Sn.filter(o=>o.name.toLowerCase().includes(t)||o.description.toLowerCase().includes(t)||o.tags.some(n=>n.includes(t)))}get(e){return Sn.find(t=>t.id===e)}getCategories(){let e=new Map;for(let o of Sn)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 jm(s){let e=fn(s),t=Zp(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(jm,"mcpListCommand");function Nm(s,e,t,o){if(!t){let r=new xn,i=r.get(e);if(i){if(kc(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(`
|
|
480
480
|
\u26A0 Required environment variables:`));for(let u of i.install.envVars)console.log(` ${a.cyan(u)}`)}console.log("");return}console.log(a.red(`
|
|
481
481
|
Usage: mc mcp add <name> <command> [args...]`)),console.log(a.dim(" Or use a registry ID: mc mcp add github"));let c=r.search(e);if(c.length>0){console.log(a.dim(`
|
|
482
|
-
Did you mean:`));for(let u of c.slice(0,5))console.log(` ${a.cyan(u.id)} \u2014 ${u.description}`)}console.log("");return}
|
|
482
|
+
Did you mean:`));for(let u of c.slice(0,5))console.log(` ${a.cyan(u.id)} \u2014 ${u.description}`)}console.log("");return}kc(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(Nm,"mcpAddCommand");function Lm(s,e){let t=Qp(s,e);console.log(""),console.log(t?a.green(` \u2713 Removed MCP server: ${e}`):a.red(` \u2717 Server not found: ${e}`)),console.log("")}l(Lm,"mcpRemoveCommand");async function Bm(s,e){let t=fn(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 ti;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(Bm,"mcpTestCommand");function Um(s){let e=new xn,t=s?e.search(s):e.getAll();if(t.length===0){console.log(a.dim(`
|
|
483
483
|
No servers matching "${s}"
|
|
484
484
|
`));return}if(s){console.log(a.bold(`
|
|
485
485
|
\u{1F50D} Search: "${s}" (${t.length} results)
|
|
486
486
|
`));for(let o of t){let n=o.official?a.green(" \u2713 official"):"";console.log(` ${o.icon} ${a.bold(o.name)}${n}`),console.log(` ${a.dim(o.description)}`),console.log(` ${a.dim("Install:")} ${a.cyan(`mc mcp add ${o.id}`)}`),o.install.envVars?.length&&console.log(` ${a.dim("Requires:")} ${o.install.envVars.join(", ")}`),console.log()}}else{let o=e.getCategories();console.log(a.bold(`
|
|
487
487
|
\u{1F50C} MCP Server Registry
|
|
488
488
|
`));for(let n of o){console.log(a.bold(` \u2500\u2500 ${n.label} (${n.count}) \u2500\u2500`));let r=e.getByCategory(n.category);for(let i of r){let c=i.official?a.green(" \u2713"):"",u=i.install.envVars?.length?a.dim(` (needs ${i.install.envVars[0]})`):"";console.log(` ${i.icon} ${a.bold(i.name)}${c}${u} \u2014 ${a.dim(i.description)}`)}console.log()}console.log(a.dim(` Add a server: ${a.cyan("mc mcp add <id>")}`)),console.log(a.dim(` Search: ${a.cyan("mc mcp browse <query>")}
|
|
489
|
-
`))}}l($m,"mcpBrowseCommand");X();var Ze=b(require("node:fs"),1),kn=b(require("node:path"),1);X();W();var wn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var Cm=["plan","fast","thinking"],_m=["dark","light","auto"],Em=["text","json","stream"],Fm={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>Cm.includes(s)?null:`must be one of: ${Cm.join(", ")}`,"defaultMode"),theme:l(s=>_m.includes(s)?null:`must be one of: ${_m.join(", ")}`,"theme"),outputFormat:l(s=>Em.includes(s)?null:`must be one of: ${Em.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Nc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:wn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(wn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=Fm[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Ze.mkdirSync(kn.dirname(r),{recursive:!0}),Ze.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Ze.existsSync(o)&&(n=JSON.parse(Ze.readFileSync(o,"utf8")))}catch{}delete n[e],Ze.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...wn};for(let t of Object.keys(wn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=A();return kn.join(e.config,"config.json")}getProjectConfigPath(){return kn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Ze.existsSync(e)){let o=JSON.parse(Ze.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=Fm[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(wn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Ze.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Tm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Tm,"printConfigList");var jc=null;function No(s){return(!jc||s)&&(jc=new Nc(s)),jc}l(No,"getConfigSystem");ur();W();_e();ee();var rw=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Rm(){let s=I(),e=H(s),t=s.ansi,o=ge();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Fe();if(d){let p=await fetch(`${rw}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Lc(n.tokensIn),u=Lc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Lc(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(Rm,"usageCommand");function Lc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Lc,"formatTokenCount");var mt=b(require("node:fs"),1),jm=b(require("node:path"),1),ws=require("node:child_process");W();var bs=b(require("node:fs"),1),Jr=b(require("node:path"),1);X();var iw="https://monkeyscode.com/api/latest-version",aw="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",cw=4*60*60*1e3;function Om(){let s=A();return Jr.join(s.config,"update-check")}l(Om,"getCachePath");function lw(){try{let s=bs.readFileSync(Om(),"utf8");return JSON.parse(s)}catch{return null}}l(lw,"readCache");function Bc(s){try{let e=Om();bs.mkdirSync(Jr.dirname(e),{recursive:!0}),bs.writeFileSync(e,JSON.stringify(s))}catch{}}l(Bc,"writeCache");function Am(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Am,"isNewerVersion");function uw(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(uw,"getAssetKey");async function Uc(s,e=!1){if(!e){let t=lw();if(t&&Date.now()-t.lastCheck<cw)return t.latestVersion&&Am(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await Pm(iw);if(t||(t=await Pm(aw)),!t)return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=uw(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Bc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Am(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Uc,"checkForUpdate");async function Pm(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(Pm,"fetchManifest");function Wc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Wc,"detectInstallMethod");async function Nm(s){let t=(await Promise.resolve().then(()=>(Im(),Mm)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.10";if(s.rollback){await Dw(t);return}if(s.check){await mw(t);return}await gw(t,s.version)}l(Nm,"updateCommand");async function mw(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Uc(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(mw,"checkOnly");async function gw(s,e){let t=Wc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await fw(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(gw,"performUpdate");async function fw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,ws.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(fw,"updateViaNpm");async function hw(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,ws.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(hw,"updateViaHomebrew");async function yw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,ws.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(yw,"updateViaWinget");async function bw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,ws.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(bw,"updateViaChocolatey");async function ww(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,ws.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(ww,"updateViaScoop");async function kw(s,e){let t=await Uc(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{mt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${jm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{mt.writeFileSync(n,c),mt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{mt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(kw,"updateViaBinaryDownload");async function Dw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Wc()==="binary"){let t=process.execPath+".backup";if(!mt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{mt.copyFileSync(t,process.execPath),mt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(Dw,"rollback");W();var ks=b(require("node:fs"),1),Yr=b(require("node:path"),1),Um=b(require("node:crypto"),1);X();var zt=!0,Hc="",et=[],Lm=!1,vw="https://monkeyscode.com/api/telemetry",Kr=50,Sw=6e4;function Wm(){let s=A();return Yr.join(s.config,"telemetry.json")}l(Wm,"getConfigPath");function Gc(){try{let s=ks.readFileSync(Wm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:xw()};return qc(s),s}}l(Gc,"loadConfig");function qc(s){try{let e=Wm();ks.mkdirSync(Yr.dirname(e),{recursive:!0}),ks.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(qc,"saveConfig");function xw(){return Um.randomUUID()}l(xw,"generateClientId");function Hm(){if(Lm)return;if(Lm=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){zt=!1;return}let s=Gc();zt=s.enabled,Hc=s.clientId,zt&&(setInterval(()=>Bm(),Sw).unref(),process.on("beforeExit",()=>Bm()))}l(Hm,"initTelemetry");function Gm(){return zt}l(Gm,"isTelemetryEnabled");function qm(){zt=!0;let s=Gc();s.enabled=!0,qc(s)}l(qm,"enableTelemetry");function Vm(){zt=!1,et=[];let s=Gc();s.enabled=!1,qc(s)}l(Vm,"disableTelemetry");function zm(s,e={}){zt&&(et.push({name:s,properties:e,timestamp:new Date().toISOString()}),et.length>Kr&&(et=et.slice(-Kr)))}l(zm,"trackEvent");async function Bm(){if(!zt||et.length===0)return;let s=[...et];et=[];let e=Ce(),o={clientId:Hc,cliVersion:"0.1.10",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(vw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{et.unshift(...s),et.length>Kr&&(et=et.slice(-Kr))}}l(Bm,"flushEvents");function Jm(){let s=Ce();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.10",` \u2022 OS: ${s.os} (${s.arch})`,` \u2022 Shell: ${s.shell}`,` \u2022 Node.js version: ${process.version}`," \u2022 Command used (interactive, headless, background)"," \u2022 Model selected"," \u2022 Duration and token count"," \u2022 Error types (not error content)"," \u2022 Tool usage frequency","","\u274C Never collected:"," \u2022 Prompts or conversation content"," \u2022 Source code or file contents"," \u2022 File paths or project names"," \u2022 Authentication tokens or API keys"," \u2022 Personal information","",`Status: ${zt?"ENABLED":"DISABLED"}`,`Client ID: ${Hc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
490
|
-
`)}l(
|
|
491
|
-
`)[0];t.push({name:"ripgrep",ok:!0,msg:r.replace("ripgrep ","")})}catch{t.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let n of t){let r=n.ok?a.green(" \u2705"):a.yellow(" \u26A0\uFE0F ");console.log(`${r} ${n.name}: ${a.dim(n.msg)}`)}console.log(""),console.log(a.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${a.cyan("mc auth login")}`),console.log(""),console.log(a.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${a.dim("Interactive:")} ${a.cyan("mc")} Open the REPL`),console.log(` ${a.dim("One-shot:")} ${a.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${a.dim("Background:")} ${a.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${a.dim("Health:")} ${a.cyan("mc doctor")} Check your setup`),console.log(` ${a.dim("Help:")} ${a.cyan("mc --help")} See all commands`),console.log(""),console.log(a.dim(" \u2500".repeat(30))),console.log(a.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),
|
|
489
|
+
`))}}l(Um,"mcpBrowseCommand");Z();var tt=w(require("node:fs"),1),$n=w(require("node:path"),1);Z();H();var _n={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 Wm=["plan","fast","thinking"],Hm=["dark","light","auto"],Gm=["text","json","stream"],qm={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=>Wm.includes(s)?null:`must be one of: ${Wm.join(", ")}`,"defaultMode"),theme:l(s=>Hm.includes(s)?null:`must be one of: ${Hm.join(", ")}`,"theme"),outputFormat:l(s=>Gm.includes(s)?null:`must be one of: ${Gm.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")},zc=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:_n[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(_n))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=qm[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,tt.mkdirSync($n.dirname(r),{recursive:!0}),tt.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{tt.existsSync(o)&&(n=JSON.parse(tt.readFileSync(o,"utf8")))}catch{}delete n[e],tt.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={..._n};for(let t of Object.keys(_n))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=A();return $n.join(e.config,"config.json")}getProjectConfigPath(){return $n.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(tt.existsSync(e)){let o=JSON.parse(tt.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=qm[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(_n));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{tt.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 Vm(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(Vm,"printConfigList");var Jc=null;function Ho(s){return(!Jc||s)&&(Jc=new zc(s)),Jc}l(Ho,"getConfigSystem");wr();H();Ce();ee();var Nb=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Jm(){let s=j(),e=G(s),t=s.ansi,o=fe();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Fe();if(d){let p=await fetch(`${Nb}/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=Kc(n.tokensIn),u=Kc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Kc(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(Jm,"usageCommand");function Kc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Kc,"formatTokenCount");var ht=w(require("node:fs"),1),Zm=w(require("node:path"),1),xs=require("node:child_process");H();var Ss=w(require("node:fs"),1),oi=w(require("node:path"),1);Z();var Lb="https://monkeyscode.com/api/latest-version",Bb="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",Ub=4*60*60*1e3;function Ym(){let s=A();return oi.join(s.config,"update-check")}l(Ym,"getCachePath");function Wb(){try{let s=Ss.readFileSync(Ym(),"utf8");return JSON.parse(s)}catch{return null}}l(Wb,"readCache");function Yc(s){try{let e=Ym();Ss.mkdirSync(oi.dirname(e),{recursive:!0}),Ss.writeFileSync(e,JSON.stringify(s))}catch{}}l(Yc,"writeCache");function zm(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(zm,"isNewerVersion");function Hb(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(Hb,"getAssetKey");async function Xc(s,e=!1){if(!e){let t=Wb();if(t&&Date.now()-t.lastCheck<Ub)return t.latestVersion&&zm(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await Km(Lb);if(t||(t=await Km(Bb)),!t)return Yc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=Hb(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Yc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&zm(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 Yc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Xc,"checkForUpdate");async function Km(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(Km,"fetchManifest");function Qc(){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(Qc,"detectInstallMethod");async function ef(s){let t=(await Promise.resolve().then(()=>(Qm(),Xm)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.11";if(s.rollback){await ek(t);return}if(s.check){await Vb(t);return}await Jb(t,s.version)}l(ef,"updateCommand");async function Vb(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Xc(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(Vb,"checkOnly");async function Jb(s,e){let t=Qc();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 zb(e);break;case"homebrew":await Kb();break;case"winget":await Yb();break;case"chocolatey":await Xb();break;case"scoop":await Qb();break;case"binary":await Zb(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(Jb,"performUpdate");async function zb(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,xs.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(zb,"updateViaNpm");async function Kb(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,xs.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(Kb,"updateViaHomebrew");async function Yb(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,xs.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(Yb,"updateViaWinget");async function Xb(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,xs.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(Xb,"updateViaChocolatey");async function Qb(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,xs.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(Qb,"updateViaScoop");async function Zb(s,e){let t=await Xc(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{ht.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${Zm.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{ht.writeFileSync(n,c),ht.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{ht.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(Zb,"updateViaBinaryDownload");async function ek(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Qc()==="binary"){let t=process.execPath+".backup";if(!ht.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{ht.copyFileSync(t,process.execPath),ht.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(ek,"rollback");H();var _s=w(require("node:fs"),1),ni=w(require("node:path"),1),sf=w(require("node:crypto"),1);Z();var Xt=!0,Zc="",ot=[],tf=!1,tk="https://monkeyscode.com/api/telemetry",si=50,ok=6e4;function nf(){let s=A();return ni.join(s.config,"telemetry.json")}l(nf,"getConfigPath");function el(){try{let s=_s.readFileSync(nf(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:sk()};return tl(s),s}}l(el,"loadConfig");function tl(s){try{let e=nf();_s.mkdirSync(ni.dirname(e),{recursive:!0}),_s.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(tl,"saveConfig");function sk(){return sf.randomUUID()}l(sk,"generateClientId");function rf(){if(tf)return;if(tf=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Xt=!1;return}let s=el();Xt=s.enabled,Zc=s.clientId,Xt&&(setInterval(()=>of(),ok).unref(),process.on("beforeExit",()=>of()))}l(rf,"initTelemetry");function af(){return Xt}l(af,"isTelemetryEnabled");function cf(){Xt=!0;let s=el();s.enabled=!0,tl(s)}l(cf,"enableTelemetry");function lf(){Xt=!1,ot=[];let s=el();s.enabled=!1,tl(s)}l(lf,"disableTelemetry");function uf(s,e={}){Xt&&(ot.push({name:s,properties:e,timestamp:new Date().toISOString()}),ot.length>si&&(ot=ot.slice(-si)))}l(uf,"trackEvent");async function of(){if(!Xt||ot.length===0)return;let s=[...ot];ot=[];let e=$e(),o={clientId:Zc,cliVersion:"0.1.11",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(tk,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{ot.unshift(...s),ot.length>si&&(ot=ot.slice(-si))}}l(of,"flushEvents");function df(){let s=$e();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.11",` \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: ${Xt?"ENABLED":"DISABLED"}`,`Client ID: ${Zc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
490
|
+
`)}l(df,"getCollectedDataSummary");async function pf(s){switch(s){case"enable":cf(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":lf(),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(df()),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)")):af()?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(pf,"telemetryCommand");var _t=w(require("node:fs"),1),Cn=w(require("node:path"),1);H();Z();async function mf(s,e){let t=$e(),o="0.1.11";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=ik();i?(n.crashLog=i,console.log(a.dim(" \u{1F4CE} Attached latest crash report"))):console.log(a.dim(" No crash reports found"))}if(await nk(n))console.log(a.green(" \u2705 Bug report submitted")),console.log(a.dim(" Thank you! Our team will review your report."));else{let i=rk(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(mf,"bugCommand");async function nk(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(nk,"submitReport");function rk(s){let e=A(),t=Cn.join(e.config,"bug-reports");_t.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Cn.join(t,`${o}.json`);return _t.writeFileSync(n,JSON.stringify(s,null,2)),n}l(rk,"saveReportLocally");function ik(){try{let s=A(),e=Cn.join(s.config,"crashes");if(!_t.existsSync(e))return null;let t=_t.readdirSync(e).filter(o=>o.endsWith(".log")).sort().reverse();return t.length===0?null:_t.readFileSync(Cn.join(e,t[0]),"utf8")}catch{return null}}l(ik,"getLatestCrashLog");var Go=w(require("node:fs"),1),ol=w(require("node:path"),1);H();Z();Ce();function ff(){let s=A(),e=ol.join(s.config,"config.json");return!Go.existsSync(e)}l(ff,"isFirstRun");function ak(){let e=A().config,t=ol.join(e,"config.json");Go.mkdirSync(e,{recursive:!0}),Go.existsSync(t)||Go.writeFileSync(t,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}l(ak,"markOnboardingComplete");async function hf(){let s=j(),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(`
|
|
491
|
+
`)[0];t.push({name:"ripgrep",ok:!0,msg:r.replace("ripgrep ","")})}catch{t.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let n of t){let r=n.ok?a.green(" \u2705"):a.yellow(" \u26A0\uFE0F ");console.log(`${r} ${n.name}: ${a.dim(n.msg)}`)}console.log(""),console.log(a.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${a.cyan("mc auth login")}`),console.log(""),console.log(a.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${a.dim("Interactive:")} ${a.cyan("mc")} Open the REPL`),console.log(` ${a.dim("One-shot:")} ${a.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${a.dim("Background:")} ${a.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${a.dim("Health:")} ${a.cyan("mc doctor")} Check your setup`),console.log(` ${a.dim("Help:")} ${a.cyan("mc --help")} See all commands`),console.log(""),console.log(a.dim(" \u2500".repeat(30))),console.log(a.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),ak()}l(hf,"runOnboarding");var ko=w(require("node:fs"),1),ri=w(require("node:path"),1);Z();var gf=[];function wf(){process.on("uncaughtException",s=>{yf(s,"uncaughtException"),console.error(`
|
|
492
492
|
\u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${s.message}
|
|
493
|
-
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));
|
|
493
|
+
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));yf(e,"unhandledRejection")})}l(wf,"installCrashHandler");function ck(){let s=A();return ri.join(s.config,"crashes")}l(ck,"getCrashDir");function yf(s,e){try{let t=ck();ko.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=ri.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.11",`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",gf.length>0?gf.map((u,d)=>` ${d+1}. ${u}`).join(`
|
|
494
494
|
`):" (none)","","\u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`TERM: ${process.env.TERM||"(not set)"}`,`CI: ${process.env.CI||"false"}`,`MONKEYSCODE_HEADLESS: ${process.env.MONKEYSCODE_HEADLESS||"false"}`,"","\u2550".repeat(60)," Submit this report: mc bug --attach-crash","\u2550".repeat(60),""].join(`
|
|
495
|
-
`);
|
|
495
|
+
`);ko.writeFileSync(n,c),lk(t,20)}catch{}}l(yf,"writeCrashReport");function lk(s,e){try{let t=ko.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)ko.unlinkSync(ri.join(s,t[o]))}catch{}}l(lk,"pruneOldReports");var Ie=w(require("node:fs"),1),Zt=w(require("node:path"),1),uk=require("node:child_process");H();Z();Ce();var dk="MEMORY.md",bf=".monkeyscode";async function kf(s={}){let e=G(j()),t=A(),o=s.since||"7d";if(s.mode&&s.mode!=="consolidate"){await fk(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=Zt.join(t.data,"sessions");if(!Ie.existsSync(n)){console.log(` ${e.info} No sessions found. Use ${a.cyan("mc")} to create some first.`);return}let r=pk(o),i=Ie.readdirSync(n).filter(g=>g.endsWith(".json")).map(g=>({name:g,path:Zt.join(n,g),mtime:Ie.statSync(Zt.join(n,g)).mtimeMs})).filter(g=>g.mtime>=r).sort((g,y)=>y.mtime-g.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 g of i)try{let y=JSON.parse(Ie.readFileSync(g.path,"utf8"));if(y.toolCalls){for(let x of y.toolCalls)if(x.tool==="file_edit"&&x.args?.path){let v=Zt.extname(x.args.path);if(v){let _=`Works primarily with ${v} files`;c.set(_,(c.get(_)||0)+1)}}}if(y.messages){let x=JSON.stringify(y.messages).toLowerCase();x.includes("vitest")&&Qt(c,"Uses vitest for testing"),x.includes("jest")&&Qt(c,"Uses jest for testing"),x.includes("mocha")&&Qt(c,"Uses mocha for testing"),x.includes("zod")&&Qt(c,"Uses Zod for runtime validation"),x.includes("joi")&&Qt(c,"Uses Joi for validation"),x.includes("tailwind")&&Qt(c,"Uses Tailwind CSS"),x.includes("styled-components")&&Qt(c,"Uses styled-components"),x.includes("result<")&&Qt(c,"Uses Result<T, E> pattern for error handling"),(x.includes("try/catch")||x.includes("try {"))&&Qt(c,"Uses try/catch for error handling")}}catch{}let u=Math.max(2,Math.floor(i.length*.3)),d=[];for(let[g,y]of c)y>=u&&d.push({rule:g,count:y});if(d.sort((g,y)=>y.count-g.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 g of d)console.log(` ${e.success} "${g.rule}" (seen in ${g.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=Zt.join(process.cwd(),bf,dk);Ie.mkdirSync(Zt.join(process.cwd(),bf),{recursive:!0});let f="";Ie.existsSync(p)&&(f=Ie.readFileSync(p,"utf8"));let m=new Date().toISOString().split("T")[0],h=f.trimEnd();h||(h=`# Project Memory
|
|
496
496
|
|
|
497
497
|
> Auto-generated by \`mc dream\`. Edit freely.
|
|
498
|
-
`),
|
|
498
|
+
`),h+=`
|
|
499
499
|
|
|
500
500
|
## Consolidated ${m} (${i.length} sessions)
|
|
501
501
|
|
|
502
|
-
`;for(let
|
|
503
|
-
`)}
|
|
504
|
-
`),console.log(` Updated: ${a.cyan(p)}`),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(
|
|
502
|
+
`;for(let g of d){let y=`- ${g.rule}`;f.includes(g.rule)||(h+=y+`
|
|
503
|
+
`)}Ie.writeFileSync(p,h.trimEnd()+`
|
|
504
|
+
`),console.log(` Updated: ${a.cyan(p)}`),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(kf,"dream");function pk(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(pk,"parseDuration");function Qt(s,e){s.set(e,(s.get(e)||0)+1)}l(Qt,"incr");var mk={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(`
|
|
505
505
|
`)},refactor:{icon:"\u{1F527}",title:"Refactoring Opportunities",prompt:["Analyze the codebase for refactoring opportunities:","","1. Find duplicated code (similar functions, copy-paste patterns)","2. Identify overly complex functions (high cyclomatic complexity)","3. Find god classes/modules that should be split","4. Detect dead code (unused exports, unreachable branches)","5. Identify missing abstractions (repeated patterns that could be generalized)","6. Find inconsistent naming conventions or code style","7. Suggest architectural improvements","","For each opportunity, provide: file, line range, description, suggested fix, and effort estimate.","Write the report to .monkeyscode/dreams/refactor-report.md"].join(`
|
|
506
506
|
`)},docs:{icon:"\u{1F4DD}",title:"Documentation Generation",prompt:["Analyze the codebase and generate or update documentation:","","1. Identify public APIs, exported functions, and classes that lack documentation","2. Generate JSDoc/docstrings for undocumented public interfaces","3. Update the project README if it's outdated or missing sections","4. Create a CONTRIBUTING.md if one doesn't exist","5. Generate an API reference summary","6. Document environment variables, configuration options, and CLI flags","","Write a summary of what you documented to .monkeyscode/dreams/docs-report.md","Actually update the source files with the documentation."].join(`
|
|
507
507
|
`)},"test-gaps":{icon:"\u{1F9EA}",title:"Test Coverage Gaps",prompt:["Analyze the codebase for untested code paths and missing test coverage:","","1. Find source files without corresponding test files","2. Identify exported functions/methods that are never tested","3. Find branches, edge cases, and error paths without test coverage","4. Check for missing integration tests (API endpoints, workflows)","5. Identify fragile tests (timing-dependent, order-dependent)","6. Suggest specific test cases that should be written","","For each gap, provide: source file, function, what to test, and priority (P0-P3).","Write the report to .monkeyscode/dreams/test-gaps-report.md"].join(`
|
|
508
|
-
`)}};async function
|
|
509
|
-
`);if(t.length<=50)return[{content:s,startLine:1,endLine:t.length,type:"module"}];switch(e){case"typescript":case"javascript":case"go":case"rust":case"java":case"c":case"cpp":case"csharp":return
|
|
508
|
+
`)}};async function fk(s){let e=mk[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=Zt.join(process.cwd(),".monkeyscode","dreams");Ie.mkdirSync(t,{recursive:!0});let{AgentLoop:o}=await Promise.resolve().then(()=>(Xe(),rs)),{loadSettings:n}=await Promise.resolve().then(()=>(Q(),we)),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),he)),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(fk,"dreamExtended");H();var Te=w(require("node:fs"),1),gt=w(require("node:path"),1),ai=w(require("node:crypto"),1),sl=require("node:child_process");Z();function vf(s,e){let t=s.split(`
|
|
509
|
+
`);if(t.length<=50)return[{content:s,startLine:1,endLine:t.length,type:"module"}];switch(e){case"typescript":case"javascript":case"go":case"rust":case"java":case"c":case"cpp":case"csharp":return hk(t);case"python":return gk(t);default:return yk(t,50)}}l(vf,"chunkCode");function hk(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(`
|
|
510
510
|
`),startLine:o+1,endLine:r+1,type:n}),o=r+1,n="module")}r-o>=50&&t<=1&&(e.push({content:s.slice(o,r+1).join(`
|
|
511
511
|
`),startLine:o+1,endLine:r+1,type:n}),o=r+1,n="module")}if(o<s.length){let r=s.slice(o);r.some(i=>i.trim())&&e.push({content:r.join(`
|
|
512
|
-
`),startLine:o+1,endLine:s.length,type:"module"})}return e}l(
|
|
512
|
+
`),startLine:o+1,endLine:s.length,type:"module"})}return e}l(hk,"chunkByBraces");function gk(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(`
|
|
513
513
|
`),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(`
|
|
514
514
|
`),startLine:t+1,endLine:n,type:o}),t=n),o="class"),n-t>=50&&(e.push({content:s.slice(t,n+1).join(`
|
|
515
515
|
`),startLine:t+1,endLine:n+1,type:o}),t=n+1,o="module")}return t<s.length&&e.push({content:s.slice(t).join(`
|
|
516
|
-
`),startLine:t+1,endLine:s.length,type:o}),e}l(
|
|
517
|
-
`),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(
|
|
518
|
-
`).filter(o=>o&&t.has(gt.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,
|
|
519
|
-
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,
|
|
520
|
-
`).filter(Boolean)}catch{return this.listAllFiles()}}};var
|
|
521
|
-
`).filter(Boolean)}catch{return[]}}l(
|
|
522
|
-
`).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(
|
|
516
|
+
`),startLine:t+1,endLine:s.length,type:o}),e}l(gk,"chunkByIndentation");function yk(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(`
|
|
517
|
+
`),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(yk,"chunkByLines");var ii=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=ai.createHash("sha256").update(e).digest("hex").slice(0,12),n=A();this.indexDir=gt.join(n.data,"indexes",o)}async index(){Te.mkdirSync(this.indexDir,{recursive:!0}),this.loadState();let e=this.listIndexableFiles(),t=e.filter(d=>this.getFileSha(d)!==this.fileShas.get(d));if(t.length===0)return this.getStats(e.length);let o=[];for(let d of t){let p=gt.join(this.workspace,d);if(!Te.existsSync(p))continue;let f=Te.readFileSync(p,"utf8"),m=this.detectLanguage(d),h=vf(f,m);for(let g of h)o.push({id:ai.randomUUID(),file:d,startLine:g.startLine,endLine:g.endLine,content:g.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,sl.execSync)("git ls-files --cached --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}),t=new Set([".ts",".tsx",".js",".jsx",".py",".go",".rs",".java",".c",".cpp",".h",".hpp",".rb",".php",".swift",".kt",".scala",".cs",".vue",".svelte",".md",".mdx"]);return e.trim().split(`
|
|
518
|
+
`).filter(o=>o&&t.has(gt.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,sl.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"}[gt.extname(e)]||"unknown"}saveState(){let e=gt.join(this.indexDir,"meta.json"),t=gt.join(this.indexDir,"vectors.bin");Te.writeFileSync(e,JSON.stringify({chunks:this.chunks,fileShas:Object.fromEntries(this.fileShas),embeddingDim:this.embeddingDim,lastIndexed:Date.now()})),this.embeddings&&Te.writeFileSync(t,Buffer.from(this.embeddings.buffer))}loadState(){let e=gt.join(this.indexDir,"meta.json"),t=gt.join(this.indexDir,"vectors.bin");if(Te.existsSync(e))try{let o=JSON.parse(Te.readFileSync(e,"utf8"));if(this.chunks=o.chunks||[],this.fileShas=new Map(Object.entries(o.fileShas||{})),this.embeddingDim=o.embeddingDim||1536,Te.existsSync(t)){let n=Te.readFileSync(t);this.embeddings=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4)}}catch{this.chunks=[],this.embeddings=null,this.fileShas.clear()}}getStats(e){let t=gt.join(this.indexDir,"vectors.bin"),o=Te.existsSync(t)?Te.statSync(t).size:0,n=e-this.fileShas.size;return{totalFiles:this.fileShas.size,totalChunks:this.chunks.length,indexSizeBytes:o,lastIndexed:Date.now(),pendingFiles:Math.max(0,n)}}};var $t=w(require("node:fs"),1),Le=w(require("node:path"),1),nl=require("node:child_process");var En=class{static{l(this,"ImportGraph")}forward=new Map;reverse=new Map;fileShas=new Map;workspace;lastUpdated=0;constructor(e){this.workspace=e}async build(){let e=this.lastUpdated===0?this.listAllFiles():this.getChangedFiles();for(let t of e)this.parseFile(t);return this.lastUpdated=Date.now(),this.getStats()}dependentsOf(e){return[...this.reverse.get(e)||[]]}dependenciesOf(e){return[...this.forward.get(e)||[]]}transitiveImports(e,t=5){let o=new Set,n=[{file:e,depth:0}];for(;n.length>0;){let{file:r,depth:i}=n.shift();if(!(o.has(r)||i>t)){o.add(r);for(let c of this.dependenciesOf(r))o.has(c)||n.push({file:c,depth:i+1})}}return o.delete(e),[...o]}relatedFiles(e,t=20){let o=new Map;for(let n of e){for(let r of this.dependenciesOf(n))o.set(r,(o.get(r)||0)+3);for(let r of this.dependentsOf(n))o.set(r,(o.get(r)||0)+2);for(let r of this.dependenciesOf(n))for(let i of this.dependenciesOf(r))e.includes(i)||o.set(i,(o.get(i)||0)+1)}for(let n of e)o.delete(n);return[...o.entries()].sort((n,r)=>r[1]-n[1]).slice(0,t).map(([n])=>n)}getStats(){let e=new Map;for(let c of this.reverse.values())for(let u of c)e.set(u,(e.get(u)||0)+1);let t=new Map;for(let[c,u]of this.reverse)t.set(c,u.size);let o=[...t.entries()].sort((c,u)=>u[1]-c[1]).slice(0,10).map(([c,u])=>({file:c,count:u})),n=new Set([...this.forward.keys(),...this.reverse.keys()]),r=[...this.forward.keys()].filter(c=>(this.forward.get(c)?.size||0)===0&&(this.reverse.get(c)?.size||0)===0).length,i=0;for(let c of this.forward.values())i+=c.size;return{totalFiles:n.size,totalEdges:i,orphanFiles:r,mostImported:o,lastUpdated:this.lastUpdated}}parseFile(e){let t=Le.join(this.workspace,e);if(!$t.existsSync(t)){this.forward.delete(e);return}let o=$t.readFileSync(t,"utf8"),n=Le.extname(e),r=[];[".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(n)?r=this.parseTsImports(e,o):n===".py"?r=this.parsePyImports(e,o):n===".go"&&(r=this.parseGoImports(e,o));let i=this.forward.get(e);if(i)for(let u of i)this.reverse.get(u)?.delete(e);let c=new Set(r);this.forward.set(e,c);for(let u of c)this.reverse.has(u)||this.reverse.set(u,new Set),this.reverse.get(u).add(e)}parseTsImports(e,t){let o=[],n=Le.dirname(e),r=/(?:import|export)\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"]/g,i;for(;(i=r.exec(t))!==null;){let d=this.resolveTs(n,i[1]);d&&o.push(d)}let c=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(i=c.exec(t))!==null;){let d=this.resolveTs(n,i[1]);d&&o.push(d)}let u=/require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(;(i=u.exec(t))!==null;){let d=this.resolveTs(n,i[1]);d&&o.push(d)}return o}parsePyImports(e,t){let o=[],n=/^(?:from\s+(\S+)|import\s+(\S+))/gm,r;for(;(r=n.exec(t))!==null;){let i=(r[1]||r[2]).replace(/\./g,"/"),c=[`${i}.py`,`${i}/__init__.py`];for(let u of c)if($t.existsSync(Le.join(this.workspace,u))){o.push(u);break}}return o}parseGoImports(e,t){let o=[],n=Le.dirname(e),r=this.getGoModulePath(),i=/^import\s+"([^"]+)"/gm,c;for(;(c=i.exec(t))!==null;){let d=this.resolveGoImport(c[1],r);d&&o.push(d)}let u=/^import\s*\(([\s\S]*?)\)/gm;for(;(c=u.exec(t))!==null;){let d=c[1],p=/"([^"]+)"/g,f;for(;(f=p.exec(d))!==null;){let m=this.resolveGoImport(f[1],r);m&&o.push(m)}}return o}goModulePath=void 0;getGoModulePath(){if(this.goModulePath!==void 0)return this.goModulePath;try{let e=Le.join(this.workspace,"go.mod");if($t.existsSync(e)){let o=$t.readFileSync(e,"utf8").match(/^module\s+(\S+)/m);this.goModulePath=o?o[1]:null}else this.goModulePath=null}catch{this.goModulePath=null}return this.goModulePath}resolveGoImport(e,t){if(!e.includes(".")&&!e.includes("/"))return null;if(t&&e.startsWith(t)){let o=e.slice(t.length+1),n=Le.join(this.workspace,o);if($t.existsSync(n))return o}return null}resolveTs(e,t){if(!t.startsWith("."))return null;let o=Le.join(e,t),n=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let r of n){let i=o+r;if($t.existsSync(Le.join(this.workspace,i)))return i}if(t.endsWith(".js")){let r=Le.join(e,t.replace(/\.js$/,".ts"));if($t.existsSync(Le.join(this.workspace,r)))return r}return null}listAllFiles(){try{return(0,nl.execSync)("git ls-files --cached --others --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
519
|
+
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,nl.execSync)("git diff --name-only HEAD~5",{cwd:this.workspace,encoding:"utf8"}).trim().split(`
|
|
520
|
+
`).filter(Boolean)}catch{return this.listAllFiles()}}};var $s=w(require("node:fs"),1),pe=w(require("node:path"),1),rl=require("node:child_process");var Fn={KEYWORD_MATCH:.3,GIT_RECENCY:.25,IMPORT_GRAPH:.2,TEST_PAIR:.15,CONFIG_PROXIMITY:.1},wk=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 Df(s,e){let t=new Map,o=bk(s),n=e.maxResults||30,r=vk(e.workspace);for(let i of r){let c=kk(i,o);c>0&&Tn(t,i,c*Fn.KEYWORD_MATCH,`Matches: ${o.filter(u=>i.toLowerCase().includes(u)).join(", ")}`)}if(e.useGitRecency!==!1){let i=Dk(e.workspace,50);for(let c=0;c<i.length;c++){let u=1-c/i.length;Tn(t,i[c],u*Fn.GIT_RECENCY,`Git recency: #${c+1}`)}}if(e.activeFiles&&e.activeFiles.length>0)for(let i of e.activeFiles){let c=Sk(e.workspace,i);for(let u of c)Tn(t,u,Fn.IMPORT_GRAPH,`Imported by ${pe.basename(i)}`)}for(let i of r){let c=_k(i);c&&t.has(i)&&Tn(t,c,Fn.TEST_PAIR,`Test pair of ${pe.basename(i)}`)}for(let i of r)if(wk.has(pe.basename(i))){let c=pe.dirname(i);[...t.keys()].some(d=>pe.dirname(d)===c)&&Tn(t,i,Fn.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(Df,"rankFiles");function Tn(s,e,t,o){let n=s.get(e)||{score:0,reasons:[]};n.score+=t,n.reasons.push(o),s.set(e,n)}l(Tn,"addScore");function bk(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(bk,"extractKeywords");function kk(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(kk,"keywordScore");function vk(s){try{return(0,rl.execSync)("git ls-files --cached --others --exclude-standard",{cwd:s,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
521
|
+
`).filter(Boolean)}catch{return[]}}l(vk,"listWorkspaceFiles");function Dk(s,e){try{let t=(0,rl.execSync)(`git log --name-only --format="" -n ${e*2} | head -n ${e}`,{cwd:s,encoding:"utf8",maxBuffer:1e6}),o=new Set;return t.trim().split(`
|
|
522
|
+
`).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(Dk,"getGitRecentFiles");function Sk(s,e){try{let t=$s.readFileSync(pe.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=pe.dirname(e),d=xk(s,pe.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($s.existsSync(pe.join(s,d))){o.push(d);break}}return o}catch{return[]}}l(Sk,"parseImportsQuick");function xk(s,e){let t=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let o of t){let n=e+o;if($s.existsSync(pe.join(s,n)))return n}return $s.existsSync(pe.join(s,e))?e:null}l(xk,"resolveImport");function _k(s){let e=pe.extname(s),t=pe.basename(s,e),o=pe.dirname(s);if(t.endsWith(".test")||t.endsWith(".spec")){let r=t.replace(/\.(test|spec)$/,"");return pe.join(o,r+e)}return[pe.join(o,`${t}.test${e}`),pe.join(o,`${t}.spec${e}`),pe.join(o,"__tests__",`${t}${e}`)].find(()=>!0)||null}l(_k,"findTestPair");Q();Ce();async function qo(s,e){let t=s[0]||"status",o=process.cwd(),n=Y(),r=G(j());switch(t){case"index":await $k(o,n);break;case"search":await Ck(o,n,s.slice(1).join(" "));break;case"status":await Ek(o,n);break;case"rebuild":await Fk(o,n);break;case"related":await Tk(o,s[1]);break;case"rank":Rk(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(qo,"contextCommand");async function $k(s,e){console.log(a.cyan(" \u26A1 Indexing workspace...")),console.log(a.dim(` ${s}`)),console.log("");let t=Date.now(),n=await ci(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(Sf(n.indexSizeBytes))}`),console.log(` Time: ${a.bold(r+"s")}`),console.log("")}l($k,"contextIndex");async function Ck(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 ci(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(`
|
|
523
523
|
`).slice(0,2).map(d=>` ${a.dim(d.substring(0,80))}`).join(`
|
|
524
|
-
`);console.log(u),console.log("")}}l(
|
|
525
|
-
`)}l(
|
|
526
|
-
Shutting down trigger daemon...`)),u.stop(),
|
|
527
|
-
`)[0].slice(0,80);console.log(` ${a.blue("\u{1F4AD}")} ${a.blue("Thinking")}${t}`),n&&console.log(` ${a.dim(n)}`);break}case"tool_call":{let n=
|
|
528
|
-
`)[0].slice(0,70);console.log(`${o}${a.dim("\u2502 "+i)}`)}e=Math.min(e+1,4);break;case"tool_call":console.log(`${o}${a.green("\u251C\u2500 \u{1F527} "+(t.tool||"tool"))}${r}`),t.resultPreview&&console.log(`${o}${a.dim("\u2502 \u2192 "+t.resultPreview.slice(0,60))}`);break;case"context_compact":e=Math.max(0,e-1),console.log(`${o}${a.yellow("\u251C\u2500 \u{1F4E6} Compact")}${n}`);break;case"error":console.log(`${o}${a.red("\u2514\u2500 \u274C Error")}: ${t.content}`);break}}console.log()}l(
|
|
524
|
+
`);console.log(u),console.log("")}}l(Ck,"contextSearch");async function Ek(s,e){let o=ci(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(Sf(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 En(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(Ek,"contextStatus");async function Fk(s,e){console.log(a.yellow(" \u{1F504} Rebuilding index from scratch...")),console.log("");let t=Date.now(),n=await ci(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(Fk,"contextRebuild");async function Tk(s,e){if(!e){console.log(a.red(" Usage: mc context related <file>"));return}let t=new En(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(Tk,"contextRelated");function Rk(s,e){if(!e){console.log(a.red(' Usage: mc context rank "your prompt"'));return}let t=Df(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(Rk,"contextRank");function ci(s,e){return new ii(s,{platformUrl:e.platformUrl,token:process.env.MC_API_KEY||"",embeddingModel:"text-embedding-3-small"})}l(ci,"createIndex");function Sf(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(Sf,"formatBytes");var vo=w(require("node:fs"),1),Pn=w(require("node:path"),1);H();Ce();Q();var Pf=".monkeyscode/triggers.json";async function Do(s,e){let t=s[0]||"list",o=process.cwd();switch(t){case"list":Ak(o);break;case"add":Pk(o,e);break;case"remove":Ik(o,s[1]);break;case"test":Mk(o,s[1]);break;case"enable":Af(o,s[1],!0);break;case"disable":Af(o,s[1],!1);break;case"serve":await Nk(o,e);break;default:jk()}}l(Do,"triggersCommand");function Ak(s){let e=In(s),t=G(j());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(Ak,"triggersList");function Pk(s,e){let t=e.event,o=e.prompt,n=e.name||Ok(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=In(s);if(d.some(p=>p.name===n)){console.log(a.red(` Trigger "${n}" already exists. Use a different --name.`));return}d.push(u),ll(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(Pk,"triggersAdd");function Ik(s,e){if(!e){console.log(a.red(" Usage: mc triggers remove <trigger-name>"));return}let t=In(s),o=t.findIndex(n=>n.name===e);if(o===-1){console.log(a.red(` Trigger "${e}" not found.`));return}t.splice(o,1),ll(s,t),console.log(a.green(` \u2705 Trigger "${e}" removed`)),console.log("")}l(Ik,"triggersRemove");function Mk(s,e){if(!e){console.log(a.red(" Usage: mc triggers test <trigger-name>"));return}let o=In(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(Mk,"triggersTest");function Af(s,e,t){if(!e){console.log(a.red(` Usage: mc triggers ${t?"enable":"disable"} <trigger-name>`));return}let o=In(s),n=o.find(r=>r.name===e);if(!n){console.log(a.red(` Trigger "${e}" not found.`));return}n.enabled=t,ll(s,o),console.log(a.green(` \u2705 Trigger "${e}" ${t?"enabled":"disabled"}`)),console.log("")}l(Af,"triggersToggle");function In(s){let e=Pn.join(s,Pf);if(!vo.existsSync(e))return[];try{return JSON.parse(vo.readFileSync(e,"utf8")).triggers||[]}catch{return[]}}l(In,"loadTriggers");function ll(s,e){let t=Pn.join(s,Pf),o=Pn.dirname(t);vo.mkdirSync(o,{recursive:!0}),vo.writeFileSync(t,JSON.stringify({triggers:e},null,2)+`
|
|
525
|
+
`)}l(ll,"saveTriggers");function Ok(s,e){let t=e.toLowerCase().split(/\s+/).slice(0,3).join("-").replace(/[^a-z0-9-]/g,"");return`${s.replace(/\./g,"-")}-${t}`}l(Ok,"generateName");function jk(){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(jk,"printHelp");async function Nk(s,e){let{TriggerEngine:t}=await Promise.resolve().then(()=>(Ef(),Cf)),{GitHubWebhookServer:o}=await Promise.resolve().then(()=>(Rf(),Tf)),n=Y(),{getAccessToken:r}=await Promise.resolve().then(()=>(ee(),he)),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 h=>{console.log(a.cyan(` \u{1F514} GitHub event: ${h.event}`)),await u.processEvent({type:`github.${h.event}`,payload:h.payload,source:"github-webhook",timestamp:Date.now()})},"onEvent")}).start(),console.log(a.dim(` \u{1F514} Webhook server: http://localhost:${c} (${p.length} trigger(s))`))}console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.green(" Trigger daemon running. Press Ctrl+C to stop.")),console.log(""),await new Promise(f=>{let m=l(()=>{console.log(a.dim(`
|
|
526
|
+
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(Nk,"triggersServe");H();H();var Lf=require("node:child_process");var Be=w(require("node:fs"),1),So=w(require("node:path"),1),If=w(require("node:crypto"),1);Z();var Es=class s{static{l(this,"TraceRecorder")}trace;turnIndex=0;currentToolStart=null;currentToolName=null;thinkingBuffer="";tracesDir;constructor(e){let t=A(Se());this.tracesDir=So.join(t.data,"traces"),Be.mkdirSync(this.tracesDir,{recursive:!0}),this.trace={runId:e.runId||If.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=So.join(this.tracesDir,`${this.trace.runId}.json`);Be.writeFileSync(e,JSON.stringify(this.trace,null,2))}getTrace(){return this.trace}trackFileAccess(e,t){if(!t)return;let o=t.path||t.file||t.filePath||t.target;if(!o)return;this.trace.fileAccessGraph[o]||(this.trace.fileAccessGraph[o]={reads:0,writes:0});let n=["read_file","grep_search","view_file","list_dir"],r=["write_file","edit_file","replace_file","create_file","delete_file"];n.some(i=>e.includes(i))?this.trace.fileAccessGraph[o].reads++:r.some(i=>e.includes(i))&&this.trace.fileAccessGraph[o].writes++}estimateTokens(e){return Math.ceil(e.length/4)}static load(e){let t=A(Se()),o=So.join(t.data,"traces"),n=So.join(o,`${e}.json`);if(!Be.existsSync(n))return null;try{return JSON.parse(Be.readFileSync(n,"utf8"))}catch{return null}}static list(e=20){let t=A(Se()),o=So.join(t.data,"traces");return Be.existsSync(o)?Be.readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=Be.statSync(So.join(o,r));return{file:r,mtime:i.mtimeMs}}).sort((r,i)=>i.mtime-r.mtime).slice(0,e).map(r=>{try{let i=JSON.parse(Be.readFileSync(So.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}};H();function Mf(s,e={}){Lk(s),e.tree?Wk(s):Bk(s,e.verbose),Hk(s),Gk(s)}l(Mf,"renderTrace");function Lk(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(Mn(s.tokensIn))} in / ${a.white(Mn(s.tokensOut))} out${s.tokensCached?` / ${a.dim(Mn(s.tokensCached)+" cached")}`:""}`),console.log(` ${a.dim("Files:")} ${o} accessed`),console.log(` ${a.dim("Turns:")} ${s.turns.length}`),console.log()}l(Lk,"renderHeader");function Bk(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)Uk(t,e);console.log()}l(Bk,"renderTimeline");function Uk(s,e){let t=s.tokens?a.dim(` (${Mn(s.tokens)} tok)`):"",o=s.durationMs?a.dim(` ${s.durationMs}ms`):"";switch(s.type){case"thinking":{let n=e?s.content||"":(s.content||"").split(`
|
|
527
|
+
`)[0].slice(0,80);console.log(` ${a.blue("\u{1F4AD}")} ${a.blue("Thinking")}${t}`),n&&console.log(` ${a.dim(n)}`);break}case"tool_call":{let n=qk(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(Uk,"renderTurn");function Wk(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(` [${Mn(t.tokens)} tok]`):"",r=t.durationMs?a.dim(` ${t.durationMs}ms`):"";switch(t.type){case"thinking":if(console.log(`${o}${a.blue("\u251C\u2500 \u{1F4AD} Think")}${n}`),t.content){let i=t.content.split(`
|
|
528
|
+
`)[0].slice(0,70);console.log(`${o}${a.dim("\u2502 "+i)}`)}e=Math.min(e+1,4);break;case"tool_call":console.log(`${o}${a.green("\u251C\u2500 \u{1F527} "+(t.tool||"tool"))}${r}`),t.resultPreview&&console.log(`${o}${a.dim("\u2502 \u2192 "+t.resultPreview.slice(0,60))}`);break;case"context_compact":e=Math.max(0,e-1),console.log(`${o}${a.yellow("\u251C\u2500 \u{1F4E6} Compact")}${n}`);break;case"error":console.log(`${o}${a.red("\u2514\u2500 \u274C Error")}: ${t.content}`);break}}console.log()}l(Wk,"renderTree");function Hk(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(Hk,"renderFileGraph");function Gk(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(Gk,"renderFooter");function qk(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(qk,"getToolIcon");function Mn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Mn,"formatNum");var jf=w(require("node:fs"),1),dl=w(require("node:path"),1);Z();var Vo={thinking:"#4A90D9",tool_call:"#2ECC71",context_compact:"#F39C12",error:"#E74C3C",root:"#34495E"};function Nf(s){let e=A(Se()),t=dl.join(e.data,"traces"),o=dl.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 Of(s,r,o)}return Of(s,n,o)}l(Nf,"generateFlamegraph");function Of(s,e,t){let c=[];c.push({name:`Run: ${s.model} \u2014 ${s.prompt.slice(0,50)}`,tokens:e,color:Vo.root,x:0,width:1200,y:0,detail:`Total: ${ul(e)} tokens, $${s.totalCostUsd.toFixed(4)}`});let u=0;for(let m of s.turns){let h=m.tokens||Vk(m);if(h===0)continue;let g=Math.max(h/e*1200,2),y=Vo[m.type]||Vo.root,x=m.type==="tool_call"?m.tool||"tool":m.type==="thinking"?"Think":m.type;c.push({name:x,tokens:h,color:y,x:u,width:g,y:1,detail:`${x}: ${ul(h)} tokens${m.durationMs?`, ${m.durationMs}ms`:""}`}),u+=g}let d=2,p=d*24+40*2+60,f=`<?xml version="1.0" encoding="UTF-8"?>
|
|
529
529
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 ${p}" width="1200" height="${p}">
|
|
530
530
|
<style>
|
|
531
531
|
.frame { cursor: pointer; }
|
|
@@ -539,31 +539,31 @@ ${t}
|
|
|
539
539
|
<rect width="1200" height="${p}" fill="#1a1a2e" rx="8"/>
|
|
540
540
|
|
|
541
541
|
<!-- Title -->
|
|
542
|
-
<text x="40" y="28" class="title">Token Flamegraph \u2014 ${
|
|
543
|
-
<text x="40" y="46" class="subtitle">${
|
|
542
|
+
<text x="40" y="28" class="title">Token Flamegraph \u2014 ${di(s.runId)}</text>
|
|
543
|
+
<text x="40" y="46" class="subtitle">${di(s.model)} \xB7 ${ul(e)} tokens \xB7 $${s.totalCostUsd.toFixed(4)} \xB7 ${(s.durationMs/1e3).toFixed(1)}s</text>
|
|
544
544
|
|
|
545
545
|
<!-- Legend -->
|
|
546
546
|
<g class="legend" transform="translate(800, 20)">
|
|
547
|
-
<rect x="0" y="0" width="12" height="12" fill="${
|
|
547
|
+
<rect x="0" y="0" width="12" height="12" fill="${Vo.thinking}"/>
|
|
548
548
|
<text x="16" y="11">Thinking</text>
|
|
549
|
-
<rect x="80" y="0" width="12" height="12" fill="${
|
|
549
|
+
<rect x="80" y="0" width="12" height="12" fill="${Vo.tool_call}"/>
|
|
550
550
|
<text x="96" y="11">Tools</text>
|
|
551
|
-
<rect x="150" y="0" width="12" height="12" fill="${
|
|
551
|
+
<rect x="150" y="0" width="12" height="12" fill="${Vo.context_compact}"/>
|
|
552
552
|
<text x="166" y="11">Compact</text>
|
|
553
|
-
<rect x="230" y="0" width="12" height="12" fill="${
|
|
553
|
+
<rect x="230" y="0" width="12" height="12" fill="${Vo.error}"/>
|
|
554
554
|
<text x="246" y="11">Error</text>
|
|
555
555
|
</g>
|
|
556
556
|
|
|
557
557
|
<!-- Frames -->
|
|
558
558
|
<g transform="translate(0, 60)">
|
|
559
|
-
`;for(let m of c){let
|
|
560
|
-
<title>${
|
|
561
|
-
<rect x="${m.x}" y="${
|
|
562
|
-
<text x="${
|
|
559
|
+
`;for(let m of c){let h=(d-1-m.y)*24,g=m.x+4,y=m.width>40?Jk(m.name,Math.floor(m.width/7)):"";f+=`<g class="frame">
|
|
560
|
+
<title>${di(m.detail)}</title>
|
|
561
|
+
<rect x="${m.x}" y="${h}" width="${m.width}" height="22" fill="${m.color}" rx="2"/>
|
|
562
|
+
<text x="${g}" y="${h+24-8}">${di(y)}</text>
|
|
563
563
|
</g>
|
|
564
|
-
`}return
|
|
565
|
-
</svg>`,
|
|
566
|
-
`)){let c=i.match(/^(\w+):\s*(.+)$/);if(!c)continue;let[,u,d]=c;switch(u){case"name":r.name=d.trim();break;case"description":r.description=d.trim();break;case"version":r.version=d.trim();break;case"author":r.author=d.trim();break;case"category":r.category=d.trim();break;case"tags":r.tags=d.split(",").map(p=>p.trim().replace(/^\[|\]$/g,""));break}}return r}createTarball(e){let t=
|
|
564
|
+
`}return f+=`</g>
|
|
565
|
+
</svg>`,jf.writeFileSync(t,f),t}l(Of,"generateSvg");function Vk(s){return s.tokens?s.tokens:s.content?Math.ceil(s.content.length/4):s.result?Math.ceil(s.result.length/4):10}l(Vk,"estimateTurnTokens");function ul(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(ul,"formatTokens");function Jk(s,e){return s.length>e?s.slice(0,e-1)+"\u2026":s}l(Jk,"truncate");function di(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}l(di,"escapeXml");function Bf(s){let e=Es.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(Bf,"traceList");function Uf(s,e){let t=s==="last"?Es.lastRunId():s;if(!t){console.log(a.red("No traces found. Run an agent first."));return}let o=Es.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=Nf(o);console.log(a.green(`Flamegraph saved: ${n}`));let r=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Lf.exec)(`${r} "${n}"`,i=>{i&&console.log(a.dim(`Open manually: ${n}`))});return}Mf(o,{tree:e.tree,verbose:e.verbose})}l(Uf,"traceShow");H();Q();ee();var eo=class{static{l(this,"MarketplaceClient")}baseUrl;token;constructor(e){let t=Y();this.baseUrl=(e?.baseUrl||t.platformUrl||"https://api.monkeyscode.com").replace(/\/$/,""),this.token=e?.token||process.env.MC_API_KEY||void 0}async search(e,t){let o=new URLSearchParams({q:e});return t?.category&&o.set("category",t.category),t?.page&&o.set("page",String(t.page)),t?.pageSize&&o.set("page_size",String(t.pageSize)),this.get(`/v1/marketplace/skills?${o}`)}async getSkill(e){return this.get(`/v1/marketplace/skills/${e}`)}async featured(){return this.get("/v1/marketplace/featured")}async getReviews(e){return this.get(`/v1/marketplace/skills/${e}/reviews`)}async addReview(e,t,o){return this.post(`/v1/marketplace/skills/${e}/reviews`,{rating:t,comment:o})}async publish(e){let t=new FormData;t.set("name",e.name),t.set("description",e.description),t.set("version",e.version),t.set("category",e.category),t.set("tags",JSON.stringify(e.tags)),t.set("tarball",new Blob([e.tarball]),`${e.name}-${e.version}.tar.gz`);let o=await fetch(`${this.baseUrl}/v1/marketplace/skills`,{method:"POST",headers:await this.authHeaders(),body:t});if(!o.ok)throw new Error(`Marketplace API error: ${o.status} ${await o.text()}`);return await o.json()}async download(e){let t=await this.getSkill(e);if(!t.downloadUrl)throw new Error(`No download URL for skill ${e}`);let o=await fetch(t.downloadUrl,{headers:await this.authHeaders()});if(!o.ok)throw new Error(`Download failed: ${o.status}`);let n=await o.arrayBuffer();return Buffer.from(n)}async get(e){let t=await fetch(`${this.baseUrl}${e}`,{headers:{...await this.authHeaders(),Accept:"application/json"}});if(!t.ok)throw new Error(`Marketplace API error: ${t.status} ${await t.text()}`);return await t.json()}async post(e,t){let o=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:{...await this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Marketplace API error: ${o.status} ${await o.text()}`);return await o.json()}async authHeaders(){let e=this.token||await Fe();return e?{Authorization:`Bearer ${e}`}:{}}};var ye=w(require("node:fs"),1),xo=w(require("node:path"),1),Wf=require("node:child_process");Z();var Jo=class{static{l(this,"SkillInstaller")}client;skillsDir;registryPath;constructor(){this.client=new eo;let e=A(Se());this.skillsDir=xo.join(e.config,"skills"),this.registryPath=xo.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=xo.join(this.skillsDir,n,r);ye.existsSync(i)&&ye.rmSync(i,{recursive:!0}),ye.mkdirSync(i,{recursive:!0});let c=xo.join(i,".tmp.tar.gz");ye.writeFileSync(c,o);try{(0,Wf.execSync)(`tar -xzf "${c}" -C "${i}" --strip-components=1`,{stdio:"pipe"})}finally{ye.unlinkSync(c)}let u=xo.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=xo.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 Et=w(require("node:fs"),1),yt=w(require("node:path"),1),Hf=require("node:child_process");var pi=class{static{l(this,"SkillPublisher")}client;constructor(){this.client=new eo}async publish(e,t){let o=yt.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(!Et.existsSync(e))throw new Error(`Directory not found: ${e}`);let t=yt.join(e,"skill.md");if(!Et.existsSync(t))throw new Error("Missing required file: skill.md");let o=yt.join(e,"README.md");if(!Et.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=Et.readFileSync(yt.join(e,"skill.md"),"utf8").match(/^---\n([\s\S]*?)\n---/);if(!o)throw new Error("skill.md must have YAML frontmatter (between --- markers)");let n=o[1],r={name:"",description:"",version:"1.0.0",author:"",category:"general",tags:[]};for(let i of n.split(`
|
|
566
|
+
`)){let c=i.match(/^(\w+):\s*(.+)$/);if(!c)continue;let[,u,d]=c;switch(u){case"name":r.name=d.trim();break;case"description":r.description=d.trim();break;case"version":r.version=d.trim();break;case"author":r.author=d.trim();break;case"category":r.category=d.trim();break;case"tags":r.tags=d.split(",").map(p=>p.trim().replace(/^\[|\]$/g,""));break}}return r}createTarball(e){let t=yt.join(e,".publish.tar.gz");try{return(0,Hf.execSync)(`tar -czf "${t}" --exclude=".*" --exclude="node_modules" --exclude="*.tar.gz" -C "${yt.dirname(e)}" "${yt.basename(e)}"`,{stdio:"pipe"}),Et.readFileSync(t)}finally{Et.existsSync(t)&&Et.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 Gf(s,e){let t=new eo;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)Xf(n)}catch(o){console.log(a.red(`Search failed: ${o.message}`))}}l(Gf,"marketplaceSearch");async function qf(s){let e=new Jo;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(qf,"marketplaceInstall");function Vf(s){new Jo().uninstall(s)?console.log(a.green(`\u2713 Uninstalled ${s}`)):console.log(a.red(`Skill not found: ${s}`))}l(Vf,"marketplaceUninstall");async function Jf(s,e){let t=new pi;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(Jf,"marketplacePublish");async function zf(){let s=new Jo;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(zf,"marketplaceUpdate");function Kf(){let e=new Jo().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(Kf,"marketplaceList");async function Yf(){let s=new eo;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)Xf(t)}catch(e){console.log(a.red(`Failed to fetch featured: ${e.message}`))}}l(Yf,"marketplaceFeatured");function Xf(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(Xf,"renderSkillCard");H();var _o=w(require("node:fs"),1),mi=w(require("node:path"),1);Z();var zk=`You translate natural language permission rules into structured JSON policies.
|
|
567
567
|
|
|
568
568
|
Each policy has:
|
|
569
569
|
- tool: glob pattern for which tools this applies to (e.g., "delete_file", "bash", "*")
|
|
@@ -587,12 +587,12 @@ Input: "Ask before modifying any file with 'config' in the name"
|
|
|
587
587
|
Output: {"tool":"*_file","condition":"path.includes('config')","action":"prompt","message":"This file contains configuration. Proceed?"}
|
|
588
588
|
|
|
589
589
|
Input: "Block any command that uses sudo"
|
|
590
|
-
Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function
|
|
590
|
+
Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function Kk(s){let e=Yk(s);return e||await Xk(s)}l(Kk,"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 Xk(s){try{let{AgentLoop:e}=await Promise.resolve().then(()=>(Xe(),rs)),{loadSettings:t}=await Promise.resolve().then(()=>(Q(),we)),{getAccessToken:o}=await Promise.resolve().then(()=>(ee(),he)),n=t(),r=await o()||process.env.MC_API_KEY||"";if(!r)return pl(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(`${zk}
|
|
591
591
|
|
|
592
592
|
Input: "${s}"
|
|
593
|
-
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?
|
|
594
|
-
`),o="",n={};for(let r of t){let i=r.trim();if(!i||i.startsWith("#"))continue;let c=i.match(/^(\w+):\s*(.*)$/);if(c&&!r.startsWith(" ")&&!r.startsWith(" ")){let[,p,
|
|
595
|
-
${
|
|
593
|
+
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?pl(s):d}catch{return pl(s)}}l(Xk,"llmTranslation");function pl(s){return{tool:"*",condition:"true",action:"prompt",message:`Custom rule: ${s}`}}l(pl,"fallbackPolicy");function Qf(){let s=A(Se());return mi.join(s.config,"natural-permissions.json")}l(Qf,"getPermissionsPath");function On(){let s=Qf();if(!_o.existsSync(s))return{naturalRules:[]};try{return JSON.parse(_o.readFileSync(s,"utf8"))}catch{return{naturalRules:[]}}}l(On,"loadNaturalPermissions");function Zf(s){let e=Qf(),t=mi.dirname(e);_o.mkdirSync(t,{recursive:!0}),_o.writeFileSync(e,JSON.stringify(s,null,2))}l(Zf,"saveNaturalPermissions");async function eh(s){let e=await Kk(s),t={text:s,generatedPolicy:e,createdAt:new Date().toISOString(),enabled:!0},o=On();return o.naturalRules.push(t),Zf(o),t}l(eh,"addNaturalRule");function th(s){let e=On();return s<0||s>=e.naturalRules.length?!1:(e.naturalRules.splice(s,1),Zf(e),!0)}l(th,"removeNaturalRule");function oh(s,e){let t=On();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(oh,"evaluateNaturalRules");async function sh(s){console.log(a.dim("Translating rule..."));let e=await eh(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:")} ${ml(e.generatedPolicy.action)}`),console.log(` ${a.dim("Message:")} ${e.generatedPolicy.message}`),console.log()}l(sh,"permissionsSet");function nh(){let s=On();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=ml(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(nh,"permissionsList");function rh(s){let e=th(s);console.log(e?a.green(`\u2713 Rule ${s} removed`):a.red(`Rule ${s} not found`))}l(rh,"permissionsRemove");function ih(s,e){let t;try{t=JSON.parse(e)}catch{console.log(a.red("Invalid JSON for args"));return}let o=oh(s,t);console.log(),console.log(` ${a.dim("Tool:")} ${s}`),console.log(` ${a.dim("Args:")} ${JSON.stringify(t)}`),console.log(` ${a.dim("Result:")} ${ml(o.action)}`),o.message&&console.log(` ${a.dim("Message:")} ${o.message}`),console.log()}l(ih,"permissionsTest");function ml(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(ml,"colorAction");var Ts=w(require("node:fs"),1),gi=w(require("node:path"),1);H();var qe=w(require("node:fs"),1),Fs=w(require("node:path"),1),fi=require("node:child_process");function Qk(s){let e={name:"Unnamed Benchmark",setup:[],steps:[],score:{testsPass:50,noRegressions:30,codeQuality:20}},t=s.split(`
|
|
594
|
+
`),o="",n={};for(let r of t){let i=r.trim();if(!i||i.startsWith("#"))continue;let c=i.match(/^(\w+):\s*(.*)$/);if(c&&!r.startsWith(" ")&&!r.startsWith(" ")){let[,p,f]=c;p==="name"&&(e.name=f.replace(/^["']|["']$/g,"")),p==="description"&&(e.description=f),p==="setup"&&(o="setup"),p==="steps"&&(o="steps"),p==="score"&&(o="score");continue}let u=i.match(/^-\s+(.+)$/);if(u){o==="setup"&&e.setup.push(u[1].replace(/^["']|["']$/g,""));continue}let d=i.match(/^(\w+):\s*(.+)$/);if(d){let[,p,f]=d,m=f.replace(/^["']|["']$/g,"");o==="steps"&&(p==="prompt"&&(n.prompt&&e.steps.push(n),n={prompt:m}),p==="verify"&&(n.verify=m),p==="expected_files_changed"&&(n.expectedFilesChanged=m.replace(/^\[|\]$/g,"").split(",").map(h=>h.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(Qk,"parseSimpleYaml");var hi=class{static{l(this,"BenchmarkRunner")}workspace;constructor(e){this.workspace=e}loadSpec(e){let t=qe.readFileSync(e,"utf8");return Qk(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,fi.execSync)(p,{cwd:this.workspace,stdio:"pipe",timeout:6e4})}catch(f){console.error(`Setup step failed: ${p}
|
|
595
|
+
${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop:m}=await Promise.resolve().then(()=>(Xe(),rs)),{loadSettings:h}=await Promise.resolve().then(()=>(Q(),we)),{getAccessToken:g}=await Promise.resolve().then(()=>(ee(),he)),y=h(),x=await g()||process.env.MC_API_KEY||"",v=new m({platformUrl:y.platformUrl,token:x,model:t,workspace:this.workspace,mode:"auto",maxTurns:p.maxTokens?Math.ceil(p.maxTokens/1e3):20,sandboxed:!0}),_=0,S=0,k=[];v.on("event",O=>{if(O.type==="state_update"&&(_=(O.state?.tokensIn||0)+(O.state?.tokensOut||0),S=O.state?.costUsd||0),O.type==="tool_call_start"&&O.name?.includes("file")){let ce=O.args?.path||O.args?.file;ce&&!k.includes(ce)&&k.push(ce)}}),await v.run(p.prompt);let C=!1,J="";try{J=(0,fi.execSync)(p.verify,{cwd:this.workspace,stdio:"pipe",timeout:p.timeoutMs||12e4}).toString().trim(),C=!0}catch(O){J=O.stderr?.toString()||O.message||"Verification failed",C=!1}r+=_,i+=S,c.push({prompt:p.prompt,passed:C,verifyOutput:J,durationMs:Date.now()-f,tokensUsed:_,filesChanged:k,score:this.scoreStep(p,C,k,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,fi.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)&&!Zk(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 Zk(s,e){return e.some(t=>{let o=t.replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(o).test(s)})}l(Zk,"matchesGlob");function fl(s){let{getPlatformPaths:e,detectPlatform:t}=(Z(),Ls(To)),o=e(t()),n=Fs.join(o.data,"benchmarks");qe.mkdirSync(n,{recursive:!0});let r=`${s.name.replace(/\s+/g,"-").toLowerCase()}-${s.model}-${Date.now()}.json`,i=Fs.join(n,r);return qe.writeFileSync(i,JSON.stringify(s,null,2)),i}l(fl,"saveBenchmarkResult");function ah(s=20){let{getPlatformPaths:e,detectPlatform:t}=(Z(),Ls(To)),o=e(t()),n=Fs.join(o.data,"benchmarks");return qe.existsSync(n)?qe.readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let i=qe.statSync(Fs.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(qe.readFileSync(Fs.join(n,r.file),"utf8"))}catch{return null}}).filter(Boolean):[]}l(ah,"loadBenchmarkResults");H();function ch(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:")} ${dh(s.totalScore,s.maxScore)} ${a.dim(`(${e}%)`)}`),console.log(` ${a.dim("Duration:")} ${t}s`),console.log(` ${a.dim("Tokens:")} ${jn(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 ${jn(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(ch,"renderResult");function lh(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))}`+dh(c.totalScore,c.maxScore).padEnd(20)+a.dim(((c.durationMs/1e3).toFixed(1)+"s").padEnd(10))+a.dim(jn(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(lh,"renderComparison");function uh(s){if(s.length===0)return`# No Results
|
|
596
596
|
`;let e=`# Benchmark Report: ${s[0].name}
|
|
597
597
|
|
|
598
598
|
`;e+=`Generated: ${new Date().toISOString()}
|
|
@@ -601,21 +601,21 @@ ${g.message}`)}let c=[];for(let p of e.steps){let g=Date.now();try{let{AgentLoop
|
|
|
601
601
|
|
|
602
602
|
`,e+=`| Model | Score | Time | Tokens | Cost | Steps Passed |
|
|
603
603
|
`,e+=`|-------|-------|------|--------|------|--------------|
|
|
604
|
-
`;let t=[...s].sort((o,n)=>n.totalScore-o.totalScore);for(let o of t){let n=(o.totalScore/o.maxScore*100).toFixed(0)+"%",r=o.steps.filter(i=>i.passed).length;e+=`| ${o.model} | ${n} | ${(o.durationMs/1e3).toFixed(1)}s | ${
|
|
604
|
+
`;let t=[...s].sort((o,n)=>n.totalScore-o.totalScore);for(let o of t){let n=(o.totalScore/o.maxScore*100).toFixed(0)+"%",r=o.steps.filter(i=>i.passed).length;e+=`| ${o.model} | ${n} | ${(o.durationMs/1e3).toFixed(1)}s | ${jn(o.tokensUsed)} | $${o.costUsd.toFixed(4)} | ${r}/${o.steps.length} |
|
|
605
605
|
`}e+=`
|
|
606
606
|
`;for(let o of s){e+=`### ${o.model}
|
|
607
607
|
|
|
608
608
|
`;for(let n=0;n<o.steps.length;n++){let r=o.steps[n],i=r.passed?"\u2705":"\u274C";e+=`${i} **Step ${n+1}**: ${r.prompt}
|
|
609
|
-
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${
|
|
609
|
+
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${jn(r.tokensUsed)}
|
|
610
610
|
`,e+=`- Files: ${r.filesChanged.join(", ")||"none"}
|
|
611
611
|
|
|
612
|
-
`}}return e}l(
|
|
613
|
-
`).slice(0,10);for(let t of e)console.log(a.dim(` ${t}`))}break;case"error":console.log(a.red(` \u2717 Error: ${s.message||s.error||"unknown"}`));break;case"complete":console.log(""),console.log(a.green(" \u2713 Complete")),s.result?.summary&&console.log(a.dim(` ${s.result.summary}`));break;case"cost_update":break;default:process.env.MC_DEBUG&&console.log(a.dim(` [${s.type}] ${JSON.stringify(s).slice(0,100)}`));break}}l(
|
|
614
|
-
Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()=>{console.log(a.green("Reconnected."))}),n.on("error",r=>{console.log(a.red(`Session error: ${r.message}`))});try{await n.connect(),console.log(a.green(`\u2713 Connected to session ${s}`)),console.log(a.dim("Waiting for host activity... Press Ctrl+C to leave."));let r=
|
|
612
|
+
`}}return e}l(uh,"generateMarkdownReport");function dh(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(dh,"colorScore");function jn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(jn,"formatNum");async function ph(s,e){let t=gi.resolve(s),o=e.workspace||process.cwd();if(!Ts.existsSync(t)){console.log(a.red(`Benchmark not found: ${t}`));return}let n=new hi(o),r=e.model||["capuchin-reason"],i=ev(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)fl(d);lh(u)}else{console.log(a.dim(`Running benchmark: ${c.name} with ${r[0]}...`));let u=await n.run(c,r[0]);fl(u),ch(u)}}l(ph,"benchmarkCustom");function mh(s){let e=ah(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(uh(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))+tv(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(mh,"benchmarkResults");function ev(s,e){return Ts.statSync(s).isFile()?[e.loadSpec(s)]:Ts.readdirSync(s).filter(o=>o.endsWith(".yaml")||o.endsWith(".yml")).map(o=>e.loadSpec(gi.join(s,o)))}l(ev,"loadSpecs");function tv(s){let e=parseInt(s);return e>=80?a.green(s):e>=50?a.yellow(s):a.red(s)}l(tv,"colorScore");H();var yh=w(require("node:readline"),1);var fh=w(require("node:crypto"),1),hh=require("node:events");mn();var Nn=class extends hh.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=fh.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 dt(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===dt.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===dt.OPEN&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){this.reconnectTimer||(this.reconnectTimer=setTimeout(async()=>{this.reconnectTimer=null;try{await this.connect(),this.emit("reconnected")}catch{this.scheduleReconnect()}},3e3))}generateSessionId(){let e=["alpha","beta","gamma","delta","echo","fox","golf","hotel"],t=e[Math.floor(Math.random()*e.length)],o=e[Math.floor(Math.random()*e.length)],n=Math.floor(Math.random()*1e3).toString().padStart(3,"0");return`mc-share-${t}-${o}-${n}`}};Q();ee();H();function gh(s){if(!(!s||!s.type))switch(s.type){case"text":process.stdout.write(s.content||"");break;case"thinking":s.content&&process.stdout.write(a.dim(s.content));break;case"tool_call":console.log(a.cyan(` \u26A1 ${s.toolName||s.tool||"tool"}`)+(s.args?a.dim(` ${JSON.stringify(s.args).slice(0,80)}`):""));break;case"tool_result":s.isError&&console.log(a.red(` \u2717 Tool error: ${s.result||"unknown"}`));break;case"file_edit":console.log(a.yellow(` \u270E Edited: ${s.path||s.file||"unknown"}`));break;case"file_read":console.log(a.dim(` \u{1F4C4} Read: ${s.path||s.file||"unknown"}`));break;case"terminal_command":if(console.log(a.blue(` $ ${s.command||""}`)),s.output){let e=s.output.split(`
|
|
613
|
+
`).slice(0,10);for(let t of e)console.log(a.dim(` ${t}`))}break;case"error":console.log(a.red(` \u2717 Error: ${s.message||s.error||"unknown"}`));break;case"complete":console.log(""),console.log(a.green(" \u2713 Complete")),s.result?.summary&&console.log(a.dim(` ${s.result.summary}`));break;case"cost_update":break;default:process.env.MC_DEBUG&&console.log(a.dim(` [${s.type}] ${JSON.stringify(s).slice(0,100)}`));break}}l(gh,"renderEvent");async function wh(s){console.log(a.dim(`Joining session ${s}...`));let e=Y();if(!(await Fe()||process.env.MC_API_KEY)){console.log(a.red("You must be logged in to join a shared session.")),console.log(a.dim("Run `mc auth login` first."));return}let o=process.env.USER||"Observer",n=new Nn({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=>{gh(r)}),n.on("remote_prompt",({prompt:r,from:i})=>{console.log(),console.log(a.cyan(`[${i}] `)+a.white(r)),console.log()}),n.on("disconnected",()=>{console.log(a.red(`
|
|
614
|
+
Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()=>{console.log(a.green("Reconnected."))}),n.on("error",r=>{console.log(a.red(`Session error: ${r.message}`))});try{await n.connect(),console.log(a.green(`\u2713 Connected to session ${s}`)),console.log(a.dim("Waiting for host activity... Press Ctrl+C to leave."));let r=yh.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(wh,"joinSession");async function bh(){let s=Y();if(!(await Fe()||process.env.MC_API_KEY))return console.log(a.red("You must be logged in to share a session.")),null;let t=process.env.USER||"Host",o=new Nn({relayUrl:s.platformUrl||"wss://api.monkeyscode.com",userName:t});o.on("participant_joined",n=>{console.log(a.green(`
|
|
615
615
|
\u2192 ${n} joined your session
|
|
616
616
|
`))}),o.on("participant_left",n=>{console.log(a.dim(`
|
|
617
617
|
\u2190 ${n} left your session
|
|
618
|
-
`))});try{return await o.connect(),console.log(a.bgBlue.white.bold(" LIVE SHARE ")),console.log(a.dim("Others can join this session using:")),console.log(a.cyan(`mc join ${o.sessionId}`)),console.log(a.dim(`Or via web: ${o.getShareUrl()}`)),console.log(),o}catch(n){return console.log(a.red(`Failed to start live share: ${n.message}`)),null}}l(
|
|
618
|
+
`))});try{return await o.connect(),console.log(a.bgBlue.white.bold(" LIVE SHARE ")),console.log(a.dim("Others can join this session using:")),console.log(a.cyan(`mc join ${o.sessionId}`)),console.log(a.dim(`Or via web: ${o.getShareUrl()}`)),console.log(),o}catch(n){return console.log(a.red(`Failed to start live share: ${n.message}`)),null}}l(bh,"setupSharedSession");var vh=w(require("node:http"),1);mn();H();function kh(s,e="Design Preview"){return`
|
|
619
619
|
<!DOCTYPE html>
|
|
620
620
|
<html lang="en">
|
|
621
621
|
<head>
|
|
@@ -662,10 +662,18 @@ Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()
|
|
|
662
662
|
</script>
|
|
663
663
|
</body>
|
|
664
664
|
</html>
|
|
665
|
-
`.trim()}l(sf,"generateHtmlPreview");var rl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=nf.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(sf(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")}},rf=new rl;W();function Sk(s){let e=new Date(s),o=new Date().getTime()-s,n=Math.floor(o/6e4),r=Math.floor(o/36e5),i=Math.floor(o/864e5);return n<1?"just now":n<60?`${n}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:e.toLocaleDateString()}l(Sk,"formatDate");function li(s){return s.substring(0,8)}l(li,"formatShortId");function xk(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(xk,"truncatePath");function af(){let e=new Lt().list();if(e.length===0){console.log(a.dim(" No saved sessions.")),console.log(a.dim(" Sessions are automatically saved when you use the CLI."));return}console.log(""),console.log(a.bold(" Recent Sessions")),console.log(a.dim(" \u2500".repeat(35))),console.log(""),console.log(a.dim(" ")+a.bold("ID".padEnd(10))+a.bold("Workspace".padEnd(42))+a.bold("Turns".padEnd(8))+a.bold("Last Active".padEnd(14))+a.bold("Preview")),console.log(a.dim(" "+"\u2500".repeat(90)));for(let t of e){let o=a.hex("#6B8DD6")(li(t.id)),n=xk(t.workspace),r=String(t.turnCount).padEnd(8),i=Sk(t.lastActive).padEnd(14),c=a.dim(t.preview.substring(0,30));console.log(` ${o} ${n.padEnd(40)} ${r}${i}${c}`)}console.log(""),console.log(a.dim(` ${e.length} session(s). Use "mc sessions show <id>" for details.`)),console.log("")}l(af,"sessionsListCommand");function cf(s){let e=new Lt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.load(o.id);if(!n){console.log(a.red(` \u2717 Failed to load session "${o.id}".`));return}if(console.log(""),console.log(a.bold(` Session ${li(n.id)}`)),console.log(a.dim(" \u2500".repeat(35))),console.log(` ${a.bold("ID:")} ${n.id}`),console.log(` ${a.bold("Workspace:")} ${n.workspace}`),console.log(` ${a.bold("Model:")} ${n.model}`),console.log(` ${a.bold("Mode:")} ${n.mode}`),console.log(` ${a.bold("Started:")} ${new Date(n.startTime).toLocaleString()}`),console.log(` ${a.bold("Last active:")} ${new Date(n.lastActive).toLocaleString()}`),console.log(` ${a.bold("Turns:")} ${n.turnCount}`),console.log(` ${a.bold("Tokens:")} ${n.stats.tokensUsed.toLocaleString()}`),console.log(` ${a.bold("Tool calls:")} ${n.stats.toolCalls}`),n.stats.filesChanged.length>0){console.log(` ${a.bold("Files changed:")}`);for(let r of n.stats.filesChanged.slice(0,10))console.log(` ${r}`);n.stats.filesChanged.length>10&&console.log(a.dim(` ... and ${n.stats.filesChanged.length-10} more`))}console.log(""),console.log(a.bold(" Conversation:")),console.log(a.dim(" \u2500".repeat(35)));for(let r of n.messages.slice(-10)){let i=r.role==="user"?a.hex("#6B8DD6").bold("You"):r.role==="assistant"?a.hex("#A3CAD3").bold("MC"):a.dim("System"),c=new Date(r.timestamp).toLocaleTimeString(),u=r.content.substring(0,120).replace(/\n/g," ");console.log(` ${a.dim(c)} ${i}: ${u}`)}n.messages.length>10&&console.log(a.dim(` ... ${n.messages.length-10} earlier messages`)),console.log(""),console.log(a.dim(` Resume with: mc --continue ${li(n.id)}`)),console.log("")}l(cf,"sessionsShowCommand");function lf(s){let e=new Lt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.delete(o.id);console.log(n?a.green(` \u2713 Deleted session ${li(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(lf,"sessionsDeleteCommand");function uf(s=30){let e=new Lt,t=s*24*60*60*1e3,{deleted:o,remaining:n}=e.prune(t);console.log(o===0?a.dim(` No sessions older than ${s} days.`):a.green(` \u2713 Pruned ${o} session(s) older than ${s} days.`)),console.log(a.dim(` ${n} session(s) remaining.`))}l(uf,"sessionsPruneCommand");un();W();Q();ee();var il=class{static{l(this,"ScheduleApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/schedules`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async create(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify({prompt:e.prompt,cronExpression:e.cron,model:e.model,autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPR,workspace:e.workspace}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,scheduleId:o.id||o.scheduleId}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async list(){try{let e=await fetch(this.baseUrl,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).schedules||[]).map($k):[]}catch{return[]}}async delete(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:t.ok,error:t.ok?void 0:`HTTP ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async togglePause(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/${t?"pause":"resume"}`,{method:"POST",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:o.ok,error:o.ok?void 0:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};function Pn(){let s=K(),t=ge()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new il(s.agentsUrl,t)}l(Pn,"getClient");async function al(s){Ck(s.cron)||(console.error(a.red(` \u274C Invalid cron expression: "${s.cron}"`)),console.log(a.dim(" Expected 5-field format: minute hour day-of-month month day-of-week")),console.log(a.dim(' Example: "0 9 * * 1" = Every Monday at 9:00 AM')),process.exit(4));let t=await Pn().create(s);t.success||(console.error(a.red(` \u274C Failed to create schedule: ${t.error}`)),process.exit(1)),console.log(""),console.log(a.bold(" \u23F0 Schedule created")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` ID: ${a.cyan(t.scheduleId)}`),console.log(` Prompt: "${s.prompt.substring(0,50)}${s.prompt.length>50?"...":""}"`),console.log(` Cron: ${s.cron} (${_k(s.cron)})`),console.log(` Auto-PR: ${s.autoPR?a.green("Yes"):"No"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Manage: ${a.dim("mc schedule list")}`),console.log("")}l(al,"scheduleCreate");async function df(){let e=await Pn().list();if(e.length===0){console.log(a.dim(" No scheduled jobs found.")),console.log(a.dim(' Create one: mc schedule "your task" --cron "0 9 * * 1"'));return}let t=" "+"\u2500".repeat(90);console.log(t),console.log(a.bold(` ${"ID".padEnd(16)} ${"Status".padEnd(10)} ${"Cron".padEnd(16)} ${"Next Run".padEnd(20)} Prompt`)),console.log(t);for(let o of e){let n=o.status==="active"?a.green("\u25B6 Active"):a.yellow("\u23F8 Paused"),r=o.nextRunAt?o.nextRunAt.toLocaleString():"\u2014",i=o.prompt.length>30?`"${o.prompt.substring(0,28)}..."`:`"${o.prompt}"`;console.log(` ${o.id.padEnd(16)} ${n.padEnd(10)} ${o.cronExpression.padEnd(16)} ${r.padEnd(20)} ${i}`)}console.log(t)}l(df,"scheduleList");async function pf(s){let t=await Pn().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(pf,"scheduleDelete");async function mf(s){let t=await Pn().togglePause(s,!0);t.success?console.log(a.yellow(` \u23F8 Schedule ${s} paused.`)):console.error(a.red(` \u274C Failed to pause schedule: ${t.error}`))}l(mf,"schedulePause");async function gf(s){let t=await Pn().togglePause(s,!1);t.success?console.log(a.green(` \u25B6 Schedule ${s} resumed.`)):console.error(a.red(` \u274C Failed to resume schedule: ${t.error}`))}l(gf,"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();if(!e)return!1;if(e.startsWith("@"))return/^@(yearly|annually|monthly|weekly|daily|midnight|hourly|every\s+\d+[smh])$/.test(e);let t=e.split(/\s+/);if(t.length!==5&&t.length!==6)return!1;let o=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return t.every(n=>o.test(n))}l(Ck,"validateCron");function _k(s){let e=s.trim();if(e.startsWith("@"))return e;let t=e.split(/\s+/);if(t.length===6&&t[0]==="0"&&(t=t.slice(1)),t.length!==5)return s;let[o,n,r,i,c]=t,u=t.join(" ");return u==="0 * * * *"?"every hour":u==="*/5 * * * *"?"every 5 minutes":u==="*/15 * * * *"?"every 15 minutes":u==="*/30 * * * *"?"every 30 minutes":o!=="*"&&n!=="*"&&r==="*"&&i==="*"&&c==="*"?`daily at ${n.padStart(2,"0")}:${o.padStart(2,"0")}`:o!=="*"&&n!=="*"&&r==="*"&&i==="*"&&c!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[c]||`day ${c}`}s at ${n.padStart(2,"0")}:${o.padStart(2,"0")}`:s}l(_k,"describeCron");Rc();Ec();fn();var ke=b(require("node:fs"),1),_t=b(require("node:path"),1),Ho=require("node:child_process");W();Ke();Q();ee();async function ff(s){let e=await Fe(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=ge(),o=K(),n,r;if(s.pr?(n=await Rk(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Ho.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Ho.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Ho.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes")),!n.trim()){console.log(a.dim(" No changes to review."));return}let i=Ek(s.workspace),c=s.focus?s.focus.split(",").map(y=>y.trim()):[],u=Fk(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new xe({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",y=>{y.type==="streaming_chunk"&&(p+=y.content,s.output==="text"&&process.stdout.write(y.content))});try{await d.run(u)}catch(y){console.error(a.red(` \u274C Review failed: ${y instanceof Error?y.message:y}`)),process.exit(1)}let g=yf(p);switch(s.output){case"json":{let y=new gs;console.log(JSON.stringify({source:r,findings:g,summary:`Found ${g.length} issue(s)`},null,2));break}case"sarif":{let y=new fs(g,s.workspace);console.log(y.formatFindings(g));break}case"github":{for(let y of g){let S=y.severity==="high"?"error":y.severity==="medium"?"warning":"notice";console.log(`::${S} file=${y.file},line=${y.line}::${y.message}`)}break}case"text":default:g.length>0&&(console.log(""),bf(g));break}s.postComments&&s.pr&&await Ak(s.pr,g,s.workspace),s.autoFix&&g.some(y=>y.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),wf(g,s.workspace));let m={high:3,medium:2,low:1,info:0},f=m[s.severityThreshold]||3;g.some(y=>(m[y.severity]||0)>=f)&&process.exit(1)}l(ff,"reviewCommand");async function hf(s){let e=await Fe(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=ge(),o=K(),n=_t.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=Pk(n,[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java"]):r=[n]:(console.error(a.red(` \u274C Target not found: ${s.target}`)),process.exit(4)),r.length===0){console.log(a.dim(" No source files found to scan."));return}console.log(""),console.log(a.bold(` \u{1F50D} Bug Finder \u2014 scanning ${r.length} file(s)`)),console.log(a.dim(` Model: ${s.model}`)),console.log("");let i=1e5,c="",u=[];for(let D of r){let C=ke.readFileSync(D,"utf8");if(c.length+C.length>i)break;let x=_t.relative(s.workspace,D);c+=`
|
|
666
|
-
|
|
667
|
-
${
|
|
668
|
-
|
|
665
|
+
`.trim()}l(kh,"generateHtmlPreview");var hl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=vh.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(kh(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new bc.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===dt.OPEN&&t.send("reload")}},Dh=new hl;H();function ov(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(ov,"formatDate");function yi(s){return s.substring(0,8)}l(yi,"formatShortId");function sv(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(sv,"truncatePath");function Sh(){let e=new Ht().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")(yi(t.id)),n=sv(t.workspace),r=String(t.turnCount).padEnd(8),i=ov(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(Sh,"sessionsListCommand");function xh(s){let e=new Ht,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 ${yi(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 ${yi(n.id)}`)),console.log("")}l(xh,"sessionsShowCommand");function _h(s){let e=new Ht,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 ${yi(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(_h,"sessionsDeleteCommand");function $h(s=30){let e=new Ht,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($h,"sessionsPruneCommand");gn();H();Eh();var Fh=require("node:os"),Th=require("node:path"),Ln=require("node:fs/promises");var J1=(0,Th.join)((0,Fh.homedir)(),".monkeyscode","runs"),z1=30*24*60*60*1e3;var cv=require("node:fs"),lv=require("node:path");var Rh=require("node:child_process"),uv=require("node:path"),dv=require("node:crypto");var pv="https://api.monkeyscode.com",Ue=class extends Error{static{l(this,"WorkspaceApiError")}status;constructor(e,t){super(e),this.name="WorkspaceApiError",this.status=t}},Rs=class extends Ue{static{l(this,"WorkspaceFileConflictError")}path;currentSha256;constructor(e,t,o){super(t,409),this.name="WorkspaceFileConflictError",this.path=e,this.currentSha256=o}};function gl(s){return s.apiBaseUrl||pv}l(gl,"baseOf");async function wi(s,e){try{let t=await s.json();if(t&&typeof t.error=="string"&&t.error)return{message:t.error,sha:t.current_sha256??t.sha256}}catch{}return{message:`${e} (HTTP ${s.status})`}}l(wi,"errorMessage");async function Ah(s,e,t,o,n){let i=await(s.fetch??fetch)(`${gl(s)}/v1/workspaces/${encodeURIComponent(s.id)}${t}`,{method:e,headers:{Authorization:`Bearer ${s.apiKey}`,Accept:"application/json",...o!==void 0?{"Content-Type":"application/json"}:{}},...o!==void 0?{body:JSON.stringify(o)}:{}});if(!i.ok){let{message:c}=await wi(i,n);throw new Ue(c,i.status)}return await i.json()}l(Ah,"request");async function yl(s,e){if(!e.command.trim())throw new Ue("command is required",400);return await Ah(s,"POST","/exec",{command:e.command,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.timeoutSecs!==void 0?{timeoutSecs:e.timeoutSecs}:{},...e.stdin!==void 0?{stdin:e.stdin}:{}},"Command failed")}l(yl,"execInWorkspace");async function wl(s,e){if(!e.trim())throw new Ue("path is required",400);let t=s.fetch??fetch,o=`${gl(s)}/v1/workspaces/${encodeURIComponent(s.id)}/files?path=${encodeURIComponent(e)}`,n=await t(o,{headers:{Authorization:`Bearer ${s.apiKey}`,Accept:"application/json"}});if(!n.ok){let{message:r}=await wi(n,"Read failed");throw new Ue(r,n.status)}return await n.json()}l(wl,"readWorkspaceFile");async function bl(s,e,t,o){if(!e.trim())throw new Ue("path is required",400);let r=await(s.fetch??fetch)(`${gl(s)}/v1/workspaces/${encodeURIComponent(s.id)}/files`,{method:"PUT",headers:{Authorization:`Bearer ${s.apiKey}`,Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({path:e,content:t,...o!==void 0?{expectedSha256:o}:{}})});if(r.status===409){let{message:i,sha:c}=await wi(r,"File modified since read");throw new Rs(e,i,c)}if(!r.ok){let{message:i}=await wi(r,"Write failed");throw new Ue(i,r.status)}return await r.json()}l(bl,"writeWorkspaceFile");async function kl(s,e){if(!e.query.trim())throw new Ue("options.query is required",400);return await Ah(s,"POST","/search",{options:e},"Search failed")}l(kl,"searchWorkspace");var mv="wss://code.monkeyscode.com";function vl(s){let{id:e,apiKey:t,ptyBaseUrl:o=mv,cols:n=80,rows:r=24}=s,i=s.WebSocketImpl??(typeof WebSocket<"u"?WebSocket:void 0);if(!i)return Promise.reject(new Error('No WebSocket implementation available. In Node, pass WebSocketImpl (e.g. from the "ws" package).'));let c=`${o.replace(/\/$/,"")}/v1/workspaces/${encodeURIComponent(e)}/pty?cols=${n}&rows=${r}`,u=new i(c,[`monkeyscode.bearer.${t}`]),d=new Set,p=new Set,f=new Set,m=!1,h=!1,g=null,y,x,v=l((S,k,C)=>{if(!(!m&&h)){m=!1;for(let J of p)try{J(S,k,C)}catch{}p.clear(),d.clear(),f.clear()}},"finish"),_={onData(S){return d.add(S),()=>d.delete(S)},onClose(S){return p.add(S),()=>p.delete(S)},onExit(S){let k=l((C,J)=>{C==="exit"&&S(J??0)},"wrapped");return p.add(k),()=>p.delete(k)},onError(S){return f.add(S),()=>f.delete(S)},send(S){m&&u.send(JSON.stringify({type:"data",data:S}))},resize(S,k){m&&u.send(JSON.stringify({type:"resize",cols:S,rows:k}))},close(){if(m){g="local";try{u.close()}catch{}}},get isOpen(){return m}};return new Promise((S,k)=>{u.onopen=()=>{m=!0,h=!0,S(_)},u.onmessage=C=>{let J;try{J=JSON.parse(String(C.data))}catch{return}switch(J.type){case"data":if(typeof J.data=="string")for(let O of d)try{O(J.data)}catch{}break;case"exit":g="exit",y=J.code??0;break;case"error":{let O=J.msg||"terminal error";g=/revok|unauthor|forbidden/i.test(O)?"revoked":"error",x=O;for(let ce of f)try{ce(O)}catch{}break}case"ping":m&&u.send(JSON.stringify({type:"ping"}));break;default:break}},u.onerror=()=>{if(!h){h=!0,k(new Error("Failed to connect to workspace terminal (authorization or network failure)"));return}for(let C of f)try{C("terminal connection error")}catch{}},u.onclose=()=>{if(!h){h=!0,k(new Error("Workspace terminal closed before it opened"));return}v(g??"transport",y,x)}})}l(vl,"connectWorkspacePty");Ph();var Ve={ok:0,failure:1,usage:2,auth:3};async function gv(){let{loadSettings:s}=await Promise.resolve().then(()=>(Q(),we)),{getAccessToken:e}=await Promise.resolve().then(()=>(ee(),he)),t=await e();return t?{apiKey:t,apiBaseUrl:s().apiUrl}:null}l(gv,"resolveConnection");function bi(s,e){return{id:s,apiKey:e.apiKey,apiBaseUrl:e.apiBaseUrl}}l(bi,"refFor");async function Ft(){let s=await gv();return s||(console.error(a.red("Not authenticated.")+" Run `mc auth login`."),process.exit(Ve.auth)),s}l(Ft,"requireConnection");async function Bn(s,e,t,o){let n=await fetch(`${s.apiBaseUrl}/v1/workspaces${t}`,{method:e,headers:{Authorization:`Bearer ${s.apiKey}`,Accept:"application/json",...o!==void 0?{"Content-Type":"application/json"}:{}},...o!==void 0?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(3e4)});if(!n.ok){let i=`HTTP ${n.status}`;try{let c=await n.json();c?.error&&(i=c.error)}catch{}throw new Ue(i,n.status)}let r=await n.text();return r?JSON.parse(r):{}}l(Bn,"platformFetch");async function yv(s){return await Bn(s,"GET","")}l(yv,"listWorkspaces");async function wv(s,e){return await Bn(s,"POST","",{name:e.name,compute_tier:e.compute_tier??"small",...e.repo_url?{repo_url:e.repo_url}:{},...e.branch?{branch:e.branch}:{}})}l(wv,"createWorkspace");function bv(s){switch(s.toLowerCase()){case"running":return a.green("\u25CF");case"starting":case"provisioning":case"stopping":return a.yellow("\u25D0");case"stopped":return a.dim("\u25CB");case"failed":case"error":return a.red("\u2717");default:return a.dim("?")}}l(bv,"statusIcon");function kv(s){if(s.length===0){console.log(a.dim(" No cloud workspaces. Create one with `mc cloud create <name>`."));return}let t=" "+(process.platform!=="win32"||process.env.WT_SESSION?"\u2500":"-").repeat(90);console.log(t),console.log(a.bold(` ${"ID".padEnd(38)} ${"Name".padEnd(20)} ${"Status".padEnd(14)} ${"Tier".padEnd(8)} Region`)),console.log(t);for(let n of s){let r=`${bv(n.status)} ${n.status}`;console.log(` ${n.id.padEnd(38)} ${(n.name??"\u2014").slice(0,19).padEnd(20)} ${r.padEnd(14+(r.length-`${n.status}`.length-2))} ${(n.compute_tier??"\u2014").padEnd(8)} ${n.region??"\u2014"}`)}console.log(t);let o=s.filter(n=>n.status.toLowerCase()==="running").length;o>0&&console.log(a.yellow(` ${o} running \u2014 billing per minute until stopped.`))}l(kv,"printWorkspacesTable");async function Ih(s={}){let e=await Ft();try{let t=await yv(e);if(s.output==="json"){console.log(JSON.stringify(t,null,2));return}kv(t)}catch(t){to(t,"Failed to list workspaces")}}l(Ih,"cloudList");async function Mh(s,e={}){let t=await Ft();s?.trim()||(console.error(a.red("A workspace name is required.")),process.exit(Ve.usage));try{let o=await wv(t,{name:s.trim(),compute_tier:e.tier,repo_url:e.repo,branch:e.branch});if(e.output==="json"){console.log(JSON.stringify(o,null,2));return}console.log(a.green("\u2713")+` Workspace created: ${a.bold(o.id)}`),console.log(a.yellow(" Started automatically \u2014 billing per minute. Stop it with ")+a.bold(`mc cloud stop ${o.id}`))}catch(o){to(o,"Failed to create workspace")}}l(Mh,"cloudCreate");async function Oh(s){let e=await Ft();try{await Bn(e,"POST",`/${encodeURIComponent(s)}/start`,{}),console.log(a.green("\u2713")+` Starting ${s} \u2014 billing per minute once running.`)}catch(t){to(t,"Failed to start workspace")}}l(Oh,"cloudStart");async function jh(s){let e=await Ft();try{await Bn(e,"POST",`/${encodeURIComponent(s)}/stop`,{}),console.log(a.green("\u2713")+` Stopped ${s}. The volume is kept.`)}catch(t){to(t,"Failed to stop workspace")}}l(jh,"cloudStop");async function Nh(s,e={}){let t=await Ft();if(!e.yes&&(process.stdin.isTTY||(console.error(a.red("Refusing to delete without confirmation.")+" Pass --yes in a non-interactive shell."),process.exit(Ve.usage)),!await Dv(`Delete workspace ${s}? This destroys its volume and cannot be undone.`))){console.log("Aborted.");return}try{await Bn(t,"DELETE",`/${encodeURIComponent(s)}`),console.log(a.green("\u2713")+` Deleted ${s}.`)}catch(o){to(o,"Failed to delete workspace")}}l(Nh,"cloudRemove");async function Lh(s,e,t={}){let o=await Ft(),n=e.join(" ").trim();n||(console.error(a.red("A command is required:")+" mc cloud exec <id> -- <command>"),process.exit(Ve.usage));try{let r=await yl(bi(s,o),{command:n,cwd:t.cwd,timeoutSecs:t.timeout?parseInt(t.timeout,10):void 0});t.output==="json"?console.log(JSON.stringify(r,null,2)):(r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.truncated&&console.error(a.yellow(`
|
|
666
|
+
[output truncated by the server]`)),r.timed_out&&console.error(a.red(`
|
|
667
|
+
[timed out after ${r.duration_ms}ms]`))),process.exit(r.exit_code)}catch(r){to(r,"Command failed")}}l(Lh,"cloudExec");async function Bh(s,e){let t=await Ft();try{let o=await wl(bi(s,t),e);o.binary&&(console.error(a.yellow(`${e} is binary (${o.size} bytes) \u2014 not printing.`)),process.exit(Ve.failure)),process.stdout.write(o.content)}catch(o){to(o,"Failed to read file")}}l(Bh,"cloudCat");async function Uh(s,e,t={}){let o=await Ft();try{let n=t.content!==void 0?t.content:await vv(),r=await bl(bi(s,o),e,n);console.log(a.green("\u2713")+` Wrote ${e}${r.size!==void 0?` (${r.size} bytes)`:""}`)}catch(n){n instanceof Rs&&(console.error(a.red(`${e} changed in the workspace since it was read.`)),process.exit(Ve.failure)),to(n,"Failed to write file")}}l(Uh,"cloudPut");async function Wh(s,e,t={}){let o=await Ft();try{let n=await kl(bi(s,o),{query:e,path:t.path,regex:t.regex,caseSensitive:t.caseSensitive,includes:t.include});if(t.output==="json"){console.log(JSON.stringify(n,null,2));return}for(let r of n.matches)console.log(`${a.cyan(r.file)}:${a.dim(String(r.line))}: ${r.content}`);n.matches.length===0&&console.log(a.dim(" No matches.")),n.truncated&&console.error(a.yellow(` [truncated \u2014 ${n.total} total matches]`))}catch(n){to(n,"Search failed")}}l(Wh,"cloudGrep");async function Hh(s){let e=await Ft();(!process.stdin.isTTY||!process.stdout.isTTY)&&(console.error(a.red("`mc cloud ssh` needs an interactive terminal.")),console.error(a.dim("In a script, use `mc cloud exec <id> -- <command>` instead.")),process.exit(Ve.usage));let t=process.env.MONKEYSCODE_PTY_URL||e.apiBaseUrl.replace(/^http/,"ws").replace("//api.","//code."),o;try{o=await vl({id:s,apiKey:e.apiKey,ptyBaseUrl:t,cols:process.stdout.columns??80,rows:process.stdout.rows??24})}catch(u){console.error(a.red("Could not open a terminal: ")+(u instanceof Error?u.message:String(u))),console.error(a.dim("Is the workspace running? `mc cloud start "+s+"`")),process.exit(Ve.failure)}let n=process.stdin.isRaw,r=l(u=>o.send(u.toString("binary")),"onStdin"),i=l(()=>o.resize(process.stdout.columns??80,process.stdout.rows??24),"onResize"),c=l(()=>{process.stdin.off("data",r),process.stdout.off("resize",i),process.stdin.isTTY&&!n&&process.stdin.setRawMode(!1),process.stdin.pause()},"restore");try{process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",r),process.stdout.on("resize",i),o.onData(d=>process.stdout.write(Buffer.from(d,"binary")));let u=await new Promise(d=>{o.onClose((p,f,m)=>{p==="revoked"?(process.stderr.write(a.yellow(`\r
|
|
668
|
+
[session revoked \u2014 the workspace may have stopped]\r
|
|
669
|
+
`)),d(Ve.failure)):p==="transport"?(process.stderr.write(a.yellow(`\r
|
|
670
|
+
[connection lost]\r
|
|
671
|
+
`)),d(Ve.failure)):p==="error"?(process.stderr.write(a.red(`\r
|
|
672
|
+
[terminal error: ${m??"unknown"}]\r
|
|
673
|
+
`)),d(Ve.failure)):d(f??Ve.ok)})});c(),process.exit(u)}finally{c()}}l(Hh,"cloudSsh");function to(s,e){let t=s instanceof Ue||s instanceof Error?s.message:String(s);console.error(a.red(`${e}: `)+t),process.exit(Ve.failure)}l(to,"fail");async function vv(){let s=[];for await(let e of process.stdin)s.push(Buffer.from(e));return Buffer.concat(s).toString("utf8")}l(vv,"readStdin");function Dv(s){return new Promise(e=>{process.stdout.write(`${s} ${a.dim("[y/N]")} `),process.stdin.resume(),process.stdin.once("data",t=>{process.stdin.pause(),e(/^y(es)?$/i.test(t.toString().trim()))})})}l(Dv,"confirm");H();Q();ee();var Dl=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(Sv):[]}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 Un(){let s=Y(),t=fe()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new Dl(s.agentsUrl,t)}l(Un,"getClient");async function Sl(s){xv(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 Un().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} (${_v(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 Gh(){let e=await Un().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(Gh,"scheduleList");async function qh(s){let t=await Un().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(qh,"scheduleDelete");async function Vh(s){let t=await Un().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(Vh,"schedulePause");async function Jh(s){let t=await Un().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(Jh,"scheduleResume");function Sv(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(Sv,"parseSchedule");function xv(s){let e=s.trim();if(!e)return!1;if(e.startsWith("@"))return/^@(yearly|annually|monthly|weekly|daily|midnight|hourly|every\s+\d+[smh])$/.test(e);let t=e.split(/\s+/);if(t.length!==5&&t.length!==6)return!1;let o=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return t.every(n=>o.test(n))}l(xv,"validateCron");function _v(s){let e=s.trim();if(e.startsWith("@"))return e;let t=e.split(/\s+/);if(t.length===6&&t[0]==="0"&&(t=t.slice(1)),t.length!==5)return s;let[o,n,r,i,c]=t,u=t.join(" ");return u==="0 * * * *"?"every hour":u==="*/5 * * * *"?"every 5 minutes":u==="*/15 * * * *"?"every 15 minutes":u==="*/30 * * * *"?"every 30 minutes":o!=="*"&&n!=="*"&&r==="*"&&i==="*"&&c==="*"?`daily at ${n.padStart(2,"0")}:${o.padStart(2,"0")}`:o!=="*"&&n!=="*"&&r==="*"&&i==="*"&&c!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[c]||`day ${c}`}s at ${n.padStart(2,"0")}:${o.padStart(2,"0")}`:s}l(_v,"describeCron");Uc();Nc();vn();var ve=w(require("node:fs"),1),Tt=w(require("node:path"),1),zo=require("node:child_process");H();Xe();Q();ee();async function zh(s){let e=await Fe(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=fe(),o=Y(),n,r;if(s.pr?(n=await Fv(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,zo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,zo.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,zo.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=$v(s.workspace),c=s.focus?s.focus.split(",").map(y=>y.trim()):[],u=Cv(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new xe({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",y=>{y.type==="streaming_chunk"&&(p+=y.content,s.output==="text"&&process.stdout.write(y.content))});try{await d.run(u)}catch(y){console.error(a.red(` \u274C Review failed: ${y instanceof Error?y.message:y}`)),process.exit(1)}let f=Yh(p);switch(s.output){case"json":{let y=new bs;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let y=new ks(f,s.workspace);console.log(y.formatFindings(f));break}case"github":{for(let y of f){let x=y.severity==="high"?"error":y.severity==="medium"?"warning":"notice";console.log(`::${x} file=${y.file},line=${y.line}::${y.message}`)}break}case"text":default:f.length>0&&(console.log(""),Xh(f));break}s.postComments&&s.pr&&await Tv(s.pr,f,s.workspace),s.autoFix&&f.some(y=>y.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),Qh(f,s.workspace));let m={high:3,medium:2,low:1,info:0},h=m[s.severityThreshold]||3;f.some(y=>(m[y.severity]||0)>=h)&&process.exit(1)}l(zh,"reviewCommand");async function Kh(s){let e=await Fe(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=fe(),o=Y(),n=Tt.resolve(s.workspace,s.target),r=[];if(ve.existsSync(n)?ve.statSync(n).isDirectory()?r=Rv(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 _=ve.readFileSync(v,"utf8");if(c.length+_.length>i)break;let S=Tt.relative(s.workspace,v);c+=`
|
|
674
|
+
--- ${S} ---
|
|
675
|
+
${_}
|
|
676
|
+
`,u.push(S)}let d=s.focus?s.focus.split(",").map(v=>v.trim()):[],p=Ev(c,u,d),f=new xe({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),m="";f.on("event",v=>{v.type==="streaming_chunk"&&(m+=v.content)});try{await f.run(p)}catch(v){console.error(a.red(` \u274C Bug scan failed: ${v instanceof Error?v.message:v}`)),process.exit(1)}let h=Yh(m);switch(s.output){case"json":console.log(JSON.stringify({scannedFiles:u,findings:h,summary:xl(h)},null,2));break;case"sarif":{let v=new ks(h,s.workspace);console.log(v.formatFindings(h));break}case"github":for(let v of h){let _=v.severity==="high"?"error":v.severity==="medium"?"warning":"notice";console.log(`::${_} file=${v.file},line=${v.line}::${v.message}`)}break;case"text":default:Xh(h);break}s.autoFix&&h.some(v=>v.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),Qh(h,s.workspace));let g={high:3,medium:2,low:1,info:0},y=g[s.severityThreshold]||3;h.some(v=>(g[v.severity]||0)>=y)&&process.exit(1)}l(Kh,"bugfindCommand");function $v(s){let e=Tt.join(s,".monkeyscode","review-rules.md");return ve.existsSync(e)?ve.readFileSync(e,"utf8"):""}l($v,"loadReviewRules");function Cv(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.
|
|
669
677
|
|
|
670
678
|
For each finding, output in this EXACT format (one per line):
|
|
671
679
|
[SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
|
|
@@ -680,7 +688,7 @@ ${o}
|
|
|
680
688
|
`),n+=`Diff:
|
|
681
689
|
\`\`\`diff
|
|
682
690
|
${s}
|
|
683
|
-
\`\`\``,n}l(
|
|
691
|
+
\`\`\``,n}l(Cv,"buildReviewPrompt");function Ev(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.
|
|
684
692
|
|
|
685
693
|
For each finding, output in this EXACT format (one per line):
|
|
686
694
|
[SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
|
|
@@ -699,27 +707,27 @@ Focus on:
|
|
|
699
707
|
`),o+=`Files to scan: ${e.join(", ")}
|
|
700
708
|
|
|
701
709
|
`,o+=`Source code:
|
|
702
|
-
${s}`,o}l(
|
|
703
|
-
`);for(let o=0;o<t.length;o++){let r=t[o].match(/\[SEVERITY:(HIGH|MEDIUM|LOW|INFO)\]\s*\[FILE:([^\]]+)\]\s*\[LINE:(\d+)\]\s*(.*)/i);if(r){let i={severity:r[1].toLowerCase(),file:r[2],line:parseInt(r[3],10),message:r[4].trim()};if(o+1<t.length){let c=t[o+1].match(/\[FIX:\d+\]\s*(.*)/);c&&(i.fix=c[1],o++)}e.push(i)}}return e}l(
|
|
704
|
-
`);o.line>0&&o.line<=r.length&&(r[o.line-1]=o.fix,
|
|
705
|
-
`)),t++,console.log(a.dim(` \u2713 Fixed ${o.file}:${o.line}`)))}catch{console.log(a.yellow(` \u26A0 Could not apply fix to ${o.file}:${o.line}`))}}console.log(` Applied ${t} fix(es).`)}l(
|
|
706
|
-
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(
|
|
710
|
+
${s}`,o}l(Ev,"buildBugfindPrompt");function Yh(s){let e=[],t=s.split(`
|
|
711
|
+
`);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(Yh,"parseFindings");function Xh(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(` ${xl(s)}`),console.log("")}l(Xh,"printFindingsTable");function xl(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(xl,"formatSeveritySummary");function Qh(s,e){let t=0;for(let o of s){if(!o.fix)continue;let n=Tt.resolve(e,o.file);if(ve.existsSync(n))try{let r=ve.readFileSync(n,"utf8").split(`
|
|
712
|
+
`);o.line>0&&o.line<=r.length&&(r[o.line-1]=o.fix,ve.writeFileSync(n,r.join(`
|
|
713
|
+
`)),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(Qh,"applyFixes");async function Fv(s,e){let t=Zh(e),o=eg();if(!o){console.log(a.dim(" No GitHub/GitLab token found. Using local git diff against main."));try{return(0,zo.execSync)("git diff main...HEAD",{cwd:e,encoding:"utf8"})}catch{return(0,zo.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(`
|
|
714
|
+
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(Fv,"fetchPRDiff");async function Tv(s,e,t){let o=Zh(t),n=eg();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(`
|
|
707
715
|
`);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
|
|
708
716
|
|
|
709
717
|
${r}
|
|
710
718
|
|
|
711
|
-
${
|
|
719
|
+
${xl(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(Tv,"postReviewComments");function Zh(s){try{let e=(0,zo.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(Zh,"getGitRemote");function eg(){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=Tt.join(process.cwd(),".monkeyscode","config.json");if(ve.existsSync(s)){let e=JSON.parse(ve.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}try{let s=Tt.join(process.env.HOME||process.env.USERPROFILE||"",".monkeyscode","config.json");if(ve.existsSync(s)){let e=JSON.parse(ve.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}return null}l(eg,"getGitToken");function Rv(s,e){let t=[];function n(r){if(t.length>=50)return;let i=ve.readdirSync(r,{withFileTypes:!0});for(let c of i){if(t.length>=50)return;let u=Tt.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(Rv,"collectFiles");wf();rf();globalThis.__mcChalk=a;var Fl="0.1.11",Yo="auto";function ng(s){let e=Ho(s);return{defaultModel:e.get("model"),defaultMode:e.get("defaultMode"),maxTokens:e.get("maxTokens")}}l(ng,"loadConfig");var V=new ql;V.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
|
|
712
720
|
Runs independently of the IDE and Agent Manager.
|
|
713
|
-
Connects directly to model-proxy via SSE streaming.`).version(ml);z.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",qo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Rt("-o, --output <format>","Output format").choices(["text","json","jsonl","diff","markdown","github","azure","sarif","stream"]).default("text")).option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("--continue","Resume the last session",!1).option("--auto-approve","Auto-approve all tool calls",!1).option("--approve-for-me","Smart auto-approval (safe=auto, risky=prompt, dangerous=block)",!1).option("--yolo","Bypass all permission checks (requires explicit opt-in)",!1).addOption(new Rt("--permission-mode <mode>","Permission mode").choices(["default","plan","ask","acceptEdits","bypassPermissions"]).default("default")).option("--allowed-tools <tools>","Comma-separated list of allowed tool names","").option("--denied-tools <tools>","Comma-separated list of denied tool names","").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new Rt("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Rt("--sandbox-provider <provider>","Sandbox provider override").choices(["auto","bubblewrap","sandbox-exec","docker","windows-sandbox"])).option("--no-hooks","Disable all lifecycle hooks").option("--hook-timeout <ms>","Hook timeout in milliseconds","10000").option("--no-web","Disable web search (air-gapped mode)").option("--auto-branch","Create a new branch for changes",!1).option("--auto-commit","Auto-commit changes after successful run",!1).option("--auto-pr","Create a pull request after background job completes",!1).option("--worktree","Run agent in an isolated git worktree",!1).option("--resume <job-id>","Resume from a completed cloud job").option("--profile <name>","Auth profile to use","default").option("--endpoint <url>","Custom model gateway URL").option("--ca-cert <path>","Custom CA certificate for corporate proxies").option("--offline","Offline mode \u2014 no internet, local models only",!1).option("--accessible","Screen reader-friendly output (no ANSI, no spinners)",!1).option("--screen-reader","Alias for --accessible",!1).option("--max-cost <dollars>","Maximum session cost in dollars (e.g. 2.00)").option("--max-tokens <count>","Maximum total tokens (input + output)").option("--timeout <ms>","Headless timeout in milliseconds (default: 300000)","300000").action(async(s,e)=>{let t=L.resolve(e.workspace),o=$f(t),n=s||e.prompt;if(n&&n.startsWith("/"))switch(n.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":n=void 0;break;case"/version":case"/v":console.log(ml),process.exit(0);break;case"/doctor":await ln(),process.exit(0);break;case"/exit":case"/quit":case"/q":process.exit(0);break;default:break}if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=wt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await hm(c)});var Mn=z.command("auth").description("Manage authentication");Mn.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()});Mn.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ka(s.profile));Mn.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>fa(s,e.profile));Mn.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await er(s.profile));Mn.command("refresh").description("Manually refresh the access token").action(async()=>await ha());z.command("status").description("Show account and agent status").action(async()=>{let s=$f(),e=new Co,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),o=t();e.printBanner("System Status"),await er(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});z.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>ln(s));z.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Nm(s));z.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Km(s));z.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Ym(s,e));z.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";sg({since:s.since,review:s.review,mode:e})});var In=z.command("config").description("Manage CLI configuration");In.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=L.resolve(t.workspace),n=No(o),r=t.project?"project":"global",i=e;e==="true"?i=!0:e==="false"?i=!1:isNaN(Number(e))||(i=Number(e));let c=n.set(s,i,r);c&&(console.error(` \u26A0\uFE0F ${c}`),process.exit(1)),console.log(` Set ${s} = ${e} [${r}]`)});In.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=No(L.resolve(e.workspace));if(s){let o=t.getResolved(s);console.log(` ${s} = ${JSON.stringify(o.value)} [${o.source}]`)}else console.log(JSON.stringify(t.getConfig(),null,2))});In.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=No(L.resolve(s.workspace));Tm(e)});In.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{No().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});In.command("path").description("Show config file locations").action(()=>{let s=A(),t=No().getPaths();console.log(` Global: ${t.global}`),console.log(` Project: ${t.project}`),console.log(` Data: ${s.data}`),console.log(` Logs: ${s.logs}`),console.log(` PID: ${s.pidFile}`)});z.command("index [path]").description("Index a workspace for context retrieval").option("--force","Force full re-index",!1).action(async(s,e)=>{let t=L.resolve(s||"."),o=new Co;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new po;o.startSpinner("Connecting to daemon...");try{await n.connect(),o.succeedSpinner("Connected"),o.startSpinner("Indexing workspace...");let r=await n.call("index",{workspace:t,force:e.force});o.succeedSpinner("Indexing complete"),console.log(` Files scanned: ${r.files_scanned}`),console.log(` Chunks created: ${r.chunks_created}`),console.log(` Duration: ${r.duration_ms}ms`),console.log("")}catch(r){o.failSpinner("Indexing failed"),console.error(` Error: ${r instanceof Error?r.message:r}`)}finally{n.disconnect()}});var jn=z.command("mcp").description("Manage MCP (Model Context Protocol) servers");jn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await Dm(L.resolve(s.workspace))});jn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{vm(L.resolve(o.workspace),s,e,t||[])});jn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{Sm(L.resolve(e.workspace),s)});jn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await xm(L.resolve(e.workspace),s)});jn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{$m(s)});var Gk=z.command("agents").description("View active agent sessions dashboard").action(async()=>{await Mc(!0)});Gk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Mc(!1)});var Cs=z.command("context").description("Semantic code search and workspace indexing");Cs.command("index").description("Index the current workspace for semantic search").action(async()=>{await Bo(["index"],{})});Cs.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await Bo(["search",s],{topK:e.topK})});Cs.command("status").description("Show index status and statistics").action(async()=>{await Bo(["status"],{})});Cs.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await Bo(["rebuild"],{})});Cs.command("related <file>").description("Find files related to a given file").action(async s=>{await Bo(["related",s],{})});Cs.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await Bo(["rank",s],{})});var Vo=z.command("triggers").description("Manage event-driven agent triggers");Vo.command("list").description("Show configured triggers").action(async()=>{await yo(["list"],{})});Vo.command("add").description("Add a new trigger").requiredOption("--event <type>","Event type (github.*, cron, file.changed)").requiredOption("--prompt <text>","Agent prompt when trigger fires").option("--name <name>","Trigger name").option("--schedule <cron>","Cron expression (for cron events)").option("--model <model>","Model to use").option("--filter <json>","Event filter (JSON)").action(async s=>{await yo(["add"],s)});Vo.command("remove <name>").description("Remove a trigger by name").action(async s=>{await yo(["remove",s],{})});Vo.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await yo(["test",s],{})});Vo.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await yo(["enable",s],{})});Vo.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await yo(["disable",s],{})});Vo.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await yo(["serve"],{port:s.port})});z.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish, pwsh)").option("--install","Show install instructions instead of the script").action((s,e)=>{let t=["bash","zsh","fish","pwsh"];t.includes(s)||(console.error(` Invalid shell: ${s}. Supported: ${t.join(", ")}`),process.exit(1));let o=s;e.install?(console.log(""),console.log(bm(o)),console.log("")):console.log(ym(o))});var pi=z.command("sessions").description("Manage saved conversation sessions");pi.command("list").description("List recent sessions").action(()=>af());pi.command("show <id>").description("Show session details").action(s=>cf(s));pi.command("delete <id>").description("Delete a session").action(s=>lf(s));pi.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{uf(parseInt(s.olderThan,10))});var Qt=z.command("jobs").description("Manage background agent jobs");Qt.command("list").description("List all background jobs").option("--status <status>","Filter by status: running, queued, completed, failed").option("--since <duration>","Show jobs since (e.g., 7d, 24h)").option("--limit <n>","Max results","20").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),fe)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Ne(o.agentsUrl,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,g)=>g.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);vc(d)});Qt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=wc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=kc(s);Wr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),fe)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Ne(o.agentsUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);Wr(i,c)});Qt.command("logs <id>").description("Full log output of a job").option("--follow","Live tail logs",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),fe)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Ne(n.agentsUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Hr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(xf(),Sf));u(s,`"${c.prompt.substring(0,60)}" \u2014 ${c.status}${c.duration?` in ${Math.round(c.duration/1e3)}s`:""}`,c.status==="completed")}}else{let c=await i.logs(s);for(let u of c)Hr(u)}});Qt.command("cancel <id>").description("Cancel a running or queued job").option("--force","Skip confirmation",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),fe)),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(g=>d.question(` Cancel job ${s}? [y/N] `,g));if(d.close(),p.toLowerCase()!=="y"){console.log(" Cancelled.");return}}let c=await new Ne(n.agentsUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Qt.command("retry <id>").description("Retry a failed job").option("--model <model>","Use a different model").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),fe)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.agentsUrl,r.access_token).retry(s,{model:e.model});c.success?(console.log(` \u{1F504} Job retried \u2192 new ID: ${c.jobId}`),c.branch&&console.log(` Branch: ${c.branch}`)):console.error(` \u274C Retry failed: ${c.error}`)});Qt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),fe)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Ne(o.agentsUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Qt.command("pull <id>").description("Pull changes from a completed job into current branch").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),fe)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.agentsUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),Dc(L.resolve(e.workspace),s,c.branch)});Qt.action(()=>{Qt.outputHelp()});var Go=z.command("schedule").description("Manage scheduled/recurring agent jobs").argument("[prompt]","Task prompt (shorthand for `schedule create`)").option("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".");Go.action(async(s,e)=>{s&&e.cron?await al({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:L.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Go.outputHelp()});Go.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await al({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:L.resolve(e.workspace)})});Go.command("list").description("List all scheduled jobs").action(async()=>{await df()});Go.command("delete <id>").description("Delete a scheduled job").action(async s=>{await pf(s)});Go.command("pause <id>").description("Pause a scheduled job").action(async s=>{await mf(s)});Go.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await gf(s)});var On=z.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");On.action(async(s,e)=>{s.length>0?await Gr({tasks:s,workspace:L.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):On.outputHelp()});On.command("spawn").description("Spawn a team of agents, each in its own worktree").argument("<tasks...>","Task prompts for each agent").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Gr({tasks:s,workspace:L.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});On.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{Fc(L.resolve(s.workspace))});On.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{Tc(L.resolve(e.workspace),s)});var di=z.command("worktrees").description("Manage git worktrees used by agent teams");di.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=ys(L.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});di.command("clean").description("Remove stale worktrees older than TTL").option("--ttl <hours>","TTL in hours (default: 24)","24").option("--force","Force removal",!1).option("--workspace <path>","Workspace path",".").action(s=>{let e=em({workspace:L.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});di.action(()=>{di.outputHelp()});var pl=z.command("messages").description("Cross-session messaging");pl.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),fe)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new gn(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),g=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)} ${g.padEnd(16)} "${m}"`)}console.log(c)});pl.action(()=>{pl.outputHelp()});var Cf=z.command("hooks").description("Manage lifecycle hooks");Cf.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Ic(L.resolve(s.workspace))});Cf.action(()=>{Ic(L.resolve("."))});var _f=z.command("models").description("Manage available models");_f.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),fe))).loadAuth();Fa(s?.org?.plan)});_f.action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),fe))).loadAuth();Fa(s?.org?.plan)});z.command("usage").description("Show monthly usage breakdown").action(async()=>{await Rm()});z.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=L.resolve(s.workspace),t=L.join(e,".monkeyscode","rules.md"),o=L.join(e,".monkeyscode","config.json");if(Y.existsSync(t)&&Y.existsSync(o)){console.log(""),console.log(a.yellow(" \u26A0\uFE0F .monkeyscode/ already exists.")),console.log(a.dim(` ${t}`)),console.log(a.dim(` ${o}`)),console.log(" Use `mc memory` to modify rules, `mc config set` for config."),console.log("");return}console.log(""),console.log(a.bold(" \u{1F435} Initializing MonkeysCode")),console.log("");let n=["# Project Conventions",""],r=L.join(e,"package.json"),i=L.join(e,"Cargo.toml"),c=L.join(e,"pyproject.toml"),u=L.join(e,"tsconfig.json"),d=L.join(e,"go.mod"),p=Y.readdirSync(e).filter(h=>h.endsWith(".csproj")),g="Unknown";if(Y.existsSync(r))try{let h=JSON.parse(Y.readFileSync(r,"utf8"));g=h.type==="module"?"TypeScript/ESM":"JavaScript/CJS",n.push(`## Language: ${g}`),h.scripts?.test&&n.push(`- Test command: \`${h.scripts.test}\``),h.scripts?.lint&&n.push(`- Lint command: \`${h.scripts.lint}\``),h.scripts?.build&&n.push(`- Build command: \`${h.scripts.build}\``),h.dependencies?.react&&n.push("- Framework: React"),h.dependencies?.next&&n.push("- Framework: Next.js"),h.dependencies?.express&&n.push("- Server: Express"),h.dependencies?.fastify&&n.push("- Server: Fastify"),n.push("")}catch{}Y.existsSync(u)&&(n.push("## TypeScript"),n.push("- Use strict TypeScript with explicit types"),n.push("- Prefer `interface` over `type` for object shapes"),n.push(""),g="TypeScript"),Y.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),g="Rust"),Y.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),g="Python"),Y.existsSync(d)&&(n.push("## Language: Go"),n.push("- Follow Go conventions (gofmt, error wrapping)"),n.push(""),g="Go"),p.length>0&&(n.push("## Language: C# / .NET"),n.push("- Follow .NET naming conventions (PascalCase)"),n.push(""),g="C#/.NET"),n.push("## Style"),n.push("- Keep functions small and focused"),n.push("- Write clear error messages"),n.push("- Add JSDoc/docstrings for public APIs"),n.push(""),n.push("## Testing"),n.push("- Write tests for all new functionality"),n.push("- Use descriptive test names"),n.push("");let m=n.join(`
|
|
714
|
-
`),
|
|
721
|
+
Connects directly to model-proxy via SSE streaming.`).version(Fl);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",Yo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Mt("-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 Mt("--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 Mt("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Mt("--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=B.resolve(e.workspace),o=ng(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(Fl),process.exit(0);break;case"/doctor":await hn(),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=vt(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 Hn=V.command("auth").description("Manage authentication");Hn.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 Fa(s.profile):s.email?await Sa():await Da()});Hn.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>Ta(s.profile));Hn.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>_a(s,e.profile));Hn.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await cr(s.profile));Hn.command("refresh").description("Manually refresh the access token").action(async()=>await $a());V.command("status").description("Show account and agent status").action(async()=>{let s=ng(),e=new Ro,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),we)),o=t();e.printBanner("System Status"),await cr(),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=>hn(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=>ef(s));V.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>pf(s));V.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>mf(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";kf({since:s.since,review:s.review,mode:e})});var Gn=V.command("config").description("Manage CLI configuration");Gn.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=B.resolve(t.workspace),n=Ho(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}]`)});Gn.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=Ho(B.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))});Gn.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=Ho(B.resolve(s.workspace));Vm(e)});Gn.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{Ho().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});Gn.command("path").description("Show config file locations").action(()=>{let s=A(),t=Ho().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=B.resolve(s||"."),o=new Ro;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new yo;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 qn=V.command("mcp").description("Manage MCP (Model Context Protocol) servers");qn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await jm(B.resolve(s.workspace))});qn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{Nm(B.resolve(o.workspace),s,e,t||[])});qn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{Lm(B.resolve(e.workspace),s)});qn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Bm(B.resolve(e.workspace),s)});qn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{Um(s)});var Wv=V.command("agents").description("View active agent sessions dashboard").action(async()=>{await qc(!0)});Wv.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await qc(!1)});var As=V.command("context").description("Semantic code search and workspace indexing");As.command("index").description("Index the current workspace for semantic search").action(async()=>{await qo(["index"],{})});As.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await qo(["search",s],{topK:e.topK})});As.command("status").description("Show index status and statistics").action(async()=>{await qo(["status"],{})});As.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await qo(["rebuild"],{})});As.command("related <file>").description("Find files related to a given file").action(async s=>{await qo(["related",s],{})});As.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await qo(["rank",s],{})});var Xo=V.command("triggers").description("Manage event-driven agent triggers");Xo.command("list").description("Show configured triggers").action(async()=>{await Do(["list"],{})});Xo.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 Do(["add"],s)});Xo.command("remove <name>").description("Remove a trigger by name").action(async s=>{await Do(["remove",s],{})});Xo.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await Do(["test",s],{})});Xo.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await Do(["enable",s],{})});Xo.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await Do(["disable",s],{})});Xo.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await Do(["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(Im(o)),console.log("")):console.log(Pm(o))});var Di=V.command("sessions").description("Manage saved conversation sessions");Di.command("list").description("List recent sessions").action(()=>Sh());Di.command("show <id>").description("Show session details").action(s=>xh(s));Di.command("delete <id>").description("Delete a session").action(s=>_h(s));Di.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{$h(parseInt(s.olderThan,10))});var so=V.command("jobs").description("Manage background agent jobs");so.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(),we)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),he)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Ne(o.agentsUrl,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(Ec({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);Ac(d)});so.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=Fc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=Tc(s);Yr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),we)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),he)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Ne(o.agentsUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);Yr(i,c)});so.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(),we)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),he)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Ne(n.agentsUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Xr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(sg(),og));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)Xr(u)}});so.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(),we)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),he)),n=t(),r=o();if(r?.access_token||(console.error("Not authenticated."),process.exit(3)),!e.force){let d=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(f=>d.question(` Cancel job ${s}? [y/N] `,f));if(d.close(),p.toLowerCase()!=="y"){console.log(" Cancelled.");return}}let c=await new Ne(n.agentsUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});so.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(),we)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),he)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.agentsUrl,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}`)});so.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),we)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),he)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Ne(o.agentsUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});so.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(),we)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),he)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.agentsUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),Rc(B.resolve(e.workspace),s,c.branch)});so.action(()=>{so.outputHelp()});var At=V.command("cloud").description("Manage cloud workspaces (persistent remote dev machines)");At.command("ls").alias("list").description("List your cloud workspaces").option("-o, --output <format>","Output format: text, json","text").action(async s=>{await Ih({output:s.output})});At.command("create <name>").description("Provision a new cloud workspace (starts automatically)").option("--tier <tier>","Compute tier: small, medium, large","small").option("--repo <url>","Repository to clone into the workspace").option("--branch <branch>","Branch to check out").option("-o, --output <format>","Output format: text, json","text").action(async(s,e)=>{await Mh(s,{tier:e.tier,repo:e.repo,branch:e.branch,output:e.output})});At.command("start <id>").description("Start a stopped workspace").action(async s=>{await Oh(s)});At.command("stop <id>").description("Stop a workspace (halts billing, keeps the volume)").action(async s=>{await jh(s)});At.command("rm <id>").alias("delete").description("Delete a workspace and destroy its volume").option("-y, --yes","Skip the confirmation prompt").action(async(s,e)=>{await Nh(s,{yes:e.yes})});At.command("exec <id>").description("Run a command in the workspace (use -- before the command)").argument("<command...>","Command to run").option("--cwd <path>","Working directory inside the workspace").option("--timeout <secs>","Timeout in seconds (server default 120)").option("-o, --output <format>","Output format: text, json","text").action(async(s,e,t)=>{await Lh(s,e,{cwd:t.cwd,timeout:t.timeout,output:t.output})});At.command("cat <id> <path>").description("Print a file from the workspace").action(async(s,e)=>{await Bh(s,e)});At.command("put <id> <path>").description("Write a file into the workspace (content from stdin)").option("--content <text>","Inline content instead of stdin").action(async(s,e,t)=>{await Uh(s,e,{content:t.content})});At.command("grep <id> <pattern>").description("Search files in the workspace").option("--path <path>","Limit the search to this subtree").option("--regex","Treat the pattern as a regular expression",!1).option("--case-sensitive","Case-sensitive match",!1).option("--include <glob...>","Only search matching files").option("-o, --output <format>","Output format: text, json","text").action(async(s,e,t)=>{await Wh(s,e,{path:t.path,regex:t.regex,caseSensitive:t.caseSensitive,include:t.include,output:t.output})});At.command("ssh <id>").alias("shell").description("Open an interactive shell in the workspace").action(async s=>{await Hh(s)});var Ko=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",Yo).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",".");Ko.action(async(s,e)=>{s&&e.cron?await Sl({prompt:s,cron:e.cron,model:vt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:B.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Ko.outputHelp()});Ko.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",Yo).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:vt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:B.resolve(e.workspace)})});Ko.command("list").description("List all scheduled jobs").action(async()=>{await Gh()});Ko.command("delete <id>").description("Delete a scheduled job").action(async s=>{await qh(s)});Ko.command("pause <id>").description("Pause a scheduled job").action(async s=>{await Vh(s)});Ko.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await Jh(s)});var Wn=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",Yo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");Wn.action(async(s,e)=>{s.length>0?await Qr({tasks:s,workspace:B.resolve(e.workspace),model:vt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):Wn.outputHelp()});Wn.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",Yo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Qr({tasks:s,workspace:B.resolve(e.workspace),model:vt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});Wn.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{Lc(B.resolve(s.workspace))});Wn.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{Bc(B.resolve(e.workspace),s)});var vi=V.command("worktrees").description("Manage git worktrees used by agent teams");vi.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=Ds(B.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}`)}});vi.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=gm({workspace:B.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}`)});vi.action(()=>{vi.outputHelp()});var El=V.command("messages").description("Cross-session messaging");El.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(),we)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),he)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new kn(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)});El.action(()=>{El.outputHelp()});var rg=V.command("hooks").description("Manage lifecycle hooks");rg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Vc(B.resolve(s.workspace))});rg.action(()=>{Vc(B.resolve("."))});var ig=V.command("models").description("Manage available models");ig.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),he))).loadAuth();La(s?.org?.plan)});ig.action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),he))).loadAuth();La(s?.org?.plan)});V.command("usage").description("Show monthly usage breakdown").action(async()=>{await Jm()});V.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=B.resolve(s.workspace),t=B.join(e,".monkeyscode","rules.md"),o=B.join(e,".monkeyscode","config.json");if(X.existsSync(t)&&X.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=B.join(e,"package.json"),i=B.join(e,"Cargo.toml"),c=B.join(e,"pyproject.toml"),u=B.join(e,"tsconfig.json"),d=B.join(e,"go.mod"),p=X.readdirSync(e).filter(g=>g.endsWith(".csproj")),f="Unknown";if(X.existsSync(r))try{let g=JSON.parse(X.readFileSync(r,"utf8"));f=g.type==="module"?"TypeScript/ESM":"JavaScript/CJS",n.push(`## Language: ${f}`),g.scripts?.test&&n.push(`- Test command: \`${g.scripts.test}\``),g.scripts?.lint&&n.push(`- Lint command: \`${g.scripts.lint}\``),g.scripts?.build&&n.push(`- Build command: \`${g.scripts.build}\``),g.dependencies?.react&&n.push("- Framework: React"),g.dependencies?.next&&n.push("- Framework: Next.js"),g.dependencies?.express&&n.push("- Server: Express"),g.dependencies?.fastify&&n.push("- Server: Fastify"),n.push("")}catch{}X.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"),X.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),X.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),X.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(`
|
|
722
|
+
`),h=Math.ceil(m.length/4);h>2e3&&console.log(a.yellow(` \u26A0\uFE0F Rules file is ~${h} tokens. Consider keeping it under 2000 for optimal context usage.`)),X.mkdirSync(B.join(e,".monkeyscode"),{recursive:!0}),X.writeFileSync(t,m,"utf8"),X.existsSync(o)||X.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 Ps=V.command("memory").description("Manage project conventions and rules");Ps.command("show").description("Show resolved rules from all sources").option("--workspace <path>","Workspace path",".").action(s=>{let e=B.resolve(s.workspace),t=A(),o=B.join(e,".monkeyscode","rules.md"),n=B.join(t.config,"rules.md"),r=B.join(e,".monkeyscode","MEMORY.md");if(console.log(""),console.log(a.bold(" \u{1F4DD} Resolved Rules")),console.log(a.dim(" "+"\u2500".repeat(50))),X.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=X.readFileSync(o,"utf8");for(let u of i.split(`
|
|
715
723
|
`))console.log(` ${u}`);let c=Math.ceil(i.length/4);c>2e3&&console.log(a.yellow(`
|
|
716
|
-
\u26A0\uFE0F ~${c} tokens \u2014 consider shortening for better context usage.`)),console.log("")}else console.log(a.dim(" No project rules. Run: mc init")),console.log("");if(
|
|
717
|
-
`))console.log(` ${i}`);console.log("")}if(
|
|
718
|
-
`))console.log(` ${i}`);console.log("")}console.log("")});
|
|
719
|
-
`,r=s.replace(/^["']|["']$/g,"");
|
|
724
|
+
\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(X.existsSync(n)){console.log(a.cyan(" [global]")+a.dim(` ${n}`));for(let i of X.readFileSync(n,"utf8").split(`
|
|
725
|
+
`))console.log(` ${i}`);console.log("")}if(X.existsSync(r)){console.log(a.magenta(" [memory]")+a.dim(` ${r}`));for(let i of X.readFileSync(r,"utf8").split(`
|
|
726
|
+
`))console.log(` ${i}`);console.log("")}console.log("")});Ps.command("add <rule>").description("Add a convention rule").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=B.resolve(e.workspace),o=B.join(t,".monkeyscode","rules.md");X.mkdirSync(B.dirname(o),{recursive:!0});let n=X.existsSync(o)?X.readFileSync(o,"utf8"):`# Project Conventions
|
|
727
|
+
`,r=s.replace(/^["']|["']$/g,"");X.writeFileSync(o,n.trimEnd()+`
|
|
720
728
|
- `+r+`
|
|
721
|
-
`,"utf8"),console.log(` \u2705 Added: ${r}`)});
|
|
722
|
-
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&
|
|
723
|
-
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});
|
|
724
|
-
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});
|
|
725
|
-
`))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});
|
|
729
|
+
`,"utf8"),console.log(` \u2705 Added: ${r}`)});Ps.command("edit").description("Open rules in $EDITOR").option("--workspace <path>","Workspace path",".").action(s=>{let e=B.resolve(s.workspace),t=B.join(e,".monkeyscode","rules.md"),o=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!X.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}`)}});Ps.command("forget <pattern>").description("Remove a learned convention matching the pattern").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=B.resolve(e.workspace),o=B.join(t,".monkeyscode","MEMORY.md"),n=B.join(t,".monkeyscode","rules.md"),r=0,i=s.replace(/^["']|["']$/g,"");for(let c of[o,n]){if(!X.existsSync(c))continue;let d=X.readFileSync(c,"utf8").split(`
|
|
730
|
+
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&X.writeFileSync(c,d.join(`
|
|
731
|
+
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});Ps.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])});Ps.action(s=>{let e=process.cwd(),t=B.join(e,".monkeyscode","rules.md");if(X.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 X.readFileSync(t,"utf8").split(`
|
|
732
|
+
`))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=B.resolve(s.workspace),t=B.join(e,".monkeyscode","rules.md");if(X.existsSync(t)){console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules"));for(let o of X.readFileSync(t,"utf8").split(`
|
|
733
|
+
`))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 Mt("-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 Mt("--severity-threshold <level>","Minimum severity to fail CI").choices(["high","medium","low"]).default("high")).option("--model <model>","Model to use",Yo).option("--workspace <path>","Workspace path",".").action(async s=>{let e=vt(s.model);await zh({workspace:B.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 Mt("-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 Mt("--severity-threshold <level>","Minimum severity to fail CI").choices(["high","medium","low"]).default("high")).option("--model <model>","Model to use",Yo).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let t=vt(e.model);await Kh({workspace:B.resolve(e.workspace),model:t,target:s||".",output:e.output,autoFix:e.autoFix,focus:e.focus,severityThreshold:e.severityThreshold})});var ag=V.command("trace").description("Inspect agent execution traces");ag.command("list").action(async s=>{Bf(s)});ag.command("show <id>").option("--tree").option("--flamegraph").option("--verbose").action(async(s,e)=>{Uf(s,e)});var Qo=V.command("marketplace").description("Browse and manage agent skills");Qo.command("search <query>").option("--category <cat>").action(async(s,e)=>{await Gf(s,e)});Qo.command("install <id>").action(async s=>{await qf(s)});Qo.command("uninstall <id>").action(async s=>{Vf(s)});Qo.command("publish <dir>").option("--name <name>").option("--bump <bump>").action(async(s,e)=>{await Jf(s,e)});Qo.command("update").action(async()=>{await zf()});Qo.command("list").action(()=>{Kf()});Qo.command("featured").action(async()=>{await Yf()});V.command("join <sessionId>").description("Join a live collaboration session").action(async s=>{await wh(s)});V.command("share").description("Start a new live collaboration session").action(async()=>{await bh()&&console.log(a.dim("Host session running..."))});var Si=V.command("permissions").description("Manage natural language policies");Si.command("set <text>").action(async s=>{await sh(s)});Si.command("list").action(()=>{nh()});Si.command("remove <index>").action(s=>{rh(parseInt(s,10))});Si.command("test <tool> <args>").action((s,e)=>{ih(s,e)});var cg=V.command("benchmark").description("Run agent benchmarks");cg.command("custom <path>").option("--model [models...]").option("--workspace <dir>").action(async(s,e)=>{await ph(s,e)});cg.command("results").option("--limit <n>").option("--format <fmt>").action(s=>{mh(s)});V.command("design").description("Start the local design artboard server").option("--port <p>").action(s=>{Dh.start(s.port?parseInt(s.port,10):void 0)});ff()&&process.argv.length<=2?hf().then(()=>V.parse()).catch(()=>V.parse()):(uf("cli_start",{version:Fl}),V.parse());
|