monkeyscode-cli 0.1.0

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.
@@ -0,0 +1,710 @@
1
+ #!/usr/bin/env node
2
+
3
+ "use strict";var yg=Object.create;var $s=Object.defineProperty;var bg=Object.getOwnPropertyDescriptor;var wg=Object.getOwnPropertyNames;var kg=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty;var l=(s,e)=>$s(s,"name",{value:e,configurable:!0});var H=(s,e)=>()=>(s&&(e=s(s=0)),e);var ce=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Te=(s,e)=>{for(var t in e)$s(s,t,{get:e[t],enumerable:!0})},al=(s,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of wg(e))!Dg.call(s,n)&&n!==t&&$s(s,n,{get:()=>e[n],enumerable:!(o=bg(e,n))||o.enumerable});return s};var y=(s,e,t)=>(t=s!=null?yg(kg(s)):{},al(e||!s||!s.__esModule?$s(t,"default",{value:s,enumerable:!0}):t,s)),_s=s=>al($s({},"__esModule",{value:!0}),s);var Es=ce(pi=>{var Rn=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}},di=class extends Rn{static{l(this,"InvalidArgumentError")}constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};pi.CommanderError=Rn;pi.InvalidArgumentError=di});var An=ce(fi=>{var{InvalidArgumentError:vg}=Es(),mi=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 vg(`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 Sg(s){let e=s.name()+(s.variadic===!0?"...":"");return s.required?"<"+e+">":"["+e+"]"}l(Sg,"humanReadableArgName");fi.Argument=mi;fi.humanReadableArgName=Sg});var yi=ce(hi=>{var{humanReadableArgName:xg}=An(),gi=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=>xg(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 cl(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 cl(s){let e=/\x1b\[\d*(;\d*)*m/g;return s.replace(e,"")}l(cl,"stripColor");hi.Help=gi;hi.stripColor=cl});var Di=ce(ki=>{var{InvalidArgumentError:Cg}=Es(),bi=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=$g(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 Cg(`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?ll(this.name().replace(/^no-/,"")):ll(this.name())}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},wi=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 ll(s){return s.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}l(ll,"camelcase");function $g(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
+ - a short flag is a single dash and a single character
9
+ - either use a single dash and a single character (for a short flag)
10
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):o.test(i)?new Error(`${c}
11
+ - too many short flags`):n.test(i)?new Error(`${c}
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($g,"splitOptionFlags");ki.Option=bi;ki.DualOptions=wi});var dl=ce(ul=>{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 Eg(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
+ (Did you mean one of ${o.join(", ")}?)`:o.length===1?`
15
+ (Did you mean ${o[0]}?)`:""}l(Eg,"suggestSimilar");ul.suggestSimilar=Eg});var gl=ce($i=>{var Fg=require("node:events").EventEmitter,vi=require("node:child_process"),_t=require("node:path"),Pn=require("node:fs"),ee=require("node:process"),{Argument:Tg,humanReadableArgName:Rg}=An(),{CommanderError:Si}=Es(),{Help:Ag,stripColor:Pg}=yi(),{Option:pl,DualOptions:Og}=Di(),{suggestSimilar:ml}=dl(),xi=class s extends Fg{static{l(this,"Command")}constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:l(t=>ee.stdout.write(t),"writeOut"),writeErr:l(t=>ee.stderr.write(t),"writeErr"),outputError:l((t,o)=>o(t),"outputError"),getOutHelpWidth:l(()=>ee.stdout.isTTY?ee.stdout.columns:void 0,"getOutHelpWidth"),getErrHelpWidth:l(()=>ee.stderr.isTTY?ee.stderr.columns:void 0,"getErrHelpWidth"),getOutHasColors:l(()=>Ci()??(ee.stdout.isTTY&&ee.stdout.hasColors?.()),"getOutHasColors"),getErrHasColors:l(()=>Ci()??(ee.stderr.isTTY&&ee.stderr.hasColors?.()),"getErrHasColors"),stripColor:l(t=>Pg(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 Ag,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 Tg(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 Si(e,t,o)),ee.exit(e)}action(e){let t=l(o=>{let n=this.registeredArguments.length,r=o.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),e.apply(this,r)},"listener");return this._actionHandler=t,this}createOption(e,t){return new pl(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 pl)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(t,o);if(i.makeOptionMandatory(!!e.mandatory),typeof n=="function")i.default(r).argParser(n);else if(n instanceof RegExp){let c=n;n=l((u,d)=>{let p=c.exec(u);return p?p[0]:d},"fn"),i.default(r).argParser(n)}else i.default(n);return this.addOption(i)}option(e,t,o,n){return this._optionEx({},e,t,o,n)}requiredOption(e,t,o,n){return this._optionEx({mandatory:!0},e,t,o,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,o){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=o,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(o=>{o.getOptionValueSource(e)!==void 0&&(t=o.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){ee.versions?.electron&&(t.from="electron");let n=ee.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=ee.argv),this.rawArgs=e.slice();let o;switch(t.from){case void 0:case"node":this._scriptPath=e[1],o=e.slice(2);break;case"electron":ee.defaultApp?(this._scriptPath=e[1],o=e.slice(2)):o=e.slice(1);break;case"user":o=e.slice(0);break;case"eval":o=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",o}parse(e,t){this._prepareForParse();let o=this._prepareUserArgs(e,t);return this._parseCommand([],o),this}async parseAsync(e,t){this._prepareForParse();let o=this._prepareUserArgs(e,t);return await this._parseCommand([],o),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
19
+ - either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(e,t,o){if(Pn.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
+ - if '${o}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
21
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
22
+ - ${n}`;throw new Error(r)}_executeSubCommand(e,t){t=t.slice();let o=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(p,f){let m=_t.resolve(p,f);if(Pn.existsSync(m))return m;if(n.includes(_t.extname(f)))return;let g=n.find(h=>Pn.existsSync(`${m}${h}`));if(g)return`${m}${g}`}l(r,"findFile"),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,c=this._executableDir||"";if(this._scriptPath){let p;try{p=Pn.realpathSync(this._scriptPath)}catch{p=this._scriptPath}c=_t.resolve(_t.dirname(p),c)}if(c){let p=r(c,i);if(!p&&!e._executableFile&&this._scriptPath){let f=_t.basename(this._scriptPath,_t.extname(this._scriptPath));f!==this._name&&(p=r(c,`${f}-${e._name}`))}i=p||i}o=n.includes(_t.extname(i));let u;ee.platform!=="win32"?o?(t.unshift(i),t=fl(ee.execArgv).concat(t),u=vi.spawn(ee.argv[0],t,{stdio:"inherit"})):u=vi.spawn(i,t,{stdio:"inherit"}):(this._checkForMissingExecutable(i,c,e._name),t.unshift(i),t=fl(ee.execArgv).concat(t),u=vi.spawn(ee.execPath,t,{stdio:"inherit"})),u.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(f=>{ee.on(f,()=>{u.killed===!1&&u.exitCode===null&&u.kill(f)})});let d=this._exitCallback;u.on("close",p=>{p=p??1,d?d(new Si(p,"commander.executeSubCommandAsync","(close)")):ee.exit(p)}),u.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(i,c,e._name);else if(p.code==="EACCES")throw new Error(`'${i}' not executable`);if(!d)ee.exit(1);else{let f=new Si(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
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
24
+ `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
25
+ `),this.outputHelp({error:!0}));let o=t||{},n=o.exitCode||1,r=o.code||"commander.error";this._exit(n,r,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in ee.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,ee.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new Og(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=ml(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=ml(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=>Rg(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=_t.basename(e,_t.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),o=this._getOutputContext(e);t.prepareContext({error:o.error,helpWidth:o.helpWidth,outputHasColors:o.hasColors});let n=t.formatHelp(this,t);return o.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(e){e=e||{};let t=!!e.error,o,n,r;return t?(o=l(c=>this._outputConfiguration.writeErr(c),"baseWrite"),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(o=l(c=>this._outputConfiguration.writeOut(c),"baseWrite"),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:t,write:l(c=>(n||(c=this._outputConfiguration.stripColor(c)),o(c)),"write"),hasColors:n,helpWidth:r}}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let o=this._getOutputContext(e),n={error:o.error,write:o.write,command:this};this._getCommandAndAncestors().reverse().forEach(i=>i.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:o.error});if(t&&(r=t(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");o.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(i=>i.emit("afterAllHelp",n))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Number(ee.exitCode??0);t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let o=["beforeAll","before","after","afterAll"];if(!o.includes(e))throw new Error(`Unexpected value for position to addHelpText.
27
+ 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 fl(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(fl,"incrementNodeInspectorPort");function Ci(){if(ee.env.NO_COLOR||ee.env.FORCE_COLOR==="0"||ee.env.FORCE_COLOR==="false")return!1;if(ee.env.FORCE_COLOR||ee.env.CLICOLOR_FORCE!==void 0)return!0}l(Ci,"useColor");$i.Command=xi;$i.useColor=Ci});var wl=ce(He=>{var{Argument:hl}=An(),{Command:_i}=gl(),{CommanderError:Mg,InvalidArgumentError:yl}=Es(),{Help:Ig}=yi(),{Option:bl}=Di();He.program=new _i;He.createCommand=s=>new _i(s);He.createOption=(s,e)=>new bl(s,e);He.createArgument=(s,e)=>new hl(s,e);He.Command=_i;He.Option=bl;He.Argument=hl;He.Help=Ig;He.CommanderError=Mg;He.InvalidArgumentError=yl;He.InvalidOptionArgumentError=yl});function Bg(){let s=new Map;for(let[e,t]of Object.entries(ne)){for(let[o,n]of Object.entries(t))ne[o]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},t[o]=ne[o],s.set(n[0],n[1]);Object.defineProperty(ne,e,{value:t,enumerable:!1})}return Object.defineProperty(ne,"codes",{value:s,enumerable:!1}),ne.color.close="\x1B[39m",ne.bgColor.close="\x1B[49m",ne.color.ansi=vl(),ne.color.ansi256=Sl(),ne.color.ansi16m=xl(),ne.bgColor.ansi=vl(10),ne.bgColor.ansi256=Sl(10),ne.bgColor.ansi16m=xl(10),Object.defineProperties(ne,{rgbToAnsi256:{value(e,t,o){return e===t&&t===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[o]=t;o.length===3&&(o=[...o].map(r=>r+r).join(""));let n=Number.parseInt(o,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:l(e=>ne.rgbToAnsi256(...ne.hexToRgb(e)),"value"),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,o,n;if(e>=232)t=((e-232)*10+8)/255,o=t,n=t;else{e-=16;let c=e%36;t=Math.floor(e/36)/5,o=Math.floor(c/6)/5,n=c%6/5}let r=Math.max(t,o,n)*2;if(r===0)return 30;let i=30+(Math.round(n)<<2|Math.round(o)<<1|Math.round(t));return r===2&&(i+=60),i},enumerable:!1},rgbToAnsi:{value:l((e,t,o)=>ne.ansi256ToAnsi(ne.rgbToAnsi256(e,t,o)),"value"),enumerable:!1},hexToAnsi:{value:l(e=>ne.ansi256ToAnsi(ne.hexToAnsi256(e)),"value"),enumerable:!1}}),ne}var vl,Sl,xl,ne,qk,jg,Ng,Vk,Lg,Ze,Cl=H(()=>{vl=l((s=0)=>e=>`\x1B[${e+s}m`,"wrapAnsi16"),Sl=l((s=0)=>e=>`\x1B[${38+s};5;${e}m`,"wrapAnsi256"),xl=l((s=0)=>(e,t,o)=>`\x1B[${38+s};2;${e};${t};${o}m`,"wrapAnsi16m"),ne={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},qk=Object.keys(ne.modifier),jg=Object.keys(ne.color),Ng=Object.keys(ne.bgColor),Vk=[...jg,...Ng];l(Bg,"assembleStyles");Lg=Bg(),Ze=Lg});function Ge(s,e=globalThis.Deno?globalThis.Deno.args:Mn.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 Ug(){if("FORCE_COLOR"in re)return re.FORCE_COLOR==="true"?1:re.FORCE_COLOR==="false"?0:re.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(re.FORCE_COLOR,10),3)}function Wg(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function Hg(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let o=Ug();o!==void 0&&(On=o);let n=t?On:o;if(n===0)return 0;if(t){if(Ge("color=16m")||Ge("color=full")||Ge("color=truecolor"))return 3;if(Ge("color=256"))return 2}if("TF_BUILD"in re&&"AGENT_NAME"in re)return 1;if(s&&!e&&n===void 0)return 0;let r=n||0;if(re.TERM==="dumb")return r;if(Mn.default.platform==="win32"){let i=_l.default.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in re)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(i=>i in re)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(i=>i in re)||re.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in re)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(re.TEAMCITY_VERSION)?1:0;if(re.COLORTERM==="truecolor"||re.TERM==="xterm-kitty"||re.TERM==="xterm-ghostty"||re.TERM==="wezterm")return 3;if("TERM_PROGRAM"in re){let i=Number.parseInt((re.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(re.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(re.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(re.TERM)||"COLORTERM"in re?1:r}function $l(s,e={}){let t=Hg(s,{streamIsTTY:s&&s.isTTY,...e});return Wg(t)}var Mn,_l,Ei,re,On,Gg,El,Fl=H(()=>{Mn=y(require("node:process"),1),_l=y(require("node:os"),1),Ei=y(require("node:tty"),1);l(Ge,"hasFlag");({env:re}=Mn.default);Ge("no-color")||Ge("no-colors")||Ge("color=false")||Ge("color=never")?On=0:(Ge("color")||Ge("colors")||Ge("color=true")||Ge("color=always"))&&(On=1);l(Ug,"envForceColor");l(Wg,"translateLevel");l(Hg,"_supportsColor");l($l,"createSupportsColor");Gg={stdout:$l({isTTY:Ei.default.isatty(1)}),stderr:$l({isTTY:Ei.default.isatty(2)})},El=Gg});function Tl(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 Rl(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
+ `:`
30
+ `)+t,n=o+1,o=s.indexOf(`
31
+ `,n)}while(o!==-1);return r+=s.slice(n),r}var Al=H(()=>{l(Tl,"stringReplaceAll");l(Rl,"stringEncaseCRLFWithFirstIndex")});function Ts(s){return Vg(s)}var Pl,Ol,Fi,qo,Fs,Ml,Vo,qg,Vg,Ti,Jg,zg,Ri,In,Kg,Yg,oD,a,W=H(()=>{Cl();Fl();Al();({stdout:Pl,stderr:Ol}=El),Fi=Symbol("GENERATOR"),qo=Symbol("STYLER"),Fs=Symbol("IS_EMPTY"),Ml=["ansi","ansi","ansi256","ansi16m"],Vo=Object.create(null),qg=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=Pl?Pl.level:0;s.level=e.level===void 0?t:e.level},"applyOptions"),Vg=l(s=>{let e=l((...t)=>t.join(" "),"chalk");return qg(e,s),Object.setPrototypeOf(e,Ts.prototype),e},"chalkFactory");l(Ts,"createChalk");Object.setPrototypeOf(Ts.prototype,Function.prototype);for(let[s,e]of Object.entries(Ze))Vo[s]={get(){let t=In(this,Ri(e.open,e.close,this[qo]),this[Fs]);return Object.defineProperty(this,s,{value:t}),t}};Vo.visible={get(){let s=In(this,this[qo],!0);return Object.defineProperty(this,"visible",{value:s}),s}};Ti=l((s,e,t,...o)=>s==="rgb"?e==="ansi16m"?Ze[t].ansi16m(...o):e==="ansi256"?Ze[t].ansi256(Ze.rgbToAnsi256(...o)):Ze[t].ansi(Ze.rgbToAnsi(...o)):s==="hex"?Ti("rgb",e,t,...Ze.hexToRgb(...o)):Ze[t][s](...o),"getModelAnsi"),Jg=["rgb","hex","ansi256"];for(let s of Jg){Vo[s]={get(){let{level:t}=this;return function(...o){let n=Ri(Ti(s,Ml[t],"color",...o),Ze.color.close,this[qo]);return In(this,n,this[Fs])}}};let e="bg"+s[0].toUpperCase()+s.slice(1);Vo[e]={get(){let{level:t}=this;return function(...o){let n=Ri(Ti(s,Ml[t],"bgColor",...o),Ze.bgColor.close,this[qo]);return In(this,n,this[Fs])}}}}zg=Object.defineProperties(()=>{},{...Vo,level:{enumerable:!0,get(){return this[Fi].level},set(s){this[Fi].level=s}}}),Ri=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"),In=l((s,e,t)=>{let o=l((...n)=>Kg(o,n.length===1?""+n[0]:n.join(" ")),"builder");return Object.setPrototypeOf(o,zg),o[Fi]=s,o[qo]=e,o[Fs]=t,o},"createBuilder"),Kg=l((s,e)=>{if(s.level<=0||!e)return s[Fs]?"":e;let t=s[qo];if(t===void 0)return e;let{openAll:o,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Tl(e,t.close,t.open),t=t.parent;let r=e.indexOf(`
32
+ `);return r!==-1&&(e=Rl(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Ts.prototype,Vo);Yg=Ts(),oD=Ts({level:Ol?Ol.level:0}),a=Yg});var Ul=ce((DD,ah)=>{ah.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 Ui=ce((vD,Hl)=>{"use strict";var Un=Object.assign({},Ul()),Wl=Object.keys(Un);Object.defineProperty(Un,"random",{get(){let s=Math.floor(Math.random()*Wl.length),e=Wl[s];return Un[e]}});Hl.exports=Un});var ou=ce((YD,tu)=>{tu.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 Do={};Te(Do,{detectPlatform:()=>De,ensureDir:()=>Hn,getPlatformInfo:()=>xe,getPlatformPaths:()=>T,isLocalModel:()=>Fh,isUNCPath:()=>_h,normalizePath:()=>$h,resolveSymlinks:()=>Eh});function De(){switch(Ft.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function T(s){switch(s??De()){case"macos":{let t=Ft.homedir(),o=se.join(t,".monkeyscode");return{config:o,data:o,pidFile:se.join(o,"daemon.pid"),socketFile:se.join(o,"daemon.sock"),credentialBackend:"macOS Keychain",logs:se.join(o,"logs")}}case"linux":{let t=Ft.homedir(),o=process.env.XDG_CONFIG_HOME||se.join(t,".config"),n=process.env.XDG_DATA_HOME||se.join(t,".local","share"),r=process.env.XDG_STATE_HOME||se.join(t,".local","state"),i=ko.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=ko.existsSync(n)?se.join(n,"monkeyscode"):se.join(t,".monkeyscode");return{config:i,data:c,pidFile:se.join(r,"monkeyscode","daemon.pid"),socketFile:se.join(r,"monkeyscode","daemon.sock"),credentialBackend:"libsecret / gnome-keyring",logs:se.join(r,"monkeyscode","logs")}}case"windows":{let t=process.env.APPDATA||se.join(Ft.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(Ft.homedir(),"AppData","Local");return{config:se.join(t,"monkeyscode"),data:se.join(o,"monkeyscode"),pidFile:se.join(o,"monkeyscode","daemon.pid"),socketFile:se.join(o,"monkeyscode","daemon.sock"),credentialBackend:"Windows Credential Manager",logs:se.join(o,"monkeyscode","logs")}}}}function xe(){let s=De();return{os:s,arch:Ft.arch(),shell:Sh(s),supportsColor:xh(),supportsUnicode:Ch(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Sh(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 xh(){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 Ch(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 Hn(s){ko.mkdirSync(s,{recursive:!0})}function $h(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function _h(s){return s.startsWith("\\\\")||s.startsWith("//")}function Eh(s){try{return ko.realpathSync(s)}catch{return s}}function Fh(s,e){if(s.startsWith("local:")||s.startsWith("ollama:"))return!0;if(e)try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}return!1}var Ft,se,ko,X=H(()=>{"use strict";Ft=y(require("node:os"),1),se=y(require("node:path"),1),ko=y(require("node:fs"),1);l(De,"detectPlatform");l(T,"getPlatformPaths");l(xe,"getPlatformInfo");l(Sh,"detectShell");l(xh,"detectColorSupport");l(Ch,"detectUnicodeSupport");l(Hn,"ensureDir");l($h,"normalizePath");l(_h,"isUNCPath");l(Eh,"resolveSymlinks");l(Fh,"isLocalModel")});function Mh(){if(process.env.NERD_FONT==="1"||process.env.MC_ICONS==="nerd")return!0;if(process.env.NERD_FONT==="0"||process.env.MC_ICONS==="unicode"||process.env.MC_ICONS==="ascii")return!1;let s=(process.env.TERM_PROGRAM||"").toLowerCase();return!!(["wezterm","kitty","alacritty","ghostty","rio","hyper"].some(t=>s.includes(t))||process.env.WT_SESSION||s==="vscode")}function j(){let s=xe(),e=process.env.NO_COLOR!==void 0,t=process.env.FORCE_COLOR!==void 0,o=!!process.stdout.isTTY,n=!!process.stdin.isTTY,r=o&&!e,i=r,c=!1,u=!1;if(t&&(r=!0,i=!0),r){let p=process.env.TERM||"",f=process.env.COLORTERM||"";(p.includes("256color")||p==="xterm-kitty"||f)&&(c=!0),(f==="truecolor"||f==="24bit")&&(u=!0),process.env.WT_SESSION&&(c=!0,u=!0)}let d=Mh();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 U(s){let e=s??j();return e.nerdFont?Th:e.unicode?Rh:Ah}function Ve(s){return(s??j()).unicode?Ph:Oh}var Th,Rh,Ah,Ph,Oh,Ce=H(()=>{"use strict";X();Th={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"},Rh={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"},Ah={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:">"},Ph={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Oh={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(Mh,"detectNerdFont");l(j,"detectCapabilities");l(U,"getIcons");l(Ve,"getBoxChars")});function Jn(){if(mt)return mt;let s=process.platform;return s==="darwin"&&mu("security")?(mt=new oa,mt):s==="linux"&&mu("secret-tool")?(mt=new sa,mt):s==="win32"?(mt=new na,mt):(mt=new ra,mt)}function mu(s){try{return(0,tt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function fu(s){return s.replace(/[\\"$`!]/g,"\\$&")}function Xh(){try{if(process.platform==="linux")return pe.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,tt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${zo.hostname()}-${zo.userInfo().username}-${zo.homedir()}`}var pe,Qt,zo,Tt,tt,Xt,oa,sa,na,ra,mt,gu=H(()=>{"use strict";pe=y(require("node:fs"),1),Qt=y(require("node:path"),1),zo=y(require("node:os"),1),Tt=y(require("node:crypto"),1),tt=require("node:child_process");X();Xt="monkeyscode-cli",oa=class{static{l(this,"KeychainStore")}get(e){try{return(0,tt.execSync)(`security find-generic-password -s "${Xt}" -a "${e}" -w 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){this.delete(e);try{(0,tt.execSync)(`security add-generic-password -s "${Xt}" -a "${e}" -w "${fu(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,tt.execSync)(`security delete-generic-password -s "${Xt}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},sa=class{static{l(this,"SecretToolStore")}get(e){try{return(0,tt.execSync)(`secret-tool lookup service "${Xt}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,tt.execSync)(`echo -n "${fu(t)}" | secret-tool store --label="${Xt}:${e}" service "${Xt}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,tt.execSync)(`secret-tool clear service "${Xt}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},na=class{static{l(this,"WinCredStore")}get(e){try{let t=`${Xt}:${e}`,o=`
33
+ $cred = cmdkey /list:${t} 2>$null;
34
+ if ($LASTEXITCODE -eq 0) {
35
+ # cmdkey can't read passwords. Use CredRead via .NET
36
+ Add-Type -AssemblyName System.Runtime.InteropServices;
37
+ $credPtr = [IntPtr]::Zero;
38
+ $result = [AdvApi32]::CredRead("${t}", 1, 0, [ref]$credPtr);
39
+ # Fallback: read from encrypted file
40
+ }
41
+ `;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{pe.existsSync(t)&&pe.unlinkSync(t)}catch{}}getFilePath(e){let t=T();return Qt.join(t.config,`cred-${e}.enc`)}getDpapi(e){let t=this.getFilePath(e);try{if(!pe.existsSync(t))return null;let o=pe.readFileSync(t,"utf8");return(0,tt.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,tt.execSync)(`powershell -NoProfile -Command "Add-Type -AssemblyName System.Security; [System.Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Protect([System.Text.Encoding]::UTF8.GetBytes('${t.replace(/'/g,"''")}'), $null, 'CurrentUser'))"`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"});pe.mkdirSync(Qt.dirname(o),{recursive:!0}),pe.writeFileSync(o,n.trim(),{mode:384})}catch{throw new Error("Failed to encrypt credential via DPAPI")}}},ra=class{static{l(this,"EncryptedFileStore")}keyPath;storePath;constructor(){let e=T();this.keyPath=Qt.join(e.config,".cred-key"),this.storePath=Qt.join(e.config,"credentials.enc")}get(e){return this.loadStore()[e]||null}set(e,t){let o=this.loadStore();o[e]=t,this.saveStore(o)}delete(e){let t=this.loadStore();delete t[e],this.saveStore(t)}getOrCreateKey(){try{if(pe.existsSync(this.keyPath))return Buffer.from(pe.readFileSync(this.keyPath,"utf8"),"hex")}catch{}let e=Xh(),t=Tt.randomBytes(16),o=Tt.scryptSync(e,t,32),n=t.toString("hex")+":"+o.toString("hex");return pe.mkdirSync(Qt.dirname(this.keyPath),{recursive:!0}),pe.writeFileSync(this.keyPath,n,{mode:384}),o}loadStore(){try{if(!pe.existsSync(this.storePath))return{};let e=pe.readFileSync(this.storePath,"utf8"),[t,o]=e.split(":"),n=this.getOrCreateKey(),r=Buffer.from(t,"hex"),i=Tt.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=Tt.randomBytes(16),n=Tt.createCipheriv("aes-256-cbc",t,o),r=n.update(JSON.stringify(e),"utf8","hex");r+=n.final("hex"),pe.mkdirSync(Qt.dirname(this.storePath),{recursive:!0}),pe.writeFileSync(this.storePath,o.toString("hex")+":"+r,{mode:384})}},mt=null;l(Jn,"getCredentialStore");l(mu,"hasCommand");l(fu,"escapeShellArg");l(Xh,"getMachineId")});var ge={};Te(ge,{authLogin:()=>ia,authLoginEmail:()=>aa,authLoginSSO:()=>ma,authLogout:()=>ca,authLogoutProfile:()=>fa,authRefresh:()=>ua,authSetToken:()=>la,authStatus:()=>zn,getAccessToken:()=>Ae,isAuthenticated:()=>pa,loadAuth:()=>me});async function ia(){let s=j(),e=U(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Device Authentication"):" Device Authentication"),console.log(t?a.dim(` API: ${Re}`):` API: ${Re}`),console.log("");try{let o=await fetch(`${Re}/v1/auth/device`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:"monkeyscode-cli"})});if(!o.ok){let p=await o.text().catch(()=>"");throw new Error(`Auth server returned ${o.status}: ${o.statusText}
42
+ ${p}`)}let n=await o.json(),r=n.user_code||"\u2014",i=n.verification_uri;console.log(t?` ${e.info} Open this URL in your browser:`:" Open this URL in your browser:"),console.log(""),console.log(t?` ${a.underline.cyan(i)}`:` ${i}`),console.log(""),n.user_code&&(console.log(t?` Your code: ${a.bold.bgBlue.white(` ${r} `)}`:` Your code: ${r}`),console.log(""));try{let{exec:p}=await import("node:child_process"),f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";p(`${f} "${i}"`),console.log(t?a.dim(" Browser opened automatically."):" Browser opened automatically.")}catch{}console.log(""),console.log(" Waiting for approval...");let c=(n.interval||5)*1e3,u=Date.now()+(n.expires_in||600)*1e3,d=0;for(;Date.now()<u;){await Qh(c);try{let f=await(await fetch(`${Re}/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 da(f.access_token),g=Date.now()+(f.expires_in||172800)*1e3;Ko({access_token:f.access_token,refresh_token:f.refresh_token,expires_at:g,auth_method:"oauth",user:m?{id:m.id?.toString(),email:m.email,name:m.name,avatar_url:m.avatar_url??void 0}:f.user?{id:f.user.id?.toString(),email:f.user.email,name:f.user.name}:void 0,org:m?.orgs?.[0]?{id:m.orgs[0].id?.toString(),name:m.orgs[0].name,plan:m.orgs[0].plan_code}:void 0}),console.log(""),console.log(` ${e.success} Logged in successfully!`),m?console.log(` ${e.info} ${m.email} (${m.orgs?.[0]?.plan_code||"free"})`):f.user&&console.log(` ${e.info} ${f.user.email}`),console.log("");return}if(f.error==="expired_token"){console.log(""),console.log(` ${e.warning} Device code expired. Please try again.`),console.log("");return}d++,process.stdout.write(t?a.dim("."):"."),d%60===0&&console.log("")}catch{process.stdout.write(t?a.red("!"):"!")}}console.log(""),console.log(` ${e.warning} Login timed out. Please try again.`),console.log("")}catch(o){console.error(""),console.error(` ${e.error} Login failed: ${o instanceof Error?o.message:o}`),console.error("")}}async function aa(){let s=j(),e=U(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Email Login"):" Email Login"),console.log(t?a.dim(` API: ${Re}`):` API: ${Re}`),console.log("");let o=hu.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 Zh(" 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(`${Re}/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 da(u.access_token),p=Date.now()+(u.expires_in||172800)*1e3;Ko({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 ca(){let s=U(),e=T(),t=Rt.join(e.config,"auth.json");$e.existsSync(t)&&$e.unlinkSync(t),console.log(` ${s.success} Logged out.`),console.log("")}function la(s,e){let t=U();Ko({access_token:s,auth_method:"apikey",profile:e},e),console.log(` ${t.success} Token saved${e?` (profile: ${e})`:""}.`),console.log("")}async function zn(s){let e=j(),t=U(e),o=e.ansi,n=me(s);if(console.log(""),n){let r=n.auth_method||"unknown",i={oauth:"\u{1F510} OAuth (browser)",apikey:"\u{1F511} API Key",email:"\u{1F4E7} Email/Password",sso:"\u{1F3E2} Enterprise SSO",env:"\u{1F30D} Environment Variable",unknown:"\u2753 Unknown"};if(console.log(` Auth: ${t.success} logged in`),console.log(` Method: ${i[r]||r}`),s&&s!=="default"&&console.log(` Profile: ${s}`),n.user?.email&&console.log(` User: ${n.user.email}`),n.user?.name&&console.log(` Name: ${n.user.name}`),n.org?.name&&console.log(` Org: ${n.org.name} (${n.org.plan||"free"})`),n.expires_at){let u=n.expires_at-Date.now();if(u>0){let d=Math.floor(u/36e5),p=Math.floor(d/24),f=p>0?`${p}d ${d%24}h`:`${d}h`;console.log(o?a.dim(` Expires: ${f}`):` Expires: ${f}`)}else console.log(o?a.yellow(` ${t.warning} Token expired \u2014 run: mc auth refresh`):` ${t.warning} Token expired`)}try{let u=await Ae(s);if(u){let d=await fetch(`${Re}/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: ${Re}`):` API: ${Re}`)}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 ua(){let s=j(),e=U(s),t=me();if(!t?.refresh_token){console.log(` ${e.error} No refresh token found. Run: mc auth login`);return}console.log(" Refreshing token...");try{let o=await fetch(`${Re}/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;Ko({...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 da(s){try{let e=await fetch(`${Re}/v1/auth/me`,{headers:{Authorization:`Bearer ${s}`}});if(e.ok)return await e.json()}catch{}return null}function me(s){let e=process.env.MONKEYSCODE_API_KEY||process.env.MC_TOKEN||process.env.MONKEYSCODE_AUTH_TOKEN;if(e)return{access_token:e,auth_method:"env"};let t=s||"default",o=`${yu}-${t}`;try{let c=Jn().get(o);if(c)return JSON.parse(c)}catch{}let n=T(),r=t==="default"?Rt.join(n.config,"auth.json"):Rt.join(n.config,`auth-${t}.json`);try{if($e.existsSync(r)){let i=JSON.parse($e.readFileSync(r,"utf8"));try{Jn().set(o,JSON.stringify(i)),$e.unlinkSync(r)}catch{}return i}}catch{}return null}function pa(){return me()!==null}async function Ae(s){let e=me(s);if(!e?.access_token)return null;if(e.expires_at&&e.expires_at<Date.now()&&e.refresh_token){process.stderr.write(` \u{1F504} Refreshing auth token...
43
+ `);try{let t=await fetch(`${Re}/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 Ko({...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 Ko(s,e){let t=e||s.profile||"default",o=`${yu}-${t}`;try{Jn().set(o,JSON.stringify({...s,profile:t}))}catch{let n=T();$e.mkdirSync(n.config,{recursive:!0});let r=t==="default"?Rt.join(n.config,"auth.json"):Rt.join(n.config,`auth-${t}.json`);$e.writeFileSync(r,JSON.stringify({...s,profile:t},null,2),{mode:384})}}function Qh(s){return new Promise(e=>setTimeout(e,s))}function Zh(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 ma(s){let e=j(),t=U(e),o=e.ansi,n=T(),r=Rt.join(n.config,"config.json"),i={};try{$e.existsSync(r)&&(i=JSON.parse($e.readFileSync(r,"utf8")))}catch{}let c=i.auth?.ssoUrl,u=i.auth?.ssoClientId,d=i.auth?.ssoProvider||"OIDC";if(!c){console.log(""),console.log(` ${t.error} SSO not configured.`),console.log(""),console.log(" Add SSO configuration to your global config:"),console.log(o?a.dim(` ${r}`):` ${r}`),console.log(""),console.log(" {"),console.log(' "auth": {'),console.log(' "method": "sso",'),console.log(' "ssoProvider": "okta",'),console.log(' "ssoUrl": "https://myorg.okta.com/app/monkeyscode/sso",'),console.log(' "ssoClientId": "0oaXXXXXX"'),console.log(" }"),console.log(" }"),console.log("");return}console.log(""),console.log(o?a.bold(` \u{1F3E2} Enterprise SSO (${d})`):` Enterprise SSO (${d})`),console.log("");let p=9876,f=`http://localhost:${p}/callback`,m=Math.random().toString(36).slice(2),g=new URL(c);g.searchParams.set("client_id",u||"monkeyscode-cli"),g.searchParams.set("redirect_uri",f),g.searchParams.set("response_type","code"),g.searchParams.set("scope","openid profile email"),g.searchParams.set("state",m),console.log(o?` ${t.info} Opening SSO login page...`:" Opening SSO login page..."),console.log(""),console.log(o?` ${a.underline.cyan(g.toString())}`:` ${g.toString()}`),console.log("");try{let{exec:S}=await import("node:child_process"),C=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";S(`${C} "${g.toString()}"`)}catch{}let{createServer:h}=await import("node:http"),k=await new Promise(S=>{let C=h((_,x)=>{let E=new URL(_.url||"/",`http://localhost:${p}`);if(E.pathname==="/callback"){let I=E.searchParams.get("code");if(E.searchParams.get("state")!==m){x.writeHead(400,{"Content-Type":"text/html"}),x.end("<html><body><h2>\u274C State mismatch. Please try again.</h2></body></html>"),C.close(),S(null);return}x.writeHead(200,{"Content-Type":"text/html"}),x.end("<html><body><h2>\u2705 Authentication successful!</h2><p>You can close this tab.</p></body></html>"),C.close(),S(I)}else x.writeHead(404),x.end()});C.listen(p,()=>{console.log(o?a.dim(` Listening on http://localhost:${p}/callback ...`):` Listening on http://localhost:${p}/callback ...`)}),setTimeout(()=>{C.close(),S(null)},3e5)});if(!k){console.log(` ${t.error} SSO login failed or timed out.`),console.log("");return}try{let S=await fetch(`${Re}/v1/auth/sso/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:k,redirect_uri:f,client_id:u||"monkeyscode-cli"})});if(!S.ok)throw new Error(`Token exchange failed: HTTP ${S.status}`);let C=await S.json(),_=await da(C.access_token),x=Date.now()+(C.expires_in||172800)*1e3;Ko({access_token:C.access_token,refresh_token:C.refresh_token,expires_at:x,auth_method:"sso",user:_?{id:_.id?.toString(),email:_.email,name:_.name,avatar_url:_.avatar_url??void 0}:void 0,org:_?.orgs?.[0]?{id:_.orgs[0].id?.toString(),name:_.orgs[0].name,plan:_.orgs[0].plan_code}:void 0},s),console.log(""),console.log(` ${t.success} SSO login successful!`),_&&console.log(` ${t.info} ${_.email} (${_.orgs?.[0]?.plan_code||"enterprise"})`),console.log("")}catch(S){console.error(` ${t.error} SSO token exchange failed: ${S instanceof Error?S.message:S}`),console.log("")}}function fa(s){let e=U(),t=T(),o=s||"default",n=o==="default"?Rt.join(t.config,"auth.json"):Rt.join(t.config,`auth-${o}.json`);$e.existsSync(n)&&$e.unlinkSync(n),console.log(` ${e.success} Logged out${o!=="default"?` (profile: ${o})`:""}.`),console.log("")}var $e,Rt,hu,Re,yu,oe=H(()=>{"use strict";$e=y(require("node:fs"),1),Rt=y(require("node:path"),1),hu=y(require("node:readline"),1);W();X();Ce();gu();Re=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com",yu="auth";l(ia,"authLogin");l(aa,"authLoginEmail");l(ca,"authLogout");l(la,"authSetToken");l(zn,"authStatus");l(ua,"authRefresh");l(da,"fetchProfile");l(me,"loadAuth");l(pa,"isAuthenticated");l(Ae,"getAccessToken");l(Ko,"saveAuth");l(Qh,"sleep");l(Zh,"askPassword");l(ma,"authLoginSSO");l(fa,"authLogoutProfile")});async function*bu(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 Kn,wu=H(()=>{"use strict";l(bu,"parseSSEStream");Kn=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 Du(s=!0){return s?ku:ku.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var ku,vu=H(()=>{"use strict";ku=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files longer than 2000 lines are truncated (head + tail) by default \u2014 use start_line/end_line to read a specific range, or full:true to read everything. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(Du,"getToolSchemas")});var ve={};Te(ve,{getSetting:()=>ty,loadSettings:()=>J,saveSettings:()=>ey});function J(){let s=T(),e=ga.join(s.config,"settings.json");try{if(Zt.existsSync(e)){let t=JSON.parse(Zt.readFileSync(e,"utf8"));return{...Su,...t}}}catch{}return{...Su}}function ey(s){let e=T();Zt.mkdirSync(e.config,{recursive:!0});let t=ga.join(e.config,"settings.json"),n={...J(),...s};Zt.writeFileSync(t,JSON.stringify(n,null,2))}function ty(s){return J()[s]}var Zt,ga,Su,Q=H(()=>{"use strict";Zt=y(require("node:fs"),1),ga=y(require("node:path"),1);X();Su={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(J,"loadSettings");l(ey,"saveSettings");l(ty,"getSetting")});var B,le,Ne,ha,oy,Yn,xu=H(()=>{"use strict";B=y(require("node:fs"),1),le=y(require("node:path"),1),Ne=require("node:child_process"),ha=require("node:fs"),oy={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"},Yn=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=oy[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 r=B.readFileSync(t,"utf8").split(`
46
+ `),i=e.start_line||1,c=e.end_line||r.length,u=e.full,d;if(u||r.length<=2e3)d=r;else{let f=r.slice(0,500),m=r.slice(-500);d=[...f,`
47
+ ... (${r.length-1e3} lines truncated \u2014 use start_line/end_line or full:true) ...
48
+ `,...m]}!u&&(e.start_line||e.end_line)&&(d=r.slice(i-1,c));let p=d.map((f,m)=>{let g=(e.start_line||1)+m;return`${String(g).padStart(5)} ${f}`});return{output:`File: ${e.path} (${r.length} lines)
49
+ ${p.join(`
50
+ `)}`}}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(`
51
+ `).length;return{output:`Created ${e.path} (${o} lines)`,wroteFiles:!0,touchedFiles:[e.path]}}editFile(e){let t=this.resolve(e.path);if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}. Use create_file to create it.`};let o=B.readFileSync(t,"utf8"),n=e.old_string,r=e.new_string;if(!o.includes(n))return{output:`Error: old_string not found in ${e.path}. Make sure the string matches EXACTLY including whitespace and indentation. Read the file first to see current content.`};let i=o.split(n).length-1;if(i>1)return{output:`Error: old_string found ${i} times in ${e.path}. Provide a more specific/longer string to match exactly one occurrence.`};this._checkpoints.has(t)||this._checkpoints.set(t,o);let c=o.replace(n,r);B.writeFileSync(t,c);let u=n.split(`
52
+ `).length,d=r.split(`
53
+ `).length;return{output:`Edited ${e.path}: replaced ${u} line(s) with ${d} line(s)`,wroteFiles:!0,touchedFiles:[e.path]}}deleteFile(e){let t=this.resolve(e.path);return B.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,B.readFileSync(t,"utf8")),B.unlinkSync(t),{output:`Deleted ${e.path}`,wroteFiles:!0,touchedFiles:[e.path]}):{output:`Error: File not found: ${e.path}`}}renameFile(e){let t=this.resolve(e.from),o=this.resolve(e.to);return B.existsSync(t)?(this._checkpoints.has(t)||this._checkpoints.set(t,B.readFileSync(t,"utf8")),this._checkpoints.set(o,null),B.mkdirSync(le.dirname(o),{recursive:!0}),B.renameSync(t,o),{output:`Renamed ${e.from} \u2192 ${e.to}`,wroteFiles:!0,touchedFiles:[e.from,e.to]}):{output:`Error: Source file not found: ${e.from}`}}listDir(e){let t=this.resolve(e.path||".");if(!B.existsSync(t))return{output:`Error: Directory not found: ${e.path}`};let o=e.recursive,n=this.listEntries(t,o?3:0,"");return n.length===0?{output:`Directory ${e.path||"."} is empty`}:{output:n.join(`
54
+ `)}}listEntries(e,t,o){let n=[],r;try{r=B.readdirSync(e,{withFileTypes:!0})}catch{return[` ${o}(permission denied)`]}r.sort((c,u)=>c.isDirectory()&&!u.isDirectory()?-1:!c.isDirectory()&&u.isDirectory()?1:c.name.localeCompare(u.name));let i=new Set(["node_modules",".git","__pycache__",".next","dist",".turbo",".cache"]);for(let c of r)if(!(i.has(c.name)&&!o))if(c.isDirectory()){if(n.push(` ${o}${c.name}/`),t>0){let u=this.listEntries(le.join(e,c.name),t-1,o+" ");n.push(...u)}}else{let u=B.statSync(le.join(e,c.name)).size,d=u<1024?`${u}B`:u<1048576?`${(u/1024).toFixed(1)}K`:`${(u/1048576).toFixed(1)}M`;n.push(` ${o}${c.name} (${d})`)}return n}grepSearch(e){let t=e.pattern,o=this.resolve(e.path||"."),n=e.include,r=e.fixed_strings,i=e.case_insensitive,c=e.max_count,u=["--line-number","--no-heading","--color=never"];r&&u.push("--fixed-strings"),i&&u.push("--ignore-case"),c&&u.push("--max-count",String(c)),n&&u.push("--glob",n),u.push("--",t,o);try{let d=(0,Ne.spawnSync)("rg",u,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1048576});if(d.status===0&&d.stdout){let p=d.stdout.split(`
55
+ `).filter(Boolean);return p.length>100?{output:`Found ${p.length} matches (showing first 100):
56
+ ${p.slice(0,100).join(`
57
+ `)}`}:{output:`Found ${p.length} match(es):
58
+ ${p.join(`
59
+ `)}`}}if(d.status===1)return{output:"No matches found."}}catch{}try{let d=["-rn","--color=never"];r&&d.push("-F"),i&&d.push("-i"),n&&d.push("--include",n),d.push("--",t,o);let p=(0,Ne.spawnSync)("grep",d,{cwd:this.workspace,encoding:"utf8",timeout:3e4,maxBuffer:1024*1024});if(p.stdout){let f=p.stdout.split(`
60
+ `).filter(Boolean);return{output:`Found ${f.length} match(es):
61
+ ${f.slice(0,100).join(`
62
+ `)}`}}return{output:"No matches found."}}catch(d){return{output:`Search error: ${d instanceof Error?d.message:d}`}}}globFiles(e){let t=e.pattern,o=this.resolve(e.path||".");try{let n=(0,Ne.spawnSync)("find",[o,"-type","f","-name",t.replace("**/","")],{cwd:this.workspace,encoding:"utf8",timeout:1e4});if(n.stdout){let r=n.stdout.split(`
63
+ `).filter(Boolean).map(i=>le.relative(this.workspace,i)).sort();return{output:r.length>0?`Found ${r.length} file(s):
64
+ ${r.join(`
65
+ `)}`:"No files found."}}return{output:"No files found."}}catch(n){return{output:`Glob error: ${n instanceof Error?n.message:n}`}}}async runCommand(e){let t=e.command,o=e.cwd?this.resolve(e.cwd):this.workspace,n=(e.timeout||120)*1e3,r="bash",i=["-c",t];if(this._sandbox)try{let c=await this._sandbox.wrapCommand("bash",["-c",t]);r=c.command,i=c.args}catch{}return new Promise(c=>{let u=(0,Ne.spawn)(r,i,{cwd:o,env:{...process.env,TERM:"dumb"},stdio:["pipe","pipe","pipe"],timeout:n}),d="",p="";u.stdout.on("data",f=>{d+=f.toString(),d.length>102400&&u.kill()}),u.stderr.on("data",f=>{p+=f.toString()}),u.on("close",f=>{let m="";d&&(m+=d),p&&(m+=(d?`
66
+
67
+ STDERR:
68
+ `:"")+p),m||(m=`(no output, exit code ${f})`),d.length>102400&&(m=m.slice(0,102400)+`
69
+ ... (output truncated at 100KB)`),m=`Exit code: ${f}
70
+ ${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}
71
+ ${c.url}
72
+ ${c.snippet}`).join(`
73
+
74
+ `)}}catch(n){return{output:`Web search failed: ${n instanceof Error?n.message:n}`}}}async readUrl(e){let t=e.url,o=e.max_length||5e4;try{let n=new URL(t);if(n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname.startsWith("192.168.")||n.hostname.startsWith("10."))return{output:"Error: Cannot fetch localhost or private network URLs for security reasons."}}catch{return{output:`Error: Invalid URL: ${t}`}}try{let n=await fetch(t,{headers:{"User-Agent":"MonkeysCode-CLI/0.1"},signal:this.signal});if(!n.ok)return{output:`Error: HTTP ${n.status} from ${t}`};let r=await n.text();return r.length>o&&(r=r.slice(0,o)+`
75
+
76
+ ... (truncated)`),{output:r}}catch(n){return{output:`Fetch failed: ${n instanceof Error?n.message:n}`}}}gitExec(e,t){try{let o=t.message||void 0,n=`git ${e}`;return o&&(n+=` -m ${JSON.stringify(o)}`),{output:(0,Ne.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,Ne.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,Ne.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,Ne.execSync)("git add -A",{cwd:this.workspace,encoding:"utf8",timeout:1e4}),{output:(0,Ne.execSync)(`git commit -m ${JSON.stringify(t)}`,{cwd:this.workspace,encoding:"utf8",timeout:15e3}),wroteFiles:!0}}catch(n){return{output:`Git commit error: ${n.stderr||n.message}`}}}todoWrite(e){let t=e.todos;return!t||!Array.isArray(t)?{output:"Error: todos must be an array of {id, content, status}"}:{output:`Task plan updated:
77
+ ${t.map(n=>` ${n.status==="done"?"\u2705":n.status==="in_progress"?"\u{1F504}":"\u2B1C"} [${n.status}] ${n.content}`).join(`
78
+ `)}`}}searchFiles(e){let t=e.pattern,o=e.path||".",n=e.max_results||50;try{let r=this.resolve(o),c=(0,ha.globSync)(t,{cwd:r}).filter(p=>{try{return B.statSync(le.join(r,p)).isFile()}catch{return!1}}),u=c.slice(0,n);return u.length===0?{output:`No files matching "${t}" in ${o}`}:{output:`Found ${c.length} file(s)${c.length>n?` (showing first ${n})`:""}:`+`
79
+ `+u.join(`
80
+ `)}}catch(r){return{output:`Error searching files: ${r.message}`}}}replaceInFile(e){let t=this.resolve(e.path),o=e.old_string,n=e.new_string,r=e.allow_multiple||!1;if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}`};let i=B.readFileSync(t,"utf8");this._checkpoints.has(t)||this._checkpoints.set(t,i);let c=i.split(o).length-1;if(c===0)return{output:`Error: String not found in ${e.path}. Make sure old_string matches exactly (including whitespace and indentation).`};if(c>1&&!r)return{output:`Error: Found ${c} occurrences of the search string in ${e.path}. Set allow_multiple:true to replace all, or use a more specific string.`};let u=r?i.replaceAll(o,n):i.replace(o,n);return B.writeFileSync(t,u,"utf8"),{output:`Replaced ${r?c:1} occurrence(s) in ${e.path}`,wroteFiles:!0,touchedFiles:[t]}}patchFile(e){let t=this.resolve(e.path),o=e.patch;if(!B.existsSync(t))return{output:`Error: File not found: ${e.path}`};let n=B.readFileSync(t,"utf8");this._checkpoints.has(t)||this._checkpoints.set(t,n);try{let r=n.split(`
81
+ `),i=o.split(`
82
+ `),c=[],u=0;for(let d of i)d.startsWith("---")||d.startsWith("+++")||d.startsWith("@@")||(d.startsWith("-")?u++:d.startsWith("+")?c.push(d.slice(1)):(d.startsWith(" ")||d==="")&&u<r.length&&(c.push(r[u]),u++));for(;u<r.length;)c.push(r[u]),u++;return B.writeFileSync(t,c.join(`
83
+ `),"utf8"),{output:`Patch applied to ${e.path}`,wroteFiles:!0,touchedFiles:[t]}}catch(r){return{output:`Error applying patch: ${r.message}`}}}runTests(e){let t=e.path,o=e.pattern,n=e.framework||"auto";n==="auto"&&(n=this.detectTestFramework());let r;switch(n){case"jest":r="npx jest --no-coverage",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"vitest":r="npx vitest run",t&&(r+=` ${t}`),o&&(r+=` -t ${JSON.stringify(o)}`);break;case"mocha":r="npx mocha",t&&(r+=` ${t}`),o&&(r+=` --grep ${JSON.stringify(o)}`);break;case"pytest":r="python -m pytest -v",t&&(r+=` ${t}`),o&&(r+=` -k ${JSON.stringify(o)}`);break;case"go":r="go test -v",t?r+=` ./${t}/...`:r+=" ./...",o&&(r+=` -run ${JSON.stringify(o)}`);break;case"cargo":r="cargo test",o&&(r+=` ${o}`),r+=" -- --nocapture";break;case"dotnet":r="dotnet test --verbosity normal",t&&(r+=` ${t}`),o&&(r+=` --filter ${JSON.stringify(o)}`);break;case"rspec":r="bundle exec rspec",t&&(r+=` ${t}`);break;default:return{output:`Unknown test framework: ${n}. Supported: jest, vitest, mocha, pytest, go, cargo, dotnet, rspec`}}try{let i=(0,Ne.execSync)(r,{cwd:this.workspace,encoding:"utf8",timeout:12e4,maxBuffer:10485760,env:{...process.env,FORCE_COLOR:"0",CI:"1"}});return{output:`[${n}] Tests passed:
84
+ ${i.slice(0,8e3)}`}}catch(i){let c=i.stdout||i.stderr||i.message;return{output:`[${n}] Tests failed:
85
+ ${c.slice(0,8e3)}`}}}detectTestFramework(){let e=le.join(this.workspace,"package.json");if(B.existsSync(e)){try{let t=JSON.parse(B.readFileSync(e,"utf8")),o={...t.dependencies,...t.devDependencies};if(o.vitest)return"vitest";if(o.jest)return"jest";if(o.mocha)return"mocha"}catch{}return"jest"}return B.existsSync(le.join(this.workspace,"pyproject.toml"))||B.existsSync(le.join(this.workspace,"setup.py"))||B.existsSync(le.join(this.workspace,"pytest.ini"))?"pytest":B.existsSync(le.join(this.workspace,"go.mod"))?"go":B.existsSync(le.join(this.workspace,"Cargo.toml"))?"cargo":B.existsSync(le.join(this.workspace,"Gemfile"))?"rspec":(0,ha.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(),ve))).loadSettings(),{getAccessToken:r}=await Promise.resolve().then(()=>(oe(),ge)),{AgentLoop:i}=await Promise.resolve().then(()=>(Je(),Yo)),c=await r();if(!c)return{output:"Error: Not authenticated. Cannot spawn subagent."};let u=new i({platformUrl:n.platformUrl,token:c,model:o||n.defaultModel,workspace:this.workspace,mode:"auto",maxTurns:30,userId:void 0,orgId:void 0}),d=`subagent-${Date.now().toString(36)}`,p=await u.run(t);return{output:[`Subagent ${d} completed:`,` Turns: ${p.turns}`,` Tokens: ${p.tokensIn+p.tokensOut}`,` Files modified: ${p.filesModified.join(", ")||"none"}`,` Duration: ${Math.round(p.duration/1e3)}s`].join(`
86
+ `),wroteFiles:p.filesModified.length>0,touchedFiles:p.filesModified}}catch(n){return{output:`Subagent error: ${n.message}`}}}remember(e){let t=e.content,o=e.category||"general";try{let n=le.join(this.workspace,".monkeyscode");B.existsSync(n)||B.mkdirSync(n,{recursive:!0});let r=le.join(n,"MEMORY.md"),i=new Date().toISOString().split("T")[0],c=`
87
+ - [${o}] ${t} _(${i})_
88
+ `,u="";return B.existsSync(r)?u=B.readFileSync(r,"utf8"):u=`# Project Memory
89
+
90
+ Facts, conventions, and decisions learned during sessions.
91
+ `,B.writeFileSync(r,u+c,"utf8"),{output:`Remembered: [${o}] ${t}`,wroteFiles:!0,touchedFiles:[r]}}catch(n){return{output:`Error saving memory: ${n.message}`}}}async _executeMCPTool(e,t){if(!this._mcpClient)return{output:"Error: MCP client not initialized. Configure MCP servers in .monkeyscode/mcp.json"};let o=e.slice(4).split("_");if(o.length<2)return{output:`Error: Invalid MCP tool name "${e}". Expected format: mcp_<server>_<tool>`};let n=o[0],r=o.slice(1).join("_");try{let i=await this._mcpClient.callTool(n,r,t);return{output:i.isError?`MCP Error (${n}/${r}): ${i.content}`:i.content}}catch(i){return{output:`MCP tool error: ${i.message}`}}}resolve(e){return le.isAbsolute(e)?e:le.resolve(this.workspace,e)}}});var Xn,ya=H(()=>{"use strict";Xn=["~/.ssh","~/.aws","~/.config/gcloud","~/.config/gh","~/.azure","~/.kube","~/.docker/config.json","~/.npmrc","~/.pypirc","~/.env","~/.netrc","~/.gnupg"]});var Cu,$u,js,Ns,_u=H(()=>{"use strict";Cu=require("node:child_process"),$u=y(require("node:os"),1),js=y(require("node:path"),1);ya();Ns=class{static{l(this,"BubblewrapProvider")}name="bubblewrap";async isAvailable(){try{return(0,Cu.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=$u.homedir(),r=[];r.push("--ro-bind","/","/");let i=js.resolve(o.workspace);r.push("--bind",i,i),r.push("--tmpfs","/tmp"),r.push("--dev","/dev"),r.push("--proc","/proc");for(let c of Xn){let u=c.replace("~",n);r.push("--tmpfs",u)}return r.push("--tmpfs",js.join(n,".env")),r.push("--tmpfs",js.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 Eu,Bs,Qn,Xo,Ls,Fu=H(()=>{"use strict";Eu=require("node:child_process"),Bs=y(require("node:os"),1),Qn=y(require("node:path"),1),Xo=y(require("node:fs"),1);ya();Ls=class{static{l(this,"SandboxExecProvider")}name="sandbox-exec";profilePath=null;async isAvailable(){try{return(0,Eu.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=Qn.join(Bs.tmpdir(),`mc-sandbox-${process.pid}.sb`);return Xo.writeFileSync(r,n,"utf-8"),this.profilePath=r,{command:"sandbox-exec",args:["-f",r,e,...t]}}async setup(e){}async teardown(){this.profilePath&&Xo.existsSync(this.profilePath)&&(Xo.unlinkSync(this.profilePath),this.profilePath=null)}generateProfile(e){let t=Bs.homedir(),o=Qn.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 "${Bs.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 Xn){let i=r.replace("~",t);n.push(`; Block credential: ${r}`),n.push(`(deny file-read* file-write* (subpath "${i}"))`)}return n.push(""),e.network==="none"?(n.push("; Block all network access"),n.push("(deny network*)")):e.network==="local"?(n.push("; Allow localhost only"),n.push('(allow network* (local ip "localhost:*"))'),n.push("(deny network*)")):(n.push("; Full network access"),n.push("(allow network*)")),n.join(`
92
+ `)}}});var ba,Zn,er,Qo,Us,Tu=H(()=>{"use strict";ba=require("node:child_process"),Zn=y(require("node:os"),1),er=y(require("node:path"),1),Qo=y(require("node:fs"),1),Us=class{static{l(this,"WindowsSandboxProvider")}name="windows-sandbox";wsbConfigPath=null;mode=null;async isAvailable(){if(Zn.platform()!=="win32")return{available:!1,reason:"Not running on Windows"};try{return(0,ba.execSync)("where WindowsSandbox.exe",{stdio:"pipe"}),this.mode="windows-sandbox",{available:!0}}catch{}try{return(0,ba.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=er.resolve(e.workspace),o=this.generateWsbConfig(t,e);this.wsbConfigPath=er.join(Zn.tmpdir(),`mc-sandbox-${process.pid}.wsb`),Qo.writeFileSync(this.wsbConfigPath,o,"utf-8")}}async teardown(){this.wsbConfigPath&&Qo.existsSync(this.wsbConfigPath)&&(Qo.unlinkSync(this.wsbConfigPath),this.wsbConfigPath=null)}wrapWithWindowsSandbox(e,t,o){let n=[e,...t].join(" ");return{command:"cmd.exe",args:["/c",`start /wait WindowsSandbox.exe "${this.wsbConfigPath}" && cmd /c "${n}"`]}}generateWsbConfig(e,t){return`
93
+ <Configuration>
94
+ <VGpu>Disable</VGpu>
95
+ <Networking>${t.network==="none"?"Disable":"Default"}</Networking>
96
+ <MappedFolders>
97
+ <MappedFolder>
98
+ <HostFolder>${e}</HostFolder>
99
+ <SandboxFolder>C:\\Workspace</SandboxFolder>
100
+ <ReadOnly>false</ReadOnly>
101
+ </MappedFolder>
102
+ </MappedFolders>
103
+ <LogonCommand>
104
+ <Command>cmd.exe /k cd C:\\Workspace</Command>
105
+ </LogonCommand>
106
+ <MemoryInMB>2048</MemoryInMB>
107
+ </Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var eo,So,to,Au,Ru,Ws,xo,Pu=H(()=>{"use strict";eo=require("node:child_process"),So=y(require("node:path"),1),to=y(require("node:fs"),1),Au=y(require("node:crypto"),1),Ru="monkeyscode-sandbox",Ws="/workspace",xo=class{static{l(this,"DockerSandboxProvider")}name="docker";containerId=null;imageName=Ru;async isAvailable(){try{return(0,eo.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",Ws),n.push(this.containerId),n.push(e,...t);else{n.splice(0),n.push("run","--rm"),n.push("-w",Ws);let r=So.resolve(o.workspace);n.push("-v",`${r}:${Ws}`),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||Ru;let t=So.resolve(e.workspace),o=e.dockerfilePath||So.join(t,".monkeyscode","Dockerfile.sandbox");if(to.existsSync(o)){let c=(0,eo.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-${Au.randomUUID().substring(0,8)}`,"-w",Ws,"-v",`${t}:${Ws}`];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,eo.spawnSync)("docker",r,{stdio:"pipe"});i.status===0&&(this.containerId=i.stdout.toString().trim().substring(0,12))}async teardown(){if(this.containerId){try{(0,eo.execSync)(`docker rm -f ${this.containerId}`,{stdio:"pipe",timeout:1e4})}catch{}this.containerId=null}}async ensureBaseImage(){try{(0,eo.execSync)(`docker image inspect ${this.imageName}`,{stdio:"pipe"});return}catch{}let e=`
108
+ FROM ubuntu:22.04
109
+ RUN apt-get update && apt-get install -y --no-install-recommends \\
110
+ git curl wget ca-certificates \\
111
+ nodejs npm \\
112
+ python3 python3-pip \\
113
+ ripgrep fd-find jq \\
114
+ && rm -rf /var/lib/apt/lists/*
115
+ RUN useradd -m -s /bin/bash sandbox
116
+ USER sandbox
117
+ WORKDIR /workspace
118
+ `.trim(),t=So.join(require("node:os").tmpdir(),"mc-sandbox-build");to.mkdirSync(t,{recursive:!0}),to.writeFileSync(So.join(t,"Dockerfile"),e);let o=(0,eo.spawnSync)("docker",["build","-t",this.imageName,t],{stdio:"pipe",timeout:3e5});if(to.rmSync(t,{recursive:!0,force:!0}),o.status!==0)throw new Error(`Failed to build sandbox base image: ${o.stderr?.toString()}`)}}});function Ou(s){switch(s){case"linux":return[new Ns,new xo];case"macos":return[new Ls,new xo];case"windows":return[new Us,new xo]}}function tr(s,e={}){return{enabled:!1,provider:"auto",network:"none",workspace:s,...e}}var Zo,wa=H(()=>{"use strict";X();_u();Fu();Tu();Pu();l(Ou,"getProviderCandidates");Zo=class{static{l(this,"SandboxManager")}config;provider=null;platform;initialized=!1;constructor(e){this.config=e,this.platform=De()}async initialize(){if(!this.config.enabled)return this.initialized=!0,{status:"disabled",provider:"none",description:"Sandbox disabled (--no-sandbox)",network:this.config.network};if(this.config.provider!=="auto"&&(this.provider=this.getExplicitProvider(this.config.provider),this.provider)){let t=await this.provider.isAvailable();return t.available?(await this.provider.setup(this.config),this.initialized=!0,{status:"active",provider:this.provider.name,description:`Sandboxed via ${this.provider.name}`,network:this.config.network}):{status:"unavailable",provider:this.config.provider,description:`${this.config.provider} not available: ${t.reason}`,network:this.config.network}}let e=Ou(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=Ou(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 Ns;case"sandbox-exec":return new Ls;case"windows-sandbox":case"appcontainer":return new Us;case"docker":return new xo;default:return null}}};l(tr,"createDefaultSandboxConfig")});function Mu(s){switch(s){case 0:return"allow";case 1:return"deny";case 2:return"modify";default:return"allow"}}var Iu,ju=H(()=>{"use strict";l(Mu,"exitCodeToAction");Iu={enabled:!0,timeoutMs:1e4}});function Co(s){let e=T(),t=ft.join(s,".monkeyscode","hooks"),o=ft.join(e.config,"hooks"),n=Nu(t,"project"),r=Nu(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 Nu(s,e){if(!es.existsSync(s))return[];let t=[];try{let o=es.readdirSync(s,{withFileTypes:!0});for(let n of o){if(!n.isFile())continue;let r=ft.extname(n.name).toLowerCase(),i=ny[r];if(!i)continue;let c=ft.basename(n.name,r).toLowerCase(),u=sy[c];u&&t.push({event:u,scriptPath:ft.join(s,n.name),source:e,scriptType:i})}}catch{}return t}function Bu(s){let e=T(),t=ft.join(s,".monkeyscode","hooks"),o=ft.join(e.config,"hooks");return[{path:t,source:"project",exists:es.existsSync(t)},{path:o,source:"global",exists:es.existsSync(o)}]}var es,ft,sy,ny,or=H(()=>{"use strict";es=y(require("node:fs"),1),ft=y(require("node:path"),1);X();sy={"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"},ny={".sh":"sh",".bash":"sh",".ps1":"ps1",".cmd":"cmd",".bat":"cmd",".js":"js",".mjs":"js",".py":"py"};l(Co,"loadHooks");l(Nu,"scanHookDirectory");l(Bu,"getHookDirectories")});var Lu,$o,ka=H(()=>{"use strict";Lu=require("node:child_process");X();ju();or();$o=class{static{l(this,"HookRunner")}hooks;config;platform=De();constructor(e,t={}){this.config={...Iu,...t},this.hooks=this.config.enabled?Co(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?Co(e):[]}async executeHook(e,t){let o=Date.now();return new Promise(n=>{let{command:r,args:i}=this.getExecutor(e),c=(0,Lu.spawn)(r,[...i,e.scriptPath],{stdio:["pipe","pipe","pipe"],timeout:this.config.timeoutMs,env:{...process.env,MC_HOOK_EVENT:t.event,MC_WORKSPACE:t.workspace,MC_SESSION_ID:t.sessionId||""}}),u="",d="",p=!1;c.stdout?.on("data",m=>{u+=m.toString()}),c.stderr?.on("data",m=>{d+=m.toString()});let f=JSON.stringify(t);c.stdin?.write(f),c.stdin?.end(),c.on("error",m=>{n({hook:e,exitCode:-1,action:"allow",stdout:u,stderr:m.message,durationMs:Date.now()-o,timedOut:!1})}),c.on("close",m=>{let g=m??0;n({hook:e,exitCode:g,action:p?"allow":Mu(g),stdout:u,stderr:d,durationMs:Date.now()-o,timedOut:p})}),setTimeout(()=>{c.killed||(p=!0,c.kill("SIGTERM"),setTimeout(()=>{c.killed||c.kill("SIGKILL")},2e3))},this.config.timeoutMs)})}getExecutor(e){switch(e.scriptType){case"sh":return{command:"/bin/sh",args:[]};case"ps1":return{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","Bypass","-File"]};case"cmd":return{command:"cmd.exe",args:["/c"]};case"js":return{command:"node",args:[]};case"py":return{command:this.platform==="windows"?"python":"python3",args:[]};default:return{command:e.scriptPath,args:[]}}}}});function Wu(s,e=60){if(!At.ansi){console.log(`
119
+ ${s}
120
+ ${"\u2500".repeat(e)}`);return}let t="\u2500".repeat(Math.max(0,e-s.length-4));console.log(""),console.log(` ${be.accent("\u2500\u2500")} ${be.bold(s)} ${be.accent(t)}`)}function Hu(s,e){let t=" "+s.map(n=>{let r=n.header;return Uu(r,n.width,n.align||"left")}).join(" ");console.log(At.ansi?be.dim(t):t);let o=" "+s.map(n=>"\u2500".repeat(n.width)).join("\u2500\u2500");console.log(At.ansi?be.dim(o):o);for(let n of e){let r=" "+n.cells.map((i,c)=>{let u=s[c];return Uu(i,u.width,u.align||"left")}).join(" ");n.dim&&At.ansi?r=be.dim(r):n.highlight&&At.ansi&&(r=be.accent(r)),console.log(r)}}function Uu(s,e,t){let o=iy(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 Da(s){console.log(At.ansi?` ${be.dim(s)}`:` ${s}`)}function Gu(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 va(s){return s===0?At.ansi?be.success("Free"):"Free":`$${s.toFixed(s<1?4:2)}`}function iy(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}function Hs(){console.log("")}var ry,be,At,jS,NS,qu=H(()=>{"use strict";W();Ce();ry=y(require("node:readline"),1),be={navy:a.hex("#051E50"),teal:a.hex("#A3CAD3"),accent:a.hex("#6B8DD6"),success:a.hex("#4ADE80"),warning:a.hex("#FBBF24"),error:a.hex("#F87171"),dim:a.dim,bold:a.bold,muted:a.gray},At=j(),jS=U(At),NS=Ve(At);l(Wu,"sectionHeader");l(Hu,"printTable");l(Uu,"padCell");l(Da,"hint");l(Gu,"formatTokens");l(va,"formatCost");l(iy,"stripAnsi");l(Hs,"blank")});function gt(s){if(s==="auto")return"auto";let e=s.toLowerCase(),t=Pt.find(r=>r.id===e);if(t)return t.id;let o=Pt.find(r=>r.aliases.some(i=>i.toLowerCase()===e));if(o)return o.id;let n=Pt.find(r=>r.displayName.toLowerCase().includes(e));return n?n.id:s}function sr(s){let e=gt(s);return Pt.find(t=>t.id===e)??null}function ay(s,e){let t=gt(s),o=Pt.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 Gs(s,e,t,o=0){let n=Pt.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 Sa(s){let e=j().ansi,t=j().emoji;Wu("Available Models"),Hs();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=Pt.map(r=>{let i=ay(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":`${va(r.costInputPerM)} / ${va(r.costOutputPerM)}`,m=[];r.thinking&&m.push(t?"\u{1F4AD} Think":"Think"),c&&m.push(e?be.warning(`\u{1F512} ${i.requiredPlan}+`):`[${i.requiredPlan}+]`);let g=m.join(" ");return{cells:[e?c?be.dim(r.displayName):a.bold(r.displayName):r.displayName,d,Gu(r.contextWindow),p,f,g],dim:c}});if(Hu(o,n),Hs(),e){console.log(` ${be.dim("Aliases:")}`);for(let r of Pt)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 Pt)r.aliases.length>0&&console.log(` ${r.displayName}: ${r.aliases.join(", ")}`)}Hs(),Da("Use --model <name|alias> to select a model"),Da("Use --model auto for smart routing based on task complexity"),Hs()}var Pt,nr=H(()=>{"use strict";W();Ce();qu();Pt=[{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(gt,"resolveModelAlias");l(sr,"getModelInfo");l(ay,"checkModelAccess");l(Gs,"estimateCost");l(Sa,"printModelList")});function Vu(s,e,t){let o=sr(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:`${xa.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:`${xa.openai}/v1/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.openai}`},isDirect:!0,provider:"openai",isAnthropicFormat:!1}:n==="google"&&r.google?{url:`${xa.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 xa,Ju=H(()=>{"use strict";nr();xa={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"};l(Vu,"resolveModelRoute")});var zu=H(()=>{"use strict"});var _a={};Te(_a,{buildSkillsContext:()=>$a,listAllSkills:()=>py,loadSkills:()=>Ku});function ly(s){let e=s.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!e)return{meta:{},body:s.trim()};let t={};for(let o of e[1].split(`
121
+ `)){let n=o.match(/^(\w+)\s*:\s*(.+)$/);if(!n)continue;let[,r,i]=n;switch(r){case"name":t.name=i.trim();break;case"description":t.description=i.trim();break;case"trigger":t.trigger=i.trim();break;case"priority":t.priority=parseInt(i.trim(),10);break;case"enabled":t.enabled=i.trim().toLowerCase()!=="false";break}}return{meta:t,body:e[2].trim()}}function uy(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 dy(s,e,t){let o=oo.join(s,"skill.md");if(!Ot.existsSync(o))return null;try{let n=Ot.readFileSync(o,"utf8"),{meta:r,body:i}=ly(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:uy(r.trigger),enabled:r.enabled!==!1,priority:r.priority??50,filePath:o}:null}catch{return null}}function rr(s,e){if(!Ot.existsSync(s))return[];try{return Ot.readdirSync(s).filter(t=>{let o=oo.join(s,t);return Ot.statSync(o).isDirectory()}).map(t=>dy(oo.join(s,t),t,e)).filter(t=>t!==null)}catch{return[]}}function Ku(s){let e=oo.join(s,".monkeyscode","skills"),t=oo.join(Ca.homedir(),".monkeyscode","skills"),o=rr(t,"global"),n=rr(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 $a(s){let e=Ku(s);if(e.length===0)return null;let t=[],o=0;for(let n of e){let r=Math.ceil(n.systemPrompt.length/4);if(o+r>2e3)break;t.push(`### Skill: ${n.name}
122
+ ${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
123
+
124
+ `):null}function py(s){let e=oo.join(s,".monkeyscode","skills"),t=oo.join(Ca.homedir(),".monkeyscode","skills"),o=rr(t,"global"),n=rr(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 Ot,oo,Ca,ir=H(()=>{"use strict";Ot=y(require("node:fs"),1),oo=y(require("node:path"),1),Ca=y(require("node:os"),1);zu();l(ly,"parseFrontmatter");l(uy,"parseTrigger");l(dy,"loadSkillFromDir");l(rr,"scanSkillsDir");l(Ku,"loadSkills");l($a,"buildSkillsContext");l(py,"listAllSkills")});function Yu(s){let e=Date.now(),t=[],o=[];switch(o.push("You are MonkeysCode, an expert AI coding assistant running in a terminal (CLI mode)."),o.push("You help developers by reading, writing, and modifying code files, running commands, and answering questions."),o.push(`
125
+ ## Available Tools`),o.push("You have access to file operations (read, edit, create, delete, rename, list, search), shell commands, and git operations."),o.push("Always use the appropriate tool rather than guessing file contents. Always read a file before editing it."),o.push(`
126
+ ## Task Tracking`),o.push("For any task with 3+ steps, maintain a checklist with todo_write: send the full list every time, keep exactly one item in_progress, and update it immediately after finishing each step."),o.push("Use ask_user when blocked on a genuine decision."),s.webEnabled&&(o.push(`
127
+ ## 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(`
128
+ ## Mode: Plan`),o.push("Plan mode: read-only. Explore the codebase, write a detailed plan, then present it to the user for approval. Do NOT make any file changes.");break;case"manual":o.push(`
129
+ ## Mode: Manual`),o.push("Always describe what you intend to do and wait for user confirmation before making changes.");break;case"accept_edits":o.push(`
130
+ ## Mode: Accept Edits`),o.push("You may make file changes without asking. Be efficient and direct.");break;case"auto":default:o.push(`
131
+ ## Mode: Auto`),o.push("Use your judgment on when to proceed and when to ask. For safe, reversible operations, proceed directly.");break}o.push(`
132
+ ## Important Guidelines`),o.push("- Be concise in responses. Show code changes, not lengthy explanations."),o.push("- When editing files, use edit_file with the EXACT current content as old_string."),o.push("- When running commands, prefer non-interactive commands (add -y, --yes, etc.)."),o.push(`- Today's date: ${new Date().toISOString().split("T")[0]}`),t.push({role:"system",content:o.join(`
133
+ `),timestamp:e});let n=[];n.push("## Workspace Context"),n.push(`- Path: ${s.workspace}`),n.push(`- Execution: Local terminal (Node.js ${process.version})`),s.sandboxed&&n.push("- Sandbox: Active \u2014 commands run in an isolated environment");let r=Mt.basename(s.workspace);n.push(`- Project: ${r}`);let i=my(s.workspace);i&&n.push(`- Stack: ${i}`),t.push({role:"system",content:n.join(`
134
+ `),timestamp:e});let c=gy(s.workspace);c&&t.push({role:"system",content:`## Workspace Rules
135
+
136
+ ${c}`,timestamp:e});let u=$a(s.workspace);u&&t.push({role:"system",content:`## Active Skills
137
+
138
+ ${u}`,timestamp:e});let d=fy(s.workspace);if(d){let p=[];p.push("## Current State"),p.push(`- Branch: ${d.branch}${d.dirty?" (uncommitted changes)":""}`),t.push({role:"system",content:p.join(`
139
+ `),timestamp:e})}return t}function my(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)ot.existsSync(Mt.join(s,o))&&t.push(n);if(ot.existsSync(Mt.join(s,"package.json")))try{let o=JSON.parse(ot.readFileSync(Mt.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 fy(s){try{let e=(0,Ea.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",timeout:3e3,stdio:["pipe","pipe","pipe"]}).trim(),t=(0,Ea.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 gy(s){let e=[];for(let o of["AGENTS.md","CLAUDE.md","GEMINI.md",".monkeyscode/AGENTS.md"]){let n=Mt.join(s,o);if(ot.existsSync(n))try{let r=ot.readFileSync(n,"utf8");r.trim()&&e.push(`### ${o}
140
+
141
+ ${r}`)}catch{}}let t=Mt.join(s,".monkeyscode","rules");if(ot.existsSync(t))try{let o=ot.readdirSync(t).filter(n=>n.endsWith(".md")).sort();for(let n of o){let r=ot.readFileSync(Mt.join(t,n),"utf8");r.trim()&&e.push(`### ${n}
142
+
143
+ ${r}`)}}catch{}return e.length>0?e.join(`
144
+
145
+ ---
146
+
147
+ `):null}var ot,Mt,Ea,Xu=H(()=>{"use strict";ot=y(require("node:fs"),1),Mt=y(require("node:path"),1),Ea=require("node:child_process");ir();l(Yu,"buildSystemMessages");l(my,"detectProjectType");l(fy,"getGitInfo");l(gy,"loadWorkspaceRules")});function Fa(s){return Math.ceil(s.length/4)}function so(s,e=6e3){let t=e;for(let o of s)if(t+=Fa(o.content),o.tool_calls)for(let n of o.tool_calls)t+=Fa(JSON.stringify(n.arguments)),n.result&&(t+=Fa(n.result));return t}function cr(s,e){if(e&&e>0)return e;let t=hy.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 Qu(s,e,t=.85){return s>=e*t}function Ta(s,e,t){let r=Math.max(4e3,(e||128e3)-(t||15e3)),i=Math.floor(r*.9)*4;if(ar(s)<=i)return{messages:s,elided:0,savedTokens:0};let u=s.map(k=>({...k})),d=0,p=so(s);for(let k of u)k.role==="tool"&&k.content&&k.content.length>8e3&&(k.content=k.content.slice(0,8e3)+`
148
+ ... [output truncated]`,d++);if(ar(u)<=i)return{messages:u,elided:d,savedTokens:p-so(u)};let f=u.filter(k=>k.role!=="system").length,m=Math.max(10,Math.floor(f*.2)),g=Math.floor((f-m)/20)*20;if(g>0){let k=0;for(let S=0;S<u.length;S++){if(u[S].role==="system")continue;if(k++,k>g)break;let C=u[S];if(k<=Math.floor(g*.75)){if(C.role==="tool"&&C.content&&C.content.length>150){let _=C.content.includes("Error")||C.content.includes("error"),x=C.content.split(`
149
+ `)[0].slice(0,100);C.content=_?`[error] ${x}`:`[ok] ${x}`,d++}if(C.role==="assistant"&&C.content&&C.content.length>300&&!C.tool_calls?.length&&(C.content=C.content.slice(0,200)+`
150
+ ...[summarized]`),C.role==="assistant"&&C.tool_calls?.length){let _=C.tool_calls.map(x=>`[called ${x.name||"unknown"}]`);C.content||(C.content=_.join(", "))}}else if(C.role==="assistant"&&C.content&&C.content.length>500&&!C.tool_calls?.length&&(C.content=C.content.slice(0,400)+`
151
+ ...[truncated]`),C.role==="tool"&&C.content&&C.content.length>500){let _=C.content.includes("Error")||C.content.includes("error"),x=C.content.split(`
152
+ `)[0].slice(0,150);C.content=_?`[error] ${x}`:`[ok] ${x}`,d++}}}if(ar(u)<=i)return{messages:u,elided:d,savedTokens:p-so(u)};let h=Math.floor(i*.85),b=ar(u);for(;b>h&&u.length>6;){let k=u.findIndex(_=>_.role==="user");if(k<0)break;let S=k;for(let _=k+1;_<u.length;_++){let x=u[_];if(x.role==="user"&&!("tool_call_id"in x))break;S=_}let C=u.splice(k,S-k+1);for(let _ of C)b-=_.content?.length||0,_.tool_calls&&(b-=JSON.stringify(_.tool_calls).length);d+=C.length}if(u.length<s.length){let k=["[CONVERSATION CONTEXT \u2014 older messages were summarized to fit within the token limit]","Continue working with the remaining context."],S=u[0]?.role==="system"?1:0;u.splice(S,0,{role:"user",content:k.join(`
153
+ `),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-so(u)}}function ar(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var hy,Ra=H(()=>{"use strict";l(Fa,"estimateTokens");l(so,"estimateContextTokens");l(cr,"resolveContextWindow");hy=new Map;l(Qu,"shouldCompact");l(Ta,"compactMessages");l(ar,"totalChars")});var Yo={};Te(Yo,{AgentLoop:()=>Se});var Zu,yy,Se,Je=H(()=>{"use strict";Zu=require("node:events");wu();vu();xu();wa();ka();Ju();Q();Xu();Ra();yy=1/0,Se=class extends Zu.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 Yn({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new Zo(tr(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new $o(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=cr(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||yy;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=Yu({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=so(this.messages);if(Qu(i,this.contextWindow)){let u=Ta(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=so(this.messages);this.emitEvent({type:"context_compacted",elided:u.elided,savedTokens:u.savedTokens,contextUsed:d,contextWindow:this.contextWindow})}}let c=await this.streamCompletion();if(!c){this.emitEvent({type:"run_error",error:"No response from model"}),this.updateState({status:"error",error:"No response from model"});break}if(this.messages.push(c),this.emitEvent({type:"streaming_end",content:c.content}),c.tool_calls&&c.tool_calls.length>0){let u=new Set(["read_file","list_dir","grep_search","web_search","read_url","get_file_info","codebase_search","find_symbol"]),d=c.tool_calls.filter(m=>m.name==="ask_user"),p=c.tool_calls.filter(m=>m.name!=="ask_user"&&u.has(m.name)),f=c.tool_calls.filter(m=>m.name!=="ask_user"&&!u.has(m.name));for(let m of d){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments});let g=m.arguments.question||"What would you like to do?";this.updateState({status:"waiting_user_input"}),this.emitEvent({type:"ask_user",question:g});let h=await this.waitForUserInput();this.messages.push({role:"tool",content:`User response: ${h}`,tool_call_id:m.id,name:m.name,timestamp:Date.now()}),this.emitEvent({type:"tool_call_result",name:m.name,result:`User: ${h}`})}if(p.length>0){for(let g of p)this.emitEvent({type:"tool_call_start",name:g.name,args:g.arguments});this.updateState({status:"tool_executing",currentToolCall:`${p.length} parallel reads`});let m=await Promise.all(p.map(async g=>{let h=await this.toolExecutor.execute(g.name,g.arguments);return{toolCall:g,result:h}}));for(let{toolCall:g,result:h}of m)g.result=h.output,this.emitEvent({type:"tool_call_result",name:g.name,result:h.output}),this.messages.push({role:"tool",content:h.output,tool_call_id:g.id,name:g.name,timestamp:Date.now()})}for(let m of f){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments}),m.name==="todo_write"&&m.arguments.todos&&this.emitEvent({type:"todo_update",todos:m.arguments.todos});let g=await this._hookRunner.fire("PreToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments}});if(g.some(k=>k.action==="deny")){let k=g.find(S=>S.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${k}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let b=await this.toolExecutor.execute(m.name,m.arguments);if(b.wroteFiles&&b.touchedFiles)for(let k of b.touchedFiles)this.filesModified.add(k);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:b.output.slice(0,1e3),wroteFiles:b.wroteFiles}}).catch(()=>{}),m.result=b.output,this.emitEvent({type:"tool_call_result",name:m.name,result:b.output}),this.messages.push({role:"tool",content:b.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=Ta(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=so(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=Du(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(x=>({role:x.role,content:x.content,...x.tool_calls?{tool_calls:x.tool_calls.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))}:{},...x.tool_call_id?{tool_call_id:x.tool_call_id}:{},...x.name?{name:x.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=J(),i=Vu(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(x){if(x instanceof Error&&x.name==="AbortError")return null;throw x}if(!c.ok){let x=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}: ${x}`)}let u="",d=new Kn,p="",f=!1,m="",g="<think>",h="</think>",b=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),k=l(x=>{f?(m+=x,h.startsWith(m)?m===h&&(f=!1,m=""):(m="",x==="<"&&(m="<"))):x==="<"&&!m?m="<":m?(m+=x,g.startsWith(m)?m===g&&(f=!0,m=""):(p+=m,m="")):p+=x},"feedChar");for await(let x of bu(c)){if(!x.choices||x.choices.length===0){x.usage&&this.updateState({tokensIn:this.state.tokensIn+(x.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(x.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(x.usage.prompt_tokens_details?.cached_tokens||0)});continue}let E=x.choices[0];if(E.delta?.content){u+=E.delta.content;for(let I of E.delta.content)k(I);b()}if(E.delta?.tool_calls&&d.feed(E.delta.tool_calls),E.finish_reason==="tool_calls"||E.finish_reason==="stop")break}m&&!f&&(p+=m),b();let S=d.flush(),_={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return S.length>0&&(_.tool_calls=S.map(x=>{let E={};try{E=JSON.parse(x.arguments)}catch{E={_raw:x.arguments}}return{id:x.id,name:x.name,arguments:E}})),_}getAuthHeaders(){let e={Authorization:`Bearer ${this.opts.token}`};return this.opts.userId&&(e["X-User-Id"]=this.opts.userId),this.opts.orgId&&(e["X-Org-Id"]=this.opts.orgId),e}async waitForUserInput(){return new Promise(e=>{this._userInputResolve=e})}updateState(e){Object.assign(this.state,e),this.emitEvent({type:"state_update",state:{...this.state}})}emitEvent(e){this.emit("event",e)}}});var jt=ce((Yx,md)=>{"use strict";var dd=["nodebuffer","arraybuffer","fragments"],pd=typeof Blob<"u";pd&&dd.push("blob");md.exports={BINARY_TYPES:dd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:pd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var Vs=ce((Qx,br)=>{"use strict";var{EMPTY_BUFFER:My}=jt(),Ia=Buffer[Symbol.species];function Iy(s,e){if(s.length===0)return My;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 Ia(t.buffer,t.byteOffset,o):t}l(Iy,"concat");function fd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(fd,"_mask");function gd(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(gd,"_unmask");function jy(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(jy,"toArrayBuffer");function ja(s){if(ja.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new Ia(s):ArrayBuffer.isView(s)?e=new Ia(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),ja.readOnly=!1),e}l(ja,"toBuffer");br.exports={concat:Iy,mask:fd,toArrayBuffer:jy,toBuffer:ja,unmask:gd};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");br.exports.mask=function(e,t,o,n,r){r<48?fd(e,t,o,n,r):s.mask(e,t,o,n,r)},br.exports.unmask=function(e,t){e.length<32?gd(e,t):s.unmask(e,t)}}catch{}});var bd=ce((eC,yd)=>{"use strict";var hd=Symbol("kDone"),Na=Symbol("kRun"),Ba=class{static{l(this,"Limiter")}constructor(e){this[hd]=()=>{this.pending--,this[Na]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Na]()}[Na](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hd])}}};yd.exports=Ba});var ns=ce((oC,vd)=>{"use strict";var Js=require("zlib"),wd=Vs(),Ny=bd(),{kStatusCode:kd}=jt(),By=Buffer[Symbol.species],Ly=Buffer.from([0,0,255,255]),kr=Symbol("permessage-deflate"),Nt=Symbol("total-length"),os=Symbol("callback"),ro=Symbol("buffers"),ss=Symbol("error"),wr,La=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,!wr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;wr=new Ny(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[os];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){wr.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){wr.add(n=>{this._compress(e,t,(r,i)=>{n(),o(r,i)})})}_decompress(e,t,o){let n=this._isServer?"client":"server";if(!this._inflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?Js.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=Js.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[kr]=this,this._inflate[Nt]=0,this._inflate[ro]=[],this._inflate.on("error",Wy),this._inflate.on("data",Dd)}this._inflate[os]=o,this._inflate.write(e),t&&this._inflate.write(Ly),this._inflate.flush(()=>{let r=this._inflate[ss];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=wd.concat(this._inflate[ro],this._inflate[Nt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Nt]=0,this._inflate[ro]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(e,t,o){let n=this._isServer?"server":"client";if(!this._deflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?Js.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=Js.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Nt]=0,this._deflate[ro]=[],this._deflate.on("data",Uy)}this._deflate[os]=o,this._deflate.write(e),this._deflate.flush(Js.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=wd.concat(this._deflate[ro],this._deflate[Nt]);t&&(r=new By(r.buffer,r.byteOffset,r.length-4)),this._deflate[os]=null,this._deflate[Nt]=0,this._deflate[ro]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};vd.exports=La;function Uy(s){this[ro].push(s),this[Nt]+=s.length}l(Uy,"deflateOnData");function Dd(s){if(this[Nt]+=s.length,this[kr]._maxPayload<1||this[Nt]<=this[kr]._maxPayload){this[ro].push(s);return}this[ss]=new RangeError("Max payload size exceeded"),this[ss].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ss][kd]=1009,this.removeListener("data",Dd),this.reset()}l(Dd,"inflateOnData");function Wy(s){if(this[kr]._inflate=null,this[ss]){this[os](this[ss]);return}s[kd]=1007,this[os](s)}l(Wy,"inflateOnError")});var rs=ce((nC,Dr)=>{"use strict";var{isUtf8:Sd}=require("buffer"),{hasBlob:Hy}=jt(),Gy=[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 qy(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(qy,"isValidStatusCode");function Ua(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(Ua,"_isValidUTF8");function Vy(s){return Hy&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(Vy,"isBlob");Dr.exports={isBlob:Vy,isValidStatusCode:qy,isValidUTF8:Ua,tokenChars:Gy};if(Sd)Dr.exports.isValidUTF8=function(s){return s.length<24?Ua(s):Sd(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");Dr.exports.isValidUTF8=function(e){return e.length<32?Ua(e):s(e)}}catch{}});var Va=ce((iC,Td)=>{"use strict";var{Writable:Jy}=require("stream"),xd=ns(),{BINARY_TYPES:zy,EMPTY_BUFFER:Cd,kStatusCode:Ky,kWebSocket:Yy}=jt(),{concat:Wa,toArrayBuffer:Xy,unmask:Qy}=Vs(),{isValidStatusCode:Zy,isValidUTF8:$d}=rs(),vr=Buffer[Symbol.species],ze=0,_d=1,Ed=2,Fd=3,Ha=4,Ga=5,Sr=6,qa=class extends Jy{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||zy[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[Yy]=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=ze}_write(e,t,o){if(this._opcode===8&&this._state==ze)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 vr(o.buffer,o.byteOffset+e,o.length-e),new vr(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 vr(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 ze:this.getInfo(e);break;case _d:this.getPayloadLength16(e);break;case Ed:this.getPayloadLength64(e);break;case Fd:this.getMask();break;case Ha:this.getData(e);break;case Ga:case Sr: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[xd.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=_d:this._payloadLength===127?this._state=Ed: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=Fd:this._state=Ha}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ha}getData(e){let t=Cd;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]&&Qy(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=Ga,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[xd.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===ze&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=ze;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=Wa(o,t):this._binaryType==="arraybuffer"?n=Xy(Wa(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=ze):(this._state=Sr,setImmediate(()=>{this.emit("message",n,!0),this._state=ze,this.startLoop(e)}))}else{let n=Wa(o,t);if(!this._skipUTF8Validation&&!$d(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===Ga||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=ze):(this._state=Sr,setImmediate(()=>{this.emit("message",n,!1),this._state=ze,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Cd),this.end();else{let o=e.readUInt16BE(0);if(!Zy(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new vr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$d(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=ze;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ze):(this._state=Sr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ze,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[Ky]=n,i}};Td.exports=qa});var Ka=ce((lC,Pd)=>{"use strict";var{Duplex:cC}=require("stream"),{randomFillSync:e0}=require("crypto"),{types:{isUint8Array:t0}}=require("util"),Rd=ns(),{EMPTY_BUFFER:o0,kWebSocket:s0,NOOP:n0}=jt(),{isBlob:is,isValidStatusCode:r0}=rs(),{mask:Ad,toBuffer:Eo}=Vs(),Ke=Symbol("kByteLength"),i0=Buffer.alloc(4),xr=8*1024,Fo,as=xr,nt=0,a0=1,c0=2,Ja=class s{static{l(this,"Sender")}constructor(e,t,o){this._extensions=t||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=nt,this.onerror=n0,this[s0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||i0,t.generateMask?t.generateMask(o):(as===xr&&(Fo===void 0&&(Fo=Buffer.alloc(xr)),e0(Fo,0,xr),as=0),o[0]=Fo[as++],o[1]=Fo[as++],o[2]=Fo[as++],o[3]=Fo[as++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Ke]!==void 0?c=t[Ke]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!i);let u=c;c>=65536?(r+=8,u=127):c>125&&(r+=2,u=126);let d=Buffer.allocUnsafe(n?c+r:r);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[r-4]=o[0],d[r-3]=o[1],d[r-2]=o[2],d[r-1]=o[3],i?[d,e]:n?(Ad(e,o,d,r,c),[d]):(Ad(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=o0;else{if(typeof e!="number"||!r0(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(t0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Ke]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==nt?this.enqueue([this.dispatch,r,!1,i,n]):this.sendFrame(s.frame(r,i),n)}ping(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):is(e)?(n=e.size,r=!1):(e=Eo(e),n=e.length,r=Eo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ke]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};is(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}pong(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):is(e)?(n=e.size,r=!1):(e=Eo(e),n=e.length,r=Eo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ke]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};is(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[Rd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):is(e)?(c=e.size,u=!1):(e=Eo(e),c=e.length,u=Eo.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=n._threshold),this._compress=i):(i=!1,r=0),t.fin&&(this._firstFragment=!0);let d={[Ke]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};is(e)?this._state!==nt?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==nt?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Ke],this._state=c0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(za,this,c,n);return}this._bufferedBytes-=o[Ke];let i=Eo(r);t?this.dispatch(i,t,o,n):(this._state=nt,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(l0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[Rd.extensionName];this._bufferedBytes+=o[Ke],this._state=a0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");za(this,u,n);return}this._bufferedBytes-=o[Ke],this._state=nt,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===nt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ke],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ke],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Pd.exports=Ja;function za(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(za,"callCallbacks");function l0(s,e,t){za(s,e,t),s.onerror(e)}l(l0,"onError")});var Wd=ce((dC,Ud)=>{"use strict";var{kForOnEventAttribute:zs,kListener:Ya}=jt(),Od=Symbol("kCode"),Md=Symbol("kData"),Id=Symbol("kError"),jd=Symbol("kMessage"),Nd=Symbol("kReason"),cs=Symbol("kTarget"),Bd=Symbol("kType"),Ld=Symbol("kWasClean"),Bt=class{static{l(this,"Event")}constructor(e){this[cs]=null,this[Bd]=e}get target(){return this[cs]}get type(){return this[Bd]}};Object.defineProperty(Bt.prototype,"target",{enumerable:!0});Object.defineProperty(Bt.prototype,"type",{enumerable:!0});var To=class extends Bt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[Od]=t.code===void 0?0:t.code,this[Nd]=t.reason===void 0?"":t.reason,this[Ld]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Od]}get reason(){return this[Nd]}get wasClean(){return this[Ld]}};Object.defineProperty(To.prototype,"code",{enumerable:!0});Object.defineProperty(To.prototype,"reason",{enumerable:!0});Object.defineProperty(To.prototype,"wasClean",{enumerable:!0});var ls=class extends Bt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[Id]=t.error===void 0?null:t.error,this[jd]=t.message===void 0?"":t.message}get error(){return this[Id]}get message(){return this[jd]}};Object.defineProperty(ls.prototype,"error",{enumerable:!0});Object.defineProperty(ls.prototype,"message",{enumerable:!0});var Ks=class extends Bt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[Md]=t.data===void 0?null:t.data}get data(){return this[Md]}};Object.defineProperty(Ks.prototype,"data",{enumerable:!0});var u0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[zs]&&n[Ya]===e&&!n[zs])return;let o;if(s==="message")o=l(function(r,i){let c=new Ks("message",{data:i?r:r.toString()});c[cs]=this,Cr(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new To("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[cs]=this,Cr(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new ls("error",{error:r,message:r.message});i[cs]=this,Cr(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Bt("open");r[cs]=this,Cr(e,this,r)},"onOpen");else return;o[zs]=!!t[zs],o[Ya]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[Ya]===e&&!t[zs]){this.removeListener(s,t);break}}};Ud.exports={CloseEvent:To,ErrorEvent:ls,Event:Bt,EventTarget:u0,MessageEvent:Ks};function Cr(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(Cr,"callListener")});var $r=ce((mC,Hd)=>{"use strict";var{tokenChars:Ys}=rs();function ht(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(ht,"push");function d0(s){let e=Object.create(null),t=Object.create(null),o=!1,n=!1,r=!1,i,c,u=-1,d=-1,p=-1,f=0;for(;f<s.length;f++)if(d=s.charCodeAt(f),i===void 0)if(p===-1&&Ys[d]===1)u===-1&&(u=f);else if(f!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);d===44?(ht(e,g,t),t=Object.create(null)):i=g,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&Ys[d]===1)u===-1&&(u=f);else if(d===32||d===9)p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),ht(t,s.slice(u,p),!0),d===44&&(ht(e,i,t),t=Object.create(null),i=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=s.slice(u,f),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(n){if(Ys[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(Ys[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&&Ys[d]===1)u===-1&&(u=f);else if(u!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);o&&(g=g.replace(/\\/g,""),o=!1),ht(t,c,g),d===44&&(ht(e,i,t),t=Object.create(null),i=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(u===-1||r||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=s.slice(u,p);return i===void 0?ht(e,m,t):(c===void 0?ht(t,m,!0):o?ht(t,c,m.replace(/\\/g,"")):ht(t,c,m),ht(e,i,t)),e}l(d0,"parse");function p0(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(p0,"format");Hd.exports={format:p0,parse:d0}});var Tr=ce((yC,tp)=>{"use strict";var m0=require("events"),f0=require("https"),g0=require("http"),Vd=require("net"),h0=require("tls"),{randomBytes:y0,createHash:b0}=require("crypto"),{Duplex:gC,Readable:hC}=require("stream"),{URL:Xa}=require("url"),io=ns(),w0=Va(),k0=Ka(),{isBlob:D0}=rs(),{BINARY_TYPES:Gd,CLOSE_TIMEOUT:v0,EMPTY_BUFFER:_r,GUID:S0,kForOnEventAttribute:Qa,kListener:x0,kStatusCode:C0,kWebSocket:we,NOOP:Jd}=jt(),{EventTarget:{addEventListener:$0,removeEventListener:_0}}=Wd(),{format:E0,parse:F0}=$r(),{toBuffer:T0}=Vs(),zd=Symbol("kAborted"),Za=[8,13],Lt=["CONNECTING","OPEN","CLOSING","CLOSED"],R0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends m0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=Gd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_r,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]),Kd(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Gd.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 k0(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",O0),n.on("drain",M0),n.on("error",I0),n.on("message",j0),n.on("ping",N0),n.on("pong",B0),r.onerror=L0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Qd),e.on("data",Fr),e.on("end",Zd),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[io.extensionName]&&this._extensions[io.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){Be(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())}),Xd(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){ec(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||_r,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){ec(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||_r,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){ec(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[io.extensionName]||(n.compress=!1),this._sender.send(e||_r,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Be(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ie,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:Lt.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:Lt.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:Lt.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:Lt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ie.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ie.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[Qa])return e[x0];return null},set(e){for(let t of this.listeners(s))if(t[Qa]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[Qa]:!0})}})});ie.prototype.addEventListener=$0;ie.prototype.removeEventListener=_0;tp.exports=ie;function Kd(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v0,protocolVersion:Za[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,!Za.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Za.join(", ")})`);let r;if(e instanceof Xa)r=e;else try{r=new Xa(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let b=new SyntaxError(u);if(s._redirects===0)throw b;Er(s,b);return}let d=i?443:80,p=y0(16).toString("base64"),f=i?f0.request:g0.request,m=new Set,g;if(n.createConnection=n.createConnection||(i?P0:A0),n.defaultPort=n.defaultPort||d,n.port=r.port||d,n.host=r.hostname.startsWith("[")?r.hostname.slice(1,-1):r.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=r.pathname+r.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(g=new io({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=E0({[io.extensionName]:g.offer()})),t.length){for(let b of t){if(typeof b!="string"||!R0.test(b)||m.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(b)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let b=n.path.split(":");n.socketPath=b[0],n.path=b[1]}let h;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let b=o&&o.headers;if(o={...o,headers:{}},b)for(let[k,S]of Object.entries(b))o.headers[k.toLowerCase()]=S}else if(s.listenerCount("redirect")===0){let b=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!b||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,b||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),h=s._req=f(n),s._redirects&&s.emit("redirect",s.url,h)}else h=s._req=f(n);n.timeout&&h.on("timeout",()=>{Be(s,h,"Opening handshake has timed out")}),h.on("error",b=>{h===null||h[zd]||(h=s._req=null,Er(s,b))}),h.on("response",b=>{let k=b.headers.location,S=b.statusCode;if(k&&n.followRedirects&&S>=300&&S<400){if(++s._redirects>n.maxRedirects){Be(s,h,"Maximum redirects exceeded");return}h.abort();let C;try{C=new Xa(k,e)}catch{let x=new SyntaxError(`Invalid URL: ${k}`);Er(s,x);return}Kd(s,C,t,o)}else s.emit("unexpected-response",h,b)||Be(s,h,`Unexpected server response: ${b.statusCode}`)}),h.on("upgrade",(b,k,S)=>{if(s.emit("upgrade",b),s.readyState!==ie.CONNECTING)return;h=s._req=null;let C=b.headers.upgrade;if(C===void 0||C.toLowerCase()!=="websocket"){Be(s,k,"Invalid Upgrade header");return}let _=b0("sha1").update(p+S0).digest("base64");if(b.headers["sec-websocket-accept"]!==_){Be(s,k,"Invalid Sec-WebSocket-Accept header");return}let x=b.headers["sec-websocket-protocol"],E;if(x!==void 0?m.size?m.has(x)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){Be(s,k,E);return}x&&(s._protocol=x);let I=b.headers["sec-websocket-extensions"];if(I!==void 0){if(!g){Be(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=F0(I)}catch{Be(s,k,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(ae);if(K.length!==1||K[0]!==io.extensionName){Be(s,k,"Server indicated an extension that was not requested");return}try{g.accept(ae[io.extensionName])}catch{Be(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[io.extensionName]=g}s.setSocket(k,S,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(h,s):h.end()}l(Kd,"initAsClient");function Er(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Er,"emitErrorAndClose");function A0(s){return s.path=s.socketPath,Vd.connect(s)}l(A0,"netConnect");function P0(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Vd.isIP(s.host)?"":s.host),h0.connect(s)}l(P0,"tlsConnect");function Be(s,e,t){s._readyState=ie.CLOSING;let o=new Error(t);Error.captureStackTrace(o,Be),e.setHeader?(e[zd]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Er,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(Be,"abortHandshake");function ec(s,e,t){if(e){let o=D0(e)?e.size:T0(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Lt[s.readyState]})`);process.nextTick(t,o)}}l(ec,"sendAfterClose");function O0(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Fr),process.nextTick(Yd,t._socket),s===1005?t.close():t.close(s,e))}l(O0,"receiverOnConclude");function M0(){let s=this[we];s.isPaused||s._socket.resume()}l(M0,"receiverOnDrain");function I0(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Fr),process.nextTick(Yd,e._socket),e.close(s[C0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(I0,"receiverOnError");function qd(){this[we].emitClose()}l(qd,"receiverOnFinish");function j0(s,e){this[we].emit("message",s,e)}l(j0,"receiverOnMessage");function N0(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,Jd),e.emit("ping",s)}l(N0,"receiverOnPing");function B0(s){this[we].emit("pong",s)}l(B0,"receiverOnPong");function Yd(s){s.resume()}l(Yd,"resume");function L0(s){let e=this[we];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,Xd(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(L0,"senderOnError");function Xd(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(Xd,"setCloseTimer");function Qd(){let s=this[we];if(this.removeListener("close",Qd),this.removeListener("data",Fr),this.removeListener("end",Zd),s._readyState=ie.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[we]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",qd),s._receiver.on("finish",qd))}l(Qd,"socketOnClose");function Fr(s){this[we]._receiver.write(s)||this.pause()}l(Fr,"socketOnData");function Zd(){let s=this[we];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}l(Zd,"socketOnEnd");function ep(){let s=this[we];this.removeListener("error",ep),this.on("error",Jd),s&&(s._readyState=ie.CLOSING,this.destroy())}l(ep,"socketOnError")});var rp=ce((kC,np)=>{"use strict";var wC=Tr(),{Duplex:U0}=require("stream");function op(s){s.emit("close")}l(op,"emitClose");function W0(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(W0,"duplexOnEnd");function sp(s){this.removeListener("error",sp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(sp,"duplexOnError");function H0(s,e){let t=!0,o=new U0({...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(op,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(op,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",W0),o.on("error",sp),o}l(H0,"createWebSocketStream");np.exports=H0});var tc=ce((vC,ip)=>{"use strict";var{tokenChars:G0}=rs();function q0(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&&G0[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(q0,"parse");ip.exports={parse:q0}});var mp=ce((CC,pp)=>{"use strict";var V0=require("events"),Rr=require("http"),{Duplex:xC}=require("stream"),{createHash:J0}=require("crypto"),ap=$r(),Ro=ns(),z0=tc(),K0=Tr(),{CLOSE_TIMEOUT:Y0,GUID:X0,kWebSocket:Q0}=jt(),Z0=/^[+/0-9A-Za-z]{22}==$/,cp=0,lp=1,dp=2,oc=class extends V0{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:Y0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:K0,...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=Rr.createServer((o,n)=>{let r=Rr.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=eb(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=cp}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===dp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Xs,this);return}if(e&&this.once("close",e),this._state!==lp)if(this._state=lp,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(Xs,this):process.nextTick(Xs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Xs(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",up);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ao(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Ao(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!Z0.test(r)){Ao(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Ao(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Qs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=z0.parse(u)}catch{Ao(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 Ro({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=ap.parse(p);g[Ro.extensionName]&&(m.accept(g[Ro.extensionName]),f[Ro.extensionName]=m)}catch{Ao(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(g,h,b,k)=>{if(!g)return Qs(t,h||401,b,k);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return Qs(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[Q0])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>cp)return Qs(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${J0("sha1").update(t+X0).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[Ro.extensionName]){let f=e[Ro.extensionName].params,m=ap.format({[Ro.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
154
+ `).join(`\r
155
+ `)),r.removeListener("error",up),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(Xs,this)})),c(p,n)}};pp.exports=oc;function eb(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(eb,"addListeners");function Xs(s){s._state=dp,s.emit("close")}l(Xs,"emitClose");function up(){this.destroy()}l(up,"socketOnError");function Qs(s,e,t,o){t=t||Rr.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} ${Rr.STATUS_CODES[e]}\r
156
+ `+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
157
+ `)+`\r
158
+ \r
159
+ `+t)}l(Qs,"abortHandshake");function Ao(s,e,t,o,n,r){if(s.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Ao),s.emit("wsClientError",i,t,e)}else Qs(t,o,n,r)}l(Ao,"abortHandshakeOrEmitwsClientError")});var tb,ob,sb,nb,rb,ib,fp,sc,rt,Zs=H(()=>{tb=y(rp(),1),ob=y($r(),1),sb=y(ns(),1),nb=y(Va(),1),rb=y(Ka(),1),ib=y(tc(),1),fp=y(Tr(),1),sc=y(mp(),1),rt=fp.default});var yc={};Te(yc,{JobsApiClient:()=>Oe,captureWorkspaceSnapshot:()=>Op,createSnapshotArchive:()=>Mp,getLocalJobLogs:()=>fc,getLocalJobStatus:()=>mc,getLocalJobs:()=>pc,printJobStatus:()=>Ir,printJobsTable:()=>hc,printLogEntry:()=>jr,pullJobChanges:()=>gc,runLocalBackgroundJob:()=>Ip,submitBackgroundJob:()=>ub});function Op(s){let e=l(p=>{try{return(0,Po.execSync)(p,{cwd:s,encoding:"utf8"}).trim()}catch{return""}},"git"),t=e("git remote get-url origin");process.platform==="win32"&&(t=t.replace(/\\/g,"/"));let o=e("git rev-parse --abbrev-ref HEAD"),n=e("git rev-parse HEAD"),r=e("git diff"),i=e("git diff --cached"),c=[r,i].filter(Boolean).join(`
160
+ `),u="";try{let p=te.join(s,".monkeyscode","rules.md");G.existsSync(p)&&(u=G.readFileSync(p,"utf8"))}catch{}let d="";try{let p=te.join(s,".monkeyscode","config.json");G.existsSync(p)&&(d=G.readFileSync(p,"utf8"))}catch{}return{repo:t,branch:o,commit:n,dirtyDiff:c,rules:u,config:d}}function Mp(s,e){let t=G.mkdtempSync(te.join(Ap.tmpdir(),"mc-archive-")),o=te.join(t,"snapshot");G.mkdirSync(o,{recursive:!0}),s.dirtyDiff&&G.writeFileSync(te.join(o,"dirty.diff"),s.dirtyDiff,"utf8"),s.rules&&G.writeFileSync(te.join(o,"rules.md"),s.rules,"utf8"),s.config&&G.writeFileSync(te.join(o,"config.json"),s.config,"utf8"),e&&e.length>0&&G.writeFileSync(te.join(o,"conversation.json"),JSON.stringify(e,null,2),"utf8"),G.writeFileSync(te.join(o,"metadata.json"),JSON.stringify({repo:s.repo,branch:s.branch,commit:s.commit,createdAt:new Date().toISOString()},null,2),"utf8");let n=te.join(t,"snapshot.tar.gz");try{(0,Po.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=Pp.gzipSync(Buffer.from(r,"utf8"));G.writeFileSync(n,i)}return n}async function ub(s){let e=J(),o=me()?.access_token;o||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),console.log(a.dim(" \u{1F4F8} Capturing workspace snapshot..."));let n=Op(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 Oe(e.platformUrl,o),i=null;try{console.log(a.dim(" \u{1F4E6} Creating compressed archive...")),i=Mp(n,s.conversationHistory);let u=G.statSync(i).size;console.log(a.dim(` \u{1F4E6} Archive: ${(u/1024).toFixed(1)} KB`));let d=await r.requestUploadUrl();d?(console.log(a.dim(" \u2601\uFE0F Uploading to GCS...")),await r.uploadArchive(d.uploadUrl,i)?(n.archiveId=d.archiveId,n.dirtyDiff="",n.rules="",n.config="",console.log(a.dim(" \u2705 Archive uploaded successfully"))):console.log(a.dim(" \u26A0\uFE0F Archive upload failed \u2014 falling back to inline JSON"))):console.log(a.dim(" \u26A0\uFE0F Server does not support archive uploads \u2014 using inline JSON"))}catch{console.log(a.dim(" \u26A0\uFE0F Archive creation failed \u2014 falling back to inline JSON"))}finally{if(i)try{let u=te.dirname(i);G.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 Ip({...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 Ip(s){let e=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,{getPlatformPaths:t}=await Promise.resolve().then(()=>(X(),Do)),o=t(),n=te.join(o.data,"jobs",e);G.mkdirSync(n,{recursive:!0});let r={jobId:e,prompt:s.prompt,workspace:te.resolve(s.workspace),model:s.model,mode:s.mode,token:s.token,autoBranch:s.autoBranch,autoCommit:s.autoCommit,autoPR:s.autoPR,maxCost:s.maxCost,timeout:s.timeout};G.writeFileSync(te.join(n,"config.json"),JSON.stringify(r,null,2),"utf8"),G.writeFileSync(te.join(n,"status.json"),JSON.stringify({status:"queued",progress:0,message:"Starting...",updatedAt:new Date().toISOString()},null,2),"utf8");let i=new URL("../agent/local-job-runner.js",mb.url).pathname,c=(0,Po.fork)(i,[],{detached:!0,stdio:["ignore","ignore","ignore","ipc"],env:{...process.env}});await new Promise((u,d)=>{let p=setTimeout(()=>d(new Error("Runner startup timeout")),1e4);c.on("message",f=>{f?.type==="ready"&&(c.send({type:"start",config:r}),clearTimeout(p),u())}),c.on("error",f=>{clearTimeout(p),d(f)})}),c.unref(),c.disconnect(),console.log(""),console.log(a.bold(" \u{1F5A5}\uFE0F Background job started (local)")),console.log(a.dim(" "+"\u2500".repeat(38))),console.log(` Job ID: ${a.cyan(e)}`),console.log(` Prompt: "${s.prompt.substring(0,60)}${s.prompt.length>60?"...":""}"`),console.log(` Model: ${s.model}`),console.log(` Location: ${a.yellow("local")} (cloud unavailable)`),console.log(a.dim(" "+"\u2500".repeat(38))),console.log(` Logs: ${a.dim(te.join(n,"log.jsonl"))}`),console.log(` Status: ${a.dim(`mc jobs status ${e}`)}`),console.log("")}function pc(s){try{let{getPlatformPaths:e}=(X(),_s(Do)),t=e(),o=te.join(t.data,"jobs");if(!G.existsSync(o))return[];let n=G.readdirSync(o,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name.startsWith("local-")).sort((i,c)=>c.name.localeCompare(i.name)),r=[];for(let i of n){if(s?.limit&&r.length>=s.limit)break;let c=te.join(o,i.name);try{let u=JSON.parse(G.readFileSync(te.join(c,"status.json"),"utf8")),d=JSON.parse(G.readFileSync(te.join(c,"config.json"),"utf8"));if(s?.status&&u.status!==s.status)continue;let p,f,m,g,h,b=te.join(c,"result.json");if(G.existsSync(b)){let k=JSON.parse(G.readFileSync(b,"utf8"));p=k.duration,f=k.filesChanged?.length,m=k.tokensUsed,g=k.costUsd,(k.status==="completed"||k.status==="failed")&&(h=new Date(Date.parse(u.updatedAt)))}r.push({id:i.name,status:u.status,prompt:d.prompt||"",model:d.model||"unknown",branch:void 0,duration:p,filesChanged:f,tokensUsed:m,cost:g,createdAt:new Date(G.statSync(te.join(c,"config.json")).birthtimeMs),completedAt:h,currentStep:u.message})}catch{}}return r}catch{return[]}}function mc(s){try{let{getPlatformPaths:e}=(X(),_s(Do)),t=e(),o=te.join(t.data,"jobs",s);if(!G.existsSync(o))return null;let n=JSON.parse(G.readFileSync(te.join(o,"status.json"),"utf8")),r=JSON.parse(G.readFileSync(te.join(o,"config.json"),"utf8")),i={id:s,status:n.status,prompt:r.prompt||"",model:r.model||"unknown",createdAt:new Date(G.statSync(te.join(o,"config.json")).birthtimeMs),currentStep:n.message},c=te.join(o,"result.json");if(G.existsSync(c)){let u=JSON.parse(G.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 fc(s){try{let{getPlatformPaths:e}=(X(),_s(Do)),t=e(),o=te.join(t.data,"jobs",s,"log.jsonl");return G.existsSync(o)?G.readFileSync(o,"utf8").split(`
161
+ `).filter(Boolean).map(n=>{let r=JSON.parse(n);return{timestamp:new Date(r.timestamp),level:r.level||"info",message:r.message||""}}):[]}catch{return[]}}function gc(s,e,t){try{console.log(a.dim(` \u{1F4E5} Fetching branch ${t}...`)),(0,Po.execSync)(`git fetch origin "${t}"`,{cwd:s,stdio:"pipe"}),console.log(a.dim(` \u{1F500} Merging ${t} into current branch...`)),(0,Po.execSync)(`git merge --no-ff "origin/${t}" -m "merge: background job ${e}"`,{cwd:s,stdio:"inherit"}),console.log(a.green(` \u2705 Changes from job ${e} merged successfully.`))}catch(o){console.error(a.red(` \u274C Merge failed: ${o instanceof Error?o.message:o}`)),console.log(a.dim(" Resolve conflicts manually, then run: git merge --continue")),process.exit(1)}}function jp(){return process.platform!=="win32"||!!process.env.WT_SESSION}function Np(s){return(jp()?db:pb)[s]||"?"}function hc(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=`${Np(n.status)} ${Bp(n.status)}`,c=n.prompt.length>34?`"${n.prompt.substring(0,32)}..."`:`"${n.prompt}"`,u=n.duration?dc(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 Ir(s,e){let t=jp();if(console.log(""),console.log(a.bold(` ${t?"\u{1F4CB}":">>"} Job: ${s.id}`)),console.log(a.dim(" "+(t?"\u2500":"-").repeat(50))),console.log(` Status: ${Np(s.status)} ${Bp(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: ${dc(s.duration)}`),s.estimatedTimeRemaining!=null&&console.log(` ETA: ~${dc(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 jr(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 Rp(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 dc(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 Bp(s){return s.charAt(0).toUpperCase()+s.slice(1)}var G,te,Ap,Pp,Po,mb,Oe,db,pb,tn=H(()=>{"use strict";G=y(require("node:fs"),1),te=y(require("node:path"),1),Ap=y(require("node:os"),1),Pp=y(require("node:zlib"),1),Po=require("node:child_process");W();Q();oe();mb={},Oe=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=G.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(Rp):[]}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 Rp(o)}catch{return null}}async logs(e){try{let t=await fetch(`${this.baseUrl}/${e}/logs`,{headers:this.headers(),signal:AbortSignal.timeout(15e3)});return t.ok?((await t.json()).logs||[]).map(n=>({timestamp:new Date(n.timestamp),level:n.level||"info",message:n.message||n.text||""})):[]}catch{return[]}}async*followLogs(e){try{let t=await fetch(`${this.baseUrl}/${e}/logs/stream`,{headers:{...this.headers(),Accept:"text/event-stream"}});if(!t.ok||!t.body)return;let o=t.body.getReader(),n=new TextDecoder,r="";for(;;){let{done:i,value:c}=await o.read();if(i)break;r+=n.decode(c,{stream:!0});let u=r.split(`
162
+ `);r=u.pop()||"";for(let d of u)if(d.startsWith("data: "))try{let p=JSON.parse(d.substring(6));yield{timestamp:new Date(p.timestamp),level:p.level||"info",message:p.message||""}}catch{}}}catch{}}async cancel(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});if(!t.ok){let o=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${o}`}}return{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async retry(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/retry`,{method:"POST",headers:this.headers(),body:JSON.stringify(t||{}),signal:AbortSignal.timeout(15e3)});if(!o.ok){let r=await o.text().catch(()=>"");return{success:!1,error:`HTTP ${o.status}: ${r}`}}let n=await o.json();return{success:!0,jobId:n.id||n.jobId,branch:n.branch,dashboardUrl:n.dashboardUrl}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}async diff(e){try{let t=await fetch(`${this.baseUrl}/${e}/diff`,{headers:{...this.headers(),Accept:"text/plain"},signal:AbortSignal.timeout(15e3)});return t.ok?await t.text():""}catch{return""}}};l(Op,"captureWorkspaceSnapshot");l(Mp,"createSnapshotArchive");l(ub,"submitBackgroundJob");l(Ip,"runLocalBackgroundJob");l(pc,"getLocalJobs");l(mc,"getLocalJobStatus");l(fc,"getLocalJobLogs");l(gc,"pullJobChanges");l(jp,"shouldUseUnicode");db={queued:"\u23F3",running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u{1F6AB}"},pb={queued:"[Q]",running:"[~]",completed:"[+]",failed:"[X]",cancelled:"[-]"};l(Np,"getStatusIcon");l(hc,"printJobsTable");l(Ir,"printJobStatus");l(jr,"printLogEntry");l(Rp,"parseJobInfo");l(dc,"formatDuration");l(Bp,"capitalize")});var Lp={};Te(Lp,{resumeFromJob:()=>fb});async function fb(s){let e=J(),o=me()?.access_token;if(!o)return console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Not authenticated"};let n=new Oe(e.platformUrl,o);console.log(a.dim(` \u{1F4CB} Fetching job ${s.jobId}...`));let r=await n.status(s.jobId);if(!r)return console.error(a.red(` \u274C Job ${s.jobId} not found.`)),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Job not found"};if(r.status!=="completed"&&r.status!=="failed")return console.error(a.yellow(` \u26A0 Job is still ${r.status}. Wait for it to complete or cancel it.`)),console.log(a.dim(` Track: mc jobs status ${s.jobId}`)),{success:!1,filesApplied:0,conversationLoaded:!1,error:`Job is ${r.status}`};if(!s.force){let d=gb(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,ps.execSync)("git apply --check -",{cwd:s.workspace,input:d,stdio:["pipe","pipe","pipe"]}),(0,ps.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=on.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");return m(f,{recursive:!0}),g(on.join(f,"resume-diff.patch"),d),{success:!1,filesApplied:0,conversationLoaded:!1,error:"Diff application failed"}}}else console.log(a.dim(" No changes to apply (job may have failed before making changes)."));let u=!1;try{let d=await fetch(`${e.platformUrl}/api/jobs/${s.jobId}/conversation`,{headers:{Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(1e4)});if(d.ok){let p=await d.json();if(p.history&&p.history.length>0){let f=on.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");m(f,{recursive:!0}),g(on.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 gb(s,e){let t=[];try{let o=(0,ps.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,ps.execSync)("git diff --name-only",{cwd:s,encoding:"utf8"}).trim();if(r){let c=r.split(`
163
+ `).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,ps.execSync)("git diff --cached --name-only",{cwd:s,encoding:"utf8"}).trim();if(i){let c=i.split(`
164
+ `).filter(Boolean);t.push(`${c.length} staged file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}}catch{t.push("Unable to check git status (not a git repository?)")}return{compatible:t.length===0,reasons:t}}var on,ps,Up=H(()=>{"use strict";on=y(require("node:path"),1),ps=require("node:child_process");W();tn();Q();oe();l(fb,"resumeFromJob");l(gb,"checkSyncCompatibility")});function wc(s){let e=yt.join(s.workspace,sn,s.teamId,s.taskSlug),t=`monkeyscode/team-${s.teamId}/${s.taskSlug}`;at.mkdirSync(yt.dirname(e),{recursive:!0});let o=s.baseBranch||(0,Wt.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s.workspace,encoding:"utf8"}).trim();try{(0,Wt.execSync)(`git worktree add -b "${t}" "${e}" "${o}"`,{cwd:s.workspace,encoding:"utf8",stdio:"pipe"})}catch{try{(0,Wt.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,Wt.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 kc(s,e,t=!1){let o=t?" --force":"",n=l(()=>{(0,Wt.execSync)(`git worktree remove "${e}"${o}`,{cwd:s,encoding:"utf8",stdio:"pipe"})},"tryRemove");if(process.platform==="win32")for(let r=0;r<bc;r++)try{n();return}catch(i){if(r<bc-1)(0,Wt.execSync)(`timeout /t ${Math.ceil(yb/1e3)}`,{stdio:"ignore"});else throw new Error(`Failed to remove worktree after ${bc} attempts (files may be locked by another process): ${i instanceof Error?i.message:i}`)}else n();try{(0,Wt.execSync)("git worktree prune",{cwd:s,stdio:"pipe"})}catch{}}function bb(s){let e;try{e=(0,Wt.execSync)("git worktree list --porcelain",{cwd:s,encoding:"utf8"})}catch{return[]}let t=[],o=e.split(`
165
+
166
+ `).filter(Boolean);for(let n of o){let r=n.split(`
167
+ `),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=at.statSync(i).birthtime}catch{}let f=i.split(yt.sep),m=f.indexOf(sn.replace(/\//g,yt.sep).split(yt.sep)[0]),g=m>=0?f.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(sn),createdAt:p,label:g})}return t}function ms(s){return bb(s).filter(e=>e.path.includes(sn))}function Wp(s){let e=s.ttlMs??hb,t=Date.now(),o=[],n=[],r=ms(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{kc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=yt.join(s.workspace,sn);try{Hp(i)}catch{}return{removed:o,errors:n}}function Hp(s){if(!at.existsSync(s))return;let e=at.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&Hp(yt.join(s,t.name));at.readdirSync(s).length===0&&at.rmdirSync(s)}function Dc(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var at,yt,Wt,sn,hb,yb,bc,vc=H(()=>{"use strict";at=y(require("node:fs"),1),yt=y(require("node:path"),1),Wt=require("node:child_process"),sn=".monkeyscode-worktrees",hb=24*60*60*1e3,yb=500,bc=3;l(wc,"createWorktree");l(kc,"removeWorktree");l(bb,"listWorktrees");l(ms,"listManagedWorktrees");l(Wp,"cleanStaleWorktrees");l(Hp,"cleanEmptyDirs");l(Dc,"slugify")});var qp={};Te(qp,{mergeTeam:()=>xc,runInWorktree:()=>kb,showTeamStatus:()=>Sc,spawnTeam:()=>Nr});async function Nr(s){let e=Db(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:Dc(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=wc({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(g){m.status="failed",m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=J(),r=me()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let g=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let h=(0,lo.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let b=JSON.parse(h);m.filesChanged=b.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-g;try{(0,lo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,lo.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 (${Gp(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-g,m.error=h instanceof Error?h.message:String(h),console.error(a.red(` \u274C Agent #${m.index} failed: ${m.error.substring(0,80)}`))}},"runAgent");await l(async()=>{let m=[];for(let g of i){for(;c.size>=s.maxAgents;)await new Promise(b=>setTimeout(b,500));c.add(g.index);let h=u(g).finally(()=>c.delete(g.index));m.push(h)}await Promise.all(m)},"processQueue")();try{let m=nn.join(s.workspace,".monkeyscode-worktrees",e);ct.mkdirSync(m,{recursive:!0});let g=nn.join(m,"state.json");ct.writeFileSync(g,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(h=>({index:h.index,task:h.task,slug:h.slug,status:h.status,duration:h.duration,filesChanged:h.filesChanged,error:h.error,branch:h.worktree?.branch}))},null,2))}catch{}let p=t.filter(m=>m.status==="completed").length,f=t.filter(m=>m.status==="failed").length;return console.log(""),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(a.bold(` Team ${e}: ${p} completed, ${f} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function Sc(s){let e=nn.join(s,".monkeyscode-worktrees");if(!ct.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=ct.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=nn.join(e,u.name,"state.json");if(ct.existsSync(d))try{t.push(JSON.parse(ct.readFileSync(d,"utf8")))}catch{}}}catch{}let o=ms(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?Gp(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",g=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+g+'"').padEnd(34)} ${(p+" "+wb(d.status)).padEnd(12)} ${f.padEnd(10)} ${m.padEnd(6)}`)}console.log(u)}for(let[c,u]of r){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c}`)+a.dim(" (no state file)"));let d=" "+"\u2500".repeat(70);console.log(d);for(let p=0;p<u.length;p++){let f=u[p],m=f.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${f.branch.padEnd(30)}`)}console.log(d)}console.log("")}function wb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function xc(s,e){let t=ms(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,lo.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{kc(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 kb(s,e,t){let o=Dc(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=wc({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,lo.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,lo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,lo.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 Db(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function Gp(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var ct,nn,lo,Cc=H(()=>{"use strict";ct=y(require("node:fs"),1),nn=y(require("node:path"),1),lo=require("node:child_process");W();vc();Q();oe();l(Nr,"spawnTeam");l(Sc,"showTeamStatus");l(wb,"capitalize");l(xc,"mergeTeam");l(kb,"runInWorktree");l(Db,"generateTeamId");l(Gp,"formatDuration")});var Br={};Te(Br,{MessageBroker:()=>rn});function vb(){try{let s=Jp.join(zp.homedir(),".monkeyscode","daemon.port"),e=Vp.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var Vp,Jp,zp,$c,_c,rn,an=H(()=>{"use strict";Vp=y(require("node:fs"),1),Jp=y(require("node:path"),1),zp=y(require("node:os"),1);Zs();$c=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new rt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},_c=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(vb,"readDaemonPort");rn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=vb();n?this.transport=new $c(n):this.transport=new _c(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 Yp={};Te(Yp,{analyzeImpact:()=>Kp,notifyAffectedSessions:()=>xb});function Kp(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=bt.basename(d).toLowerCase(),f=d.toLowerCase();if(i.includes(p)&&.9>u&&(u=.9,c=`Task mentions "${p}" which was modified`),r.workspace){let m=bt.relative(r.workspace,d),g=bt.dirname(m).split(bt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Sb)if(m.pathPattern.test(f))for(let g of m.keywords)i.includes(g)&&.6>u&&(u=.6,c=`Modified ${p} (${g}-related) \u2014 task mentions "${g}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function xb(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=Kp(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>bt.basename(p)).join(", "):`${e.slice(0,3).map(p=>bt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
168
+ `),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var bt,Sb,Xp=H(()=>{"use strict";bt=y(require("node:path"),1),Sb=[{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(Kp,"analyzeImpact");l(xb,"notifyAffectedSessions")});var vm={};Te(vm,{default:()=>Wb});var Wb,Sm=H(()=>{Wb={name:"monkeyscode-cli",version:"0.1.0",description:"MonkeysCode CLI \u2014 standalone terminal coding agent. Works independently of the IDE and Agent Manager.",license:"MIT",type:"module",main:"dist/monkeyscode-cli.cjs",bin:{mc:"dist/monkeyscode-cli.cjs",mcode:"dist/monkeyscode-cli.cjs",monkeyscode:"dist/monkeyscode-cli.cjs"},files:["dist/monkeyscode-cli.cjs","README.md","LICENSE"],scripts:{build:"tsc","build:watch":"tsc --watch",bundle:"node esbuild.config.mjs","bundle:prod":"node esbuild.config.mjs --prod","build:sea":"bash scripts/build.sh --sea",release:"bash scripts/build.sh --all --checksums",dev:"tsx src/main.ts",start:"node dist/main.js",lint:"eslint src/",test:"node --import tsx --test tests/**/*.test.ts","test:watch":"node --import tsx --test --watch tests/**/*.test.ts",clean:"rm -rf dist",prepublishOnly:"npm run clean && npm run bundle:prod"},keywords:["monkeyscode","cli","coding-agent","terminal","ai","standalone"],dependencies:{chalk:"^5.4.0","cli-highlight":"^2.1.11",commander:"^13.0.0",diff:"^7.0.0",marked:"^18.0.11",ora:"^8.1.0",ws:"^8.18.0"},devDependencies:{"@types/diff":"^6.0.0","@types/node":"^22.0.0","@types/ws":"^8.5.0",esbuild:"^0.24.0",tsx:"^4.19.0",typescript:"^5.7.0"},engines:{node:">=20.0.0"}}});var Yr,zm=H(()=>{"use strict";Yr=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 yn,Hc,Xr,Km=H(()=>{"use strict";yn=y(require("node:fs"),1),Hc=y(require("node:path"),1),Xr=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=yn.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=yn.readdirSync(e,{withFileTypes:!0});for(let n of o){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let r=Hc.join(e,n.name);try{let i=yn.watch(r,(c,u)=>{!u||!this.running||this.onFileChange(Hc.join(n.name,u))});this.watchers.push(i),this.watchDirectories(r,t+1)}catch{}}}catch{}}}});var Xm={};Te(Xm,{TriggerEngine:()=>Gc});var Dt,bn,Ym,Gc,Qm=H(()=>{"use strict";Dt=y(require("node:fs"),1),bn=y(require("node:path"),1),Ym=require("node:events");Je();Q();zm();Km();Gc=class extends Ym.EventEmitter{static{l(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=bn.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new Yr,this.fileWatcher=new Xr(e.workspace),this.loadState()}loadTriggers(){let e=bn.join(this.opts.workspace,".monkeyscode","triggers.json");if(!Dt.existsSync(e))return this.triggers=[],[];try{let t=JSON.parse(Dt.readFileSync(e,"utf8"));return this.triggers=(t.triggers||[]).filter(o=>o.enabled!==!1),this.triggers}catch{return[]}}start(){this.loadTriggers();for(let e of this.triggers)e.event==="cron"&&e.schedule&&this.cronScheduler.add({id:e.name,expression:e.schedule,callback:l(()=>this.fire(e,{type:"cron",payload:{schedule:e.schedule},source:"cron-scheduler",timestamp:Date.now()}),"callback")}),e.event==="file.changed"&&this.fileWatcher.watch(e.watchPatterns||["**/*"],t=>{this.fire(e,{type:"file.changed",payload:{files:t},source:"file-watcher",timestamp:Date.now()})});this.cronScheduler.start(),this.fileWatcher.start(),this.emit("started",{triggerCount:this.triggers.length})}stop(){this.cronScheduler.stop(),this.fileWatcher.stop();for(let e of this.activeRuns.values())e.cancel();this.activeRuns.clear(),this.saveState()}async processEvent(e){for(let t of this.triggers)this.matches(t,e)&&await this.fire(t,e)}listTriggers(){return this.triggers.map(e=>({...e,state:this.state.get(e.name)||{name:e.name,lastFired:0,fireCount:0,lastResult:null}}))}dryRun(e){let t=this.triggers.find(o=>o.name===e);return t?{matched:!0,prompt:t.prompt,model:t.model||"default"}:{matched:!1,prompt:"",model:""}}matches(e,t){if(e.event!==t.type)return!1;if(e.filter){for(let[o,n]of Object.entries(e.filter))if(t.payload[o]!==n)return!1}return!0}async fire(e,t){let o=this.state.get(e.name),n=(e.cooldownSeconds||300)*1e3;if(o&&Date.now()-o.lastFired<n){this.emit("cooldown",{trigger:e.name,remaining:n-(Date.now()-o.lastFired)});return}if(this.activeRuns.has(e.name))return;this.emit("firing",{trigger:e.name,event:t.type});let r=J(),i=new Se({platformUrl:r.platformUrl,token:this.opts.token,model:e.model||r.defaultModel||"capuchin-reason",workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!0,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeRuns.set(e.name,i);try{let c=[`[Trigger: ${e.name}]`,`Event: ${t.type}`,t.payload?`Payload: ${JSON.stringify(t.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
169
+ `);await i.run(c),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(c){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:c instanceof Error?c.message:String(c)})}finally{this.activeRuns.delete(e.name)}}updateState(e,t){let o=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};o.lastFired=Date.now(),o.fireCount++,o.lastResult=t,this.state.set(e,o),this.saveState()}saveState(){try{let e=bn.dirname(this.statePath);Dt.mkdirSync(e,{recursive:!0}),Dt.writeFileSync(this.statePath,JSON.stringify(Object.fromEntries(this.state),null,2))}catch{}}loadState(){try{if(Dt.existsSync(this.statePath)){let e=JSON.parse(Dt.readFileSync(this.statePath,"utf8"));this.state=new Map(Object.entries(e))}}catch{this.state=new Map}}}});var ef={};Te(ef,{GitHubWebhookServer:()=>qc});var Zm,bs,qc,tf=H(()=>{"use strict";Zm=y(require("node:http"),1),bs=y(require("node:crypto"),1),qc=class s{static{l(this,"GitHubWebhookServer")}server=null;opts;constructor(e){this.opts={port:9122,...e}}async start(){return new Promise((e,t)=>{this.server=Zm.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"]||bs.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="+bs.createHmac("sha256",o).update(e).digest("hex");return bs.timingSafeEqual(Buffer.from(t),Buffer.from(n))}}});var ug={};Te(ug,{getNotificationBackend:()=>mk,notifyJobComplete:()=>uk,notifyUpdateAvailable:()=>dk,sendNotification:()=>nl,supportsNotifications:()=>pk});function nl(s){if(process.env.CI==="true"||process.env.CI==="1")return!1;try{switch(process.platform){case"darwin":return fk(s);case"linux":return gk(s);case"win32":return wk(s);default:return!1}}catch{return!1}}function uk(s,e,t){return nl({title:t?"\u2705 Job Complete":"\u274C Job Failed",body:`Job ${s}: ${e}`,subtitle:"MonkeysCode",sound:t?"Glass":"Basso",urgency:t?"normal":"critical"})}function dk(s){return nl({title:"\u{1F504} Update Available",body:`MonkeysCode v${s} is available. Run: mc update`,subtitle:"MonkeysCode",urgency:"low"})}function pk(){if(process.env.CI==="true"||process.env.CI==="1")return!1;switch(process.platform){case"darwin":return xt("osascript");case"linux":return!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY?!1:xt("notify-send")||xt("kdialog")||xt("zenity");case"win32":return!0;default:return!1}}function mk(){switch(process.platform){case"darwin":return"macOS (osascript)";case"linux":return xt("notify-send")?"Linux (notify-send)":xt("kdialog")?"Linux (kdialog)":xt("zenity")?"Linux (zenity)":"Linux (terminal bell)";case"win32":return"Windows (PowerShell toast)";default:return"Unsupported"}}function fk(s){let e=ri(s.title),o=`display notification "${ri(s.body)}" with title "${e}"`;s.subtitle&&(o+=` subtitle "${ri(s.subtitle)}"`),s.sound&&(o+=` sound name "${ri(s.sound)}"`);let n=ol.join(sl.tmpdir(),`mc-notify-${process.pid}.scpt`);try{return yo.writeFileSync(n,o,"utf8"),(0,zt.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{yo.unlinkSync(n)}catch{}}}function ri(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function gk(s){if(!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)){if(xt("notify-send"))return hk(s);if(xt("kdialog"))return yk(s);if(xt("zenity"))return bk(s)}return process.stderr.write("\x07"),process.stderr.write(`[Notification] ${s.title}: ${s.body}
170
+ `),!0}function hk(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(yo.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,zt.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function yk(s){try{return(0,zt.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function bk(s){try{return(0,zt.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function wk(s){let e=lg(s.title),t=lg(s.body),o=`
171
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
172
+
173
+ # Try WinRT Toast (Windows 10 1709+)
174
+ try {
175
+ [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
176
+ [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom, ContentType = WindowsRuntime] | Out-Null
177
+
178
+ $template = @"
179
+ <toast>
180
+ <visual>
181
+ <binding template="ToastGeneric">
182
+ <text>${e}</text>
183
+ <text>${t}</text>
184
+ </binding>
185
+ </visual>
186
+ <audio src="ms-winsoundevent:Notification.Default" />
187
+ </toast>
188
+ "@
189
+
190
+ $xml = [Windows.Data.Xml.Dom.XmlDocument]::new()
191
+ $xml.LoadXml($template)
192
+
193
+ # Use a known AppUserModelID (PowerShell's)
194
+ $appId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'
195
+ $notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($appId)
196
+ $toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
197
+ $notifier.Show($toast)
198
+ exit 0
199
+ }
200
+ catch {}
201
+
202
+ # Fallback: BurntToast module
203
+ try {
204
+ Import-Module BurntToast -ErrorAction Stop
205
+ New-BurntToastNotification -Text '${e}', '${t}' -AppLogo $null
206
+ exit 0
207
+ }
208
+ catch {}
209
+
210
+ # Fallback: NotifyIcon balloon tip
211
+ try {
212
+ Add-Type -AssemblyName System.Windows.Forms
213
+ $icon = New-Object System.Windows.Forms.NotifyIcon
214
+ $icon.Icon = [System.Drawing.SystemIcons]::Information
215
+ $icon.BalloonTipTitle = '${e}'
216
+ $icon.BalloonTipText = '${t}'
217
+ $icon.BalloonTipIcon = 'Info'
218
+ $icon.Visible = $true
219
+ $icon.ShowBalloonTip(10000)
220
+ Start-Sleep -Milliseconds 500
221
+ $icon.Dispose()
222
+ exit 0
223
+ }
224
+ catch {}
225
+
226
+ # Fallback: msg.exe (shows a message box)
227
+ try {
228
+ msg.exe * /TIME:10 "${e}: ${t}" 2>$null
229
+ exit 0
230
+ }
231
+ catch {}
232
+
233
+ exit 1
234
+ `,n=ol.join(sl.tmpdir(),`mc-notify-${process.pid}.ps1`);try{let r=Buffer.from([239,187,191]),i=Buffer.concat([r,Buffer.from(o,"utf8")]);return yo.writeFileSync(n,i),(0,zt.execSync)(`powershell -NoProfile -ExecutionPolicy Bypass -File "${n}"`,{stdio:"pipe",timeout:15e3}),!0}catch{return!1}finally{try{yo.unlinkSync(n)}catch{}}}function lg(s){return s.replace(/'/g,"''")}function xt(s){try{return process.platform==="win32"?(0,zt.execSync)(`where ${s} 2>NUL`,{stdio:"pipe"}):(0,zt.execSync)(`command -v ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}var yo,ol,sl,zt,dg=H(()=>{"use strict";yo=y(require("node:fs"),1),ol=y(require("node:path"),1),sl=y(require("node:os"),1),zt=require("node:child_process");l(nl,"sendNotification");l(uk,"notifyJobComplete");l(dk,"notifyUpdateAvailable");l(pk,"supportsNotifications");l(mk,"getNotificationBackend");l(fk,"notifyMac");l(ri,"escapeAS");l(gk,"notifyLinux");l(hk,"notifyLinuxLibnotify");l(yk,"notifyLinuxKdialog");l(bk,"notifyLinuxZenity");l(wk,"notifyWindows");l(lg,"escapePowerShell");l(xt,"commandExists")});var kl=y(wl(),1),{program:Mk,createCommand:Ik,createArgument:jk,createOption:Nk,CommanderError:Bk,InvalidArgumentError:Lk,InvalidOptionArgumentError:Uk,Command:Dl,Argument:Wk,Option:Et,Help:Hk}=kl.default;var N=y(require("node:path"),1),z=y(require("node:fs"),1);var Zp=y(require("node:readline"),1),V=y(require("node:path"),1),M=y(require("node:fs"),1),Ye=require("node:child_process");W();W();var Os=y(require("node:process"),1);W();var Bi=y(require("node:process"),1);var Rs=y(require("node:process"),1);var Xg=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);!Qg(n,r)&&o||Object.defineProperty(s,t,r)},"copyProperty"),Qg=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"),Zg=l((s,e)=>{let t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(s)&&Object.setPrototypeOf(s,t)},"changePrototype"),eh=l((s,e)=>`/* Wrapped ${s}*/
235
+ ${e}`,"wrappedToString"),th=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),oh=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),sh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=eh.bind(null,o,e.toString());Object.defineProperty(n,"name",oh);let{writable:r,enumerable:i,configurable:c}=th;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Ai(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))Xg(s,e,n,t);return Zg(s,e),sh(s,e,o),s}l(Ai,"mimicFunction");var jn=new WeakMap,Il=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(jn.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 Ai(r,s),jn.set(r,o),r},"onetime");Il.callCount=s=>{if(!jn.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return jn.get(s)};var jl=Il;var wo=[];wo.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&wo.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&wo.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Nn=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"),Pi=Symbol.for("signal-exit emitter"),Oi=globalThis,nh=Object.defineProperty.bind(Object),Mi=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Oi[Pi])return Oi[Pi];nh(Oi,Pi,{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}},Bn=class{static{l(this,"SignalExitBase")}},rh=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Ii=class extends Bn{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},ji=class extends Bn{static{l(this,"SignalExit")}#i=Ni.platform==="win32"?"SIGINT":"SIGHUP";#o=new Mi;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of wo)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(!Nn(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 wo)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,wo.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 Nn(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"&&Nn(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)}},Ni=globalThis.process,{onExit:Nl,load:pD,unload:mD}=rh(Nn(Ni)?new ji(Ni):new Ii);var Bl=Rs.default.stderr.isTTY?Rs.default.stderr:Rs.default.stdout.isTTY?Rs.default.stdout:void 0,ih=Bl?jl(()=>{Nl(()=>{Bl.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Ll=ih;var Ln=!1,Jo={};Jo.show=(s=Bi.default.stderr)=>{s.isTTY&&(Ln=!1,s.write("\x1B[?25h"))};Jo.hide=(s=Bi.default.stderr)=>{s.isTTY&&(Ll(),Ln=!0,s.write("\x1B[?25l"))};Jo.toggle=(s,e)=>{s!==void 0&&(Ln=s),Ln?Jo.show(e):Jo.hide(e)};var Li=Jo;var Ms=y(Ui(),1);W();var qe=y(require("node:process"),1);function Wi(){return qe.default.platform!=="win32"?qe.default.env.TERM!=="linux":!!qe.default.env.CI||!!qe.default.env.WT_SESSION||!!qe.default.env.TERMINUS_SUBLIME||qe.default.env.ConEmuTask==="{cmd::Cmder}"||qe.default.env.TERM_PROGRAM==="Terminus-Sublime"||qe.default.env.TERM_PROGRAM==="vscode"||qe.default.env.TERM==="xterm-256color"||qe.default.env.TERM==="alacritty"||qe.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Wi,"isUnicodeSupported");var ch={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},lh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},uh=Wi()?ch:lh,As=uh;function Hi({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(Hi,"ansiRegex");var dh=Hi();function Ps(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(dh,"")}l(Ps,"stripAnsi");var Gl=[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],ql=12288,Vl=65510,Jl=[12288,12288,65281,65376,65504,65510];var zl=4352,Kl=262141,Gi=[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 Wn=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 Yl=19968,[fh,gh]=hh(Gi);function hh(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(Yl>=n&&Yl<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(hh,"findWideFastPathRange");var Xl=l(s=>s<161||s>1114109?!1:Wn(Gl,s),"isAmbiguous"),Ql=l(s=>s<ql||s>Vl?!1:Wn(Jl,s),"isFullWidth");var Zl=l(s=>s>=fh&&s<=gh?!0:s<zl||s>Kl?!1:Wn(Gi,s),"isWide");function yh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(yh,"validate");function eu(s,{ambiguousAsWide:e=!1}={}){return yh(s),Ql(s)||Zl(s)||e&&Xl(s)?2:1}l(eu,"eastAsianWidth");var su=y(ou(),1);var bh=new Intl.Segmenter,wh=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function qi(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=Ps(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of bh.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)&&!wh.test(i)){if((0,su.default)().test(i)){n+=2;continue}n+=eu(c,r)}}return n}l(qi,"stringWidth");function Vi({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(Vi,"isInteractive");var Ji=y(require("node:process"),1);function zi(){let{env:s}=Ji.default,{TERM:e,TERM_PROGRAM:t}=s;return Ji.default.platform!=="win32"?e!=="linux":!!s.WT_SESSION||!!s.TERMINUS_SUBLIME||s.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||s.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(zi,"isUnicodeSupported");var et=y(require("node:process"),1);var kh=3,Ki=class{static{l(this,"StdinDiscarder")}#i=0;start(){this.#i++,this.#i===1&&this.#o()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#o(){et.default.platform==="win32"||!et.default.stdin.isTTY||(et.default.stdin.setRawMode(!0),et.default.stdin.on("data",this.#n),et.default.stdin.resume())}#e(){et.default.stdin.isTTY&&(et.default.stdin.off("data",this.#n),et.default.stdin.pause(),et.default.stdin.setRawMode(!1))}#n(e){e[0]===kh&&et.default.emit("SIGINT")}},Dh=new Ki,Yi=Dh;var vh=y(Ui(),1);var Xi=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#g;#l;#u;#d;#h;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Os.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Vi({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,Os.default.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(t){this.#i=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#n}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#f()}get interval(){return this.#g??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#g=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!zi())this.#r=Ms.default.line;else if(e===void 0)this.#r=Ms.default.dots;else if(e!=="default"&&Ms.default[e])this.#r=Ms.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#h}set text(e=""){this.#h=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#f()}get isSpinning(){return this.#m!==void 0}#y(e=this.#a,t=" "){return typeof e=="string"&&e!==""?e+t:typeof e=="function"?e()+t:""}#b(e=this.#c,t=" "){return typeof e=="string"&&e!==""?t+e:typeof e=="function"?t+e():""}#f(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),o=this.#b(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#h+"--"+o;this.#e=0;for(let r of Ps(n).split(`
236
+ `))this.#e+=Math.max(1,Math.ceil(qi(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&&Li.hide(this.#s),this.#t.discardStdin&&Os.default.stdin.isTTY&&(this.#o=!0,Yi.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#s.write(`- ${this.text}
237
+ `),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&Li.show(this.#s),this.#t.discardStdin&&Os.default.stdin.isTTY&&this.#o&&(Yi.stop(),this.#o=!1),this):this}succeed(e){return this.stopAndPersist({symbol:As.success,text:e})}fail(e){return this.stopAndPersist({symbol:As.error,text:e})}warn(e){return this.stopAndPersist({symbol:As.warning,text:e})}info(e){return this.stopAndPersist({symbol:As.info,text:e})}stopAndPersist(e={}){if(this.#u)return this;let t=e.prefixText??this.#a,o=this.#y(t," "),n=e.symbol??" ",r=e.text??this.text,c=typeof r=="string"?(n?" ":"")+r:"",u=e.suffixText??this.#c,d=this.#b(u," "),p=o+n+c+d+`
238
+ `;return this.stop(),this.#s.write(p),this}};function Is(s){return new Xi(s)}l(Is,"ora");Ce();W();Ce();W();Ce();function nu(s,e,t={}){let o=j(),n=Ve(o),r=U(o),i=t.maxWidth??o.columns,c=t.color??o.ansi,u=e.split(`
239
+ `),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,f=n.horizontal.repeat(Math.max(0,i-iu(p).length-1));d.push(c?a.cyan(p+f+n.topRight):p+f+n.topRight);let m=0,g=0;for(let S of u)if(!(S.startsWith("---")||S.startsWith("+++")||S.startsWith("diff ")||S.startsWith("index "))){if(S.startsWith("@@")){let C=`${n.vertical} ${S}`;d.push(c?a.magenta(C):C);continue}if(S.startsWith("+")){m++;let C=`${n.vertical} + ${S.slice(1)}`,_=Qi(C,i);d.push(c?a.green(_):_);continue}if(S.startsWith("-")){g++;let C=`${n.vertical} - ${S.slice(1)}`,_=Qi(C,i);d.push(c?a.red(_):_);continue}if(S.startsWith(" ")||S===""){let C=`${n.vertical} ${S}`,_=Qi(C,i);d.push(c?a.dim(_):_)}}let h=` +${m} -${g} `,b=`${n.bottomLeft}${n.horizontal}${h}`,k=n.horizontal.repeat(Math.max(0,i-b.length-1));return d.push(c?a.cyan(b+k+n.bottomRight):b+k+n.bottomRight),d.join(`
240
+ `)}l(nu,"renderDiff");function ru(s,e,t){let o=j(),n=U(o),r=o.ansi,i=r?a.green(`+${e}`):`+${e}`,c=r?a.red(`-${t}`):`-${t}`;return` ${n.file} ${s} (${i} ${c})`}l(ru,"renderDiffSummary");function Qi(s,e){return iu(s).length<=e?s:s.slice(0,e-3)+"..."}l(Qi,"truncateLine");function iu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(iu,"stripAnsi");function ea(s,e){let t=j(),o=U(t),n=t.ansi,r=Gh(s,o),i=qh(s,e),c=` ${r} ${s}: ${i}`;return n?a.yellow(c):c}l(ea,"renderToolStart");function ta(s,e,t={}){switch(e.type){case"file_edit":return Ih(e,t);case"file_read":return jh(e);case"terminal":return Nh(e,t);case"search":return Bh(e,t);case"git":return Lh(e);case"browser":return Uh(e);case"mcp":return Wh(e);case"web_search":return Hh(e);case"generic":return au(s,e);default:return au(s,{type:"generic",summary:JSON.stringify(e)})}}l(ta,"renderToolResult");function cu(s,e){let t=j(),o=U(t),n=t.ansi,r=` ${o.error} ${s} failed: ${e}`;return n?a.red(r):r}l(cu,"renderToolError");function Ih(s,e){return e.verbose&&s.diff?nu(s.filePath,s.diff):ru(s.filePath,s.linesAdded,s.linesRemoved)}l(Ih,"renderFileEdit");function jh(s){let e=j();return` ${U(e).file} Read ${Zi(s.filePath)} (${s.lineCount} lines)`}l(jh,"renderFileRead");function Nh(s,e){let t=j(),o=Ve(t),n=U(t),r=t.ansi,i=e.maxOutputLines??50,c=[],u=s.exitCode===0?r?a.green(n.checkmark):n.checkmark:r?a.red(n.cross):n.cross,d=` ${n.tool} $ ${s.command}`;if(c.push(r?a.bold(d):d),s.stdout){let f=s.stdout.split(`
241
+ `),m=f.slice(0,i);for(let g of m)c.push(r?a.dim(` ${g}`):` ${g}`);if(f.length>i){let g=` [truncated ${f.length-i} lines \u2014 use --verbose for full output]`;c.push(r?a.yellow(g):g)}}if(s.stderr&&s.stderr!==s.stdout){let f=s.stderr.split(`
242
+ `).slice(0,10);for(let m of f)c.push(r?a.red(` ${m}`):` ${m}`)}let p=s.duration?` (${(s.duration/1e3).toFixed(1)}s)`:"";return c.push(` ${u} Exit ${s.exitCode}${p}`),c.join(`
243
+ `)}l(Nh,"renderTerminal");function Bh(s,e){let t=j(),o=U(t),n=t.ansi,r=[];r.push(` ${o.search} Search: "${s.query}" (${s.totalMatches} matches)`);let i=e.verbose?20:8,c=s.matches.slice(0,i);for(let u of c){let d=`${u.file}:${u.line}`,p=u.content.trim().slice(0,80),f=` ${d}: ${p}`;r.push(n?a.dim(f):f)}return s.matches.length>i&&r.push(n?a.yellow(` ... ${s.matches.length-i} more matches`):` ... ${s.matches.length-i} more matches`),r.join(`
244
+ `)}l(Bh,"renderSearch");function Lh(s){let e=j(),t=U(e),o=e.ansi,n=[];if(n.push(` ${t.git} git ${s.command}`),s.output){let r=s.output.split(`
245
+ `).slice(0,15);for(let i of r)n.push(o?a.dim(` ${i}`):` ${i}`)}return n.join(`
246
+ `)}l(Lh,"renderGit");function Uh(s){let e=j(),t=U(e),o=e.ansi,n=[];if(n.push(` ${t.browser} ${s.title||s.url}`),s.url&&n.push(o?a.dim(` ${s.url}`):` ${s.url}`),s.content){let r=s.content.slice(0,200).replace(/\n/g," ");n.push(o?a.dim(` ${r}...`):` ${r}...`)}return n.join(`
247
+ `)}l(Uh,"renderBrowser");function Wh(s){let e=j(),t=U(e),o=Ve(e),n=e.ansi,r=e.columns,i=[],c=n?a.cyan(s.server):s.server,u=n?a.bold(s.tool):s.tool,d=`${o.topLeft}${o.horizontal} ${t.mcp} ${s.server}::${s.tool} `,p=o.horizontal.repeat(Math.max(0,r-d.length-3));i.push(n?a.blue(o.topLeft+o.horizontal+" ")+`${t.mcp} ${c}::${u} `+a.blue(p+o.topRight):d+p+o.topRight);let f=typeof s.result=="string"?s.result:JSON.stringify(s.result,null,2),m=f.split(`
248
+ `).slice(0,10);for(let h of m)i.push(`${o.vertical} ${h}`);f.split(`
249
+ `).length>10&&i.push(`${o.vertical} ${n?a.dim(`... ${f.split(`
250
+ `).length-10} more lines`):"..."}`);let g=`${o.bottomLeft}${o.horizontal.repeat(Math.max(0,r-2))}${o.bottomRight}`;return i.push(n?a.blue(g):g),i.join(`
251
+ `)}l(Wh,"renderMcp");function Hh(s){let e=j(),t=U(e),o=Ve(e),n=e.ansi,r=e.columns,i=[],c=`${o.topLeft}${o.horizontal} ${t.web} web_search `,u=o.horizontal.repeat(Math.max(0,r-c.length-3));i.push(n?a.cyan(c+u+o.topRight):c+u+o.topRight),i.push(`${o.vertical} Query: "${s.query}"`),i.push(`${o.vertical} Results:`);for(let p=0;p<s.results.length&&p<5;p++){let f=s.results[p],m=` ${p+1}. `;i.push(n?`${o.vertical}${m}${a.bold(f.title)} (${a.dim(f.url)})`:`${o.vertical}${m}${f.title} (${f.url})`)}i.push(`${o.vertical} Context injected: ${s.tokensInjected.toLocaleString()} tokens`);let d=`${o.bottomLeft}${o.horizontal.repeat(Math.max(0,r-2))}${o.bottomRight}`;return i.push(n?a.cyan(d):d),i.join(`
252
+ `)}l(Hh,"renderWebSearch");function au(s,e){let t=j();return` ${U(t).tool} ${s}: ${e.summary}`}l(au,"renderGeneric");function Gh(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(Gh,"getToolIcon");function qh(s,e){switch(s){case"file_edit":return Zi(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return Zi(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(qh,"getToolArgsSummary");function Zi(s){return process.platform==="win32"?s.replace(/\//g,"\\"):s}l(Zi,"displayPath");W();function qn(s,e={}){let t=e.width||process.stdout.columns||80,o=s.split(`
253
+ `),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(lu(c,i)),r=!1,c=[],i=""):(r=!0,i=d[1]||"");continue}if(r){c.push(u);continue}let p=u.match(/^# (.+)/);if(p){n.push(""),n.push(a.bold.hex("#a3cad3")(p[1])),n.push(a.dim("\u2500".repeat(Math.min(p[1].length+2,t-4))));continue}let f=u.match(/^## (.+)/);if(f){n.push(""),n.push(a.bold.hex("#6B8DD6")(f[1]));continue}let m=u.match(/^### (.+)/);if(m){n.push(a.bold(m[1]));continue}let g=u.match(/^####+ (.+)/);if(g){n.push(a.bold.dim(g[1]));continue}if(/^---+$/.test(u.trim())||/^\*\*\*+$/.test(u.trim())){n.push(a.dim("\u2500".repeat(Math.min(40,t-4))));continue}let h=u.match(/^(\s*)([-*+])\s(.+)/);if(h){let S=h[1],C=Gn(h[3]);n.push(`${S} \u2022 ${C}`);continue}let b=u.match(/^(\s*)(\d+)\.\s(.+)/);if(b){let S=b[1],C=b[2],_=Gn(b[3]);n.push(`${S} ${a.dim(C+".")} ${_}`);continue}let k=u.match(/^>\s?(.*)/);if(k){n.push(a.dim(" \u2502 ")+a.italic(Gn(k[1])));continue}if(u.trim()===""){n.push("");continue}n.push(Gn(u))}return r&&c.length>0&&n.push(lu(c,i)),n.join(`
254
+ `)}l(qn,"renderMarkdown");function Gn(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(Gn,"renderInline");function lu(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}${Vh(c,e)}`);return[n,...i,r].join(`
255
+ `)}l(lu,"renderCodeBlock");function Vh(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=Jh(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(Vh,"highlightSyntax");function Jh(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(Jh,"getLanguageKeywords");function uu(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(uu,"containsMarkdown");W();Ce();var Vn=class{static{l(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=j(),this.icons=U(this.caps),this.data={model:"",mode:"code",branch:"",dirty:!1,sandbox:!1,tokensIn:0,tokensOut:0,cost:0,turn:0,contextPct:0,activity:"",busy:!1,budgetUsd:0,...e}}start(){!this.caps.stdoutTTY||!this.caps.ansi||(this.enabled=!0,process.stdout.write(`
256
+ `),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=j(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,b=t.dirty?a.yellow:a.green,k=t.dirty?" \u25CF":"";o.push(b(` ${h} ${t.branch}${k} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=zh(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,b=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(b(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,b=6,k=Math.round(t.contextPct/100*b),S=b-k,C=h("\u2588".repeat(k))+a.dim("\u2591".repeat(S));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=du(c).length,p=du(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function zh(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(zh,"formatTokensCompact");function du(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(du,"stripAnsi");var Kh={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},pu={navy:"#051E50",teal:"#A3CAD3",accent:"#6B8DD6"},vo=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={...Kh,...e},this.caps=j(),this.icons=U(this.caps),this.box=Ve(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:l(t=>this.renderToken(t),"onToken"),onThinking:l(t=>this.renderThinking(t),"onThinking"),onRunStarted:l(t=>this.renderRunStarted(t),"onRunStarted"),onRunComplete:l(t=>this.renderRunComplete(t),"onRunComplete"),onRunError:l(t=>this.renderRunError(t),"onRunError"),onToolStart:l(t=>this.renderToolStart(t),"onToolStart"),onToolProgress:l(t=>this.renderToolProgress(t),"onToolProgress"),onToolResult:l(t=>this.renderToolResult(t),"onToolResult"),onToolError:l(t=>this.renderToolError(t),"onToolError"),onApprovalRequest:l(t=>this.renderApprovalRequest(t),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new Vn(e)),this.statusBar}printTurnBoundary(e,t,o,n){let r=this.caps.ansi,i=Math.min(60,this.caps.columns-4),c=t>=1e3?`${(t/1e3).toFixed(1)}K`:`${t}`,u=o?` ${this.icons.cost} $${o.toFixed(3)}`:"",d=n?` ${a.dim(`total: $${n.toFixed(2)}`)}`:"",p=` Turn ${e} ${a.dim("\xB7")} ${c} tokens${u}${d} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,m=Math.max(0,i-f),g=Math.floor(m/2),h=` ${this.box.horizontal.repeat(g)}${p}${this.box.horizontal.repeat(m-g)}`;console.log(""),console.log(r?a.dim(h):h),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e){let t=this.caps.ansi,o=t?a.hex(pu.accent):d=>d,n=t?a.bold:d=>d,r=t?a.dim:d=>d,i=t?a.white.bold:d=>d,c=t?a.hex("#4A7CBA"):d=>d,u=t?a.hex("#a3cad3"):d=>d;if(console.log(""),this.caps.unicode&&this.caps.columns>=56){let d=this.box,p=52;console.log(o(` ${d.topLeft}${d.horizontal.repeat(p)}${d.topRight}`));let m=`${this.caps.nerdFont?"\uF120":"\u25C1/\u25B7"} MonkeysCode`,g="CLI Agent",h=Math.max(0,p-m.length-g.length-2);console.log(` ${o(d.vertical)} ${i(m)}${" ".repeat(h)}${r(g)} ${o(d.vertical)}`),console.log(o(` ${d.teeRight}${d.horizontal.repeat(p)}${d.teeLeft}`));let k=`v2.0.0${e?` ${r("\xB7")} ${e}`:""}`.replace(/\x1b\[[0-9;]*m/g,""),S=Math.max(0,p-k.length-2);console.log(` ${o(d.vertical)} ${o("v2.0.0")}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(S)} ${o(d.vertical)}`),console.log(o(` ${d.bottomLeft}${d.horizontal.repeat(p)}${d.bottomRight}`))}else this.caps.unicode?(console.log(c(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),console.log(` \u2502 ${u("\u25C1\u2571\u25B7")} ${i("MonkeysCode CLI")} \u2502`),console.log(` \u2502 ${o("v2.0.0")} ${r("\xB7 Agent")} \u2502`),console.log(c(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),e&&console.log(` ${r(e)}`)):(console.log(" </> MC - MonkeysCode CLI v2.0.0"),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let d=` ${this.icons.lock} Sandboxed`;console.log(t?a.green(d):d)}else{let d=` ${this.icons.unlock} Unsandboxed`;console.log(t?a.yellow(d):d)}console.log("")}renderToken(e){if(this.lastWasToken||(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode&&process.stdout.write(a.dim(` ${this.box.vertical} `))),this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
257
+ `+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(pu.accent),c=a.green,u=a.dim,d=l((p,f)=>{let m=(p+f).replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(0,r-m.length-4);return` ${i(n.vertical)} ${p}${" ".repeat(g)}${f} ${i(n.vertical)}`},"pad");if(console.log(""),console.log(i(` ${n.topLeft}${n.horizontal} ${c(`${this.icons.success} Run Complete`)} ${n.horizontal.repeat(Math.max(0,r-17))}${n.topRight}`)),console.log(d(" Duration:",`${o}s`)),console.log(d(" Tokens:",`${e.tokensUsed.toLocaleString()}`)),console.log(d(" Tools:",`${e.toolCalls} calls`)),e.filesChanged.length>0){console.log(i(` ${n.teeRight}${n.horizontal.repeat(r)}${n.teeLeft}`)),console.log(d(" Files Changed:",`${e.filesChanged.length}`));for(let p of e.filesChanged){let f=p.split("/").slice(-2).join("/");console.log(d(` ${this.icons.edit} ${f}`,""))}}console.log(i(` ${n.bottomLeft}${n.horizontal.repeat(r)}${n.bottomRight}`)),console.log("")}else{let r=this.box.separator.repeat(Math.min(60,this.caps.columns-2)),i=[`${this.icons.success} Done`,`${e.tokensUsed.toLocaleString()} tokens`,`${e.toolCalls} tool calls`,`${e.filesChanged.length} files changed`,`${o}s`].join(" \xB7 ");if(console.log(""),console.log(r),console.log(` ${i}`),e.filesChanged.length>0){console.log(""),console.log(" Files changed:");for(let c of e.filesChanged)console.log(` ${c}`)}console.log(r),console.log("")}this.statusBar&&this.statusBar.update({busy:!1,activity:""})}renderRunError(e){this.lastWasToken&&(console.log(""),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=` ${this.icons.error} Agent error: ${e.message}`;console.log(t?a.red(o):o),e.code&&console.log(t?a.dim(` Code: ${e.code}`):` Code: ${e.code}`)}renderToolStart(e){if(this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),console.log(""),console.log(ea(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=Is({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(ta(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(cu(e.toolName,e.message))}renderApprovalRequest(e){this.lastWasToken&&(console.log(""),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=this.box,n={safe:{color:t?a.green:i=>i,icon:this.icons.success,label:"Safe"},moderate:{color:t?a.yellow:i=>i,icon:this.icons.warning,label:"Moderate"},dangerous:{color:t?a.red:i=>i,icon:this.icons.error,label:"Destructive"}},r=n[e.riskLevel]||n.moderate;if(this.caps.unicode){let i=Math.min(54,this.caps.columns-6);console.log(""),console.log(r.color(` ${o.topLeft}${o.horizontal} ${r.icon} Approval Required ${o.horizontal.repeat(Math.max(0,i-23))}${o.topRight}`)),console.log(r.color(` ${o.vertical}${" ".repeat(i)}${o.vertical}`));let c=` Tool: ${e.toolName}`,u=Math.max(0,i-c.length);console.log(r.color(` ${o.vertical}`)+` ${c}${" ".repeat(u)}`+r.color(o.vertical));let d=` ${e.description}`.slice(0,i-2),p=Math.max(0,i-d.length);console.log(r.color(` ${o.vertical}`)+` ${d}${" ".repeat(p)}`+r.color(o.vertical));let f=` Risk: ${r.icon} ${r.label}`,m=f.replace(/\x1b\[[0-9;]*m/g,""),g=Math.max(0,i-m.length);console.log(r.color(` ${o.vertical}`)+` ${f}${" ".repeat(g)}`+r.color(o.vertical)),console.log(r.color(` ${o.vertical}${" ".repeat(i)}${o.vertical}`));let b=e.riskLevel==="dangerous"?" [y] Allow once [n] Deny":" [y] Allow [n] Deny [a] Always [!] YOLO",k=Math.max(0,i-b.length);console.log(r.color(` ${o.vertical}`)+a.dim(` ${b}${" ".repeat(k)}`)+r.color(o.vertical)),console.log(r.color(` ${o.bottomLeft}${o.horizontal.repeat(i)}${o.bottomRight}`))}else{console.log(""),console.log(r.color(` ${r.icon} Permission required: ${e.toolName}`)),console.log(r.color(` ${e.description}`)),console.log(r.color(` Risk: ${r.label}`));let i=JSON.stringify(e.args,null,2).split(`
258
+ `).slice(0,5);for(let c of i)console.log(t?a.dim(` ${c}`):` ${c}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let t=this.caps.ansi;console.log(t?a.dim(` ${e}`):` ${e}`)}printSuccess(e){let t=this.caps.ansi;console.log(t?a.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let t=this.caps.ansi;console.error(t?a.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let t=this.caps.ansi;console.log(t?a.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=Is({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):"?",n=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(""),console.log(t?a.dim(n):n),console.log(t?a.bold(" Session Summary"):" 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(ea(e,t)),!this.opts.accessible&&this.caps.ansi){let o=Is({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(ta(e,r,n))}printTodoList(e){let t=this.caps.ansi,o=t?a.dim:r=>r,n=t?a.bold:r=>r;console.log(""),console.log(n(" \u{1F4CB} Task Plan:"));for(let r of e){let i=r.status==="done"?"\u2705":r.status==="in_progress"?"\u{1F504}":"\u2B1C",c=r.status==="done"?t?a.green:u=>u:r.status==="in_progress"?t?a.yellow:u=>u:o;console.log(c(` ${i} ${r.content}`))}console.log("")}flushTokenBuffer(){if(!this.tokenBuffer)return;let e=this.tokenBuffer.replace(/<think>[\s\S]*?<\/think>/g,"").trim();this.tokenBuffer="";let t=e.split(`
259
+ `).length;if(this.caps.ansi&&uu(e)){for(let n=0;n<t;n++)process.stdout.write("\x1B[2K"),n<t-1&&process.stdout.write("\x1B[1A");process.stdout.write("\r");let o=qn(e,{caps:this.caps});process.stdout.write(o)}else console.log("")}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=Yh(e.content,d),f=` ${t.bottomLeft}${t.horizontal.repeat(n)}${t.bottomRight}`;console.log(""),console.log(this.caps.ansi?a.cyan(u):u);for(let b of p){let k=b.padEnd(d);console.log(this.caps.ansi?` ${a.cyan(t.vertical)} ${k} ${a.cyan(t.vertical)}`:` ${t.vertical} ${k} ${t.vertical}`)}let m=`${i} `,g=Math.max(0,n-m.length),h=` ${t.bottomLeft}${t.horizontal.repeat(g)}${m}${t.bottomRight}`;console.log(this.caps.ansi?a.cyan(h):h),console.log("")}};function Yh(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(Yh,"wrapText");Ce();oe();Je();Q();var ue=y(require("node:fs"),1),Pe=y(require("node:path"),1);X();var by=20;function ed(s,e,t,o){if(o.size===0)return;let n=T(),r=Pe.join(n.data,"checkpoints");ue.mkdirSync(r,{recursive:!0});let i={runId:s,prompt:e,workspace:t,timestamp:Date.now(),snapshots:Object.fromEntries(o)},c=Pe.join(r,`${s}.json`);ue.writeFileSync(c,JSON.stringify(i,null,2)),wy(r)}l(ed,"saveCheckpoint");function td(){let s=T(),e=Pe.join(s.data,"checkpoints");return ue.existsSync(e)?ue.readdirSync(e).filter(o=>o.endsWith(".json")).sort().reverse().map(o=>{try{return JSON.parse(ue.readFileSync(Pe.join(e,o),"utf8"))}catch{return null}}).filter(Boolean):[]}l(td,"listCheckpoints");function od(s){let e=T(),t=Pe.join(e.data,"checkpoints",`${s}.json`);if(!ue.existsSync(t))throw new Error(`Checkpoint not found: ${s}`);let o=JSON.parse(ue.readFileSync(t,"utf8")),n=[];for(let[r,i]of Object.entries(o.snapshots))try{i===null?ue.existsSync(r)&&(ue.unlinkSync(r),n.push(`deleted ${Pe.relative(o.workspace,r)}`)):(ue.mkdirSync(Pe.dirname(r),{recursive:!0}),ue.writeFileSync(r,i),n.push(`restored ${Pe.relative(o.workspace,r)}`))}catch(c){n.push(`FAILED ${Pe.relative(o.workspace,r)}: ${c instanceof Error?c.message:c}`)}return ue.unlinkSync(t),n}l(od,"revertCheckpoint");function wy(s){let e=ue.readdirSync(s).filter(t=>t.endsWith(".json")).map(t=>({name:t,mtime:ue.statSync(Pe.join(s,t)).mtime.getTime()})).sort((t,o)=>o.mtime-t.mtime);for(let t of e.slice(by))try{ue.unlinkSync(Pe.join(s,t.name))}catch{}}l(wy,"pruneCheckpoints");var he=y(require("node:fs"),1),no=y(require("node:path"),1),sd=y(require("node:crypto"),1);X();var ky="sessions",Dy=20,vy=30*24*60*60*1e3,It=class{static{l(this,"SessionStore")}sessionsDir;constructor(){let e=T();this.sessionsDir=no.join(e.data,ky),this.ensureDir()}save(e){this.ensureDir();let t=this.sessionPath(e.id),o=JSON.stringify(e,null,2);he.writeFileSync(t,o,"utf-8")}create(e,t,o){let n={id:sd.randomUUID(),workspace:no.resolve(e),startTime:Date.now(),lastActive:Date.now(),turnCount:0,model:t,mode:o,messages:[],stats:{tokensUsed:0,toolCalls:0,filesChanged:[]}};return this.save(n),n}addMessage(e,t,o){e.messages.push({role:t,content:o,timestamp:Date.now()}),e.lastActive=Date.now(),t==="user"&&e.turnCount++,this.save(e)}updateStats(e,t,o,n){e.stats.tokensUsed+=t,e.stats.toolCalls+=o;for(let r of n)e.stats.filesChanged.includes(r)||e.stats.filesChanged.push(r);e.lastActive=Date.now(),this.save(e)}load(e){let t=this.sessionPath(e);if(!he.existsSync(t))return null;try{let o=he.readFileSync(t,"utf-8");return JSON.parse(o)}catch{return null}}loadLatest(e){let t=this.list(),o=e?t.filter(n=>n.workspace===no.resolve(e)):t;return o.length===0?null:this.load(o[0].id)}list(){this.ensureDir();let e=he.readdirSync(this.sessionsDir).filter(o=>o.endsWith(".json")).map(o=>no.join(this.sessionsDir,o)),t=[];for(let o of e)try{let n=he.readFileSync(o,"utf-8"),r=JSON.parse(n),i=r.messages.find(c=>c.role==="user");t.push({id:r.id,workspace:r.workspace,startTime:r.startTime,lastActive:r.lastActive,turnCount:r.turnCount,model:r.model,preview:i?i.content.substring(0,80).replace(/\n/g," "):"(empty)"})}catch{}return t.sort((o,n)=>n.lastActive-o.lastActive),t.slice(0,Dy)}delete(e){let t=this.sessionPath(e);return he.existsSync(t)?(he.unlinkSync(t),!0):!1}prune(e=vy){this.ensureDir();let t=Date.now(),o=0,n=he.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).map(i=>no.join(this.sessionsDir,i));for(let i of n)try{let c=he.readFileSync(i,"utf-8"),u=JSON.parse(c);t-u.lastActive>e&&(he.unlinkSync(i),o++)}catch{}let r=he.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).length;return{deleted:o,remaining:r}}sessionPath(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"");return no.join(this.sessionsDir,`${t}.json`)}ensureDir(){he.existsSync(this.sessionsDir)||he.mkdirSync(this.sessionsDir,{recursive:!0})}};ka();var st=y(require("node:fs"),1),ur=y(require("node:path"),1);X();var Aa=1e3,Sy="history",lr=class{static{l(this,"HistoryManager")}historyFile;constructor(){let e=T();this.historyFile=ur.join(e.data,Sy)}load(){try{return st.existsSync(this.historyFile)?st.readFileSync(this.historyFile,"utf-8").split(`
260
+ `).filter(t=>t.trim().length>0).slice(-Aa):[]}catch{return[]}}append(e){let t=e.trim();if(t&&!t.startsWith("/"))try{let o=ur.dirname(this.historyFile);st.existsSync(o)||st.mkdirSync(o,{recursive:!0});let n=[];if(st.existsSync(this.historyFile)&&(n=st.readFileSync(this.historyFile,"utf-8").split(`
261
+ `).filter(r=>r.trim().length>0)),n.length>0&&n[n.length-1]===t)return;n.push(t),n.length>Aa&&(n=n.slice(-Aa)),st.writeFileSync(this.historyFile,n.join(`
262
+ `)+`
263
+ `,"utf-8")}catch{}}wire(e){let t=this.load(),o=e;o.history&&Array.isArray(o.history)&&(o.history=[...t.reverse(),...o.history],o.history.length>e.historySize&&(o.history=o.history.slice(0,e.historySize))),e.on("line",n=>{this.append(n)})}getPath(){return this.historyFile}};W();var dr=require("node:child_process");Je();Q();function Pa(s){return xy(s)?Fy(s):Cy(s)?Ty(s):$y(s)?Ry(s):_y(s)?Ay(s):Ey(s)?Py(s):Oy(s)}l(Pa,"parseTestOutput");function nd(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(nd,"detectVerifyCommand");function xy(s){return/Tests?:\s+\d+ (?:passed|failed)/.test(s)||/PASS|FAIL/.test(s)&&/Test Suites:/.test(s)}l(xy,"isJest");function Cy(s){return s.includes("vitest")||/✓|×/.test(s)&&/Tests\s+\d+/.test(s)}l(Cy,"isVitest");function $y(s){return/={3,}\s*(?:FAILURES|ERRORS|short test summary)/.test(s)||/\d+ passed/.test(s)&&/pytest/.test(s)}l($y,"isPytest");function _y(s){return/test result:/.test(s)&&/ok|FAILED/.test(s)}l(_y,"isCargoTest");function Ey(s){return/^(?:ok|FAIL)\s+\S+/.test(s)||/--- FAIL:/.test(s)}l(Ey,"isGoTest");function Fy(s){let e=[],t=/✓|✔|√|PASS/,o=/✕|✖|×|✗|FAIL/,n=/FAIL\s+(\S+)\n([\s\S]*?)(?=\n(?:PASS|FAIL|Test Suites:)|\z)/g,r;for(;(r=n.exec(s))!==null;){let m=r[1],g=r[2],h=/(?:✕|✖|×|✗)\s+(.+?)(?:\s+\((\d+)\s*ms\))?$/gm,b;for(;(b=h.exec(g))!==null;)e.push({suite:m,name:b[1].trim(),status:"fail",file:m,durationMs:b[2]?parseInt(b[2],10):void 0})}let i=/●\s+(.+?)\s*\n\s*\n\s*([\s\S]*?)(?=\n\s*●|\n\s*Test Suites:)/g;for(;(r=i.exec(s))!==null;){let m=r[1].trim(),g=r[2].trim().split(`
264
+ `)[0],h=e.find(b=>m.includes(b.name));h&&(h.error=g)}let c=s.match(/Tests:\s+(?:(\d+) failed,?\s*)?(?:(\d+) skipped,?\s*)?(?:(\d+) passed,?\s*)?(\d+) total/),u=c?parseInt(c[1]||"0",10):e.filter(m=>m.status==="fail").length,d=c?parseInt(c[2]||"0",10):0,p=c?parseInt(c[3]||"0",10):0,f=c?parseInt(c[4]||"0",10):e.length;return ts("jest",e,{total:f,passed:p,failed:u,skipped:d})}l(Fy,"parseJest");function Ty(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 ts("vitest",e)}l(Ty,"parseVitest");function Ry(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 ts("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(Ry,"parsePytest");function Ay(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(`
265
+ `)[0])}return ts("cargo",e)}l(Ay,"parseCargoTest");function Py(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 ts("go",e)}l(Py,"parseGoTest");function Oy(s){let e=[],t=s.split(`
266
+ `);for(let o of t)/\bFAIL\b|✕|✗|ERROR|BROKEN/.test(o)&&e.push({suite:"unknown",name:o.trim().substring(0,100),status:"fail"});return ts("unknown",e)}l(Oy,"parseGeneric");function ts(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(ts,"buildSummary");var rd=10,id=1800,ad=5,pr=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||rd,status:"planning",subtasks:[],elapsed:0,totalTokens:0,totalCost:0}}async run(){this.startTime=Date.now();let e=this.opts.maxIterations||rd,t=(this.opts.timeoutSeconds||id)*1e3,o=this.opts.maxCostUsd||ad,n=J();if(this.printGoalHeader(),!this.opts.verifyCommand){let r=nd(this.opts.workspace);r&&(this.opts.verifyCommand=r,console.log(a.dim(` Auto-detected verify command: ${r}`)))}for(let r=1;r<=e;r++){if(this.cancelled){this.progress.status="cancelled",this.printGoalStatus("cancelled");break}let i=Date.now()-this.startTime;if(i>t){this.progress.status="limit_reached",this.printGoalStatus("timeout");break}if(this.progress.totalCost>o){this.progress.status="limit_reached",this.printGoalStatus("cost_limit");break}this.progress.iteration=r,this.progress.elapsed=i;let c=this.buildIterationPrompt(r,e);this.progress.status="executing",this.printIterationHeader(r,e);let u=new Se({platformUrl:n.platformUrl,token:this.opts.token,model:this.opts.model,workspace:this.opts.workspace,mode:"auto",maxTurns:20,sandboxed:!1,webEnabled:n.webEnabled,effort:"reasoning",userId:this.opts.userId,orgId:this.opts.orgId}),d="";u.on("event",f=>{switch(f.type){case"streaming_chunk":d+=f.content,process.stdout.write(f.content);break;case"streaming_end":console.log("");break;case"tool_call_start":this.renderer.printToolCallStart(f.name,f.args);break;case"tool_call_result":this.renderer.printToolCallResult(f.name,f.result);break;case"run_complete":this.progress.totalTokens+=f.summary.tokensIn+f.summary.tokensOut,this.progress.totalCost+=f.summary.costUsd;break}});try{await u.run(c)}catch(f){this.renderer.printError(`Iteration ${r} error: ${f instanceof Error?f.message:f}`)}if(this.evaluateGoalCompletion(d)){this.progress.status="completed",this.printGoalStatus("completed");break}this.lastTestSummary&&this.lastTestSummary.failed>this.prevFailCount&&(console.log(a.yellow(` \u26A0\uFE0F Failures increased (${this.prevFailCount} \u2192 ${this.lastTestSummary.failed}). Rolling back...`)),this.rollbackCheckpoint()),this.prevFailCount=this.lastTestSummary?.failed??1/0,this.saveCheckpoint(),r===e&&(this.progress.status="limit_reached",this.printGoalStatus("max_iterations"))}return this.progress.elapsed=Date.now()-this.startTime,this.progress}cancel(){this.cancelled=!0}getProgress(){return this.progress.elapsed=Date.now()-this.startTime,{...this.progress}}buildIterationPrompt(e,t){if(e===1)return[`AUTONOMOUS GOAL MODE \u2014 Iteration ${e}/${t}`,"",`Goal: ${this.opts.goal}`,"","You are running in autonomous goal mode. Your job:","1. Plan: Break the goal into concrete sub-tasks","2. Execute: Implement the changes needed","3. Verify: Run tests, lint, or type-check to confirm the goal is met",this.opts.verifyCommand?`4. After you finish, I will automatically run: \`${this.opts.verifyCommand}\`. If it fails, you will get another iteration to fix the issues.`:'4. Report: End your response with "GOAL_STATUS: COMPLETE" if done, or "GOAL_STATUS: IN_PROGRESS" if more work is needed',"","Work autonomously \u2014 do not ask for user input. Make decisions yourself.","If you encounter errors, fix them and continue."].join(`
267
+ `);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(`
268
+ `)}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(`
269
+ \u{1F50D} Running verification: ${e}`));try{let o=(0,dr.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=Pa(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(`
270
+ `).slice(-3).join(`
271
+ `)}`)),!0}catch(t){let o=t.stderr?.toString().slice(-500)||"",n=t.stdout?.toString().slice(-500)||"",r=n+`
272
+ `+o;if(this.lastTestSummary=Pa(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(`
273
+ `).slice(-3).join(`
274
+ `)}`)):n.trim()&&console.log(a.dim(` ${n.trim().split(`
275
+ `).slice(-3).join(`
276
+ `)}`));return!1}}saveCheckpoint(){try{(0,dr.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,dr.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||ad).toFixed(2)}`)),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}printIterationHeader(e,t){let o=((Date.now()-this.startTime)/1e3).toFixed(0);console.log(""),console.log(a.hex("#6B8DD6")(` \u2501\u2501\u2501 Iteration ${e}/${t} \u2501\u2501\u2501 ${o}s elapsed \u2501\u2501\u2501 ${this.progress.totalTokens.toLocaleString()} tokens \u2501\u2501\u2501`)),console.log("")}printGoalStatus(e){let t=((Date.now()-this.startTime)/1e3).toFixed(0);switch(console.log(""),console.log(a.dim(` ${"\u2500".repeat(50)}`)),e){case"completed":console.log(a.green.bold(" \u2705 Goal completed!"));break;case"cancelled":console.log(a.yellow(" \u26A0\uFE0F Goal cancelled by user."));break;case"timeout":console.log(a.yellow(" \u23F1 Goal stopped: timeout reached."));break;case"cost_limit":console.log(a.yellow(` \u{1F4B0} Goal stopped: cost limit reached ($${this.progress.totalCost.toFixed(2)}).`));break;case"max_iterations":console.log(a.yellow(` \u{1F504} Goal stopped: max iterations reached (${this.progress.maxIterations}).`));break}console.log(a.dim(` Iterations: ${this.progress.iteration}`)),console.log(a.dim(` Elapsed: ${t}s`)),console.log(a.dim(` Tokens: ${this.progress.totalTokens.toLocaleString()}`)),console.log(a.dim(` Est. cost: $${this.progress.totalCost.toFixed(4)}`)),e!=="completed"&&console.log(a.dim(" Resume: mc --continue")),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}};W();var cd=y(require("node:crypto"),1);Je();Q();var mr=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=cd.randomUUID().slice(0,8),o=J(),n={id:t,description:e,status:"running",startTime:Date.now(),tokensUsed:0};this.subtasks.set(t,n),this.renderer.printSuccess(`Subtask ${a.bold(t)} spawned: "${e}"`),console.log(a.dim(` Track: /subtask status \xB7 Cancel: /subtask cancel ${t}`));let r=new Se({platformUrl:o.platformUrl,token:this.opts.token,model:this.opts.model,workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:o.webEnabled,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.loops.set(t,r);let i="";return r.on("event",c=>{switch(c.type){case"streaming_chunk":i+=c.content;break;case"run_complete":n.tokensUsed+=c.summary.tokensIn+c.summary.tokensOut;break}}),this.executeSubtask(t,r,e,n,i).catch(()=>{}),t}cancel(e){let t=this.subtasks.get(e),o=this.loops.get(e);return!t||t.status!=="running"?(this.renderer.printError(`Subtask ${e} not found or not running.`),!1):(o&&o.cancel(),t.status="cancelled",t.endTime=Date.now(),this.loops.delete(e),this.renderer.printSuccess(`Subtask ${e} cancelled.`),!0)}getStatus(){return[...this.subtasks.values()].sort((e,t)=>t.startTime-e.startTime)}printStatus(){let e=this.getStatus();if(e.length===0){console.log(a.dim(" No subtasks."));return}console.log(""),console.log(a.bold(" Subtasks:")),console.log(` ${"\u2500".repeat(70)}`);for(let t of e){let o=((t.endTime||Date.now())-t.startTime)/1e3,n={running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u23F9"}[t.status],r={running:a.cyan,completed:a.green,failed:a.red,cancelled:a.yellow}[t.status];if(console.log(` ${n} ${a.bold(t.id)} ${r(t.status.padEnd(10))} ${t.description.substring(0,40).padEnd(42)} ${a.dim(`${o.toFixed(0)}s ${t.tokensUsed.toLocaleString()} tok`)}`),t.status==="completed"&&t.result){let i=t.result.split(`
277
+ `)[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(`
278
+ `);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(`
279
+ `).slice(0,3).join(`
280
+ `);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 Ma=y(require("node:path"),1),qs=require("node:child_process"),ud=require("node:events");Je();var fr=require("node:child_process"),Ee=y(require("node:fs"),1),_o=y(require("node:path"),1);var gr=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=_o.join(this.workspace,".git","mc-merge-tmp");Ee.mkdirSync(c,{recursive:!0});let u=_o.join(c,"base"),d=_o.join(c,"ours"),p=_o.join(c,"theirs");Ee.writeFileSync(u,n),Ee.writeFileSync(d,r),Ee.writeFileSync(p,i);try{(0,fr.execSync)(`git merge-file ${d} ${u} ${p}`,{cwd:this.workspace,stdio:"pipe"});let f=Ee.readFileSync(d,"utf8");return this.cleanup(c),{file:e,success:!0,hadConflicts:!1,mergedContent:f,conflictMarkers:[]}}catch{let f=Ee.readFileSync(d,"utf8"),m=this.parseConflictMarkers(f,t[1]);if(this.cleanup(c),m.length>0){let g=this.autoResolveMarkers(f);return{file:e,success:g.resolved,hadConflicts:!0,mergedContent:g.content,conflictMarkers:g.resolved?[]:m}}return{file:e,success:!1,hadConflicts:!0,mergedContent:f,conflictMarkers:m}}}catch{return this.noConflict(e)}}async mergeAll(e,t){let o=await this.resolve(e,[t[0],t[1]]);for(let n=2;n<t.length&&o.success;n++){let r=_o.join(this.workspace,e);Ee.writeFileSync(r,o.mergedContent),o=await this.resolve(e,["HEAD",t[n]])}return o}noConflict(e){let t=_o.join(this.workspace,e);return{file:e,success:!0,hadConflicts:!1,mergedContent:Ee.existsSync(t)?Ee.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(`
281
+ `),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]+`
282
+ `:c+=n[r]+`
283
+ `,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(`
284
+ `),o=[],n=0,r=!0,i=[];for(;n<t.length;)if(t[n].startsWith("<<<<<<<")){let c="",u="",d=!1;for(n++;n<t.length&&!t[n].startsWith(">>>>>>>");)t[n].startsWith("=======")?d=!0:d?u+=t[n]+`
285
+ `:c+=t[n]+`
286
+ `,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(`
287
+ `);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(`
288
+ `),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(Je(),Yo)),{loadSettings:n}=await Promise.resolve().then(()=>(Q(),ve)),{getAccessToken:r}=await Promise.resolve().then(()=>(oe(),ge)),i=n(),c=await r()||process.env.MC_API_KEY||"";if(!c)return null;let u=new o({platformUrl:i.platformUrl,token:c,model:i.defaultModel||"capuchin-reason",workspace:this.workspace,mode:"auto",maxTurns:1,sandboxed:!0,webEnabled:!1,effort:"fast"}),d="";u.on("event",m=>{m.type==="streaming_chunk"&&(d+=m.content)});let p=["You are merging two versions of a code section that were edited by different agents.","Combine both changes intelligently, preserving the intent of each.","Return ONLY the merged code. No explanations, no markdown fences.","","=== Version A (ours) ===",e,"","=== Version B (theirs) ===",t,"","=== Merged result ==="].join(`
289
+ `);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{Ee.rmSync(e,{recursive:!0,force:!0})}catch{}}};Q();var ld=require("node:events"),Oa=y(require("node:crypto"),1);var hr=class extends ld.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:Oa.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.${Oa.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 yr=class extends ud.EventEmitter{static{l(this,"AgentOrchestrator")}opts;resolver;activeLoops=new Map;broker;constructor(e){super(),this.opts={maxConcurrency:5,timeoutMs:6e5,...e},this.resolver=new gr(e.workspace),this.broker=new hr,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+=`
290
+
291
+ `+r.inputTransform(o):o&&(i+=`
292
+
293
+ --- Previous stage output ---
294
+ ${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=Ma.join(this.opts.workspace,"..",`.mc-worktree-${e.id}`);try{return(0,qs.execSync)(`git worktree add -b ${t} ${o}`,{cwd:this.opts.workspace,stdio:"pipe"}),await this.executeAgent(e,o,t)}catch{return await this.executeAgent(e,this.opts.workspace,void 0)}}async runInline(e){return await this.executeAgent(e,this.opts.workspace,void 0)}async executeAgent(e,t,o){let n=J(),r=Date.now(),i="",c=0,u=0,d=[],p=new Se({platformUrl:n.platformUrl,token:this.opts.token,model:e.model||this.opts.model,workspace:t,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeLoops.set(e.id,p);let f=e.timeoutMs||this.opts.timeoutMs||6e5,m=setTimeout(()=>p.cancel(),f);p.on("event",g=>{switch(g.type){case"streaming_chunk":i+=g.content;break;case"tool_call_start":if(["write_file","edit_file","create_file","replace_file_content"].includes(g.name)){let h=g.args.path||g.args.file_path||g.args.target_file;h&&d.push(h)}this.broker.publish(`agent.${e.id}`,{from:e.id,type:"tool_call",data:{tool:g.name}});break;case"run_complete":c+=g.summary.tokensIn+g.summary.tokensOut,u+=g.summary.costUsd||0,this.broker.publish("orchestrator",{from:e.id,type:"complete",data:{tokensUsed:c,costUsd:u,filesChanged:[...new Set(d)]}});break}});try{let g=["You are running as a parallel subagent in an orchestrated multi-agent workflow.","","Your specific task:",e.prompt,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished concisely."].join(`
295
+ `);return await p.run(g),{taskId:e.id,status:"complete",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,worktreeBranch:o}}catch(g){return{taskId:e.id,status:"failed",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,error:g instanceof Error?g.message:String(g),worktreeBranch:o}}finally{clearTimeout(m),this.activeLoops.delete(e.id)}}async cherryPickFile(e,t){try{(0,qs.execSync)(`git checkout ${t} -- ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}cleanupWorktree(e){try{let t=Ma.join(this.opts.workspace,"..",`.mc-worktree-${e.replace(/^mc-agent-/,"")}`);(0,qs.execSync)(`git worktree remove --force ${t}`,{cwd:this.opts.workspace,stdio:"pipe"}),(0,qs.execSync)(`git branch -D ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}emitEvent(e,t,o){let n={type:e,taskId:t,data:o};this.emit("orchestrator",n)}};var Ep=y(require("node:fs"),1),Pr=require("node:child_process");W();X();Ce();var Dp=require("node:child_process"),co=y(require("node:fs"),1),Ar=y(require("node:path"),1),vp=require("node:events");Zs();X();var ab=1;function gp(s,e={}){return{jsonrpc:"2.0",id:ab++,method:s,params:e}}l(gp,"createRequest");function hp(s){return JSON.stringify(s)}l(hp,"serialize");function yp(s){try{let e=JSON.parse(s);return e.kind||e.id!==void 0||e.method?e:null}catch{return null}}l(yp,"parseMessage");function bp(s){return typeof s=="object"&&s!==null&&"kind"in s}l(bp,"isDaemonEvent");function wp(s){return typeof s=="object"&&s!==null&&"id"in s&&"jsonrpc"in s}l(wp,"isRpcResponse");var ao=class extends vp.EventEmitter{static{l(this,"DaemonConnection")}ws=null;daemonProcess=null;pending=new Map;platform;paths;opts;reconnectAttempts=0;_connected=!1;constructor(e={}){super(),this.platform=xe(),this.paths=T(),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=gp(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(hp(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(!co.existsSync(this.paths.pidFile))return null;let e=co.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 co.unlinkSync(this.paths.pidFile),null}}catch{return null}}async spawnDaemon(){Hn(Ar.dirname(this.paths.pidFile)),Hn(this.paths.logs);let e=Ar.join(this.paths.logs,`daemon-${Date.now()}.log`),t=co.createWriteStream(e,{flags:"a"}),o=this.opts.port;return this.daemonProcess=(0,Dp.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 kp(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 rt(`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 rt(`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=yp(e);if(t){if(wp(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(bp(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 kp(t);try{await this.connectWebSocket(e)}catch{}}};function kp(s){return new Promise(e=>setTimeout(e,s))}l(kp,"sleep");oe();wa();var Le=y(require("node:fs"),1),it=y(require("node:path"),1);X();function en(s){let e=T(),t=it.join(s,".monkeyscode","mcp.json"),o=it.join(e.config,"mcp.json"),n=Sp(o),r=Sp(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(en,"loadMcpConfig");function Sp(s){if(!Le.existsSync(s))return[];try{let e=Le.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:cb(n),autoStart:n.autoStart??!0}))}catch{return[]}}l(Sp,"loadConfigFile");function cb(s){return s.transport?s.transport:s.url?"sse":"stdio"}l(cb,"detectTransport");function nc(s,e,t,o){let n=it.join(s,".monkeyscode","mcp.json"),r=$p(n);r.servers[e]={command:t,args:o};let i=it.dirname(n);Le.mkdirSync(i,{recursive:!0}),Le.writeFileSync(n,JSON.stringify(r,null,2)+`
296
+ `)}l(nc,"addMcpServer");function xp(s,e){let t=it.join(s,".monkeyscode","mcp.json"),o=$p(t);return o.servers[e]?(delete o.servers[e],Le.writeFileSync(t,JSON.stringify(o,null,2)+`
297
+ `),!0):!1}l(xp,"removeMcpServer");function Cp(s){let e=T();return[{path:it.join(s,".monkeyscode","mcp.json"),source:"project",exists:Le.existsSync(it.join(s,".monkeyscode","mcp.json"))},{path:it.join(e.config,"mcp.json"),source:"global",exists:Le.existsSync(it.join(e.config,"mcp.json"))}]}l(Cp,"getMcpConfigPaths");function $p(s){if(!Le.existsSync(s))return{servers:{}};try{return JSON.parse(Le.readFileSync(s,"utf-8"))}catch{return{servers:{}}}}l($p,"loadConfigFileRaw");or();async function Or(s={}){let e=j(),t=U(e),o=e.ansi,n=xe(),r=T();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=_p(n.daemonBinary);i.push(d?{name:"Daemon binary",status:"ok",message:`${n.daemonBinary} found on PATH`}:{name:"Daemon binary",status:"warn",message:"Not found on PATH",fix:"The daemon will be downloaded on first run, or install manually"});try{let E=new ao({autoSpawn:!1,startTimeout:3e3});await E.connect(),E.disconnect(),i.push({name:"Daemon connection",status:"ok",message:"Connected"})}catch{i.push({name:"Daemon connection",status:"warn",message:"Not running (will auto-start)",fix:"The daemon starts automatically when you run a command"})}i.push(pa()?{name:"Authentication",status:"ok",message:"Logged in"}:{name:"Authentication",status:"warn",message:"Not logged in",fix:"Run: mc auth login"});let p=_p("git");i.push(p?{name:"Git",status:"ok",message:lb("git --version")||"found"}:{name:"Git",status:"error",message:"Not found",fix:"Install git: https://git-scm.com"});let m=await new Zo(tr(".")).checkAllProviders(),g=m.filter(E=>E.available);if(g.length>0)i.push({name:"Sandbox",status:"ok",message:`Available: ${g.map(E=>E.name).join(", ")}`});else{let E=n.os==="linux"?"Install bubblewrap: apt install bubblewrap":n.os==="macos"?"Install Docker Desktop":"Enable Windows Sandbox or install Docker Desktop";i.push({name:"Sandbox",status:"warn",message:"No sandbox provider available",fix:E})}for(let E of m)E.available||i.push({name:` \u2514 ${E.name}`,status:"warn",message:E.reason||"Not available"});let h=process.cwd(),b=en(h);b.length>0?i.push({name:"MCP servers",status:"ok",message:`${b.length} configured: ${b.map(E=>E.name).join(", ")}`}):i.push({name:"MCP servers",status:"ok",message:"None configured (optional)"});let k=Co(h);k.length>0?i.push({name:"Hooks",status:"ok",message:`${k.length} active: ${k.map(E=>E.event).join(", ")}`}):i.push({name:"Hooks",status:"ok",message:"None configured (optional)"});let S=Ep.existsSync(r.config);i.push(S?{name:"Config directory",status:"ok",message:r.config}:{name:"Config directory",status:"warn",message:`Not found: ${r.config}`,fix:"Will be created on first run"});let C=j();i.push({name:"Terminal",status:"ok",message:[C.trueColor?"24-bit color":C.color256?"256 color":C.color16?"16 color":"no color",C.unicode?"Unicode":"ASCII",C.interactive?"interactive":"non-interactive",`${C.columns}x${C.rows}`].join(" \xB7 ")});for(let E of i){let I=E.status==="ok"?t.success:E.status==="warn"?t.warning:t.error,ae=E.status==="ok"?o?a.green:K=>K:E.status==="warn"?o?a.yellow:K=>K:o?a.red:K=>K;console.log(` ${I} ${ae(`${E.name}`)}: ${E.message}`),E.fix&&console.log(o?a.dim(` Fix: ${E.fix}`):` Fix: ${E.fix}`)}console.log("");let _=i.filter(E=>E.status==="error").length,x=i.filter(E=>E.status==="warn").length;if(_>0?console.log(o?a.red(` ${_} error(s), ${x} warning(s)`):` ${_} error(s), ${x} warning(s)`):x>0?console.log(o?a.yellow(` All good! ${x} warning(s)`):` All good! ${x} warning(s)`):console.log(o?a.green(" \u2728 Everything looks great!"):" Everything looks great!"),console.log(""),s.fix){let E=i.filter(I=>I.status!=="ok"&&I.fix);if(E.length===0)console.log(o?a.green(" Nothing to fix!"):" Nothing to fix!");else{console.log(o?a.bold(" \u{1F527} Auto-fixing issues..."):" Auto-fixing issues..."),console.log("");for(let I of E){console.log(` \u2192 ${I.name}: ${I.fix}`);try{(0,Pr.execSync)(I.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(Or,"doctorCommand");function _p(s){try{return(0,Pr.execSync)(`which ${s} 2>/dev/null || where ${s} 2>nul`,{stdio:"pipe"}),!0}catch{return!1}}l(_p,"checkBinary");function lb(s){try{return(0,Pr.execSync)(s,{stdio:"pipe"}).toString().trim().split(`
298
+ `)[0]}catch{return null}}l(lb,"getVersion");Ra();nr();var rc=y(require("node:fs"),1),ic=require("node:child_process");function Ut(s){return s.replace(/\\/g,"/")}l(Ut,"normalizePath");var us=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:Ut(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}},ac=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:Ut(o.path)}))};return JSON.stringify(t)}formatEvent(e){return JSON.stringify({type:e.type,timestamp:e.timestamp,...e.data})}},cc=class{static{l(this,"DiffFormatter")}workspace;constructor(e){this.workspace=e}formatResult(e){try{let t=(0,ic.execSync)("git diff",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760});return t.trim()?t:(0,ic.execSync)("git diff --cached",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760})||"# No changes detected"}catch{return e.filesChanged.map(t=>`# ${t.action}: ${Ut(t.path)} (+${t.linesAdded} -${t.linesRemoved})`).join(`
299
+ `)}}},Mr=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(`| \`${Ut(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(`\`\`\`
300
+ ${e.error}
301
+ \`\`\``),t.push("")),t.join(`
302
+ `)}},lc=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=>Ut(i.path)).join(",")}`,`cost=${e.cost.toFixed(4)}`,`tokens=${e.tokens.total}`,`duration=${e.duration}`,`model=${e.model}`,`session-id=${e.sessionId}`];try{rc.appendFileSync(o,r.join(`
303
+ `)+`
304
+ `)}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=>Ut(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 Mr().formatResult(e);try{rc.appendFileSync(n,r+`
305
+ `)}catch{}}return!e.success&&e.error&&t.push(`::error::${e.error}`),t.join(`
306
+ `)}},uc=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=>Ut(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(`
307
+ `)}},ds=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:Ut(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:Ut(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 Fp(s,e={}){switch(s){case"json":return new us;case"jsonl":return new ac;case"diff":return new cc(e.workspace||".");case"markdown":return new Mr;case"github":return new lc;case"azure":return new uc;case"sarif":return new ds(e.findings,e.workspace);case"text":case"stream":default:return new us}}l(Fp,"createFormatter");function Tp(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(Tp,"createEmptyResult");function em(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(em,"mapMode");async function tm(s){let e=j(),t=s.prompt;!t&&!e.interactive&&(t=await _b());let o=await Ae();if(o||(console.error(a.red(" Error: Not authenticated. Run `mc auth login` first.")),process.exit(1)),s.model==="auto"){let r=J();s.model=r.defaultModel}let n=me();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(Up(),Lp));await r({jobId:s.resume,workspace:s.workspace}),await Qp(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Cc(),qp));await r(s.prompt,s.workspace,s.model)}else s.headless?await Cb(t,s,o,n):s.background?await $b(t,s):await Qp(t,s,o,n)}l(tm,"runCommand");async function Qp(s,e,t,o){let n=j(),r=J(),i=new vo({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new $o(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new It,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,g=new Set,h=0,b=0,k=0,S=0,C=null,_=!1;if(e.continueSession){let P=u.loadLatest(e.workspace);if(P){d=P,S=P.turnCount;for(let L of P.stats.filesChanged)m.add(L);i.printSuccess(`Resumed session ${P.id.substring(0,8)} (${P.turnCount} turns, ${P.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 P=a.dim,L=a.green,Y=a.yellow,F=a.hex("#6B8DD6"),D=a.bold(e.model),w=P(e.mode);console.log(` ${F("Model:")} ${D} ${P("\xB7")} ${w} mode`);let v=(()=>{try{return(0,Ye.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),$=(()=>{try{return(0,Ye.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),O=v?` ${P("\xB7")} ${P("branch:")} ${v}${$?Y(" \u25CF"):L(" \u2713")}`:"";console.log(` ${F("Path:")} ${P(e.workspace)}${O}`);let R=e.sandbox?L("\u{1F512} on"):Y("off"),Z=e.permissionMode!=="default"?` ${P("\xB7")} ${P("perm:")} ${e.permissionMode}`:"",A=e.autoApprove?` ${P("\xB7")} ${Y("auto-approve")}`:e.approveForMe?` ${P("\xB7")} ${L("smart-approve")}`:"";console.log(` ${F("Sandbox:")} ${R}${Z}${A}`);let Yt=c.getHooks(),Cs=Yt.length>0?`${Yt.length} hooks`:P("none"),Go=0;try{let{listAllSkills:We}=await Promise.resolve().then(()=>(ir(),_a));Go=We(e.workspace).length}catch{}let li=Go>0?`${Go} skills`:P("none");console.log(` ${F("Plugins:")} ${Cs} ${P("\xB7")} ${li}`);let ui=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${F("Engine:")} ${P(ui)}`)}console.log("");let x=i.getStatusBar({model:e.model,mode:e.mode,branch:(()=>{try{return(0,Ye.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),dirty:(()=>{try{return(0,Ye.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});x.start(),console.log(a.dim(" Type a prompt to start. /help for commands, /exit to quit, Ctrl+C to cancel.")),await c.fire("SessionStart",{workspace:e.workspace,data:{model:e.model,mode:e.mode}});let E=["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"],I=Zp.createInterface({input:process.stdin,output:process.stdout,terminal:!0,prompt:(()=>{let P=U(n);return n.ansi?`
308
+ ${a.hex("#6B8DD6")(P.prompt)} `:`
309
+ ${P.prompt} `})(),historySize:200,completer:l(P=>{if(P.startsWith("/")){let L=P.slice(1).toLowerCase(),Y=E.filter(F=>F.startsWith(L)).map(F=>`/${F}`);return[Y.length?Y:E.map(F=>`/${F}`),P]}if(P.startsWith("/context ")){let L=P.slice(9);try{let Y=V.dirname(V.resolve(e.workspace,L)),F=V.basename(L);return[M.readdirSync(Y).filter(v=>v.startsWith(F)).map(v=>`/context ${L.replace(F,"")}${v}`),P]}catch{return[[],P]}}return[[],P]},"completer")});new lr().wire(I);let K=null,fe=null,je=!1,pt=null,bo=new mr({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),Ct=null;try{let{MessageBroker:P}=await Promise.resolve().then(()=>(an(),Br));t&&r.platformUrl&&(Ct=new P(r.platformUrl,t,p))}catch{}let xs=l(async()=>{if(Ct)try{let P=await Ct.pollMessages();if(P&&P.length>0)for(let L of P)i.renderMessageCard({from:L.from||L.senderId||"unknown",content:L.content||L.message||"",timestamp:L.timestamp?new Date(L.timestamp):new Date})}catch{}},"pollAndRenderMessages"),$t=l(async P=>{d||(d=u.create(e.workspace,e.model,e.mode)),u.addMessage(d,"user",P),S++,x.update({turn:S,busy:!0,activity:"thinking..."});let L=new Se({platformUrl:r.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:em(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});K=L;let Y="";L.on("event",D=>{switch(D.type){case"streaming_chunk":Y+=D.content,process.stdout.write(D.content);break;case"streaming_end":if(Y.trim()){let v=Y.split(`
310
+ `).length;process.stdout.write(`\x1B[${v}A\x1B[J`),console.log(qn(Y))}else console.log("");Y="";break;case"tool_call_start":i.printToolCallStart(D.name,D.args),D.name==="file_read"&&D.args?.file_path&&g.add(String(D.args.file_path)),["file_edit","file_write","file_create"].includes(D.name)&&D.args?.file_path&&m.add(String(D.args.file_path));break;case"tool_call_result":i.printToolCallResult(D.name,D.result);break;case"ask_user":console.log(a.cyan(`
311
+ \u{1F914} ${D.question}`)),I.question(a.dim(" Answer: "),v=>{L.resolveUserInput(v)});break;case"todo_update":i.printTodoList(D.todos);break;case"run_complete":Eb(D.summary,i),h+=D.summary.tokensIn,b+=D.summary.tokensOut,k+=D.summary.tokensThinking||0,C=L.state.runId;for(let v of D.summary.filesModified)m.add(v);if(x.update({tokensIn:h,tokensOut:b,cost:Gs(e.model,h,b,k),turn:S,busy:!1,activity:""}),e.maxCost&&e.maxCost>0){let v=Gs(e.model,h,b,k),$=v/e.maxCost;$>=1?(console.log(""),console.log(a.red(` \u{1F6AB} Session budget exceeded ($${v.toFixed(2)}/$${e.maxCost.toFixed(2)}). Stopping.`)),console.log(a.dim(" Use --max-cost to increase the budget.")),console.log(""),_=!0):$>=.8&&console.log(a.yellow(` \u26A0\uFE0F 80% of session budget used ($${v.toFixed(2)}/$${e.maxCost.toFixed(2)})`))}let w=L.getCheckpoints();w.size>0&&ed(L.state.runId,P,e.workspace,w),d&&u.updateStats(d,D.summary.tokensIn+D.summary.tokensOut,0,D.summary.filesModified);break;case"context_compacted":i.printSuccess(`Context auto-compacted: ${D.elided} tool result${D.elided===1?"":"s"} summarized (${Math.round(D.savedTokens/1e3)}K tokens saved, now ${Math.round(D.contextUsed/D.contextWindow*100)}% full)`);break;case"run_error":i.printError(D.error);break}});let F=[];L.on("run_complete",D=>{D?.summary?.filesModified&&(F=D.summary.filesModified)});try{await L.run(P)}catch(D){i.printError(D instanceof Error?D.message:String(D))}if(F.length>0&&Ct)try{let{notifyAffectedSessions:D}=await Promise.resolve().then(()=>(Xp(),Yp));await D(Ct,F,p)}catch{}K=null},"executePrompt");s&&await $t(s),await xs(),I.prompt(),I.on("line",async P=>{let L=P.trim();if(_){I.close();return}if(!pt&&(L==="<<EOF"||L.endsWith("<<EOF"))){let Y=L.replace(/<<EOF$/,"").trim();pt=Y?[Y]:[],I.setPrompt(a.dim(" ... ")),I.prompt();return}if(pt!==null){if(L==="EOF"){let Y=pt.join(`
312
+ `);pt=null,I.setPrompt(n.emoji?`
313
+ \u{1F435} > `:`
314
+ > `),Y.trim()&&await $t(Y),I.prompt();return}pt.push(P),I.setPrompt(a.dim(" ... ")),I.prompt();return}if(L.endsWith("\\")){pt=[L.slice(0,-1)],I.setPrompt(a.dim(" ... ")),I.prompt();return}if(!L){I.prompt();return}if(L.startsWith("/")){let[Y,...F]=L.slice(1).split(" "),D=F.join(" ");switch(Y){case"exit":case"quit":case"q":c.fire("Stop",{workspace:e.workspace,data:{}}),x.stop(),I.close();return;case"clear":case"cls":console.clear();break;case"model":D?(e.model=D,i.printSuccess(`Model changed to: ${D}`),x.update({model:D})):console.log(` Current model: ${e.model}`);break;case"mode":["plan","fast","thinking"].includes(D)?(e.mode=D,i.printSuccess(`Mode changed to: ${D}`)):i.printError("Valid modes: plan, fast, thinking");break;case"diff":try{let w=(0,Ye.execSync)("git diff",{cwd:e.workspace,encoding:"utf8"});w.trim()?(console.log(""),console.log(w)):console.log(a.dim(" No uncommitted changes."))}catch{i.printError("Failed to run git diff (is this a git repository?)")}break;case"undo":{let w=td();if(w.length===0){i.printError("Nothing to undo \u2014 no checkpoints found.");break}let v=w[0];try{let $=od(v.runId);i.printSuccess(`Reverted ${$.length} file(s):`);for(let O of $)console.log(` \u21A9 ${O}`)}catch($){i.printError($ instanceof Error?$.message:"Undo failed")}break}case"commit":{try{(0,Ye.execSync)("git add -A",{cwd:e.workspace,stdio:"pipe"});let w=D||`mc: agent changes (${m.size} files)`,$=(0,Ye.execSync)(`git commit -m "${w.replace(/"/g,'\\"')}"`,{cwd:e.workspace,encoding:"utf8",stdio:"pipe"}).match(/\[[\w-]+\s+([a-f0-9]+)\]/),O=$?$[1]:"???";i.printSuccess(`Committed: ${O} \u2014 ${w}`)}catch(w){i.printError(w instanceof Error?w.message:"Commit failed")}break}case"files":if(m.size===0&&g.size===0)console.log(a.dim(" No files accessed in this session."));else{if(console.log(""),m.size>0){console.log(` Files modified (${m.size}):`);for(let w of m)console.log(` \u270F\uFE0F ${V.relative(e.workspace,w)||w}`)}if(g.size>0){console.log(` Files read (${g.size}):`);for(let w of[...g].slice(0,20))console.log(` \u{1F4D6} ${V.relative(e.workspace,w)||w}`);g.size>20&&console.log(a.dim(` ... and ${g.size-20} more`))}console.log("")}break;case"cost":{let w=sr(e.model),v=w?h/1e6*w.costInputPerM:0,$=w?b/1e6*w.costOutputPerM:0,O=w?k/1e6*w.costOutputPerM:0,R=v+$+O;if(console.log(""),console.log(" \u{1F4B0} Session Cost"),console.log(` ${"\u2500".repeat(36)}`),console.log(` Model: ${w?.displayName||e.model}`),console.log(` Input: ${h.toLocaleString()} tokens ($${v.toFixed(2)})`),console.log(` Output: ${b.toLocaleString()} tokens ($${$.toFixed(2)})`),k>0&&console.log(` Thinking: ${k.toLocaleString()} tokens ($${O.toFixed(2)})`),console.log(` Total: $${R.toFixed(2)}`),e.maxCost&&e.maxCost>0){let Z=Math.max(0,e.maxCost-R),A=Math.round((1-R/e.maxCost)*100);console.log(` Budget: $${e.maxCost.toFixed(2)} (${A}% remaining)`)}console.log(` Turns: ${S}`),console.log(` ${"\u2500".repeat(36)}`),console.log("");break}case"context":case"ctx":if(D){let w=V.resolve(e.workspace,D);try{let $=require("node:fs").readFileSync(w,"utf8").split(`
315
+ `).length;g.add(w),i.printSuccess(`Added ${D} to context (${$} lines). Mention it in your next prompt.`)}catch{i.printError(`File not found: ${D}`)}}else{let w=cr(e.model),v=K?.getContextStats();if(console.log(""),console.log(" \u{1F4CA} Context Summary"),console.log(` ${"\u2500".repeat(40)}`),console.log(` Turns: ${S}`),console.log(` Tokens in: ${h.toLocaleString()}`),console.log(` Tokens out: ${b.toLocaleString()}`),console.log(` Files read: ${g.size}`),console.log(` Files edited: ${m.size}`),console.log(` Model: ${e.model}`),console.log(` Context window: ${(w/1e3).toFixed(0)}K tokens`),v){let $=v.pct,O=30,R=Math.round($/100*O),Z=O-R,A=$>=80?a.red:$>=60?a.yellow:a.green;console.log(` Context used: ${A(`${$}%`)} ${A("\u2588".repeat(R))}${a.dim("\u2591".repeat(Z))}`),console.log(` Messages: ${v.messageCount}`),console.log(` Auto-compact: ${$>=85?a.yellow("will trigger"):a.green("standby")}`)}console.log(` ${"\u2500".repeat(40)}`),console.log("")}break;case"compact":{if(!K){console.log(a.dim(" No active conversation to compact. Run a prompt first."));break}let w=D.replace(/^["']|["']$/g,"").trim(),v=K.getContextStats();if(!w&&v.pct<50){console.log(a.dim(` Context is only ${v.pct}% full \u2014 compaction not needed.`)),console.log(a.dim(' Use /compact "retain X" to force compaction with specific focus.'));break}if(w){i.printStatus(`Compacting with focus: "${w}"`);let $=K.manualCompact(2);if($.elided>0){let O=K.getContextStats(),R=Math.round($.savedTokens/1e3);i.printSuccess(`Compacted: ${$.elided} tool result${$.elided===1?"":"s"} summarized (${R}K tokens saved, ${v.pct}% \u2192 ${O.pct}%)`),console.log(a.dim(` Retained focus: "${w}"`))}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}else{let $=K.manualCompact();if($.elided>0){let O=K.getContextStats(),R=Math.round($.savedTokens/1e3);i.printSuccess(`Compacted: ${$.elided} tool result${$.elided===1?"":"s"} summarized (${R}K tokens saved, ${v.pct}% \u2192 ${O.pct}%)`)}else console.log(a.dim(" Nothing to compact \u2014 all tool results are already summarized or recent."))}break}case"doctor":await Or();break;case"permissions":{let w=D.split(" ")[0]?.toLowerCase()||"show",v=V.join(e.workspace,".monkeyscode","permissions.json");if(w==="edit"){let $=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!M.existsSync(v))console.log(a.dim(" No permissions.json. Run /init to generate one."));else try{(0,Ye.execSync)(`${$} "${v}"`,{stdio:"inherit"}),i.printSuccess("Permissions saved.")}catch{i.printError(`Failed to open editor: ${$}`)}}else if(w==="reset")M.existsSync(v)?(M.unlinkSync(v),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(", ")}`),M.existsSync(v))try{let $=JSON.parse(M.readFileSync(v,"utf8"));console.log(""),console.log(a.dim(` \u{1F4C4} ${V.relative(e.workspace,v)}`)),$.allow?.length&&console.log(` Allow rules: ${$.allow.length} rules`),$.deny?.length&&console.log(` Deny rules: ${$.deny.length} rules`),$.cost?.max_per_run_usd&&console.log(` Cost limit: $${$.cost.max_per_run_usd}`),$.sandbox?.enabled&&console.log(` Sandbox paths: ${$.sandbox.writable_paths?.join(", ")||"all"}`)}catch{}else console.log(a.dim(" No project permissions.json. Run /init to generate."));console.log("")}break}case"fork":{let w=D.trim()||"Continue working on the current task in the background";await bo.spawn(w);break}case"sessions":{let w=u.list();if(w.length===0)console.log(a.dim(" No saved sessions."));else{console.log(""),console.log(a.bold(" Recent Sessions:"));for(let v of w.slice(0,10)){let $=a.hex("#6B8DD6")(v.id.substring(0,8)),O=Tb(v.lastActive);console.log(` ${$} ${v.preview.substring(0,50).padEnd(52)} ${a.dim(O)}`)}console.log("")}break}case"resume":case"continue":{let w=D.trim(),v=w?u.load(w):u.loadLatest(e.workspace);if(!v)i.printError(w?`Session "${w}" not found.`:"No sessions to resume.");else{d=v,S=v.turnCount;for(let $ of v.stats.filesChanged)m.add($);i.printSuccess(`Resumed session ${v.id.substring(0,8)} (${v.turnCount} turns, ${v.stats.tokensUsed.toLocaleString()} tokens)`)}break}case"goal":{let w=D.trim().replace(/^["']|["']$/g,"");if(!w&&w!=="status"&&w!=="cancel"){i.printError('Usage: /goal "implement feature X with tests" | /goal status | /goal cancel');break}if(w==="status"){if(fe){let v=fe.getProgress();console.log(a.dim(` Goal: iteration ${v.iteration}/${v.maxIterations}, ${v.totalTokens.toLocaleString()} tokens, $${v.totalCost.toFixed(4)}`))}else console.log(a.dim(" No active goal."));break}if(w==="cancel"){fe?(fe.cancel(),i.printSuccess("Goal cancelled.")):console.log(a.dim(" No active goal."));break}fe=new pr({goal:w,workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),await fe.run(),fe=null;break}case"subtask":case"sub":{let w=D.trim();if(w==="status")bo.printStatus();else if(w.startsWith("cancel "))bo.cancel(w.slice(7).trim());else if(w){let v=w.replace(/^["']|["']$/g,"");await bo.spawn(v)}else i.printError('Usage: /subtask "task description" | /subtask status | /subtask cancel <id>');break}case"delegate":case"del":{let w=D.trim();if(!w){i.printError('Usage: /delegate "task 1" "task 2" ["task 3" ...]'),console.log(a.dim(" Spawns parallel agents for each task, merges results."));break}let v=w.match(/"([^"]+)"/g)?.map(R=>R.replace(/"/g,""))||[w];if(v.length<1){i.printError("Provide at least one task in quotes.");break}console.log(a.cyan(` \u26A1 Delegating ${v.length} task(s) to parallel agents...`));for(let R=0;R<v.length;R++)console.log(a.dim(` ${R+1}. "${v[R]}"`));console.log("");let $=new yr({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 O=v.map((R,Z)=>({id:`delegate-${Z+1}`,prompt:R,workspace:e.workspace,parentId:"repl",dependencies:[],status:"pending"}));try{let R=await $.fanOut(O),Z=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(A=>A.status==="complete").length))}`),console.log(` Failed: ${a.red(String(R.filter(A=>A.status==="failed").length))}`),console.log(` Files: ${Z.mergedFiles.length}`),console.log(` Conflicts: ${Z.conflicts.length}`),console.log(` Tokens: ${Z.totalTokens.toLocaleString()}`),console.log(` Cost: $${Z.totalCost.toFixed(4)}`),console.log(` Duration: ${(Z.totalDurationMs/1e3).toFixed(1)}s`),console.log(` ${"\u2500".repeat(50)}`),console.log("")}catch(R){i.printError(`Delegation failed: ${R.message}`)}break}case"search":D?await $t(`Search the web for: ${D.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":D?await $t(`Look up documentation for: ${D}`):console.log(a.dim(" Usage: /docs express routing \u2014 looks up documentation for a topic."));break;case"review":{let w="all changes in this session",v="git diff";D==="staged"?(v="git diff --cached",w="staged changes"):D&&(v=`git diff -- ${D}`,w=`changes in ${D}`);try{let $=(0,Ye.execSync)(v,{cwd:e.workspace,encoding:"utf8"});$.trim()?(console.log(a.bold(`
316
+ \u{1F50D} Reviewing ${w}...`)),await $t(`Review the following code changes for bugs, security issues, and code quality. Provide severity ratings (HIGH/MEDIUM/LOW) for each finding.
317
+
318
+ \`\`\`diff
319
+ ${$}
320
+ \`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let w=V.join(e.workspace,".monkeyscode"),v=V.join(w,"rules.md"),$=V.join(w,"permissions.json"),O=V.join(w,"skills"),R=V.join(w,"hooks");M.mkdirSync(w,{recursive:!0});let Z=[];if(!M.existsSync(v)){let A=["# Project Conventions",""],Yt=V.join(e.workspace,"package.json"),Cs=V.join(e.workspace,"Cargo.toml"),Go=V.join(e.workspace,"pyproject.toml"),li=V.join(e.workspace,"tsconfig.json"),ui=V.join(e.workspace,"go.mod");if(M.existsSync(Yt))try{let We=JSON.parse(M.readFileSync(Yt,"utf8"));A.push(`## Language: ${We.type==="module"?"TypeScript/ESM":"JavaScript/CJS"}`),We.scripts?.test&&A.push(`- Test command: \`${We.scripts.test}\``),We.scripts?.lint&&A.push(`- Lint command: \`${We.scripts.lint}\``),We.scripts?.build&&A.push(`- Build command: \`${We.scripts.build}\``),We.dependencies?.react&&A.push("- Framework: React"),We.dependencies?.next&&A.push("- Framework: Next.js"),We.dependencies?.express&&A.push("- Server: Express"),A.push("")}catch{}M.existsSync(li)&&(A.push("## TypeScript"),A.push("- Use strict TypeScript with explicit types"),A.push("- Prefer `interface` over `type` for object shapes"),A.push("")),M.existsSync(Cs)&&(A.push("## Language: Rust"),A.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),A.push("")),M.existsSync(Go)&&(A.push("## Language: Python"),A.push("- Follow PEP 8 conventions"),A.push("")),M.existsSync(ui)&&(A.push("## Language: Go"),A.push("- Follow Go conventions (gofmt, error wrapping)"),A.push("")),A.push("## Style"),A.push("- Keep functions small and focused"),A.push("- Write clear error messages"),A.push("- Add JSDoc/docstrings for public APIs"),A.push(""),A.push("## Testing"),A.push("- Write tests for all new functionality"),A.push("- Use descriptive test names"),A.push(""),M.writeFileSync(v,A.join(`
321
+ `),"utf8"),Z.push("rules.md")}if(!M.existsSync($)){let A="",Yt=V.join(e.workspace,"package.json");if(M.existsSync(Yt))try{JSON.parse(M.readFileSync(Yt,"utf8")).scripts?.test&&(A="npm test")}catch{}!A&&M.existsSync(V.join(e.workspace,"Cargo.toml"))&&(A="cargo test"),!A&&M.existsSync(V.join(e.workspace,"go.mod"))&&(A="go test ./..."),!A&&M.existsSync(V.join(e.workspace,"pyproject.toml"))&&(A="pytest");let Cs={mode:"default",allow:["Bash(git status*)","Bash(git diff*)","Bash(git log*)"],deny:["Bash(rm -rf /)","Bash(sudo *)","/Bash\\(curl.*\\|.*sh\\)/"],smartApprove:A?[`Bash(${A}*)`]:[],sandbox:{enabled:!0,writable_paths:["src/","tests/","test/","docs/","lib/"],blocked_commands:["rm -rf /","sudo","curl | sh","chmod 777"]},cost:{max_per_run_usd:10,warn_at_usd:5}};M.writeFileSync($,JSON.stringify(Cs,null,2)+`
322
+ `,"utf8"),Z.push("permissions.json")}if(M.existsSync(O)||(M.mkdirSync(O,{recursive:!0}),M.writeFileSync(V.join(O,"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(`
323
+ `),"utf8"),Z.push("skills/")),!M.existsSync(R)){M.mkdirSync(R,{recursive:!0});let A=V.join(R,"pre-write-lint.sh.example");M.writeFileSync(A,["#!/bin/bash","# Example PreToolUse hook: lint before file writes.","# Remove .example extension to enable.","#","# Env vars: MC_TOOL_NAME, MC_TOOL_ARGS (JSON), MC_WORKSPACE, MC_SESSION_ID","# Exit 0=allow, 1=deny, 2=deny+message on stderr","",'if [[ "$MC_TOOL_NAME" == "edit_file" || "$MC_TOOL_NAME" == "create_file" ]]; then',` FILE=$(echo "$MC_TOOL_ARGS" | jq -r '.path // .file_path // empty')`,' if [[ "$FILE" == *.ts && -f "$FILE" ]]; then',' npx eslint "$FILE" --quiet 2>/dev/null || true'," fi","fi","","exit 0",""].join(`
324
+ `),"utf8");try{M.chmodSync(A,493)}catch{}Z.push("hooks/")}Z.length>0?(i.printSuccess(`Initialized .monkeyscode/ with: ${Z.join(", ")}`),console.log(a.dim(" Edit with: /memory, /permissions, /skill"))):i.printWarning("Project already initialized. Use /memory, /permissions, /skill to manage.");break}case"memory":{let w=V.join(e.workspace,".monkeyscode","rules.md"),v=D.split(" ")[0]?.toLowerCase(),$=D.slice(v?.length||0).trim();if(v==="add"&&$){let O=$.replace(/^["']|["']$/g,"");M.mkdirSync(V.dirname(w),{recursive:!0});let R=M.existsSync(w)?M.readFileSync(w,"utf8"):`# Project Conventions
325
+ `;M.writeFileSync(w,R.trimEnd()+`
326
+ - `+O+`
327
+ `,"utf8"),i.printSuccess(`Added rule: ${O}`)}else if(v==="show"||!v)if(M.existsSync(w)){let O=M.readFileSync(w,"utf8");console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules")),console.log(a.dim(` ${w}`)),console.log(a.dim(" "+"\u2500".repeat(40)));for(let R of O.split(`
328
+ `))console.log(` ${R}`);console.log("")}else console.log(a.dim(" No rules file found. Run /init to generate one."));else if(v==="edit"){let O=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!M.existsSync(w))console.log(a.dim(" No rules file. Run /init first."));else try{(0,Ye.execSync)(`${O} "${w}"`,{stdio:"inherit"}),i.printSuccess("Rules file saved.")}catch{i.printError(`Failed to open editor: ${O}`)}}else console.log(a.dim(' Usage: /memory show | /memory add "rule" | /memory edit'));break}case"skill":case"skills":{let w=D.split(" ")[0]?.toLowerCase(),v=D.slice(w?.length||0).trim();if(w==="create"&&v){let $=v.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),O=V.join(e.workspace,".monkeyscode","skills",$),R=V.join(O,"skill.md");M.existsSync(R)?console.log(a.yellow(` Skill "${$}" already exists.`)):(M.mkdirSync(O,{recursive:!0}),M.writeFileSync(R,["---",`name: ${v}`,`description: Custom skill for ${v}`,"trigger: always","priority: 50","enabled: true","---","",`# ${v}`,"","Add your skill instructions here. These will be injected into the agent's context.",""].join(`
329
+ `),"utf8"),i.printSuccess(`Created skill: ${V.relative(e.workspace,R)}`),console.log(a.dim(" Edit the file to add your instructions.")))}else try{let{listAllSkills:$}=await Promise.resolve().then(()=>(ir(),_a)),O=$(e.workspace);if(O.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 O){let Z=R.enabled?a.green("\u25CF"):a.dim("\u25CB"),A=R.source==="project"?a.cyan("proj"):a.dim("glob");console.log(` ${Z} ${a.bold(R.name.padEnd(20))} ${A} P:${R.priority} ${a.dim(R.description.slice(0,40))}`)}console.log("")}}catch($){i.printError(`Failed to list skills: ${$ instanceof Error?$.message:$}`)}break}case"hooks":case"hook":{let w=D.split(" ")[0]?.toLowerCase(),v=D.slice(w?.length||0).trim();if(w==="create"&&v){let $=v.replace(/[^a-z0-9-_]/gi,"-").toLowerCase(),O=V.join(e.workspace,".monkeyscode","hooks",`${$}.sh`);if(M.existsSync(O))console.log(a.yellow(` Hook "${$}" already exists.`));else{M.mkdirSync(V.dirname(O),{recursive:!0}),M.writeFileSync(O,["#!/bin/bash",`# Hook: ${v}`,"#","# 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(`
330
+ `),"utf8");try{M.chmodSync(O,493)}catch{}i.printSuccess(`Created hook: ${V.relative(e.workspace,O)}`)}}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 O of $){let R=a.cyan(O.event||"PreToolUse"),Z=a.bold(O.name||O.path||"hook");console.log(` ${R.padEnd(20)} ${Z}`)}console.log("")}}break}case"plan":e.mode="plan",i.printSuccess("Switched to plan mode \u2014 agent will research and propose without editing.");break;case"ask":e.mode="plan",i.printSuccess("Switched to ask mode \u2014 read-only Q&A about the codebase (no edits, no commands).");break;case"cloud":{console.log(a.dim(" \u2601\uFE0F Submitting current task to cloud..."));try{let{submitBackgroundJob:w}=await Promise.resolve().then(()=>(tn(),yc)),v=e.prompt||"(continue session)",$=K?.getConversationHistory?.()||[];await w({prompt:v.substring(0,2e3),workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:!0,autoCommit:!0,autoPR:!1,maxCost:e.maxCost,timeout:e.timeout,conversationHistory:$.length>0?$:void 0})}catch(w){console.error(a.red(` \u274C Cloud submission failed: ${w instanceof Error?w.message:w}`))}break}case"message":{let w=D.match(/^(\S+)\s+"?([^"]+)"?$/);if(!w){console.log(a.yellow(' Usage: /message <session-id> "your message"'));break}try{let{MessageBroker:v}=await Promise.resolve().then(()=>(an(),Br)),$=(await Promise.resolve().then(()=>(Q(),ve))).loadSettings(),O=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth(),Z=await new v($.platformUrl,O?.access_token||"",p).sendMessage(w[1],w[2]);Z.success?console.log(a.green(` \u{1F4E8} Message sent to ${w[1]}`)):console.error(a.red(` \u274C Send failed: ${Z.error}`))}catch(v){console.error(a.red(` \u274C Messaging error: ${v instanceof Error?v.message:v}`))}break}case"broadcast":{let w=D.replace(/^"/,"").replace(/"$/,"").trim();if(!w){console.log(a.yellow(' Usage: /broadcast "your message to all sessions"'));break}try{let{MessageBroker:v}=await Promise.resolve().then(()=>(an(),Br)),$=(await Promise.resolve().then(()=>(Q(),ve))).loadSettings(),O=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth(),Z=await new v($.platformUrl,O?.access_token||"",p).broadcast(w);Z.success?console.log(a.green(" \u{1F4E2} Broadcast sent to all active sessions")):console.error(a.red(` \u274C Broadcast failed: ${Z.error}`))}catch(v){console.error(a.red(` \u274C Messaging error: ${v instanceof Error?v.message:v}`))}break}case"bug":case"feedback":{let w=process.platform,v=process.version,$=K?.getContextStats();console.log(""),console.log(a.bold(" \u{1F41B} Bug Report Context")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Platform: ${w} (${process.arch})`),console.log(` Node: ${v}`),console.log(` Model: ${e.model}`),console.log(` Mode: ${e.mode}`),console.log(` Turns: ${S}`),console.log(` Tokens: ${(h+b).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":{je=!je,je?(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.")),I.setPrompt(n.emoji?`
331
+ \u{1F435} [I]> `:`
332
+ [I]> `),console.log("")):(i.printSuccess("Vim mode disabled"),I.setPrompt(n.emoji?`
333
+ \u{1F435} > `:`
334
+ > `));break}case"help":case"h":case"?":Fb();break;case"logout":ca(),i.printSuccess("Logged out."),process.exit(0);break;default:i.printError(`Unknown command: /${Y}. Type /help for available commands.`)}I.prompt();return}await $t(L),await xs(),I.prompt()});let Tn=l(()=>{let P=Date.now()-f,L=Math.floor(P/6e4),Y=Math.floor(P%6e4/1e3),F=L>0?`${L}m ${Y}s`:`${Y}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: ${F}`)),console.log(a.dim(` Turns: ${S}`)),console.log(a.dim(` Tokens: ${(h+b).toLocaleString()}`)),m.size>0){console.log(a.dim(` Files changed: ${m.size}`));for(let D of m)console.log(a.dim(` \u270F\uFE0F ${V.relative(e.workspace,D)||D}`))}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");I.on("close",()=>{c.fire("Stop",{workspace:e.workspace,data:{}}),Tn(),process.exit(0)}),I.on("SIGINT",()=>{K?(console.log(`
335
+ Cancelling current run...`),K.cancel()):(c.fire("Stop",{workspace:e.workspace,data:{}}),I.close())}),await new Promise(P=>{I.on("close",P)})}l(Qp,"runInteractive");async function Cb(s,e,t,o){s||(process.stderr.write(`Error: No prompt provided. Use -p "your prompt" or pipe via stdin.
336
+ `),process.exit(4)),t||(process.stderr.write("Error: Not authenticated. Run `mc auth login` or set MONKEYSCODE_API_KEY.\n"),process.exit(3));let m=J(),g=Date.now(),h=`headless-${Date.now().toString(36)}`,b="",k=!1,S=!1,C=e.output,_=Fp(C,{workspace:e.workspace}),x=Tp(e.model,h),E=[],I=[],ae=0,K=0,fe=0,je=0,pt=process.env.CI==="true"||process.env.CI==="1"||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI;pt&&!e.sandbox&&e.permissionMode!=="bypassPermissions"&&process.stderr.write(`[headless] CI environment detected \u2014 sandbox=auto
337
+ `);let bo=new $o(e.workspace,{enabled:!0,timeoutMs:1e4});await bo.fire("HeadlessStart",{workspace:e.workspace,data:{prompt:s,model:e.model}});let Ct=e.timeout||3e5,xs=setTimeout(()=>{S=!0,process.stderr.write(`
338
+ [headless] Timeout after ${Ct}ms. Stopping gracefully.
339
+ `)},Ct),$t=l(()=>{k=!0,process.stderr.write(`
340
+ [headless] SIGINT received. Stopping.
341
+ `)},"sigintHandler");process.on("SIGINT",$t);let Tn=await import("node:crypto"),P=new Map;try{let F=(0,Ye.execSync)("git ls-files -m",{cwd:e.workspace,encoding:"utf8"}).trim().split(`
342
+ `).filter(Boolean);for(let D of F)try{let w=M.readFileSync(V.join(e.workspace,D));P.set(D,Tn.createHash("sha256").update(w).digest("hex"))}catch{}}catch{}let L=new Se({platformUrl:m.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:em(e.mode),maxTurns:m.maxTurns,sandboxed:e.sandbox||pt,webEnabled:m.webEnabled&&!e.offline,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});L.on("event",F=>{switch(F.type){case"streaming_chunk":if(b+=F.content,C==="stream"&&process.stdout.write(F.content),C==="jsonl"&&_.formatEvent){let D=_.formatEvent({type:"chunk",timestamp:Date.now(),data:{content:F.content}});D&&process.stdout.write(D+`
343
+ `)}break;case"tool_call_start":if(ae=Date.now(),e.mode==="plan"&&["file_edit","file_write","file_create","bash","file_delete"].includes(F.name)){process.stderr.write(`[headless] Plan mode: blocked write tool "${F.name}"
344
+ `);break}if(process.stderr.write(`[tool] ${F.name}(${JSON.stringify(F.args).substring(0,100)})
345
+ `),["file_edit","file_write","file_create"].includes(F.name)&&F.args?.file_path&&I.push({path:String(F.args.file_path),action:F.name==="file_create"?"created":"modified",linesAdded:0,linesRemoved:0}),C==="jsonl"&&_.formatEvent){let D=_.formatEvent({type:"tool_start",timestamp:Date.now(),data:{tool:F.name,args:F.args}});D&&process.stdout.write(D+`
346
+ `)}break;case"tool_call_result":if(E.push({tool:F.name,args:{},duration:Date.now()-ae,result:typeof F.result=="string"?F.result.substring(0,200):void 0}),C==="jsonl"&&_.formatEvent){let D=_.formatEvent({type:"tool_result",timestamp:Date.now(),data:{tool:F.name,duration:Date.now()-ae,result:typeof F.result=="string"?F.result.substring(0,200):""}});D&&process.stdout.write(D+`
347
+ `)}break;case"ask_user":process.stderr.write(`[headless] Input prompt skipped (headless mode): ${F.question}
348
+ `),L.resolveUserInput("");break;case"run_complete":K+=F.summary.tokensIn,fe+=F.summary.tokensOut,je+=F.summary.tokensThinking||0;for(let D of F.summary.filesModified)I.find(v=>v.path===D)||I.push({path:D,action:"modified",linesAdded:0,linesRemoved:0});process.stderr.write(`[headless] Run complete: ${F.summary.filesModified.length} files, ${F.summary.tokensIn+F.summary.tokensOut} tokens
349
+ `);break;case"run_error":if(process.stderr.write(`[headless] Error: ${F.message||"unknown"}
350
+ `),C==="jsonl"&&_.formatEvent){let D=_.formatEvent({type:"error",timestamp:Date.now(),data:{message:F.message||"unknown"}});D&&process.stdout.write(D+`
351
+ `)}break}});let Y=0;try{let F=L.run(s),D=new Promise($=>{let O=setInterval(()=>{(S||k)&&(clearInterval(O),$(null))},500)}),w=await Promise.race([F,D]);clearTimeout(xs);let v=Date.now()-g;if(S?(Y=124,x.status="timeout",x.summary=`Timeout after ${(Ct/1e3).toFixed(0)}s. Partial result below.`):k?(Y=130,x.status="interrupted",x.summary="Interrupted by SIGINT."):w&&(x.status="completed",x.success=!0,x.summary=b.split(`
352
+ `)[0]?.substring(0,200)||"Task completed."),x.filesChanged=I,x.toolCalls=E,x.tokens={input:K,output:fe,thinking:je,total:K+fe+je},x.cost=Gs(e.model,K,fe,je),x.duration=v,x.success&&P.size>0){let $=!0;for(let[O,R]of P)try{let Z=M.readFileSync(V.join(e.workspace,O));if(Tn.createHash("sha256").update(Z).digest("hex")!==R){$=!1;break}}catch{$=!1;break}$&&I.length===0&&(process.stderr.write(`[headless] Idempotency: no files changed \u2014 edits already applied.
353
+ `),x.summary="No changes needed \u2014 edits already applied.")}}catch(F){clearTimeout(xs);let D=F instanceof Error?F.message:String(F);D.includes("401")||D.includes("auth")||D.includes("token")?Y=3:D.includes("ECONNREFUSED")||D.includes("ENOTFOUND")||D.includes("fetch failed")?Y=5:Y=1,x.status="failed",x.error=D,x.summary=`Error: ${D.substring(0,200)}`,x.duration=Date.now()-g,x.tokens={input:K,output:fe,thinking:je,total:K+fe+je},x.cost=Gs(e.model,K,fe,je),x.filesChanged=I,x.toolCalls=E}if(C==="text"||C==="stream")C==="text"&&process.stdout.write(b+`
354
+ `);else{let F=_.formatResult(x);process.stdout.write(F+`
355
+ `)}await bo.fire("HeadlessStop",{workspace:e.workspace,data:{success:x.success,exitCode:Y,duration:x.duration,filesChanged:I.length}}),process.removeListener("SIGINT",$t),process.exit(Y)}l(Cb,"runHeadless");async function $b(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(tn(),yc));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($b,"runBackground");async function _b(){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(_b,"readStdin");function Eb(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(Eb,"printRunSummary");function Fb(){let s=j(),e=U(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(Fb,"printSlashHelp");function Tb(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(Tb,"formatAge");oe();var Lr=y(require("node:readline"),1);W();Ce();var Ec=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=U(this.caps),this.box=Ve(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(Lr.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(`
356
+ Focusing on ${t.id}... (press Esc to return)
357
+ `);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=Lr.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 Fc(s=!0){let e=new ao({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 Ec(e);s&&process.stdin.isTTY?await t.start():await t.list(),e.disconnect()}l(Fc,"agentsCommand");var Ht=[{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"}],cn=[{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 om(s){switch(s){case"bash":return Rb();case"zsh":return Ab();case"fish":return Pb();case"pwsh":return Ob();default:throw new Error(`Unsupported shell: ${s}. Supported: bash, zsh, fish, pwsh`)}}l(om,"generateCompletions");function sm(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(`
358
+ `);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(`
359
+ `);case"fish":return["monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish"].join(`
360
+ `);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(`
361
+ `)}}l(sm,"getCompletionInstallInstructions");function Rb(){let s=Ht.map(n=>n.name).join(" "),e=cn.map(n=>n.long).join(" "),t=cn.filter(n=>n.short).map(n=>n.short).join(" "),o=Ht.filter(n=>n.subcommands).map(n=>{let r=n.subcommands.map(i=>i.name).join(" ");return` ${n.name}) COMPREPLY=( $(compgen -W "${r}" -- "$cur") ) ;;`}).join(`
362
+ `);return`#!/bin/bash
363
+ # monkeyscode bash completion \u2014 generated by monkeyscode completions bash
364
+ # Install: eval "$(monkeyscode completions bash)"
365
+
366
+ _monkeyscode_completions() {
367
+ local cur prev words cword
368
+ _init_completion || return
369
+
370
+ local commands="${s}"
371
+ local flags="${e} ${t}"
372
+
373
+ case "\${words[1]}" in
374
+ ${o}
375
+ *)
376
+ if [[ "$cur" == -* ]]; then
377
+ COMPREPLY=( $(compgen -W "$flags" -- "$cur") )
378
+ else
379
+ COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
380
+ fi
381
+ ;;
382
+ esac
383
+ }
384
+
385
+ complete -F _monkeyscode_completions monkeyscode
386
+ complete -F _monkeyscode_completions mc
387
+ complete -F _monkeyscode_completions mcode
388
+ `}l(Rb,"generateBashCompletions");function Ab(){let s=Ht.map(o=>`'${o.name}:${o.description.replace(/'/g,"''")}'`).join(`
389
+ `),e=cn.map(o=>{let n=o.takesValue?`=${o.description}`:"";return`'${o.short?`{${o.short},${o.long}}`:o.long}[${o.description.replace(/'/g,"''")}]${n}'`}).join(`
390
+ `),t=Ht.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>`'${r.name}:${r.description.replace(/'/g,"''")}'`).join(`
391
+ `);return`
392
+ __monkeyscode_${o.name}_commands() {
393
+ local commands
394
+ commands=(
395
+ ${n}
396
+ )
397
+ _describe 'subcommand' commands
398
+ }`}).join(`
399
+ `);return`#compdef monkeyscode mc mcode
400
+ # monkeyscode zsh completion \u2014 generated by monkeyscode completions zsh
401
+ # Install: eval "$(monkeyscode completions zsh)"
402
+
403
+ _monkeyscode() {
404
+ local -a commands
405
+ commands=(
406
+ ${s}
407
+ )
408
+
409
+ _arguments -C \\
410
+ ${e} \\
411
+ '1:command:->cmd' \\
412
+ '*::arg:->args'
413
+
414
+ case "$state" in
415
+ cmd)
416
+ _describe 'command' commands
417
+ ;;
418
+ args)
419
+ case "\${words[1]}" in
420
+ ${Ht.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_${o.name}_commands ;;`).join(`
421
+ `)}
422
+ esac
423
+ ;;
424
+ esac
425
+ }
426
+ ${t}
427
+
428
+ compdef _monkeyscode monkeyscode mc mcode
429
+ `}l(Ab,"generateZshCompletions");function Pb(){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 Ht)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 Ht)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 cn){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(`
430
+ `)+`
431
+ `}l(Pb,"generateFishCompletions");function Ob(){let s=Ht.map(o=>` [CompletionResult]::new('${o.name}', '${o.name}', [CompletionResultType]::ParameterValue, '${o.description}')`).join(`
432
+ `),e=cn.map(o=>` [CompletionResult]::new('${o.long}', '${o.long}', [CompletionResultType]::ParameterName, '${o.description}')`).join(`
433
+ `),t=Ht.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>` [CompletionResult]::new('${r.name}', '${r.name}', [CompletionResultType]::ParameterValue, '${r.description}')`).join(`
434
+ `);return` '${o.name}' {
435
+ ${n}
436
+ }`}).join(`
437
+ `);return`# monkeyscode PowerShell completion \u2014 generated by monkeyscode completions pwsh
438
+ # Install: monkeyscode completions pwsh | Out-String | Invoke-Expression
439
+
440
+ Register-ArgumentCompleter -Native -CommandName @('monkeyscode', 'mc', 'mcode') -ScriptBlock {
441
+ param($wordToComplete, $commandAst, $cursorPosition)
442
+
443
+ $words = $commandAst.ToString().Split(' ', [StringSplitOptions]::RemoveEmptyEntries)
444
+
445
+ if ($words.Count -le 1 -or ($words.Count -eq 2 -and $wordToComplete)) {
446
+ # Top-level completions
447
+ if ($wordToComplete.StartsWith('-')) {
448
+ ${e}
449
+ } else {
450
+ ${s}
451
+ }
452
+ } elseif ($words.Count -ge 2) {
453
+ # Subcommand completions
454
+ switch ($words[1]) {
455
+ ${t}
456
+ }
457
+ }
458
+ }
459
+ `}l(Ob,"generatePowerShellCompletions");W();or();function Tc(s){let e=Co(s),t=Bu(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(Tc,"hooksListCommand");W();var nm=require("node:events"),rm=require("node:child_process");var Ur=class extends nm.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,rm.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(`
460
+ `);e.buffer=f.pop()||"";for(let m=0;m<f.length;m++){let g=f[m];if(g.startsWith("data: "))try{let h=JSON.parse(g.slice(6));this._handleResponse(e,h)}catch{}else if(g.startsWith("event: endpoint")){let h=f[m+1];h?.startsWith("data: ")&&(e.sseSessionUrl=h.slice(6).trim())}}}}catch(u){o.signal.aborted||(e.connected=!1,this.emit("error",new Error(`MCP SSE "${e.config.name}": ${u.message}`)))}},"processSSE")(),await new Promise(u=>setTimeout(u,500)),await this._initialize(e)}catch(t){this.emit("error",new Error(`MCP SSE "${e.config.name}" connect failed: ${t.message}`))}}async _initialize(e){try{await this._sendRequest(e,"initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0}},clientInfo:{name:"MonkeysCode-CLI",version:"1.0.0"}})&&(e.connected=!0,this.emit("connection-changed",{server:e.config.name,connected:!0}),this._sendNotification(e,"notifications/initialized",{}),await this._discoverTools(e),await this._discoverResources(e),await this._discoverPrompts(e))}catch(t){this.emit("error",new Error(`MCP "${e.config.name}" initialize failed: ${t.message}`))}}async _discoverTools(e){try{let t=await this._sendRequest(e,"tools/list",{});t?.tools&&(e.tools=t.tools.map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema||{type:"object",properties:{},required:[]},serverName:e.config.name})),this.emit("tools-discovered",e.tools))}catch(t){this.emit("log",`[MCP ${e.config.name}] tools/list failed: ${t.message}`)}}async _discoverResources(e){try{let t=await this._sendRequest(e,"resources/list",{});t?.resources&&(e.resources=t.resources.map(o=>({uri:o.uri,name:o.name,mimeType:o.mimeType,description:o.description,serverName:e.config.name})))}catch{}}async _discoverPrompts(e){try{let t=await this._sendRequest(e,"prompts/list",{});t?.prompts&&(e.prompts=t.prompts.map(o=>({name:o.name,description:o.description,arguments:o.arguments,serverName:e.config.name})))}catch{}}async callTool(e,t,o){let n=this._servers.get(e);if(!n||!n.connected)return{content:`MCP server "${e}" is not connected.`,isError:!0};try{let r=await this._sendRequest(n,"tools/call",{name:t,arguments:o});return r?.content?{content:r.content.filter(c=>c.type==="text").map(c=>c.text).join(`
461
+ `)||"(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(`
462
+ `):""}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+`
463
+ `):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(`
464
+ `);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 ln=[{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}],un=class{static{l(this,"MCPRegistry")}getAll(){return[...ln]}getByCategory(e){return ln.filter(t=>t.category===e)}search(e){let t=e.toLowerCase();return ln.filter(o=>o.name.toLowerCase().includes(t)||o.description.toLowerCase().includes(t)||o.tags.some(n=>n.includes(t)))}get(e){return ln.find(t=>t.id===e)}getCategories(){let e=new Map;for(let o of ln)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 im(s){let e=en(s),t=Cp(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(im,"mcpListCommand");function am(s,e,t,o){if(!t){let r=new un,i=r.get(e);if(i){if(nc(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(`
465
+ \u26A0 Required environment variables:`));for(let u of i.install.envVars)console.log(` ${a.cyan(u)}`)}console.log("");return}console.log(a.red(`
466
+ 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(`
467
+ Did you mean:`));for(let u of c.slice(0,5))console.log(` ${a.cyan(u.id)} \u2014 ${u.description}`)}console.log("");return}nc(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(am,"mcpAddCommand");function cm(s,e){let t=xp(s,e);console.log(""),console.log(t?a.green(` \u2713 Removed MCP server: ${e}`):a.red(` \u2717 Server not found: ${e}`)),console.log("")}l(cm,"mcpRemoveCommand");async function lm(s,e){let t=en(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 Ur;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(lm,"mcpTestCommand");function um(s){let e=new un,t=s?e.search(s):e.getAll();if(t.length===0){console.log(a.dim(`
468
+ No servers matching "${s}"
469
+ `));return}if(s){console.log(a.bold(`
470
+ \u{1F50D} Search: "${s}" (${t.length} results)
471
+ `));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(`
472
+ \u{1F50C} MCP Server Registry
473
+ `));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>")}
474
+ `))}}l(um,"mcpBrowseCommand");X();var Xe=y(require("node:fs"),1),pn=y(require("node:path"),1);X();W();var dn={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 dm=["plan","fast","thinking"],pm=["dark","light","auto"],mm=["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=>dm.includes(s)?null:`must be one of: ${dm.join(", ")}`,"defaultMode"),theme:l(s=>pm.includes(s)?null:`must be one of: ${pm.join(", ")}`,"theme"),outputFormat:l(s=>mm.includes(s)?null:`must be one of: ${mm.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")},Ac=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:dn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(dn))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,Xe.mkdirSync(pn.dirname(r),{recursive:!0}),Xe.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Xe.existsSync(o)&&(n=JSON.parse(Xe.readFileSync(o,"utf8")))}catch{}delete n[e],Xe.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...dn};for(let t of Object.keys(dn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=T();return pn.join(e.config,"config.json")}getProjectConfigPath(){return pn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Xe.existsSync(e)){let o=JSON.parse(Xe.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=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(dn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Xe.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function gm(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(gm,"printConfigList");var Rc=null;function Oo(s){return(!Rc||s)&&(Rc=new Ac(s)),Rc}l(Oo,"getConfigSystem");nr();W();Ce();oe();var Mb=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function hm(){let s=j(),e=U(s),t=s.ansi,o=me();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Ae();if(d){let p=await fetch(`${Mb}/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=Pc(n.tokensIn),u=Pc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Pc(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(hm,"usageCommand");function Pc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Pc,"formatTokenCount");var lt=y(require("node:fs"),1),xm=y(require("node:path"),1),gs=require("node:child_process");W();var fs=y(require("node:fs"),1),Wr=y(require("node:path"),1);X();var Ib="https://monkeyscode.com/api/latest-version",jb="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",Nb=4*60*60*1e3;function wm(){let s=T();return Wr.join(s.config,"update-check")}l(wm,"getCachePath");function Bb(){try{let s=fs.readFileSync(wm(),"utf8");return JSON.parse(s)}catch{return null}}l(Bb,"readCache");function Oc(s){try{let e=wm();fs.mkdirSync(Wr.dirname(e),{recursive:!0}),fs.writeFileSync(e,JSON.stringify(s))}catch{}}l(Oc,"writeCache");function ym(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(ym,"isNewerVersion");function Lb(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(Lb,"getAssetKey");async function Hr(s,e=!1){if(!e){let t=Bb();if(t&&Date.now()-t.lastCheck<Nb)return t.latestVersion&&ym(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await bm(Ib);if(t||(t=await bm(jb)),!t)return Oc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=Lb(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Oc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&ym(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 Oc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Hr,"checkForUpdate");async function bm(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(bm,"fetchManifest");function km(s){Hr(s).then(e=>{e&&(globalThis.__mcUpdateAvailable=e)}).catch(()=>{})}l(km,"checkForUpdateBackground");function Dm(){let s=globalThis.__mcUpdateAvailable;if(!s)return;let e=globalThis.__mcChalk,t=`\u2139\uFE0F Update available: v${s.currentVersion} \u2192 v${s.version}. Run "mc update" to upgrade.`;console.error(e?e.dim(t):t)}l(Dm,"printUpdateNotice");function Mc(){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(Mc,"detectInstallMethod");async function Cm(s){let t=(await Promise.resolve().then(()=>(Sm(),vm)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.0";if(s.rollback){await Xb(t);return}if(s.check){await Hb(t);return}await Gb(t,s.version)}l(Cm,"updateCommand");async function Hb(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Hr(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(Hb,"checkOnly");async function Gb(s,e){let t=Mc();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 qb(e);break;case"homebrew":await Vb();break;case"winget":await Jb();break;case"chocolatey":await zb();break;case"scoop":await Kb();break;case"binary":await Yb(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(Gb,"performUpdate");async function qb(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,gs.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(qb,"updateViaNpm");async function Vb(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,gs.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(Vb,"updateViaHomebrew");async function Jb(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,gs.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(Jb,"updateViaWinget");async function zb(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,gs.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(zb,"updateViaChocolatey");async function Kb(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,gs.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(Kb,"updateViaScoop");async function Yb(s,e){let t=await Hr(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{lt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${xm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{lt.writeFileSync(n,c),lt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{lt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(Yb,"updateViaBinaryDownload");async function Xb(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Mc()==="binary"){let t=process.execPath+".backup";if(!lt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{lt.copyFileSync(t,process.execPath),lt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(Xb,"rollback");W();var hs=y(require("node:fs"),1),qr=y(require("node:path"),1),Em=y(require("node:crypto"),1);X();var Gt=!0,Ic="",Qe=[],$m=!1,Qb="https://monkeyscode.com/api/telemetry",Gr=50,Zb=6e4;function Fm(){let s=T();return qr.join(s.config,"telemetry.json")}l(Fm,"getConfigPath");function jc(){try{let s=hs.readFileSync(Fm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:ew()};return Nc(s),s}}l(jc,"loadConfig");function Nc(s){try{let e=Fm();hs.mkdirSync(qr.dirname(e),{recursive:!0}),hs.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(Nc,"saveConfig");function ew(){return Em.randomUUID()}l(ew,"generateClientId");function Tm(){if($m)return;if($m=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Gt=!1;return}let s=jc();Gt=s.enabled,Ic=s.clientId,Gt&&(setInterval(()=>_m(),Zb).unref(),process.on("beforeExit",()=>_m()))}l(Tm,"initTelemetry");function Rm(){return Gt}l(Rm,"isTelemetryEnabled");function Am(){Gt=!0;let s=jc();s.enabled=!0,Nc(s)}l(Am,"enableTelemetry");function Pm(){Gt=!1,Qe=[];let s=jc();s.enabled=!1,Nc(s)}l(Pm,"disableTelemetry");function Om(s,e={}){Gt&&(Qe.push({name:s,properties:e,timestamp:new Date().toISOString()}),Qe.length>Gr&&(Qe=Qe.slice(-Gr)))}l(Om,"trackEvent");async function _m(){if(!Gt||Qe.length===0)return;let s=[...Qe];Qe=[];let e=xe(),o={clientId:Ic,cliVersion:"0.1.0",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(Qb,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{Qe.unshift(...s),Qe.length>Gr&&(Qe=Qe.slice(-Gr))}}l(_m,"flushEvents");function Mm(){let s=xe();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.0",` \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: ${Gt?"ENABLED":"DISABLED"}`,`Client ID: ${Ic||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
475
+ `)}l(Mm,"getCollectedDataSummary");async function Im(s){switch(s){case"enable":Am(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":Pm(),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(Mm()),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)")):Rm()?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(Im,"telemetryCommand");var wt=y(require("node:fs"),1),mn=y(require("node:path"),1);W();X();async function jm(s,e){let t=xe(),o="0.1.0";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=sw();i?(n.crashLog=i,console.log(a.dim(" \u{1F4CE} Attached latest crash report"))):console.log(a.dim(" No crash reports found"))}if(await tw(n))console.log(a.green(" \u2705 Bug report submitted")),console.log(a.dim(" Thank you! Our team will review your report."));else{let i=ow(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(jm,"bugCommand");async function tw(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(tw,"submitReport");function ow(s){let e=T(),t=mn.join(e.config,"bug-reports");wt.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=mn.join(t,`${o}.json`);return wt.writeFileSync(n,JSON.stringify(s,null,2)),n}l(ow,"saveReportLocally");function sw(){try{let s=T(),e=mn.join(s.config,"crashes");if(!wt.existsSync(e))return null;let t=wt.readdirSync(e).filter(o=>o.endsWith(".log")).sort().reverse();return t.length===0?null:wt.readFileSync(mn.join(e,t[0]),"utf8")}catch{return null}}l(sw,"getLatestCrashLog");var Mo=y(require("node:fs"),1),Bc=y(require("node:path"),1);W();X();Ce();function Nm(){let s=T(),e=Bc.join(s.config,"config.json");return!Mo.existsSync(e)}l(Nm,"isFirstRun");function nw(){let e=T().config,t=Bc.join(e,"config.json");Mo.mkdirSync(e,{recursive:!0}),Mo.existsSync(t)||Mo.writeFileSync(t,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}l(nw,"markOnboardingComplete");async function Bm(){let s=j(),e=xe();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(`
476
+ `)[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(""),nw()}l(Bm,"runOnboarding");var uo=y(require("node:fs"),1),Vr=y(require("node:path"),1);X();var Lm=[];function Wm(){process.on("uncaughtException",s=>{Um(s,"uncaughtException"),console.error(`
477
+ \u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${s.message}
478
+ `),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));Um(e,"unhandledRejection")})}l(Wm,"installCrashHandler");function rw(){let s=T();return Vr.join(s.config,"crashes")}l(rw,"getCrashDir");function Um(s,e){try{let t=rw();uo.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Vr.join(t,`${o}.log`),r=xe(),c=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 0.1.0",`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",Lm.length>0?Lm.map((u,d)=>` ${d+1}. ${u}`).join(`
479
+ `):" (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(`
480
+ `);uo.writeFileSync(n,c),iw(t,20)}catch{}}l(Um,"writeCrashReport");function iw(s,e){try{let t=uo.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)uo.unlinkSync(Vr.join(s,t[o]))}catch{}}l(iw,"pruneOldReports");var Fe=y(require("node:fs"),1),Vt=y(require("node:path"),1),aw=require("node:child_process");W();X();Ce();var cw="MEMORY.md",Hm=".monkeyscode";async function Gm(s={}){let e=U(j()),t=T(),o=s.since||"7d";if(s.mode&&s.mode!=="consolidate"){await dw(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=Vt.join(t.data,"sessions");if(!Fe.existsSync(n)){console.log(` ${e.info} No sessions found. Use ${a.cyan("mc")} to create some first.`);return}let r=lw(o),i=Fe.readdirSync(n).filter(h=>h.endsWith(".json")).map(h=>({name:h,path:Vt.join(n,h),mtime:Fe.statSync(Vt.join(n,h)).mtimeMs})).filter(h=>h.mtime>=r).sort((h,b)=>b.mtime-h.mtime);if(console.log(` Sessions reviewed: ${a.bold(String(i.length))} (last ${o})`),i.length===0){console.log(` ${e.info} No sessions in the last ${o}. Nothing to consolidate.`);return}let c=new Map;for(let h of i)try{let b=JSON.parse(Fe.readFileSync(h.path,"utf8"));if(b.toolCalls){for(let k of b.toolCalls)if(k.tool==="file_edit"&&k.args?.path){let S=Vt.extname(k.args.path);if(S){let C=`Works primarily with ${S} files`;c.set(C,(c.get(C)||0)+1)}}}if(b.messages){let k=JSON.stringify(b.messages).toLowerCase();k.includes("vitest")&&qt(c,"Uses vitest for testing"),k.includes("jest")&&qt(c,"Uses jest for testing"),k.includes("mocha")&&qt(c,"Uses mocha for testing"),k.includes("zod")&&qt(c,"Uses Zod for runtime validation"),k.includes("joi")&&qt(c,"Uses Joi for validation"),k.includes("tailwind")&&qt(c,"Uses Tailwind CSS"),k.includes("styled-components")&&qt(c,"Uses styled-components"),k.includes("result<")&&qt(c,"Uses Result<T, E> pattern for error handling"),(k.includes("try/catch")||k.includes("try {"))&&qt(c,"Uses try/catch for error handling")}}catch{}let u=Math.max(2,Math.floor(i.length*.3)),d=[];for(let[h,b]of c)b>=u&&d.push({rule:h,count:b});if(d.sort((h,b)=>b.count-h.count),d.length===0){console.log(` ${e.info} No strong patterns detected (need at least ${u} occurrences).`);return}console.log(" New conventions found:");for(let h of d)console.log(` ${e.success} "${h.rule}" (seen in ${h.count}/${i.length} sessions)`);if(s.review){console.log(),console.log(a.yellow(` ${e.info} Review mode \u2014 no changes written.`)),console.log(` Run ${a.cyan("mc dream")} (without --review) to write these.`);return}let p=Vt.join(process.cwd(),Hm,cw);Fe.mkdirSync(Vt.join(process.cwd(),Hm),{recursive:!0});let f="";Fe.existsSync(p)&&(f=Fe.readFileSync(p,"utf8"));let m=new Date().toISOString().split("T")[0],g=f.trimEnd();g||(g=`# Project Memory
481
+
482
+ > Auto-generated by \`mc dream\`. Edit freely.
483
+ `),g+=`
484
+
485
+ ## Consolidated ${m} (${i.length} sessions)
486
+
487
+ `;for(let h of d){let b=`- ${h.rule}`;f.includes(h.rule)||(g+=b+`
488
+ `)}Fe.writeFileSync(p,g.trimEnd()+`
489
+ `),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(Gm,"dream");function lw(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(lw,"parseDuration");function qt(s,e){s.set(e,(s.get(e)||0)+1)}l(qt,"incr");var uw={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(`
490
+ `)},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(`
491
+ `)},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(`
492
+ `)},"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(`
493
+ `)}};async function dw(s){let e=uw[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=Vt.join(process.cwd(),".monkeyscode","dreams");Fe.mkdirSync(t,{recursive:!0});let{AgentLoop:o}=await Promise.resolve().then(()=>(Je(),Yo)),{loadSettings:n}=await Promise.resolve().then(()=>(Q(),ve)),{getAccessToken:r}=await Promise.resolve().then(()=>(oe(),ge)),i=n(),c=await r()||process.env.MC_API_KEY||"",u=new o({platformUrl:i.platformUrl,token:c,model:i.defaultModel||"capuchin-reason",workspace:process.cwd(),mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:!1,effort:"reasoning"}),d="",p=0;u.on("event",f=>{switch(f.type){case"streaming_chunk":d+=f.content,process.stdout.write(a.dim(f.content));break;case"run_complete":p=f.summary.tokensIn+f.summary.tokensOut;break}});try{await u.run(e.prompt),console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.green(` \u2705 Dream complete (${p.toLocaleString()} tokens)`)),console.log(a.dim(" Report: .monkeyscode/dreams/")),console.log("")}catch(f){console.log(a.red(` Dream failed: ${f instanceof Error?f.message:f}`))}}l(dw,"dreamExtended");W();var _e=y(require("node:fs"),1),ut=y(require("node:path"),1),zr=y(require("node:crypto"),1),Lc=require("node:child_process");X();function qm(s,e){let t=s.split(`
494
+ `);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 pw(t);case"python":return mw(t);default:return fw(t,50)}}l(qm,"chunkCode");function pw(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(`
495
+ `),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(`
496
+ `),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(`
497
+ `),startLine:o+1,endLine:s.length,type:"module"})}return e}l(pw,"chunkByBraces");function mw(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(`
498
+ `),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(`
499
+ `),startLine:t+1,endLine:n,type:o}),t=n),o="class"),n-t>=50&&(e.push({content:s.slice(t,n+1).join(`
500
+ `),startLine:t+1,endLine:n+1,type:o}),t=n+1,o="module")}return t<s.length&&e.push({content:s.slice(t).join(`
501
+ `),startLine:t+1,endLine:s.length,type:o}),e}l(mw,"chunkByIndentation");function fw(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(`
502
+ `),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(fw,"chunkByLines");var Jr=class{static{l(this,"EmbeddingIndex")}workspace;indexDir;opts;chunks=[];embeddings=null;embeddingDim=1536;fileShas=new Map;constructor(e,t){this.workspace=e,this.opts={embeddingModel:"text-embedding-3-small",batchSize:100,...t};let o=zr.createHash("sha256").update(e).digest("hex").slice(0,12),n=T();this.indexDir=ut.join(n.data,"indexes",o)}async index(){_e.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=ut.join(this.workspace,d);if(!_e.existsSync(p))continue;let f=_e.readFileSync(p,"utf8"),m=this.detectLanguage(d),g=qm(f,m);for(let h of g)o.push({id:zr.randomUUID(),file:d,startLine:h.startLine,endLine:h.endLine,content:h.content,language:m,fileSha:this.getFileSha(d)});this.fileShas.set(d,this.getFileSha(d))}let n=new Set(t);this.chunks=this.chunks.filter(d=>!n.has(d.file)),this.chunks.push(...o);let r=this.opts.batchSize||100,i=this.embeddings?this.float32ToArrays(this.embeddings,this.embeddingDim):[],c=this.chunks.map(d=>d.content),u=[];for(let d=0;d<c.length;d+=r){let p=c.slice(d,d+r),f=await this.embed(p);u.push(...f)}this.embeddings=new Float32Array(u.length*this.embeddingDim);for(let d=0;d<u.length;d++)this.embeddings.set(u[d],d*this.embeddingDim);return this.saveState(),this.getStats(e.length)}async search(e,t=10){if(!this.embeddings||this.chunks.length===0)return[];let o=await this.embed([e]);if(o.length===0)return[];let n=o[0],r=[];for(let i=0;i<this.chunks.length;i++){let c=i*this.embeddingDim,u=this.embeddings.slice(c,c+this.embeddingDim),d=this.cosineSimilarity(n,u);r.push({index:i,score:d})}return r.sort((i,c)=>c.score-i.score),r.slice(0,t).map(({index:i,score:c})=>{let u=this.chunks[i];return{file:u.file,chunk:u.content,startLine:u.startLine,endLine:u.endLine,score:c,language:u.language}})}status(){this.loadState();let e=this.listIndexableFiles();return this.getStats(e.length)}async rebuild(){return this.chunks=[],this.embeddings=null,this.fileShas.clear(),this.index()}async embed(e){try{let t=await fetch(`${this.opts.platformUrl}/v1/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.token}`},body:JSON.stringify({input:e,model:this.opts.embeddingModel})});if(!t.ok)throw new Error(`Embedding API error: ${t.status}`);let o=await t.json();return o.data.length>0&&(this.embeddingDim=o.data[0].embedding.length),o.data.map(n=>n.embedding)}catch{return e.map(()=>new Array(this.embeddingDim).fill(0))}}cosineSimilarity(e,t){let o=0,n=0,r=0;for(let c=0;c<e.length;c++)o+=e[c]*t[c],n+=e[c]*e[c],r+=t[c]*t[c];let i=Math.sqrt(n)*Math.sqrt(r);return i===0?0:o/i}float32ToArrays(e,t){let o=[];for(let n=0;n<e.length;n+=t)o.push(Array.from(e.slice(n,n+t)));return o}listIndexableFiles(){try{let e=(0,Lc.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(`
503
+ `).filter(o=>o&&t.has(ut.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,Lc.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"}[ut.extname(e)]||"unknown"}saveState(){let e=ut.join(this.indexDir,"meta.json"),t=ut.join(this.indexDir,"vectors.bin");_e.writeFileSync(e,JSON.stringify({chunks:this.chunks,fileShas:Object.fromEntries(this.fileShas),embeddingDim:this.embeddingDim,lastIndexed:Date.now()})),this.embeddings&&_e.writeFileSync(t,Buffer.from(this.embeddings.buffer))}loadState(){let e=ut.join(this.indexDir,"meta.json"),t=ut.join(this.indexDir,"vectors.bin");if(_e.existsSync(e))try{let o=JSON.parse(_e.readFileSync(e,"utf8"));if(this.chunks=o.chunks||[],this.fileShas=new Map(Object.entries(o.fileShas||{})),this.embeddingDim=o.embeddingDim||1536,_e.existsSync(t)){let n=_e.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=ut.join(this.indexDir,"vectors.bin"),o=_e.existsSync(t)?_e.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 kt=y(require("node:fs"),1),Me=y(require("node:path"),1),Uc=require("node:child_process");var fn=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=Me.join(this.workspace,e);if(!kt.existsSync(t)){this.forward.delete(e);return}let o=kt.readFileSync(t,"utf8"),n=Me.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=Me.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(kt.existsSync(Me.join(this.workspace,u))){o.push(u);break}}return o}parseGoImports(e,t){let o=[],n=Me.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=Me.join(this.workspace,"go.mod");if(kt.existsSync(e)){let o=kt.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=Me.join(this.workspace,o);if(kt.existsSync(n))return o}return null}resolveTs(e,t){if(!t.startsWith("."))return null;let o=Me.join(e,t),n=["",".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let r of n){let i=o+r;if(kt.existsSync(Me.join(this.workspace,i)))return i}if(t.endsWith(".js")){let r=Me.join(e,t.replace(/\.js$/,".ts"));if(kt.existsSync(Me.join(this.workspace,r)))return r}return null}listAllFiles(){try{return(0,Uc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}).trim().split(`
504
+ `).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,Uc.execSync)("git diff --name-only HEAD~5",{cwd:this.workspace,encoding:"utf8"}).trim().split(`
505
+ `).filter(Boolean)}catch{return this.listAllFiles()}}};var ys=y(require("node:fs"),1),de=y(require("node:path"),1),Wc=require("node:child_process");var gn={KEYWORD_MATCH:.3,GIT_RECENCY:.25,IMPORT_GRAPH:.2,TEST_PAIR:.15,CONFIG_PROXIMITY:.1},gw=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 Vm(s,e){let t=new Map,o=hw(s),n=e.maxResults||30,r=bw(e.workspace);for(let i of r){let c=yw(i,o);c>0&&hn(t,i,c*gn.KEYWORD_MATCH,`Matches: ${o.filter(u=>i.toLowerCase().includes(u)).join(", ")}`)}if(e.useGitRecency!==!1){let i=ww(e.workspace,50);for(let c=0;c<i.length;c++){let u=1-c/i.length;hn(t,i[c],u*gn.GIT_RECENCY,`Git recency: #${c+1}`)}}if(e.activeFiles&&e.activeFiles.length>0)for(let i of e.activeFiles){let c=kw(e.workspace,i);for(let u of c)hn(t,u,gn.IMPORT_GRAPH,`Imported by ${de.basename(i)}`)}for(let i of r){let c=vw(i);c&&t.has(i)&&hn(t,c,gn.TEST_PAIR,`Test pair of ${de.basename(i)}`)}for(let i of r)if(gw.has(de.basename(i))){let c=de.dirname(i);[...t.keys()].some(d=>de.dirname(d)===c)&&hn(t,i,gn.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(Vm,"rankFiles");function hn(s,e,t,o){let n=s.get(e)||{score:0,reasons:[]};n.score+=t,n.reasons.push(o),s.set(e,n)}l(hn,"addScore");function hw(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(hw,"extractKeywords");function yw(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(yw,"keywordScore");function bw(s){try{return(0,Wc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:s,encoding:"utf8",maxBuffer:1e7}).trim().split(`
506
+ `).filter(Boolean)}catch{return[]}}l(bw,"listWorkspaceFiles");function ww(s,e){try{let t=(0,Wc.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(`
507
+ `).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(ww,"getGitRecentFiles");function kw(s,e){try{let t=ys.readFileSync(de.join(s,e),"utf8"),o=[],n=/(?:import|require)\s*\(?['"]([^'"]+)['"]\)?/g,r;for(;(r=n.exec(t))!==null;){let c=r[1];if(c.startsWith(".")){let u=de.dirname(e),d=Dw(s,de.join(u,c));d&&o.push(d)}}let i=/^(?:from|import)\s+(\S+)/gm;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\./g,"/"),u=[`${c}.py`,`${c}/__init__.py`];for(let d of u)if(ys.existsSync(de.join(s,d))){o.push(d);break}}return o}catch{return[]}}l(kw,"parseImportsQuick");function Dw(s,e){let t=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let o of t){let n=e+o;if(ys.existsSync(de.join(s,n)))return n}return ys.existsSync(de.join(s,e))?e:null}l(Dw,"resolveImport");function vw(s){let e=de.extname(s),t=de.basename(s,e),o=de.dirname(s);if(t.endsWith(".test")||t.endsWith(".spec")){let r=t.replace(/\.(test|spec)$/,"");return de.join(o,r+e)}return[de.join(o,`${t}.test${e}`),de.join(o,`${t}.spec${e}`),de.join(o,"__tests__",`${t}${e}`)].find(()=>!0)||null}l(vw,"findTestPair");Q();Ce();async function Io(s,e){let t=s[0]||"status",o=process.cwd(),n=J(),r=U(j());switch(t){case"index":await Sw(o,n);break;case"search":await xw(o,n,s.slice(1).join(" "));break;case"status":await Cw(o,n);break;case"rebuild":await $w(o,n);break;case"related":await _w(o,s[1]);break;case"rank":Ew(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(Io,"contextCommand");async function Sw(s,e){console.log(a.cyan(" \u26A1 Indexing workspace...")),console.log(a.dim(` ${s}`)),console.log("");let t=Date.now(),n=await Kr(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(Jm(n.indexSizeBytes))}`),console.log(` Time: ${a.bold(r+"s")}`),console.log("")}l(Sw,"contextIndex");async function xw(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 Kr(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(`
508
+ `).slice(0,2).map(d=>` ${a.dim(d.substring(0,80))}`).join(`
509
+ `);console.log(u),console.log("")}}l(xw,"contextSearch");async function Cw(s,e){let o=Kr(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(Jm(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 fn(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(Cw,"contextStatus");async function $w(s,e){console.log(a.yellow(" \u{1F504} Rebuilding index from scratch...")),console.log("");let t=Date.now(),n=await Kr(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($w,"contextRebuild");async function _w(s,e){if(!e){console.log(a.red(" Usage: mc context related <file>"));return}let t=new fn(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(_w,"contextRelated");function Ew(s,e){if(!e){console.log(a.red(' Usage: mc context rank "your prompt"'));return}let t=Vm(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(Ew,"contextRank");function Kr(s,e){return new Jr(s,{platformUrl:e.platformUrl,token:process.env.MC_API_KEY||"",embeddingModel:"text-embedding-3-small"})}l(Kr,"createIndex");function Jm(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(Jm,"formatBytes");var po=y(require("node:fs"),1),wn=y(require("node:path"),1);W();Ce();Q();var sf=".monkeyscode/triggers.json";async function mo(s,e){let t=s[0]||"list",o=process.cwd();switch(t){case"list":Fw(o);break;case"add":Tw(o,e);break;case"remove":Rw(o,s[1]);break;case"test":Aw(o,s[1]);break;case"enable":of(o,s[1],!0);break;case"disable":of(o,s[1],!1);break;case"serve":await Mw(o,e);break;default:Ow()}}l(mo,"triggersCommand");function Fw(s){let e=kn(s),t=U(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(Fw,"triggersList");function Tw(s,e){let t=e.event,o=e.prompt,n=e.name||Pw(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=kn(s);if(d.some(p=>p.name===n)){console.log(a.red(` Trigger "${n}" already exists. Use a different --name.`));return}d.push(u),Vc(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(Tw,"triggersAdd");function Rw(s,e){if(!e){console.log(a.red(" Usage: mc triggers remove <trigger-name>"));return}let t=kn(s),o=t.findIndex(n=>n.name===e);if(o===-1){console.log(a.red(` Trigger "${e}" not found.`));return}t.splice(o,1),Vc(s,t),console.log(a.green(` \u2705 Trigger "${e}" removed`)),console.log("")}l(Rw,"triggersRemove");function Aw(s,e){if(!e){console.log(a.red(" Usage: mc triggers test <trigger-name>"));return}let o=kn(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(Aw,"triggersTest");function of(s,e,t){if(!e){console.log(a.red(` Usage: mc triggers ${t?"enable":"disable"} <trigger-name>`));return}let o=kn(s),n=o.find(r=>r.name===e);if(!n){console.log(a.red(` Trigger "${e}" not found.`));return}n.enabled=t,Vc(s,o),console.log(a.green(` \u2705 Trigger "${e}" ${t?"enabled":"disabled"}`)),console.log("")}l(of,"triggersToggle");function kn(s){let e=wn.join(s,sf);if(!po.existsSync(e))return[];try{return JSON.parse(po.readFileSync(e,"utf8")).triggers||[]}catch{return[]}}l(kn,"loadTriggers");function Vc(s,e){let t=wn.join(s,sf),o=wn.dirname(t);po.mkdirSync(o,{recursive:!0}),po.writeFileSync(t,JSON.stringify({triggers:e},null,2)+`
510
+ `)}l(Vc,"saveTriggers");function Pw(s,e){let t=e.toLowerCase().split(/\s+/).slice(0,3).join("-").replace(/[^a-z0-9-]/g,"");return`${s.replace(/\./g,"-")}-${t}`}l(Pw,"generateName");function Ow(){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(Ow,"printHelp");async function Mw(s,e){let{TriggerEngine:t}=await Promise.resolve().then(()=>(Qm(),Xm)),{GitHubWebhookServer:o}=await Promise.resolve().then(()=>(tf(),ef)),n=J(),{getAccessToken:r}=await Promise.resolve().then(()=>(oe(),ge)),i=await r()||process.env.MC_API_KEY||"",c=parseInt(String(e.port||"9122"),10);console.log(""),console.log(a.bold(" \u26A1 MonkeysCode Trigger Daemon")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let u=new t({workspace:s,token:i,model:n.defaultModel||"capuchin-reason",cooldownSeconds:300});u.on("started",f=>{console.log(a.green(` \u2713 Loaded ${f.triggerCount} trigger(s)`))}),u.on("trigger.fired",f=>{console.log(a.cyan(` \u26A1 Trigger fired: ${f.name} [${f.event}]`))}),u.on("trigger.completed",f=>{console.log(a.green(` \u2705 Completed: ${f.name}`))}),u.on("trigger.failed",f=>{console.log(a.red(` \u274C Failed: ${f.name} \u2014 ${f.error}`))}),u.start();let p=u.loadTriggers().filter(f=>f.event.startsWith("github."));if(p.length>0){let f=process.env.MC_WEBHOOK_SECRET;await new o({port:c,secret:f,onEvent:l(async g=>{console.log(a.cyan(` \u{1F514} GitHub event: ${g.event}`)),await u.processEvent({type:`github.${g.event}`,payload:g.payload,source:"github-webhook",timestamp:Date.now()})},"onEvent")}).start(),console.log(a.dim(` \u{1F514} Webhook server: http://localhost:${c} (${p.length} trigger(s))`))}console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.green(" Trigger daemon running. Press Ctrl+C to stop.")),console.log(""),await new Promise(f=>{let m=l(()=>{console.log(a.dim(`
511
+ Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(Mw,"triggersServe");W();W();var uf=require("node:child_process");var Ie=y(require("node:fs"),1),fo=y(require("node:path"),1),nf=y(require("node:crypto"),1);X();var ws=class s{static{l(this,"TraceRecorder")}trace;turnIndex=0;currentToolStart=null;currentToolName=null;thinkingBuffer="";tracesDir;constructor(e){let t=T(De());this.tracesDir=fo.join(t.data,"traces"),Ie.mkdirSync(this.tracesDir,{recursive:!0}),this.trace={runId:e.runId||nf.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=fo.join(this.tracesDir,`${this.trace.runId}.json`);Ie.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=T(De()),o=fo.join(t.data,"traces"),n=fo.join(o,`${e}.json`);if(!Ie.existsSync(n))return null;try{return JSON.parse(Ie.readFileSync(n,"utf8"))}catch{return null}}static list(e=20){let t=T(De()),o=fo.join(t.data,"traces");return Ie.existsSync(o)?Ie.readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=Ie.statSync(fo.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(Ie.readFileSync(fo.join(o,r.file),"utf8"));return{runId:i.runId,model:i.model,prompt:i.prompt.slice(0,80),date:i.startedAt,cost:i.totalCostUsd}}catch{return null}}).filter(Boolean):[]}static lastRunId(){let e=s.list(1);return e.length>0?e[0].runId:null}};W();function rf(s,e={}){Iw(s),e.tree?Bw(s):jw(s,e.verbose),Lw(s),Uw(s)}l(rf,"renderTrace");function Iw(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(Dn(s.tokensIn))} in / ${a.white(Dn(s.tokensOut))} out${s.tokensCached?` / ${a.dim(Dn(s.tokensCached)+" cached")}`:""}`),console.log(` ${a.dim("Files:")} ${o} accessed`),console.log(` ${a.dim("Turns:")} ${s.turns.length}`),console.log()}l(Iw,"renderHeader");function jw(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)Nw(t,e);console.log()}l(jw,"renderTimeline");function Nw(s,e){let t=s.tokens?a.dim(` (${Dn(s.tokens)} tok)`):"",o=s.durationMs?a.dim(` ${s.durationMs}ms`):"";switch(s.type){case"thinking":{let n=e?s.content||"":(s.content||"").split(`
512
+ `)[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=Ww(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(Nw,"renderTurn");function Bw(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(` [${Dn(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(`
513
+ `)[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(Bw,"renderTree");function Lw(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(Lw,"renderFileGraph");function Uw(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(Uw,"renderFooter");function Ww(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(Ww,"getToolIcon");function Dn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Dn,"formatNum");var cf=y(require("node:fs"),1),zc=y(require("node:path"),1);X();var jo={thinking:"#4A90D9",tool_call:"#2ECC71",context_compact:"#F39C12",error:"#E74C3C",root:"#34495E"};function lf(s){let e=T(De()),t=zc.join(e.data,"traces"),o=zc.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 af(s,r,o)}return af(s,n,o)}l(lf,"generateFlamegraph");function af(s,e,t){let c=[];c.push({name:`Run: ${s.model} \u2014 ${s.prompt.slice(0,50)}`,tokens:e,color:jo.root,x:0,width:1200,y:0,detail:`Total: ${Jc(e)} tokens, $${s.totalCostUsd.toFixed(4)}`});let u=0;for(let m of s.turns){let g=m.tokens||Hw(m);if(g===0)continue;let h=Math.max(g/e*1200,2),b=jo[m.type]||jo.root,k=m.type==="tool_call"?m.tool||"tool":m.type==="thinking"?"Think":m.type;c.push({name:k,tokens:g,color:b,x:u,width:h,y:1,detail:`${k}: ${Jc(g)} tokens${m.durationMs?`, ${m.durationMs}ms`:""}`}),u+=h}let d=2,p=d*24+40*2+60,f=`<?xml version="1.0" encoding="UTF-8"?>
514
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 ${p}" width="1200" height="${p}">
515
+ <style>
516
+ .frame { cursor: pointer; }
517
+ .frame:hover rect { opacity: 0.8; stroke: #fff; stroke-width: 1; }
518
+ .frame text { font-family: 'SF Mono', 'Fira Code', monospace; font-size: 12px; fill: white; pointer-events: none; }
519
+ .title { font-family: system-ui, sans-serif; font-size: 16px; font-weight: bold; fill: #ECF0F1; }
520
+ .subtitle { font-family: system-ui, sans-serif; font-size: 12px; fill: #95A5A6; }
521
+ .legend rect { rx: 3; }
522
+ .legend text { font-family: system-ui, sans-serif; font-size: 11px; fill: #BDC3C7; }
523
+ </style>
524
+ <rect width="1200" height="${p}" fill="#1a1a2e" rx="8"/>
525
+
526
+ <!-- Title -->
527
+ <text x="40" y="28" class="title">Token Flamegraph \u2014 ${Qr(s.runId)}</text>
528
+ <text x="40" y="46" class="subtitle">${Qr(s.model)} \xB7 ${Jc(e)} tokens \xB7 $${s.totalCostUsd.toFixed(4)} \xB7 ${(s.durationMs/1e3).toFixed(1)}s</text>
529
+
530
+ <!-- Legend -->
531
+ <g class="legend" transform="translate(800, 20)">
532
+ <rect x="0" y="0" width="12" height="12" fill="${jo.thinking}"/>
533
+ <text x="16" y="11">Thinking</text>
534
+ <rect x="80" y="0" width="12" height="12" fill="${jo.tool_call}"/>
535
+ <text x="96" y="11">Tools</text>
536
+ <rect x="150" y="0" width="12" height="12" fill="${jo.context_compact}"/>
537
+ <text x="166" y="11">Compact</text>
538
+ <rect x="230" y="0" width="12" height="12" fill="${jo.error}"/>
539
+ <text x="246" y="11">Error</text>
540
+ </g>
541
+
542
+ <!-- Frames -->
543
+ <g transform="translate(0, 60)">
544
+ `;for(let m of c){let g=(d-1-m.y)*24,h=m.x+4,b=m.width>40?Gw(m.name,Math.floor(m.width/7)):"";f+=`<g class="frame">
545
+ <title>${Qr(m.detail)}</title>
546
+ <rect x="${m.x}" y="${g}" width="${m.width}" height="22" fill="${m.color}" rx="2"/>
547
+ <text x="${h}" y="${g+24-8}">${Qr(b)}</text>
548
+ </g>
549
+ `}return f+=`</g>
550
+ </svg>`,cf.writeFileSync(t,f),t}l(af,"generateSvg");function Hw(s){return s.tokens?s.tokens:s.content?Math.ceil(s.content.length/4):s.result?Math.ceil(s.result.length/4):10}l(Hw,"estimateTurnTokens");function Jc(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Jc,"formatTokens");function Gw(s,e){return s.length>e?s.slice(0,e-1)+"\u2026":s}l(Gw,"truncate");function Qr(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}l(Qr,"escapeXml");function df(s){let e=ws.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(df,"traceList");function pf(s,e){let t=s==="last"?ws.lastRunId():s;if(!t){console.log(a.red("No traces found. Run an agent first."));return}let o=ws.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=lf(o);console.log(a.green(`Flamegraph saved: ${n}`));let r=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,uf.exec)(`${r} "${n}"`,i=>{i&&console.log(a.dim(`Open manually: ${n}`))});return}rf(o,{tree:e.tree,verbose:e.verbose})}l(pf,"traceShow");W();Q();oe();var Jt=class{static{l(this,"MarketplaceClient")}baseUrl;token;constructor(e){let t=J();this.baseUrl=(e?.baseUrl||t.platformUrl||"https://api.monkeyscode.com").replace(/\/$/,""),this.token=e?.token||process.env.MC_API_KEY||void 0}async search(e,t){let o=new URLSearchParams({q:e});return t?.category&&o.set("category",t.category),t?.page&&o.set("page",String(t.page)),t?.pageSize&&o.set("page_size",String(t.pageSize)),this.get(`/v1/marketplace/skills?${o}`)}async getSkill(e){return this.get(`/v1/marketplace/skills/${e}`)}async featured(){return this.get("/v1/marketplace/featured")}async getReviews(e){return this.get(`/v1/marketplace/skills/${e}/reviews`)}async addReview(e,t,o){return this.post(`/v1/marketplace/skills/${e}/reviews`,{rating:t,comment:o})}async publish(e){let t=new FormData;t.set("name",e.name),t.set("description",e.description),t.set("version",e.version),t.set("category",e.category),t.set("tags",JSON.stringify(e.tags)),t.set("tarball",new Blob([e.tarball]),`${e.name}-${e.version}.tar.gz`);let o=await fetch(`${this.baseUrl}/v1/marketplace/skills`,{method:"POST",headers:await this.authHeaders(),body:t});if(!o.ok)throw new Error(`Marketplace API error: ${o.status} ${await o.text()}`);return await o.json()}async download(e){let t=await this.getSkill(e);if(!t.downloadUrl)throw new Error(`No download URL for skill ${e}`);let o=await fetch(t.downloadUrl,{headers:await this.authHeaders()});if(!o.ok)throw new Error(`Download failed: ${o.status}`);let n=await o.arrayBuffer();return Buffer.from(n)}async get(e){let t=await fetch(`${this.baseUrl}${e}`,{headers:{...await this.authHeaders(),Accept:"application/json"}});if(!t.ok)throw new Error(`Marketplace API error: ${t.status} ${await t.text()}`);return await t.json()}async post(e,t){let o=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:{...await this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok)throw new Error(`Marketplace API error: ${o.status} ${await o.text()}`);return await o.json()}async authHeaders(){let e=this.token||await Ae();return e?{Authorization:`Bearer ${e}`}:{}}};var ye=y(require("node:fs"),1),go=y(require("node:path"),1),mf=require("node:child_process");X();var No=class{static{l(this,"SkillInstaller")}client;skillsDir;registryPath;constructor(){this.client=new Jt;let e=T(De());this.skillsDir=go.join(e.config,"skills"),this.registryPath=go.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=go.join(this.skillsDir,n,r);ye.existsSync(i)&&ye.rmSync(i,{recursive:!0}),ye.mkdirSync(i,{recursive:!0});let c=go.join(i,".tmp.tar.gz");ye.writeFileSync(c,o);try{(0,mf.execSync)(`tar -xzf "${c}" -C "${i}" --strip-components=1`,{stdio:"pipe"})}finally{ye.unlinkSync(c)}let u=go.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=go.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 vt=y(require("node:fs"),1),dt=y(require("node:path"),1),ff=require("node:child_process");var Zr=class{static{l(this,"SkillPublisher")}client;constructor(){this.client=new Jt}async publish(e,t){let o=dt.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(!vt.existsSync(e))throw new Error(`Directory not found: ${e}`);let t=dt.join(e,"skill.md");if(!vt.existsSync(t))throw new Error("Missing required file: skill.md");let o=dt.join(e,"README.md");if(!vt.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=vt.readFileSync(dt.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(`
551
+ `)){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=dt.join(e,".publish.tar.gz");try{return(0,ff.execSync)(`tar -czf "${t}" --exclude=".*" --exclude="node_modules" --exclude="*.tar.gz" -C "${dt.dirname(e)}" "${dt.basename(e)}"`,{stdio:"pipe"}),vt.readFileSync(t)}finally{vt.existsSync(t)&&vt.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 Jt;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)vf(n)}catch(o){console.log(a.red(`Search failed: ${o.message}`))}}l(gf,"marketplaceSearch");async function hf(s){let e=new No;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(hf,"marketplaceInstall");function yf(s){new No().uninstall(s)?console.log(a.green(`\u2713 Uninstalled ${s}`)):console.log(a.red(`Skill not found: ${s}`))}l(yf,"marketplaceUninstall");async function bf(s,e){let t=new Zr;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(bf,"marketplacePublish");async function wf(){let s=new No;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(wf,"marketplaceUpdate");function kf(){let e=new No().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 Df(){let s=new Jt;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)vf(t)}catch(e){console.log(a.red(`Failed to fetch featured: ${e.message}`))}}l(Df,"marketplaceFeatured");function vf(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(vf,"renderSkillCard");W();var ho=y(require("node:fs"),1),ei=y(require("node:path"),1);X();var qw=`You translate natural language permission rules into structured JSON policies.
552
+
553
+ Each policy has:
554
+ - tool: glob pattern for which tools this applies to (e.g., "delete_file", "bash", "*")
555
+ - condition: a JavaScript-like condition using these variables:
556
+ - path: file path being accessed
557
+ - args: tool arguments object
558
+ - command: bash command string (if bash tool)
559
+ - action: "deny" (block), "warn" (allow with warning), or "prompt" (ask user)
560
+ - message: human-readable explanation
561
+
562
+ Return ONLY valid JSON, no markdown fences, no explanation.
563
+
564
+ Examples:
565
+ Input: "Never delete files outside the src directory"
566
+ Output: {"tool":"delete_file","condition":"!path.startsWith('src/')","action":"deny","message":"Cannot delete files outside src/ per project policy"}
567
+
568
+ Input: "Always run tests before committing"
569
+ Output: {"tool":"bash","condition":"command.includes('git commit')","action":"warn","message":"Consider running tests before committing"}
570
+
571
+ Input: "Ask before modifying any file with 'config' in the name"
572
+ Output: {"tool":"*_file","condition":"path.includes('config')","action":"prompt","message":"This file contains configuration. Proceed?"}
573
+
574
+ Input: "Block any command that uses sudo"
575
+ Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function Vw(s){let e=Jw(s);return e||await zw(s)}l(Vw,"translateNaturalRule");function Jw(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(Jw,"tryLocalTranslation");async function zw(s){try{let{AgentLoop:e}=await Promise.resolve().then(()=>(Je(),Yo)),{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{getAccessToken:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=await o()||process.env.MC_API_KEY||"";if(!r)return Kc(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(`${qw}
576
+
577
+ Input: "${s}"
578
+ Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?Kc(s):d}catch{return Kc(s)}}l(zw,"llmTranslation");function Kc(s){return{tool:"*",condition:"true",action:"prompt",message:`Custom rule: ${s}`}}l(Kc,"fallbackPolicy");function Sf(){let s=T(De());return ei.join(s.config,"natural-permissions.json")}l(Sf,"getPermissionsPath");function vn(){let s=Sf();if(!ho.existsSync(s))return{naturalRules:[]};try{return JSON.parse(ho.readFileSync(s,"utf8"))}catch{return{naturalRules:[]}}}l(vn,"loadNaturalPermissions");function xf(s){let e=Sf(),t=ei.dirname(e);ho.mkdirSync(t,{recursive:!0}),ho.writeFileSync(e,JSON.stringify(s,null,2))}l(xf,"saveNaturalPermissions");async function Cf(s){let e=await Vw(s),t={text:s,generatedPolicy:e,createdAt:new Date().toISOString(),enabled:!0},o=vn();return o.naturalRules.push(t),xf(o),t}l(Cf,"addNaturalRule");function $f(s){let e=vn();return s<0||s>=e.naturalRules.length?!1:(e.naturalRules.splice(s,1),xf(e),!0)}l($f,"removeNaturalRule");function _f(s,e){let t=vn();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(_f,"evaluateNaturalRules");async function Ef(s){console.log(a.dim("Translating rule..."));let e=await Cf(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:")} ${Yc(e.generatedPolicy.action)}`),console.log(` ${a.dim("Message:")} ${e.generatedPolicy.message}`),console.log()}l(Ef,"permissionsSet");function Ff(){let s=vn();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=Yc(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(Ff,"permissionsList");function Tf(s){let e=$f(s);console.log(e?a.green(`\u2713 Rule ${s} removed`):a.red(`Rule ${s} not found`))}l(Tf,"permissionsRemove");function Rf(s,e){let t;try{t=JSON.parse(e)}catch{console.log(a.red("Invalid JSON for args"));return}let o=_f(s,t);console.log(),console.log(` ${a.dim("Tool:")} ${s}`),console.log(` ${a.dim("Args:")} ${JSON.stringify(t)}`),console.log(` ${a.dim("Result:")} ${Yc(o.action)}`),o.message&&console.log(` ${a.dim("Message:")} ${o.message}`),console.log()}l(Rf,"permissionsTest");function Yc(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(Yc,"colorAction");var Ds=y(require("node:fs"),1),si=y(require("node:path"),1);W();var Ue=y(require("node:fs"),1),ks=y(require("node:path"),1),ti=require("node:child_process");function Kw(s){let e={name:"Unnamed Benchmark",setup:[],steps:[],score:{testsPass:50,noRegressions:30,codeQuality:20}},t=s.split(`
579
+ `),o="",n={};for(let r of t){let i=r.trim();if(!i||i.startsWith("#"))continue;let c=i.match(/^(\w+):\s*(.*)$/);if(c&&!r.startsWith(" ")&&!r.startsWith(" ")){let[,p,f]=c;p==="name"&&(e.name=f.replace(/^["']|["']$/g,"")),p==="description"&&(e.description=f),p==="setup"&&(o="setup"),p==="steps"&&(o="steps"),p==="score"&&(o="score");continue}let u=i.match(/^-\s+(.+)$/);if(u){o==="setup"&&e.setup.push(u[1].replace(/^["']|["']$/g,""));continue}let d=i.match(/^(\w+):\s*(.+)$/);if(d){let[,p,f]=d,m=f.replace(/^["']|["']$/g,"");o==="steps"&&(p==="prompt"&&(n.prompt&&e.steps.push(n),n={prompt:m}),p==="verify"&&(n.verify=m),p==="expected_files_changed"&&(n.expectedFilesChanged=m.replace(/^\[|\]$/g,"").split(",").map(g=>g.trim().replace(/^["']|["']$/g,""))),p==="max_tokens"&&(n.maxTokens=parseInt(m)),p==="timeout_ms"&&(n.timeoutMs=parseInt(m))),o==="score"&&(p==="tests_pass"&&(e.score.testsPass=parseInt(m)),p==="no_regressions"&&(e.score.noRegressions=parseInt(m)),p==="code_quality"&&(e.score.codeQuality=parseInt(m)))}}return n.prompt&&e.steps.push(n),e}l(Kw,"parseSimpleYaml");var oi=class{static{l(this,"BenchmarkRunner")}workspace;constructor(e){this.workspace=e}loadSpec(e){let t=Ue.readFileSync(e,"utf8");return Kw(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,ti.execSync)(p,{cwd:this.workspace,stdio:"pipe",timeout:6e4})}catch(f){console.error(`Setup step failed: ${p}
580
+ ${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop:m}=await Promise.resolve().then(()=>(Je(),Yo)),{loadSettings:g}=await Promise.resolve().then(()=>(Q(),ve)),{getAccessToken:h}=await Promise.resolve().then(()=>(oe(),ge)),b=g(),k=await h()||process.env.MC_API_KEY||"",S=new m({platformUrl:b.platformUrl,token:k,model:t,workspace:this.workspace,mode:"auto",maxTurns:p.maxTokens?Math.ceil(p.maxTokens/1e3):20,sandboxed:!0}),C=0,_=0,x=[];S.on("event",ae=>{if(ae.type==="state_update"&&(C=(ae.state?.tokensIn||0)+(ae.state?.tokensOut||0),_=ae.state?.costUsd||0),ae.type==="tool_call_start"&&ae.name?.includes("file")){let K=ae.args?.path||ae.args?.file;K&&!x.includes(K)&&x.push(K)}}),await S.run(p.prompt);let E=!1,I="";try{I=(0,ti.execSync)(p.verify,{cwd:this.workspace,stdio:"pipe",timeout:p.timeoutMs||12e4}).toString().trim(),E=!0}catch(ae){I=ae.stderr?.toString()||ae.message||"Verification failed",E=!1}r+=C,i+=_,c.push({prompt:p.prompt,passed:E,verifyOutput:I,durationMs:Date.now()-f,tokensUsed:C,filesChanged:x,score:this.scoreStep(p,E,x,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,ti.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)&&!Yw(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 Yw(s,e){return e.some(t=>{let o=t.replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(o).test(s)})}l(Yw,"matchesGlob");function Xc(s){let{getPlatformPaths:e,detectPlatform:t}=(X(),_s(Do)),o=e(t()),n=ks.join(o.data,"benchmarks");Ue.mkdirSync(n,{recursive:!0});let r=`${s.name.replace(/\s+/g,"-").toLowerCase()}-${s.model}-${Date.now()}.json`,i=ks.join(n,r);return Ue.writeFileSync(i,JSON.stringify(s,null,2)),i}l(Xc,"saveBenchmarkResult");function Af(s=20){let{getPlatformPaths:e,detectPlatform:t}=(X(),_s(Do)),o=e(t()),n=ks.join(o.data,"benchmarks");return Ue.existsSync(n)?Ue.readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let i=Ue.statSync(ks.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(Ue.readFileSync(ks.join(n,r.file),"utf8"))}catch{return null}}).filter(Boolean):[]}l(Af,"loadBenchmarkResults");W();function Pf(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:")} ${If(s.totalScore,s.maxScore)} ${a.dim(`(${e}%)`)}`),console.log(` ${a.dim("Duration:")} ${t}s`),console.log(` ${a.dim("Tokens:")} ${Sn(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 ${Sn(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(Pf,"renderResult");function Of(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))}`+If(c.totalScore,c.maxScore).padEnd(20)+a.dim(((c.durationMs/1e3).toFixed(1)+"s").padEnd(10))+a.dim(Sn(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(Of,"renderComparison");function Mf(s){if(s.length===0)return`# No Results
581
+ `;let e=`# Benchmark Report: ${s[0].name}
582
+
583
+ `;e+=`Generated: ${new Date().toISOString()}
584
+
585
+ `,e+=`## Results
586
+
587
+ `,e+=`| Model | Score | Time | Tokens | Cost | Steps Passed |
588
+ `,e+=`|-------|-------|------|--------|------|--------------|
589
+ `;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 | ${Sn(o.tokensUsed)} | $${o.costUsd.toFixed(4)} | ${r}/${o.steps.length} |
590
+ `}e+=`
591
+ `;for(let o of s){e+=`### ${o.model}
592
+
593
+ `;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}
594
+ `,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${Sn(r.tokensUsed)}
595
+ `,e+=`- Files: ${r.filesChanged.join(", ")||"none"}
596
+
597
+ `}}return e}l(Mf,"generateMarkdownReport");function If(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(If,"colorScore");function Sn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Sn,"formatNum");async function jf(s,e){let t=si.resolve(s),o=e.workspace||process.cwd();if(!Ds.existsSync(t)){console.log(a.red(`Benchmark not found: ${t}`));return}let n=new oi(o),r=e.model||["capuchin-reason"],i=Xw(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)Xc(d);Of(u)}else{console.log(a.dim(`Running benchmark: ${c.name} with ${r[0]}...`));let u=await n.run(c,r[0]);Xc(u),Pf(u)}}l(jf,"benchmarkCustom");function Nf(s){let e=Af(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(Mf(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))+Qw(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(Nf,"benchmarkResults");function Xw(s,e){return Ds.statSync(s).isFile()?[e.loadSpec(s)]:Ds.readdirSync(s).filter(o=>o.endsWith(".yaml")||o.endsWith(".yml")).map(o=>e.loadSpec(si.join(s,o)))}l(Xw,"loadSpecs");function Qw(s){let e=parseInt(s);return e>=80?a.green(s):e>=50?a.yellow(s):a.red(s)}l(Qw,"colorScore");W();var Wf=y(require("node:readline"),1);var Bf=y(require("node:crypto"),1),Lf=require("node:events");Zs();var xn=class extends Lf.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=Bf.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 rt(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===rt.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===rt.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();oe();W();function Uf(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(`
598
+ `).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(Uf,"renderEvent");async function Hf(s){console.log(a.dim(`Joining session ${s}...`));let e=J();if(!(await Ae()||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 xn({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=>{Uf(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(`
599
+ 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=Wf.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(Hf,"joinSession");async function Gf(){let s=J();if(!(await Ae()||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 xn({relayUrl:s.platformUrl||"wss://api.monkeyscode.com",userName:t});o.on("participant_joined",n=>{console.log(a.green(`
600
+ \u2192 ${n} joined your session
601
+ `))}),o.on("participant_left",n=>{console.log(a.dim(`
602
+ \u2190 ${n} left your session
603
+ `))});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(Gf,"setupSharedSession");var Vf=y(require("node:http"),1);Zs();W();function qf(s,e="Design Preview"){return`
604
+ <!DOCTYPE html>
605
+ <html lang="en">
606
+ <head>
607
+ <meta charset="UTF-8">
608
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
609
+ <title>${e}</title>
610
+ <script src="https://cdn.tailwindcss.com"></script>
611
+ <style>
612
+ body { font-family: system-ui, -apple-system, sans-serif; }
613
+ .mc-preview-container {
614
+ display: flex;
615
+ justify-content: center;
616
+ align-items: center;
617
+ min-height: 100vh;
618
+ background: #f3f4f6;
619
+ padding: 2rem;
620
+ }
621
+ .mc-component-wrapper {
622
+ background: white;
623
+ border-radius: 12px;
624
+ box-shadow: 0 10px 25px rgba(0,0,0,0.1);
625
+ overflow: hidden;
626
+ resize: both;
627
+ max-width: 100%;
628
+ min-width: 320px;
629
+ min-height: 200px;
630
+ }
631
+ </style>
632
+ </head>
633
+ <body>
634
+ <div class="mc-preview-container">
635
+ <div class="mc-component-wrapper">
636
+ ${s}
637
+ </div>
638
+ </div>
639
+ <script>
640
+ // Setup WebSocket for live reload
641
+ const ws = new WebSocket('ws://localhost:__PORT__/ws');
642
+ ws.onmessage = (msg) => {
643
+ if (msg.data === 'reload') {
644
+ window.location.reload();
645
+ }
646
+ };
647
+ </script>
648
+ </body>
649
+ </html>
650
+ `.trim()}l(qf,"generateHtmlPreview");var Qc=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=Vf.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(qf(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new sc.default({server:this.server,path:"/ws"})}start(e=3030){this.port=e,this.server.listen(e,()=>{console.log(a.green(`\u{1F3A8} Design artboard live at http://localhost:${e}`))})}stop(){this.wss.close(),this.server.close()}updateDesign(e){this.currentHtml=e;for(let t of this.wss.clients)t.readyState===rt.OPEN&&t.send("reload")}},Jf=new Qc;W();function Zw(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(Zw,"formatDate");function ni(s){return s.substring(0,8)}l(ni,"formatShortId");function ek(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(ek,"truncatePath");function zf(){let e=new It().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")(ni(t.id)),n=ek(t.workspace),r=String(t.turnCount).padEnd(8),i=Zw(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(zf,"sessionsListCommand");function Kf(s){let e=new It,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 ${ni(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 ${ni(n.id)}`)),console.log("")}l(Kf,"sessionsShowCommand");function Yf(s){let e=new It,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 ${ni(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(Yf,"sessionsDeleteCommand");function Xf(s=30){let e=new It,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(Xf,"sessionsPruneCommand");tn();W();Q();oe();var Zc=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(tk):[]}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 Cn(){let s=J(),t=me()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new Zc(s.platformUrl,t)}l(Cn,"getClient");async function el(s){ok(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 Cn().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} (${sk(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(el,"scheduleCreate");async function Qf(){let e=await Cn().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(Qf,"scheduleList");async function Zf(s){let t=await Cn().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(Zf,"scheduleDelete");async function eg(s){let t=await Cn().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(eg,"schedulePause");async function tg(s){let t=await Cn().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(tg,"scheduleResume");function tk(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(tk,"parseSchedule");function ok(s){let e=s.trim().split(/\s+/);if(e.length!==5)return!1;let t=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return e.every(o=>t.test(o))}l(ok,"validateCron");function sk(s){let e=s.trim().split(/\s+/);if(e.length!==5)return s;let[t,o,n,r,i]=e;return s==="0 * * * *"?"every hour":s==="*/5 * * * *"?"every 5 minutes":s==="*/15 * * * *"?"every 15 minutes":s==="*/30 * * * *"?"every 30 minutes":t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i==="*"?`daily at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[i]||`day ${i}`}s at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:s}l(sk,"describeCron");Cc();vc();an();var ke=y(require("node:fs"),1),St=y(require("node:path"),1),Bo=require("node:child_process");W();Je();Q();oe();async function og(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=J(),n,r;if(s.pr?(n=await ak(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Bo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Bo.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Bo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes")),!n.trim()){console.log(a.dim(" No changes to review."));return}let i=nk(s.workspace),c=s.focus?s.focus.split(",").map(b=>b.trim()):[],u=rk(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new Se({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",b=>{b.type==="streaming_chunk"&&(p+=b.content,s.output==="text"&&process.stdout.write(b.content))});try{await d.run(u)}catch(b){console.error(a.red(` \u274C Review failed: ${b instanceof Error?b.message:b}`)),process.exit(1)}let f=ng(p);switch(s.output){case"json":{let b=new us;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let b=new ds(f,s.workspace);console.log(b.formatFindings(f));break}case"github":{for(let b of f){let k=b.severity==="high"?"error":b.severity==="medium"?"warning":"notice";console.log(`::${k} file=${b.file},line=${b.line}::${b.message}`)}break}case"text":default:f.length>0&&(console.log(""),rg(f));break}s.postComments&&s.pr&&await ck(s.pr,f,s.workspace),s.autoFix&&f.some(b=>b.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),ig(f,s.workspace));let m={high:3,medium:2,low:1,info:0},g=m[s.severityThreshold]||3;f.some(b=>(m[b.severity]||0)>=g)&&process.exit(1)}l(og,"reviewCommand");async function sg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=J(),n=St.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=lk(n,[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java"]):r=[n]:(console.error(a.red(` \u274C Target not found: ${s.target}`)),process.exit(4)),r.length===0){console.log(a.dim(" No source files found to scan."));return}console.log(""),console.log(a.bold(` \u{1F50D} Bug Finder \u2014 scanning ${r.length} file(s)`)),console.log(a.dim(` Model: ${s.model}`)),console.log("");let i=1e5,c="",u=[];for(let S of r){let C=ke.readFileSync(S,"utf8");if(c.length+C.length>i)break;let _=St.relative(s.workspace,S);c+=`
651
+ --- ${_} ---
652
+ ${C}
653
+ `,u.push(_)}let d=s.focus?s.focus.split(",").map(S=>S.trim()):[],p=ik(c,u,d),f=new Se({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),m="";f.on("event",S=>{S.type==="streaming_chunk"&&(m+=S.content)});try{await f.run(p)}catch(S){console.error(a.red(` \u274C Bug scan failed: ${S instanceof Error?S.message:S}`)),process.exit(1)}let g=ng(m);switch(s.output){case"json":console.log(JSON.stringify({scannedFiles:u,findings:g,summary:tl(g)},null,2));break;case"sarif":{let S=new ds(g,s.workspace);console.log(S.formatFindings(g));break}case"github":for(let S of g){let C=S.severity==="high"?"error":S.severity==="medium"?"warning":"notice";console.log(`::${C} file=${S.file},line=${S.line}::${S.message}`)}break;case"text":default:rg(g);break}s.autoFix&&g.some(S=>S.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),ig(g,s.workspace));let h={high:3,medium:2,low:1,info:0},b=h[s.severityThreshold]||3;g.some(S=>(h[S.severity]||0)>=b)&&process.exit(1)}l(sg,"bugfindCommand");function nk(s){let e=St.join(s,".monkeyscode","review-rules.md");return ke.existsSync(e)?ke.readFileSync(e,"utf8"):""}l(nk,"loadReviewRules");function rk(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.
654
+
655
+ For each finding, output in this EXACT format (one per line):
656
+ [SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
657
+
658
+ IMPORTANT: Only report real, actionable issues. Do NOT report style preferences or minor formatting.
659
+
660
+ `;return t.length>0&&(n+=`Focus areas: ${t.join(", ")}
661
+
662
+ `),o&&(n+=`Review rules:
663
+ ${o}
664
+
665
+ `),n+=`Diff:
666
+ \`\`\`diff
667
+ ${s}
668
+ \`\`\``,n}l(rk,"buildReviewPrompt");function ik(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.
669
+
670
+ For each finding, output in this EXACT format (one per line):
671
+ [SEVERITY:HIGH|MEDIUM|LOW] [FILE:path/to/file] [LINE:123] Description of the issue
672
+ [FIX:123] Suggested fix code (optional, one line)
673
+
674
+ Focus on:
675
+ - Security vulnerabilities (injection, XSS, path traversal, etc.)
676
+ - Race conditions and concurrency bugs
677
+ - Null/undefined dereferences
678
+ - Resource leaks
679
+ - Logic errors
680
+ - Performance issues (N+1 queries, unbounded loops)
681
+
682
+ `;return t.length>0&&(o+=`Additional focus areas: ${t.join(", ")}
683
+
684
+ `),o+=`Files to scan: ${e.join(", ")}
685
+
686
+ `,o+=`Source code:
687
+ ${s}`,o}l(ik,"buildBugfindPrompt");function ng(s){let e=[],t=s.split(`
688
+ `);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(ng,"parseFindings");function rg(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(` ${tl(s)}`),console.log("")}l(rg,"printFindingsTable");function tl(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(tl,"formatSeveritySummary");function ig(s,e){let t=0;for(let o of s){if(!o.fix)continue;let n=St.resolve(e,o.file);if(ke.existsSync(n))try{let r=ke.readFileSync(n,"utf8").split(`
689
+ `);o.line>0&&o.line<=r.length&&(r[o.line-1]=o.fix,ke.writeFileSync(n,r.join(`
690
+ `)),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(ig,"applyFixes");async function ak(s,e){let t=ag(e),o=cg();if(!o){console.log(a.dim(" No GitHub/GitLab token found. Using local git diff against main."));try{return(0,Bo.execSync)("git diff main...HEAD",{cwd:e,encoding:"utf8"})}catch{return(0,Bo.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(`
691
+ `)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(ak,"fetchPRDiff");async function ck(s,e,t){let o=ag(t),n=cg();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(`
692
+ `);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
693
+
694
+ ${r}
695
+
696
+ ${tl(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(ck,"postReviewComments");function ag(s){try{let e=(0,Bo.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(ag,"getGitRemote");function cg(){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=St.join(process.cwd(),".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}try{let s=St.join(process.env.HOME||process.env.USERPROFILE||"",".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}return null}l(cg,"getGitToken");function lk(s,e){let t=[];function n(r){if(t.length>=50)return;let i=ke.readdirSync(r,{withFileTypes:!0});for(let c of i){if(t.length>=50)return;let u=St.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(lk,"collectFiles");Wm();Tm();globalThis.__mcChalk=a;var rl="0.1.0",Uo="auto";function pg(s){let e=Oo(s);return{defaultModel:e.get("model"),defaultMode:e.get("defaultMode"),maxTokens:e.get("maxTokens")}}l(pg,"loadConfig");var q=new Dl;q.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
697
+ Runs independently of the IDE and Agent Manager.
698
+ Connects directly to model-proxy via SSE streaming.`).version(rl);q.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",Uo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Et("-o, --output <format>","Output format").choices(["text","json","jsonl","diff","markdown","github","azure","sarif","stream"]).default("text")).option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("--continue","Resume the last session",!1).option("--auto-approve","Auto-approve all tool calls",!1).option("--approve-for-me","Smart auto-approval (safe=auto, risky=prompt, dangerous=block)",!1).option("--yolo","Bypass all permission checks (requires explicit opt-in)",!1).addOption(new Et("--permission-mode <mode>","Permission mode").choices(["default","plan","ask","acceptEdits","bypassPermissions"]).default("default")).option("--allowed-tools <tools>","Comma-separated list of allowed tool names","").option("--denied-tools <tools>","Comma-separated list of denied tool names","").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new Et("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Et("--sandbox-provider <provider>","Sandbox provider override").choices(["auto","bubblewrap","sandbox-exec","docker","windows-sandbox"])).option("--no-hooks","Disable all lifecycle hooks").option("--hook-timeout <ms>","Hook timeout in milliseconds","10000").option("--no-web","Disable web search (air-gapped mode)").option("--auto-branch","Create a new branch for changes",!1).option("--auto-commit","Auto-commit changes after successful run",!1).option("--auto-pr","Create a pull request after background job completes",!1).option("--worktree","Run agent in an isolated git worktree",!1).option("--resume <job-id>","Resume from a completed cloud job").option("--profile <name>","Auth profile to use","default").option("--endpoint <url>","Custom model gateway URL").option("--ca-cert <path>","Custom CA certificate for corporate proxies").option("--offline","Offline mode \u2014 no internet, local models only",!1).option("--accessible","Screen reader-friendly output (no ANSI, no spinners)",!1).option("--screen-reader","Alias for --accessible",!1).option("--max-cost <dollars>","Maximum session cost in dollars (e.g. 2.00)").option("--max-tokens <count>","Maximum total tokens (input + output)").option("--timeout <ms>","Headless timeout in milliseconds (default: 300000)","300000").action(async(s,e)=>{let t=N.resolve(e.workspace),o=pg(t),n=s||e.prompt;if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=gt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await tm(c)});var _n=q.command("auth").description("Manage authentication");_n.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 ma(s.profile):s.email?await aa():await ia()});_n.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>fa(s.profile));_n.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>la(s,e.profile));_n.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await zn(s.profile));_n.command("refresh").description("Manually refresh the access token").action(async()=>await ua());q.command("status").description("Show account and agent status").action(async()=>{let s=pg(),e=new vo,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),o=t();e.printBanner("System Status"),await zn(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});q.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>Or(s));q.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Cm(s));q.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Im(s));q.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>jm(s,e));q.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";Gm({since:s.since,review:s.review,mode:e})});var En=q.command("config").description("Manage CLI configuration");En.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=N.resolve(t.workspace),n=Oo(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}]`)});En.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=Oo(N.resolve(e.workspace));if(s){let o=t.getResolved(s);console.log(` ${s} = ${JSON.stringify(o.value)} [${o.source}]`)}else console.log(JSON.stringify(t.getConfig(),null,2))});En.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=Oo(N.resolve(s.workspace));gm(e)});En.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{Oo().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});En.command("path").description("Show config file locations").action(()=>{let s=T(),t=Oo().getPaths();console.log(` Global: ${t.global}`),console.log(` Project: ${t.project}`),console.log(` Data: ${s.data}`),console.log(` Logs: ${s.logs}`),console.log(` PID: ${s.pidFile}`)});q.command("index [path]").description("Index a workspace for context retrieval").option("--force","Force full re-index",!1).action(async(s,e)=>{let t=N.resolve(s||"."),o=new vo;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new ao;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 Fn=q.command("mcp").description("Manage MCP (Model Context Protocol) servers");Fn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await im(N.resolve(s.workspace))});Fn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{am(N.resolve(o.workspace),s,e,t||[])});Fn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{cm(N.resolve(e.workspace),s)});Fn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await lm(N.resolve(e.workspace),s)});Fn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{um(s)});var kk=q.command("agents").description("View active agent sessions dashboard").action(async()=>{await Fc(!0)});kk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Fc(!1)});var vs=q.command("context").description("Semantic code search and workspace indexing");vs.command("index").description("Index the current workspace for semantic search").action(async()=>{await Io(["index"],{})});vs.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await Io(["search",s],{topK:e.topK})});vs.command("status").description("Show index status and statistics").action(async()=>{await Io(["status"],{})});vs.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await Io(["rebuild"],{})});vs.command("related <file>").description("Find files related to a given file").action(async s=>{await Io(["related",s],{})});vs.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await Io(["rank",s],{})});var Wo=q.command("triggers").description("Manage event-driven agent triggers");Wo.command("list").description("Show configured triggers").action(async()=>{await mo(["list"],{})});Wo.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 mo(["add"],s)});Wo.command("remove <name>").description("Remove a trigger by name").action(async s=>{await mo(["remove",s],{})});Wo.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await mo(["test",s],{})});Wo.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await mo(["enable",s],{})});Wo.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await mo(["disable",s],{})});Wo.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await mo(["serve"],{port:s.port})});q.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish, pwsh)").option("--install","Show install instructions instead of the script").action((s,e)=>{let t=["bash","zsh","fish","pwsh"];t.includes(s)||(console.error(` Invalid shell: ${s}. Supported: ${t.join(", ")}`),process.exit(1));let o=s;e.install?(console.log(""),console.log(sm(o)),console.log("")):console.log(om(o))});var ai=q.command("sessions").description("Manage saved conversation sessions");ai.command("list").description("List recent sessions").action(()=>zf());ai.command("show <id>").description("Show session details").action(s=>Kf(s));ai.command("delete <id>").description("Delete a session").action(s=>Yf(s));ai.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{Xf(parseInt(s.olderThan,10))});var Kt=q.command("jobs").description("Manage background agent jobs");Kt.command("list").description("List all background jobs").option("--status <status>","Filter by status: running, queued, completed, failed").option("--since <duration>","Show jobs since (e.g., 7d, 24h)").option("--limit <n>","Max results","20").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Oe(o.platformUrl,n.access_token),i=parseInt(s.limit,10),[c,u]=await Promise.all([r.list({status:s.status,since:s.since,limit:i}).catch(()=>[]),Promise.resolve(pc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);hc(d)});Kt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=mc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=fc(s);Ir(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Oe(o.platformUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);Ir(i,c)});Kt.command("logs <id>").description("Full log output of a job").option("--follow","Live tail logs",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Oe(n.platformUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))jr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(dg(),ug));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)jr(u)}});Kt.command("cancel <id>").description("Cancel a running or queued job").option("--force","Skip confirmation",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();if(r?.access_token||(console.error("Not authenticated."),process.exit(3)),!e.force){let d=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(f=>d.question(` Cancel job ${s}? [y/N] `,f));if(d.close(),p.toLowerCase()!=="y"){console.log(" Cancelled.");return}}let c=await new Oe(n.platformUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Kt.command("retry <id>").description("Retry a failed job").option("--model <model>","Use a different model").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Oe(n.platformUrl,r.access_token).retry(s,{model:e.model});c.success?(console.log(` \u{1F504} Job retried \u2192 new ID: ${c.jobId}`),c.branch&&console.log(` Branch: ${c.branch}`)):console.error(` \u274C Retry failed: ${c.error}`)});Kt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Oe(o.platformUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Kt.command("pull <id>").description("Pull changes from a completed job into current branch").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Oe(n.platformUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),gc(N.resolve(e.workspace),s,c.branch)});Kt.action(()=>{Kt.outputHelp()});var Lo=q.command("schedule").description("Manage scheduled/recurring agent jobs").argument("[prompt]","Task prompt (shorthand for `schedule create`)").option("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",Uo).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",".");Lo.action(async(s,e)=>{s&&e.cron?await el({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Lo.outputHelp()});Lo.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",Uo).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 el({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)})});Lo.command("list").description("List all scheduled jobs").action(async()=>{await Qf()});Lo.command("delete <id>").description("Delete a scheduled job").action(async s=>{await Zf(s)});Lo.command("pause <id>").description("Pause a scheduled job").action(async s=>{await eg(s)});Lo.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await tg(s)});var $n=q.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",Uo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");$n.action(async(s,e)=>{s.length>0?await Nr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):$n.outputHelp()});$n.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",Uo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Nr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});$n.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{Sc(N.resolve(s.workspace))});$n.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{xc(N.resolve(e.workspace),s)});var ii=q.command("worktrees").description("Manage git worktrees used by agent teams");ii.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=ms(N.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});ii.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=Wp({workspace:N.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});ii.action(()=>{ii.outputHelp()});var il=q.command("messages").description("Cross-session messaging");il.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new rn(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)});il.action(()=>{il.outputHelp()});var mg=q.command("hooks").description("Manage lifecycle hooks");mg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Tc(N.resolve(s.workspace))});mg.action(()=>{Tc(N.resolve("."))});var fg=q.command("models").description("Manage available models");fg.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();Sa(s?.org?.plan)});fg.action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();Sa(s?.org?.plan)});q.command("usage").description("Show monthly usage breakdown").action(async()=>{await hm()});q.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md"),o=N.join(e,".monkeyscode","config.json");if(z.existsSync(t)&&z.existsSync(o)){console.log(""),console.log(a.yellow(" \u26A0\uFE0F .monkeyscode/ already exists.")),console.log(a.dim(` ${t}`)),console.log(a.dim(` ${o}`)),console.log(" Use `mc memory` to modify rules, `mc config set` for config."),console.log("");return}console.log(""),console.log(a.bold(" \u{1F435} Initializing MonkeysCode")),console.log("");let n=["# Project Conventions",""],r=N.join(e,"package.json"),i=N.join(e,"Cargo.toml"),c=N.join(e,"pyproject.toml"),u=N.join(e,"tsconfig.json"),d=N.join(e,"go.mod"),p=z.readdirSync(e).filter(h=>h.endsWith(".csproj")),f="Unknown";if(z.existsSync(r))try{let h=JSON.parse(z.readFileSync(r,"utf8"));f=h.type==="module"?"TypeScript/ESM":"JavaScript/CJS",n.push(`## Language: ${f}`),h.scripts?.test&&n.push(`- Test command: \`${h.scripts.test}\``),h.scripts?.lint&&n.push(`- Lint command: \`${h.scripts.lint}\``),h.scripts?.build&&n.push(`- Build command: \`${h.scripts.build}\``),h.dependencies?.react&&n.push("- Framework: React"),h.dependencies?.next&&n.push("- Framework: Next.js"),h.dependencies?.express&&n.push("- Server: Express"),h.dependencies?.fastify&&n.push("- Server: Fastify"),n.push("")}catch{}z.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"),z.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),z.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),z.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(`
699
+ `),g=Math.ceil(m.length/4);g>2e3&&console.log(a.yellow(` \u26A0\uFE0F Rules file is ~${g} tokens. Consider keeping it under 2000 for optimal context usage.`)),z.mkdirSync(N.join(e,".monkeyscode"),{recursive:!0}),z.writeFileSync(t,m,"utf8"),z.existsSync(o)||z.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 Ss=q.command("memory").description("Manage project conventions and rules");Ss.command("show").description("Show resolved rules from all sources").option("--workspace <path>","Workspace path",".").action(s=>{let e=N.resolve(s.workspace),t=T(),o=N.join(e,".monkeyscode","rules.md"),n=N.join(t.config,"rules.md"),r=N.join(e,".monkeyscode","MEMORY.md");if(console.log(""),console.log(a.bold(" \u{1F4DD} Resolved Rules")),console.log(a.dim(" "+"\u2500".repeat(50))),z.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=z.readFileSync(o,"utf8");for(let u of i.split(`
700
+ `))console.log(` ${u}`);let c=Math.ceil(i.length/4);c>2e3&&console.log(a.yellow(`
701
+ \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(z.existsSync(n)){console.log(a.cyan(" [global]")+a.dim(` ${n}`));for(let i of z.readFileSync(n,"utf8").split(`
702
+ `))console.log(` ${i}`);console.log("")}if(z.existsSync(r)){console.log(a.magenta(" [memory]")+a.dim(` ${r}`));for(let i of z.readFileSync(r,"utf8").split(`
703
+ `))console.log(` ${i}`);console.log("")}console.log("")});Ss.command("add <rule>").description("Add a convention rule").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=N.resolve(e.workspace),o=N.join(t,".monkeyscode","rules.md");z.mkdirSync(N.dirname(o),{recursive:!0});let n=z.existsSync(o)?z.readFileSync(o,"utf8"):`# Project Conventions
704
+ `,r=s.replace(/^["']|["']$/g,"");z.writeFileSync(o,n.trimEnd()+`
705
+ - `+r+`
706
+ `,"utf8"),console.log(` \u2705 Added: ${r}`)});Ss.command("edit").description("Open rules in $EDITOR").option("--workspace <path>","Workspace path",".").action(s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md"),o=process.env.EDITOR||process.env.VISUAL||(process.platform==="win32"?"notepad":"vi");if(!z.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}`)}});Ss.command("forget <pattern>").description("Remove a learned convention matching the pattern").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=N.resolve(e.workspace),o=N.join(t,".monkeyscode","MEMORY.md"),n=N.join(t,".monkeyscode","rules.md"),r=0,i=s.replace(/^["']|["']$/g,"");for(let c of[o,n]){if(!z.existsSync(c))continue;let d=z.readFileSync(c,"utf8").split(`
707
+ `).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&z.writeFileSync(c,d.join(`
708
+ `),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});Ss.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 q.parseAsync(["node","mc","dream","--since",s.since,...s.review?["--review"]:[],"--workspace",s.workspace])});Ss.action(s=>{let e=process.cwd(),t=N.join(e,".monkeyscode","rules.md");if(z.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 z.readFileSync(t,"utf8").split(`
709
+ `))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});q.command("rules").description("Show resolved rules (alias for mc memory show)").option("--workspace <path>","Workspace path",".").action(s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md");if(z.existsSync(t)){console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules"));for(let o of z.readFileSync(t,"utf8").split(`
710
+ `))console.log(` ${o}`);console.log("")}else console.log(a.dim(" No rules file. Run: mc init"))});q.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 Et("-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 Et("--severity-threshold <level>","Minimum severity to fail CI").choices(["high","medium","low"]).default("high")).option("--model <model>","Model to use",Uo).option("--workspace <path>","Workspace path",".").action(async s=>{let e=gt(s.model);await og({workspace:N.resolve(s.workspace),model:e,staged:s.staged,pr:s.pr?parseInt(s.pr,10):void 0,focus:s.focus,output:s.output,postComments:s.postComments,suggest:s.suggest,autoFix:s.autoFix,severityThreshold:s.severityThreshold})});q.command("bugfind [target]").description("Scan files for potential bugs with severity ratings").addOption(new Et("-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 Et("--severity-threshold <level>","Minimum severity to fail CI").choices(["high","medium","low"]).default("high")).option("--model <model>","Model to use",Uo).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let t=gt(e.model);await sg({workspace:N.resolve(e.workspace),model:t,target:s||".",output:e.output,autoFix:e.autoFix,focus:e.focus,severityThreshold:e.severityThreshold})});var gg=q.command("trace").description("Inspect agent execution traces");gg.command("list").action(async s=>{df(s)});gg.command("show <id>").option("--tree").option("--flamegraph").option("--verbose").action(async(s,e)=>{pf(s,e)});var Ho=q.command("marketplace").description("Browse and manage agent skills");Ho.command("search <query>").option("--category <cat>").action(async(s,e)=>{await gf(s,e)});Ho.command("install <id>").action(async s=>{await hf(s)});Ho.command("uninstall <id>").action(async s=>{yf(s)});Ho.command("publish <dir>").option("--name <name>").option("--bump <bump>").action(async(s,e)=>{await bf(s,e)});Ho.command("update").action(async()=>{await wf()});Ho.command("list").action(()=>{kf()});Ho.command("featured").action(async()=>{await Df()});q.command("join <sessionId>").description("Join a live collaboration session").action(async s=>{await Hf(s)});q.command("share").description("Start a new live collaboration session").action(async()=>{await Gf()&&console.log(a.dim("Host session running..."))});var ci=q.command("permissions").description("Manage natural language policies");ci.command("set <text>").action(async s=>{await Ef(s)});ci.command("list").action(()=>{Ff()});ci.command("remove <index>").action(s=>{Tf(parseInt(s,10))});ci.command("test <tool> <args>").action((s,e)=>{Rf(s,e)});var hg=q.command("benchmark").description("Run agent benchmarks");hg.command("custom <path>").option("--model [models...]").option("--workspace <dir>").action(async(s,e)=>{await jf(s,e)});hg.command("results").option("--limit <n>").option("--format <fmt>").action(s=>{Nf(s)});q.command("design").description("Start the local design artboard server").option("--port <p>").action(s=>{Jf.start(s.port?parseInt(s.port,10):void 0)});Nm()&&process.argv.length<=2?Bm().then(()=>q.parse()).catch(()=>q.parse()):(km(rl),Om("cli_start",{version:rl}),q.parse(),process.on("beforeExit",()=>{Dm()}));