monkeyscode-cli 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/monkeyscode-cli.cjs +117 -115
- package/package.json +1 -1
package/dist/monkeyscode-cli.cjs
CHANGED
|
@@ -25,11 +25,11 @@ Expecting one of '${o.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
25
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 Bg(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=gl(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=gl(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
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=>jg(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
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 hl(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(hl,"incrementNodeInspectorPort");function _i(){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(_i,"useColor");Ei.Command=$i;Ei.useColor=_i});var Dl=ce(He=>{var{Argument:bl}=On(),{Command:Fi}=yl(),{CommanderError:Ug,InvalidArgumentError:wl}=Fs(),{Help:Wg}=wi(),{Option:kl}=Si();He.program=new Fi;He.createCommand=s=>new Fi(s);He.createOption=(s,e)=>new kl(s,e);He.createArgument=(s,e)=>new bl(s,e);He.Command=Fi;He.Option=kl;He.Argument=bl;He.Help=Wg;He.CommanderError=Ug;He.InvalidArgumentError=wl;He.InvalidOptionArgumentError=wl});function qg(){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=xl(),ne.color.ansi256=Cl(),ne.color.ansi16m=$l(),ne.bgColor.ansi=xl(10),ne.bgColor.ansi256=Cl(10),ne.bgColor.ansi16m=$l(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 xl,Cl,$l,ne,tD,Hg,Gg,oD,Vg,Ze,_l=H(()=>{xl=l((s=0)=>e=>`\x1B[${e+s}m`,"wrapAnsi16"),Cl=l((s=0)=>e=>`\x1B[${38+s};5;${e}m`,"wrapAnsi256"),$l=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]}},tD=Object.keys(ne.modifier),Hg=Object.keys(ne.color),Gg=Object.keys(ne.bgColor),oD=[...Hg,...Gg];l(qg,"assembleStyles");Vg=qg(),Ze=Vg});function Ge(s,e=globalThis.Deno?globalThis.Deno.args:jn.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
|
|
28
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function hl(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(hl,"incrementNodeInspectorPort");function _i(){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(_i,"useColor");Ei.Command=$i;Ei.useColor=_i});var Dl=ce(He=>{var{Argument:bl}=On(),{Command:Fi}=yl(),{CommanderError:Ug,InvalidArgumentError:wl}=Fs(),{Help:Wg}=wi(),{Option:kl}=Si();He.program=new Fi;He.createCommand=s=>new Fi(s);He.createOption=(s,e)=>new kl(s,e);He.createArgument=(s,e)=>new bl(s,e);He.Command=Fi;He.Option=kl;He.Argument=bl;He.Help=Wg;He.CommanderError=Ug;He.InvalidArgumentError=wl;He.InvalidOptionArgumentError=wl});function qg(){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=xl(),ne.color.ansi256=Cl(),ne.color.ansi16m=$l(),ne.bgColor.ansi=xl(10),ne.bgColor.ansi256=Cl(10),ne.bgColor.ansi16m=$l(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 xl,Cl,$l,ne,tD,Hg,Gg,oD,Vg,Ze,_l=H(()=>{xl=l((s=0)=>e=>`\x1B[${e+s}m`,"wrapAnsi16"),Cl=l((s=0)=>e=>`\x1B[${38+s};5;${e}m`,"wrapAnsi256"),$l=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]}},tD=Object.keys(ne.modifier),Hg=Object.keys(ne.color),Gg=Object.keys(ne.bgColor),oD=[...Hg,...Gg];l(qg,"assembleStyles");Vg=qg(),Ze=Vg});function Ge(s,e=globalThis.Deno?globalThis.Deno.args:jn.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 zg(){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 Jg(s){return s===0?!1:{level:s,hasBasic:!0,has256:s>=2,has16m:s>=3}}function Kg(s,{streamIsTTY:e,sniffFlags:t=!0}={}){let o=zg();o!==void 0&&(In=o);let n=t?In: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(jn.default.platform==="win32"){let i=Fl.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 El(s,e={}){let t=Kg(s,{streamIsTTY:s&&s.isTTY,...e});return Jg(t)}var jn,Fl,Ti,re,In,Yg,Tl,Rl=H(()=>{jn=y(require("node:process"),1),Fl=y(require("node:os"),1),Ti=y(require("node:tty"),1);l(Ge,"hasFlag");({env:re}=jn.default);Ge("no-color")||Ge("no-colors")||Ge("color=false")||Ge("color=never")?In=0:(Ge("color")||Ge("colors")||Ge("color=true")||Ge("color=always"))&&(In=1);l(zg,"envForceColor");l(Jg,"translateLevel");l(Kg,"_supportsColor");l(El,"createSupportsColor");Yg={stdout:El({isTTY:Ti.default.isatty(1)}),stderr:El({isTTY:Ti.default.isatty(2)})},Tl=Yg});function Al(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 Pl(s,e,t,o){let n=0,r="";do{let i=s[o-1]==="\r";r+=s.slice(n,i?o-1:o)+e+(i?`\r
|
|
29
29
|
`:`
|
|
30
30
|
`)+t,n=o+1,o=s.indexOf(`
|
|
31
|
-
`,n)}while(o!==-1);return r+=s.slice(n),r}var Ol=H(()=>{l(Al,"stringReplaceAll");l(Pl,"stringEncaseCRLFWithFirstIndex")});function Rs(s){return Qg(s)}var Ml,Il,Ri,
|
|
32
|
-
`);return r!==-1&&(e=Pl(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Rs.prototype,Vo);oh=Rs(),pD=Rs({level:Il?Il.level:0}),a=oh});var Hl=ce((RD,mh)=>{mh.exports={dots:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{interval:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{interval:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{interval:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{interval:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{interval:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{interval:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{interval:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{interval:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{interval:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{interval:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{interval:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{interval:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots8Bit:{interval:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},sand:{interval:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},pipe:{interval:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{interval:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{interval:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{interval:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","\xB0","O","o","."]},noise:{interval:100,frames:["\u2593","\u2592","\u2591"]},bounce:{interval:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{interval:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{interval:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{interval:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{interval:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{interval:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{interval:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{interval:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{interval:100,frames:["\u256B","\u256A"]},toggle:{interval:250,frames:["\u22B6","\u22B7"]},toggle2:{interval:80,frames:["\u25AB","\u25AA"]},toggle3:{interval:120,frames:["\u25A1","\u25A0"]},toggle4:{interval:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{interval:100,frames:["\u25AE","\u25AF"]},toggle6:{interval:300,frames:["\u101D","\u1040"]},toggle7:{interval:80,frames:["\u29BE","\u29BF"]},toggle8:{interval:100,frames:["\u25CD","\u25CC"]},toggle9:{interval:100,frames:["\u25C9","\u25CE"]},toggle10:{interval:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{interval:50,frames:["\u29C7","\u29C6"]},toggle12:{interval:120,frames:["\u2617","\u2616"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{interval:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{interval:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{interval:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{interval:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{interval:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u2764\uFE0F "]},clock:{interval:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{interval:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{interval:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{interval:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{interval:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{interval:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{interval:120,frames:["\u2590|\\____________\u258C","\u2590_|\\___________\u258C","\u2590__|\\__________\u258C","\u2590___|\\_________\u258C","\u2590____|\\________\u258C","\u2590_____|\\_______\u258C","\u2590______|\\______\u258C","\u2590_______|\\_____\u258C","\u2590________|\\____\u258C","\u2590_________|\\___\u258C","\u2590__________|\\__\u258C","\u2590___________|\\_\u258C","\u2590____________|\\\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{interval:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{interval:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{interval:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{interval:150,frames:["-","=","\u2261"]},betaWave:{interval:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{interval:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{interval:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{interval:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{interval:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{interval:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{interval:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{interval:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{interval:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{interval:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]}}});var Hi=ce((AD,ql)=>{"use strict";var Hn=Object.assign({},Hl()),Gl=Object.keys(Hn);Object.defineProperty(Hn,"random",{get(){let s=Math.floor(Math.random()*Gl.length),e=Gl[s];return Hn[e]}});ql.exports=Hn});var nu=ce((iv,su)=>{su.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var Do={};Te(Do,{detectPlatform:()=>De,ensureDir:()=>qn,getPlatformInfo:()=>xe,getPlatformPaths:()=>T,isLocalModel:()=>Mh,isUNCPath:()=>Ph,normalizePath:()=>Ah,resolveSymlinks:()=>Oh});function De(){switch(Ft.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function T(s){switch(s??De()){case"macos":{let t=Ft.homedir(),o=se.join(t,".monkeyscode");return{config:o,data:o,pidFile:se.join(o,"daemon.pid"),socketFile:se.join(o,"daemon.sock"),credentialBackend:"macOS Keychain",logs:se.join(o,"logs")}}case"linux":{let t=Ft.homedir(),o=process.env.XDG_CONFIG_HOME||se.join(t,".config"),n=process.env.XDG_DATA_HOME||se.join(t,".local","share"),r=process.env.XDG_STATE_HOME||se.join(t,".local","state"),i=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:Fh(s),supportsColor:Th(),supportsUnicode:Rh(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Fh(s){return s==="windows"?process.env.PSModulePath?"powershell":process.env.SHELL?se.basename(process.env.SHELL):"cmd":process.env.SHELL?se.basename(process.env.SHELL):"sh"}function Th(){return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:process.stdout.isTTY?process.env.WT_SESSION?!0:(process.env.TERM||"")!=="dumb":!1}function Rh(s){if(s==="windows")return!!(process.env.WT_SESSION||process.env.ConEmuPID);let e=process.env.LANG||process.env.LC_ALL||"";return e.includes("UTF-8")||e.includes("utf-8")||e.includes("UTF8")}function qn(s){ko.mkdirSync(s,{recursive:!0})}function Ah(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function Ph(s){return s.startsWith("\\\\")||s.startsWith("//")}function Oh(s){try{return ko.realpathSync(s)}catch{return s}}function Mh(s,e){if(s.startsWith("local:")||s.startsWith("ollama:"))return!0;if(e)try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}return!1}var Ft,se,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(Fh,"detectShell");l(Th,"detectColorSupport");l(Rh,"detectUnicodeSupport");l(qn,"ensureDir");l(Ah,"normalizePath");l(Ph,"isUNCPath");l(Oh,"resolveSymlinks");l(Mh,"isLocalModel")});function Uh(){if(process.env.NERD_FONT==="1"||process.env.MC_ICONS==="nerd")return!0;if(process.env.NERD_FONT==="0"||process.env.MC_ICONS==="unicode"||process.env.MC_ICONS==="ascii")return!1;let s=(process.env.TERM_PROGRAM||"").toLowerCase();return!!(["wezterm","kitty","alacritty","ghostty","rio","hyper"].some(t=>s.includes(t))||process.env.WT_SESSION||s==="vscode")}function j(){let s=xe(),e=process.env.NO_COLOR!==void 0,t=process.env.FORCE_COLOR!==void 0,o=!!process.stdout.isTTY,n=!!process.stdin.isTTY,r=o&&!e,i=r,c=!1,u=!1;if(t&&(r=!0,i=!0),r){let p=process.env.TERM||"",f=process.env.COLORTERM||"";(p.includes("256color")||p==="xterm-kitty"||f)&&(c=!0),(f==="truecolor"||f==="24bit")&&(u=!0),process.env.WT_SESSION&&(c=!0,u=!0)}let d=Uh();return{ansi:r,color16:i,color256:c,trueColor:u,unicode:s.supportsUnicode,nerdFont:d,emoji:s.supportsUnicode&&s.os!=="windows",columns:process.stdout.columns||80,rows:process.stdout.rows||24,interactive:n,stdoutTTY:o}}function W(s){let e=s??j();return e.nerdFont?Ih:e.unicode?jh:Nh}function Ve(s){return(s??j()).unicode?Lh:Bh}var Ih,jh,Nh,Lh,Bh,Ce=H(()=>{"use strict";X();Ih={file:"\uF0F6",folder:"\uF07B",tool:"\uF0AD",search:"\uF002",git:"\uE725",browser:"\uF0AC",mcp:"\uF1E6",web:"\uF0AC",success:"\uF058",error:"\uF057",warning:"\uF071",info:"\uF05A",spinner:"\u28FB",arrow:"\uF061",bullet:"\u25CF",checkmark:"\uF00C",cross:"\uF00D",lock:"\uF023",unlock:"\uF09C",message:"\uF075",rocket:"\uF135",thinking:"\uF0EB",terminal:"\uF120",edit:"\uF044",delete:"\uF1F8",add:"\uF055",cost:"\uF155",model:"\uF544",branch:"\uE725",hook:"\uF0C1",skill:"\uF0EB",sandbox:"\uF132",prompt:"\uF054"},jh={file:"\u25C7",folder:"\u25C6",tool:"\u2699",search:"\u25CE",git:"\u2325",browser:"\u25C9",mcp:"\u2299",web:"\u25C9",success:"\u2713",error:"\u2717",warning:"\u25B2",info:"\u25CF",spinner:"\u280B",arrow:"\u2192",bullet:"\u2022",checkmark:"\u2713",cross:"\u2717",lock:"\u25C6",unlock:"\u25C7",message:"\u25B8",rocket:"\u27EB",thinking:"\u25CC",terminal:"\u25B6",edit:"\u270E",delete:"\u2715",add:"+",cost:"$",model:"\u25C8",branch:"\u2442",hook:"\u27F3",skill:"\u2605",sandbox:"\u25C6",prompt:"\u276F"},Nh={file:"[F]",folder:"[D]",tool:"[T]",search:"[S]",git:"[G]",browser:"[W]",mcp:"[M]",web:"[W]",success:"[OK]",error:"[ERR]",warning:"[!]",info:"[i]",spinner:"|",arrow:"->",bullet:"*",checkmark:"+",cross:"x",lock:"[LOCKED]",unlock:"[OPEN]",message:"[MSG]",rocket:"[>>]",thinking:"[...]",terminal:"[$]",edit:"[E]",delete:"[-]",add:"[+]",cost:"[$]",model:"[M]",branch:"[B]",hook:"[H]",skill:"[S]",sandbox:"[S]",prompt:">"},Lh={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Bh={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(Uh,"detectNerdFont");l(j,"detectCapabilities");l(W,"getIcons");l(Ve,"getBoxChars")});function Kn(){if(mt)return mt;let s=process.platform;return s==="darwin"&&wu("security")?(mt=new ra,mt):s==="linux"&&wu("secret-tool")?(mt=new ia,mt):s==="win32"?(mt=new aa,mt):(mt=new ca,mt)}function wu(s){try{return(0,tt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function ku(s){return s.replace(/[\\"$`!]/g,"\\$&")}function ay(){try{if(process.platform==="linux")return pe.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,tt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${Ko.hostname()}-${Ko.userInfo().username}-${Ko.homedir()}`}var pe,Qt,Ko,Tt,tt,Xt,ra,ia,aa,ca,mt,Du=H(()=>{"use strict";pe=y(require("node:fs"),1),Qt=y(require("node:path"),1),Ko=y(require("node:os"),1),Tt=y(require("node:crypto"),1),tt=require("node:child_process");X();Xt="monkeyscode-cli",ra=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 "${ku(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,tt.execSync)(`security delete-generic-password -s "${Xt}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ia=class{static{l(this,"SecretToolStore")}get(e){try{return(0,tt.execSync)(`secret-tool lookup service "${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 "${ku(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{}}},aa=class{static{l(this,"WinCredStore")}get(e){try{let t=`${Xt}:${e}`,o=`
|
|
31
|
+
`,n)}while(o!==-1);return r+=s.slice(n),r}var Ol=H(()=>{l(Al,"stringReplaceAll");l(Pl,"stringEncaseCRLFWithFirstIndex")});function Rs(s){return Qg(s)}var Ml,Il,Ri,Vo,Ts,jl,zo,Xg,Qg,Ai,Zg,eh,Pi,Nn,th,oh,pD,a,U=H(()=>{_l();Rl();Ol();({stdout:Ml,stderr:Il}=Tl),Ri=Symbol("GENERATOR"),Vo=Symbol("STYLER"),Ts=Symbol("IS_EMPTY"),jl=["ansi","ansi","ansi256","ansi16m"],zo=Object.create(null),Xg=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=Ml?Ml.level:0;s.level=e.level===void 0?t:e.level},"applyOptions"),Qg=l(s=>{let e=l((...t)=>t.join(" "),"chalk");return Xg(e,s),Object.setPrototypeOf(e,Rs.prototype),e},"chalkFactory");l(Rs,"createChalk");Object.setPrototypeOf(Rs.prototype,Function.prototype);for(let[s,e]of Object.entries(Ze))zo[s]={get(){let t=Nn(this,Pi(e.open,e.close,this[Vo]),this[Ts]);return Object.defineProperty(this,s,{value:t}),t}};zo.visible={get(){let s=Nn(this,this[Vo],!0);return Object.defineProperty(this,"visible",{value:s}),s}};Ai=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"?Ai("rgb",e,t,...Ze.hexToRgb(...o)):Ze[t][s](...o),"getModelAnsi"),Zg=["rgb","hex","ansi256"];for(let s of Zg){zo[s]={get(){let{level:t}=this;return function(...o){let n=Pi(Ai(s,jl[t],"color",...o),Ze.color.close,this[Vo]);return Nn(this,n,this[Ts])}}};let e="bg"+s[0].toUpperCase()+s.slice(1);zo[e]={get(){let{level:t}=this;return function(...o){let n=Pi(Ai(s,jl[t],"bgColor",...o),Ze.bgColor.close,this[Vo]);return Nn(this,n,this[Ts])}}}}eh=Object.defineProperties(()=>{},{...zo,level:{enumerable:!0,get(){return this[Ri].level},set(s){this[Ri].level=s}}}),Pi=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"),Nn=l((s,e,t)=>{let o=l((...n)=>th(o,n.length===1?""+n[0]:n.join(" ")),"builder");return Object.setPrototypeOf(o,eh),o[Ri]=s,o[Vo]=e,o[Ts]=t,o},"createBuilder"),th=l((s,e)=>{if(s.level<=0||!e)return s[Ts]?"":e;let t=s[Vo];if(t===void 0)return e;let{openAll:o,closeAll:n}=t;if(e.includes("\x1B"))for(;t!==void 0;)e=Al(e,t.close,t.open),t=t.parent;let r=e.indexOf(`
|
|
32
|
+
`);return r!==-1&&(e=Pl(e,n,o,r)),o+e+n},"applyStyle");Object.defineProperties(Rs.prototype,zo);oh=Rs(),pD=Rs({level:Il?Il.level:0}),a=oh});var Hl=ce((RD,mh)=>{mh.exports={dots:{interval:80,frames:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]},dots2:{interval:80,frames:["\u28FE","\u28FD","\u28FB","\u28BF","\u287F","\u28DF","\u28EF","\u28F7"]},dots3:{interval:80,frames:["\u280B","\u2819","\u281A","\u281E","\u2816","\u2826","\u2834","\u2832","\u2833","\u2813"]},dots4:{interval:80,frames:["\u2804","\u2806","\u2807","\u280B","\u2819","\u2838","\u2830","\u2820","\u2830","\u2838","\u2819","\u280B","\u2807","\u2806"]},dots5:{interval:80,frames:["\u280B","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B"]},dots6:{interval:80,frames:["\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2834","\u2832","\u2812","\u2802","\u2802","\u2812","\u281A","\u2819","\u2809","\u2801"]},dots7:{interval:80,frames:["\u2808","\u2809","\u280B","\u2813","\u2812","\u2810","\u2810","\u2812","\u2816","\u2826","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808"]},dots8:{interval:80,frames:["\u2801","\u2801","\u2809","\u2819","\u281A","\u2812","\u2802","\u2802","\u2812","\u2832","\u2834","\u2824","\u2804","\u2804","\u2824","\u2820","\u2820","\u2824","\u2826","\u2816","\u2812","\u2810","\u2810","\u2812","\u2813","\u280B","\u2809","\u2808","\u2808"]},dots9:{interval:80,frames:["\u28B9","\u28BA","\u28BC","\u28F8","\u28C7","\u2867","\u2857","\u284F"]},dots10:{interval:80,frames:["\u2884","\u2882","\u2881","\u2841","\u2848","\u2850","\u2860"]},dots11:{interval:100,frames:["\u2801","\u2802","\u2804","\u2840","\u2880","\u2820","\u2810","\u2808"]},dots12:{interval:80,frames:["\u2880\u2800","\u2840\u2800","\u2804\u2800","\u2882\u2800","\u2842\u2800","\u2805\u2800","\u2883\u2800","\u2843\u2800","\u280D\u2800","\u288B\u2800","\u284B\u2800","\u280D\u2801","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2888\u2829","\u2840\u2899","\u2804\u2859","\u2882\u2829","\u2842\u2898","\u2805\u2858","\u2883\u2828","\u2843\u2890","\u280D\u2850","\u288B\u2820","\u284B\u2880","\u280D\u2841","\u288B\u2801","\u284B\u2801","\u280D\u2809","\u280B\u2809","\u280B\u2809","\u2809\u2819","\u2809\u2819","\u2809\u2829","\u2808\u2899","\u2808\u2859","\u2808\u2829","\u2800\u2899","\u2800\u2859","\u2800\u2829","\u2800\u2898","\u2800\u2858","\u2800\u2828","\u2800\u2890","\u2800\u2850","\u2800\u2820","\u2800\u2880","\u2800\u2840"]},dots13:{interval:80,frames:["\u28FC","\u28F9","\u28BB","\u283F","\u285F","\u28CF","\u28E7","\u28F6"]},dots8Bit:{interval:80,frames:["\u2800","\u2801","\u2802","\u2803","\u2804","\u2805","\u2806","\u2807","\u2840","\u2841","\u2842","\u2843","\u2844","\u2845","\u2846","\u2847","\u2808","\u2809","\u280A","\u280B","\u280C","\u280D","\u280E","\u280F","\u2848","\u2849","\u284A","\u284B","\u284C","\u284D","\u284E","\u284F","\u2810","\u2811","\u2812","\u2813","\u2814","\u2815","\u2816","\u2817","\u2850","\u2851","\u2852","\u2853","\u2854","\u2855","\u2856","\u2857","\u2818","\u2819","\u281A","\u281B","\u281C","\u281D","\u281E","\u281F","\u2858","\u2859","\u285A","\u285B","\u285C","\u285D","\u285E","\u285F","\u2820","\u2821","\u2822","\u2823","\u2824","\u2825","\u2826","\u2827","\u2860","\u2861","\u2862","\u2863","\u2864","\u2865","\u2866","\u2867","\u2828","\u2829","\u282A","\u282B","\u282C","\u282D","\u282E","\u282F","\u2868","\u2869","\u286A","\u286B","\u286C","\u286D","\u286E","\u286F","\u2830","\u2831","\u2832","\u2833","\u2834","\u2835","\u2836","\u2837","\u2870","\u2871","\u2872","\u2873","\u2874","\u2875","\u2876","\u2877","\u2838","\u2839","\u283A","\u283B","\u283C","\u283D","\u283E","\u283F","\u2878","\u2879","\u287A","\u287B","\u287C","\u287D","\u287E","\u287F","\u2880","\u2881","\u2882","\u2883","\u2884","\u2885","\u2886","\u2887","\u28C0","\u28C1","\u28C2","\u28C3","\u28C4","\u28C5","\u28C6","\u28C7","\u2888","\u2889","\u288A","\u288B","\u288C","\u288D","\u288E","\u288F","\u28C8","\u28C9","\u28CA","\u28CB","\u28CC","\u28CD","\u28CE","\u28CF","\u2890","\u2891","\u2892","\u2893","\u2894","\u2895","\u2896","\u2897","\u28D0","\u28D1","\u28D2","\u28D3","\u28D4","\u28D5","\u28D6","\u28D7","\u2898","\u2899","\u289A","\u289B","\u289C","\u289D","\u289E","\u289F","\u28D8","\u28D9","\u28DA","\u28DB","\u28DC","\u28DD","\u28DE","\u28DF","\u28A0","\u28A1","\u28A2","\u28A3","\u28A4","\u28A5","\u28A6","\u28A7","\u28E0","\u28E1","\u28E2","\u28E3","\u28E4","\u28E5","\u28E6","\u28E7","\u28A8","\u28A9","\u28AA","\u28AB","\u28AC","\u28AD","\u28AE","\u28AF","\u28E8","\u28E9","\u28EA","\u28EB","\u28EC","\u28ED","\u28EE","\u28EF","\u28B0","\u28B1","\u28B2","\u28B3","\u28B4","\u28B5","\u28B6","\u28B7","\u28F0","\u28F1","\u28F2","\u28F3","\u28F4","\u28F5","\u28F6","\u28F7","\u28B8","\u28B9","\u28BA","\u28BB","\u28BC","\u28BD","\u28BE","\u28BF","\u28F8","\u28F9","\u28FA","\u28FB","\u28FC","\u28FD","\u28FE","\u28FF"]},sand:{interval:80,frames:["\u2801","\u2802","\u2804","\u2840","\u2848","\u2850","\u2860","\u28C0","\u28C1","\u28C2","\u28C4","\u28CC","\u28D4","\u28E4","\u28E5","\u28E6","\u28EE","\u28F6","\u28F7","\u28FF","\u287F","\u283F","\u289F","\u281F","\u285B","\u281B","\u282B","\u288B","\u280B","\u280D","\u2849","\u2809","\u2811","\u2821","\u2881"]},line:{interval:130,frames:["-","\\","|","/"]},line2:{interval:100,frames:["\u2802","-","\u2013","\u2014","\u2013","-"]},pipe:{interval:100,frames:["\u2524","\u2518","\u2534","\u2514","\u251C","\u250C","\u252C","\u2510"]},simpleDots:{interval:400,frames:[". ",".. ","..."," "]},simpleDotsScrolling:{interval:200,frames:[". ",".. ","..."," .."," ."," "]},star:{interval:70,frames:["\u2736","\u2738","\u2739","\u273A","\u2739","\u2737"]},star2:{interval:80,frames:["+","x","*"]},flip:{interval:70,frames:["_","_","_","-","`","`","'","\xB4","-","_","_","_"]},hamburger:{interval:100,frames:["\u2631","\u2632","\u2634"]},growVertical:{interval:120,frames:["\u2581","\u2583","\u2584","\u2585","\u2586","\u2587","\u2586","\u2585","\u2584","\u2583"]},growHorizontal:{interval:120,frames:["\u258F","\u258E","\u258D","\u258C","\u258B","\u258A","\u2589","\u258A","\u258B","\u258C","\u258D","\u258E"]},balloon:{interval:140,frames:[" ",".","o","O","@","*"," "]},balloon2:{interval:120,frames:[".","o","O","\xB0","O","o","."]},noise:{interval:100,frames:["\u2593","\u2592","\u2591"]},bounce:{interval:120,frames:["\u2801","\u2802","\u2804","\u2802"]},boxBounce:{interval:120,frames:["\u2596","\u2598","\u259D","\u2597"]},boxBounce2:{interval:100,frames:["\u258C","\u2580","\u2590","\u2584"]},triangle:{interval:50,frames:["\u25E2","\u25E3","\u25E4","\u25E5"]},binary:{interval:80,frames:["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},arc:{interval:100,frames:["\u25DC","\u25E0","\u25DD","\u25DE","\u25E1","\u25DF"]},circle:{interval:120,frames:["\u25E1","\u2299","\u25E0"]},squareCorners:{interval:180,frames:["\u25F0","\u25F3","\u25F2","\u25F1"]},circleQuarters:{interval:120,frames:["\u25F4","\u25F7","\u25F6","\u25F5"]},circleHalves:{interval:50,frames:["\u25D0","\u25D3","\u25D1","\u25D2"]},squish:{interval:100,frames:["\u256B","\u256A"]},toggle:{interval:250,frames:["\u22B6","\u22B7"]},toggle2:{interval:80,frames:["\u25AB","\u25AA"]},toggle3:{interval:120,frames:["\u25A1","\u25A0"]},toggle4:{interval:100,frames:["\u25A0","\u25A1","\u25AA","\u25AB"]},toggle5:{interval:100,frames:["\u25AE","\u25AF"]},toggle6:{interval:300,frames:["\u101D","\u1040"]},toggle7:{interval:80,frames:["\u29BE","\u29BF"]},toggle8:{interval:100,frames:["\u25CD","\u25CC"]},toggle9:{interval:100,frames:["\u25C9","\u25CE"]},toggle10:{interval:100,frames:["\u3282","\u3280","\u3281"]},toggle11:{interval:50,frames:["\u29C7","\u29C6"]},toggle12:{interval:120,frames:["\u2617","\u2616"]},toggle13:{interval:80,frames:["=","*","-"]},arrow:{interval:100,frames:["\u2190","\u2196","\u2191","\u2197","\u2192","\u2198","\u2193","\u2199"]},arrow2:{interval:80,frames:["\u2B06\uFE0F ","\u2197\uFE0F ","\u27A1\uFE0F ","\u2198\uFE0F ","\u2B07\uFE0F ","\u2199\uFE0F ","\u2B05\uFE0F ","\u2196\uFE0F "]},arrow3:{interval:120,frames:["\u25B9\u25B9\u25B9\u25B9\u25B9","\u25B8\u25B9\u25B9\u25B9\u25B9","\u25B9\u25B8\u25B9\u25B9\u25B9","\u25B9\u25B9\u25B8\u25B9\u25B9","\u25B9\u25B9\u25B9\u25B8\u25B9","\u25B9\u25B9\u25B9\u25B9\u25B8"]},bouncingBar:{interval:80,frames:["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},bouncingBall:{interval:80,frames:["( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF)","( \u25CF )","( \u25CF )","( \u25CF )","( \u25CF )","(\u25CF )"]},smiley:{interval:200,frames:["\u{1F604} ","\u{1F61D} "]},monkey:{interval:300,frames:["\u{1F648} ","\u{1F648} ","\u{1F649} ","\u{1F64A} "]},hearts:{interval:100,frames:["\u{1F49B} ","\u{1F499} ","\u{1F49C} ","\u{1F49A} ","\u2764\uFE0F "]},clock:{interval:100,frames:["\u{1F55B} ","\u{1F550} ","\u{1F551} ","\u{1F552} ","\u{1F553} ","\u{1F554} ","\u{1F555} ","\u{1F556} ","\u{1F557} ","\u{1F558} ","\u{1F559} ","\u{1F55A} "]},earth:{interval:180,frames:["\u{1F30D} ","\u{1F30E} ","\u{1F30F} "]},material:{interval:17,frames:["\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581","\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"]},moon:{interval:80,frames:["\u{1F311} ","\u{1F312} ","\u{1F313} ","\u{1F314} ","\u{1F315} ","\u{1F316} ","\u{1F317} ","\u{1F318} "]},runner:{interval:140,frames:["\u{1F6B6} ","\u{1F3C3} "]},pong:{interval:80,frames:["\u2590\u2802 \u258C","\u2590\u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802\u258C","\u2590 \u2820\u258C","\u2590 \u2840\u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590 \u2820 \u258C","\u2590 \u2802 \u258C","\u2590 \u2808 \u258C","\u2590 \u2802 \u258C","\u2590 \u2820 \u258C","\u2590 \u2840 \u258C","\u2590\u2820 \u258C"]},shark:{interval:120,frames:["\u2590|\\____________\u258C","\u2590_|\\___________\u258C","\u2590__|\\__________\u258C","\u2590___|\\_________\u258C","\u2590____|\\________\u258C","\u2590_____|\\_______\u258C","\u2590______|\\______\u258C","\u2590_______|\\_____\u258C","\u2590________|\\____\u258C","\u2590_________|\\___\u258C","\u2590__________|\\__\u258C","\u2590___________|\\_\u258C","\u2590____________|\\\u258C","\u2590____________/|\u258C","\u2590___________/|_\u258C","\u2590__________/|__\u258C","\u2590_________/|___\u258C","\u2590________/|____\u258C","\u2590_______/|_____\u258C","\u2590______/|______\u258C","\u2590_____/|_______\u258C","\u2590____/|________\u258C","\u2590___/|_________\u258C","\u2590__/|__________\u258C","\u2590_/|___________\u258C","\u2590/|____________\u258C"]},dqpb:{interval:100,frames:["d","q","p","b"]},weather:{interval:100,frames:["\u2600\uFE0F ","\u2600\uFE0F ","\u2600\uFE0F ","\u{1F324} ","\u26C5\uFE0F ","\u{1F325} ","\u2601\uFE0F ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u26C8 ","\u{1F328} ","\u{1F327} ","\u{1F328} ","\u2601\uFE0F ","\u{1F325} ","\u26C5\uFE0F ","\u{1F324} ","\u2600\uFE0F ","\u2600\uFE0F "]},christmas:{interval:400,frames:["\u{1F332}","\u{1F384}"]},grenade:{interval:80,frames:["\u060C ","\u2032 "," \xB4 "," \u203E "," \u2E0C"," \u2E0A"," |"," \u204E"," \u2055"," \u0DF4 "," \u2053"," "," "," "]},point:{interval:125,frames:["\u2219\u2219\u2219","\u25CF\u2219\u2219","\u2219\u25CF\u2219","\u2219\u2219\u25CF","\u2219\u2219\u2219"]},layer:{interval:150,frames:["-","=","\u2261"]},betaWave:{interval:80,frames:["\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2","\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"]},fingerDance:{interval:160,frames:["\u{1F918} ","\u{1F91F} ","\u{1F596} ","\u270B ","\u{1F91A} ","\u{1F446} "]},fistBump:{interval:80,frames:["\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ","\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ","\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ","\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ","\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "]},soccerHeader:{interval:80,frames:[" \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ","\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "]},mindblown:{interval:160,frames:["\u{1F610} ","\u{1F610} ","\u{1F62E} ","\u{1F62E} ","\u{1F626} ","\u{1F626} ","\u{1F627} ","\u{1F627} ","\u{1F92F} ","\u{1F4A5} ","\u2728 ","\u3000 ","\u3000 ","\u3000 "]},speaker:{interval:160,frames:["\u{1F508} ","\u{1F509} ","\u{1F50A} ","\u{1F509} "]},orangePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} "]},bluePulse:{interval:100,frames:["\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},orangeBluePulse:{interval:100,frames:["\u{1F538} ","\u{1F536} ","\u{1F7E0} ","\u{1F7E0} ","\u{1F536} ","\u{1F539} ","\u{1F537} ","\u{1F535} ","\u{1F535} ","\u{1F537} "]},timeTravel:{interval:100,frames:["\u{1F55B} ","\u{1F55A} ","\u{1F559} ","\u{1F558} ","\u{1F557} ","\u{1F556} ","\u{1F555} ","\u{1F554} ","\u{1F553} ","\u{1F552} ","\u{1F551} ","\u{1F550} "]},aesthetic:{interval:80,frames:["\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1","\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0","\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"]},dwarfFortress:{interval:80,frames:[" \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A\u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 ","\u263A \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\u2588\xA3\xA3\xA3 "," \u263A \u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2588\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2593\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2592\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A\u2591\u2588\xA3\xA3\xA3 "," \u263A \u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2588\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2592\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A\u2591\xA3\xA3\xA3 "," \u263A \xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\xA3\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2593\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2592\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A\u2591\xA3\xA3 "," \u263A \xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\xA3\xA3 "," \u263A\u2593\xA3 "," \u263A\u2593\xA3 "," \u263A\u2592\xA3 "," \u263A\u2592\xA3 "," \u263A\u2591\xA3 "," \u263A\u2591\xA3 "," \u263A \xA3 "," \u263A\xA3 "," \u263A\xA3 "," \u263A\u2593 "," \u263A\u2593 "," \u263A\u2592 "," \u263A\u2592 "," \u263A\u2591 "," \u263A\u2591 "," \u263A "," \u263A &"," \u263A \u263C&"," \u263A \u263C &"," \u263A\u263C &"," \u263A\u263C & "," \u203C & "," \u263A & "," \u203C & "," \u263A & "," \u203C & "," \u263A & ","\u203C & "," & "," & "," & \u2591 "," & \u2592 "," & \u2593 "," & \xA3 "," & \u2591\xA3 "," & \u2592\xA3 "," & \u2593\xA3 "," & \xA3\xA3 "," & \u2591\xA3\xA3 "," & \u2592\xA3\xA3 ","& \u2593\xA3\xA3 ","& \xA3\xA3\xA3 "," \u2591\xA3\xA3\xA3 "," \u2592\xA3\xA3\xA3 "," \u2593\xA3\xA3\xA3 "," \u2588\xA3\xA3\xA3 "," \u2591\u2588\xA3\xA3\xA3 "," \u2592\u2588\xA3\xA3\xA3 "," \u2593\u2588\xA3\xA3\xA3 "," \u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2591\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2592\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2593\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "," \u2588\u2588\u2588\u2588\u2588\u2588\xA3\xA3\xA3 "]}}});var Hi=ce((AD,ql)=>{"use strict";var Hn=Object.assign({},Hl()),Gl=Object.keys(Hn);Object.defineProperty(Hn,"random",{get(){let s=Math.floor(Math.random()*Gl.length),e=Gl[s];return Hn[e]}});ql.exports=Hn});var nu=ce((iv,su)=>{su.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var vo={};Te(vo,{detectPlatform:()=>De,ensureDir:()=>qn,getPlatformInfo:()=>xe,getPlatformPaths:()=>T,isLocalModel:()=>Mh,isUNCPath:()=>Ph,normalizePath:()=>Ah,resolveSymlinks:()=>Oh});function De(){switch(Ft.platform()){case"darwin":return"macos";case"win32":return"windows";default:return"linux"}}function T(s){switch(s??De()){case"macos":{let t=Ft.homedir(),o=se.join(t,".monkeyscode");return{config:o,data:o,pidFile:se.join(o,"daemon.pid"),socketFile:se.join(o,"daemon.sock"),credentialBackend:"macOS Keychain",logs:se.join(o,"logs")}}case"linux":{let t=Ft.homedir(),o=process.env.XDG_CONFIG_HOME||se.join(t,".config"),n=process.env.XDG_DATA_HOME||se.join(t,".local","share"),r=process.env.XDG_STATE_HOME||se.join(t,".local","state"),i=Do.existsSync(o)?se.join(o,"monkeyscode"):se.join(t,".monkeyscode"),c=Do.existsSync(n)?se.join(n,"monkeyscode"):se.join(t,".monkeyscode");return{config:i,data:c,pidFile:se.join(r,"monkeyscode","daemon.pid"),socketFile:se.join(r,"monkeyscode","daemon.sock"),credentialBackend:"libsecret / gnome-keyring",logs:se.join(r,"monkeyscode","logs")}}case"windows":{let t=process.env.APPDATA||se.join(Ft.homedir(),"AppData","Roaming"),o=process.env.LOCALAPPDATA||se.join(Ft.homedir(),"AppData","Local");return{config:se.join(t,"monkeyscode"),data:se.join(o,"monkeyscode"),pidFile:se.join(o,"monkeyscode","daemon.pid"),socketFile:se.join(o,"monkeyscode","daemon.sock"),credentialBackend:"Windows Credential Manager",logs:se.join(o,"monkeyscode","logs")}}}}function xe(){let s=De();return{os:s,arch:Ft.arch(),shell:Fh(s),supportsColor:Th(),supportsUnicode:Rh(s),columns:process.stdout.columns||80,isTTY:!!process.stdin.isTTY,daemonBinary:s==="windows"?"monkeyscode-daemon.exe":"monkeyscode-daemon"}}function Fh(s){return s==="windows"?process.env.PSModulePath?"powershell":process.env.SHELL?se.basename(process.env.SHELL):"cmd":process.env.SHELL?se.basename(process.env.SHELL):"sh"}function Th(){return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:process.stdout.isTTY?process.env.WT_SESSION?!0:(process.env.TERM||"")!=="dumb":!1}function Rh(s){if(s==="windows")return!!(process.env.WT_SESSION||process.env.ConEmuPID);let e=process.env.LANG||process.env.LC_ALL||"";return e.includes("UTF-8")||e.includes("utf-8")||e.includes("UTF8")}function qn(s){Do.mkdirSync(s,{recursive:!0})}function Ah(s,e=!1){return e?s.startsWith("\\\\")?"//"+s.slice(2).replace(/\\\\/g,"/"):s.replace(/\\\\/g,"/"):se.normalize(s)}function Ph(s){return s.startsWith("\\\\")||s.startsWith("//")}function Oh(s){try{return Do.realpathSync(s)}catch{return s}}function Mh(s,e){if(s.startsWith("local:")||s.startsWith("ollama:"))return!0;if(e)try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="::1"}catch{return!1}return!1}var Ft,se,Do,X=H(()=>{"use strict";Ft=y(require("node:os"),1),se=y(require("node:path"),1),Do=y(require("node:fs"),1);l(De,"detectPlatform");l(T,"getPlatformPaths");l(xe,"getPlatformInfo");l(Fh,"detectShell");l(Th,"detectColorSupport");l(Rh,"detectUnicodeSupport");l(qn,"ensureDir");l(Ah,"normalizePath");l(Ph,"isUNCPath");l(Oh,"resolveSymlinks");l(Mh,"isLocalModel")});function Uh(){if(process.env.NERD_FONT==="1"||process.env.MC_ICONS==="nerd")return!0;if(process.env.NERD_FONT==="0"||process.env.MC_ICONS==="unicode"||process.env.MC_ICONS==="ascii")return!1;let s=(process.env.TERM_PROGRAM||"").toLowerCase();return!!(["wezterm","kitty","alacritty","ghostty","rio","hyper"].some(t=>s.includes(t))||process.env.WT_SESSION||s==="vscode")}function j(){let s=xe(),e=process.env.NO_COLOR!==void 0,t=process.env.FORCE_COLOR!==void 0,o=!!process.stdout.isTTY,n=!!process.stdin.isTTY,r=o&&!e,i=r,c=!1,u=!1;if(t&&(r=!0,i=!0),r){let p=process.env.TERM||"",f=process.env.COLORTERM||"";(p.includes("256color")||p==="xterm-kitty"||f)&&(c=!0),(f==="truecolor"||f==="24bit")&&(u=!0),process.env.WT_SESSION&&(c=!0,u=!0)}let d=Uh();return{ansi:r,color16:i,color256:c,trueColor:u,unicode:s.supportsUnicode,nerdFont:d,emoji:s.supportsUnicode&&s.os!=="windows",columns:process.stdout.columns||80,rows:process.stdout.rows||24,interactive:n,stdoutTTY:o}}function W(s){let e=s??j();return e.nerdFont?Ih:e.unicode?jh:Nh}function Ve(s){return(s??j()).unicode?Lh:Bh}var Ih,jh,Nh,Lh,Bh,Ce=H(()=>{"use strict";X();Ih={file:"\uF0F6",folder:"\uF07B",tool:"\uF0AD",search:"\uF002",git:"\uE725",browser:"\uF0AC",mcp:"\uF1E6",web:"\uF0AC",success:"\uF058",error:"\uF057",warning:"\uF071",info:"\uF05A",spinner:"\u28FB",arrow:"\uF061",bullet:"\u25CF",checkmark:"\uF00C",cross:"\uF00D",lock:"\uF023",unlock:"\uF09C",message:"\uF075",rocket:"\uF135",thinking:"\uF0EB",terminal:"\uF120",edit:"\uF044",delete:"\uF1F8",add:"\uF055",cost:"\uF155",model:"\uF544",branch:"\uE725",hook:"\uF0C1",skill:"\uF0EB",sandbox:"\uF132",prompt:"\uF054"},jh={file:"\u25C7",folder:"\u25C6",tool:"\u2699",search:"\u25CE",git:"\u2325",browser:"\u25C9",mcp:"\u2299",web:"\u25C9",success:"\u2713",error:"\u2717",warning:"\u25B2",info:"\u25CF",spinner:"\u280B",arrow:"\u2192",bullet:"\u2022",checkmark:"\u2713",cross:"\u2717",lock:"\u25C6",unlock:"\u25C7",message:"\u25B8",rocket:"\u27EB",thinking:"\u25CC",terminal:"\u25B6",edit:"\u270E",delete:"\u2715",add:"+",cost:"$",model:"\u25C8",branch:"\u2442",hook:"\u27F3",skill:"\u2605",sandbox:"\u25C6",prompt:"\u276F"},Nh={file:"[F]",folder:"[D]",tool:"[T]",search:"[S]",git:"[G]",browser:"[W]",mcp:"[M]",web:"[W]",success:"[OK]",error:"[ERR]",warning:"[!]",info:"[i]",spinner:"|",arrow:"->",bullet:"*",checkmark:"+",cross:"x",lock:"[LOCKED]",unlock:"[OPEN]",message:"[MSG]",rocket:"[>>]",thinking:"[...]",terminal:"[$]",edit:"[E]",delete:"[-]",add:"[+]",cost:"[$]",model:"[M]",branch:"[B]",hook:"[H]",skill:"[S]",sandbox:"[S]",prompt:">"},Lh={topLeft:"\u256D",topRight:"\u256E",bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",vertical:"\u2502",separator:"\u2501",teeRight:"\u251C",teeLeft:"\u2524"},Bh={topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|",separator:"=",teeRight:"+",teeLeft:"+"};l(Uh,"detectNerdFont");l(j,"detectCapabilities");l(W,"getIcons");l(Ve,"getBoxChars")});function Kn(){if(mt)return mt;let s=process.platform;return s==="darwin"&&wu("security")?(mt=new ra,mt):s==="linux"&&wu("secret-tool")?(mt=new ia,mt):s==="win32"?(mt=new aa,mt):(mt=new ca,mt)}function wu(s){try{return(0,tt.execSync)(`command -v ${s} 2>/dev/null || which ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}function ku(s){return s.replace(/[\\"$`!]/g,"\\$&")}function ay(){try{if(process.platform==="linux")return pe.readFileSync("/etc/machine-id","utf8").trim();if(process.platform==="darwin"){let e=(0,tt.execSync)("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf8"}).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/);if(e)return e[1]}}catch{}return`${Ko.hostname()}-${Ko.userInfo().username}-${Ko.homedir()}`}var pe,Zt,Ko,Rt,tt,Qt,ra,ia,aa,ca,mt,Du=H(()=>{"use strict";pe=y(require("node:fs"),1),Zt=y(require("node:path"),1),Ko=y(require("node:os"),1),Rt=y(require("node:crypto"),1),tt=require("node:child_process");X();Qt="monkeyscode-cli",ra=class{static{l(this,"KeychainStore")}get(e){try{return(0,tt.execSync)(`security find-generic-password -s "${Qt}" -a "${e}" -w 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){this.delete(e);try{(0,tt.execSync)(`security add-generic-password -s "${Qt}" -a "${e}" -w "${ku(t)}" -U`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential in macOS Keychain")}}delete(e){try{(0,tt.execSync)(`security delete-generic-password -s "${Qt}" -a "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},ia=class{static{l(this,"SecretToolStore")}get(e){try{return(0,tt.execSync)(`secret-tool lookup service "${Qt}" account "${e}" 2>/dev/null`,{stdio:["pipe","pipe","pipe"],encoding:"utf8"}).trim()||null}catch{return null}}set(e,t){try{(0,tt.execSync)(`echo -n "${ku(t)}" | secret-tool store --label="${Qt}:${e}" service "${Qt}" account "${e}"`,{stdio:"pipe"})}catch{throw new Error("Failed to store credential via secret-tool (libsecret)")}}delete(e){try{(0,tt.execSync)(`secret-tool clear service "${Qt}" account "${e}" 2>/dev/null`,{stdio:"pipe"})}catch{}}},aa=class{static{l(this,"WinCredStore")}get(e){try{let t=`${Qt}:${e}`,o=`
|
|
33
33
|
$cred = cmdkey /list:${t} 2>$null;
|
|
34
34
|
if ($LASTEXITCODE -eq 0) {
|
|
35
35
|
# cmdkey can't read passwords. Use CredRead via .NET
|
|
@@ -38,11 +38,11 @@ Expecting one of '${o.join("', '")}'`);let n=`${e}Help`;return this.on(n,r=>{let
|
|
|
38
38
|
$result = [AdvApi32]::CredRead("${t}", 1, 0, [ref]$credPtr);
|
|
39
39
|
# Fallback: read from encrypted file
|
|
40
40
|
}
|
|
41
|
-
`;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{pe.existsSync(t)&&pe.unlinkSync(t)}catch{}}getFilePath(e){let t=T();return
|
|
42
|
-
${p}`)}let n=await o.json(),r=n.user_code||"\u2014",i=n.verification_uri;console.log(t?` ${e.info} Open this URL in your browser:`:" Open this URL in your browser:"),console.log(""),console.log(t?` ${a.underline.cyan(i)}`:` ${i}`),console.log(""),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 cy(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 fa(f.access_token),g=Date.now()+(f.expires_in||172800)*1e3;Yo({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 ua(){let s=j(),e=W(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Email Login"):" Email Login"),console.log(t?a.dim(` API: ${Re}`):` API: ${Re}`),console.log("");let o=vu.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 ly(" 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 fa(u.access_token),p=Date.now()+(u.expires_in||172800)*1e3;Yo({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 da(){let s=W(),e=T(),t=
|
|
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 Yo({...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 Yo(s,e){let t=e||s.profile||"default",o=`${Su}-${t}`;try{Kn().set(o,JSON.stringify({...s,profile:t}))}catch{let n=T();$e.mkdirSync(n.config,{recursive:!0});let r=t==="default"?
|
|
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 ha(s){let e=j(),t=W(e),o=e.ansi,n=T(),r=
|
|
45
|
-
`);o=i.pop();for(let c of i){let u=c.trim();if(!(!u||u.startsWith(":"))&&u.startsWith("data: ")){let d=u.slice(6).trim();if(d==="[DONE]")return;try{yield JSON.parse(d)}catch{}}}}if(o.trim()){let n=o.trim();if(n.startsWith("data: ")){let r=n.slice(6).trim();if(r!=="[DONE]")try{yield JSON.parse(r)}catch{}}}}finally{e.releaseLock()}}var Xn,Cu=H(()=>{"use strict";l(xu,"parseSSEStream");Xn=class{static{l(this,"ToolCallAccumulator")}_calls=new Map;feed(e){for(let t of e){let o=this._calls.get(t.index);t.id&&t.function?.name?this._calls.set(t.index,{id:t.id,name:t.function.name,arguments:t.function.arguments||""}):o&&t.function?.arguments&&(o.arguments+=t.function.arguments)}}flush(){let e=Array.from(this._calls.values());return this._calls.clear(),e}get hasPending(){return this._calls.size>0}}});function _u(s=!0){return s?$u:$u.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var $u,Eu=H(()=>{"use strict";$u=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files longer than 2000 lines are truncated (head + tail) by default \u2014 use start_line/end_line to read a specific range, or full:true to read everything. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(_u,"getToolSchemas")});var ve={};Te(ve,{getSetting:()=>dy,loadSettings:()=>J,saveSettings:()=>uy});function J(){let s=T(),e=ba.join(s.config,"settings.json");try{if(Zt.existsSync(e)){let t=JSON.parse(Zt.readFileSync(e,"utf8"));return{...Fu,...t}}}catch{}return{...Fu}}function uy(s){let e=T();Zt.mkdirSync(e.config,{recursive:!0});let t=ba.join(e.config,"settings.json"),n={...J(),...s};Zt.writeFileSync(t,JSON.stringify(n,null,2))}function dy(s){return J()[s]}var Zt,ba,Fu,Q=H(()=>{"use strict";Zt=y(require("node:fs"),1),ba=y(require("node:path"),1);X();Fu={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(J,"loadSettings");l(uy,"saveSettings");l(dy,"getSetting")});var L,le,Ne,wa,py,Qn,Tu=H(()=>{"use strict";L=y(require("node:fs"),1),le=y(require("node:path"),1),Ne=require("node:child_process"),wa=require("node:fs"),py={write_file:"create_file",list_files:"list_dir",list_directory:"list_dir",search_code:"grep_search",execute_command:"run_command",view_file:"read_file",str_replace:"replace_in_file",str_replace_editor:"replace_in_file",str_replace_based_edit_tool:"replace_in_file",bash:"run_command",bash_tool:"run_command",shell:"run_command",terminal:"run_command",text_editor:"edit_file",apply_patch:"patch_file",container_exec:"run_command",file_search:"search_files",codebase_search:"grep_search",semantic_search:"grep_search",grep:"grep_search",ripgrep:"grep_search",find_files:"search_files",glob:"search_files",glob_file_search:"search_files",ls:"list_dir",read:"read_file",cat:"read_file",write:"create_file",edit:"edit_file",multi_edit:"edit_file",search_replace:"replace_in_file",run_terminal_cmd:"run_command",run_in_terminal:"run_command",web_fetch:"read_url",fetch_webpage:"read_url",search_web:"web_search",google_search:"web_search",move_file:"rename_file",remove_file:"delete_file",task:"spawn_subagent",subagent:"spawn_subagent"},Qn=class{static{l(this,"ToolExecutor")}workspace;platformUrl;token;signal;_checkpoints=new Map;_runId="";_mcpClient;_sandbox;constructor(e){this.workspace=e.workspace,this.platformUrl=e.platformUrl,this.token=e.token,this.signal=e.signal}setRunId(e){this._runId=e,this._checkpoints.clear()}setMCPClient(e){this._mcpClient=e}setSandbox(e){this._sandbox=e}async execute(e,t){let o=py[e]||e;switch(o){case"read_file":return this.readFile(t);case"create_file":return this.createFile(t);case"edit_file":return this.editFile(t);case"delete_file":return this.deleteFile(t);case"rename_file":return this.renameFile(t);case"list_dir":return this.listDir(t);case"grep_search":return this.grepSearch(t);case"glob_files":return this.globFiles(t);case"search_files":return this.searchFiles(t);case"replace_in_file":return this.replaceInFile(t);case"patch_file":return this.patchFile(t);case"run_command":return this.runCommand(t);case"run_tests":return this.runTests(t);case"web_search":return this.webSearch(t);case"read_url":return this.readUrl(t);case"git_status":return this.gitExec("status",t);case"git_diff":return this.gitDiff(t);case"git_log":return this.gitLog(t);case"git_commit":return this.gitCommit(t);case"git_stash":return this.gitExec("stash",t);case"git_stash_pop":return this.gitExec("stash pop",t);case"todo_write":return this.todoWrite(t);case"spawn_subagent":return this.spawnSubagent(t);case"remember":return this.remember(t);default:return o.startsWith("mcp_")&&this._mcpClient?this._executeMCPTool(o,t):{output:`Unknown tool: ${e}. Use one of: read_file, create_file, edit_file, replace_in_file, patch_file, run_command, run_tests, grep_search, search_files, list_dir, git_status, git_commit, web_search, read_url, ask_user, todo_write, spawn_subagent, remember, or mcp_<server>_<tool>`}}}getCheckpoints(){return this._checkpoints}readFile(e){let t=this.resolve(e.path);if(!L.existsSync(t))return{output:`Error: File not found: ${e.path}`};if(L.statSync(t).isDirectory())return{output:`Error: ${e.path} is a directory. Use list_dir instead.`};let r=L.readFileSync(t,"utf8").split(`
|
|
41
|
+
`;return this.getDpapi(e)}catch{return null}}set(e,t){this.setDpapi(e,t)}delete(e){let t=this.getFilePath(e);try{pe.existsSync(t)&&pe.unlinkSync(t)}catch{}}getFilePath(e){let t=T();return Zt.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(Zt.dirname(o),{recursive:!0}),pe.writeFileSync(o,n.trim(),{mode:384})}catch{throw new Error("Failed to encrypt credential via DPAPI")}}},ca=class{static{l(this,"EncryptedFileStore")}keyPath;storePath;constructor(){let e=T();this.keyPath=Zt.join(e.config,".cred-key"),this.storePath=Zt.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=ay(),t=Rt.randomBytes(16),o=Rt.scryptSync(e,t,32),n=t.toString("hex")+":"+o.toString("hex");return pe.mkdirSync(Zt.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=Rt.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=Rt.randomBytes(16),n=Rt.createCipheriv("aes-256-cbc",t,o),r=n.update(JSON.stringify(e),"utf8","hex");r+=n.final("hex"),pe.mkdirSync(Zt.dirname(this.storePath),{recursive:!0}),pe.writeFileSync(this.storePath,o.toString("hex")+":"+r,{mode:384})}},mt=null;l(Kn,"getCredentialStore");l(wu,"hasCommand");l(ku,"escapeShellArg");l(ay,"getMachineId")});var ge={};Te(ge,{authLogin:()=>la,authLoginEmail:()=>ua,authLoginSSO:()=>ha,authLogout:()=>da,authLogoutProfile:()=>ya,authRefresh:()=>ma,authSetToken:()=>pa,authStatus:()=>Yn,getAccessToken:()=>Ae,isAuthenticated:()=>ga,loadAuth:()=>me});async function la(){let s=j(),e=W(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Device Authentication"):" Device Authentication"),console.log(t?a.dim(` API: ${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 cy(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 fa(f.access_token),g=Date.now()+(f.expires_in||172800)*1e3;Yo({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 ua(){let s=j(),e=W(s),t=s.ansi;console.log(""),console.log(t?a.bold(" \u{1F510} Email Login"):" Email Login"),console.log(t?a.dim(` API: ${Re}`):` API: ${Re}`),console.log("");let o=vu.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 ly(" 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 fa(u.access_token),p=Date.now()+(u.expires_in||172800)*1e3;Yo({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 da(){let s=W(),e=T(),t=At.join(e.config,"auth.json");$e.existsSync(t)&&$e.unlinkSync(t),console.log(` ${s.success} Logged out.`),console.log("")}function pa(s,e){let t=W();Yo({access_token:s,auth_method:"apikey",profile:e},e),console.log(` ${t.success} Token saved${e?` (profile: ${e})`:""}.`),console.log("")}async function Yn(s){let e=j(),t=W(e),o=e.ansi,n=me(s);if(console.log(""),n){let r=n.auth_method||"unknown",i={oauth:"\u{1F510} OAuth (browser)",apikey:"\u{1F511} API Key",email:"\u{1F4E7} Email/Password",sso:"\u{1F3E2} Enterprise SSO",env:"\u{1F30D} Environment Variable",unknown:"\u2753 Unknown"};if(console.log(` Auth: ${t.success} logged in`),console.log(` Method: ${i[r]||r}`),s&&s!=="default"&&console.log(` Profile: ${s}`),n.user?.email&&console.log(` User: ${n.user.email}`),n.user?.name&&console.log(` Name: ${n.user.name}`),n.org?.name&&console.log(` Org: ${n.org.name} (${n.org.plan||"free"})`),n.expires_at){let u=n.expires_at-Date.now();if(u>0){let d=Math.floor(u/36e5),p=Math.floor(d/24),f=p>0?`${p}d ${d%24}h`:`${d}h`;console.log(o?a.dim(` Expires: ${f}`):` Expires: ${f}`)}else console.log(o?a.yellow(` ${t.warning} Token expired \u2014 run: mc auth refresh`):` ${t.warning} Token expired`)}try{let u=await 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 ma(){let s=j(),e=W(s),t=me();if(!t?.refresh_token){console.log(` ${e.error} No refresh token found. Run: mc auth login`);return}console.log(" Refreshing token...");try{let o=await fetch(`${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;Yo({...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 fa(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=`${Su}-${t}`;try{let c=Kn().get(o);if(c)return JSON.parse(c)}catch{}let n=T(),r=t==="default"?At.join(n.config,"auth.json"):At.join(n.config,`auth-${t}.json`);try{if($e.existsSync(r)){let i=JSON.parse($e.readFileSync(r,"utf8"));try{Kn().set(o,JSON.stringify(i)),$e.unlinkSync(r)}catch{}return i}}catch{}return null}function ga(){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 Yo({...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 Yo(s,e){let t=e||s.profile||"default",o=`${Su}-${t}`;try{Kn().set(o,JSON.stringify({...s,profile:t}))}catch{let n=T();$e.mkdirSync(n.config,{recursive:!0});let r=t==="default"?At.join(n.config,"auth.json"):At.join(n.config,`auth-${t}.json`);$e.writeFileSync(r,JSON.stringify({...s,profile:t},null,2),{mode:384})}}function cy(s){return new Promise(e=>setTimeout(e,s))}function ly(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 ha(s){let e=j(),t=W(e),o=e.ansi,n=T(),r=At.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:v}=await import("node:child_process"),x=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";v(`${x} "${g.toString()}"`)}catch{}let{createServer:h}=await import("node:http"),k=await new Promise(v=>{let x=h((_,C)=>{let E=new URL(_.url||"/",`http://localhost:${p}`);if(E.pathname==="/callback"){let I=E.searchParams.get("code");if(E.searchParams.get("state")!==m){C.writeHead(400,{"Content-Type":"text/html"}),C.end("<html><body><h2>\u274C State mismatch. Please try again.</h2></body></html>"),x.close(),v(null);return}C.writeHead(200,{"Content-Type":"text/html"}),C.end("<html><body><h2>\u2705 Authentication successful!</h2><p>You can close this tab.</p></body></html>"),x.close(),v(I)}else C.writeHead(404),C.end()});x.listen(p,()=>{console.log(o?a.dim(` Listening on http://localhost:${p}/callback ...`):` Listening on http://localhost:${p}/callback ...`)}),setTimeout(()=>{x.close(),v(null)},3e5)});if(!k){console.log(` ${t.error} SSO login failed or timed out.`),console.log("");return}try{let v=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(!v.ok)throw new Error(`Token exchange failed: HTTP ${v.status}`);let x=await v.json(),_=await fa(x.access_token),C=Date.now()+(x.expires_in||172800)*1e3;Yo({access_token:x.access_token,refresh_token:x.refresh_token,expires_at:C,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(v){console.error(` ${t.error} SSO token exchange failed: ${v instanceof Error?v.message:v}`),console.log("")}}function ya(s){let e=W(),t=T(),o=s||"default",n=o==="default"?At.join(t.config,"auth.json"):At.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,At,vu,Re,Su,oe=H(()=>{"use strict";$e=y(require("node:fs"),1),At=y(require("node:path"),1),vu=y(require("node:readline"),1);U();X();Ce();Du();Re=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com",Su="auth";l(la,"authLogin");l(ua,"authLoginEmail");l(da,"authLogout");l(pa,"authSetToken");l(Yn,"authStatus");l(ma,"authRefresh");l(fa,"fetchProfile");l(me,"loadAuth");l(ga,"isAuthenticated");l(Ae,"getAccessToken");l(Yo,"saveAuth");l(cy,"sleep");l(ly,"askPassword");l(ha,"authLoginSSO");l(ya,"authLogoutProfile")});async function*xu(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 Xn,Cu=H(()=>{"use strict";l(xu,"parseSSEStream");Xn=class{static{l(this,"ToolCallAccumulator")}_calls=new Map;feed(e){for(let t of e){let o=this._calls.get(t.index);t.id&&t.function?.name?this._calls.set(t.index,{id:t.id,name:t.function.name,arguments:t.function.arguments||""}):o&&t.function?.arguments&&(o.arguments+=t.function.arguments)}}flush(){let e=Array.from(this._calls.values());return this._calls.clear(),e}get hasPending(){return this._calls.size>0}}});function _u(s=!0){return s?$u:$u.filter(e=>e.function.name!=="web_search"&&e.function.name!=="read_url")}var $u,Eu=H(()=>{"use strict";$u=[{type:"function",function:{name:"read_file",description:"Read the contents of a file with line numbers. Files longer than 2000 lines are truncated (head + tail) by default \u2014 use start_line/end_line to read a specific range, or full:true to read everything. ALWAYS read a file before editing it.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},start_line:{type:"number",description:"Optional 1-indexed start line."},end_line:{type:"number",description:"Optional 1-indexed end line (inclusive)."},full:{type:"boolean",description:"Set true to bypass truncation and read the entire file."}},required:["path"]}}},{type:"function",function:{name:"create_file",description:"Create a new file with the given content. Fails if the file already exists \u2014 use edit_file to modify existing files.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},content:{type:"string",description:"Complete file content to write"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Edit an existing file using search-and-replace. Each edit replaces the FIRST exact match of old_string with new_string. To delete text, set new_string to empty. ALWAYS read the file first to see the current content.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"},old_string:{type:"string",description:"Exact string to find (must match current file content exactly, including whitespace and indentation)"},new_string:{type:"string",description:"Replacement string"}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"delete_file",description:"Delete a file from the workspace.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to the workspace root"}},required:["path"]}}},{type:"function",function:{name:"rename_file",description:"Rename or move a file within the workspace.",parameters:{type:"object",properties:{from:{type:"string",description:"Current file path"},to:{type:"string",description:"New file path"}},required:["from","to"]}}},{type:"function",function:{name:"list_dir",description:"List the contents of a directory. Returns file names, types, and sizes. Use for exploration before reading specific files.",parameters:{type:"object",properties:{path:{type:"string",description:'Directory path relative to workspace root. Use "." for workspace root.'},recursive:{type:"boolean",description:"If true, list recursively (max depth 3)"}},required:["path"]}}},{type:"function",function:{name:"grep_search",description:"Search for a pattern in files using ripgrep. Returns matching lines with file paths and line numbers. Supports regex and glob filtering.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Search pattern (regex by default)"},path:{type:"string",description:'Directory or file to search in (relative to workspace root). Default: "."'},include:{type:"string",description:'Glob pattern to include files (e.g., "*.ts")'},fixed_strings:{type:"boolean",description:"If true, treat pattern as literal string instead of regex"},case_insensitive:{type:"boolean",description:"If true, search case-insensitively"},max_count:{type:"number",description:"Maximum matches to return per file"}},required:["pattern"]}}},{type:"function",function:{name:"glob_files",description:"Find files matching a glob pattern. Returns a list of file paths. Useful for discovering project structure.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern (e.g., "**/*.ts", "src/**/*.{js,ts}")'},path:{type:"string",description:"Base directory to search from (default: workspace root)"}},required:["pattern"]}}},{type:"function",function:{name:"run_command",description:"Execute a shell command in the workspace directory. Use for running tests, builds, installations, git operations, and any other terminal command. Commands run in the user's default shell.",parameters:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},cwd:{type:"string",description:"Working directory (relative to workspace root). Default: workspace root."},timeout:{type:"number",description:"Timeout in seconds. Default: 120."},background:{type:"boolean",description:"If true, run in the background and return immediately."}},required:["command"]}}},{type:"function",function:{name:"web_search",description:"Search the web for information using Google. Returns a list of results with titles, URLs, and snippets. Use for finding documentation, solving errors, or researching unfamiliar topics.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Maximum number of results (default: 5, max: 10)"}},required:["query"]}}},{type:"function",function:{name:"read_url",description:"Fetch the content of a URL. Returns the page content as markdown. Use for reading documentation pages, API references, or blog posts.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to read"},max_length:{type:"number",description:"Maximum response length in characters (default: 50000)"}},required:["url"]}}},{type:"function",function:{name:"git_status",description:"Show the working tree status (modified, staged, untracked files).",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Show changes between commits, commit and working tree, etc.",parameters:{type:"object",properties:{target:{type:"string",description:'Diff target: "staged", "unstaged", a commit hash, or a range like "HEAD~3..HEAD"'},path:{type:"string",description:"Optional file path to diff"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show commit history.",parameters:{type:"object",properties:{max_count:{type:"number",description:"Number of commits to show (default: 10)"},path:{type:"string",description:"Show commits that affect this file/directory"},oneline:{type:"boolean",description:"If true, show compact one-line format"}},required:[]}}},{type:"function",function:{name:"git_commit",description:"Create a commit with the staged changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},add_all:{type:"boolean",description:"If true, stage all changes before committing (git add -A)"}},required:["message"]}}},{type:"function",function:{name:"git_stash",description:"Stash the current working directory changes.",parameters:{type:"object",properties:{message:{type:"string",description:"Optional stash message"}},required:[]}}},{type:"function",function:{name:"git_stash_pop",description:"Restore the most recent stash.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"search_files",description:"Search for files by name pattern (glob). Returns matching file paths. Use for finding files when you know part of the name but not the location.",parameters:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "**/*.test.ts", "src/**/index.*")'},path:{type:"string",description:'Directory to search in (relative to workspace root). Default: "."'},max_results:{type:"number",description:"Maximum results to return (default: 50)"}},required:["pattern"]}}},{type:"function",function:{name:"replace_in_file",description:"Replace specific text in a file. Searches for an exact string match and replaces it. More surgical than edit_file \u2014 use when you need to change a specific known string. Fails if the search text is not found or matches multiple times (unless allow_multiple is true).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},old_string:{type:"string",description:"Exact string to find (must match exactly, including whitespace)"},new_string:{type:"string",description:"Replacement string"},allow_multiple:{type:"boolean",description:"If true, replace all occurrences. Default: false (error on multiple matches)."}},required:["path","old_string","new_string"]}}},{type:"function",function:{name:"patch_file",description:"Apply a unified diff patch to a file. Use when making complex multi-line changes. The patch must be in standard unified diff format (lines starting with +, -, or space).",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to workspace root"},patch:{type:"string",description:"Unified diff patch content. Lines starting with - are removed, + are added, space are context."}},required:["path","patch"]}}},{type:"function",function:{name:"run_tests",description:"Detect and run the project's test suite. Automatically detects the test framework (jest, vitest, pytest, go test, cargo test, etc.) and runs tests. Optionally target specific test files or patterns.",parameters:{type:"object",properties:{path:{type:"string",description:"Specific test file or directory to run (relative to workspace root). Default: run all tests."},pattern:{type:"string",description:'Test name pattern to filter (e.g., "should handle errors")'},framework:{type:"string",description:"Force a specific framework. Auto-detected if not specified.",enum:["jest","vitest","mocha","pytest","go","cargo","dotnet","rspec","auto"]}},required:[]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when you need clarification, a decision, or permission before proceeding.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"todo_write",description:"Update your task plan. Call this at the start of complex tasks to break them into steps, and update as you complete each step. The plan is shown to the user.",parameters:{type:"object",properties:{todos:{type:"array",description:"List of task items",items:{type:"object",properties:{id:{type:"string",description:"Unique task ID"},content:{type:"string",description:"Task description"},status:{type:"string",description:"Task status",enum:["pending","in_progress","done"]}},required:["id","content","status"]}}},required:["todos"]}}},{type:"function",function:{name:"spawn_subagent",description:"Spawn an independent sub-agent to work on a task in parallel. The sub-agent gets its own conversation and tool access but shares the same workspace. Use for: (1) tasks that can run independently, (2) exploring alternative approaches, (3) large refactors that can be parallelized by component.",parameters:{type:"object",properties:{task:{type:"string",description:"Clear description of what the sub-agent should do"},model:{type:"string",description:"Model to use for the sub-agent. Default: same as parent."}},required:["task"]}}},{type:"function",function:{name:"remember",description:"Save an important fact, convention, or decision to persistent memory. Use when you learn something about the project that should be remembered across sessions (coding conventions, architecture decisions, user preferences, common patterns).",parameters:{type:"object",properties:{content:{type:"string",description:"The fact, convention, or decision to remember. Be specific and actionable."},category:{type:"string",description:"Category for organization",enum:["convention","architecture","preference","gotcha","pattern"]}},required:["content"]}}}];l(_u,"getToolSchemas")});var ve={};Te(ve,{getSetting:()=>dy,loadSettings:()=>z,saveSettings:()=>uy});function z(){let s=T(),e=ba.join(s.config,"settings.json");try{if(eo.existsSync(e)){let t=JSON.parse(eo.readFileSync(e,"utf8"));return{...Fu,...t}}}catch{}return{...Fu}}function uy(s){let e=T();eo.mkdirSync(e.config,{recursive:!0});let t=ba.join(e.config,"settings.json"),n={...z(),...s};eo.writeFileSync(t,JSON.stringify(n,null,2))}function dy(s){return z()[s]}var eo,ba,Fu,Q=H(()=>{"use strict";eo=y(require("node:fs"),1),ba=y(require("node:path"),1);X();Fu={platformUrl:process.env.MONKEYSCODE_PLATFORM_URL||"https://models.monkeyscode.com",defaultModel:"capuchin-reason",effort:"reasoning",autoApprove:!1,mode:"auto",maxTurns:void 0,webEnabled:!0};l(z,"loadSettings");l(uy,"saveSettings");l(dy,"getSetting")});var L,le,Ne,wa,py,Qn,Tu=H(()=>{"use strict";L=y(require("node:fs"),1),le=y(require("node:path"),1),Ne=require("node:child_process"),wa=require("node:fs"),py={write_file:"create_file",list_files:"list_dir",list_directory:"list_dir",search_code:"grep_search",execute_command:"run_command",view_file:"read_file",str_replace:"replace_in_file",str_replace_editor:"replace_in_file",str_replace_based_edit_tool:"replace_in_file",bash:"run_command",bash_tool:"run_command",shell:"run_command",terminal:"run_command",text_editor:"edit_file",apply_patch:"patch_file",container_exec:"run_command",file_search:"search_files",codebase_search:"grep_search",semantic_search:"grep_search",grep:"grep_search",ripgrep:"grep_search",find_files:"search_files",glob:"search_files",glob_file_search:"search_files",ls:"list_dir",read:"read_file",cat:"read_file",write:"create_file",edit:"edit_file",multi_edit:"edit_file",search_replace:"replace_in_file",run_terminal_cmd:"run_command",run_in_terminal:"run_command",web_fetch:"read_url",fetch_webpage:"read_url",search_web:"web_search",google_search:"web_search",move_file:"rename_file",remove_file:"delete_file",task:"spawn_subagent",subagent:"spawn_subagent"},Qn=class{static{l(this,"ToolExecutor")}workspace;platformUrl;token;signal;_checkpoints=new Map;_runId="";_mcpClient;_sandbox;constructor(e){this.workspace=e.workspace,this.platformUrl=e.platformUrl,this.token=e.token,this.signal=e.signal}setRunId(e){this._runId=e,this._checkpoints.clear()}setMCPClient(e){this._mcpClient=e}setSandbox(e){this._sandbox=e}async execute(e,t){let o=py[e]||e;switch(o){case"read_file":return this.readFile(t);case"create_file":return this.createFile(t);case"edit_file":return this.editFile(t);case"delete_file":return this.deleteFile(t);case"rename_file":return this.renameFile(t);case"list_dir":return this.listDir(t);case"grep_search":return this.grepSearch(t);case"glob_files":return this.globFiles(t);case"search_files":return this.searchFiles(t);case"replace_in_file":return this.replaceInFile(t);case"patch_file":return this.patchFile(t);case"run_command":return this.runCommand(t);case"run_tests":return this.runTests(t);case"web_search":return this.webSearch(t);case"read_url":return this.readUrl(t);case"git_status":return this.gitExec("status",t);case"git_diff":return this.gitDiff(t);case"git_log":return this.gitLog(t);case"git_commit":return this.gitCommit(t);case"git_stash":return this.gitExec("stash",t);case"git_stash_pop":return this.gitExec("stash pop",t);case"todo_write":return this.todoWrite(t);case"spawn_subagent":return this.spawnSubagent(t);case"remember":return this.remember(t);default:return o.startsWith("mcp_")&&this._mcpClient?this._executeMCPTool(o,t):{output:`Unknown tool: ${e}. Use one of: read_file, create_file, edit_file, replace_in_file, patch_file, run_command, run_tests, grep_search, search_files, list_dir, git_status, git_commit, web_search, read_url, ask_user, todo_write, spawn_subagent, remember, or mcp_<server>_<tool>`}}}getCheckpoints(){return this._checkpoints}readFile(e){let t=this.resolve(e.path);if(!L.existsSync(t))return{output:`Error: File not found: ${e.path}`};if(L.statSync(t).isDirectory())return{output:`Error: ${e.path} is a directory. Use list_dir instead.`};let r=L.readFileSync(t,"utf8").split(`
|
|
46
46
|
`),i=e.start_line||1,c=e.end_line||r.length,u=e.full,d;if(u||r.length<=2e3)d=r;else{let f=r.slice(0,500),m=r.slice(-500);d=[...f,`
|
|
47
47
|
... (${r.length-1e3} lines truncated \u2014 use start_line/end_line or full:true) ...
|
|
48
48
|
`,...m]}!u&&(e.start_line||e.end_line)&&(d=r.slice(i-1,c));let p=d.map((f,m)=>{let g=(e.start_line||1)+m;return`${String(g).padStart(5)} ${f}`});return{output:`File: ${e.path} (${r.length} lines)
|
|
@@ -82,7 +82,7 @@ ${t.map(n=>` ${n.status==="done"?"\u2705":n.status==="in_progress"?"\u{1F504}":
|
|
|
82
82
|
`),c=[],u=0;for(let d of i)d.startsWith("---")||d.startsWith("+++")||d.startsWith("@@")||(d.startsWith("-")?u++:d.startsWith("+")?c.push(d.slice(1)):(d.startsWith(" ")||d==="")&&u<r.length&&(c.push(r[u]),u++));for(;u<r.length;)c.push(r[u]),u++;return L.writeFileSync(t,c.join(`
|
|
83
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
84
|
${i.slice(0,8e3)}`}}catch(i){let c=i.stdout||i.stderr||i.message;return{output:`[${n}] Tests failed:
|
|
85
|
-
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=le.join(this.workspace,"package.json");if(L.existsSync(e)){try{let t=JSON.parse(L.readFileSync(e,"utf8")),o={...t.dependencies,...t.devDependencies};if(o.vitest)return"vitest";if(o.jest)return"jest";if(o.mocha)return"mocha"}catch{}return"jest"}return L.existsSync(le.join(this.workspace,"pyproject.toml"))||L.existsSync(le.join(this.workspace,"setup.py"))||L.existsSync(le.join(this.workspace,"pytest.ini"))?"pytest":L.existsSync(le.join(this.workspace,"go.mod"))?"go":L.existsSync(le.join(this.workspace,"Cargo.toml"))?"cargo":L.existsSync(le.join(this.workspace,"Gemfile"))?"rspec":(0,wa.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(()=>(
|
|
85
|
+
${c.slice(0,8e3)}`}}}detectTestFramework(){let e=le.join(this.workspace,"package.json");if(L.existsSync(e)){try{let t=JSON.parse(L.readFileSync(e,"utf8")),o={...t.dependencies,...t.devDependencies};if(o.vitest)return"vitest";if(o.jest)return"jest";if(o.mocha)return"mocha"}catch{}return"jest"}return L.existsSync(le.join(this.workspace,"pyproject.toml"))||L.existsSync(le.join(this.workspace,"setup.py"))||L.existsSync(le.join(this.workspace,"pytest.ini"))?"pytest":L.existsSync(le.join(this.workspace,"go.mod"))?"go":L.existsSync(le.join(this.workspace,"Cargo.toml"))?"cargo":L.existsSync(le.join(this.workspace,"Gemfile"))?"rspec":(0,wa.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(()=>(ze(),Xo)),c=await r();if(!c)return{output:"Error: Not authenticated. Cannot spawn subagent."};let u=new i({platformUrl:n.platformUrl,token:c,model:o||n.defaultModel,workspace:this.workspace,mode:"auto",maxTurns:30,userId:void 0,orgId:void 0}),d=`subagent-${Date.now().toString(36)}`,p=await u.run(t);return{output:[`Subagent ${d} completed:`,` Turns: ${p.turns}`,` Tokens: ${p.tokensIn+p.tokensOut}`,` Files modified: ${p.filesModified.join(", ")||"none"}`,` Duration: ${Math.round(p.duration/1e3)}s`].join(`
|
|
86
86
|
`),wroteFiles:p.filesModified.length>0,touchedFiles:p.filesModified}}catch(n){return{output:`Subagent error: ${n.message}`}}}remember(e){let t=e.content,o=e.category||"general";try{let n=le.join(this.workspace,".monkeyscode");L.existsSync(n)||L.mkdirSync(n,{recursive:!0});let r=le.join(n,"MEMORY.md"),i=new Date().toISOString().split("T")[0],c=`
|
|
87
87
|
- [${o}] ${t} _(${i})_
|
|
88
88
|
`,u="";return L.existsSync(r)?u=L.readFileSync(r,"utf8"):u=`# Project Memory
|
|
@@ -104,7 +104,7 @@ Facts, conventions, and decisions learned during sessions.
|
|
|
104
104
|
<Command>cmd.exe /k cd C:\\Workspace</Command>
|
|
105
105
|
</LogonCommand>
|
|
106
106
|
<MemoryInMB>2048</MemoryInMB>
|
|
107
|
-
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var
|
|
107
|
+
</Configuration>`.trim()}wrapWithAppContainer(e,t,o){return{command:"cmd.exe",args:["/c",`RunAs /TrustLevel:0x20000 "${e} ${t.join(" ")}"`]}}}});var to,xo,oo,Nu,ju,Hs,Co,Lu=H(()=>{"use strict";to=require("node:child_process"),xo=y(require("node:path"),1),oo=y(require("node:fs"),1),Nu=y(require("node:crypto"),1),ju="monkeyscode-sandbox",Hs="/workspace",Co=class{static{l(this,"DockerSandboxProvider")}name="docker";containerId=null;imageName=ju;async isAvailable(){try{return(0,to.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",Hs),n.push(this.containerId),n.push(e,...t);else{n.splice(0),n.push("run","--rm"),n.push("-w",Hs);let r=xo.resolve(o.workspace);n.push("-v",`${r}:${Hs}`),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||ju;let t=xo.resolve(e.workspace),o=e.dockerfilePath||xo.join(t,".monkeyscode","Dockerfile.sandbox");if(oo.existsSync(o)){let c=(0,to.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-${Nu.randomUUID().substring(0,8)}`,"-w",Hs,"-v",`${t}:${Hs}`];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,to.spawnSync)("docker",r,{stdio:"pipe"});i.status===0&&(this.containerId=i.stdout.toString().trim().substring(0,12))}async teardown(){if(this.containerId){try{(0,to.execSync)(`docker rm -f ${this.containerId}`,{stdio:"pipe",timeout:1e4})}catch{}this.containerId=null}}async ensureBaseImage(){try{(0,to.execSync)(`docker image inspect ${this.imageName}`,{stdio:"pipe"});return}catch{}let e=`
|
|
108
108
|
FROM ubuntu:22.04
|
|
109
109
|
RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
110
110
|
git curl wget ca-certificates \\
|
|
@@ -115,13 +115,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \\
|
|
|
115
115
|
RUN useradd -m -s /bin/bash sandbox
|
|
116
116
|
USER sandbox
|
|
117
117
|
WORKDIR /workspace
|
|
118
|
-
`.trim(),t=
|
|
118
|
+
`.trim(),t=xo.join(require("node:os").tmpdir(),"mc-sandbox-build");oo.mkdirSync(t,{recursive:!0}),oo.writeFileSync(xo.join(t,"Dockerfile"),e);let o=(0,to.spawnSync)("docker",["build","-t",this.imageName,t],{stdio:"pipe",timeout:3e5});if(oo.rmSync(t,{recursive:!0,force:!0}),o.status!==0)throw new Error(`Failed to build sandbox base image: ${o.stderr?.toString()}`)}}});function Bu(s){switch(s){case"linux":return[new Ls,new Co];case"macos":return[new Us,new Co];case"windows":return[new Ws,new Co]}}function sr(s,e={}){return{enabled:!1,provider:"auto",network:"none",workspace:s,...e}}var es,va=H(()=>{"use strict";X();Pu();Mu();Iu();Lu();l(Bu,"getProviderCandidates");es=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=Bu(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=Bu(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 Ls;case"sandbox-exec":return new Us;case"windows-sandbox":case"appcontainer":return new Ws;case"docker":return new Co;default:return null}}};l(sr,"createDefaultSandboxConfig")});function Uu(s){switch(s){case 0:return"allow";case 1:return"deny";case 2:return"modify";default:return"allow"}}var Wu,Hu=H(()=>{"use strict";l(Uu,"exitCodeToAction");Wu={enabled:!0,timeoutMs:1e4}});function $o(s){let e=T(),t=ft.join(s,".monkeyscode","hooks"),o=ft.join(e.config,"hooks"),n=Gu(t,"project"),r=Gu(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 Gu(s,e){if(!ts.existsSync(s))return[];let t=[];try{let o=ts.readdirSync(s,{withFileTypes:!0});for(let n of o){if(!n.isFile())continue;let r=ft.extname(n.name).toLowerCase(),i=fy[r];if(!i)continue;let c=ft.basename(n.name,r).toLowerCase(),u=my[c];u&&t.push({event:u,scriptPath:ft.join(s,n.name),source:e,scriptType:i})}}catch{}return t}function qu(s){let e=T(),t=ft.join(s,".monkeyscode","hooks"),o=ft.join(e.config,"hooks");return[{path:t,source:"project",exists:ts.existsSync(t)},{path:o,source:"global",exists:ts.existsSync(o)}]}var ts,ft,my,fy,nr=H(()=>{"use strict";ts=y(require("node:fs"),1),ft=y(require("node:path"),1);X();my={"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"},fy={".sh":"sh",".bash":"sh",".ps1":"ps1",".cmd":"cmd",".bat":"cmd",".js":"js",".mjs":"js",".py":"py"};l($o,"loadHooks");l(Gu,"scanHookDirectory");l(qu,"getHookDirectories")});var Vu,_o,Sa=H(()=>{"use strict";Vu=require("node:child_process");X();Hu();nr();_o=class{static{l(this,"HookRunner")}hooks;config;platform=De();constructor(e,t={}){this.config={...Wu,...t},this.hooks=this.config.enabled?$o(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?$o(e):[]}async executeHook(e,t){let o=Date.now();return new Promise(n=>{let{command:r,args:i}=this.getExecutor(e),c=(0,Vu.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":Uu(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 Ju(s,e=60){if(!Pt.ansi){console.log(`
|
|
119
119
|
${s}
|
|
120
|
-
${"\u2500".repeat(e)}`);return}let t="\u2500".repeat(Math.max(0,e-s.length-4));console.log(""),console.log(` ${be.accent("\u2500\u2500")} ${be.bold(s)} ${be.accent(t)}`)}function Ku(s,e){let t=" "+s.map(n=>{let r=n.header;return
|
|
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 ky(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=
|
|
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 Ku(s,e){let t=" "+s.map(n=>{let r=n.header;return zu(r,n.width,n.align||"left")}).join(" ");console.log(Pt.ansi?be.dim(t):t);let o=" "+s.map(n=>"\u2500".repeat(n.width)).join("\u2500\u2500");console.log(Pt.ansi?be.dim(o):o);for(let n of e){let r=" "+n.cells.map((i,c)=>{let u=s[c];return zu(i,u.width,u.align||"left")}).join(" ");n.dim&&Pt.ansi?r=be.dim(r):n.highlight&&Pt.ansi&&(r=be.accent(r)),console.log(r)}}function zu(s,e,t){let o=hy(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 xa(s){console.log(Pt.ansi?` ${be.dim(s)}`:` ${s}`)}function Yu(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 Ca(s){return s===0?Pt.ansi?be.success("Free"):"Free":`$${s.toFixed(s<1?4:2)}`}function hy(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}function Gs(){console.log("")}var gy,be,Pt,XS,QS,Xu=H(()=>{"use strict";U();Ce();gy=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},Pt=j(),XS=W(Pt),QS=Ve(Pt);l(Ju,"sectionHeader");l(Ku,"printTable");l(zu,"padCell");l(xa,"hint");l(Yu,"formatTokens");l(Ca,"formatCost");l(hy,"stripAnsi");l(Gs,"blank")});function gt(s){if(s==="auto")return"auto";let e=s.toLowerCase(),t=Ot.find(r=>r.id===e);if(t)return t.id;let o=Ot.find(r=>r.aliases.some(i=>i.toLowerCase()===e));if(o)return o.id;let n=Ot.find(r=>r.displayName.toLowerCase().includes(e));return n?n.id:s}function rr(s){let e=gt(s);return Ot.find(t=>t.id===e)??null}function yy(s,e){let t=gt(s),o=Ot.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 qs(s,e,t,o=0){let n=Ot.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 $a(s){let e=j().ansi,t=j().emoji;Ju("Available Models"),Gs();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=Ot.map(r=>{let i=yy(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":`${Ca(r.costInputPerM)} / ${Ca(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,Yu(r.contextWindow),p,f,g],dim:c}});if(Ku(o,n),Gs(),e){console.log(` ${be.dim("Aliases:")}`);for(let r of Ot)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 Ot)r.aliases.length>0&&console.log(` ${r.displayName}: ${r.aliases.join(", ")}`)}Gs(),xa("Use --model <name|alias> to select a model"),xa("Use --model auto for smart routing based on task complexity"),Gs()}var Ot,ir=H(()=>{"use strict";U();Ce();Xu();Ot=[{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(rr,"getModelInfo");l(yy,"checkModelAccess");l(qs,"estimateCost");l($a,"printModelList")});function Qu(s,e,t){let o=rr(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:`${_a.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:`${_a.openai}/v1/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.openai}`},isDirect:!0,provider:"openai",isAnthropicFormat:!1}:n==="google"&&r.google?{url:`${_a.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 _a,Zu=H(()=>{"use strict";ir();_a={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"};l(Qu,"resolveModelRoute")});var ed=H(()=>{"use strict"});var Ta={};Te(Ta,{buildSkillsContext:()=>Fa,listAllSkills:()=>vy,loadSkills:()=>td});function wy(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 ky(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=so.join(s,"skill.md");if(!Mt.existsSync(o))return null;try{let n=Mt.readFileSync(o,"utf8"),{meta:r,body:i}=wy(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:ky(r.trigger),enabled:r.enabled!==!1,priority:r.priority??50,filePath:o}:null}catch{return null}}function ar(s,e){if(!Mt.existsSync(s))return[];try{return Mt.readdirSync(s).filter(t=>{let o=so.join(s,t);return Mt.statSync(o).isDirectory()}).map(t=>Dy(so.join(s,t),t,e)).filter(t=>t!==null)}catch{return[]}}function td(s){let e=so.join(s,".monkeyscode","skills"),t=so.join(Ea.homedir(),".monkeyscode","skills"),o=ar(t,"global"),n=ar(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 Fa(s){let e=td(s);if(e.length===0)return null;let t=[],o=0;for(let n of e){let r=Math.ceil(n.systemPrompt.length/4);if(o+r>2e3)break;t.push(`### Skill: ${n.name}
|
|
122
122
|
${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
123
123
|
|
|
124
|
-
`):null}function vy(s){let e=
|
|
124
|
+
`):null}function vy(s){let e=so.join(s,".monkeyscode","skills"),t=so.join(Ea.homedir(),".monkeyscode","skills"),o=ar(t,"global"),n=ar(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 Mt,so,Ea,cr=H(()=>{"use strict";Mt=y(require("node:fs"),1),so=y(require("node:path"),1),Ea=y(require("node:os"),1);ed();l(wy,"parseFrontmatter");l(ky,"parseTrigger");l(Dy,"loadSkillFromDir");l(ar,"scanSkillsDir");l(td,"loadSkills");l(Fa,"buildSkillsContext");l(vy,"listAllSkills")});function od(s){let e=Date.now(),t=[],o=[];switch(o.push("You are MonkeysCode, an expert AI coding assistant running in a terminal (CLI mode)."),o.push("You help developers by reading, writing, and modifying code files, running commands, and answering questions."),o.push(`
|
|
125
125
|
## Available Tools`),o.push("You have access to file operations (read, edit, create, delete, rename, list, search), shell commands, and git operations."),o.push("Always use the appropriate tool rather than guessing file contents. Always read a file before editing it."),o.push(`
|
|
126
126
|
## Task Tracking`),o.push("For any task with 3+ steps, maintain a checklist with todo_write: send the full list every time, keep exactly one item in_progress, and update it immediately after finishing each step."),o.push("Use ask_user when blocked on a genuine decision."),s.webEnabled&&(o.push(`
|
|
127
127
|
## Web Search`),o.push("You can search the web with web_search and fetch URL content with read_url. Use these when you need documentation, error solutions, or information not available in the workspace.")),s.mode){case"plan":o.push(`
|
|
@@ -130,44 +130,44 @@ ${n.systemPrompt}`),o+=r}return t.length>0?t.join(`
|
|
|
130
130
|
## Mode: Accept Edits`),o.push("You may make file changes without asking. Be efficient and direct.");break;case"auto":default:o.push(`
|
|
131
131
|
## Mode: Auto`),o.push("Use your judgment on when to proceed and when to ask. For safe, reversible operations, proceed directly.");break}o.push(`
|
|
132
132
|
## Important Guidelines`),o.push("- Be concise in responses. Show code changes, not lengthy explanations."),o.push("- When editing files, use edit_file with the EXACT current content as old_string."),o.push("- When running commands, prefer non-interactive commands (add -y, --yes, etc.)."),o.push(`- Today's date: ${new Date().toISOString().split("T")[0]}`),t.push({role:"system",content:o.join(`
|
|
133
|
-
`),timestamp:e});let n=[];n.push("## Workspace Context"),n.push(`- Path: ${s.workspace}`),n.push(`- Execution: Local terminal (Node.js ${process.version})`),s.sandboxed&&n.push("- Sandbox: Active \u2014 commands run in an isolated environment");let r=
|
|
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=It.basename(s.workspace);n.push(`- Project: ${r}`);let i=Sy(s.workspace);i&&n.push(`- Stack: ${i}`),t.push({role:"system",content:n.join(`
|
|
134
134
|
`),timestamp:e});let c=Cy(s.workspace);c&&t.push({role:"system",content:`## Workspace Rules
|
|
135
135
|
|
|
136
136
|
${c}`,timestamp:e});let u=Fa(s.workspace);u&&t.push({role:"system",content:`## Active Skills
|
|
137
137
|
|
|
138
138
|
${u}`,timestamp:e});let d=xy(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 Sy(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(
|
|
139
|
+
`),timestamp:e})}return t}function Sy(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(It.join(s,o))&&t.push(n);if(ot.existsSync(It.join(s,"package.json")))try{let o=JSON.parse(ot.readFileSync(It.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 xy(s){try{let e=(0,Ra.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s,encoding:"utf8",timeout:3e3,stdio:["pipe","pipe","pipe"]}).trim(),t=(0,Ra.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 Cy(s){let e=[];for(let o of["AGENTS.md","CLAUDE.md","GEMINI.md",".monkeyscode/AGENTS.md"]){let n=It.join(s,o);if(ot.existsSync(n))try{let r=ot.readFileSync(n,"utf8");r.trim()&&e.push(`### ${o}
|
|
140
140
|
|
|
141
|
-
${r}`)}catch{}}let t=
|
|
141
|
+
${r}`)}catch{}}let t=It.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(It.join(t,n),"utf8");r.trim()&&e.push(`### ${n}
|
|
142
142
|
|
|
143
143
|
${r}`)}}catch{}return e.length>0?e.join(`
|
|
144
144
|
|
|
145
145
|
---
|
|
146
146
|
|
|
147
|
-
`):null}var ot,
|
|
148
|
-
... [output truncated]`,d++);if(lr(u)<=i)return{messages:u,elided:d,savedTokens:p-
|
|
147
|
+
`):null}var ot,It,Ra,sd=H(()=>{"use strict";ot=y(require("node:fs"),1),It=y(require("node:path"),1),Ra=require("node:child_process");cr();l(od,"buildSystemMessages");l(Sy,"detectProjectType");l(xy,"getGitInfo");l(Cy,"loadWorkspaceRules")});function Aa(s){return Math.ceil(s.length/4)}function no(s,e=6e3){let t=e;for(let o of s)if(t+=Aa(o.content),o.tool_calls)for(let n of o.tool_calls)t+=Aa(JSON.stringify(n.arguments)),n.result&&(t+=Aa(n.result));return t}function ur(s,e){if(e&&e>0)return e;let t=$y.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 nd(s,e,t=.85){return s>=e*t}function Pa(s,e,t){let r=Math.max(4e3,(e||128e3)-(t||15e3)),i=Math.floor(r*.9)*4;if(lr(s)<=i)return{messages:s,elided:0,savedTokens:0};let u=s.map(k=>({...k})),d=0,p=no(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(lr(u)<=i)return{messages:u,elided:d,savedTokens:p-no(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 v=0;v<u.length;v++){if(u[v].role==="system")continue;if(k++,k>g)break;let x=u[v];if(k<=Math.floor(g*.75)){if(x.role==="tool"&&x.content&&x.content.length>150){let _=x.content.includes("Error")||x.content.includes("error"),C=x.content.split(`
|
|
149
149
|
`)[0].slice(0,100);x.content=_?`[error] ${C}`:`[ok] ${C}`,d++}if(x.role==="assistant"&&x.content&&x.content.length>300&&!x.tool_calls?.length&&(x.content=x.content.slice(0,200)+`
|
|
150
150
|
...[summarized]`),x.role==="assistant"&&x.tool_calls?.length){let _=x.tool_calls.map(C=>`[called ${C.name||"unknown"}]`);x.content||(x.content=_.join(", "))}}else if(x.role==="assistant"&&x.content&&x.content.length>500&&!x.tool_calls?.length&&(x.content=x.content.slice(0,400)+`
|
|
151
151
|
...[truncated]`),x.role==="tool"&&x.content&&x.content.length>500){let _=x.content.includes("Error")||x.content.includes("error"),C=x.content.split(`
|
|
152
|
-
`)[0].slice(0,150);x.content=_?`[error] ${C}`:`[ok] ${C}`,d++}}}if(lr(u)<=i)return{messages:u,elided:d,savedTokens:p-
|
|
153
|
-
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-so(u)}}function lr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var $y,Oa=H(()=>{"use strict";l(Aa,"estimateTokens");l(so,"estimateContextTokens");l(ur,"resolveContextWindow");$y=new Map;l(nd,"shouldCompact");l(Pa,"compactMessages");l(lr,"totalChars")});var Xo={};Te(Xo,{AgentLoop:()=>Se});var rd,_y,Se,Je=H(()=>{"use strict";rd=require("node:events");Cu();Eu();Tu();va();Sa();Zu();Q();sd();Oa();_y=1/0,Se=class extends rd.EventEmitter{static{l(this,"AgentLoop")}opts;toolExecutor;abortController;state;messages=[];filesModified=new Set;contextWindow;_approvalResolve=null;_userInputResolve=null;_hookRunner;_insideThinkTag=!1;constructor(e){if(super(),this.opts=e,this.abortController=new AbortController,this.toolExecutor=new Qn({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new es(sr(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new $o(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=ur(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||_y;this.updateState({status:"streaming"}),this._hookRunner.fire("SessionStart",{workspace:this.opts.workspace,data:{prompt:e,model:this.opts.model,mode:this.opts.mode}}).catch(()=>{}),this.messages=od({workspace:this.opts.workspace,mode:this.opts.mode,model:this.opts.model,sandboxed:this.opts.sandboxed||!1,webEnabled:this.opts.webEnabled!==!1}),this.messages.push({role:"user",content:e,timestamp:Date.now()});try{for(let r=0;r<o;r++){if(this.abortController.signal.aborted){this.updateState({status:"cancelled"});break}this.updateState({status:"streaming",turns:r+1}),this.emitEvent({type:"streaming_start"});let i=so(this.messages);if(nd(i,this.contextWindow)){let u=Pa(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=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(v=>v.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${k}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let b=await this.toolExecutor.execute(m.name,m.arguments);if(b.wroteFiles&&b.touchedFiles)for(let k of b.touchedFiles)this.filesModified.add(k);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:b.output.slice(0,1e3),wroteFiles:b.wroteFiles}}).catch(()=>{}),m.result=b.output,this.emitEvent({type:"tool_call_result",name:m.name,result:b.output}),this.messages.push({role:"tool",content:b.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=Pa(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=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=_u(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(C=>({role:C.role,content:C.content,...C.tool_calls?{tool_calls:C.tool_calls.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))}:{},...C.tool_call_id?{tool_call_id:C.tool_call_id}:{},...C.name?{name:C.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=J(),i=Qu(this.opts.model,r,t),c;try{c=await fetch(i.url,{method:"POST",headers:i.headers,body:JSON.stringify(o),signal:this.abortController.signal})}catch(C){if(C instanceof Error&&C.name==="AbortError")return null;throw C}if(!c.ok){let C=await c.text();throw c.status===401?new Error("Authentication failed \u2014 run `mc auth login` to authenticate."):c.status===403?new Error("Access denied \u2014 your plan may not include this model, or your quota is exhausted."):c.status===429?new Error("Rate limited \u2014 please wait a moment and try again."):new Error(`Model API error ${c.status}: ${C}`)}let u="",d=new Xn,p="",f=!1,m="",g="<think>",h="</think>",b=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),k=l(C=>{f?(m+=C,h.startsWith(m)?m===h&&(f=!1,m=""):(m="",C==="<"&&(m="<"))):C==="<"&&!m?m="<":m?(m+=C,g.startsWith(m)?m===g&&(f=!0,m=""):h.startsWith(m)?m===h&&(m=""):(p+=m,m="")):p+=C},"feedChar");for await(let C of xu(c)){if(!C.choices||C.choices.length===0){C.usage&&this.updateState({tokensIn:this.state.tokensIn+(C.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(C.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(C.usage.prompt_tokens_details?.cached_tokens||0)});continue}let E=C.choices[0];if(E.delta?.content){u+=E.delta.content;for(let I of E.delta.content)k(I);b()}if(E.delta?.tool_calls&&d.feed(E.delta.tool_calls),E.finish_reason==="tool_calls"||E.finish_reason==="stop")break}m&&!f&&(p+=m),b();let v=d.flush(),_={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return v.length>0&&(_.tool_calls=v.map(C=>{let E={};try{E=JSON.parse(C.arguments)}catch{E={_raw:C.arguments}}return{id:C.id,name:C.name,arguments:E}})),_}getAuthHeaders(){let e={Authorization:`Bearer ${this.opts.token}`};return this.opts.userId&&(e["X-User-Id"]=this.opts.userId),this.opts.orgId&&(e["X-Org-Id"]=this.opts.orgId),e}async waitForUserInput(){return new Promise(e=>{this._userInputResolve=e})}updateState(e){Object.assign(this.state,e),this.emitEvent({type:"state_update",state:{...this.state}})}emitEvent(e){this.emit("event",e)}}});var jt=ce((uC,wd)=>{"use strict";var yd=["nodebuffer","arraybuffer","fragments"],bd=typeof Blob<"u";bd&&yd.push("blob");wd.exports={BINARY_TYPES:yd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var Js=ce((pC,kr)=>{"use strict";var{EMPTY_BUFFER:qy}=jt(),La=Buffer[Symbol.species];function Vy(s,e){if(s.length===0)return qy;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),o=0;for(let n=0;n<s.length;n++){let r=s[n];t.set(r,o),o+=r.length}return o<e?new La(t.buffer,t.byteOffset,o):t}l(Vy,"concat");function kd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(kd,"_mask");function Dd(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(Dd,"_unmask");function Jy(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(Jy,"toArrayBuffer");function Ba(s){if(Ba.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new La(s):ArrayBuffer.isView(s)?e=new La(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ba.readOnly=!1),e}l(Ba,"toBuffer");kr.exports={concat:Vy,mask:kd,toArrayBuffer:Jy,toBuffer:Ba,unmask:Dd};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");kr.exports.mask=function(e,t,o,n,r){r<48?kd(e,t,o,n,r):s.mask(e,t,o,n,r)},kr.exports.unmask=function(e,t){e.length<32?Dd(e,t):s.unmask(e,t)}}catch{}});var xd=ce((fC,Sd)=>{"use strict";var vd=Symbol("kDone"),Ua=Symbol("kRun"),Wa=class{static{l(this,"Limiter")}constructor(e){this[vd]=()=>{this.pending--,this[Ua]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ua]()}[Ua](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[vd])}}};Sd.exports=Wa});var rs=ce((hC,Ed)=>{"use strict";var zs=require("zlib"),Cd=Js(),zy=xd(),{kStatusCode:$d}=jt(),Ky=Buffer[Symbol.species],Yy=Buffer.from([0,0,255,255]),vr=Symbol("permessage-deflate"),Nt=Symbol("total-length"),ss=Symbol("callback"),ro=Symbol("buffers"),ns=Symbol("error"),Dr,Ha=class{static{l(this,"PerMessageDeflate")}constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Dr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Dr=new zy(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ss];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,o=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&(typeof n.client_max_window_bits=="number"?t.clientMaxWindowBits>n.client_max_window_bits:!n.client_max_window_bits)));if(!o)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(o.server_no_context_takeover=!0),t.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(o.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?o.client_max_window_bits=t.clientMaxWindowBits:(o.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(o=>{let n=t[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);t[o]=n})}),e}decompress(e,t,o){Dr.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){Dr.add(n=>{this._compress(e,t,(r,i)=>{n(),o(r,i)})})}_decompress(e,t,o){let n=this._isServer?"client":"server";if(!this._inflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?zs.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=zs.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[vr]=this,this._inflate[Nt]=0,this._inflate[ro]=[],this._inflate.on("error",Qy),this._inflate.on("data",_d)}this._inflate[ss]=o,this._inflate.write(e),t&&this._inflate.write(Yy),this._inflate.flush(()=>{let r=this._inflate[ns];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Cd.concat(this._inflate[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"?zs.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=zs.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Nt]=0,this._deflate[ro]=[],this._deflate.on("data",Xy)}this._deflate[ss]=o,this._deflate.write(e),this._deflate.flush(zs.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Cd.concat(this._deflate[ro],this._deflate[Nt]);t&&(r=new Ky(r.buffer,r.byteOffset,r.length-4)),this._deflate[ss]=null,this._deflate[Nt]=0,this._deflate[ro]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Ed.exports=Ha;function Xy(s){this[ro].push(s),this[Nt]+=s.length}l(Xy,"deflateOnData");function _d(s){if(this[Nt]+=s.length,this[vr]._maxPayload<1||this[Nt]<=this[vr]._maxPayload){this[ro].push(s);return}this[ns]=new RangeError("Max payload size exceeded"),this[ns].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ns][$d]=1009,this.removeListener("data",_d),this.reset()}l(_d,"inflateOnData");function Qy(s){if(this[vr]._inflate=null,this[ns]){this[ss](this[ns]);return}s[$d]=1007,this[ss](s)}l(Qy,"inflateOnError")});var is=ce((bC,Sr)=>{"use strict";var{isUtf8:Fd}=require("buffer"),{hasBlob:Zy}=jt(),e0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function t0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(t0,"isValidStatusCode");function Ga(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}l(Ga,"_isValidUTF8");function o0(s){return Zy&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(o0,"isBlob");Sr.exports={isBlob:o0,isValidStatusCode:t0,isValidUTF8:Ga,tokenChars:e0};if(Fd)Sr.exports.isValidUTF8=function(s){return s.length<24?Ga(s):Fd(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");Sr.exports.isValidUTF8=function(e){return e.length<32?Ga(e):s(e)}}catch{}});var Ka=ce((kC,Id)=>{"use strict";var{Writable:s0}=require("stream"),Td=rs(),{BINARY_TYPES:n0,EMPTY_BUFFER:Rd,kStatusCode:r0,kWebSocket:i0}=jt(),{concat:qa,toArrayBuffer:a0,unmask:c0}=Js(),{isValidStatusCode:l0,isValidUTF8:Ad}=is(),xr=Buffer[Symbol.species],ze=0,Pd=1,Od=2,Md=3,Va=4,Ja=5,Cr=6,za=class extends s0{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||n0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[i0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=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 xr(o.buffer,o.byteOffset+e,o.length-e),new xr(o.buffer,o.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let o=this._buffers[0],n=t.length-e;e>=o.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(o.buffer,o.byteOffset,e),n),this._buffers[0]=new xr(o.buffer,o.byteOffset+e,o.length-e)),e-=o.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case ze:this.getInfo(e);break;case Pd:this.getPayloadLength16(e);break;case Od:this.getPayloadLength64(e);break;case Md:this.getMask();break;case Va:this.getData(e);break;case Ja:case Cr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let o=(t[0]&64)===64;if(o&&!this._extensions[Td.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Pd:this._payloadLength===127?this._state=Od:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),o=t.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=o*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Md:this._state=Va}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Va}getData(e){let t=Rd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&c0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(o);return}if(this._compressed){this._state=Ja,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Td.extensionName].decompress(e,this._fin,(n,r)=>{if(n)return t(n);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(i);return}this._fragments.push(r)}this.dataMessage(t),this._state===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=qa(o,t):this._binaryType==="arraybuffer"?n=a0(qa(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=ze):(this._state=Cr,setImmediate(()=>{this.emit("message",n,!0),this._state=ze,this.startLoop(e)}))}else{let n=qa(o,t);if(!this._skipUTF8Validation&&!Ad(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===Ja||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=ze):(this._state=Cr,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,Rd),this.end();else{let o=e.readUInt16BE(0);if(!l0(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new xr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ad(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(r);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=ze;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ze):(this._state=Cr,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[r0]=n,i}};Id.exports=za});var Qa=ce((SC,Ld)=>{"use strict";var{Duplex:vC}=require("stream"),{randomFillSync:u0}=require("crypto"),{types:{isUint8Array:d0}}=require("util"),jd=rs(),{EMPTY_BUFFER:p0,kWebSocket:m0,NOOP:f0}=jt(),{isBlob:as,isValidStatusCode:g0}=is(),{mask:Nd,toBuffer:Eo}=Js(),Ke=Symbol("kByteLength"),h0=Buffer.alloc(4),$r=8*1024,Fo,cs=$r,nt=0,y0=1,b0=2,Ya=class s{static{l(this,"Sender")}constructor(e,t,o){this._extensions=t||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=nt,this.onerror=f0,this[m0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||h0,t.generateMask?t.generateMask(o):(cs===$r&&(Fo===void 0&&(Fo=Buffer.alloc($r)),u0(Fo,0,$r),cs=0),o[0]=Fo[cs++],o[1]=Fo[cs++],o[2]=Fo[cs++],o[3]=Fo[cs++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Ke]!==void 0?c=t[Ke]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!i);let u=c;c>=65536?(r+=8,u=127):c>125&&(r+=2,u=126);let d=Buffer.allocUnsafe(n?c+r:r);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[r-4]=o[0],d[r-3]=o[1],d[r-2]=o[2],d[r-1]=o[3],i?[d,e]:n?(Nd(e,o,d,r,c),[d]):(Nd(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=p0;else{if(typeof e!="number"||!g0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)r=Buffer.allocUnsafe(2),r.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(r=Buffer.allocUnsafe(2+c),r.writeUInt16BE(e,0),typeof t=="string")r.write(t,2);else if(d0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Ke]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==nt?this.enqueue([this.dispatch,r,!1,i,n]):this.sendFrame(s.frame(r,i),n)}ping(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):as(e)?(n=e.size,r=!1):(e=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};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}pong(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):as(e)?(n=e.size,r=!1):(e=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};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[jd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):as(e)?(c=e.size,u=!1):(e=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};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==nt?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Ke],this._state=b0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Xa,this,c,n);return}this._bufferedBytes-=o[Ke];let i=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(w0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[jd.extensionName];this._bufferedBytes+=o[Ke],this._state=y0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Xa(this,u,n);return}this._bufferedBytes-=o[Ke],this._state=nt,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===nt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ke],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ke],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Ld.exports=Ya;function Xa(s,e,t){typeof t=="function"&&t(e);for(let o=0;o<s._queue.length;o++){let n=s._queue[o],r=n[n.length-1];typeof r=="function"&&r(e)}}l(Xa,"callCallbacks");function w0(s,e,t){Xa(s,e,t),s.onerror(e)}l(w0,"onError")});var zd=ce((CC,Jd)=>{"use strict";var{kForOnEventAttribute:Ks,kListener:Za}=jt(),Bd=Symbol("kCode"),Ud=Symbol("kData"),Wd=Symbol("kError"),Hd=Symbol("kMessage"),Gd=Symbol("kReason"),ls=Symbol("kTarget"),qd=Symbol("kType"),Vd=Symbol("kWasClean"),Lt=class{static{l(this,"Event")}constructor(e){this[ls]=null,this[qd]=e}get target(){return this[ls]}get type(){return this[qd]}};Object.defineProperty(Lt.prototype,"target",{enumerable:!0});Object.defineProperty(Lt.prototype,"type",{enumerable:!0});var To=class extends Lt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[Bd]=t.code===void 0?0:t.code,this[Gd]=t.reason===void 0?"":t.reason,this[Vd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Bd]}get reason(){return this[Gd]}get wasClean(){return this[Vd]}};Object.defineProperty(To.prototype,"code",{enumerable:!0});Object.defineProperty(To.prototype,"reason",{enumerable:!0});Object.defineProperty(To.prototype,"wasClean",{enumerable:!0});var us=class extends Lt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[Wd]=t.error===void 0?null:t.error,this[Hd]=t.message===void 0?"":t.message}get error(){return this[Wd]}get message(){return this[Hd]}};Object.defineProperty(us.prototype,"error",{enumerable:!0});Object.defineProperty(us.prototype,"message",{enumerable:!0});var Ys=class extends Lt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[Ud]=t.data===void 0?null:t.data}get data(){return this[Ud]}};Object.defineProperty(Ys.prototype,"data",{enumerable:!0});var k0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[Ks]&&n[Za]===e&&!n[Ks])return;let o;if(s==="message")o=l(function(r,i){let c=new Ys("message",{data:i?r:r.toString()});c[ls]=this,_r(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new To("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ls]=this,_r(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new us("error",{error:r,message:r.message});i[ls]=this,_r(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Lt("open");r[ls]=this,_r(e,this,r)},"onOpen");else return;o[Ks]=!!t[Ks],o[Za]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[Za]===e&&!t[Ks]){this.removeListener(s,t);break}}};Jd.exports={CloseEvent:To,ErrorEvent:us,Event:Lt,EventTarget:k0,MessageEvent:Ys};function _r(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(_r,"callListener")});var Er=ce((_C,Kd)=>{"use strict";var{tokenChars:Xs}=is();function ht(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(ht,"push");function D0(s){let e=Object.create(null),t=Object.create(null),o=!1,n=!1,r=!1,i,c,u=-1,d=-1,p=-1,f=0;for(;f<s.length;f++)if(d=s.charCodeAt(f),i===void 0)if(p===-1&&Xs[d]===1)u===-1&&(u=f);else if(f!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);d===44?(ht(e,g,t),t=Object.create(null)):i=g,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&Xs[d]===1)u===-1&&(u=f);else if(d===32||d===9)p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),ht(t,s.slice(u,p),!0),d===44&&(ht(e,i,t),t=Object.create(null),i=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=s.slice(u,f),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(n){if(Xs[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(Xs[d]===1)u===-1&&(u=f);else if(d===34&&u!==-1)r=!1,p=f;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&s.charCodeAt(f-1)===61)r=!0;else if(p===-1&&Xs[d]===1)u===-1&&(u=f);else if(u!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);o&&(g=g.replace(/\\/g,""),o=!1),ht(t,c,g),d===44&&(ht(e,i,t),t=Object.create(null),i=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(u===-1||r||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=s.slice(u,p);return i===void 0?ht(e,m,t):(c===void 0?ht(t,m,!0):o?ht(t,c,m.replace(/\\/g,"")):ht(t,c,m),ht(e,i,t)),e}l(D0,"parse");function v0(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(o=>[e].concat(Object.keys(o).map(n=>{let r=o[n];return Array.isArray(r)||(r=[r]),r.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}l(v0,"format");Kd.exports={format:v0,parse:D0}});var Ar=ce((RC,ap)=>{"use strict";var S0=require("events"),x0=require("https"),C0=require("http"),Qd=require("net"),$0=require("tls"),{randomBytes:_0,createHash:E0}=require("crypto"),{Duplex:FC,Readable:TC}=require("stream"),{URL:ec}=require("url"),io=rs(),F0=Ka(),T0=Qa(),{isBlob:R0}=is(),{BINARY_TYPES:Yd,CLOSE_TIMEOUT:A0,EMPTY_BUFFER:Fr,GUID:P0,kForOnEventAttribute:tc,kListener:O0,kStatusCode:M0,kWebSocket:we,NOOP:Zd}=jt(),{EventTarget:{addEventListener:I0,removeEventListener:j0}}=zd(),{format:N0,parse:L0}=Er(),{toBuffer:B0}=Js(),ep=Symbol("kAborted"),oc=[8,13],Bt=["CONNECTING","OPEN","CLOSING","CLOSED"],U0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends S0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=Yd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(o=t,t=[]):t=[t]),tp(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,o){let n=new F0({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),r=new T0(e,this._extensions,o.generateMask);this._receiver=n,this._sender=r,this._socket=e,n[we]=this,r[we]=this,e[we]=this,n.on("conclude",G0),n.on("drain",q0),n.on("error",V0),n.on("message",J0),n.on("ping",z0),n.on("pong",K0),r.onerror=Y0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",np),e.on("data",Rr),e.on("end",rp),e.on("error",ip),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[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){Le(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),sp(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){sc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Fr,t,o)}pong(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){sc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Fr,t,o)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(o=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){sc(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[io.extensionName]||(n.compress=!1),this._sender.send(e||Fr,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ie,"CONNECTING",{enumerable:!0,value:Bt.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:Bt.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:Bt.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:Bt.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:Bt.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:Bt.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:Bt.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:Bt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ie.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ie.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[tc])return e[O0];return null},set(e){for(let t of this.listeners(s))if(t[tc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[tc]:!0})}})});ie.prototype.addEventListener=I0;ie.prototype.removeEventListener=j0;ap.exports=ie;function tp(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:A0,protocolVersion:oc[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=n.autoPong,s._closeTimeout=n.closeTimeout,!oc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${oc.join(", ")})`);let r;if(e instanceof ec)r=e;else try{r=new ec(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let b=new SyntaxError(u);if(s._redirects===0)throw b;Tr(s,b);return}let d=i?443:80,p=_0(16).toString("base64"),f=i?x0.request:C0.request,m=new Set,g;if(n.createConnection=n.createConnection||(i?H0:W0),n.defaultPort=n.defaultPort||d,n.port=r.port||d,n.host=r.hostname.startsWith("[")?r.hostname.slice(1,-1):r.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=r.pathname+r.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(g=new io({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=N0({[io.extensionName]:g.offer()})),t.length){for(let b of t){if(typeof b!="string"||!U0.test(b)||m.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(b)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let b=n.path.split(":");n.socketPath=b[0],n.path=b[1]}let h;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let b=o&&o.headers;if(o={...o,headers:{}},b)for(let[k,v]of Object.entries(b))o.headers[k.toLowerCase()]=v}else if(s.listenerCount("redirect")===0){let b=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!b||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,b||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),h=s._req=f(n),s._redirects&&s.emit("redirect",s.url,h)}else h=s._req=f(n);n.timeout&&h.on("timeout",()=>{Le(s,h,"Opening handshake has timed out")}),h.on("error",b=>{h===null||h[ep]||(h=s._req=null,Tr(s,b))}),h.on("response",b=>{let k=b.headers.location,v=b.statusCode;if(k&&n.followRedirects&&v>=300&&v<400){if(++s._redirects>n.maxRedirects){Le(s,h,"Maximum redirects exceeded");return}h.abort();let x;try{x=new ec(k,e)}catch{let C=new SyntaxError(`Invalid URL: ${k}`);Tr(s,C);return}tp(s,x,t,o)}else s.emit("unexpected-response",h,b)||Le(s,h,`Unexpected server response: ${b.statusCode}`)}),h.on("upgrade",(b,k,v)=>{if(s.emit("upgrade",b),s.readyState!==ie.CONNECTING)return;h=s._req=null;let x=b.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){Le(s,k,"Invalid Upgrade header");return}let _=E0("sha1").update(p+P0).digest("base64");if(b.headers["sec-websocket-accept"]!==_){Le(s,k,"Invalid Sec-WebSocket-Accept header");return}let C=b.headers["sec-websocket-protocol"],E;if(C!==void 0?m.size?m.has(C)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){Le(s,k,E);return}C&&(s._protocol=C);let I=b.headers["sec-websocket-extensions"];if(I!==void 0){if(!g){Le(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=L0(I)}catch{Le(s,k,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(ae);if(K.length!==1||K[0]!==io.extensionName){Le(s,k,"Server indicated an extension that was not requested");return}try{g.accept(ae[io.extensionName])}catch{Le(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[io.extensionName]=g}s.setSocket(k,v,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(h,s):h.end()}l(tp,"initAsClient");function Tr(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Tr,"emitErrorAndClose");function W0(s){return s.path=s.socketPath,Qd.connect(s)}l(W0,"netConnect");function H0(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Qd.isIP(s.host)?"":s.host),$0.connect(s)}l(H0,"tlsConnect");function Le(s,e,t){s._readyState=ie.CLOSING;let o=new Error(t);Error.captureStackTrace(o,Le),e.setHeader?(e[ep]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Tr,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(Le,"abortHandshake");function sc(s,e,t){if(e){let o=R0(e)?e.size:B0(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Bt[s.readyState]})`);process.nextTick(t,o)}}l(sc,"sendAfterClose");function G0(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Rr),process.nextTick(op,t._socket),s===1005?t.close():t.close(s,e))}l(G0,"receiverOnConclude");function q0(){let s=this[we];s.isPaused||s._socket.resume()}l(q0,"receiverOnDrain");function V0(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Rr),process.nextTick(op,e._socket),e.close(s[M0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(V0,"receiverOnError");function Xd(){this[we].emitClose()}l(Xd,"receiverOnFinish");function J0(s,e){this[we].emit("message",s,e)}l(J0,"receiverOnMessage");function z0(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,Zd),e.emit("ping",s)}l(z0,"receiverOnPing");function K0(s){this[we].emit("pong",s)}l(K0,"receiverOnPong");function op(s){s.resume()}l(op,"resume");function Y0(s){let e=this[we];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,sp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(Y0,"senderOnError");function sp(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(sp,"setCloseTimer");function np(){let s=this[we];if(this.removeListener("close",np),this.removeListener("data",Rr),this.removeListener("end",rp),s._readyState=ie.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[we]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Xd),s._receiver.on("finish",Xd))}l(np,"socketOnClose");function Rr(s){this[we]._receiver.write(s)||this.pause()}l(Rr,"socketOnData");function rp(){let s=this[we];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}l(rp,"socketOnEnd");function ip(){let s=this[we];this.removeListener("error",ip),this.on("error",Zd),s&&(s._readyState=ie.CLOSING,this.destroy())}l(ip,"socketOnError")});var dp=ce((OC,up)=>{"use strict";var PC=Ar(),{Duplex:X0}=require("stream");function cp(s){s.emit("close")}l(cp,"emitClose");function Q0(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(Q0,"duplexOnEnd");function lp(s){this.removeListener("error",lp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(lp,"duplexOnError");function Z0(s,e){let t=!0,o=new X0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",l(function(r,i){let c=!i&&o._readableState.objectMode?r.toString():r;o.push(c)||s.pause()},"message")),s.once("error",l(function(r){o.destroyed||(t=!1,o.destroy(r))},"error")),s.once("close",l(function(){o.destroyed||o.push(null)},"close")),o._destroy=function(n,r){if(s.readyState===s.CLOSED){r(n),process.nextTick(cp,o);return}let i=!1;s.once("error",l(function(u){i=!0,r(u)},"error")),s.once("close",l(function(){i||r(n),process.nextTick(cp,o)},"close")),t&&s.terminate()},o._final=function(n){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._final(n)},"open"));return}s._socket!==null&&(s._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(s._socket.once("finish",l(function(){n()},"finish")),s.close()))},o._read=function(){s.isPaused&&s.resume()},o._write=function(n,r,i){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._write(n,r,i)},"open"));return}s.send(n,i)},o.on("end",Q0),o.on("error",lp),o}l(Z0,"createWebSocketStream");up.exports=Z0});var nc=ce((IC,pp)=>{"use strict";var{tokenChars:eb}=is();function tb(s){let e=new Set,t=-1,o=-1,n=0;for(n;n<s.length;n++){let i=s.charCodeAt(n);if(o===-1&&eb[i]===1)t===-1&&(t=n);else if(n!==0&&(i===32||i===9))o===-1&&t!==-1&&(o=n);else if(i===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let c=s.slice(t,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(t===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let r=s.slice(t,n);if(e.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);return e.add(r),e}l(tb,"parse");pp.exports={parse:tb}});var wp=ce((LC,bp)=>{"use strict";var ob=require("events"),Pr=require("http"),{Duplex:NC}=require("stream"),{createHash:sb}=require("crypto"),mp=Er(),Ro=rs(),nb=nc(),rb=Ar(),{CLOSE_TIMEOUT:ib,GUID:ab,kWebSocket:cb}=jt(),lb=/^[+/0-9A-Za-z]{22}==$/,fp=0,gp=1,yp=2,rc=class extends ob{static{l(this,"WebSocketServer")}constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ib,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:rb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Pr.createServer((o,n)=>{let r=Pr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),n.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=ub(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:l((n,r,i)=>{this.handleUpgrade(n,r,i,o)},"upgrade")})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=fp}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Qs,this);return}if(e&&this.once("close",e),this._state!==gp)if(this._state=gp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Qs,this):process.nextTick(Qs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Qs(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,o,n){t.on("error",hp);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){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||!lb.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)){Zs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=nb.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=mp.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 Zs(t,h||401,b,k);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return Zs(t,401)}this.completeUpgrade(f,r,d,e,t,o,n)}completeUpgrade(e,t,o,n,r,i,c){if(!r.readable||!r.writable)return r.destroy();if(r[cb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fp)return Zs(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${sb("sha1").update(t+ab).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(o.size){let f=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Ro.extensionName]){let f=e[Ro.extensionName].params,m=mp.format({[Ro.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
152
|
+
`)[0].slice(0,150);x.content=_?`[error] ${C}`:`[ok] ${C}`,d++}}}if(lr(u)<=i)return{messages:u,elided:d,savedTokens:p-no(u)};let h=Math.floor(i*.85),b=lr(u);for(;b>h&&u.length>6;){let k=u.findIndex(_=>_.role==="user");if(k<0)break;let v=k;for(let _=k+1;_<u.length;_++){let C=u[_];if(C.role==="user"&&!("tool_call_id"in C))break;v=_}let x=u.splice(k,v-k+1);for(let _ of x)b-=_.content?.length||0,_.tool_calls&&(b-=JSON.stringify(_.tool_calls).length);d+=x.length}if(u.length<s.length){let k=["[CONVERSATION CONTEXT \u2014 older messages were summarized to fit within the token limit]","Continue working with the remaining context."],v=u[0]?.role==="system"?1:0;u.splice(v,0,{role:"user",content:k.join(`
|
|
153
|
+
`),timestamp:Date.now()})}return{messages:u,elided:d,savedTokens:p-no(u)}}function lr(s){return s.reduce((e,t)=>e+(t.content?.length||0)+(t.tool_calls?JSON.stringify(t.tool_calls).length:0),0)}var $y,Oa=H(()=>{"use strict";l(Aa,"estimateTokens");l(no,"estimateContextTokens");l(ur,"resolveContextWindow");$y=new Map;l(nd,"shouldCompact");l(Pa,"compactMessages");l(lr,"totalChars")});var Xo={};Te(Xo,{AgentLoop:()=>Se});var rd,_y,Se,ze=H(()=>{"use strict";rd=require("node:events");Cu();Eu();Tu();va();Sa();Zu();Q();sd();Oa();_y=1/0,Se=class extends rd.EventEmitter{static{l(this,"AgentLoop")}opts;toolExecutor;abortController;state;messages=[];filesModified=new Set;contextWindow;_approvalResolve=null;_userInputResolve=null;_hookRunner;_insideThinkTag=!1;constructor(e){if(super(),this.opts=e,this.abortController=new AbortController,this.toolExecutor=new Qn({workspace:e.workspace,platformUrl:e.platformUrl,token:e.token,signal:this.abortController.signal}),e.sandboxed){let t=new es(sr(e.workspace,{enabled:!0,provider:"auto",network:"none"}));this.toolExecutor.setSandbox(t),t.initialize().catch(()=>{})}this._hookRunner=new _o(e.workspace),this.state={runId:crypto.randomUUID(),status:"idle",tokensIn:0,tokensOut:0,tokensCached:0,costUsd:0,turns:0},this.contextWindow=ur(e.model),this.toolExecutor.setRunId(this.state.runId)}async run(e){let t=Date.now(),o=this.opts.maxTurns||_y;this.updateState({status:"streaming"}),this._hookRunner.fire("SessionStart",{workspace:this.opts.workspace,data:{prompt:e,model:this.opts.model,mode:this.opts.mode}}).catch(()=>{}),this.messages=od({workspace:this.opts.workspace,mode:this.opts.mode,model:this.opts.model,sandboxed:this.opts.sandboxed||!1,webEnabled:this.opts.webEnabled!==!1}),this.messages.push({role:"user",content:e,timestamp:Date.now()});try{for(let r=0;r<o;r++){if(this.abortController.signal.aborted){this.updateState({status:"cancelled"});break}this.updateState({status:"streaming",turns:r+1}),this.emitEvent({type:"streaming_start"});let i=no(this.messages);if(nd(i,this.contextWindow)){let u=Pa(this.messages,this.contextWindow);if(u.elided>0){this.messages.length=0,this.messages.push(...u.messages);let d=no(this.messages);this.emitEvent({type:"context_compacted",elided:u.elided,savedTokens:u.savedTokens,contextUsed:d,contextWindow:this.contextWindow})}}let c=await this.streamCompletion();if(!c){this.emitEvent({type:"run_error",error:"No response from model"}),this.updateState({status:"error",error:"No response from model"});break}if(this.messages.push(c),this.emitEvent({type:"streaming_end",content:c.content}),c.tool_calls&&c.tool_calls.length>0){let u=new Set(["read_file","list_dir","grep_search","web_search","read_url","get_file_info","codebase_search","find_symbol"]),d=c.tool_calls.filter(m=>m.name==="ask_user"),p=c.tool_calls.filter(m=>m.name!=="ask_user"&&u.has(m.name)),f=c.tool_calls.filter(m=>m.name!=="ask_user"&&!u.has(m.name));for(let m of d){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments});let g=m.arguments.question||"What would you like to do?";this.updateState({status:"waiting_user_input"}),this.emitEvent({type:"ask_user",question:g});let h=await this.waitForUserInput();this.messages.push({role:"tool",content:`User response: ${h}`,tool_call_id:m.id,name:m.name,timestamp:Date.now()}),this.emitEvent({type:"tool_call_result",name:m.name,result:`User: ${h}`})}if(p.length>0){for(let g of p)this.emitEvent({type:"tool_call_start",name:g.name,args:g.arguments});this.updateState({status:"tool_executing",currentToolCall:`${p.length} parallel reads`});let m=await Promise.all(p.map(async g=>{let h=await this.toolExecutor.execute(g.name,g.arguments);return{toolCall:g,result:h}}));for(let{toolCall:g,result:h}of m)g.result=h.output,this.emitEvent({type:"tool_call_result",name:g.name,result:h.output}),this.messages.push({role:"tool",content:h.output,tool_call_id:g.id,name:g.name,timestamp:Date.now()})}for(let m of f){this.updateState({status:"tool_executing",currentToolCall:m.name}),this.emitEvent({type:"tool_call_start",name:m.name,args:m.arguments}),m.name==="todo_write"&&m.arguments.todos&&this.emitEvent({type:"todo_update",todos:m.arguments.todos});let g=await this._hookRunner.fire("PreToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments}});if(g.some(k=>k.action==="deny")){let k=g.find(v=>v.action==="deny")?.stderr||"Blocked by PreToolUse hook";m.result=`HOOK DENIED: ${k}`,this.emitEvent({type:"tool_call_result",name:m.name,result:m.result}),this.messages.push({role:"tool",content:m.result,tool_call_id:m.id,name:m.name,timestamp:Date.now()});continue}let b=await this.toolExecutor.execute(m.name,m.arguments);if(b.wroteFiles&&b.touchedFiles)for(let k of b.touchedFiles)this.filesModified.add(k);this._hookRunner.fire("PostToolUse",{sessionId:this.state.runId,workspace:this.opts.workspace,data:{tool:m.name,arguments:m.arguments,result:b.output.slice(0,1e3),wroteFiles:b.wroteFiles}}).catch(()=>{}),m.result=b.output,this.emitEvent({type:"tool_call_result",name:m.name,result:b.output}),this.messages.push({role:"tool",content:b.output,tool_call_id:m.id,name:m.name,timestamp:Date.now()})}continue}this.updateState({status:"done"});break}}catch(r){let i=r instanceof Error?r.message:String(r);this.emitEvent({type:"run_error",error:i}),this.updateState({status:"error",error:i})}let n={turns:this.state.turns,tokensIn:this.state.tokensIn,tokensOut:this.state.tokensOut,tokensCached:this.state.tokensCached,costUsd:this.state.costUsd,duration:Date.now()-t,filesModified:Array.from(this.filesModified)};return this.emitEvent({type:"run_complete",summary:n}),n}cancel(){this.abortController.abort(),this.updateState({status:"cancelled"})}resolveUserInput(e){this._userInputResolve&&(this._userInputResolve(e),this._userInputResolve=null)}resolveApproval(e){this._approvalResolve&&(this._approvalResolve(e),this._approvalResolve=null)}getCheckpoints(){return this.toolExecutor.getCheckpoints()}getMessages(){return[...this.messages]}manualCompact(e=4){let t=Pa(this.messages,e);return t.elided>0&&(this.messages.length=0,this.messages.push(...t.messages)),t}getContextStats(){let e=no(this.messages);return{used:e,window:this.contextWindow,pct:this.contextWindow>0?Math.min(100,Math.round(e/this.contextWindow*100)):0,messageCount:this.messages.length}}getConversationHistory(){return this.messages.map(e=>({role:e.role,content:e.content}))}async streamCompletion(){let e=_u(this.opts.webEnabled!==!1),t=this.getAuthHeaders(),o={model:this.opts.model,messages:this.messages.map(C=>({role:C.role,content:C.content,...C.tool_calls?{tool_calls:C.tool_calls.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))}:{},...C.tool_call_id?{tool_call_id:C.tool_call_id}:{},...C.name?{name:C.name}:{}})),tools:e,stream:!0,temperature:0};this.opts.effort==="reasoning"&&(o.reasoning_effort="medium");let n={"Content-Type":"application/json",...t},r=z(),i=Qu(this.opts.model,r,t),c;try{c=await fetch(i.url,{method:"POST",headers:i.headers,body:JSON.stringify(o),signal:this.abortController.signal})}catch(C){if(C instanceof Error&&C.name==="AbortError")return null;throw C}if(!c.ok){let C=await c.text();throw c.status===401?new Error("Authentication failed \u2014 run `mc auth login` to authenticate."):c.status===403?new Error("Access denied \u2014 your plan may not include this model, or your quota is exhausted."):c.status===429?new Error("Rate limited \u2014 please wait a moment and try again."):new Error(`Model API error ${c.status}: ${C}`)}let u="",d=new Xn,p="",f=!1,m="",g="<think>",h="</think>",b=l(()=>{p&&(this.emitEvent({type:"streaming_chunk",content:p}),p="")},"flushDisplay"),k=l(C=>{f?(m+=C,h.startsWith(m)?m===h&&(f=!1,m=""):(m="",C==="<"&&(m="<"))):C==="<"&&!m?m="<":m?(m+=C,g.startsWith(m)?m===g&&(f=!0,m=""):h.startsWith(m)?m===h&&(m=""):(p+=m,m="")):p+=C},"feedChar");for await(let C of xu(c)){if(!C.choices||C.choices.length===0){C.usage&&this.updateState({tokensIn:this.state.tokensIn+(C.usage.prompt_tokens||0),tokensOut:this.state.tokensOut+(C.usage.completion_tokens||0),tokensCached:this.state.tokensCached+(C.usage.prompt_tokens_details?.cached_tokens||0)});continue}let E=C.choices[0];if(E.delta?.content){u+=E.delta.content;for(let I of E.delta.content)k(I);b()}if(E.delta?.tool_calls&&d.feed(E.delta.tool_calls),E.finish_reason==="tool_calls"||E.finish_reason==="stop")break}m&&!f&&(p+=m),b();let v=d.flush(),_={role:"assistant",content:u.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||u,timestamp:Date.now()};return v.length>0&&(_.tool_calls=v.map(C=>{let E={};try{E=JSON.parse(C.arguments)}catch{E={_raw:C.arguments}}return{id:C.id,name:C.name,arguments:E}})),_}getAuthHeaders(){let e={Authorization:`Bearer ${this.opts.token}`};return this.opts.userId&&(e["X-User-Id"]=this.opts.userId),this.opts.orgId&&(e["X-Org-Id"]=this.opts.orgId),e}async waitForUserInput(){return new Promise(e=>{this._userInputResolve=e})}updateState(e){Object.assign(this.state,e),this.emitEvent({type:"state_update",state:{...this.state}})}emitEvent(e){this.emit("event",e)}}});var Nt=ce((uC,wd)=>{"use strict";var yd=["nodebuffer","arraybuffer","fragments"],bd=typeof Blob<"u";bd&&yd.push("blob");wd.exports={BINARY_TYPES:yd,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bd,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:l(()=>{},"NOOP")}});var zs=ce((pC,kr)=>{"use strict";var{EMPTY_BUFFER:qy}=Nt(),La=Buffer[Symbol.species];function Vy(s,e){if(s.length===0)return qy;if(s.length===1)return s[0];let t=Buffer.allocUnsafe(e),o=0;for(let n=0;n<s.length;n++){let r=s[n];t.set(r,o),o+=r.length}return o<e?new La(t.buffer,t.byteOffset,o):t}l(Vy,"concat");function kd(s,e,t,o,n){for(let r=0;r<n;r++)t[o+r]=s[r]^e[r&3]}l(kd,"_mask");function Dd(s,e){for(let t=0;t<s.length;t++)s[t]^=e[t&3]}l(Dd,"_unmask");function zy(s){return s.length===s.buffer.byteLength?s.buffer:s.buffer.slice(s.byteOffset,s.byteOffset+s.length)}l(zy,"toArrayBuffer");function Ba(s){if(Ba.readOnly=!0,Buffer.isBuffer(s))return s;let e;return s instanceof ArrayBuffer?e=new La(s):ArrayBuffer.isView(s)?e=new La(s.buffer,s.byteOffset,s.byteLength):(e=Buffer.from(s),Ba.readOnly=!1),e}l(Ba,"toBuffer");kr.exports={concat:Vy,mask:kd,toArrayBuffer:zy,toBuffer:Ba,unmask:Dd};if(!process.env.WS_NO_BUFFER_UTIL)try{let s=require("bufferutil");kr.exports.mask=function(e,t,o,n,r){r<48?kd(e,t,o,n,r):s.mask(e,t,o,n,r)},kr.exports.unmask=function(e,t){e.length<32?Dd(e,t):s.unmask(e,t)}}catch{}});var xd=ce((fC,Sd)=>{"use strict";var vd=Symbol("kDone"),Ua=Symbol("kRun"),Wa=class{static{l(this,"Limiter")}constructor(e){this[vd]=()=>{this.pending--,this[Ua]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ua]()}[Ua](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[vd])}}};Sd.exports=Wa});var rs=ce((hC,Ed)=>{"use strict";var Js=require("zlib"),Cd=zs(),Jy=xd(),{kStatusCode:$d}=Nt(),Ky=Buffer[Symbol.species],Yy=Buffer.from([0,0,255,255]),vr=Symbol("permessage-deflate"),Lt=Symbol("total-length"),ss=Symbol("callback"),io=Symbol("buffers"),ns=Symbol("error"),Dr,Ha=class{static{l(this,"PerMessageDeflate")}constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Dr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Dr=new Jy(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ss];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,o=e.find(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&(typeof n.client_max_window_bits=="number"?t.clientMaxWindowBits>n.client_max_window_bits:!n.client_max_window_bits)));if(!o)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(o.server_no_context_takeover=!0),t.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(o.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?o.client_max_window_bits=t.clientMaxWindowBits:(o.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(o=>{let n=t[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let r=+n;if(!Number.isInteger(r)||r<8||r>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=r}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);t[o]=n})}),e}decompress(e,t,o){Dr.add(n=>{this._decompress(e,t,(r,i)=>{n(),o(r,i)})})}compress(e,t,o){Dr.add(n=>{this._compress(e,t,(r,i)=>{n(),o(r,i)})})}_decompress(e,t,o){let n=this._isServer?"client":"server";if(!this._inflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?Js.Z_DEFAULT_WINDOWBITS:this.params[r];this._inflate=Js.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[vr]=this,this._inflate[Lt]=0,this._inflate[io]=[],this._inflate.on("error",Qy),this._inflate.on("data",_d)}this._inflate[ss]=o,this._inflate.write(e),t&&this._inflate.write(Yy),this._inflate.flush(()=>{let r=this._inflate[ns];if(r){this._inflate.close(),this._inflate=null,o(r);return}let i=Cd.concat(this._inflate[io],this._inflate[Lt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Lt]=0,this._inflate[io]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(e,t,o){let n=this._isServer?"server":"client";if(!this._deflate){let r=`${n}_max_window_bits`,i=typeof this.params[r]!="number"?Js.Z_DEFAULT_WINDOWBITS:this.params[r];this._deflate=Js.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[Lt]=0,this._deflate[io]=[],this._deflate.on("data",Xy)}this._deflate[ss]=o,this._deflate.write(e),this._deflate.flush(Js.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let r=Cd.concat(this._deflate[io],this._deflate[Lt]);t&&(r=new Ky(r.buffer,r.byteOffset,r.length-4)),this._deflate[ss]=null,this._deflate[Lt]=0,this._deflate[io]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,r)})}};Ed.exports=Ha;function Xy(s){this[io].push(s),this[Lt]+=s.length}l(Xy,"deflateOnData");function _d(s){if(this[Lt]+=s.length,this[vr]._maxPayload<1||this[Lt]<=this[vr]._maxPayload){this[io].push(s);return}this[ns]=new RangeError("Max payload size exceeded"),this[ns].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ns][$d]=1009,this.removeListener("data",_d),this.reset()}l(_d,"inflateOnData");function Qy(s){if(this[vr]._inflate=null,this[ns]){this[ss](this[ns]);return}s[$d]=1007,this[ss](s)}l(Qy,"inflateOnError")});var is=ce((bC,Sr)=>{"use strict";var{isUtf8:Fd}=require("buffer"),{hasBlob:Zy}=Nt(),e0=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function t0(s){return s>=1e3&&s<=1014&&s!==1004&&s!==1005&&s!==1006||s>=3e3&&s<=4999}l(t0,"isValidStatusCode");function Ga(s){let e=s.length,t=0;for(;t<e;)if(!(s[t]&128))t++;else if((s[t]&224)===192){if(t+1===e||(s[t+1]&192)!==128||(s[t]&254)===192)return!1;t+=2}else if((s[t]&240)===224){if(t+2>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||s[t]===224&&(s[t+1]&224)===128||s[t]===237&&(s[t+1]&224)===160)return!1;t+=3}else if((s[t]&248)===240){if(t+3>=e||(s[t+1]&192)!==128||(s[t+2]&192)!==128||(s[t+3]&192)!==128||s[t]===240&&(s[t+1]&240)===128||s[t]===244&&s[t+1]>143||s[t]>244)return!1;t+=4}else return!1;return!0}l(Ga,"_isValidUTF8");function o0(s){return Zy&&typeof s=="object"&&typeof s.arrayBuffer=="function"&&typeof s.type=="string"&&typeof s.stream=="function"&&(s[Symbol.toStringTag]==="Blob"||s[Symbol.toStringTag]==="File")}l(o0,"isBlob");Sr.exports={isBlob:o0,isValidStatusCode:t0,isValidUTF8:Ga,tokenChars:e0};if(Fd)Sr.exports.isValidUTF8=function(s){return s.length<24?Ga(s):Fd(s)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let s=require("utf-8-validate");Sr.exports.isValidUTF8=function(e){return e.length<32?Ga(e):s(e)}}catch{}});var Ka=ce((kC,Id)=>{"use strict";var{Writable:s0}=require("stream"),Td=rs(),{BINARY_TYPES:n0,EMPTY_BUFFER:Rd,kStatusCode:r0,kWebSocket:i0}=Nt(),{concat:qa,toArrayBuffer:a0,unmask:c0}=zs(),{isValidStatusCode:l0,isValidUTF8:Ad}=is(),xr=Buffer[Symbol.species],Je=0,Pd=1,Od=2,Md=3,Va=4,za=5,Cr=6,Ja=class extends s0{static{l(this,"Receiver")}constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||n0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[i0]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Je}_write(e,t,o){if(this._opcode===8&&this._state==Je)return o();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){o(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(o)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new xr(o.buffer,o.byteOffset+e,o.length-e),new xr(o.buffer,o.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let o=this._buffers[0],n=t.length-e;e>=o.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(o.buffer,o.byteOffset,e),n),this._buffers[0]=new xr(o.buffer,o.byteOffset+e,o.length-e)),e-=o.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Je:this.getInfo(e);break;case Pd:this.getPayloadLength16(e);break;case Od:this.getPayloadLength64(e);break;case Md:this.getMask();break;case Va:this.getData(e);break;case za:case Cr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let o=(t[0]&64)===64;if(o&&!this._extensions[Td.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Pd:this._payloadLength===127?this._state=Od:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),o=t.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);return}this._payloadLength=o*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Md:this._state=Va}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Va}getData(e){let t=Rd;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&c0(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let o=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(o);return}if(this._compressed){this._state=za,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Td.extensionName].decompress(e,this._fin,(n,r)=>{if(n)return t(n);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(i);return}this._fragments.push(r)}this.dataMessage(t),this._state===Je&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Je;return}let t=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=qa(o,t):this._binaryType==="arraybuffer"?n=a0(qa(o,t)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=Je):(this._state=Cr,setImmediate(()=>{this.emit("message",n,!0),this._state=Je,this.startLoop(e)}))}else{let n=qa(o,t);if(!this._skipUTF8Validation&&!Ad(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(r);return}this._state===za||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=Je):(this._state=Cr,setImmediate(()=>{this.emit("message",n,!1),this._state=Je,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Rd),this.end();else{let o=e.readUInt16BE(0);if(!l0(o)){let r=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(r);return}let n=new xr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ad(n)){let r=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(r);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=Je;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Je):(this._state=Cr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Je,this.startLoop(t)}))}createError(e,t,o,n,r){this._loop=!1,this._errored=!0;let i=new e(o?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(i,this.createError),i.code=r,i[r0]=n,i}};Id.exports=Ja});var Qa=ce((SC,Ld)=>{"use strict";var{Duplex:vC}=require("stream"),{randomFillSync:u0}=require("crypto"),{types:{isUint8Array:d0}}=require("util"),jd=rs(),{EMPTY_BUFFER:p0,kWebSocket:m0,NOOP:f0}=Nt(),{isBlob:as,isValidStatusCode:g0}=is(),{mask:Nd,toBuffer:Fo}=zs(),Ke=Symbol("kByteLength"),h0=Buffer.alloc(4),$r=8*1024,To,cs=$r,nt=0,y0=1,b0=2,Ya=class s{static{l(this,"Sender")}constructor(e,t,o){this._extensions=t||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=nt,this.onerror=f0,this[m0]=void 0}static frame(e,t){let o,n=!1,r=2,i=!1;t.mask&&(o=t.maskBuffer||h0,t.generateMask?t.generateMask(o):(cs===$r&&(To===void 0&&(To=Buffer.alloc($r)),u0(To,0,$r),cs=0),o[0]=To[cs++],o[1]=To[cs++],o[2]=To[cs++],o[3]=To[cs++]),i=(o[0]|o[1]|o[2]|o[3])===0,r=6);let c;typeof e=="string"?(!t.mask||i)&&t[Ke]!==void 0?c=t[Ke]:(e=Buffer.from(e),c=e.length):(c=e.length,n=t.mask&&t.readOnly&&!i);let u=c;c>=65536?(r+=8,u=127):c>125&&(r+=2,u=126);let d=Buffer.allocUnsafe(n?c+r:r);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=u,u===126?d.writeUInt16BE(c,2):u===127&&(d[2]=d[3]=0,d.writeUIntBE(c,4,6)),t.mask?(d[1]|=128,d[r-4]=o[0],d[r-3]=o[1],d[r-2]=o[2],d[r-1]=o[3],i?[d,e]:n?(Nd(e,o,d,r,c),[d]):(Nd(e,o,e,0,c),[d,e])):[d,e]}close(e,t,o,n){let r;if(e===void 0)r=p0;else{if(typeof e!="number"||!g0(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)r=Buffer.allocUnsafe(2),r.writeUInt16BE(e,0);else{let c=Buffer.byteLength(t);if(c>123)throw new RangeError("The message must not be greater than 123 bytes");if(r=Buffer.allocUnsafe(2+c),r.writeUInt16BE(e,0),typeof t=="string")r.write(t,2);else if(d0(t))r.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let i={[Ke]:r.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==nt?this.enqueue([this.dispatch,r,!1,i,n]):this.sendFrame(s.frame(r,i),n)}ping(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):as(e)?(n=e.size,r=!1):(e=Fo(e),n=e.length,r=Fo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ke]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:r,rsv1:!1};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}pong(e,t,o){let n,r;if(typeof e=="string"?(n=Buffer.byteLength(e),r=!1):as(e)?(n=e.size,r=!1):(e=Fo(e),n=e.length,r=Fo.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[Ke]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:r,rsv1:!1};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,!1,i,o]):this.getBlobData(e,!1,i,o):this._state!==nt?this.enqueue([this.dispatch,e,!1,i,o]):this.sendFrame(s.frame(e,i),o)}send(e,t,o){let n=this._extensions[jd.extensionName],r=t.binary?2:1,i=t.compress,c,u;typeof e=="string"?(c=Buffer.byteLength(e),u=!1):as(e)?(c=e.size,u=!1):(e=Fo(e),c=e.length,u=Fo.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=c>=n._threshold),this._compress=i):(i=!1,r=0),t.fin&&(this._firstFragment=!0);let d={[Ke]:c,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:u,rsv1:i};as(e)?this._state!==nt?this.enqueue([this.getBlobData,e,this._compress,d,o]):this.getBlobData(e,this._compress,d,o):this._state!==nt?this.enqueue([this.dispatch,e,this._compress,d,o]):this.dispatch(e,this._compress,d,o)}getBlobData(e,t,o,n){this._bufferedBytes+=o[Ke],this._state=b0,e.arrayBuffer().then(r=>{if(this._socket.destroyed){let c=new Error("The socket was closed while the blob was being read");process.nextTick(Xa,this,c,n);return}this._bufferedBytes-=o[Ke];let i=Fo(r);t?this.dispatch(i,t,o,n):(this._state=nt,this.sendFrame(s.frame(i,o),n),this.dequeue())}).catch(r=>{process.nextTick(w0,this,r,n)})}dispatch(e,t,o,n){if(!t){this.sendFrame(s.frame(e,o),n);return}let r=this._extensions[jd.extensionName];this._bufferedBytes+=o[Ke],this._state=y0,r.compress(e,o.fin,(i,c)=>{if(this._socket.destroyed){let u=new Error("The socket was closed while data was being compressed");Xa(this,u,n);return}this._bufferedBytes-=o[Ke],this._state=nt,o.readOnly=!1,this.sendFrame(s.frame(c,o),n),this.dequeue()})}dequeue(){for(;this._state===nt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ke],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ke],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};Ld.exports=Ya;function Xa(s,e,t){typeof t=="function"&&t(e);for(let o=0;o<s._queue.length;o++){let n=s._queue[o],r=n[n.length-1];typeof r=="function"&&r(e)}}l(Xa,"callCallbacks");function w0(s,e,t){Xa(s,e,t),s.onerror(e)}l(w0,"onError")});var Jd=ce((CC,zd)=>{"use strict";var{kForOnEventAttribute:Ks,kListener:Za}=Nt(),Bd=Symbol("kCode"),Ud=Symbol("kData"),Wd=Symbol("kError"),Hd=Symbol("kMessage"),Gd=Symbol("kReason"),ls=Symbol("kTarget"),qd=Symbol("kType"),Vd=Symbol("kWasClean"),Bt=class{static{l(this,"Event")}constructor(e){this[ls]=null,this[qd]=e}get target(){return this[ls]}get type(){return this[qd]}};Object.defineProperty(Bt.prototype,"target",{enumerable:!0});Object.defineProperty(Bt.prototype,"type",{enumerable:!0});var Ro=class extends Bt{static{l(this,"CloseEvent")}constructor(e,t={}){super(e),this[Bd]=t.code===void 0?0:t.code,this[Gd]=t.reason===void 0?"":t.reason,this[Vd]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Bd]}get reason(){return this[Gd]}get wasClean(){return this[Vd]}};Object.defineProperty(Ro.prototype,"code",{enumerable:!0});Object.defineProperty(Ro.prototype,"reason",{enumerable:!0});Object.defineProperty(Ro.prototype,"wasClean",{enumerable:!0});var us=class extends Bt{static{l(this,"ErrorEvent")}constructor(e,t={}){super(e),this[Wd]=t.error===void 0?null:t.error,this[Hd]=t.message===void 0?"":t.message}get error(){return this[Wd]}get message(){return this[Hd]}};Object.defineProperty(us.prototype,"error",{enumerable:!0});Object.defineProperty(us.prototype,"message",{enumerable:!0});var Ys=class extends Bt{static{l(this,"MessageEvent")}constructor(e,t={}){super(e),this[Ud]=t.data===void 0?null:t.data}get data(){return this[Ud]}};Object.defineProperty(Ys.prototype,"data",{enumerable:!0});var k0={addEventListener(s,e,t={}){for(let n of this.listeners(s))if(!t[Ks]&&n[Za]===e&&!n[Ks])return;let o;if(s==="message")o=l(function(r,i){let c=new Ys("message",{data:i?r:r.toString()});c[ls]=this,_r(e,this,c)},"onMessage");else if(s==="close")o=l(function(r,i){let c=new Ro("close",{code:r,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});c[ls]=this,_r(e,this,c)},"onClose");else if(s==="error")o=l(function(r){let i=new us("error",{error:r,message:r.message});i[ls]=this,_r(e,this,i)},"onError");else if(s==="open")o=l(function(){let r=new Bt("open");r[ls]=this,_r(e,this,r)},"onOpen");else return;o[Ks]=!!t[Ks],o[Za]=e,t.once?this.once(s,o):this.on(s,o)},removeEventListener(s,e){for(let t of this.listeners(s))if(t[Za]===e&&!t[Ks]){this.removeListener(s,t);break}}};zd.exports={CloseEvent:Ro,ErrorEvent:us,Event:Bt,EventTarget:k0,MessageEvent:Ys};function _r(s,e,t){typeof s=="object"&&s.handleEvent?s.handleEvent.call(s,t):s.call(e,t)}l(_r,"callListener")});var Er=ce((_C,Kd)=>{"use strict";var{tokenChars:Xs}=is();function ht(s,e,t){s[e]===void 0?s[e]=[t]:s[e].push(t)}l(ht,"push");function D0(s){let e=Object.create(null),t=Object.create(null),o=!1,n=!1,r=!1,i,c,u=-1,d=-1,p=-1,f=0;for(;f<s.length;f++)if(d=s.charCodeAt(f),i===void 0)if(p===-1&&Xs[d]===1)u===-1&&(u=f);else if(f!==0&&(d===32||d===9))p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);d===44?(ht(e,g,t),t=Object.create(null)):i=g,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);else if(c===void 0)if(p===-1&&Xs[d]===1)u===-1&&(u=f);else if(d===32||d===9)p===-1&&u!==-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f),ht(t,s.slice(u,p),!0),d===44&&(ht(e,i,t),t=Object.create(null),i=void 0),u=p=-1}else if(d===61&&u!==-1&&p===-1)c=s.slice(u,f),u=p=-1;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(n){if(Xs[d]!==1)throw new SyntaxError(`Unexpected character at index ${f}`);u===-1?u=f:o||(o=!0),n=!1}else if(r)if(Xs[d]===1)u===-1&&(u=f);else if(d===34&&u!==-1)r=!1,p=f;else if(d===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${f}`);else if(d===34&&s.charCodeAt(f-1)===61)r=!0;else if(p===-1&&Xs[d]===1)u===-1&&(u=f);else if(u!==-1&&(d===32||d===9))p===-1&&(p=f);else if(d===59||d===44){if(u===-1)throw new SyntaxError(`Unexpected character at index ${f}`);p===-1&&(p=f);let g=s.slice(u,p);o&&(g=g.replace(/\\/g,""),o=!1),ht(t,c,g),d===44&&(ht(e,i,t),t=Object.create(null),i=void 0),c=void 0,u=p=-1}else throw new SyntaxError(`Unexpected character at index ${f}`);if(u===-1||r||d===32||d===9)throw new SyntaxError("Unexpected end of input");p===-1&&(p=f);let m=s.slice(u,p);return i===void 0?ht(e,m,t):(c===void 0?ht(t,m,!0):o?ht(t,c,m.replace(/\\/g,"")):ht(t,c,m),ht(e,i,t)),e}l(D0,"parse");function v0(s){return Object.keys(s).map(e=>{let t=s[e];return Array.isArray(t)||(t=[t]),t.map(o=>[e].concat(Object.keys(o).map(n=>{let r=o[n];return Array.isArray(r)||(r=[r]),r.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}l(v0,"format");Kd.exports={format:v0,parse:D0}});var Ar=ce((RC,ap)=>{"use strict";var S0=require("events"),x0=require("https"),C0=require("http"),Qd=require("net"),$0=require("tls"),{randomBytes:_0,createHash:E0}=require("crypto"),{Duplex:FC,Readable:TC}=require("stream"),{URL:ec}=require("url"),ao=rs(),F0=Ka(),T0=Qa(),{isBlob:R0}=is(),{BINARY_TYPES:Yd,CLOSE_TIMEOUT:A0,EMPTY_BUFFER:Fr,GUID:P0,kForOnEventAttribute:tc,kListener:O0,kStatusCode:M0,kWebSocket:we,NOOP:Zd}=Nt(),{EventTarget:{addEventListener:I0,removeEventListener:j0}}=Jd(),{format:N0,parse:L0}=Er(),{toBuffer:B0}=zs(),ep=Symbol("kAborted"),oc=[8,13],Ut=["CONNECTING","OPEN","CLOSING","CLOSED"],U0=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ie=class s extends S0{static{l(this,"WebSocket")}constructor(e,t,o){super(),this._binaryType=Yd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Fr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=s.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(o=t,t=[]):t=[t]),tp(this,e,t,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,o){let n=new F0({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:o.maxBufferedChunks,maxFragments:o.maxFragments,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),r=new T0(e,this._extensions,o.generateMask);this._receiver=n,this._sender=r,this._socket=e,n[we]=this,r[we]=this,e[we]=this,n.on("conclude",G0),n.on("drain",q0),n.on("error",V0),n.on("message",z0),n.on("ping",J0),n.on("pong",K0),r.onerror=Y0,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",np),e.on("data",Rr),e.on("end",rp),e.on("error",ip),this._readyState=s.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ao.extensionName]&&this._extensions[ao.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=s.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===s.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=s.CLOSING,this._sender.close(e,t,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),sp(this)}}pause(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){sc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Fr,t,o)}pong(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(o=e,e=t=void 0):typeof t=="function"&&(o=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){sc(this,e,o);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Fr,t,o)}resume(){this.readyState===s.CONNECTING||this.readyState===s.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,o){if(this.readyState===s.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(o=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==s.OPEN){sc(this,e,o);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ao.extensionName]||(n.compress=!1),this._sender.send(e||Fr,n,o)}terminate(){if(this.readyState!==s.CLOSED){if(this.readyState===s.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=s.CLOSING,this._socket.destroy())}}};Object.defineProperty(ie,"CONNECTING",{enumerable:!0,value:Ut.indexOf("CONNECTING")});Object.defineProperty(ie.prototype,"CONNECTING",{enumerable:!0,value:Ut.indexOf("CONNECTING")});Object.defineProperty(ie,"OPEN",{enumerable:!0,value:Ut.indexOf("OPEN")});Object.defineProperty(ie.prototype,"OPEN",{enumerable:!0,value:Ut.indexOf("OPEN")});Object.defineProperty(ie,"CLOSING",{enumerable:!0,value:Ut.indexOf("CLOSING")});Object.defineProperty(ie.prototype,"CLOSING",{enumerable:!0,value:Ut.indexOf("CLOSING")});Object.defineProperty(ie,"CLOSED",{enumerable:!0,value:Ut.indexOf("CLOSED")});Object.defineProperty(ie.prototype,"CLOSED",{enumerable:!0,value:Ut.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(s=>{Object.defineProperty(ie.prototype,s,{enumerable:!0})});["open","error","close","message"].forEach(s=>{Object.defineProperty(ie.prototype,`on${s}`,{enumerable:!0,get(){for(let e of this.listeners(s))if(e[tc])return e[O0];return null},set(e){for(let t of this.listeners(s))if(t[tc]){this.removeListener(s,t);break}typeof e=="function"&&this.addEventListener(s,e,{[tc]:!0})}})});ie.prototype.addEventListener=I0;ie.prototype.removeEventListener=j0;ap.exports=ie;function tp(s,e,t,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:A0,protocolVersion:oc[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(s._autoPong=n.autoPong,s._closeTimeout=n.closeTimeout,!oc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${oc.join(", ")})`);let r;if(e instanceof ec)r=e;else try{r=new ec(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}r.protocol==="http:"?r.protocol="ws:":r.protocol==="https:"&&(r.protocol="wss:"),s._url=r.href;let i=r.protocol==="wss:",c=r.protocol==="ws+unix:",u;if(r.protocol!=="ws:"&&!i&&!c?u=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:c&&!r.pathname?u="The URL's pathname is empty":r.hash&&(u="The URL contains a fragment identifier"),u){let b=new SyntaxError(u);if(s._redirects===0)throw b;Tr(s,b);return}let d=i?443:80,p=_0(16).toString("base64"),f=i?x0.request:C0.request,m=new Set,g;if(n.createConnection=n.createConnection||(i?H0:W0),n.defaultPort=n.defaultPort||d,n.port=r.port||d,n.host=r.hostname.startsWith("[")?r.hostname.slice(1,-1):r.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":p,Connection:"Upgrade",Upgrade:"websocket"},n.path=r.pathname+r.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(g=new ao({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=N0({[ao.extensionName]:g.offer()})),t.length){for(let b of t){if(typeof b!="string"||!U0.test(b)||m.has(b))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(b)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(r.username||r.password)&&(n.auth=`${r.username}:${r.password}`),c){let b=n.path.split(":");n.socketPath=b[0],n.path=b[1]}let h;if(n.followRedirects){if(s._redirects===0){s._originalIpc=c,s._originalSecure=i,s._originalHostOrSocketPath=c?n.socketPath:r.host;let b=o&&o.headers;if(o={...o,headers:{}},b)for(let[k,v]of Object.entries(b))o.headers[k.toLowerCase()]=v}else if(s.listenerCount("redirect")===0){let b=c?s._originalIpc?n.socketPath===s._originalHostOrSocketPath:!1:s._originalIpc?!1:r.host===s._originalHostOrSocketPath;(!b||s._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,b||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),h=s._req=f(n),s._redirects&&s.emit("redirect",s.url,h)}else h=s._req=f(n);n.timeout&&h.on("timeout",()=>{Le(s,h,"Opening handshake has timed out")}),h.on("error",b=>{h===null||h[ep]||(h=s._req=null,Tr(s,b))}),h.on("response",b=>{let k=b.headers.location,v=b.statusCode;if(k&&n.followRedirects&&v>=300&&v<400){if(++s._redirects>n.maxRedirects){Le(s,h,"Maximum redirects exceeded");return}h.abort();let x;try{x=new ec(k,e)}catch{let C=new SyntaxError(`Invalid URL: ${k}`);Tr(s,C);return}tp(s,x,t,o)}else s.emit("unexpected-response",h,b)||Le(s,h,`Unexpected server response: ${b.statusCode}`)}),h.on("upgrade",(b,k,v)=>{if(s.emit("upgrade",b),s.readyState!==ie.CONNECTING)return;h=s._req=null;let x=b.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){Le(s,k,"Invalid Upgrade header");return}let _=E0("sha1").update(p+P0).digest("base64");if(b.headers["sec-websocket-accept"]!==_){Le(s,k,"Invalid Sec-WebSocket-Accept header");return}let C=b.headers["sec-websocket-protocol"],E;if(C!==void 0?m.size?m.has(C)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){Le(s,k,E);return}C&&(s._protocol=C);let I=b.headers["sec-websocket-extensions"];if(I!==void 0){if(!g){Le(s,k,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let ae;try{ae=L0(I)}catch{Le(s,k,"Invalid Sec-WebSocket-Extensions header");return}let K=Object.keys(ae);if(K.length!==1||K[0]!==ao.extensionName){Le(s,k,"Server indicated an extension that was not requested");return}try{g.accept(ae[ao.extensionName])}catch{Le(s,k,"Invalid Sec-WebSocket-Extensions header");return}s._extensions[ao.extensionName]=g}s.setSocket(k,v,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(h,s):h.end()}l(tp,"initAsClient");function Tr(s,e){s._readyState=ie.CLOSING,s._errorEmitted=!0,s.emit("error",e),s.emitClose()}l(Tr,"emitErrorAndClose");function W0(s){return s.path=s.socketPath,Qd.connect(s)}l(W0,"netConnect");function H0(s){return s.path=void 0,!s.servername&&s.servername!==""&&(s.servername=Qd.isIP(s.host)?"":s.host),$0.connect(s)}l(H0,"tlsConnect");function Le(s,e,t){s._readyState=ie.CLOSING;let o=new Error(t);Error.captureStackTrace(o,Le),e.setHeader?(e[ep]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Tr,s,o)):(e.destroy(o),e.once("error",s.emit.bind(s,"error")),e.once("close",s.emitClose.bind(s)))}l(Le,"abortHandshake");function sc(s,e,t){if(e){let o=R0(e)?e.size:B0(e).length;s._socket?s._sender._bufferedBytes+=o:s._bufferedAmount+=o}if(t){let o=new Error(`WebSocket is not open: readyState ${s.readyState} (${Ut[s.readyState]})`);process.nextTick(t,o)}}l(sc,"sendAfterClose");function G0(s,e){let t=this[we];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=s,t._socket[we]!==void 0&&(t._socket.removeListener("data",Rr),process.nextTick(op,t._socket),s===1005?t.close():t.close(s,e))}l(G0,"receiverOnConclude");function q0(){let s=this[we];s.isPaused||s._socket.resume()}l(q0,"receiverOnDrain");function V0(s){let e=this[we];e._socket[we]!==void 0&&(e._socket.removeListener("data",Rr),process.nextTick(op,e._socket),e.close(s[M0])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s))}l(V0,"receiverOnError");function Xd(){this[we].emitClose()}l(Xd,"receiverOnFinish");function z0(s,e){this[we].emit("message",s,e)}l(z0,"receiverOnMessage");function J0(s){let e=this[we];e._autoPong&&e.pong(s,!this._isServer,Zd),e.emit("ping",s)}l(J0,"receiverOnPing");function K0(s){this[we].emit("pong",s)}l(K0,"receiverOnPong");function op(s){s.resume()}l(op,"resume");function Y0(s){let e=this[we];e.readyState!==ie.CLOSED&&(e.readyState===ie.OPEN&&(e._readyState=ie.CLOSING,sp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",s)))}l(Y0,"senderOnError");function sp(s){s._closeTimer=setTimeout(s._socket.destroy.bind(s._socket),s._closeTimeout)}l(sp,"setCloseTimer");function np(){let s=this[we];if(this.removeListener("close",np),this.removeListener("data",Rr),this.removeListener("end",rp),s._readyState=ie.CLOSING,!this._readableState.endEmitted&&!s._closeFrameReceived&&!s._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);s._receiver.write(e)}s._receiver.end(),this[we]=void 0,clearTimeout(s._closeTimer),s._receiver._writableState.finished||s._receiver._writableState.errorEmitted?s.emitClose():(s._receiver.on("error",Xd),s._receiver.on("finish",Xd))}l(np,"socketOnClose");function Rr(s){this[we]._receiver.write(s)||this.pause()}l(Rr,"socketOnData");function rp(){let s=this[we];s._readyState=ie.CLOSING,s._receiver.end(),this.end()}l(rp,"socketOnEnd");function ip(){let s=this[we];this.removeListener("error",ip),this.on("error",Zd),s&&(s._readyState=ie.CLOSING,this.destroy())}l(ip,"socketOnError")});var dp=ce((OC,up)=>{"use strict";var PC=Ar(),{Duplex:X0}=require("stream");function cp(s){s.emit("close")}l(cp,"emitClose");function Q0(){!this.destroyed&&this._writableState.finished&&this.destroy()}l(Q0,"duplexOnEnd");function lp(s){this.removeListener("error",lp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",s)}l(lp,"duplexOnError");function Z0(s,e){let t=!0,o=new X0({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return s.on("message",l(function(r,i){let c=!i&&o._readableState.objectMode?r.toString():r;o.push(c)||s.pause()},"message")),s.once("error",l(function(r){o.destroyed||(t=!1,o.destroy(r))},"error")),s.once("close",l(function(){o.destroyed||o.push(null)},"close")),o._destroy=function(n,r){if(s.readyState===s.CLOSED){r(n),process.nextTick(cp,o);return}let i=!1;s.once("error",l(function(u){i=!0,r(u)},"error")),s.once("close",l(function(){i||r(n),process.nextTick(cp,o)},"close")),t&&s.terminate()},o._final=function(n){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._final(n)},"open"));return}s._socket!==null&&(s._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(s._socket.once("finish",l(function(){n()},"finish")),s.close()))},o._read=function(){s.isPaused&&s.resume()},o._write=function(n,r,i){if(s.readyState===s.CONNECTING){s.once("open",l(function(){o._write(n,r,i)},"open"));return}s.send(n,i)},o.on("end",Q0),o.on("error",lp),o}l(Z0,"createWebSocketStream");up.exports=Z0});var nc=ce((IC,pp)=>{"use strict";var{tokenChars:eb}=is();function tb(s){let e=new Set,t=-1,o=-1,n=0;for(n;n<s.length;n++){let i=s.charCodeAt(n);if(o===-1&&eb[i]===1)t===-1&&(t=n);else if(n!==0&&(i===32||i===9))o===-1&&t!==-1&&(o=n);else if(i===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let c=s.slice(t,o);if(e.has(c))throw new SyntaxError(`The "${c}" subprotocol is duplicated`);e.add(c),t=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(t===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let r=s.slice(t,n);if(e.has(r))throw new SyntaxError(`The "${r}" subprotocol is duplicated`);return e.add(r),e}l(tb,"parse");pp.exports={parse:tb}});var wp=ce((LC,bp)=>{"use strict";var ob=require("events"),Pr=require("http"),{Duplex:NC}=require("stream"),{createHash:sb}=require("crypto"),mp=Er(),Ao=rs(),nb=nc(),rb=Ar(),{CLOSE_TIMEOUT:ib,GUID:ab,kWebSocket:cb}=Nt(),lb=/^[+/0-9A-Za-z]{22}==$/,fp=0,gp=1,yp=2,rc=class extends ob{static{l(this,"WebSocketServer")}constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:ib,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:rb,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Pr.createServer((o,n)=>{let r=Pr.STATUS_CODES[426];n.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),n.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=ub(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:l((n,r,i)=>{this.handleUpgrade(n,r,i,o)},"upgrade")})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=fp}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===yp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Qs,this);return}if(e&&this.once("close",e),this._state!==gp)if(this._state=gp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Qs,this):process.nextTick(Qs,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Qs(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,o,n){t.on("error",hp);let r=e.headers["sec-websocket-key"],i=e.headers.upgrade,c=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Po(this,e,t,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){Po(this,e,t,400,"Invalid Upgrade header");return}if(r===void 0||!lb.test(r)){Po(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(c!==13&&c!==8){Po(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Zs(t,400);return}let u=e.headers["sec-websocket-protocol"],d=new Set;if(u!==void 0)try{d=nb.parse(u)}catch{Po(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let p=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&p!==void 0){let m=new Ao({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=mp.parse(p);g[Ao.extensionName]&&(m.accept(g[Ao.extensionName]),f[Ao.extensionName]=m)}catch{Po(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${c===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(g,h,b,k)=>{if(!g)return Zs(t,h||401,b,k);this.completeUpgrade(f,r,d,e,t,o,n)});return}if(!this.options.verifyClient(m))return Zs(t,401)}this.completeUpgrade(f,r,d,e,t,o,n)}completeUpgrade(e,t,o,n,r,i,c){if(!r.readable||!r.writable)return r.destroy();if(r[cb])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fp)return Zs(r,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${sb("sha1").update(t+ab).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(o.size){let f=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;f&&(d.push(`Sec-WebSocket-Protocol: ${f}`),p._protocol=f)}if(e[Ao.extensionName]){let f=e[Ao.extensionName].params,m=mp.format({[Ao.extensionName]:[f]});d.push(`Sec-WebSocket-Extensions: ${m}`),p._extensions=e}this.emit("headers",d,n),r.write(d.concat(`\r
|
|
154
154
|
`).join(`\r
|
|
155
155
|
`)),r.removeListener("error",hp),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(Qs,this)})),c(p,n)}};bp.exports=rc;function ub(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(ub,"addListeners");function Qs(s){s._state=yp,s.emit("close")}l(Qs,"emitClose");function hp(){this.destroy()}l(hp,"socketOnError");function Zs(s,e,t,o){t=t||Pr.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} ${Pr.STATUS_CODES[e]}\r
|
|
156
156
|
`+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
|
|
157
157
|
`)+`\r
|
|
158
158
|
\r
|
|
159
|
-
`+t)}l(Zs,"abortHandshake");function
|
|
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 Up(s,e){let t=G.mkdtempSync(te.join(Np.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,
|
|
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 bc(s,e,t){try{console.log(a.dim(` \u{1F4E5} Fetching branch ${t}...`)),(0,
|
|
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(Bp,"captureWorkspaceSnapshot");l(Up,"createSnapshotArchive");l(kb,"submitBackgroundJob");l(Wp,"runLocalBackgroundJob");l(gc,"getLocalJobs");l(hc,"getLocalJobStatus");l(yc,"getLocalJobLogs");l(bc,"pullJobChanges");l(Hp,"shouldUseUnicode");Db={queued:"\u23F3",running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u{1F6AB}"},vb={queued:"[Q]",running:"[~]",completed:"[+]",failed:"[X]",cancelled:"[-]"};l(Gp,"getStatusIcon");l(wc,"printJobsTable");l(jr,"printJobStatus");l(Nr,"printLogEntry");l(jp,"parseJobInfo");l(fc,"formatDuration");l(qp,"capitalize")});var Vp={};Te(Vp,{resumeFromJob:()=>xb});async function xb(s){let e=
|
|
159
|
+
`+t)}l(Zs,"abortHandshake");function Po(s,e,t,o,n,r){if(s.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,Po),s.emit("wsClientError",i,t,e)}else Zs(t,o,n,r)}l(Po,"abortHandshakeOrEmitwsClientError")});var db,pb,mb,fb,gb,hb,kp,ic,rt,en=H(()=>{db=y(dp(),1),pb=y(Er(),1),mb=y(rs(),1),fb=y(Ka(),1),gb=y(Qa(),1),hb=y(nc(),1),kp=y(Ar(),1),ic=y(wp(),1),rt=kp.default});var kc={};Te(kc,{JobsApiClient:()=>Oe,captureWorkspaceSnapshot:()=>Bp,createSnapshotArchive:()=>Up,getLocalJobLogs:()=>yc,getLocalJobStatus:()=>hc,getLocalJobs:()=>gc,printJobStatus:()=>jr,printJobsTable:()=>wc,printLogEntry:()=>Nr,pullJobChanges:()=>bc,runLocalBackgroundJob:()=>Wp,submitBackgroundJob:()=>kb});function Bp(s){let e=l(p=>{try{return(0,Oo.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 Up(s,e){let t=G.mkdtempSync(te.join(Np.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,Oo.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=Lp.gzipSync(Buffer.from(r,"utf8"));G.writeFileSync(n,i)}return n}async function kb(s){let e=z(),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=Bp(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=Up(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 Wp({...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 Wp(s){let e=`local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,{getPlatformPaths:t}=await Promise.resolve().then(()=>(X(),vo)),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",Sb.url).pathname,c=(0,Oo.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 gc(s){try{let{getPlatformPaths:e}=(X(),Es(vo)),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 hc(s){try{let{getPlatformPaths:e}=(X(),Es(vo)),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 yc(s){try{let{getPlatformPaths:e}=(X(),Es(vo)),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 bc(s,e,t){try{console.log(a.dim(` \u{1F4E5} Fetching branch ${t}...`)),(0,Oo.execSync)(`git fetch origin "${t}"`,{cwd:s,stdio:"pipe"}),console.log(a.dim(` \u{1F500} Merging ${t} into current branch...`)),(0,Oo.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 Hp(){return process.platform!=="win32"||!!process.env.WT_SESSION}function Gp(s){return(Hp()?Db:vb)[s]||"?"}function wc(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=`${Gp(n.status)} ${qp(n.status)}`,c=n.prompt.length>34?`"${n.prompt.substring(0,32)}..."`:`"${n.prompt}"`,u=n.duration?fc(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 jr(s,e){let t=Hp();if(console.log(""),console.log(a.bold(` ${t?"\u{1F4CB}":">>"} Job: ${s.id}`)),console.log(a.dim(" "+(t?"\u2500":"-").repeat(50))),console.log(` Status: ${Gp(s.status)} ${qp(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: ${fc(s.duration)}`),s.estimatedTimeRemaining!=null&&console.log(` ETA: ~${fc(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 Nr(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 jp(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 fc(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 qp(s){return s.charAt(0).toUpperCase()+s.slice(1)}var G,te,Np,Lp,Oo,Sb,Oe,Db,vb,sn=H(()=>{"use strict";G=y(require("node:fs"),1),te=y(require("node:path"),1),Np=y(require("node:os"),1),Lp=y(require("node:zlib"),1),Oo=require("node:child_process");U();Q();oe();Sb={},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(jp):[]}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 jp(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(Bp,"captureWorkspaceSnapshot");l(Up,"createSnapshotArchive");l(kb,"submitBackgroundJob");l(Wp,"runLocalBackgroundJob");l(gc,"getLocalJobs");l(hc,"getLocalJobStatus");l(yc,"getLocalJobLogs");l(bc,"pullJobChanges");l(Hp,"shouldUseUnicode");Db={queued:"\u23F3",running:"\u{1F504}",completed:"\u2705",failed:"\u274C",cancelled:"\u{1F6AB}"},vb={queued:"[Q]",running:"[~]",completed:"[+]",failed:"[X]",cancelled:"[-]"};l(Gp,"getStatusIcon");l(wc,"printJobsTable");l(jr,"printJobStatus");l(Nr,"printLogEntry");l(jp,"parseJobInfo");l(fc,"formatDuration");l(qp,"capitalize")});var Vp={};Te(Vp,{resumeFromJob:()=>xb});async function xb(s){let e=z(),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=Cb(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,ms.execSync)("git apply --check -",{cwd:s.workspace,input:d,stdio:["pipe","pipe","pipe"]}),(0,ms.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=nn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");return m(f,{recursive:!0}),g(nn.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=nn.join(s.workspace,".monkeyscode"),{mkdirSync:m,writeFileSync:g}=await import("node:fs");m(f,{recursive:!0}),g(nn.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 Cb(s,e){let t=[];try{let o=(0,ms.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,ms.execSync)("git diff --name-only",{cwd:s,encoding:"utf8"}).trim();if(r){let c=r.split(`
|
|
163
163
|
`).filter(Boolean);t.push(`${c.length} locally modified file(s): ${c.slice(0,3).join(", ")}${c.length>3?"...":""}`)}let i=(0,ms.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 nn,ms,
|
|
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 nn,ms,zp=H(()=>{"use strict";nn=y(require("node:path"),1),ms=require("node:child_process");U();sn();Q();oe();l(xb,"resumeFromJob");l(Cb,"checkSyncCompatibility")});function vc(s){let e=yt.join(s.workspace,rn,s.teamId,s.taskSlug),t=`monkeyscode/team-${s.teamId}/${s.taskSlug}`;at.mkdirSync(yt.dirname(e),{recursive:!0});let o=s.baseBranch||(0,Ht.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:s.workspace,encoding:"utf8"}).trim();try{(0,Ht.execSync)(`git worktree add -b "${t}" "${e}" "${o}"`,{cwd:s.workspace,encoding:"utf8",stdio:"pipe"})}catch{try{(0,Ht.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,Ht.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 Sc(s,e,t=!1){let o=t?" --force":"",n=l(()=>{(0,Ht.execSync)(`git worktree remove "${e}"${o}`,{cwd:s,encoding:"utf8",stdio:"pipe"})},"tryRemove");if(process.platform==="win32")for(let r=0;r<Dc;r++)try{n();return}catch(i){if(r<Dc-1)(0,Ht.execSync)(`timeout /t ${Math.ceil(_b/1e3)}`,{stdio:"ignore"});else throw new Error(`Failed to remove worktree after ${Dc} attempts (files may be locked by another process): ${i instanceof Error?i.message:i}`)}else n();try{(0,Ht.execSync)("git worktree prune",{cwd:s,stdio:"pipe"})}catch{}}function Eb(s){let e;try{e=(0,Ht.execSync)("git worktree list --porcelain",{cwd:s,encoding:"utf8"})}catch{return[]}let t=[],o=e.split(`
|
|
165
165
|
|
|
166
166
|
`).filter(Boolean);for(let n of o){let r=n.split(`
|
|
167
|
-
`),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=at.statSync(i).birthtime}catch{}let f=i.split(yt.sep),m=f.indexOf(rn.replace(/\//g,yt.sep).split(yt.sep)[0]),g=m>=0?f.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(rn),createdAt:p,label:g})}return t}function fs(s){return Eb(s).filter(e=>e.path.includes(rn))}function zp(s){let e=s.ttlMs??$b,t=Date.now(),o=[],n=[],r=fs(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Sc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=yt.join(s.workspace,rn);try{Kp(i)}catch{}return{removed:o,errors:n}}function Kp(s){if(!at.existsSync(s))return;let e=at.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&Kp(yt.join(s,t.name));at.readdirSync(s).length===0&&at.rmdirSync(s)}function xc(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var at,yt,Wt,rn,$b,_b,Dc,Cc=H(()=>{"use strict";at=y(require("node:fs"),1),yt=y(require("node:path"),1),Wt=require("node:child_process"),rn=".monkeyscode-worktrees",$b=24*60*60*1e3,_b=500,Dc=3;l(vc,"createWorktree");l(Sc,"removeWorktree");l(Eb,"listWorktrees");l(fs,"listManagedWorktrees");l(zp,"cleanStaleWorktrees");l(Kp,"cleanEmptyDirs");l(xc,"slugify")});var Xp={};Te(Xp,{mergeTeam:()=>_c,runInWorktree:()=>Tb,showTeamStatus:()=>$c,spawnTeam:()=>Lr});async function Lr(s){let e=Rb(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:xc(m),status:"queued"}));console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Spawning Agent Team: ${e}`)),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(` Tasks: ${t.length}`),console.log(` Max agents: ${s.maxAgents}`),console.log(` Model: ${s.model}`),console.log(a.dim(" "+"\u2500".repeat(50))),console.log("");for(let m of t)try{console.log(a.dim(` \u{1F4C1} Creating worktree for agent #${m.index}: "${m.task.substring(0,40)}..."`)),m.worktree=vc({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(g){m.status="failed",m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=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 (${Yp(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-g,m.error=h instanceof Error?h.message:String(h),console.error(a.red(` \u274C Agent #${m.index} failed: ${m.error.substring(0,80)}`))}},"runAgent");await l(async()=>{let m=[];for(let g of i){for(;c.size>=s.maxAgents;)await new Promise(b=>setTimeout(b,500));c.add(g.index);let h=u(g).finally(()=>c.delete(g.index));m.push(h)}await Promise.all(m)},"processQueue")();try{let m=an.join(s.workspace,".monkeyscode-worktrees",e);ct.mkdirSync(m,{recursive:!0});let g=an.join(m,"state.json");ct.writeFileSync(g,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(h=>({index:h.index,task:h.task,slug:h.slug,status:h.status,duration:h.duration,filesChanged:h.filesChanged,error:h.error,branch:h.worktree?.branch}))},null,2))}catch{}let p=t.filter(m=>m.status==="completed").length,f=t.filter(m=>m.status==="failed").length;return console.log(""),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(a.bold(` Team ${e}: ${p} completed, ${f} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function $c(s){let e=an.join(s,".monkeyscode-worktrees");if(!ct.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=ct.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=an.join(e,u.name,"state.json");if(ct.existsSync(d))try{t.push(JSON.parse(ct.readFileSync(d,"utf8")))}catch{}}}catch{}let o=fs(s),n=new Set(t.map(c=>c.teamId)),r=new Map;for(let c of o){let d=(c.label?.split("/")||[])[0]||"unknown";n.has(d)||(r.has(d)||r.set(d,[]),r.get(d).push(c))}if(t.length===0&&r.size===0){console.log(a.dim(" No active agent teams found."));return}let i=l(c=>{switch(c){case"completed":return"\u2705";case"running":return"\u{1F504}";case"queued":return"\u23F3";case"failed":return"\u274C";default:return"?"}},"statusIcon");for(let c of t){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c.teamId}`));let u=" "+"\u2500".repeat(76);console.log(u),console.log(a.bold(` ${"Agent".padEnd(8)} ${"Task".padEnd(34)} ${"Status".padEnd(12)} ${"Duration".padEnd(10)} ${"Files".padEnd(6)}`)),console.log(u);for(let d of c.agents){let p=i(d.status),f=d.duration?Yp(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",g=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+g+'"').padEnd(34)} ${(p+" "+Fb(d.status)).padEnd(12)} ${f.padEnd(10)} ${m.padEnd(6)}`)}console.log(u)}for(let[c,u]of r){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c}`)+a.dim(" (no state file)"));let d=" "+"\u2500".repeat(70);console.log(d);for(let p=0;p<u.length;p++){let f=u[p],m=f.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${f.branch.padEnd(30)}`)}console.log(d)}console.log("")}function Fb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function _c(s,e){let t=fs(s).filter(r=>r.label?.startsWith(e));if(t.length===0){console.error(a.red(` \u274C No worktrees found for team ${e}.`));return}console.log(""),console.log(a.bold(` \u{1F500} Merging team ${e} (${t.length} branches)`));let o=0,n=0;for(let r of t){let i=r.label?.split("/").slice(1).join("/")||"?";console.log(a.dim(` Merging: ${r.branch} (${i})`));try{(0,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{Sc(s,r.path,!0)}catch{}}console.log(""),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.bold(` Merged: ${o}, Conflicts: ${n}`)),console.log("")}async function Tb(s,e,t){let o=xc(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=vc({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,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 Rb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function Yp(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var ct,an,lo,Ec=H(()=>{"use strict";ct=y(require("node:fs"),1),an=y(require("node:path"),1),lo=require("node:child_process");U();Cc();Q();oe();l(Lr,"spawnTeam");l($c,"showTeamStatus");l(Fb,"capitalize");l(_c,"mergeTeam");l(Tb,"runInWorktree");l(Rb,"generateTeamId");l(Yp,"formatDuration")});var Br={};Te(Br,{MessageBroker:()=>cn});function Ab(){try{let s=Zp.join(em.homedir(),".monkeyscode","daemon.port"),e=Qp.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var Qp,Zp,em,Fc,Tc,cn,ln=H(()=>{"use strict";Qp=y(require("node:fs"),1),Zp=y(require("node:path"),1),em=y(require("node:os"),1);en();Fc=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new rt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},Tc=class{constructor(e,t){this.platformUrl=e;this.token=t}static{l(this,"CloudTransport")}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async sendMessage(e,t,o){try{let n=await fetch(`${this.platformUrl}/api/messages`,{method:"POST",headers:this.headers(),body:JSON.stringify({from:e,to:t,content:o,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(!n.ok){let i=await n.text().catch(()=>"");return{success:!1,error:`HTTP ${n.status}: ${i}`}}return{success:!0,messageId:(await n.json()).messageId}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{let e=await fetch(`${this.platformUrl}/api/sessions`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).sessions||[]).map(o=>({id:o.id,task:o.task||o.prompt?.substring(0,80)||"(no task)",status:o.status||"running",type:o.type||"interactive",workspace:o.workspace||"",startedAt:new Date(o.startedAt||o.createdAt),model:o.model||"unknown"})):[]}catch{return[]}}async pollMessages(e){try{let t=await fetch(`${this.platformUrl}/api/messages/pending?session=${e}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)});if(!t.ok)return[];let n=((await t.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:!1}));for(let r of n)try{await fetch(`${this.platformUrl}/api/messages/${r.id}/ack`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)})}catch{}return n}catch{return[]}}async getMessageHistory(e,t){try{let o=await fetch(`${this.platformUrl}/api/messages?session=${e}&limit=${t}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return o.ok?((await o.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:r.delivered??!0})):[]}catch{return[]}}async register(){}async unregister(){}};l(Ab,"readDaemonPort");cn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=Ab();n?this.transport=new Fc(n):this.transport=new Tc(e,t)}async init(e,t,o){await this.transport.register(this.sessionId,e,t,o)}async dispose(){await this.transport.unregister(this.sessionId)}async sendMessage(e,t){return this.transport.sendMessage(this.sessionId,e,t)}async broadcast(e){return this.sendMessage("broadcast",e)}async listAgents(){return this.transport.listAgents()}async getMessageHistory(e=50){return this.transport.getMessageHistory(this.sessionId,e)}async checkPendingMessages(){return this.transport.pollMessages(this.sessionId)}onMessage(e){this.onMessageCallback=e}async pollMessages(){let e=await this.checkPendingMessages();if(this.onMessageCallback)for(let t of e)this.onMessageCallback(t);return e}static getToolSchemas(){return[{name:"SendMessage",description:"Send a message to another active agent session. Use when you make changes that affect shared code and other agents need to know.",parameters:{type:"object",properties:{target:{type:"string",description:'Target session ID (from ListAgents) or "broadcast" to notify all.'},message:{type:"string",description:"Message content describing what changed and what other agents should do."}},required:["target","message"]}},{name:"ListAgents",description:"List all active agent sessions on the current machine. Returns session IDs, tasks, and status.",parameters:{type:"object",properties:{}}}]}}});var om={};Te(om,{analyzeImpact:()=>tm,notifyAffectedSessions:()=>Ob});function tm(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=bt.basename(d).toLowerCase(),f=d.toLowerCase();if(i.includes(p)&&.9>u&&(u=.9,c=`Task mentions "${p}" which was modified`),r.workspace){let m=bt.relative(r.workspace,d),g=bt.dirname(m).split(bt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Pb)if(m.pathPattern.test(f))for(let g of m.keywords)i.includes(g)&&.6>u&&(u=.6,c=`Modified ${p} (${g}-related) \u2014 task mentions "${g}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function Ob(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=tm(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>bt.basename(p)).join(", "):`${e.slice(0,3).map(p=>bt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
168
|
-
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var bt,Pb,sm=H(()=>{"use strict";bt=y(require("node:path"),1),Pb=[{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(tm,"analyzeImpact");l(Ob,"notifyAffectedSessions")});var Em={};Te(Em,{default:()=>Qb});var Qb,Fm=H(()=>{Qb={name:"monkeyscode-cli",version:"0.1.
|
|
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=kn.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 af={};Te(af,{GitHubWebhookServer:()=>
|
|
170
|
-
`),!0}function $k(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(
|
|
167
|
+
`),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=at.statSync(i).birthtime}catch{}let f=i.split(yt.sep),m=f.indexOf(rn.replace(/\//g,yt.sep).split(yt.sep)[0]),g=m>=0?f.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(rn),createdAt:p,label:g})}return t}function fs(s){return Eb(s).filter(e=>e.path.includes(rn))}function Jp(s){let e=s.ttlMs??$b,t=Date.now(),o=[],n=[],r=fs(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Sc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=yt.join(s.workspace,rn);try{Kp(i)}catch{}return{removed:o,errors:n}}function Kp(s){if(!at.existsSync(s))return;let e=at.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&Kp(yt.join(s,t.name));at.readdirSync(s).length===0&&at.rmdirSync(s)}function xc(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var at,yt,Ht,rn,$b,_b,Dc,Cc=H(()=>{"use strict";at=y(require("node:fs"),1),yt=y(require("node:path"),1),Ht=require("node:child_process"),rn=".monkeyscode-worktrees",$b=24*60*60*1e3,_b=500,Dc=3;l(vc,"createWorktree");l(Sc,"removeWorktree");l(Eb,"listWorktrees");l(fs,"listManagedWorktrees");l(Jp,"cleanStaleWorktrees");l(Kp,"cleanEmptyDirs");l(xc,"slugify")});var Xp={};Te(Xp,{mergeTeam:()=>_c,runInWorktree:()=>Tb,showTeamStatus:()=>$c,spawnTeam:()=>Lr});async function Lr(s){let e=Rb(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:xc(m),status:"queued"}));console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Spawning Agent Team: ${e}`)),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(` Tasks: ${t.length}`),console.log(` Max agents: ${s.maxAgents}`),console.log(` Model: ${s.model}`),console.log(a.dim(" "+"\u2500".repeat(50))),console.log("");for(let m of t)try{console.log(a.dim(` \u{1F4C1} Creating worktree for agent #${m.index}: "${m.task.substring(0,40)}..."`)),m.worktree=vc({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(g){m.status="failed",m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=z(),r=me()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let g=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let h=(0,uo.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let b=JSON.parse(h);m.filesChanged=b.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-g;try{(0,uo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,uo.execSync)(`git commit -m "feat: ${m.task.substring(0,72)}" --allow-empty`,{cwd:m.worktree.path,stdio:"pipe"})}catch{}console.log(a.green(` \u2705 Agent #${m.index} completed (${Yp(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-g,m.error=h instanceof Error?h.message:String(h),console.error(a.red(` \u274C Agent #${m.index} failed: ${m.error.substring(0,80)}`))}},"runAgent");await l(async()=>{let m=[];for(let g of i){for(;c.size>=s.maxAgents;)await new Promise(b=>setTimeout(b,500));c.add(g.index);let h=u(g).finally(()=>c.delete(g.index));m.push(h)}await Promise.all(m)},"processQueue")();try{let m=an.join(s.workspace,".monkeyscode-worktrees",e);ct.mkdirSync(m,{recursive:!0});let g=an.join(m,"state.json");ct.writeFileSync(g,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(h=>({index:h.index,task:h.task,slug:h.slug,status:h.status,duration:h.duration,filesChanged:h.filesChanged,error:h.error,branch:h.worktree?.branch}))},null,2))}catch{}let p=t.filter(m=>m.status==="completed").length,f=t.filter(m=>m.status==="failed").length;return console.log(""),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(a.bold(` Team ${e}: ${p} completed, ${f} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function $c(s){let e=an.join(s,".monkeyscode-worktrees");if(!ct.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=ct.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=an.join(e,u.name,"state.json");if(ct.existsSync(d))try{t.push(JSON.parse(ct.readFileSync(d,"utf8")))}catch{}}}catch{}let o=fs(s),n=new Set(t.map(c=>c.teamId)),r=new Map;for(let c of o){let d=(c.label?.split("/")||[])[0]||"unknown";n.has(d)||(r.has(d)||r.set(d,[]),r.get(d).push(c))}if(t.length===0&&r.size===0){console.log(a.dim(" No active agent teams found."));return}let i=l(c=>{switch(c){case"completed":return"\u2705";case"running":return"\u{1F504}";case"queued":return"\u23F3";case"failed":return"\u274C";default:return"?"}},"statusIcon");for(let c of t){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c.teamId}`));let u=" "+"\u2500".repeat(76);console.log(u),console.log(a.bold(` ${"Agent".padEnd(8)} ${"Task".padEnd(34)} ${"Status".padEnd(12)} ${"Duration".padEnd(10)} ${"Files".padEnd(6)}`)),console.log(u);for(let d of c.agents){let p=i(d.status),f=d.duration?Yp(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",g=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+g+'"').padEnd(34)} ${(p+" "+Fb(d.status)).padEnd(12)} ${f.padEnd(10)} ${m.padEnd(6)}`)}console.log(u)}for(let[c,u]of r){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c}`)+a.dim(" (no state file)"));let d=" "+"\u2500".repeat(70);console.log(d);for(let p=0;p<u.length;p++){let f=u[p],m=f.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${f.branch.padEnd(30)}`)}console.log(d)}console.log("")}function Fb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function _c(s,e){let t=fs(s).filter(r=>r.label?.startsWith(e));if(t.length===0){console.error(a.red(` \u274C No worktrees found for team ${e}.`));return}console.log(""),console.log(a.bold(` \u{1F500} Merging team ${e} (${t.length} branches)`));let o=0,n=0;for(let r of t){let i=r.label?.split("/").slice(1).join("/")||"?";console.log(a.dim(` Merging: ${r.branch} (${i})`));try{(0,uo.execSync)(`git merge --no-ff "${r.branch}" -m "merge: team ${e} \u2014 ${i}"`,{cwd:s,stdio:"inherit"}),o++,console.log(a.green(` \u2705 Merged ${r.branch}`))}catch{n++,console.error(a.yellow(` \u26A0 Merge conflict on ${r.branch}. Resolve and continue.`)),console.log(a.dim(" After resolving: git merge --continue")),console.log(a.dim(" Then re-run: mc team merge "+e));return}}if(n===0){console.log(a.dim(" \u{1F9F9} Cleaning up worktrees..."));for(let r of t)try{Sc(s,r.path,!0)}catch{}}console.log(""),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.bold(` Merged: ${o}, Conflicts: ${n}`)),console.log("")}async function Tb(s,e,t){let o=xc(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=vc({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,uo.execSync)(`node "${process.argv[1]}" -p "${s.replace(/"/g,'\\"')}" --headless --auto-approve --model "${t}" --workspace "${r.path}" -o json`,{cwd:r.path,encoding:"utf8",timeout:6e5,env:{...process.env},stdio:"inherit"});try{(0,uo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,uo.execSync)(`git commit -m "feat: ${s.substring(0,72)}"`,{cwd:r.path,stdio:"pipe"})}catch{}console.log(a.green(" \u2705 Worktree task completed.")),console.log(a.dim(` Merge: git merge --no-ff ${r.branch}`))}catch(i){console.error(a.red(` \u274C Worktree task failed: ${i instanceof Error?i.message:i}`))}}function Rb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function Yp(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var ct,an,uo,Ec=H(()=>{"use strict";ct=y(require("node:fs"),1),an=y(require("node:path"),1),uo=require("node:child_process");U();Cc();Q();oe();l(Lr,"spawnTeam");l($c,"showTeamStatus");l(Fb,"capitalize");l(_c,"mergeTeam");l(Tb,"runInWorktree");l(Rb,"generateTeamId");l(Yp,"formatDuration")});var Br={};Te(Br,{MessageBroker:()=>cn});function Ab(){try{let s=Zp.join(em.homedir(),".monkeyscode","daemon.port"),e=Qp.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var Qp,Zp,em,Fc,Tc,cn,ln=H(()=>{"use strict";Qp=y(require("node:fs"),1),Zp=y(require("node:path"),1),em=y(require("node:os"),1);en();Fc=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new rt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},Tc=class{constructor(e,t){this.platformUrl=e;this.token=t}static{l(this,"CloudTransport")}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async sendMessage(e,t,o){try{let n=await fetch(`${this.platformUrl}/api/messages`,{method:"POST",headers:this.headers(),body:JSON.stringify({from:e,to:t,content:o,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(!n.ok){let i=await n.text().catch(()=>"");return{success:!1,error:`HTTP ${n.status}: ${i}`}}return{success:!0,messageId:(await n.json()).messageId}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{let e=await fetch(`${this.platformUrl}/api/sessions`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).sessions||[]).map(o=>({id:o.id,task:o.task||o.prompt?.substring(0,80)||"(no task)",status:o.status||"running",type:o.type||"interactive",workspace:o.workspace||"",startedAt:new Date(o.startedAt||o.createdAt),model:o.model||"unknown"})):[]}catch{return[]}}async pollMessages(e){try{let t=await fetch(`${this.platformUrl}/api/messages/pending?session=${e}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)});if(!t.ok)return[];let n=((await t.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:!1}));for(let r of n)try{await fetch(`${this.platformUrl}/api/messages/${r.id}/ack`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)})}catch{}return n}catch{return[]}}async getMessageHistory(e,t){try{let o=await fetch(`${this.platformUrl}/api/messages?session=${e}&limit=${t}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return o.ok?((await o.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:r.delivered??!0})):[]}catch{return[]}}async register(){}async unregister(){}};l(Ab,"readDaemonPort");cn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=Ab();n?this.transport=new Fc(n):this.transport=new Tc(e,t)}async init(e,t,o){await this.transport.register(this.sessionId,e,t,o)}async dispose(){await this.transport.unregister(this.sessionId)}async sendMessage(e,t){return this.transport.sendMessage(this.sessionId,e,t)}async broadcast(e){return this.sendMessage("broadcast",e)}async listAgents(){return this.transport.listAgents()}async getMessageHistory(e=50){return this.transport.getMessageHistory(this.sessionId,e)}async checkPendingMessages(){return this.transport.pollMessages(this.sessionId)}onMessage(e){this.onMessageCallback=e}async pollMessages(){let e=await this.checkPendingMessages();if(this.onMessageCallback)for(let t of e)this.onMessageCallback(t);return e}static getToolSchemas(){return[{name:"SendMessage",description:"Send a message to another active agent session. Use when you make changes that affect shared code and other agents need to know.",parameters:{type:"object",properties:{target:{type:"string",description:'Target session ID (from ListAgents) or "broadcast" to notify all.'},message:{type:"string",description:"Message content describing what changed and what other agents should do."}},required:["target","message"]}},{name:"ListAgents",description:"List all active agent sessions on the current machine. Returns session IDs, tasks, and status.",parameters:{type:"object",properties:{}}}]}}});var om={};Te(om,{analyzeImpact:()=>tm,notifyAffectedSessions:()=>Ob});function tm(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=bt.basename(d).toLowerCase(),f=d.toLowerCase();if(i.includes(p)&&.9>u&&(u=.9,c=`Task mentions "${p}" which was modified`),r.workspace){let m=bt.relative(r.workspace,d),g=bt.dirname(m).split(bt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Pb)if(m.pathPattern.test(f))for(let g of m.keywords)i.includes(g)&&.6>u&&(u=.6,c=`Modified ${p} (${g}-related) \u2014 task mentions "${g}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function Ob(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=tm(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>bt.basename(p)).join(", "):`${e.slice(0,3).map(p=>bt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
168
|
+
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var bt,Pb,sm=H(()=>{"use strict";bt=y(require("node:path"),1),Pb=[{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(tm,"analyzeImpact");l(Ob,"notifyAffectedSessions")});var Em={};Te(Em,{default:()=>Qb});var Qb,Fm=H(()=>{Qb={name:"monkeyscode-cli",version:"0.1.3",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 Xr,ef=H(()=>{"use strict";Xr=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 wn,Vc,Qr,tf=H(()=>{"use strict";wn=y(require("node:fs"),1),Vc=y(require("node:path"),1),Qr=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=wn.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=wn.readdirSync(e,{withFileTypes:!0});for(let n of o){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let r=Vc.join(e,n.name);try{let i=wn.watch(r,(c,u)=>{!u||!this.running||this.onFileChange(Vc.join(n.name,u))});this.watchers.push(i),this.watchDirectories(r,t+1)}catch{}}}catch{}}}});var sf={};Te(sf,{TriggerEngine:()=>zc});var Dt,kn,of,zc,nf=H(()=>{"use strict";Dt=y(require("node:fs"),1),kn=y(require("node:path"),1),of=require("node:events");ze();Q();ef();tf();zc=class extends of.EventEmitter{static{l(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=kn.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new Xr,this.fileWatcher=new Qr(e.workspace),this.loadState()}loadTriggers(){let e=kn.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=z(),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=kn.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 af={};Te(af,{GitHubWebhookServer:()=>Jc});var rf,ws,Jc,cf=H(()=>{"use strict";rf=y(require("node:http"),1),ws=y(require("node:crypto"),1),Jc=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=rf.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"]||ws.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="+ws.createHmac("sha256",o).update(e).digest("hex");return ws.timingSafeEqual(Buffer.from(t),Buffer.from(n))}}});var hg={};Te(hg,{getNotificationBackend:()=>Sk,notifyJobComplete:()=>kk,notifyUpdateAvailable:()=>Dk,sendNotification:()=>al,supportsNotifications:()=>vk});function al(s){if(process.env.CI==="true"||process.env.CI==="1")return!1;try{switch(process.platform){case"darwin":return xk(s);case"linux":return Ck(s);case"win32":return Fk(s);default:return!1}}catch{return!1}}function kk(s,e,t){return al({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 al({title:"\u{1F504} Update Available",body:`MonkeysCode v${s} is available. Run: mc update`,subtitle:"MonkeysCode",urgency:"low"})}function vk(){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 Sk(){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 xk(s){let e=ii(s.title),o=`display notification "${ii(s.body)}" with title "${e}"`;s.subtitle&&(o+=` subtitle "${ii(s.subtitle)}"`),s.sound&&(o+=` sound name "${ii(s.sound)}"`);let n=rl.join(il.tmpdir(),`mc-notify-${process.pid}.scpt`);try{return bo.writeFileSync(n,o,"utf8"),(0,Kt.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{bo.unlinkSync(n)}catch{}}}function ii(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Ck(s){if(!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)){if(xt("notify-send"))return $k(s);if(xt("kdialog"))return _k(s);if(xt("zenity"))return Ek(s)}return process.stderr.write("\x07"),process.stderr.write(`[Notification] ${s.title}: ${s.body}
|
|
170
|
+
`),!0}function $k(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(bo.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,Kt.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function _k(s){try{return(0,Kt.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Ek(s){try{return(0,Kt.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Fk(s){let e=gg(s.title),t=gg(s.body),o=`
|
|
171
171
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
172
172
|
|
|
173
173
|
# Try WinRT Toast (Windows 10 1709+)
|
|
@@ -231,39 +231,41 @@ try {
|
|
|
231
231
|
catch {}
|
|
232
232
|
|
|
233
233
|
exit 1
|
|
234
|
-
`,n=rl.join(il.tmpdir(),`mc-notify-${process.pid}.ps1`);try{let r=Buffer.from([239,187,191]),i=Buffer.concat([r,Buffer.from(o,"utf8")]);return
|
|
235
|
-
${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ch=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),lh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=ih.bind(null,o,e.toString());Object.defineProperty(n,"name",ch);let{writable:r,enumerable:i,configurable:c}=ah;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Oi(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))sh(s,e,n,t);return rh(s,e),lh(s,e,o),s}l(Oi,"mimicFunction");var Ln=new WeakMap,Nl=l((s,e={})=>{if(typeof s!="function")throw new TypeError("Expected a function");let t,o=0,n=s.displayName||s.name||"<anonymous>",r=l(function(...i){if(Ln.set(r,++o),o===1)t=s.apply(this,i),s=void 0;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return t},"onetime");return Oi(r,s),Ln.set(r,o),r},"onetime");Nl.callCount=s=>{if(!Ln.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Ln.get(s)};var Ll=Nl;var 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 Bn=l(s=>!!s&&typeof s=="object"&&typeof s.removeListener=="function"&&typeof s.emit=="function"&&typeof s.reallyExit=="function"&&typeof s.listeners=="function"&&typeof s.kill=="function"&&typeof s.pid=="number"&&typeof s.on=="function","processOk"),Mi=Symbol.for("signal-exit emitter"),Ii=globalThis,uh=Object.defineProperty.bind(Object),ji=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ii[Mi])return Ii[Mi];uh(Ii,Mi,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let o=this.listeners[e],n=o.indexOf(t);n!==-1&&(n===0&&o.length===1?o.length=0:o.splice(n,1))}emit(e,t,o){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,o)===!0||n;return e==="exit"&&(n=this.emit("afterExit",t,o)||n),n}},Un=class{static{l(this,"SignalExitBase")}},dh=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Ni=class extends Un{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Li=class extends Un{static{l(this,"SignalExit")}#i=Bi.platform==="win32"?"SIGINT":"SIGHUP";#o=new ji;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of 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(!Bn(this.#e))return()=>{};this.#r===!1&&this.load();let o=t?.alwaysLast?"afterExit":"exit";return this.#o.on(o,e),()=>{this.#o.removeListener(o,e),this.#o.listeners.exit.length===0&&this.#o.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#r){this.#r=!0,this.#o.count+=1;for(let e of 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 Bn(this.#e)?(this.#e.exitCode=e||0,this.#o.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...t){let o=this.#n;if(e==="exit"&&Bn(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);let n=o.call(this.#e,e,...t);return this.#o.emit("exit",this.#e.exitCode,null),n}else return o.call(this.#e,e,...t)}},Bi=globalThis.process,{onExit:Bl,load:vD,unload:SD}=dh(Bn(Bi)?new Li(Bi):new Ni);var Ul=As.default.stderr.isTTY?As.default.stderr:As.default.stdout.isTTY?As.default.stdout:void 0,ph=Ul?Ll(()=>{Bl(()=>{Ul.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Wl=ph;var Wn=!1,Jo={};Jo.show=(s=Ui.default.stderr)=>{s.isTTY&&(Wn=!1,s.write("\x1B[?25h"))};Jo.hide=(s=Ui.default.stderr)=>{s.isTTY&&(Wl(),Wn=!0,s.write("\x1B[?25l"))};Jo.toggle=(s,e)=>{s!==void 0&&(Wn=s),Wn?Jo.show(e):Jo.hide(e)};var Wi=Jo;var Is=y(Hi(),1);U();var qe=y(require("node:process"),1);function Gi(){return qe.default.platform!=="win32"?qe.default.env.TERM!=="linux":!!qe.default.env.CI||!!qe.default.env.WT_SESSION||!!qe.default.env.TERMINUS_SUBLIME||qe.default.env.ConEmuTask==="{cmd::Cmder}"||qe.default.env.TERM_PROGRAM==="Terminus-Sublime"||qe.default.env.TERM_PROGRAM==="vscode"||qe.default.env.TERM==="xterm-256color"||qe.default.env.TERM==="alacritty"||qe.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Gi,"isUnicodeSupported");var fh={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},gh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},hh=Gi()?fh:gh,Ps=hh;function qi({onlyFirst:s=!1}={}){let n="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(n,s?void 0:"g")}l(qi,"ansiRegex");var yh=qi();function Os(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(yh,"")}l(Os,"stripAnsi");var Vl=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Jl=12288,zl=65510,Kl=[12288,12288,65281,65376,65504,65510];var Yl=4352,Xl=262141,Vi=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Gn=l((s,e)=>{let t=0,o=Math.floor(s.length/2)-1;for(;t<=o;){let n=Math.floor((t+o)/2),r=n*2;if(e<s[r])o=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1},"isInRange");var Ql=19968,[kh,Dh]=vh(Vi);function vh(s){let e=s[0],t=s[1];for(let o=0;o<s.length;o+=2){let n=s[o],r=s[o+1];if(Ql>=n&&Ql<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(vh,"findWideFastPathRange");var Zl=l(s=>s<161||s>1114109?!1:Gn(Vl,s),"isAmbiguous"),eu=l(s=>s<Jl||s>zl?!1:Gn(Kl,s),"isFullWidth");var tu=l(s=>s>=kh&&s<=Dh?!0:s<Yl||s>Xl?!1:Gn(Vi,s),"isWide");function Sh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(Sh,"validate");function ou(s,{ambiguousAsWide:e=!1}={}){return Sh(s),eu(s)||tu(s)||e&&Zl(s)?2:1}l(ou,"eastAsianWidth");var ru=y(nu(),1);var xh=new Intl.Segmenter,Ch=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Ji(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=Os(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of xh.segment(s)){let c=i.codePointAt(0);if(!(c<=31||c>=127&&c<=159)&&!(c>=8203&&c<=8207||c===65279)&&!(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)&&!(c>=55296&&c<=57343)&&!(c>=65024&&c<=65039)&&!Ch.test(i)){if((0,ru.default)().test(i)){n+=2;continue}n+=ou(c,r)}}return n}l(Ji,"stringWidth");function zi({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(zi,"isInteractive");var Ki=y(require("node:process"),1);function Yi(){let{env:s}=Ki.default,{TERM:e,TERM_PROGRAM:t}=s;return Ki.default.platform!=="win32"?e!=="linux":!!s.WT_SESSION||!!s.TERMINUS_SUBLIME||s.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||s.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Yi,"isUnicodeSupported");var et=y(require("node:process"),1);var $h=3,Xi=class{static{l(this,"StdinDiscarder")}#i=0;start(){this.#i++,this.#i===1&&this.#o()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#o(){et.default.platform==="win32"||!et.default.stdin.isTTY||(et.default.stdin.setRawMode(!0),et.default.stdin.on("data",this.#n),et.default.stdin.resume())}#e(){et.default.stdin.isTTY&&(et.default.stdin.off("data",this.#n),et.default.stdin.pause(),et.default.stdin.setRawMode(!1))}#n(e){e[0]===$h&&et.default.emit("SIGINT")}},_h=new Xi,Qi=_h;var Eh=y(Hi(),1);var Zi=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#g;#l;#u;#d;#h;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Ms.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:zi({stream:this.#s}),this.#u=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Ms.default.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(t){this.#i=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#n}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#f()}get interval(){return this.#g??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#g=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!Yi())this.#r=Is.default.line;else if(e===void 0)this.#r=Is.default.dots;else if(e!=="default"&&Is.default[e])this.#r=Is.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#h}set text(e=""){this.#h=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#f()}get isSpinning(){return this.#m!==void 0}#y(e=this.#a,t=" "){return typeof e=="string"&&e!==""?e+t:typeof e=="function"?e()+t:""}#b(e=this.#c,t=" "){return typeof e=="string"&&e!==""?t+e:typeof e=="function"?t+e():""}#f(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),o=this.#b(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#h+"--"+o;this.#e=0;for(let r of Os(n).split(`
|
|
236
|
-
`))this.#e+=Math.max(1,Math.ceil(
|
|
234
|
+
`,n=rl.join(il.tmpdir(),`mc-notify-${process.pid}.ps1`);try{let r=Buffer.from([239,187,191]),i=Buffer.concat([r,Buffer.from(o,"utf8")]);return bo.writeFileSync(n,i),(0,Kt.execSync)(`powershell -NoProfile -ExecutionPolicy Bypass -File "${n}"`,{stdio:"pipe",timeout:15e3}),!0}catch{return!1}finally{try{bo.unlinkSync(n)}catch{}}}function gg(s){return s.replace(/'/g,"''")}function xt(s){try{return process.platform==="win32"?(0,Kt.execSync)(`where ${s} 2>NUL`,{stdio:"pipe"}):(0,Kt.execSync)(`command -v ${s} 2>/dev/null`,{stdio:"pipe"}),!0}catch{return!1}}var bo,rl,il,Kt,yg=H(()=>{"use strict";bo=y(require("node:fs"),1),rl=y(require("node:path"),1),il=y(require("node:os"),1),Kt=require("node:child_process");l(al,"sendNotification");l(kk,"notifyJobComplete");l(Dk,"notifyUpdateAvailable");l(vk,"supportsNotifications");l(Sk,"getNotificationBackend");l(xk,"notifyMac");l(ii,"escapeAS");l(Ck,"notifyLinux");l($k,"notifyLinuxLibnotify");l(_k,"notifyLinuxKdialog");l(Ek,"notifyLinuxZenity");l(Fk,"notifyWindows");l(gg,"escapePowerShell");l(xt,"commandExists")});var vl=y(Dl(),1),{program:qk,createCommand:Vk,createArgument:zk,createOption:Jk,CommanderError:Kk,InvalidArgumentError:Yk,InvalidOptionArgumentError:Xk,Command:Sl,Argument:Qk,Option:Et,Help:Zk}=vl.default;var N=y(require("node:path"),1),J=y(require("node:fs"),1);var rm=y(require("node:readline"),1),V=y(require("node:path"),1),M=y(require("node:fs"),1),Ye=require("node:child_process");U();U();var Ms=y(require("node:process"),1);U();var Ui=y(require("node:process"),1);var As=y(require("node:process"),1);var sh=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);!nh(n,r)&&o||Object.defineProperty(s,t,r)},"copyProperty"),nh=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"),rh=l((s,e)=>{let t=Object.getPrototypeOf(e);t!==Object.getPrototypeOf(s)&&Object.setPrototypeOf(s,t)},"changePrototype"),ih=l((s,e)=>`/* Wrapped ${s}*/
|
|
235
|
+
${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),ch=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),lh=l((s,e,t)=>{let o=t===""?"":`with ${t.trim()}() `,n=ih.bind(null,o,e.toString());Object.defineProperty(n,"name",ch);let{writable:r,enumerable:i,configurable:c}=ah;Object.defineProperty(s,"toString",{value:n,writable:r,enumerable:i,configurable:c})},"changeToString");function Oi(s,e,{ignoreNonConfigurable:t=!1}={}){let{name:o}=s;for(let n of Reflect.ownKeys(e))sh(s,e,n,t);return rh(s,e),lh(s,e,o),s}l(Oi,"mimicFunction");var Ln=new WeakMap,Nl=l((s,e={})=>{if(typeof s!="function")throw new TypeError("Expected a function");let t,o=0,n=s.displayName||s.name||"<anonymous>",r=l(function(...i){if(Ln.set(r,++o),o===1)t=s.apply(this,i),s=void 0;else if(e.throw===!0)throw new Error(`Function \`${n}\` can only be called once`);return t},"onetime");return Oi(r,s),Ln.set(r,o),r},"onetime");Nl.callCount=s=>{if(!Ln.has(s))throw new Error(`The given function \`${s.name}\` is not wrapped by the \`onetime\` package`);return Ln.get(s)};var Ll=Nl;var ko=[];ko.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&ko.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&ko.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Bn=l(s=>!!s&&typeof s=="object"&&typeof s.removeListener=="function"&&typeof s.emit=="function"&&typeof s.reallyExit=="function"&&typeof s.listeners=="function"&&typeof s.kill=="function"&&typeof s.pid=="number"&&typeof s.on=="function","processOk"),Mi=Symbol.for("signal-exit emitter"),Ii=globalThis,uh=Object.defineProperty.bind(Object),ji=class{static{l(this,"Emitter")}emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Ii[Mi])return Ii[Mi];uh(Ii,Mi,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let o=this.listeners[e],n=o.indexOf(t);n!==-1&&(n===0&&o.length===1?o.length=0:o.splice(n,1))}emit(e,t,o){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let r of this.listeners[e])n=r(t,o)===!0||n;return e==="exit"&&(n=this.emit("afterExit",t,o)||n),n}},Un=class{static{l(this,"SignalExitBase")}},dh=l(s=>({onExit(e,t){return s.onExit(e,t)},load(){return s.load()},unload(){return s.unload()}}),"signalExitWrap"),Ni=class extends Un{static{l(this,"SignalExitFallback")}onExit(){return()=>{}}load(){}unload(){}},Li=class extends Un{static{l(this,"SignalExit")}#i=Bi.platform==="win32"?"SIGINT":"SIGHUP";#o=new ji;#e;#n;#p;#t={};#r=!1;constructor(e){super(),this.#e=e,this.#t={};for(let t of ko)this.#t[t]=()=>{let o=this.#e.listeners(t),{count:n}=this.#o,r=e;if(typeof r.__signal_exit_emitter__=="object"&&typeof r.__signal_exit_emitter__.count=="number"&&(n+=r.__signal_exit_emitter__.count),o.length===n){this.unload();let i=this.#o.emit("exit",null,t),c=t==="SIGHUP"?this.#i:t;i||e.kill(e.pid,c)}};this.#p=e.reallyExit,this.#n=e.emit}onExit(e,t){if(!Bn(this.#e))return()=>{};this.#r===!1&&this.load();let o=t?.alwaysLast?"afterExit":"exit";return this.#o.on(o,e),()=>{this.#o.removeListener(o,e),this.#o.listeners.exit.length===0&&this.#o.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#r){this.#r=!0,this.#o.count+=1;for(let e of ko)try{let t=this.#t[e];t&&this.#e.on(e,t)}catch{}this.#e.emit=(e,...t)=>this.#m(e,...t),this.#e.reallyExit=e=>this.#s(e)}}unload(){this.#r&&(this.#r=!1,ko.forEach(e=>{let t=this.#t[e];if(!t)throw new Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch{}}),this.#e.emit=this.#n,this.#e.reallyExit=this.#p,this.#o.count-=1)}#s(e){return Bn(this.#e)?(this.#e.exitCode=e||0,this.#o.emit("exit",this.#e.exitCode,null),this.#p.call(this.#e,this.#e.exitCode)):0}#m(e,...t){let o=this.#n;if(e==="exit"&&Bn(this.#e)){typeof t[0]=="number"&&(this.#e.exitCode=t[0]);let n=o.call(this.#e,e,...t);return this.#o.emit("exit",this.#e.exitCode,null),n}else return o.call(this.#e,e,...t)}},Bi=globalThis.process,{onExit:Bl,load:vD,unload:SD}=dh(Bn(Bi)?new Li(Bi):new Ni);var Ul=As.default.stderr.isTTY?As.default.stderr:As.default.stdout.isTTY?As.default.stdout:void 0,ph=Ul?Ll(()=>{Bl(()=>{Ul.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},Wl=ph;var Wn=!1,Jo={};Jo.show=(s=Ui.default.stderr)=>{s.isTTY&&(Wn=!1,s.write("\x1B[?25h"))};Jo.hide=(s=Ui.default.stderr)=>{s.isTTY&&(Wl(),Wn=!0,s.write("\x1B[?25l"))};Jo.toggle=(s,e)=>{s!==void 0&&(Wn=s),Wn?Jo.show(e):Jo.hide(e)};var Wi=Jo;var Is=y(Hi(),1);U();var qe=y(require("node:process"),1);function Gi(){return qe.default.platform!=="win32"?qe.default.env.TERM!=="linux":!!qe.default.env.CI||!!qe.default.env.WT_SESSION||!!qe.default.env.TERMINUS_SUBLIME||qe.default.env.ConEmuTask==="{cmd::Cmder}"||qe.default.env.TERM_PROGRAM==="Terminus-Sublime"||qe.default.env.TERM_PROGRAM==="vscode"||qe.default.env.TERM==="xterm-256color"||qe.default.env.TERM==="alacritty"||qe.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Gi,"isUnicodeSupported");var fh={info:a.blue("\u2139"),success:a.green("\u2714"),warning:a.yellow("\u26A0"),error:a.red("\u2716")},gh={info:a.blue("i"),success:a.green("\u221A"),warning:a.yellow("\u203C"),error:a.red("\xD7")},hh=Gi()?fh:gh,Ps=hh;function qi({onlyFirst:s=!1}={}){let n="(?:\\u001B\\][^\\u0007\\u001B\\u009C]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";return new RegExp(n,s?void 0:"g")}l(qi,"ansiRegex");var yh=qi();function Os(s){if(typeof s!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof s}\``);return!s.includes("\x1B")&&!s.includes("\x9B")?s:s.replace(yh,"")}l(Os,"stripAnsi");var Vl=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],zl=12288,Jl=65510,Kl=[12288,12288,65281,65376,65504,65510];var Yl=4352,Xl=262141,Vi=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Gn=l((s,e)=>{let t=0,o=Math.floor(s.length/2)-1;for(;t<=o;){let n=Math.floor((t+o)/2),r=n*2;if(e<s[r])o=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1},"isInRange");var Ql=19968,[kh,Dh]=vh(Vi);function vh(s){let e=s[0],t=s[1];for(let o=0;o<s.length;o+=2){let n=s[o],r=s[o+1];if(Ql>=n&&Ql<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}l(vh,"findWideFastPathRange");var Zl=l(s=>s<161||s>1114109?!1:Gn(Vl,s),"isAmbiguous"),eu=l(s=>s<zl||s>Jl?!1:Gn(Kl,s),"isFullWidth");var tu=l(s=>s>=kh&&s<=Dh?!0:s<Yl||s>Xl?!1:Gn(Vi,s),"isWide");function Sh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}l(Sh,"validate");function ou(s,{ambiguousAsWide:e=!1}={}){return Sh(s),eu(s)||tu(s)||e&&Zl(s)?2:1}l(ou,"eastAsianWidth");var ru=y(nu(),1);var xh=new Intl.Segmenter,Ch=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function zi(s,e={}){if(typeof s!="string"||s.length===0)return 0;let{ambiguousIsNarrow:t=!0,countAnsiEscapeCodes:o=!1}=e;if(o||(s=Os(s)),s.length===0)return 0;let n=0,r={ambiguousAsWide:!t};for(let{segment:i}of xh.segment(s)){let c=i.codePointAt(0);if(!(c<=31||c>=127&&c<=159)&&!(c>=8203&&c<=8207||c===65279)&&!(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)&&!(c>=55296&&c<=57343)&&!(c>=65024&&c<=65039)&&!Ch.test(i)){if((0,ru.default)().test(i)){n+=2;continue}n+=ou(c,r)}}return n}l(zi,"stringWidth");function Ji({stream:s=process.stdout}={}){return!!(s&&s.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}l(Ji,"isInteractive");var Ki=y(require("node:process"),1);function Yi(){let{env:s}=Ki.default,{TERM:e,TERM_PROGRAM:t}=s;return Ki.default.platform!=="win32"?e!=="linux":!!s.WT_SESSION||!!s.TERMINUS_SUBLIME||s.ConEmuTask==="{cmd::Cmder}"||t==="Terminus-Sublime"||t==="vscode"||e==="xterm-256color"||e==="alacritty"||e==="rxvt-unicode"||e==="rxvt-unicode-256color"||s.TERMINAL_EMULATOR==="JetBrains-JediTerm"}l(Yi,"isUnicodeSupported");var et=y(require("node:process"),1);var $h=3,Xi=class{static{l(this,"StdinDiscarder")}#i=0;start(){this.#i++,this.#i===1&&this.#o()}stop(){if(this.#i<=0)throw new Error("`stop` called more times than `start`");this.#i--,this.#i===0&&this.#e()}#o(){et.default.platform==="win32"||!et.default.stdin.isTTY||(et.default.stdin.setRawMode(!0),et.default.stdin.on("data",this.#n),et.default.stdin.resume())}#e(){et.default.stdin.isTTY&&(et.default.stdin.off("data",this.#n),et.default.stdin.pause(),et.default.stdin.setRawMode(!1))}#n(e){e[0]===$h&&et.default.emit("SIGINT")}},_h=new Xi,Qi=_h;var Eh=y(Hi(),1);var Zi=class{static{l(this,"Ora")}#i=0;#o=!1;#e=0;#n=-1;#p=0;#t;#r;#s;#m;#g;#l;#u;#d;#h;#a;#c;color;constructor(e){typeof e=="string"&&(e={text:e}),this.#t={color:"cyan",stream:Ms.default.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#t.color,this.spinner=this.#t.spinner,this.#g=this.#t.interval,this.#s=this.#t.stream,this.#l=typeof this.#t.isEnabled=="boolean"?this.#t.isEnabled:Ji({stream:this.#s}),this.#u=typeof this.#t.isSilent=="boolean"?this.#t.isSilent:!1,this.text=this.#t.text,this.prefixText=this.#t.prefixText,this.suffixText=this.#t.suffixText,this.indent=this.#t.indent,Ms.default.env.NODE_ENV==="test"&&(this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#i},set(t){this.#i=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#n}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}}))}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw new Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#f()}get interval(){return this.#g??this.#r.interval??100}get spinner(){return this.#r}set spinner(e){if(this.#n=-1,this.#g=void 0,typeof e=="object"){if(e.frames===void 0)throw new Error("The given spinner must have a `frames` property");this.#r=e}else if(!Yi())this.#r=Is.default.line;else if(e===void 0)this.#r=Is.default.dots;else if(e!=="default"&&Is.default[e])this.#r=Is.default[e];else throw new Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#h}set text(e=""){this.#h=e,this.#f()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#f()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#f()}get isSpinning(){return this.#m!==void 0}#y(e=this.#a,t=" "){return typeof e=="string"&&e!==""?e+t:typeof e=="function"?e()+t:""}#b(e=this.#c,t=" "){return typeof e=="string"&&e!==""?t+e:typeof e=="function"?t+e():""}#f(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),o=this.#b(this.#c,"-"),n=" ".repeat(this.#d)+t+"--"+this.#h+"--"+o;this.#e=0;for(let r of Os(n).split(`
|
|
236
|
+
`))this.#e+=Math.max(1,Math.ceil(zi(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&&Wi.hide(this.#s),this.#t.discardStdin&&Ms.default.stdin.isTTY&&(this.#o=!0,Qi.start()),this.render(),this.#m=setInterval(this.render.bind(this),this.interval),this):(this.text&&this.#s.write(`- ${this.text}
|
|
237
237
|
`),this)}stop(){return this.#l?(clearInterval(this.#m),this.#m=void 0,this.#n=0,this.clear(),this.#t.hideCursor&&Wi.show(this.#s),this.#t.discardStdin&&Ms.default.stdin.isTTY&&this.#o&&(Qi.stop(),this.#o=!1),this):this}succeed(e){return this.stopAndPersist({symbol:Ps.success,text:e})}fail(e){return this.stopAndPersist({symbol:Ps.error,text:e})}warn(e){return this.stopAndPersist({symbol:Ps.warning,text:e})}info(e){return this.stopAndPersist({symbol:Ps.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
238
|
`;return this.stop(),this.#s.write(p),this}};function js(s){return new Zi(s)}l(js,"ora");Ce();U();Ce();U();Ce();function iu(s,e,t={}){let o=j(),n=Ve(o),r=W(o),i=t.maxWidth??o.columns,c=t.color??o.ansi,u=e.split(`
|
|
239
239
|
`),d=[],p=`${n.topLeft}${n.horizontal} ${r.file} ${s} `,f=n.horizontal.repeat(Math.max(0,i-cu(p).length-1));d.push(c?a.cyan(p+f+n.topRight):p+f+n.topRight);let m=0,g=0;for(let v of u)if(!(v.startsWith("---")||v.startsWith("+++")||v.startsWith("diff ")||v.startsWith("index "))){if(v.startsWith("@@")){let x=`${n.vertical} ${v}`;d.push(c?a.magenta(x):x);continue}if(v.startsWith("+")){m++;let x=`${n.vertical} + ${v.slice(1)}`,_=ea(x,i);d.push(c?a.green(_):_);continue}if(v.startsWith("-")){g++;let x=`${n.vertical} - ${v.slice(1)}`,_=ea(x,i);d.push(c?a.red(_):_);continue}if(v.startsWith(" ")||v===""){let x=`${n.vertical} ${v}`,_=ea(x,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(iu,"renderDiff");function au(s,e,t){let o=j(),n=W(o),r=o.ansi,i=r?a.green(`+${e}`):`+${e}`,c=r?a.red(`-${t}`):`-${t}`;return` ${n.file} ${s} (${i} ${c})`}l(au,"renderDiffSummary");function ea(s,e){return cu(s).length<=e?s:s.slice(0,e-3)+"..."}l(ea,"truncateLine");function cu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(cu,"stripAnsi");function oa(s,e){let t=j(),o=W(t),n=t.ansi,r=Yh(s,o),i=Xh(s,e),c=` ${r} ${s}: ${i}`;return n?a.yellow(c):c}l(oa,"renderToolStart");function sa(s,e,t={}){switch(e.type){case"file_edit":return Wh(e,t);case"file_read":return Hh(e);case"terminal":return Gh(e,t);case"search":return qh(e,t);case"git":return Vh(e);case"browser":return
|
|
240
|
+
`)}l(iu,"renderDiff");function au(s,e,t){let o=j(),n=W(o),r=o.ansi,i=r?a.green(`+${e}`):`+${e}`,c=r?a.red(`-${t}`):`-${t}`;return` ${n.file} ${s} (${i} ${c})`}l(au,"renderDiffSummary");function ea(s,e){return cu(s).length<=e?s:s.slice(0,e-3)+"..."}l(ea,"truncateLine");function cu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(cu,"stripAnsi");function oa(s,e){let t=j(),o=W(t),n=t.ansi,r=Yh(s,o),i=Xh(s,e),c=` ${r} ${s}: ${i}`;return n?a.yellow(c):c}l(oa,"renderToolStart");function sa(s,e,t={}){switch(e.type){case"file_edit":return Wh(e,t);case"file_read":return Hh(e);case"terminal":return Gh(e,t);case"search":return qh(e,t);case"git":return Vh(e);case"browser":return zh(e);case"mcp":return Jh(e);case"web_search":return Kh(e);case"generic":return lu(s,e);default:return lu(s,{type:"generic",summary:JSON.stringify(e)})}}l(sa,"renderToolResult");function uu(s,e){let t=j(),o=W(t),n=t.ansi,r=` ${o.error} ${s} failed: ${e}`;return n?a.red(r):r}l(uu,"renderToolError");function Wh(s,e){return e.verbose&&s.diff?iu(s.filePath,s.diff):au(s.filePath,s.linesAdded,s.linesRemoved)}l(Wh,"renderFileEdit");function Hh(s){let e=j();return` ${W(e).file} Read ${ta(s.filePath)} (${s.lineCount} lines)`}l(Hh,"renderFileRead");function Gh(s,e){let t=j(),o=Ve(t),n=W(t),r=t.ansi,i=e.maxOutputLines??50,c=[],u=s.exitCode===0?r?a.green(n.checkmark):n.checkmark:r?a.red(n.cross):n.cross,d=` ${n.tool} $ ${s.command}`;if(c.push(r?a.bold(d):d),s.stdout){let f=s.stdout.split(`
|
|
241
241
|
`),m=f.slice(0,i);for(let g of m)c.push(r?a.dim(` ${g}`):` ${g}`);if(f.length>i){let g=` [truncated ${f.length-i} lines \u2014 use --verbose for full output]`;c.push(r?a.yellow(g):g)}}if(s.stderr&&s.stderr!==s.stdout){let f=s.stderr.split(`
|
|
242
242
|
`).slice(0,10);for(let m of f)c.push(r?a.red(` ${m}`):` ${m}`)}let p=s.duration?` (${(s.duration/1e3).toFixed(1)}s)`:"";return c.push(` ${u} Exit ${s.exitCode}${p}`),c.join(`
|
|
243
243
|
`)}l(Gh,"renderTerminal");function qh(s,e){let t=j(),o=W(t),n=t.ansi,r=[];r.push(` ${o.search} Search: "${s.query}" (${s.totalMatches} matches)`);let i=e.verbose?20:8,c=s.matches.slice(0,i);for(let u of c){let d=`${u.file}:${u.line}`,p=u.content.trim().slice(0,80),f=` ${d}: ${p}`;r.push(n?a.dim(f):f)}return s.matches.length>i&&r.push(n?a.yellow(` ... ${s.matches.length-i} more matches`):` ... ${s.matches.length-i} more matches`),r.join(`
|
|
244
244
|
`)}l(qh,"renderSearch");function Vh(s){let e=j(),t=W(e),o=e.ansi,n=[];if(n.push(` ${t.git} git ${s.command}`),s.output){let r=s.output.split(`
|
|
245
245
|
`).slice(0,15);for(let i of r)n.push(o?a.dim(` ${i}`):` ${i}`)}return n.join(`
|
|
246
|
-
`)}l(Vh,"renderGit");function
|
|
247
|
-
`)}l(
|
|
246
|
+
`)}l(Vh,"renderGit");function zh(s){let e=j(),t=W(e),o=e.ansi,n=[];if(n.push(` ${t.browser} ${s.title||s.url}`),s.url&&n.push(o?a.dim(` ${s.url}`):` ${s.url}`),s.content){let r=s.content.slice(0,200).replace(/\n/g," ");n.push(o?a.dim(` ${r}...`):` ${r}...`)}return n.join(`
|
|
247
|
+
`)}l(zh,"renderBrowser");function Jh(s){let e=j(),t=W(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
248
|
`).slice(0,10);for(let h of m)i.push(`${o.vertical} ${h}`);f.split(`
|
|
249
249
|
`).length>10&&i.push(`${o.vertical} ${n?a.dim(`... ${f.split(`
|
|
250
250
|
`).length-10} more lines`):"..."}`);let g=`${o.bottomLeft}${o.horizontal.repeat(Math.max(0,r-2))}${o.bottomRight}`;return i.push(n?a.blue(g):g),i.join(`
|
|
251
|
-
`)}l(
|
|
252
|
-
`)}l(Kh,"renderWebSearch");function lu(s,e){let t=j();return` ${W(t).tool} ${s}: ${e.summary}`}l(lu,"renderGeneric");function Yh(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(Yh,"getToolIcon");function Xh(s,e){switch(s){case"file_edit":return ta(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return ta(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(Xh,"getToolArgsSummary");function ta(s){return process.platform==="win32"?s.replace(/\//g,"\\"):s}l(ta,"displayPath");U();function
|
|
251
|
+
`)}l(Jh,"renderMcp");function Kh(s){let e=j(),t=W(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(Kh,"renderWebSearch");function lu(s,e){let t=j();return` ${W(t).tool} ${s}: ${e.summary}`}l(lu,"renderGeneric");function Yh(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(Yh,"getToolIcon");function Xh(s,e){switch(s){case"file_edit":return ta(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return ta(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(Xh,"getToolArgsSummary");function ta(s){return process.platform==="win32"?s.replace(/\//g,"\\"):s}l(ta,"displayPath");U();function zn(s,e={}){let t=e.width||process.stdout.columns||80,o=s.split(`
|
|
253
253
|
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(du(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 v=h[1],x=Vn(h[3]);n.push(`${v} \u2022 ${x}`);continue}let b=u.match(/^(\s*)(\d+)\.\s(.+)/);if(b){let v=b[1],x=b[2],_=Vn(b[3]);n.push(`${v} ${a.dim(x+".")} ${_}`);continue}let k=u.match(/^>\s?(.*)/);if(k){n.push(a.dim(" \u2502 ")+a.italic(Vn(k[1])));continue}if(u.trim()===""){n.push("");continue}n.push(Vn(u))}return r&&c.length>0&&n.push(du(c,i)),n.join(`
|
|
254
|
-
`)}l(
|
|
255
|
-
`)}l(du,"renderCodeBlock");function Qh(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=Zh(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(Qh,"highlightSyntax");function Zh(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(Zh,"getLanguageKeywords");function pu(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(pu,"containsMarkdown");U();Ce();var
|
|
256
|
-
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=j(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,b=t.dirty?a.yellow:a.green,k=t.dirty?" \u25CF":"";o.push(b(` ${h} ${t.branch}${k} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=ey(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,b=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(b(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,b=6,k=Math.round(t.contextPct/100*b),v=b-k,x=h("\u2588".repeat(k))+a.dim("\u2591".repeat(v));r.push(` ${x} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=mu(c).length,p=mu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function ey(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(ey,"formatTokensCompact");function mu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(mu,"stripAnsi");U();var zo={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},ty={width:44,height:19,glyphs:[" \u2584\u2584\u2588 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2588 "," \u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u2588\u2584 ","\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588","\u2588\u2588\u2588 \u2580\u2588\u2580\u2580 \u2584\u2588 \u2588\u2588\u2588 \u2584\u2584 \u2580\u2580\u2588\u2580 \u2588\u2588\u2588","\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2584 \u2584\u2588\u2588\u2588","\u2580\u2588\u2588\u2588\u2588\u2584\u2584 \u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588 \u2584\u2584\u2588\u2588\u2588\u2588\u2580"," \u2580\u2588\u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2588\u2580 \u2584\u2588\u2588\u2588\u2588\u2580 \u2588\u2588\u2588\u2588\u2580 "," \u2580\u2588\u2584 \u2580\u2588\u2588 \u2584\u2588\u2588\u2580 \u2588\u2588\u2580 \u2584\u2588\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2588\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["......................nnn...................","..................nnnnnnnnnn................","..............nnnnnnnnnnnnnnnn..............","...........nnnnnnnnnnnnnnnnnnnnnn...........","........nnnnnnnnnnnnnnnnnnnnnnnnnnnn........","....n...nnnnnnn....nnnnnn....nnnnnnn...n....",".nnnnnnnnnnn....................nnnnnnnnnnn.","nnnnnnnnnnnn....................nnnnnnnnnnnn","nnn....nnnn....ll......lll..ll...nnnn....nnn","nnnn........lllll.....lll...lllll.......nnnn","nnnnnnn....llll......lll.....lllll...nnnnnnn","...nnnnn...llllll...llll....llllll..nnnnn...","......nnn.....lll..llll.....lll....nnn......","........nnnnn......lll.........nnnnn........","........nnnnnnnn............nnnnnnnn........",".........nnnnnnnnn........nnnnnnnnn.........","............nnnnnnn......nnnnnnn............","................nnnnnnnnnnnn................","...................nnnnnn..................."]},oy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},sy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},ny={large:ty,medium:oy,mini:sy},fu="\u25C1\u2571\u25B7",gu="</>";function hu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(hu,"isDarkBackground");function yu(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=ny[s],c=o?zo.navyOnDark:zo.navy,u=t?a.hex(c):m=>m,d=t?a.hex(zo.ice):m=>m,p=l((m,g)=>g==="n"?u(m):g==="l"?d(m):m,"paint"),f=" ".repeat(r!==void 0?Math.max(0,Math.floor((r-i.width)/2)):n);return i.glyphs.map((m,g)=>{let h=i.mask[g],b="",k="",v=h[0]??".";for(let x=0;x<m.length;x++){let _=h[x]??".";_!==v&&(b+=p(k,v),k="",v=_),k+=m[x]}return b+=p(k,v),(f+b).replace(/\s+$/,"")})}l(yu,"renderLogo");function bu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(bu,"pickLogoSize");function na(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(na,"visibleWidth");var ry={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},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={...ry,...e},this.caps=j(),this.icons=W(this.caps),this.box=Ve(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:l(t=>this.renderToken(t),"onToken"),onThinking:l(t=>this.renderThinking(t),"onThinking"),onRunStarted:l(t=>this.renderRunStarted(t),"onRunStarted"),onRunComplete:l(t=>this.renderRunComplete(t),"onRunComplete"),onRunError:l(t=>this.renderRunError(t),"onRunError"),onToolStart:l(t=>this.renderToolStart(t),"onToolStart"),onToolProgress:l(t=>this.renderToolProgress(t),"onToolProgress"),onToolResult:l(t=>this.renderToolResult(t),"onToolResult"),onToolError:l(t=>this.renderToolError(t),"onToolError"),onApprovalRequest:l(t=>this.renderApprovalRequest(t),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new zn(e)),this.statusBar}printTurnBoundary(e,t,o,n){let r=this.caps.ansi,i=Math.min(60,this.caps.columns-4),c=t>=1e3?`${(t/1e3).toFixed(1)}K`:`${t}`,u=o?` ${this.icons.cost} $${o.toFixed(3)}`:"",d=n?` ${a.dim(`total: $${n.toFixed(2)}`)}`:"",p=` Turn ${e} ${a.dim("\xB7")} ${c} tokens${u}${d} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,m=Math.max(0,i-f),g=Math.floor(m/2),h=` ${this.box.horizontal.repeat(g)}${p}${this.box.horizontal.repeat(m-g)}`;console.log(""),console.log(r?a.dim(h):h),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,t={}){let o=this.caps.ansi,n=o?a.hex(zo.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.1";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?bu(this.caps.columns,this.caps.unicode):u;if(d){let f=yu(d,{color:o,dark:hu(),center:Math.min(56,this.caps.columns)});for(let m of f)console.log(m);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,f=52;console.log(n(` ${p.topLeft}${p.horizontal.repeat(f)}${p.topRight}`));let g=`${this.caps.nerdFont?"\uF120":fu} MonkeysCode`,h="CLI Agent",b=Math.max(0,f-na(g)-h.length-2);console.log(` ${n(p.vertical)} ${i(g)}${" ".repeat(b)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let k=`${c}${e?` \xB7 ${e}`:""}`,v=Math.max(0,f-na(k)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(v)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${gu} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(this.lastWasToken||(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode&&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(
|
|
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=js({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(
|
|
259
|
-
`).length;if(this.caps.ansi&&pu(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=
|
|
254
|
+
`)}l(zn,"renderMarkdown");function Vn(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(Vn,"renderInline");function du(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}${Qh(c,e)}`);return[n,...i,r].join(`
|
|
255
|
+
`)}l(du,"renderCodeBlock");function Qh(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=Zh(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(Qh,"highlightSyntax");function Zh(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(Zh,"getLanguageKeywords");function pu(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(pu,"containsMarkdown");U();Ce();var Jn=class{static{l(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=j(),this.icons=W(this.caps),this.data={model:"",mode:"code",branch:"",dirty:!1,sandbox:!1,tokensIn:0,tokensOut:0,cost:0,turn:0,contextPct:0,activity:"",busy:!1,budgetUsd:0,...e}}start(){!this.caps.stdoutTTY||!this.caps.ansi||(this.enabled=!0,process.stdout.write(`
|
|
256
|
+
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=j(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,b=t.dirty?a.yellow:a.green,k=t.dirty?" \u25CF":"";o.push(b(` ${h} ${t.branch}${k} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=ey(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,b=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(b(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,b=6,k=Math.round(t.contextPct/100*b),v=b-k,x=h("\u2588".repeat(k))+a.dim("\u2591".repeat(v));r.push(` ${x} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=mu(c).length,p=mu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function ey(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(ey,"formatTokensCompact");function mu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(mu,"stripAnsi");U();var Tt={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},ty={width:44,height:19,glyphs:[" \u2584\u2584\u2588 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2584\u2584\u2588\u2588 "," \u2584\u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2580\u2580 \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2584\u2588\u2588\u2588\u2588\u2588\u2584 ","\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2588\u2588\u2588\u2588","\u2588\u2588\u2588 \u2580\u2588\u2580\u2580 \u2584\u2588 \u2588\u2588\u2588 \u2584\u2584 \u2580\u2580\u2588\u2580 \u2588\u2588\u2588","\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588 \u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2584 \u2584\u2588\u2588\u2588","\u2580\u2588\u2588\u2588\u2588\u2584\u2584 \u2588\u2588\u2588\u2580 \u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588 \u2584\u2584\u2588\u2588\u2588\u2588\u2580"," \u2580\u2588\u2588\u2588\u2588 \u2580\u2588\u2588\u2588\u2588\u2584 \u2588\u2588\u2588\u2580 \u2584\u2588\u2588\u2588\u2588\u2580 \u2588\u2588\u2588\u2588\u2580 "," \u2580\u2588\u2584 \u2580\u2588\u2588 \u2584\u2588\u2588\u2580 \u2588\u2588\u2580 \u2584\u2588\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2584\u2584 \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2588 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2580\u2580 "," \u2580\u2588\u2588\u2588\u2584\u2584\u2584\u2584\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["......................nnn...................","..................nnnnnnnnnn................","..............nnnnnnnnnnnnnnnn..............","...........nnnnnnnnnnnnnnnnnnnnnn...........","........nnnnnnnnnnnnnnnnnnnnnnnnnnnn........","....n...nnnnnnn....nnnnnn....nnnnnnn...n....",".nnnnnnnnnnn....................nnnnnnnnnnn.","nnnnnnnnnnnn....................nnnnnnnnnnnn","nnn....nnnn....ll......lll..ll...nnnn....nnn","nnnn........lllll.....lll...lllll.......nnnn","nnnnnnn....llll......lll.....lllll...nnnnnnn","...nnnnn...llllll...llll....llllll..nnnnn...","......nnn.....lll..llll.....lll....nnn......","........nnnnn......lll.........nnnnn........","........nnnnnnnn............nnnnnnnn........",".........nnnnnnnnn........nnnnnnnnn.........","............nnnnnnn......nnnnnnn............","................nnnnnnnnnnnn................","...................nnnnnn..................."]},oy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},sy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},ny={large:ty,medium:oy,mini:sy},fu="\u25C1\u2571\u25B7",gu="</>";function hu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(hu,"isDarkBackground");function yu(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=ny[s],c=o?Tt.navyOnDark:Tt.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Tt.ice):m=>m,p=l((m,g)=>g==="n"?u(m):g==="l"?d(m):m,"paint"),f=" ".repeat(r!==void 0?Math.max(0,Math.floor((r-i.width)/2)):n);return i.glyphs.map((m,g)=>{let h=i.mask[g],b="",k="",v=h[0]??".";for(let x=0;x<m.length;x++){let _=h[x]??".";_!==v&&(b+=p(k,v),k="",v=_),k+=m[x]}return b+=p(k,v),(f+b).replace(/\s+$/,"")})}l(yu,"renderLogo");function bu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(bu,"pickLogoSize");function na(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(na,"visibleWidth");var ry={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},So=class{static{l(this,"TuiRenderer")}caps;icons;box;opts;spinner=null;activeToolSpinners=new Map;toolDurations=new Map;toolStartTimes=new Map;tokenBuffer="";lastWasToken=!1;statusBar=null;currentTurn=0;turnTokens=0;constructor(e={}){this.opts={...ry,...e},this.caps=j(),this.icons=W(this.caps),this.box=Ve(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:l(t=>this.renderToken(t),"onToken"),onThinking:l(t=>this.renderThinking(t),"onThinking"),onRunStarted:l(t=>this.renderRunStarted(t),"onRunStarted"),onRunComplete:l(t=>this.renderRunComplete(t),"onRunComplete"),onRunError:l(t=>this.renderRunError(t),"onRunError"),onToolStart:l(t=>this.renderToolStart(t),"onToolStart"),onToolProgress:l(t=>this.renderToolProgress(t),"onToolProgress"),onToolResult:l(t=>this.renderToolResult(t),"onToolResult"),onToolError:l(t=>this.renderToolError(t),"onToolError"),onApprovalRequest:l(t=>this.renderApprovalRequest(t),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new Jn(e)),this.statusBar}printTurnBoundary(e,t,o,n){let r=this.caps.ansi,i=Math.min(60,this.caps.columns-4),c=t>=1e3?`${(t/1e3).toFixed(1)}K`:`${t}`,u=o?` ${this.icons.cost} $${o.toFixed(3)}`:"",d=n?` ${a.dim(`total: $${n.toFixed(2)}`)}`:"",p=` Turn ${e} ${a.dim("\xB7")} ${c} tokens${u}${d} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,m=Math.max(0,i-f),g=Math.floor(m/2),h=` ${this.box.horizontal.repeat(g)}${p}${this.box.horizontal.repeat(m-g)}`;console.log(""),console.log(r?a.dim(h):h),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,t={}){let o=this.caps.ansi,n=o?a.hex(Tt.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.3";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?bu(this.caps.columns,this.caps.unicode):u;if(d){let f=yu(d,{color:o,dark:hu(),center:Math.min(56,this.caps.columns)});for(let m of f)console.log(m);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,f=52;console.log(n(` ${p.topLeft}${p.horizontal.repeat(f)}${p.topRight}`));let g=`${this.caps.nerdFont?"\uF120":fu} MonkeysCode`,h="CLI Agent",b=Math.max(0,f-na(g)-h.length-2);console.log(` ${n(p.vertical)} ${i(g)}${" ".repeat(b)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let k=`${c}${e?` \xB7 ${e}`:""}`,v=Math.max(0,f-na(k)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(v)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${gu} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let t=a.hex(Tt.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
257
|
+
`+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(Tt.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(oa(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=js({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(sa(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(uu(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=js({text:e,indent:2,spinner:"dots"}).start()}succeedSpinner(e){this.spinner&&(this.spinner.succeed(e),this.spinner=null)}failSpinner(e){this.spinner&&(this.spinner.fail(e),this.spinner=null)}clearSpinners(){this.spinner&&(this.spinner.stop(),this.spinner=null);for(let[e,t]of this.activeToolSpinners)t.stop();this.activeToolSpinners.clear()}getToolAvgDuration(e){let t=this.toolDurations.get(e);if(!t||t.length===0)return 0;let o=t.reduce((n,r)=>n+r,0);return Math.round(o/t.length)}recordToolDuration(e,t){let o=this.toolDurations.get(e)??[];o.push(t),o.length>10&&o.shift(),this.toolDurations.set(e,o)}printSessionSummary(e){let t=this.caps.ansi,o=e.endTime?((e.endTime-e.startTime)/1e3).toFixed(1):"?";if(this.caps.unicode){let n=this.box,r=Math.min(48,this.caps.columns-6),i=a.hex(Tt.accent),c=a.dim,u=[["Duration",`${o}s`],["Tokens",e.tokensUsed.toLocaleString()],["Tools",`${e.toolCalls} calls`],["Files",`${e.filesChanged.length} changed`]];console.log(""),console.log(i(` ${n.topLeft}${n.horizontal} \u{1F4CB} Session Summary ${n.horizontal.repeat(Math.max(0,r-22))}${n.topRight}`));for(let[d,p]of u){let f=d.padEnd(12),m=`${f}${p}`,g=Math.max(0,r-m.length-4);console.log(i(` ${n.vertical}`)+` ${c(f)}${p}${" ".repeat(g)}`+i(n.vertical))}if(e.filesChanged.length>0){console.log(i(` ${n.teeRight}${n.horizontal.repeat(r)}${n.teeLeft}`));for(let d of e.filesChanged){let p=d.split("/").slice(-2).join("/"),f=` ${this.icons.edit} ${p}`,m=Math.max(0,r-f.length);console.log(i(` ${n.vertical}`)+`${f}${" ".repeat(m)}`+i(n.vertical))}}console.log(i(` ${n.bottomLeft}${n.horizontal.repeat(r)}${n.bottomRight}`)),console.log("")}else{let n=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(""),console.log(t?a.dim(n):n),console.log(" Session Summary"),console.log(` Tokens: ${e.tokensUsed.toLocaleString()}`),console.log(` Tool calls: ${e.toolCalls}`),console.log(` Files changed: ${e.filesChanged.length}`),console.log(` Duration: ${o}s`),console.log(t?a.dim(n):n),console.log("")}}printToolCallStart(e,t){if(this.lastWasToken&&(console.log(""),this.lastWasToken=!1),console.log(""),console.log(oa(e,t)),!this.opts.accessible&&this.caps.ansi){let o=js({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(sa(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&&pu(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=zn(e,{caps:this.caps});if(this.caps.unicode){let n=a.dim(` ${this.box.vertical} `),r=o.split(`
|
|
260
|
+
`).map(i=>n+i).join(`
|
|
261
|
+
`);process.stdout.write(r)}else process.stdout.write(o)}else console.log("");if(this.caps.unicode){let o=a.hex(Tt.accent),n=Math.min(56,this.caps.columns-6);console.log(""),console.log(o(` ${this.box.bottomLeft}${this.box.horizontal.repeat(n)}${this.box.bottomRight}`))}}renderMessageCard(e){let t=this.box,o=this.caps.emoji?"\u{1F4E8}":">>",n=Math.min(60,Math.max(40,e.content.length+6)),r=` ${o} Message from ${e.from} `,i=e.timestamp.toLocaleTimeString(),c=Math.max(0,n-r.length-2),u=` ${t.topLeft}${t.horizontal}${r}${t.horizontal.repeat(c)}${t.topRight}`,d=n-4,p=iy(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 iy(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(iy,"wrapText");Ce();oe();ze();Q();var ue=y(require("node:fs"),1),Pe=y(require("node:path"),1);X();var Ey=20;function id(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)),Fy(r)}l(id,"saveCheckpoint");function ad(){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(ad,"listCheckpoints");function cd(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(cd,"revertCheckpoint");function Fy(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(Ey))try{ue.unlinkSync(Pe.join(s,t.name))}catch{}}l(Fy,"pruneCheckpoints");var he=y(require("node:fs"),1),ro=y(require("node:path"),1),ld=y(require("node:crypto"),1);X();var Ty="sessions",Ry=20,Ay=30*24*60*60*1e3,jt=class{static{l(this,"SessionStore")}sessionsDir;constructor(){let e=T();this.sessionsDir=ro.join(e.data,Ty),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:ld.randomUUID(),workspace:ro.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===ro.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=>ro.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,Ry)}delete(e){let t=this.sessionPath(e);return he.existsSync(t)?(he.unlinkSync(t),!0):!1}prune(e=Ay){this.ensureDir();let t=Date.now(),o=0,n=he.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).map(i=>ro.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 ro.join(this.sessionsDir,`${t}.json`)}ensureDir(){he.existsSync(this.sessionsDir)||he.mkdirSync(this.sessionsDir,{recursive:!0})}};Sa();var st=y(require("node:fs"),1),pr=y(require("node:path"),1);X();var Ma=1e3,Py="history",dr=class{static{l(this,"HistoryManager")}historyFile;constructor(){let e=T();this.historyFile=pr.join(e.data,Py)}load(){try{return st.existsSync(this.historyFile)?st.readFileSync(this.historyFile,"utf-8").split(`
|
|
260
262
|
`).filter(t=>t.trim().length>0).slice(-Ma):[]}catch{return[]}}append(e){let t=e.trim();if(t&&!t.startsWith("/"))try{let o=pr.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
263
|
`).filter(r=>r.trim().length>0)),n.length>0&&n[n.length-1]===t)return;n.push(t),n.length>Ma&&(n=n.slice(-Ma)),st.writeFileSync(this.historyFile,n.join(`
|
|
262
264
|
`)+`
|
|
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}};U();var mr=require("node:child_process");
|
|
265
|
+
`,"utf-8")}catch{}}wire(e){let t=this.load(),o=e;o.history&&Array.isArray(o.history)&&(o.history=[...t.reverse(),...o.history],o.history.length>e.historySize&&(o.history=o.history.slice(0,e.historySize))),e.on("line",n=>{this.append(n)})}getPath(){return this.historyFile}};U();var mr=require("node:child_process");ze();Q();function Ia(s){return Oy(s)?Ly(s):My(s)?By(s):Iy(s)?Uy(s):jy(s)?Wy(s):Ny(s)?Hy(s):Gy(s)}l(Ia,"parseTestOutput");function ud(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(ud,"detectVerifyCommand");function Oy(s){return/Tests?:\s+\d+ (?:passed|failed)/.test(s)||/PASS|FAIL/.test(s)&&/Test Suites:/.test(s)}l(Oy,"isJest");function My(s){return s.includes("vitest")||/✓|×/.test(s)&&/Tests\s+\d+/.test(s)}l(My,"isVitest");function Iy(s){return/={3,}\s*(?:FAILURES|ERRORS|short test summary)/.test(s)||/\d+ passed/.test(s)&&/pytest/.test(s)}l(Iy,"isPytest");function jy(s){return/test result:/.test(s)&&/ok|FAILED/.test(s)}l(jy,"isCargoTest");function Ny(s){return/^(?:ok|FAIL)\s+\S+/.test(s)||/--- FAIL:/.test(s)}l(Ny,"isGoTest");function Ly(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
266
|
`)[0],h=e.find(b=>m.includes(b.name));h&&(h.error=g)}let c=s.match(/Tests:\s+(?:(\d+) failed,?\s*)?(?:(\d+) skipped,?\s*)?(?:(\d+) passed,?\s*)?(\d+) total/),u=c?parseInt(c[1]||"0",10):e.filter(m=>m.status==="fail").length,d=c?parseInt(c[2]||"0",10):0,p=c?parseInt(c[3]||"0",10):0,f=c?parseInt(c[4]||"0",10):e.length;return os("jest",e,{total:f,passed:p,failed:u,skipped:d})}l(Ly,"parseJest");function By(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 os("vitest",e)}l(By,"parseVitest");function Uy(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 os("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(Uy,"parsePytest");function Wy(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
267
|
`)[0])}return os("cargo",e)}l(Wy,"parseCargoTest");function Hy(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 os("go",e)}l(Hy,"parseGoTest");function Gy(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 os("unknown",e)}l(Gy,"parseGeneric");function os(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(os,"buildSummary");var dd=10,pd=1800,md=5,fr=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||dd,status:"planning",subtasks:[],elapsed:0,totalTokens:0,totalCost:0}}async run(){this.startTime=Date.now();let e=this.opts.maxIterations||dd,t=(this.opts.timeoutSeconds||pd)*1e3,o=this.opts.maxCostUsd||md,n=
|
|
268
|
+
`);for(let o of t)/\bFAIL\b|✕|✗|ERROR|BROKEN/.test(o)&&e.push({suite:"unknown",name:o.trim().substring(0,100),status:"fail"});return os("unknown",e)}l(Gy,"parseGeneric");function os(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(os,"buildSummary");var dd=10,pd=1800,md=5,fr=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||dd,status:"planning",subtasks:[],elapsed:0,totalTokens:0,totalCost:0}}async run(){this.startTime=Date.now();let e=this.opts.maxIterations||dd,t=(this.opts.timeoutSeconds||pd)*1e3,o=this.opts.maxCostUsd||md,n=z();if(this.printGoalHeader(),!this.opts.verifyCommand){let r=ud(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
269
|
`);let o=[`AUTONOMOUS GOAL MODE \u2014 Iteration ${e}/${t}`,"",`Goal: ${this.opts.goal}`,"",`This is iteration ${e}. Previous iterations did not fully complete the goal.`,"Review the current state of the workspace and continue working toward the goal."];if(this.lastTestSummary&&this.lastTestSummary.failingTests.length>0){o.push(""),o.push("The following tests are still failing \u2014 focus on these:");for(let n of this.lastTestSummary.failingTests.slice(0,10)){let r=n.file?` (${n.file}${n.line?`:${n.line}`:""})`:"";o.push(` \u2717 ${n.suite}::${n.name}${r}${n.error?` \u2014 ${n.error.substring(0,80)}`:""}`)}o.push(""),o.push("Fix ONLY these specific failures. Do not refactor unrelated code.")}return o.push(""),o.push('End your response with "GOAL_STATUS: COMPLETE" if the goal is fully met,'),o.push('or "GOAL_STATUS: IN_PROGRESS" if more work is needed.'),o.join(`
|
|
268
270
|
`)}evaluateGoalCompletion(e){return this.opts.verifyCommand?this.runVerifyCommand():!!(e.includes("GOAL_STATUS: COMPLETE")||e.includes("GOAL_STATUS: DONE")||e.includes("All tests pass")&&e.includes("GOAL_STATUS"))}runVerifyCommand(){let e=this.opts.verifyCommand;console.log(a.dim(`
|
|
269
271
|
\u{1F50D} Running verification: ${e}`));try{let o=(0,mr.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=Ia(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(`
|
|
@@ -273,11 +275,11 @@ ${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
273
275
|
`).slice(-3).join(`
|
|
274
276
|
`)}`)):n.trim()&&console.log(a.dim(` ${n.trim().split(`
|
|
275
277
|
`).slice(-3).join(`
|
|
276
|
-
`)}`));return!1}}saveCheckpoint(){try{(0,mr.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,mr.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||pd)/60}min \xB7 Max cost: $${(this.opts.maxCostUsd||md).toFixed(2)}`)),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}printIterationHeader(e,t){let o=((Date.now()-this.startTime)/1e3).toFixed(0);console.log(""),console.log(a.hex("#6B8DD6")(` \u2501\u2501\u2501 Iteration ${e}/${t} \u2501\u2501\u2501 ${o}s elapsed \u2501\u2501\u2501 ${this.progress.totalTokens.toLocaleString()} tokens \u2501\u2501\u2501`)),console.log("")}printGoalStatus(e){let t=((Date.now()-this.startTime)/1e3).toFixed(0);switch(console.log(""),console.log(a.dim(` ${"\u2500".repeat(50)}`)),e){case"completed":console.log(a.green.bold(" \u2705 Goal completed!"));break;case"cancelled":console.log(a.yellow(" \u26A0\uFE0F Goal cancelled by user."));break;case"timeout":console.log(a.yellow(" \u23F1 Goal stopped: timeout reached."));break;case"cost_limit":console.log(a.yellow(` \u{1F4B0} Goal stopped: cost limit reached ($${this.progress.totalCost.toFixed(2)}).`));break;case"max_iterations":console.log(a.yellow(` \u{1F504} Goal stopped: max iterations reached (${this.progress.maxIterations}).`));break}console.log(a.dim(` Iterations: ${this.progress.iteration}`)),console.log(a.dim(` Elapsed: ${t}s`)),console.log(a.dim(` Tokens: ${this.progress.totalTokens.toLocaleString()}`)),console.log(a.dim(` Est. cost: $${this.progress.totalCost.toFixed(4)}`)),e!=="completed"&&console.log(a.dim(" Resume: mc --continue")),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}};U();var fd=y(require("node:crypto"),1);
|
|
278
|
+
`)}`));return!1}}saveCheckpoint(){try{(0,mr.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,mr.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||pd)/60}min \xB7 Max cost: $${(this.opts.maxCostUsd||md).toFixed(2)}`)),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}printIterationHeader(e,t){let o=((Date.now()-this.startTime)/1e3).toFixed(0);console.log(""),console.log(a.hex("#6B8DD6")(` \u2501\u2501\u2501 Iteration ${e}/${t} \u2501\u2501\u2501 ${o}s elapsed \u2501\u2501\u2501 ${this.progress.totalTokens.toLocaleString()} tokens \u2501\u2501\u2501`)),console.log("")}printGoalStatus(e){let t=((Date.now()-this.startTime)/1e3).toFixed(0);switch(console.log(""),console.log(a.dim(` ${"\u2500".repeat(50)}`)),e){case"completed":console.log(a.green.bold(" \u2705 Goal completed!"));break;case"cancelled":console.log(a.yellow(" \u26A0\uFE0F Goal cancelled by user."));break;case"timeout":console.log(a.yellow(" \u23F1 Goal stopped: timeout reached."));break;case"cost_limit":console.log(a.yellow(` \u{1F4B0} Goal stopped: cost limit reached ($${this.progress.totalCost.toFixed(2)}).`));break;case"max_iterations":console.log(a.yellow(` \u{1F504} Goal stopped: max iterations reached (${this.progress.maxIterations}).`));break}console.log(a.dim(` Iterations: ${this.progress.iteration}`)),console.log(a.dim(` Elapsed: ${t}s`)),console.log(a.dim(` Tokens: ${this.progress.totalTokens.toLocaleString()}`)),console.log(a.dim(` Est. cost: $${this.progress.totalCost.toFixed(4)}`)),e!=="completed"&&console.log(a.dim(" Resume: mc --continue")),console.log(a.dim(` ${"\u2500".repeat(50)}`)),console.log("")}};U();var fd=y(require("node:crypto"),1);ze();Q();var gr=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=fd.randomUUID().slice(0,8),o=z(),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
279
|
`)[0].substring(0,70);console.log(a.dim(` \u2514\u2500 ${i}`))}t.status==="failed"&&t.error&&console.log(a.red(` \u2514\u2500 ${t.error.substring(0,70)}`))}console.log(` ${"\u2500".repeat(70)}`),console.log("")}async executeSubtask(e,t,o,n,r){try{let i=["You are running as an isolated subtask. Your task:","",`${o}`,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished."].join(`
|
|
278
280
|
`);await t.run(i),n.status="completed",n.endTime=Date.now(),n.result=r;let c=((n.endTime-n.startTime)/1e3).toFixed(0);if(console.log(""),console.log(a.green(` \u2705 Subtask ${a.bold(e)} completed (${c}s, ${n.tokensUsed.toLocaleString()} tokens)`)),console.log(a.dim(` "${o}"`)),r.trim()){let u=r.trim().split(`
|
|
279
281
|
`).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 Na=y(require("node:path"),1),Vs=require("node:child_process"),hd=require("node:events");
|
|
282
|
+
`);console.log(a.dim(` ${u}`))}console.log("")}catch(i){n.status="failed",n.endTime=Date.now(),n.error=i instanceof Error?i.message:String(i),console.log(""),console.log(a.red(` \u274C Subtask ${a.bold(e)} failed: ${n.error}`)),console.log("")}finally{this.loops.delete(e)}}};var Na=y(require("node:path"),1),Vs=require("node:child_process"),hd=require("node:events");ze();var hr=require("node:child_process"),Ee=y(require("node:fs"),1),Eo=y(require("node:path"),1);var yr=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=Eo.join(this.workspace,".git","mc-merge-tmp");Ee.mkdirSync(c,{recursive:!0});let u=Eo.join(c,"base"),d=Eo.join(c,"ours"),p=Eo.join(c,"theirs");Ee.writeFileSync(u,n),Ee.writeFileSync(d,r),Ee.writeFileSync(p,i);try{(0,hr.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=Eo.join(this.workspace,e);Ee.writeFileSync(r,o.mergedContent),o=await this.resolve(e,["HEAD",t[n]])}return o}noConflict(e){let t=Eo.join(this.workspace,e);return{file:e,success:!0,hadConflicts:!1,mergedContent:Ee.existsSync(t)?Ee.readFileSync(t,"utf8"):"",conflictMarkers:[]}}getBaseBranch(){try{return(0,hr.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:this.workspace,encoding:"utf8"}).trim()}catch{return"HEAD"}}getFileAtBranch(e,t){try{return(0,hr.execSync)(`git show ${t}:${e}`,{cwd:this.workspace,encoding:"utf8"})}catch{return""}}parseConflictMarkers(e,t){let o=[],n=e.split(`
|
|
281
283
|
`),r=0;for(;r<n.length;){if(n[r].startsWith("<<<<<<<")){let i=r+1,c="",u="",d=!1;for(r++;r<n.length&&!n[r].startsWith(">>>>>>>");)n[r].startsWith("=======")?d=!0:d?u+=n[r]+`
|
|
282
284
|
`:c+=n[r]+`
|
|
283
285
|
`,r++;o.push({startLine:i,endLine:r+1,ours:c.trimEnd(),theirs:u.trimEnd(),branchName:t})}r++}return o}async autoResolveMarkers(e){let t=e.split(`
|
|
@@ -285,40 +287,40 @@ ${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
285
287
|
`:c+=t[n]+`
|
|
286
288
|
`,n++;if(n++,c.trim()===u.trim())o.push(c.trimEnd());else if(c.trim()==="")o.push(u.trimEnd());else if(u.trim()==="")o.push(c.trimEnd());else{let p=`__CONFLICT_${i.length}__`;i.push({ours:c.trimEnd(),theirs:u.trimEnd(),index:i.length}),o.push(p),r=!1}}else o.push(t[n]),n++;if(i.length>0){let c=o.join(`
|
|
287
289
|
`);for(let d of i){let p=await this.llmMerge(d.ours,d.theirs);p?c=c.replace(`__CONFLICT_${d.index}__`,p):c=c.replace(`__CONFLICT_${d.index}__`,d.ours)}let u=/__CONFLICT_\d+__/.test(c);return{content:c,resolved:!u}}return{content:o.join(`
|
|
288
|
-
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(
|
|
290
|
+
`),resolved:r}}async llmMerge(e,t){try{let{AgentLoop:o}=await Promise.resolve().then(()=>(ze(),Xo)),{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
291
|
`);return await u.run(p),d.trim()||null}catch{return null}}cleanup(e){try{Ee.rmSync(e,{recursive:!0,force:!0})}catch{}}};Q();var gd=require("node:events"),ja=y(require("node:crypto"),1);var br=class extends gd.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:ja.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.${ja.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 wr=class extends hd.EventEmitter{static{l(this,"AgentOrchestrator")}opts;resolver;activeLoops=new Map;broker;constructor(e){super(),this.opts={maxConcurrency:5,timeoutMs:6e5,...e},this.resolver=new yr(e.workspace),this.broker=new br,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
292
|
|
|
291
293
|
`+r.inputTransform(o):o&&(i+=`
|
|
292
294
|
|
|
293
295
|
--- 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=Na.join(this.opts.workspace,"..",`.mc-worktree-${e.id}`);try{return(0,Vs.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=
|
|
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,Vs.execSync)(`git checkout ${t} -- ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}cleanupWorktree(e){try{let t=Na.join(this.opts.workspace,"..",`.mc-worktree-${e.replace(/^mc-agent-/,"")}`);(0,Vs.execSync)(`git worktree remove --force ${t}`,{cwd:this.opts.workspace,stdio:"pipe"}),(0,Vs.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 Op=y(require("node:fs"),1),Mr=require("node:child_process");U();X();Ce();var _p=require("node:child_process"),
|
|
296
|
+
${o}`);let c={id:r.id,prompt:i,workspace:this.opts.workspace,parentId:"pipeline",dependencies:[],status:"pending",model:r.model,maxCostUsd:r.maxCostUsd},u=await this.runInline(c);if(t.push({...u,stageId:r.id}),o=u.output,u.status==="failed")break}return{stages:t,finalOutput:o,totalTokens:t.reduce((r,i)=>r+i.tokensUsed,0),totalCost:t.reduce((r,i)=>r+i.costUsd,0),totalDurationMs:Date.now()-n}}cancelAll(){for(let[e,t]of this.activeLoops)t.cancel(),this.activeLoops.delete(e)}async runIsolated(e){let t=`mc-agent-${e.id}-${Date.now()}`,o=Na.join(this.opts.workspace,"..",`.mc-worktree-${e.id}`);try{return(0,Vs.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=z(),r=Date.now(),i="",c=0,u=0,d=[],p=new Se({platformUrl:n.platformUrl,token:this.opts.token,model:e.model||this.opts.model,workspace:t,mode:"auto",maxTurns:30,sandboxed:!1,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeLoops.set(e.id,p);let f=e.timeoutMs||this.opts.timeoutMs||6e5,m=setTimeout(()=>p.cancel(),f);p.on("event",g=>{switch(g.type){case"streaming_chunk":i+=g.content;break;case"tool_call_start":if(["write_file","edit_file","create_file","replace_file_content"].includes(g.name)){let h=g.args.path||g.args.file_path||g.args.target_file;h&&d.push(h)}this.broker.publish(`agent.${e.id}`,{from:e.id,type:"tool_call",data:{tool:g.name}});break;case"run_complete":c+=g.summary.tokensIn+g.summary.tokensOut,u+=g.summary.costUsd||0,this.broker.publish("orchestrator",{from:e.id,type:"complete",data:{tokensUsed:c,costUsd:u,filesChanged:[...new Set(d)]}});break}});try{let g=["You are running as a parallel subagent in an orchestrated multi-agent workflow.","","Your specific task:",e.prompt,"","Complete this task autonomously. Do not ask for user input.","When done, summarize what you accomplished concisely."].join(`
|
|
297
|
+
`);return await p.run(g),{taskId:e.id,status:"complete",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,worktreeBranch:o}}catch(g){return{taskId:e.id,status:"failed",output:i,filesChanged:[...new Set(d)],tokensUsed:c,costUsd:u,durationMs:Date.now()-r,error:g instanceof Error?g.message:String(g),worktreeBranch:o}}finally{clearTimeout(m),this.activeLoops.delete(e.id)}}async cherryPickFile(e,t){try{(0,Vs.execSync)(`git checkout ${t} -- ${e}`,{cwd:this.opts.workspace,stdio:"pipe"})}catch{}}cleanupWorktree(e){try{let t=Na.join(this.opts.workspace,"..",`.mc-worktree-${e.replace(/^mc-agent-/,"")}`);(0,Vs.execSync)(`git worktree remove --force ${t}`,{cwd:this.opts.workspace,stdio:"pipe"}),(0,Vs.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 Op=y(require("node:fs"),1),Mr=require("node:child_process");U();X();Ce();var _p=require("node:child_process"),lo=y(require("node:fs"),1),Or=y(require("node:path"),1),Ep=require("node:events");en();X();var yb=1;function Dp(s,e={}){return{jsonrpc:"2.0",id:yb++,method:s,params:e}}l(Dp,"createRequest");function vp(s){return JSON.stringify(s)}l(vp,"serialize");function Sp(s){try{let e=JSON.parse(s);return e.kind||e.id!==void 0||e.method?e:null}catch{return null}}l(Sp,"parseMessage");function xp(s){return typeof s=="object"&&s!==null&&"kind"in s}l(xp,"isDaemonEvent");function Cp(s){return typeof s=="object"&&s!==null&&"id"in s&&"jsonrpc"in s}l(Cp,"isRpcResponse");var co=class extends Ep.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=Dp(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(vp(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(!lo.existsSync(this.paths.pidFile))return null;let e=lo.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 lo.unlinkSync(this.paths.pidFile),null}}catch{return null}}async spawnDaemon(){qn(Or.dirname(this.paths.pidFile)),qn(this.paths.logs);let e=Or.join(this.paths.logs,`daemon-${Date.now()}.log`),t=lo.createWriteStream(e,{flags:"a"}),o=this.opts.port;return this.daemonProcess=(0,_p.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 $p(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=Sp(e);if(t){if(Cp(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(xp(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 $p(t);try{await this.connectWebSocket(e)}catch{}}};function $p(s){return new Promise(e=>setTimeout(e,s))}l($p,"sleep");oe();va();var Be=y(require("node:fs"),1),it=y(require("node:path"),1);X();function tn(s){let e=T(),t=it.join(s,".monkeyscode","mcp.json"),o=it.join(e.config,"mcp.json"),n=Fp(o),r=Fp(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(tn,"loadMcpConfig");function Fp(s){if(!Be.existsSync(s))return[];try{let e=Be.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:bb(n),autoStart:n.autoStart??!0}))}catch{return[]}}l(Fp,"loadConfigFile");function bb(s){return s.transport?s.transport:s.url?"sse":"stdio"}l(bb,"detectTransport");function ac(s,e,t,o){let n=it.join(s,".monkeyscode","mcp.json"),r=Ap(n);r.servers[e]={command:t,args:o};let i=it.dirname(n);Be.mkdirSync(i,{recursive:!0}),Be.writeFileSync(n,JSON.stringify(r,null,2)+`
|
|
296
298
|
`)}l(ac,"addMcpServer");function Tp(s,e){let t=it.join(s,".monkeyscode","mcp.json"),o=Ap(t);return o.servers[e]?(delete o.servers[e],Be.writeFileSync(t,JSON.stringify(o,null,2)+`
|
|
297
|
-
`),!0):!1}l(Tp,"removeMcpServer");function Rp(s){let e=T();return[{path:it.join(s,".monkeyscode","mcp.json"),source:"project",exists:Be.existsSync(it.join(s,".monkeyscode","mcp.json"))},{path:it.join(e.config,"mcp.json"),source:"global",exists:Be.existsSync(it.join(e.config,"mcp.json"))}]}l(Rp,"getMcpConfigPaths");function Ap(s){if(!Be.existsSync(s))return{servers:{}};try{return JSON.parse(Be.readFileSync(s,"utf-8"))}catch{return{servers:{}}}}l(Ap,"loadConfigFileRaw");nr();async function on(s={}){let e=j(),t=W(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=Pp(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
|
|
298
|
-
`)[0]}catch{return null}}l(wb,"getVersion");Oa();ir();var cc=y(require("node:fs"),1),lc=require("node:child_process");function
|
|
299
|
-
`)}}},Ir=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(`| \`${
|
|
299
|
+
`),!0):!1}l(Tp,"removeMcpServer");function Rp(s){let e=T();return[{path:it.join(s,".monkeyscode","mcp.json"),source:"project",exists:Be.existsSync(it.join(s,".monkeyscode","mcp.json"))},{path:it.join(e.config,"mcp.json"),source:"global",exists:Be.existsSync(it.join(e.config,"mcp.json"))}]}l(Rp,"getMcpConfigPaths");function Ap(s){if(!Be.existsSync(s))return{servers:{}};try{return JSON.parse(Be.readFileSync(s,"utf-8"))}catch{return{servers:{}}}}l(Ap,"loadConfigFileRaw");nr();async function on(s={}){let e=j(),t=W(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=Pp(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 co({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(ga()?{name:"Authentication",status:"ok",message:"Logged in"}:{name:"Authentication",status:"warn",message:"Not logged in",fix:"Run: mc auth login"});let p=Pp("git");i.push(p?{name:"Git",status:"ok",message:wb("git --version")||"found"}:{name:"Git",status:"error",message:"Not found",fix:"Install git: https://git-scm.com"});let m=await new es(sr(".")).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=tn(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=$o(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 v=Op.existsSync(r.config);i.push(v?{name:"Config directory",status:"ok",message:r.config}:{name:"Config directory",status:"warn",message:`Not found: ${r.config}`,fix:"Will be created on first run"});let x=j();i.push({name:"Terminal",status:"ok",message:[x.trueColor?"24-bit color":x.color256?"256 color":x.color16?"16 color":"no color",x.unicode?"Unicode":"ASCII",x.interactive?"interactive":"non-interactive",`${x.columns}x${x.rows}`].join(" \xB7 ")});for(let 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,C=i.filter(E=>E.status==="warn").length;if(_>0?console.log(o?a.red(` ${_} error(s), ${C} warning(s)`):` ${_} error(s), ${C} warning(s)`):C>0?console.log(o?a.yellow(` All good! ${C} warning(s)`):` All good! ${C} 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,Mr.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(on,"doctorCommand");function Pp(s){try{return(0,Mr.execSync)(`which ${s} 2>/dev/null || where ${s} 2>nul`,{stdio:"pipe"}),!0}catch{return!1}}l(Pp,"checkBinary");function wb(s){try{return(0,Mr.execSync)(s,{stdio:"pipe"}).toString().trim().split(`
|
|
300
|
+
`)[0]}catch{return null}}l(wb,"getVersion");Oa();ir();var cc=y(require("node:fs"),1),lc=require("node:child_process");function Wt(s){return s.replace(/\\/g,"/")}l(Wt,"normalizePath");var ds=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:Wt(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}},uc=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:Wt(o.path)}))};return JSON.stringify(t)}formatEvent(e){return JSON.stringify({type:e.type,timestamp:e.timestamp,...e.data})}},dc=class{static{l(this,"DiffFormatter")}workspace;constructor(e){this.workspace=e}formatResult(e){try{let t=(0,lc.execSync)("git diff",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760});return t.trim()?t:(0,lc.execSync)("git diff --cached",{cwd:this.workspace,encoding:"utf8",maxBuffer:10485760})||"# No changes detected"}catch{return e.filesChanged.map(t=>`# ${t.action}: ${Wt(t.path)} (+${t.linesAdded} -${t.linesRemoved})`).join(`
|
|
301
|
+
`)}}},Ir=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(`| \`${Wt(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
302
|
${e.error}
|
|
301
303
|
\`\`\``),t.push("")),t.join(`
|
|
302
|
-
`)}},pc=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=>
|
|
304
|
+
`)}},pc=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=>Wt(i.path)).join(",")}`,`cost=${e.cost.toFixed(4)}`,`tokens=${e.tokens.total}`,`duration=${e.duration}`,`model=${e.model}`,`session-id=${e.sessionId}`];try{cc.appendFileSync(o,r.join(`
|
|
303
305
|
`)+`
|
|
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=>
|
|
306
|
+
`)}catch{}}t.push(`::set-output name=success::${e.success}`),t.push(`::set-output name=status::${e.status}`),t.push(`::set-output name=summary::${e.summary}`),t.push(`::set-output name=files-changed::${e.filesChanged.map(r=>Wt(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 Ir().formatResult(e);try{cc.appendFileSync(n,r+`
|
|
305
307
|
`)}catch{}}return!e.success&&e.error&&t.push(`::error::${e.error}`),t.join(`
|
|
306
|
-
`)}},mc=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=>
|
|
307
|
-
`)}},ps=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:
|
|
308
|
+
`)}},mc=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=>Wt(o.path)).join(",")}`),t.push(`##vso[task.setvariable variable=agentTokens]${e.tokens.total}`),t.push(`##vso[task.setvariable variable=agentDuration]${e.duration}`),e.success?t.push(`##vso[task.complete result=Succeeded;]${e.summary}`):t.push(`##vso[task.complete result=Failed;]${e.error||e.summary}`),t.push(`##vso[task.uploadsummary]MonkeysCode: ${e.summary}`),t.join(`
|
|
309
|
+
`)}},ps=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:Wt(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:Wt(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 Mp(s,e={}){switch(s){case"json":return new ds;case"jsonl":return new uc;case"diff":return new dc(e.workspace||".");case"markdown":return new Ir;case"github":return new pc;case"azure":return new mc;case"sarif":return new ps(e.findings,e.workspace);case"text":case"stream":default:return new ds}}l(Mp,"createFormatter");function Ip(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(Ip,"createEmptyResult");function im(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(im,"mapMode");async function am(s){let e=j(),t=s.prompt;!t&&!e.interactive&&(t=await jb());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=z();s.model=r.defaultModel}let n=me();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(zp(),Vp));await r({jobId:s.resume,workspace:s.workspace}),await nm(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Ec(),Xp));await r(s.prompt,s.workspace,s.model)}else s.headless?await Mb(t,s,o,n):s.background?await Ib(t,s):await nm(t,s,o,n)}l(am,"runCommand");async function nm(s,e,t,o){let n=j(),r=z(),i=new So({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new _o(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new jt,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,g=new Set,h=0,b=0,k=0,v=0,x=null,_=!1;if(e.continueSession){let P=u.loadLatest(e.workspace);if(P){d=P,v=P.turnCount;for(let B of P.stats.filesChanged)m.add(B);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,B=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 S=(()=>{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=S?` ${P("\xB7")} ${P("branch:")} ${S}${$?Y(" \u25CF"):B(" \u2713")}`:"";console.log(` ${F("Path:")} ${P(e.workspace)}${O}`);let R=e.sandbox?B("\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")} ${B("smart-approve")}`:"";console.log(` ${F("Sandbox:")} ${R}${Z}${A}`);let Xt=c.getHooks(),$s=Xt.length>0?`${Xt.length} hooks`:P("none"),qo=0;try{let{listAllSkills:We}=await Promise.resolve().then(()=>(cr(),Ta));qo=We(e.workspace).length}catch{}let di=qo>0?`${qo} skills`:P("none");console.log(` ${F("Plugins:")} ${$s} ${P("\xB7")} ${di}`);let pi=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${F("Engine:")} ${P(pi)}`)}console.log("");let C=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});C.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=rm.createInterface({input:process.stdin,output:process.stdout,terminal:!0,prompt:(()=>{let P=W(n);return n.ansi?`
|
|
308
310
|
${a.hex("#6B8DD6")(P.prompt)} `:`
|
|
309
|
-
${P.prompt} `})(),historySize:200,completer:l(P=>{if(P.startsWith("/")){let B=P.slice(1).toLowerCase(),Y=E.filter(F=>F.startsWith(B)).map(F=>`/${F}`);return[Y.length?Y:E.map(F=>`/${F}`),P]}if(P.startsWith("/context ")){let B=P.slice(9);try{let Y=V.dirname(V.resolve(e.workspace,B)),F=V.basename(B);return[M.readdirSync(Y).filter(S=>S.startsWith(F)).map(S=>`/context ${B.replace(F,"")}${S}`),P]}catch{return[[],P]}}return[[],P]},"completer")});new dr().wire(I);let K=null,fe=null,je=!1,pt=null,
|
|
310
|
-
`).length;process.stdout.write(`\x1B[${S}A\x1B[J`),console.log(
|
|
311
|
+
${P.prompt} `})(),historySize:200,completer:l(P=>{if(P.startsWith("/")){let B=P.slice(1).toLowerCase(),Y=E.filter(F=>F.startsWith(B)).map(F=>`/${F}`);return[Y.length?Y:E.map(F=>`/${F}`),P]}if(P.startsWith("/context ")){let B=P.slice(9);try{let Y=V.dirname(V.resolve(e.workspace,B)),F=V.basename(B);return[M.readdirSync(Y).filter(S=>S.startsWith(F)).map(S=>`/context ${B.replace(F,"")}${S}`),P]}catch{return[[],P]}}return[[],P]},"completer")});new dr().wire(I);let K=null,fe=null,je=!1,pt=null,wo=new gr({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(()=>(ln(),Br));t&&r.platformUrl&&(Ct=new P(r.platformUrl,t,p))}catch{}let Cs=l(async()=>{if(Ct)try{let P=await Ct.pollMessages();if(P&&P.length>0)for(let B of P)i.renderMessageCard({from:B.from||B.senderId||"unknown",content:B.content||B.message||"",timestamp:B.timestamp?new Date(B.timestamp):new Date})}catch{}},"pollAndRenderMessages"),$t=l(async P=>{d||(d=u.create(e.workspace,e.model,e.mode)),u.addMessage(d,"user",P),v++,C.update({turn:v,busy:!0,activity:"thinking..."});let B=new Se({platformUrl:r.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:im(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=B;let Y="";B.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 S=Y.split(`
|
|
312
|
+
`).length;process.stdout.write(`\x1B[${S}A\x1B[J`),console.log(zn(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
313
|
\u{1F914} ${D.question}`)),I.question(a.dim(" Answer: "),S=>{B.resolveUserInput(S)});break;case"todo_update":i.printTodoList(D.todos);break;case"run_complete":Nb(D.summary,i),h+=D.summary.tokensIn,b+=D.summary.tokensOut,k+=D.summary.tokensThinking||0,x=B.state.runId;for(let S of D.summary.filesModified)m.add(S);if(C.update({tokensIn:h,tokensOut:b,cost:qs(e.model,h,b,k),turn:v,busy:!1,activity:""}),e.maxCost&&e.maxCost>0){let S=qs(e.model,h,b,k),$=S/e.maxCost;$>=1?(console.log(""),console.log(a.red(` \u{1F6AB} Session budget exceeded ($${S.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 ($${S.toFixed(2)}/$${e.maxCost.toFixed(2)})`))}let w=B.getCheckpoints();w.size>0&&id(B.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=[];B.on("run_complete",D=>{D?.summary?.filesModified&&(F=D.summary.filesModified)});try{await B.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(()=>(sm(),om));await D(Ct,F,p)}catch{}K=null},"executePrompt");s&&await $t(s),await Cs(),I.prompt(),I.on("line",async P=>{let B=P.trim();if(_){I.close();return}if(!pt&&(B==="<<EOF"||B.endsWith("<<EOF"))){let Y=B.replace(/<<EOF$/,"").trim();pt=Y?[Y]:[],I.setPrompt(a.dim(" ... ")),I.prompt();return}if(pt!==null){if(B==="EOF"){let Y=pt.join(`
|
|
312
314
|
`);pt=null,I.setPrompt(n.emoji?`
|
|
313
315
|
\u{1F435} > `:`
|
|
314
316
|
> `),Y.trim()&&await $t(Y),I.prompt();return}pt.push(P),I.setPrompt(a.dim(" ... ")),I.prompt();return}if(B.endsWith("\\")){pt=[B.slice(0,-1)],I.setPrompt(a.dim(" ... ")),I.prompt();return}if(!B){I.prompt();return}if(B.startsWith("/")){let[Y,...F]=B.slice(1).split(" "),D=F.join(" ");switch(Y){case"exit":case"quit":case"q":c.fire("Stop",{workspace:e.workspace,data:{}}),C.stop(),I.close();return;case"clear":case"cls":console.clear();break;case"model":D?(e.model=D,i.printSuccess(`Model changed to: ${D}`),C.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=ad();if(w.length===0){i.printError("Nothing to undo \u2014 no checkpoints found.");break}let S=w[0];try{let $=cd(S.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=rr(e.model),S=w?h/1e6*w.costInputPerM:0,$=w?b/1e6*w.costOutputPerM:0,O=w?k/1e6*w.costOutputPerM:0,R=S+$+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 ($${S.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: ${v}`),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=ur(e.model),S=K?.getContextStats();if(console.log(""),console.log(" \u{1F4CA} Context Summary"),console.log(` ${"\u2500".repeat(40)}`),console.log(` Turns: ${v}`),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`),S){let $=S.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: ${S.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(),S=K.getContextStats();if(!w&&S.pct<50){console.log(a.dim(` Context is only ${S.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, ${S.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, ${S.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 on();break;case"permissions":{let w=D.split(" ")[0]?.toLowerCase()||"show",S=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(S))console.log(a.dim(" No permissions.json. Run /init to generate one."));else try{(0,Ye.execSync)(`${$} "${S}"`,{stdio:"inherit"}),i.printSuccess("Permissions saved.")}catch{i.printError(`Failed to open editor: ${$}`)}}else if(w==="reset")M.existsSync(S)?(M.unlinkSync(S),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(S))try{let $=JSON.parse(M.readFileSync(S,"utf8"));console.log(""),console.log(a.dim(` \u{1F4C4} ${V.relative(e.workspace,S)}`)),$.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
|
|
317
|
+
`).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=ur(e.model),S=K?.getContextStats();if(console.log(""),console.log(" \u{1F4CA} Context Summary"),console.log(` ${"\u2500".repeat(40)}`),console.log(` Turns: ${v}`),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`),S){let $=S.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: ${S.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(),S=K.getContextStats();if(!w&&S.pct<50){console.log(a.dim(` Context is only ${S.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, ${S.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, ${S.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 on();break;case"permissions":{let w=D.split(" ")[0]?.toLowerCase()||"show",S=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(S))console.log(a.dim(" No permissions.json. Run /init to generate one."));else try{(0,Ye.execSync)(`${$} "${S}"`,{stdio:"inherit"}),i.printSuccess("Permissions saved.")}catch{i.printError(`Failed to open editor: ${$}`)}}else if(w==="reset")M.existsSync(S)?(M.unlinkSync(S),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(S))try{let $=JSON.parse(M.readFileSync(S,"utf8"));console.log(""),console.log(a.dim(` \u{1F4C4} ${V.relative(e.workspace,S)}`)),$.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 wo.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 S of w.slice(0,10)){let $=a.hex("#6B8DD6")(S.id.substring(0,8)),O=Bb(S.lastActive);console.log(` ${$} ${S.preview.substring(0,50).padEnd(52)} ${a.dim(O)}`)}console.log("")}break}case"resume":case"continue":{let w=D.trim(),S=w?u.load(w):u.loadLatest(e.workspace);if(!S)i.printError(w?`Session "${w}" not found.`:"No sessions to resume.");else{d=S,v=S.turnCount;for(let $ of S.stats.filesChanged)m.add($);i.printSuccess(`Resumed session ${S.id.substring(0,8)} (${S.turnCount} turns, ${S.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 S=fe.getProgress();console.log(a.dim(` Goal: iteration ${S.iteration}/${S.maxIterations}, ${S.totalTokens.toLocaleString()} tokens, $${S.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 fr({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")wo.printStatus();else if(w.startsWith("cancel "))wo.cancel(w.slice(7).trim());else if(w){let S=w.replace(/^["']|["']$/g,"");await wo.spawn(S)}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 S=w.match(/"([^"]+)"/g)?.map(R=>R.replace(/"/g,""))||[w];if(S.length<1){i.printError("Provide at least one task in quotes.");break}console.log(a.cyan(` \u26A1 Delegating ${S.length} task(s) to parallel agents...`));for(let R=0;R<S.length;R++)console.log(a.dim(` ${R+1}. "${S[R]}"`));console.log("");let $=new wr({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=S.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",S="git diff";D==="staged"?(S="git diff --cached",w="staged changes"):D&&(S=`git diff -- ${D}`,w=`changes in ${D}`);try{let $=(0,Ye.execSync)(S,{cwd:e.workspace,encoding:"utf8"});$.trim()?(console.log(a.bold(`
|
|
316
318
|
\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
319
|
|
|
318
320
|
\`\`\`diff
|
|
319
321
|
${$}
|
|
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"),S=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(S)){let A=["# Project Conventions",""],
|
|
321
|
-
`),"utf8"),Z.push("rules.md")}if(!M.existsSync($)){let A="",
|
|
322
|
+
\`\`\``)):console.log(a.dim(" No changes to review."))}catch{console.log(a.dim(" No git changes found to review."))}break}case"init":{let w=V.join(e.workspace,".monkeyscode"),S=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(S)){let A=["# Project Conventions",""],Xt=V.join(e.workspace,"package.json"),$s=V.join(e.workspace,"Cargo.toml"),qo=V.join(e.workspace,"pyproject.toml"),di=V.join(e.workspace,"tsconfig.json"),pi=V.join(e.workspace,"go.mod");if(M.existsSync(Xt))try{let We=JSON.parse(M.readFileSync(Xt,"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(di)&&(A.push("## TypeScript"),A.push("- Use strict TypeScript with explicit types"),A.push("- Prefer `interface` over `type` for object shapes"),A.push("")),M.existsSync($s)&&(A.push("## Language: Rust"),A.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),A.push("")),M.existsSync(qo)&&(A.push("## Language: Python"),A.push("- Follow PEP 8 conventions"),A.push("")),M.existsSync(pi)&&(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(S,A.join(`
|
|
323
|
+
`),"utf8"),Z.push("rules.md")}if(!M.existsSync($)){let A="",Xt=V.join(e.workspace,"package.json");if(M.existsSync(Xt))try{JSON.parse(M.readFileSync(Xt,"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 $s={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($s,null,2)+`
|
|
322
324
|
`,"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
325
|
`),"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
326
|
`),"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"),S=D.split(" ")[0]?.toLowerCase(),$=D.slice(S?.length||0).trim();if(S==="add"&&$){let O=$.replace(/^["']|["']$/g,"");M.mkdirSync(V.dirname(w),{recursive:!0});let R=M.existsSync(w)?M.readFileSync(w,"utf8"):`# Project Conventions
|
|
@@ -333,8 +335,8 @@ ${$}
|
|
|
333
335
|
\u{1F435} > `:`
|
|
334
336
|
> `));break}case"help":case"h":case"?":Lb();break;case"logout":da(),i.printSuccess("Logged out."),process.exit(0);break;default:i.printError(`Unknown command: /${Y}. Type /help for available commands.`)}I.prompt();return}await $t(B),await Cs(),I.prompt()});let An=l(()=>{let P=Date.now()-f,B=Math.floor(P/6e4),Y=Math.floor(P%6e4/1e3),F=B>0?`${B}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: ${v}`)),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:{}}),An(),process.exit(0)}),I.on("SIGINT",()=>{K?(console.log(`
|
|
335
337
|
Cancelling current run...`),K.cancel()):(c.fire("Stop",{workspace:e.workspace,data:{}}),I.close())}),await new Promise(P=>{I.on("close",P)})}l(nm,"runInteractive");async function Mb(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=
|
|
337
|
-
`);let
|
|
338
|
+
`),process.exit(4)),t||(process.stderr.write("Error: Not authenticated. Run `mc auth login` or set MONKEYSCODE_API_KEY.\n"),process.exit(3));let m=z(),g=Date.now(),h=`headless-${Date.now().toString(36)}`,b="",k=!1,v=!1,x=e.output,_=Mp(x,{workspace:e.workspace}),C=Ip(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
|
|
339
|
+
`);let wo=new _o(e.workspace,{enabled:!0,timeoutMs:1e4});await wo.fire("HeadlessStart",{workspace:e.workspace,data:{prompt:s,model:e.model}});let Ct=e.timeout||3e5,Cs=setTimeout(()=>{v=!0,process.stderr.write(`
|
|
338
340
|
[headless] Timeout after ${Ct}ms. Stopping gracefully.
|
|
339
341
|
`)},Ct),$t=l(()=>{k=!0,process.stderr.write(`
|
|
340
342
|
[headless] SIGINT received. Stopping.
|
|
@@ -352,13 +354,13 @@ ${$}
|
|
|
352
354
|
`)[0]?.substring(0,200)||"Task completed."),C.filesChanged=I,C.toolCalls=E,C.tokens={input:K,output:fe,thinking:je,total:K+fe+je},C.cost=qs(e.model,K,fe,je),C.duration=S,C.success&&P.size>0){let $=!0;for(let[O,R]of P)try{let Z=M.readFileSync(V.join(e.workspace,O));if(An.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
355
|
`),C.summary="No changes needed \u2014 edits already applied.")}}catch(F){clearTimeout(Cs);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,C.status="failed",C.error=D,C.summary=`Error: ${D.substring(0,200)}`,C.duration=Date.now()-g,C.tokens={input:K,output:fe,thinking:je,total:K+fe+je},C.cost=qs(e.model,K,fe,je),C.filesChanged=I,C.toolCalls=E}if(x==="text"||x==="stream")x==="text"&&process.stdout.write(b+`
|
|
354
356
|
`);else{let F=_.formatResult(C);process.stdout.write(F+`
|
|
355
|
-
`)}await bo.fire("HeadlessStop",{workspace:e.workspace,data:{success:C.success,exitCode:Y,duration:C.duration,filesChanged:I.length}}),process.removeListener("SIGINT",$t),process.exit(Y)}l(Mb,"runHeadless");async function Ib(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(sn(),kc));await t({prompt:s,workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:e.autoBranch??!0,autoCommit:e.autoCommit??!0,autoPR:e.autoPR??!1,maxCost:e.maxCost,timeout:e.timeout})}l(Ib,"runBackground");async function jb(){return new Promise(s=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{s(e.trim())})})}l(jb,"readStdin");function Nb(s,e){console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Turns: ${s.turns} \xB7 Tokens: ${s.tokensIn} in / ${s.tokensOut} out`)),s.tokensCached>0&&console.log(a.dim(` Cached: ${s.tokensCached}`)),s.filesModified.length>0&&console.log(a.dim(` Files modified: ${s.filesModified.length}`));let t=(s.duration/1e3).toFixed(1);console.log(a.dim(` Duration: ${t}s`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(Nb,"printRunSummary");function Lb(){let s=j(),e=W(s),t=a.hex("#6B8DD6"),o=a.dim,n=a.bold,r=l((i,c)=>{let u=i.padEnd(30);return` ${t(u)} ${o(c)}`},"cmd");if(s.unicode){let i={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",tr2:"\u251C",tl2:"\u2524"},c=Math.min(62,s.columns-4),u=` ${e.tool} MonkeysCode Commands `,d=Math.max(0,c-u.length-2);console.log(""),console.log(t(` ${i.tl}${i.h}${u}${i.h.repeat(d)}${i.tr}`)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.message} Chat`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/model <name>","Switch model")+t(i.v)),console.log(t(` ${i.v}`)+r("/mode <plan|fast>","Switch mode")+t(i.v)),console.log(t(` ${i.v}`)+r("/compact","Compact context")+t(i.v)),console.log(t(` ${i.v}`)+r('/search "query"',"Web search")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.folder} Project`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/init","Initialize .monkeyscode/")+t(i.v)),console.log(t(` ${i.v}`)+r('/memory add "rule"',"Add convention")+t(i.v)),console.log(t(` ${i.v}`)+r("/permissions","Show/edit permissions")+t(i.v)),console.log(t(` ${i.v}`)+r("/skill","List/create skills")+t(i.v)),console.log(t(` ${i.v}`)+r("/hooks","List/create hooks")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.info} Stats`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/cost","Token usage & cost")+t(i.v)),console.log(t(` ${i.v}`)+r("/context [file]","Context window usage")+t(i.v)),console.log(t(` ${i.v}`)+r("/diff","Show uncommitted changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/files","List modified files")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.rocket} Actions`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/commit [msg]","Auto-commit changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/undo","Undo last file changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/review","Run code review")+t(i.v)),console.log(t(` ${i.v}`)+r('/goal "target"',"Autonomous goal loop")+t(i.v)),console.log(t(` ${i.v}`)+r('/fork ["task"]',"Fork to background")+t(i.v)),console.log(t(` ${i.v}`)+r('/delegate "t1" "t2"',"Parallel agents")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.lock} Session`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/sessions","List saved sessions")+t(i.v)),console.log(t(` ${i.v}`)+r("/resume [id]","Resume a session")+t(i.v)),console.log(t(` ${i.v}`)+r("/exit","Exit the REPL")+t(i.v)),console.log(t(` ${i.v}`)+r("/doctor","System health check")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+o(" Press / + Tab for autocomplete").padEnd(c+12)+t(i.v)),console.log(t(` ${i.bl}${i.h.repeat(c)}${i.br}`)),console.log("")}else console.log(""),console.log(n(" Slash Commands")),console.log(o(" Tab to auto-complete")),console.log(""),console.log(t(" Chat")),console.log(r("/model <name>","Switch model")),console.log(r("/mode <plan|fast>","Switch mode")),console.log(r("/compact","Compact context")),console.log(""),console.log(t(" Project")),console.log(r("/init","Initialize .monkeyscode/")),console.log(r('/memory add "rule"',"Add convention")),console.log(r("/permissions","Show/edit permissions")),console.log(r("/skill","List/create skills")),console.log(r("/hooks","List/create hooks")),console.log(""),console.log(t(" Stats")),console.log(r("/cost","Token usage & cost")),console.log(r("/context [file]","Context window usage")),console.log(r("/diff","Show uncommitted changes")),console.log(r("/files","List modified files")),console.log(""),console.log(t(" Actions")),console.log(r("/commit [msg]","Auto-commit changes")),console.log(r("/undo","Undo last file changes")),console.log(r("/review","Run code review")),console.log(r('/goal "target"',"Autonomous goal loop")),console.log(r('/fork ["task"]',"Fork to background")),console.log(""),console.log(t(" Session")),console.log(r("/sessions","List saved sessions")),console.log(r("/resume [id]","Resume a session")),console.log(r("/exit","Exit the REPL")),console.log(r("/doctor","System health check")),console.log("")}l(Lb,"printSlashHelp");function Bb(s){let e=Date.now()-s,t=Math.floor(e/6e4),o=Math.floor(e/36e5),n=Math.floor(e/864e5);return t<1?"just now":t<60?`${t}m ago`:o<24?`${o}h ago`:`${n}d ago`}l(Bb,"formatAge");oe();var Ur=y(require("node:readline"),1);U();Ce();var Rc=class{static{l(this,"AgentsDashboard")}daemon;caps;icons;box;agents=[];selectedIndex=0;running=!1;refreshInterval=null;constructor(e){this.daemon=e,this.caps=j(),this.icons=W(this.caps),this.box=Ve(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(Ur.emitKeypressEvents(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume()),process.stdin.on("keypress",(e,t)=>{this.running&&this.handleKeypress(e,t)}),this.daemon.on("event",()=>{this.fetchAgents().then(()=>this.render())}),this.refreshInterval=setInterval(async()=>{await this.fetchAgents(),this.render()},5e3),this.render(),await new Promise(e=>{let t=setInterval(()=>{this.running||(clearInterval(t),e())},100)})}async list(){await this.fetchAgents();let e=this.caps.ansi;if(this.agents.length===0){console.log(" No active agents.");return}let t=`${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.bold(` ${t}`):` ${t}`),console.log(` ${"\u2500".repeat(Math.min(this.caps.columns-4,100))}`);for(let o of this.agents){let n=this.formatAgentLine(o,!1);console.log(` ${n}`)}}async fetchAgents(){try{this.agents=await this.daemon.call("agents.list",{})}catch{this.agents=[]}}render(){let e=this.caps.ansi,t=Math.min(this.caps.columns,120);console.clear();let o=`${this.icons.rocket} MonkeysCode Agents Dashboard`;if(console.log(e?a.bold(o):o),console.log(e?a.dim(` ${this.agents.length} agent(s) active`):` ${this.agents.length} agent(s) active`),console.log(`${this.box.separator.repeat(t)}`),this.agents.length===0)console.log(""),console.log(" No active agents."),console.log(""),console.log(e?a.dim(' Start one with: mc "your prompt"'):' Start one with: mc "your prompt"'),console.log("");else{let r=` ${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.dim(r):r),console.log(` ${"\u2500".repeat(t-4)}`);for(let i=0;i<this.agents.length;i++){let c=i===this.selectedIndex,u=this.formatAgentLine(this.agents[i],c);console.log(c&&e?a.bgHex("#1a1a2e").white(`\u25B6 ${u}`):` ${u}`)}}console.log(""),console.log(`${this.box.separator.repeat(t)}`);let n=e?` ${a.cyan("[j/k]")} Nav ${a.cyan("[Enter]")} Focus ${a.cyan("[m]")} Message ${a.cyan("[c]")} Cancel ${a.cyan("[l]")} Logs ${a.cyan("[r]")} Retry ${a.cyan("[q]")} Quit`:" [j/k] Nav [Enter] Focus [m] Message [c] Cancel [l] Logs [r] Retry [q] Quit";console.log(n)}formatAgentLine(e,t){let o=this.caps.ansi,n=e.id.slice(0,12).padEnd(14),r=e.type.padEnd(14),i=this.formatStatus(e.status).padEnd(12),c=`"${e.task.slice(0,33)}"`.padEnd(35),u=this.formatDuration(e.duration).padEnd(10),d=this.formatTokens(e.tokens),p=`${n} ${r} ${i} ${c} ${u} ${d}`;if(!o)return p;let f={active:a.green,running:a.green,idle:a.yellow,queued:a.blue,done:a.dim,failed:a.red,cancelled:a.dim}[e.status]||a.white;return`${a.white(n)} ${a.dim(r)} ${f(i)} ${a.white(c)} ${a.dim(u)} ${a.dim(d)}`}formatStatus(e){return{active:this.caps.emoji?"\u{1F504} Active":"[ACTIVE]",running:this.caps.emoji?"\u{1F504} Running":"[RUNNING]",idle:this.caps.emoji?"\u23F8\uFE0F Idle":"[IDLE]",queued:this.caps.emoji?"\u23F3 Queued":"[QUEUED]",done:this.caps.emoji?"\u2705 Done":"[DONE]",failed:this.caps.emoji?"\u274C Failed":"[FAILED]",cancelled:this.caps.emoji?"\u{1F6AB} Cancel":"[CANCEL]"}[e]||e}formatDuration(e){if(e<=0)return"\u2014";let t=Math.floor(e/1e3),o=Math.floor(t/60),n=Math.floor(o/60);return n>0?`${n}h ${o%60}m`:o>0?`${o}m ${t%60}s`:`${t}s`}formatTokens(e){return e<=0?"\u2014":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}handleKeypress(e,t){if(t){if(t.name==="q"||t.ctrl&&t.name==="c"){this.stop();return}if(t.name==="j"||t.name==="down"){this.selectedIndex=Math.min(this.selectedIndex+1,this.agents.length-1),this.render();return}if(t.name==="k"||t.name==="up"){this.selectedIndex=Math.max(this.selectedIndex-1,0),this.render();return}if(t.name==="return"){this.handleAction("focus");return}if(t.name==="m"){this.handleAction("message");return}if(t.name==="c"){this.handleAction("cancel");return}if(t.name==="l"){this.handleAction("logs");return}if(t.name==="r"){this.handleAction("retry");return}}}async handleAction(e){let t=this.agents[this.selectedIndex];if(t)switch(e){case"focus":console.log(`
|
|
357
|
+
`)}await wo.fire("HeadlessStop",{workspace:e.workspace,data:{success:C.success,exitCode:Y,duration:C.duration,filesChanged:I.length}}),process.removeListener("SIGINT",$t),process.exit(Y)}l(Mb,"runHeadless");async function Ib(s,e){s||(console.error("Error: No prompt provided for background job."),process.exit(1));let{submitBackgroundJob:t}=await Promise.resolve().then(()=>(sn(),kc));await t({prompt:s,workspace:e.workspace,model:e.model,mode:e.mode,autoBranch:e.autoBranch??!0,autoCommit:e.autoCommit??!0,autoPR:e.autoPR??!1,maxCost:e.maxCost,timeout:e.timeout})}l(Ib,"runBackground");async function jb(){return new Promise(s=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",t=>{e+=t}),process.stdin.on("end",()=>{s(e.trim())})})}l(jb,"readStdin");function Nb(s,e){console.log(""),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(` Turns: ${s.turns} \xB7 Tokens: ${s.tokensIn} in / ${s.tokensOut} out`)),s.tokensCached>0&&console.log(a.dim(` Cached: ${s.tokensCached}`)),s.filesModified.length>0&&console.log(a.dim(` Files modified: ${s.filesModified.length}`));let t=(s.duration/1e3).toFixed(1);console.log(a.dim(` Duration: ${t}s`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(Nb,"printRunSummary");function Lb(){let s=j(),e=W(s),t=a.hex("#6B8DD6"),o=a.dim,n=a.bold,r=l((i,c)=>{let u=i.padEnd(30);return` ${t(u)} ${o(c)}`},"cmd");if(s.unicode){let i={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",h:"\u2500",v:"\u2502",tr2:"\u251C",tl2:"\u2524"},c=Math.min(62,s.columns-4),u=` ${e.tool} MonkeysCode Commands `,d=Math.max(0,c-u.length-2);console.log(""),console.log(t(` ${i.tl}${i.h}${u}${i.h.repeat(d)}${i.tr}`)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.message} Chat`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/model <name>","Switch model")+t(i.v)),console.log(t(` ${i.v}`)+r("/mode <plan|fast>","Switch mode")+t(i.v)),console.log(t(` ${i.v}`)+r("/compact","Compact context")+t(i.v)),console.log(t(` ${i.v}`)+r('/search "query"',"Web search")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.folder} Project`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/init","Initialize .monkeyscode/")+t(i.v)),console.log(t(` ${i.v}`)+r('/memory add "rule"',"Add convention")+t(i.v)),console.log(t(` ${i.v}`)+r("/permissions","Show/edit permissions")+t(i.v)),console.log(t(` ${i.v}`)+r("/skill","List/create skills")+t(i.v)),console.log(t(` ${i.v}`)+r("/hooks","List/create hooks")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.info} Stats`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/cost","Token usage & cost")+t(i.v)),console.log(t(` ${i.v}`)+r("/context [file]","Context window usage")+t(i.v)),console.log(t(` ${i.v}`)+r("/diff","Show uncommitted changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/files","List modified files")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.rocket} Actions`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/commit [msg]","Auto-commit changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/undo","Undo last file changes")+t(i.v)),console.log(t(` ${i.v}`)+r("/review","Run code review")+t(i.v)),console.log(t(` ${i.v}`)+r('/goal "target"',"Autonomous goal loop")+t(i.v)),console.log(t(` ${i.v}`)+r('/fork ["task"]',"Fork to background")+t(i.v)),console.log(t(` ${i.v}`)+r('/delegate "t1" "t2"',"Parallel agents")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+` ${n(`${e.lock} Session`)}`.padEnd(c+12)+t(i.v)),console.log(t(` ${i.v}`)+r("/sessions","List saved sessions")+t(i.v)),console.log(t(` ${i.v}`)+r("/resume [id]","Resume a session")+t(i.v)),console.log(t(` ${i.v}`)+r("/exit","Exit the REPL")+t(i.v)),console.log(t(` ${i.v}`)+r("/doctor","System health check")+t(i.v)),console.log(t(` ${i.v}${" ".repeat(c)}${i.v}`)),console.log(t(` ${i.v}`)+o(" Press / + Tab for autocomplete").padEnd(c+12)+t(i.v)),console.log(t(` ${i.bl}${i.h.repeat(c)}${i.br}`)),console.log("")}else console.log(""),console.log(n(" Slash Commands")),console.log(o(" Tab to auto-complete")),console.log(""),console.log(t(" Chat")),console.log(r("/model <name>","Switch model")),console.log(r("/mode <plan|fast>","Switch mode")),console.log(r("/compact","Compact context")),console.log(""),console.log(t(" Project")),console.log(r("/init","Initialize .monkeyscode/")),console.log(r('/memory add "rule"',"Add convention")),console.log(r("/permissions","Show/edit permissions")),console.log(r("/skill","List/create skills")),console.log(r("/hooks","List/create hooks")),console.log(""),console.log(t(" Stats")),console.log(r("/cost","Token usage & cost")),console.log(r("/context [file]","Context window usage")),console.log(r("/diff","Show uncommitted changes")),console.log(r("/files","List modified files")),console.log(""),console.log(t(" Actions")),console.log(r("/commit [msg]","Auto-commit changes")),console.log(r("/undo","Undo last file changes")),console.log(r("/review","Run code review")),console.log(r('/goal "target"',"Autonomous goal loop")),console.log(r('/fork ["task"]',"Fork to background")),console.log(""),console.log(t(" Session")),console.log(r("/sessions","List saved sessions")),console.log(r("/resume [id]","Resume a session")),console.log(r("/exit","Exit the REPL")),console.log(r("/doctor","System health check")),console.log("")}l(Lb,"printSlashHelp");function Bb(s){let e=Date.now()-s,t=Math.floor(e/6e4),o=Math.floor(e/36e5),n=Math.floor(e/864e5);return t<1?"just now":t<60?`${t}m ago`:o<24?`${o}h ago`:`${n}d ago`}l(Bb,"formatAge");oe();var Ur=y(require("node:readline"),1);U();Ce();var Rc=class{static{l(this,"AgentsDashboard")}daemon;caps;icons;box;agents=[];selectedIndex=0;running=!1;refreshInterval=null;constructor(e){this.daemon=e,this.caps=j(),this.icons=W(this.caps),this.box=Ve(this.caps)}async start(){this.running=!0,await this.fetchAgents(),process.stdin.isTTY&&(Ur.emitKeypressEvents(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume()),process.stdin.on("keypress",(e,t)=>{this.running&&this.handleKeypress(e,t)}),this.daemon.on("event",()=>{this.fetchAgents().then(()=>this.render())}),this.refreshInterval=setInterval(async()=>{await this.fetchAgents(),this.render()},5e3),this.render(),await new Promise(e=>{let t=setInterval(()=>{this.running||(clearInterval(t),e())},100)})}async list(){await this.fetchAgents();let e=this.caps.ansi;if(this.agents.length===0){console.log(" No active agents.");return}let t=`${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.bold(` ${t}`):` ${t}`),console.log(` ${"\u2500".repeat(Math.min(this.caps.columns-4,100))}`);for(let o of this.agents){let n=this.formatAgentLine(o,!1);console.log(` ${n}`)}}async fetchAgents(){try{this.agents=await this.daemon.call("agents.list",{})}catch{this.agents=[]}}render(){let e=this.caps.ansi,t=Math.min(this.caps.columns,120);console.clear();let o=`${this.icons.rocket} MonkeysCode Agents Dashboard`;if(console.log(e?a.bold(o):o),console.log(e?a.dim(` ${this.agents.length} agent(s) active`):` ${this.agents.length} agent(s) active`),console.log(`${this.box.separator.repeat(t)}`),this.agents.length===0)console.log(""),console.log(" No active agents."),console.log(""),console.log(e?a.dim(' Start one with: mc "your prompt"'):' Start one with: mc "your prompt"'),console.log("");else{let r=` ${"ID".padEnd(14)} ${"Type".padEnd(14)} ${"Status".padEnd(12)} ${"Task".padEnd(35)} ${"Duration".padEnd(10)} Tokens`;console.log(e?a.dim(r):r),console.log(` ${"\u2500".repeat(t-4)}`);for(let i=0;i<this.agents.length;i++){let c=i===this.selectedIndex,u=this.formatAgentLine(this.agents[i],c);console.log(c&&e?a.bgHex("#1a1a2e").white(`\u25B6 ${u}`):` ${u}`)}}console.log(""),console.log(`${this.box.separator.repeat(t)}`);let n=e?` ${a.cyan("[j/k]")} Nav ${a.cyan("[Enter]")} Focus ${a.cyan("[m]")} Message ${a.cyan("[c]")} Cancel ${a.cyan("[l]")} Logs ${a.cyan("[r]")} Retry ${a.cyan("[q]")} Quit`:" [j/k] Nav [Enter] Focus [m] Message [c] Cancel [l] Logs [r] Retry [q] Quit";console.log(n)}formatAgentLine(e,t){let o=this.caps.ansi,n=e.id.slice(0,12).padEnd(14),r=e.type.padEnd(14),i=this.formatStatus(e.status).padEnd(12),c=`"${e.task.slice(0,33)}"`.padEnd(35),u=this.formatDuration(e.duration).padEnd(10),d=this.formatTokens(e.tokens),p=`${n} ${r} ${i} ${c} ${u} ${d}`;if(!o)return p;let f={active:a.green,running:a.green,idle:a.yellow,queued:a.blue,done:a.dim,failed:a.red,cancelled:a.dim}[e.status]||a.white;return`${a.white(n)} ${a.dim(r)} ${f(i)} ${a.white(c)} ${a.dim(u)} ${a.dim(d)}`}formatStatus(e){return{active:this.caps.emoji?"\u{1F504} Active":"[ACTIVE]",running:this.caps.emoji?"\u{1F504} Running":"[RUNNING]",idle:this.caps.emoji?"\u23F8\uFE0F Idle":"[IDLE]",queued:this.caps.emoji?"\u23F3 Queued":"[QUEUED]",done:this.caps.emoji?"\u2705 Done":"[DONE]",failed:this.caps.emoji?"\u274C Failed":"[FAILED]",cancelled:this.caps.emoji?"\u{1F6AB} Cancel":"[CANCEL]"}[e]||e}formatDuration(e){if(e<=0)return"\u2014";let t=Math.floor(e/1e3),o=Math.floor(t/60),n=Math.floor(o/60);return n>0?`${n}h ${o%60}m`:o>0?`${o}m ${t%60}s`:`${t}s`}formatTokens(e){return e<=0?"\u2014":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e)}handleKeypress(e,t){if(t){if(t.name==="q"||t.ctrl&&t.name==="c"){this.stop();return}if(t.name==="j"||t.name==="down"){this.selectedIndex=Math.min(this.selectedIndex+1,this.agents.length-1),this.render();return}if(t.name==="k"||t.name==="up"){this.selectedIndex=Math.max(this.selectedIndex-1,0),this.render();return}if(t.name==="return"){this.handleAction("focus");return}if(t.name==="m"){this.handleAction("message");return}if(t.name==="c"){this.handleAction("cancel");return}if(t.name==="l"){this.handleAction("logs");return}if(t.name==="r"){this.handleAction("retry");return}}}async handleAction(e){let t=this.agents[this.selectedIndex];if(t)switch(e){case"focus":console.log(`
|
|
356
358
|
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=Ur.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 Ac(s=!0){let e=new
|
|
359
|
+
`);try{await this.daemon.call("agents.focus",{id:t.id})}catch{console.log(" Cannot focus on this agent.")}break;case"message":if(!process.stdin.isTTY)break;process.stdin.setRawMode(!1);let o=Ur.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 Ac(s=!0){let e=new co({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 Rc(e);s&&process.stdin.isTTY?await t.start():await t.list(),e.disconnect()}l(Ac,"agentsCommand");var Gt=[{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"}],un=[{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 cm(s){switch(s){case"bash":return Ub();case"zsh":return Wb();case"fish":return Hb();case"pwsh":return Gb();default:throw new Error(`Unsupported shell: ${s}. Supported: bash, zsh, fish, pwsh`)}}l(cm,"generateCompletions");function lm(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
360
|
`);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
361
|
`);case"fish":return["monkeyscode completions fish > ~/.config/fish/completions/monkeyscode.fish"].join(`
|
|
360
362
|
`);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(lm,"getCompletionInstallInstructions");function Ub(){let s=
|
|
363
|
+
`)}}l(lm,"getCompletionInstallInstructions");function Ub(){let s=Gt.map(n=>n.name).join(" "),e=un.map(n=>n.long).join(" "),t=un.filter(n=>n.short).map(n=>n.short).join(" "),o=Gt.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
364
|
`);return`#!/bin/bash
|
|
363
365
|
# monkeyscode bash completion \u2014 generated by monkeyscode completions bash
|
|
364
366
|
# Install: eval "$(monkeyscode completions bash)"
|
|
@@ -385,9 +387,9 @@ ${o}
|
|
|
385
387
|
complete -F _monkeyscode_completions monkeyscode
|
|
386
388
|
complete -F _monkeyscode_completions mc
|
|
387
389
|
complete -F _monkeyscode_completions mcode
|
|
388
|
-
`}l(Ub,"generateBashCompletions");function Wb(){let s=
|
|
390
|
+
`}l(Ub,"generateBashCompletions");function Wb(){let s=Gt.map(o=>`'${o.name}:${o.description.replace(/'/g,"''")}'`).join(`
|
|
389
391
|
`),e=un.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=
|
|
392
|
+
`),t=Gt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>`'${r.name}:${r.description.replace(/'/g,"''")}'`).join(`
|
|
391
393
|
`);return`
|
|
392
394
|
__monkeyscode_${o.name}_commands() {
|
|
393
395
|
local commands
|
|
@@ -417,7 +419,7 @@ _monkeyscode() {
|
|
|
417
419
|
;;
|
|
418
420
|
args)
|
|
419
421
|
case "\${words[1]}" in
|
|
420
|
-
${
|
|
422
|
+
${Gt.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_${o.name}_commands ;;`).join(`
|
|
421
423
|
`)}
|
|
422
424
|
esac
|
|
423
425
|
;;
|
|
@@ -426,11 +428,11 @@ ${Ht.filter(o=>o.subcommands).map(o=>` ${o.name}) __monkeyscode_$
|
|
|
426
428
|
${t}
|
|
427
429
|
|
|
428
430
|
compdef _monkeyscode monkeyscode mc mcode
|
|
429
|
-
`}l(Wb,"generateZshCompletions");function Hb(){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
|
|
431
|
+
`}l(Wb,"generateZshCompletions");function Hb(){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 Gt)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 Gt)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 un){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
432
|
`)+`
|
|
431
|
-
`}l(Hb,"generateFishCompletions");function Gb(){let s=
|
|
433
|
+
`}l(Hb,"generateFishCompletions");function Gb(){let s=Gt.map(o=>` [CompletionResult]::new('${o.name}', '${o.name}', [CompletionResultType]::ParameterValue, '${o.description}')`).join(`
|
|
432
434
|
`),e=un.map(o=>` [CompletionResult]::new('${o.long}', '${o.long}', [CompletionResultType]::ParameterName, '${o.description}')`).join(`
|
|
433
|
-
`),t=
|
|
435
|
+
`),t=Gt.filter(o=>o.subcommands).map(o=>{let n=o.subcommands.map(r=>` [CompletionResult]::new('${r.name}', '${r.name}', [CompletionResultType]::ParameterValue, '${r.description}')`).join(`
|
|
434
436
|
`);return` '${o.name}' {
|
|
435
437
|
${n}
|
|
436
438
|
}`}).join(`
|
|
@@ -456,7 +458,7 @@ ${t}
|
|
|
456
458
|
}
|
|
457
459
|
}
|
|
458
460
|
}
|
|
459
|
-
`}l(Gb,"generatePowerShellCompletions");U();nr();function Pc(s){let e
|
|
461
|
+
`}l(Gb,"generatePowerShellCompletions");U();nr();function Pc(s){let e=$o(s),t=qu(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(Pc,"hooksListCommand");U();var um=require("node:events"),dm=require("node:child_process");var Wr=class extends um.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,dm.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
462
|
`);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
463
|
`)||"(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
464
|
`):""}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+`
|
|
@@ -471,13 +473,13 @@ ${t}
|
|
|
471
473
|
`));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
474
|
\u{1F50C} MCP Server Registry
|
|
473
475
|
`));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(hm,"mcpBrowseCommand");X();var Xe=y(require("node:fs"),1),fn=y(require("node:path"),1);X();U();var mn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var ym=["plan","fast","thinking"],bm=["dark","light","auto"],wm=["text","json","stream"],km={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>ym.includes(s)?null:`must be one of: ${ym.join(", ")}`,"defaultMode"),theme:l(s=>bm.includes(s)?null:`must be one of: ${bm.join(", ")}`,"theme"),outputFormat:l(s=>wm.includes(s)?null:`must be one of: ${wm.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Mc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:mn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(mn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=km[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Xe.mkdirSync(fn.dirname(r),{recursive:!0}),Xe.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Xe.existsSync(o)&&(n=JSON.parse(Xe.readFileSync(o,"utf8")))}catch{}delete n[e],Xe.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...mn};for(let t of Object.keys(mn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=T();return fn.join(e.config,"config.json")}getProjectConfigPath(){return fn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Xe.existsSync(e)){let o=JSON.parse(Xe.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=km[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(mn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Xe.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Dm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Dm,"printConfigList");var Oc=null;function Oo(s){return(!Oc||s)&&(Oc=new Mc(s)),Oc}l(Oo,"getConfigSystem");ir();U();Ce();oe();var qb=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function vm(){let s=j(),e=W(s),t=s.ansi,o=me();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Ae();if(d){let p=await fetch(`${qb}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Ic(n.tokensIn),u=Ic(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Ic(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(vm,"usageCommand");function Ic(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Ic,"formatTokenCount");var lt=y(require("node:fs"),1),Tm=y(require("node:path"),1),hs=require("node:child_process");U();var gs=y(require("node:fs"),1),Hr=y(require("node:path"),1);X();var Vb="https://monkeyscode.com/api/latest-version",Jb="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",zb=4*60*60*1e3;function Cm(){let s=T();return Hr.join(s.config,"update-check")}l(Cm,"getCachePath");function Kb(){try{let s=gs.readFileSync(Cm(),"utf8");return JSON.parse(s)}catch{return null}}l(Kb,"readCache");function jc(s){try{let e=Cm();gs.mkdirSync(Hr.dirname(e),{recursive:!0}),gs.writeFileSync(e,JSON.stringify(s))}catch{}}l(jc,"writeCache");function Sm(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Sm,"isNewerVersion");function Yb(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(Yb,"getAssetKey");async function Gr(s,e=!1){if(!e){let t=Kb();if(t&&Date.now()-t.lastCheck<zb)return t.latestVersion&&Sm(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await xm(Vb);if(t||(t=await xm(Jb)),!t)return jc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=Yb(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return jc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Sm(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return jc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Gr,"checkForUpdate");async function xm(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(xm,"fetchManifest");function $m(s){Gr(s).then(e=>{e&&(globalThis.__mcUpdateAvailable=e)}).catch(()=>{})}l($m,"checkForUpdateBackground");function _m(){let s=globalThis.__mcUpdateAvailable;if(!s)return;let e=globalThis.__mcChalk,t=`\u2139\uFE0F Update available: v${s.currentVersion} \u2192 v${s.version}. Run "mc update" to upgrade.`;console.error(e?e.dim(t):t)}l(_m,"printUpdateNotice");function Nc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Nc,"detectInstallMethod");async function Rm(s){let t=(await Promise.resolve().then(()=>(Fm(),Em)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.1";if(s.rollback){await aw(t);return}if(s.check){await Zb(t);return}await ew(t,s.version)}l(Rm,"updateCommand");async function Zb(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Gr(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(Zb,"checkOnly");async function ew(s,e){let t=Nc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await tw(e);break;case"homebrew":await ow();break;case"winget":await sw();break;case"chocolatey":await nw();break;case"scoop":await rw();break;case"binary":await iw(s,e);break;default:console.log(a.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${a.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${a.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${a.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(o){console.error(a.red(` \u274C Update failed: ${o instanceof Error?o.message:String(o)}`)),console.log(a.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}l(ew,"performUpdate");async function tw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,hs.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(tw,"updateViaNpm");async function ow(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,hs.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(ow,"updateViaHomebrew");async function sw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,hs.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(sw,"updateViaWinget");async function nw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,hs.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(nw,"updateViaChocolatey");async function rw(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,hs.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(rw,"updateViaScoop");async function iw(s,e){let t=await Gr(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{lt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${Tm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{lt.writeFileSync(n,c),lt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{lt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(iw,"updateViaBinaryDownload");async function aw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Nc()==="binary"){let t=process.execPath+".backup";if(!lt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{lt.copyFileSync(t,process.execPath),lt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(aw,"rollback");U();var ys=y(require("node:fs"),1),Vr=y(require("node:path"),1),Om=y(require("node:crypto"),1);X();var Gt=!0,Lc="",Qe=[],Am=!1,cw="https://monkeyscode.com/api/telemetry",qr=50,lw=6e4;function Mm(){let s=T();return Vr.join(s.config,"telemetry.json")}l(Mm,"getConfigPath");function Bc(){try{let s=ys.readFileSync(Mm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:uw()};return Uc(s),s}}l(Bc,"loadConfig");function Uc(s){try{let e=Mm();ys.mkdirSync(Vr.dirname(e),{recursive:!0}),ys.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(Uc,"saveConfig");function uw(){return Om.randomUUID()}l(uw,"generateClientId");function Im(){if(Am)return;if(Am=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Gt=!1;return}let s=Bc();Gt=s.enabled,Lc=s.clientId,Gt&&(setInterval(()=>Pm(),lw).unref(),process.on("beforeExit",()=>Pm()))}l(Im,"initTelemetry");function jm(){return Gt}l(jm,"isTelemetryEnabled");function Nm(){Gt=!0;let s=Bc();s.enabled=!0,Uc(s)}l(Nm,"enableTelemetry");function Lm(){Gt=!1,Qe=[];let s=Bc();s.enabled=!1,Uc(s)}l(Lm,"disableTelemetry");function Bm(s,e={}){Gt&&(Qe.push({name:s,properties:e,timestamp:new Date().toISOString()}),Qe.length>qr&&(Qe=Qe.slice(-qr)))}l(Bm,"trackEvent");async function Pm(){if(!Gt||Qe.length===0)return;let s=[...Qe];Qe=[];let e=xe(),o={clientId:Lc,cliVersion:"0.1.1",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(cw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{Qe.unshift(...s),Qe.length>qr&&(Qe=Qe.slice(-qr))}}l(Pm,"flushEvents");function Um(){let s=xe();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.1",` \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: ${Lc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
475
|
-
`)}l(Um,"getCollectedDataSummary");async function Wm(s){switch(s){case"enable":Nm(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":Lm(),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(Um()),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)")):jm()?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(Wm,"telemetryCommand");var wt=y(require("node:fs"),1),gn=y(require("node:path"),1);U();X();async function Hm(s,e){let t=xe(),o="0.1.
|
|
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(""),fw()}l(qm,"runOnboarding");var
|
|
476
|
+
`))}}l(hm,"mcpBrowseCommand");X();var Xe=y(require("node:fs"),1),fn=y(require("node:path"),1);X();U();var mn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var ym=["plan","fast","thinking"],bm=["dark","light","auto"],wm=["text","json","stream"],km={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>ym.includes(s)?null:`must be one of: ${ym.join(", ")}`,"defaultMode"),theme:l(s=>bm.includes(s)?null:`must be one of: ${bm.join(", ")}`,"theme"),outputFormat:l(s=>wm.includes(s)?null:`must be one of: ${wm.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Mc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:mn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(mn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=km[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Xe.mkdirSync(fn.dirname(r),{recursive:!0}),Xe.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Xe.existsSync(o)&&(n=JSON.parse(Xe.readFileSync(o,"utf8")))}catch{}delete n[e],Xe.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...mn};for(let t of Object.keys(mn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=T();return fn.join(e.config,"config.json")}getProjectConfigPath(){return fn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Xe.existsSync(e)){let o=JSON.parse(Xe.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=km[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(mn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Xe.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Dm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Dm,"printConfigList");var Oc=null;function Mo(s){return(!Oc||s)&&(Oc=new Mc(s)),Oc}l(Mo,"getConfigSystem");ir();U();Ce();oe();var qb=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function vm(){let s=j(),e=W(s),t=s.ansi,o=me();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Ae();if(d){let p=await fetch(`${qb}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Ic(n.tokensIn),u=Ic(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Ic(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(vm,"usageCommand");function Ic(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Ic,"formatTokenCount");var lt=y(require("node:fs"),1),Tm=y(require("node:path"),1),hs=require("node:child_process");U();var gs=y(require("node:fs"),1),Hr=y(require("node:path"),1);X();var Vb="https://monkeyscode.com/api/latest-version",zb="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",Jb=4*60*60*1e3;function Cm(){let s=T();return Hr.join(s.config,"update-check")}l(Cm,"getCachePath");function Kb(){try{let s=gs.readFileSync(Cm(),"utf8");return JSON.parse(s)}catch{return null}}l(Kb,"readCache");function jc(s){try{let e=Cm();gs.mkdirSync(Hr.dirname(e),{recursive:!0}),gs.writeFileSync(e,JSON.stringify(s))}catch{}}l(jc,"writeCache");function Sm(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Sm,"isNewerVersion");function Yb(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(Yb,"getAssetKey");async function Gr(s,e=!1){if(!e){let t=Kb();if(t&&Date.now()-t.lastCheck<Jb)return t.latestVersion&&Sm(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await xm(Vb);if(t||(t=await xm(zb)),!t)return jc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=Yb(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return jc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Sm(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return jc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Gr,"checkForUpdate");async function xm(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(xm,"fetchManifest");function $m(s){Gr(s).then(e=>{e&&(globalThis.__mcUpdateAvailable=e)}).catch(()=>{})}l($m,"checkForUpdateBackground");function _m(){let s=globalThis.__mcUpdateAvailable;if(!s)return;let e=globalThis.__mcChalk,t=`\u2139\uFE0F Update available: v${s.currentVersion} \u2192 v${s.version}. Run "mc update" to upgrade.`;console.error(e?e.dim(t):t)}l(_m,"printUpdateNotice");function Nc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Nc,"detectInstallMethod");async function Rm(s){let t=(await Promise.resolve().then(()=>(Fm(),Em)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.3";if(s.rollback){await aw(t);return}if(s.check){await Zb(t);return}await ew(t,s.version)}l(Rm,"updateCommand");async function Zb(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Gr(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(Zb,"checkOnly");async function ew(s,e){let t=Nc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await tw(e);break;case"homebrew":await ow();break;case"winget":await sw();break;case"chocolatey":await nw();break;case"scoop":await rw();break;case"binary":await iw(s,e);break;default:console.log(a.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${a.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${a.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${a.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(o){console.error(a.red(` \u274C Update failed: ${o instanceof Error?o.message:String(o)}`)),console.log(a.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}l(ew,"performUpdate");async function tw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,hs.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(tw,"updateViaNpm");async function ow(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,hs.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(ow,"updateViaHomebrew");async function sw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,hs.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(sw,"updateViaWinget");async function nw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,hs.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(nw,"updateViaChocolatey");async function rw(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,hs.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(rw,"updateViaScoop");async function iw(s,e){let t=await Gr(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{lt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${Tm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{lt.writeFileSync(n,c),lt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{lt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(iw,"updateViaBinaryDownload");async function aw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Nc()==="binary"){let t=process.execPath+".backup";if(!lt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{lt.copyFileSync(t,process.execPath),lt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(aw,"rollback");U();var ys=y(require("node:fs"),1),Vr=y(require("node:path"),1),Om=y(require("node:crypto"),1);X();var qt=!0,Lc="",Qe=[],Am=!1,cw="https://monkeyscode.com/api/telemetry",qr=50,lw=6e4;function Mm(){let s=T();return Vr.join(s.config,"telemetry.json")}l(Mm,"getConfigPath");function Bc(){try{let s=ys.readFileSync(Mm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:uw()};return Uc(s),s}}l(Bc,"loadConfig");function Uc(s){try{let e=Mm();ys.mkdirSync(Vr.dirname(e),{recursive:!0}),ys.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(Uc,"saveConfig");function uw(){return Om.randomUUID()}l(uw,"generateClientId");function Im(){if(Am)return;if(Am=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){qt=!1;return}let s=Bc();qt=s.enabled,Lc=s.clientId,qt&&(setInterval(()=>Pm(),lw).unref(),process.on("beforeExit",()=>Pm()))}l(Im,"initTelemetry");function jm(){return qt}l(jm,"isTelemetryEnabled");function Nm(){qt=!0;let s=Bc();s.enabled=!0,Uc(s)}l(Nm,"enableTelemetry");function Lm(){qt=!1,Qe=[];let s=Bc();s.enabled=!1,Uc(s)}l(Lm,"disableTelemetry");function Bm(s,e={}){qt&&(Qe.push({name:s,properties:e,timestamp:new Date().toISOString()}),Qe.length>qr&&(Qe=Qe.slice(-qr)))}l(Bm,"trackEvent");async function Pm(){if(!qt||Qe.length===0)return;let s=[...Qe];Qe=[];let e=xe(),o={clientId:Lc,cliVersion:"0.1.3",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(cw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{Qe.unshift(...s),Qe.length>qr&&(Qe=Qe.slice(-qr))}}l(Pm,"flushEvents");function Um(){let s=xe();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.3",` \u2022 OS: ${s.os} (${s.arch})`,` \u2022 Shell: ${s.shell}`,` \u2022 Node.js version: ${process.version}`," \u2022 Command used (interactive, headless, background)"," \u2022 Model selected"," \u2022 Duration and token count"," \u2022 Error types (not error content)"," \u2022 Tool usage frequency","","\u274C Never collected:"," \u2022 Prompts or conversation content"," \u2022 Source code or file contents"," \u2022 File paths or project names"," \u2022 Authentication tokens or API keys"," \u2022 Personal information","",`Status: ${qt?"ENABLED":"DISABLED"}`,`Client ID: ${Lc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
477
|
+
`)}l(Um,"getCollectedDataSummary");async function Wm(s){switch(s){case"enable":Nm(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":Lm(),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(Um()),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)")):jm()?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(Wm,"telemetryCommand");var wt=y(require("node:fs"),1),gn=y(require("node:path"),1);U();X();async function Hm(s,e){let t=xe(),o="0.1.3";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=mw();i?(n.crashLog=i,console.log(a.dim(" \u{1F4CE} Attached latest crash report"))):console.log(a.dim(" No crash reports found"))}if(await dw(n))console.log(a.green(" \u2705 Bug report submitted")),console.log(a.dim(" Thank you! Our team will review your report."));else{let i=pw(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(Hm,"bugCommand");async function dw(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(dw,"submitReport");function pw(s){let e=T(),t=gn.join(e.config,"bug-reports");wt.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=gn.join(t,`${o}.json`);return wt.writeFileSync(n,JSON.stringify(s,null,2)),n}l(pw,"saveReportLocally");function mw(){try{let s=T(),e=gn.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(gn.join(e,t[0]),"utf8")}catch{return null}}l(mw,"getLatestCrashLog");var Io=y(require("node:fs"),1),Wc=y(require("node:path"),1);U();X();Ce();function Gm(){let s=T(),e=Wc.join(s.config,"config.json");return!Io.existsSync(e)}l(Gm,"isFirstRun");function fw(){let e=T().config,t=Wc.join(e,"config.json");Io.mkdirSync(e,{recursive:!0}),Io.existsSync(t)||Io.writeFileSync(t,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}l(fw,"markOnboardingComplete");async function qm(){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(`
|
|
478
|
+
`)[0];t.push({name:"ripgrep",ok:!0,msg:r.replace("ripgrep ","")})}catch{t.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let n of t){let r=n.ok?a.green(" \u2705"):a.yellow(" \u26A0\uFE0F ");console.log(`${r} ${n.name}: ${a.dim(n.msg)}`)}console.log(""),console.log(a.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${a.cyan("mc auth login")}`),console.log(""),console.log(a.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${a.dim("Interactive:")} ${a.cyan("mc")} Open the REPL`),console.log(` ${a.dim("One-shot:")} ${a.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${a.dim("Background:")} ${a.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${a.dim("Health:")} ${a.cyan("mc doctor")} Check your setup`),console.log(` ${a.dim("Help:")} ${a.cyan("mc --help")} See all commands`),console.log(""),console.log(a.dim(" \u2500".repeat(30))),console.log(a.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),fw()}l(qm,"runOnboarding");var po=y(require("node:fs"),1),zr=y(require("node:path"),1);X();var Vm=[];function Jm(){process.on("uncaughtException",s=>{zm(s,"uncaughtException"),console.error(`
|
|
477
479
|
\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));
|
|
480
|
+
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));zm(e,"unhandledRejection")})}l(Jm,"installCrashHandler");function gw(){let s=T();return zr.join(s.config,"crashes")}l(gw,"getCrashDir");function zm(s,e){try{let t=gw();po.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=zr.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.3",`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",Vm.length>0?Vm.map((u,d)=>` ${d+1}. ${u}`).join(`
|
|
479
481
|
`):" (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
|
-
`);
|
|
482
|
+
`);po.writeFileSync(n,c),hw(t,20)}catch{}}l(zm,"writeCrashReport");function hw(s,e){try{let t=po.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)po.unlinkSync(zr.join(s,t[o]))}catch{}}l(hw,"pruneOldReports");var Fe=y(require("node:fs"),1),zt=y(require("node:path"),1),yw=require("node:child_process");U();X();Ce();var bw="MEMORY.md",Km=".monkeyscode";async function Ym(s={}){let e=W(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=zt.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=ww(o),i=Fe.readdirSync(n).filter(h=>h.endsWith(".json")).map(h=>({name:h,path:zt.join(n,h),mtime:Fe.statSync(zt.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 v=zt.extname(k.args.path);if(v){let x=`Works primarily with ${v} files`;c.set(x,(c.get(x)||0)+1)}}}if(b.messages){let k=JSON.stringify(b.messages).toLowerCase();k.includes("vitest")&&Vt(c,"Uses vitest for testing"),k.includes("jest")&&Vt(c,"Uses jest for testing"),k.includes("mocha")&&Vt(c,"Uses mocha for testing"),k.includes("zod")&&Vt(c,"Uses Zod for runtime validation"),k.includes("joi")&&Vt(c,"Uses Joi for validation"),k.includes("tailwind")&&Vt(c,"Uses Tailwind CSS"),k.includes("styled-components")&&Vt(c,"Uses styled-components"),k.includes("result<")&&Vt(c,"Uses Result<T, E> pattern for error handling"),(k.includes("try/catch")||k.includes("try {"))&&Vt(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=zt.join(process.cwd(),Km,bw);Fe.mkdirSync(zt.join(process.cwd(),Km),{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
483
|
|
|
482
484
|
> Auto-generated by \`mc dream\`. Edit freely.
|
|
483
485
|
`),g+=`
|
|
@@ -486,11 +488,11 @@ ${t}
|
|
|
486
488
|
|
|
487
489
|
`;for(let h of d){let b=`- ${h.rule}`;f.includes(h.rule)||(g+=b+`
|
|
488
490
|
`)}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(Ym,"dream");function ww(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(ww,"parseDuration");function
|
|
491
|
+
`),console.log(` Updated: ${a.cyan(p)}`),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"))}l(Ym,"dream");function ww(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(ww,"parseDuration");function Vt(s,e){s.set(e,(s.get(e)||0)+1)}l(Vt,"incr");var kw={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
492
|
`)},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
493
|
`)},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
494
|
`)},"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=kw[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=
|
|
495
|
+
`)}};async function Dw(s){let e=kw[s];if(!e){console.log(a.red(` Unknown dream mode: ${s}`)),console.log(a.dim(" Available: --audit, --refactor, --docs, --test-gaps"));return}console.log(""),console.log(a.bold(` ${e.icon} Dream Mode: ${e.title}`)),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),console.log(a.dim(" Running headless agent analysis...")),console.log("");let t=zt.join(process.cwd(),".monkeyscode","dreams");Fe.mkdirSync(t,{recursive:!0});let{AgentLoop:o}=await Promise.resolve().then(()=>(ze(),Xo)),{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");U();var _e=y(require("node:fs"),1),ut=y(require("node:path"),1),Kr=y(require("node:crypto"),1),Hc=require("node:child_process");X();function Xm(s,e){let t=s.split(`
|
|
494
496
|
`);if(t.length<=50)return[{content:s,startLine:1,endLine:t.length,type:"module"}];switch(e){case"typescript":case"javascript":case"go":case"rust":case"java":case"c":case"cpp":case"csharp":return vw(t);case"python":return Sw(t);default:return xw(t,50)}}l(Xm,"chunkCode");function vw(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
497
|
`),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
498
|
`),startLine:o+1,endLine:r+1,type:n}),o=r+1,n="module")}if(o<s.length){let r=s.slice(o);r.some(i=>i.trim())&&e.push({content:r.join(`
|
|
@@ -499,18 +501,18 @@ ${t}
|
|
|
499
501
|
`),startLine:t+1,endLine:n,type:o}),t=n),o="class"),n-t>=50&&(e.push({content:s.slice(t,n+1).join(`
|
|
500
502
|
`),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
503
|
`),startLine:t+1,endLine:s.length,type:o}),e}l(Sw,"chunkByIndentation");function xw(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(xw,"chunkByLines");var
|
|
504
|
+
`),startLine:o+1,endLine:Math.min(o+e,s.length),type:"block"})}return t}l(xw,"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=Kr.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=Xm(f,m);for(let h of g)o.push({id:Kr.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,Hc.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
505
|
`).filter(o=>o&&t.has(ut.extname(o)))}catch{return[]}}getFileSha(e){try{return(0,Hc.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),Gc=require("node:child_process");var hn=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,Gc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:this.workspace,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
504
506
|
`).filter(Boolean)}catch{return[]}}getChangedFiles(){try{return(0,Gc.execSync)("git diff --name-only HEAD~5",{cwd:this.workspace,encoding:"utf8"}).trim().split(`
|
|
505
507
|
`).filter(Boolean)}catch{return this.listAllFiles()}}};var bs=y(require("node:fs"),1),de=y(require("node:path"),1),qc=require("node:child_process");var yn={KEYWORD_MATCH:.3,GIT_RECENCY:.25,IMPORT_GRAPH:.2,TEST_PAIR:.15,CONFIG_PROXIMITY:.1},Cw=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 Qm(s,e){let t=new Map,o=$w(s),n=e.maxResults||30,r=Ew(e.workspace);for(let i of r){let c=_w(i,o);c>0&&bn(t,i,c*yn.KEYWORD_MATCH,`Matches: ${o.filter(u=>i.toLowerCase().includes(u)).join(", ")}`)}if(e.useGitRecency!==!1){let i=Fw(e.workspace,50);for(let c=0;c<i.length;c++){let u=1-c/i.length;bn(t,i[c],u*yn.GIT_RECENCY,`Git recency: #${c+1}`)}}if(e.activeFiles&&e.activeFiles.length>0)for(let i of e.activeFiles){let c=Tw(e.workspace,i);for(let u of c)bn(t,u,yn.IMPORT_GRAPH,`Imported by ${de.basename(i)}`)}for(let i of r){let c=Aw(i);c&&t.has(i)&&bn(t,c,yn.TEST_PAIR,`Test pair of ${de.basename(i)}`)}for(let i of r)if(Cw.has(de.basename(i))){let c=de.dirname(i);[...t.keys()].some(d=>de.dirname(d)===c)&&bn(t,i,yn.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(Qm,"rankFiles");function bn(s,e,t,o){let n=s.get(e)||{score:0,reasons:[]};n.score+=t,n.reasons.push(o),s.set(e,n)}l(bn,"addScore");function $w(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($w,"extractKeywords");function _w(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(_w,"keywordScore");function Ew(s){try{return(0,qc.execSync)("git ls-files --cached --others --exclude-standard",{cwd:s,encoding:"utf8",maxBuffer:1e7}).trim().split(`
|
|
506
508
|
`).filter(Boolean)}catch{return[]}}l(Ew,"listWorkspaceFiles");function Fw(s,e){try{let t=(0,qc.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(Fw,"getGitRecentFiles");function Tw(s,e){try{let t=bs.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=Rw(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(bs.existsSync(de.join(s,d))){o.push(d);break}}return o}catch{return[]}}l(Tw,"parseImportsQuick");function Rw(s,e){let t=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let o of t){let n=e+o;if(bs.existsSync(de.join(s,n)))return n}return bs.existsSync(de.join(s,e))?e:null}l(Rw,"resolveImport");function Aw(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(Aw,"findTestPair");Q();Ce();async function
|
|
509
|
+
`).filter(n=>!n||o.has(n)?!1:(o.add(n),!0)).slice(0,e)}catch{return[]}}l(Fw,"getGitRecentFiles");function Tw(s,e){try{let t=bs.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=Rw(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(bs.existsSync(de.join(s,d))){o.push(d);break}}return o}catch{return[]}}l(Tw,"parseImportsQuick");function Rw(s,e){let t=[".ts",".tsx",".js",".jsx","/index.ts","/index.js"];for(let o of t){let n=e+o;if(bs.existsSync(de.join(s,n)))return n}return bs.existsSync(de.join(s,e))?e:null}l(Rw,"resolveImport");function Aw(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(Aw,"findTestPair");Q();Ce();async function jo(s,e){let t=s[0]||"status",o=process.cwd(),n=z(),r=W(j());switch(t){case"index":await Pw(o,n);break;case"search":await Ow(o,n,s.slice(1).join(" "));break;case"status":await Mw(o,n);break;case"rebuild":await Iw(o,n);break;case"related":await jw(o,s[1]);break;case"rank":Nw(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(jo,"contextCommand");async function Pw(s,e){console.log(a.cyan(" \u26A1 Indexing workspace...")),console.log(a.dim(` ${s}`)),console.log("");let t=Date.now(),n=await Yr(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(Zm(n.indexSizeBytes))}`),console.log(` Time: ${a.bold(r+"s")}`),console.log("")}l(Pw,"contextIndex");async function Ow(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 Yr(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
510
|
`).slice(0,2).map(d=>` ${a.dim(d.substring(0,80))}`).join(`
|
|
509
|
-
`);console.log(u),console.log("")}}l(Ow,"contextSearch");async function Mw(s,e){let o=Yr(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(Zm(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 hn(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(Mw,"contextStatus");async function Iw(s,e){console.log(a.yellow(" \u{1F504} Rebuilding index from scratch...")),console.log("");let t=Date.now(),n=await Yr(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(Iw,"contextRebuild");async function jw(s,e){if(!e){console.log(a.red(" Usage: mc context related <file>"));return}let t=new hn(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(jw,"contextRelated");function Nw(s,e){if(!e){console.log(a.red(' Usage: mc context rank "your prompt"'));return}let t=Qm(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(Nw,"contextRank");function Yr(s,e){return new
|
|
510
|
-
`)}l(Kc,"saveTriggers");function Hw(s,e){let t=e.toLowerCase().split(/\s+/).slice(0,3).join("-").replace(/[^a-z0-9-]/g,"");return`${s.replace(/\./g,"-")}-${t}`}l(Hw,"generateName");function Gw(){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(Gw,"printHelp");async function qw(s,e){let{TriggerEngine:t}=await Promise.resolve().then(()=>(nf(),sf)),{GitHubWebhookServer:o}=await Promise.resolve().then(()=>(cf(),af)),n=
|
|
511
|
-
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(qw,"triggersServe");U();U();var hf=require("node:child_process");var Ie=y(require("node:fs"),1),
|
|
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=Qw(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(
|
|
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(Kw,"renderTree");function Yw(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(Yw,"renderFileGraph");function Xw(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(Xw,"renderFooter");function Qw(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(Qw,"getToolIcon");function Sn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Sn,"formatNum");var ff=y(require("node:fs"),1),Xc=y(require("node:path"),1);X();var
|
|
511
|
+
`);console.log(u),console.log("")}}l(Ow,"contextSearch");async function Mw(s,e){let o=Yr(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(Zm(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 hn(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(Mw,"contextStatus");async function Iw(s,e){console.log(a.yellow(" \u{1F504} Rebuilding index from scratch...")),console.log("");let t=Date.now(),n=await Yr(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(Iw,"contextRebuild");async function jw(s,e){if(!e){console.log(a.red(" Usage: mc context related <file>"));return}let t=new hn(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(jw,"contextRelated");function Nw(s,e){if(!e){console.log(a.red(' Usage: mc context rank "your prompt"'));return}let t=Qm(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(Nw,"contextRank");function Yr(s,e){return new Jr(s,{platformUrl:e.platformUrl,token:process.env.MC_API_KEY||"",embeddingModel:"text-embedding-3-small"})}l(Yr,"createIndex");function Zm(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(Zm,"formatBytes");var mo=y(require("node:fs"),1),Dn=y(require("node:path"),1);U();Ce();Q();var uf=".monkeyscode/triggers.json";async function fo(s,e){let t=s[0]||"list",o=process.cwd();switch(t){case"list":Lw(o);break;case"add":Bw(o,e);break;case"remove":Uw(o,s[1]);break;case"test":Ww(o,s[1]);break;case"enable":lf(o,s[1],!0);break;case"disable":lf(o,s[1],!1);break;case"serve":await qw(o,e);break;default:Gw()}}l(fo,"triggersCommand");function Lw(s){let e=vn(s),t=W(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(Lw,"triggersList");function Bw(s,e){let t=e.event,o=e.prompt,n=e.name||Hw(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=vn(s);if(d.some(p=>p.name===n)){console.log(a.red(` Trigger "${n}" already exists. Use a different --name.`));return}d.push(u),Kc(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(Bw,"triggersAdd");function Uw(s,e){if(!e){console.log(a.red(" Usage: mc triggers remove <trigger-name>"));return}let t=vn(s),o=t.findIndex(n=>n.name===e);if(o===-1){console.log(a.red(` Trigger "${e}" not found.`));return}t.splice(o,1),Kc(s,t),console.log(a.green(` \u2705 Trigger "${e}" removed`)),console.log("")}l(Uw,"triggersRemove");function Ww(s,e){if(!e){console.log(a.red(" Usage: mc triggers test <trigger-name>"));return}let o=vn(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(Ww,"triggersTest");function lf(s,e,t){if(!e){console.log(a.red(` Usage: mc triggers ${t?"enable":"disable"} <trigger-name>`));return}let o=vn(s),n=o.find(r=>r.name===e);if(!n){console.log(a.red(` Trigger "${e}" not found.`));return}n.enabled=t,Kc(s,o),console.log(a.green(` \u2705 Trigger "${e}" ${t?"enabled":"disabled"}`)),console.log("")}l(lf,"triggersToggle");function vn(s){let e=Dn.join(s,uf);if(!mo.existsSync(e))return[];try{return JSON.parse(mo.readFileSync(e,"utf8")).triggers||[]}catch{return[]}}l(vn,"loadTriggers");function Kc(s,e){let t=Dn.join(s,uf),o=Dn.dirname(t);mo.mkdirSync(o,{recursive:!0}),mo.writeFileSync(t,JSON.stringify({triggers:e},null,2)+`
|
|
512
|
+
`)}l(Kc,"saveTriggers");function Hw(s,e){let t=e.toLowerCase().split(/\s+/).slice(0,3).join("-").replace(/[^a-z0-9-]/g,"");return`${s.replace(/\./g,"-")}-${t}`}l(Hw,"generateName");function Gw(){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(Gw,"printHelp");async function qw(s,e){let{TriggerEngine:t}=await Promise.resolve().then(()=>(nf(),sf)),{GitHubWebhookServer:o}=await Promise.resolve().then(()=>(cf(),af)),n=z(),{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(`
|
|
513
|
+
Shutting down trigger daemon...`)),u.stop(),f()},"shutdown");process.on("SIGINT",m),process.on("SIGTERM",m)})}l(qw,"triggersServe");U();U();var hf=require("node:child_process");var Ie=y(require("node:fs"),1),go=y(require("node:path"),1),df=y(require("node:crypto"),1);X();var ks=class s{static{l(this,"TraceRecorder")}trace;turnIndex=0;currentToolStart=null;currentToolName=null;thinkingBuffer="";tracesDir;constructor(e){let t=T(De());this.tracesDir=go.join(t.data,"traces"),Ie.mkdirSync(this.tracesDir,{recursive:!0}),this.trace={runId:e.runId||df.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=go.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=go.join(t.data,"traces"),n=go.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=go.join(t.data,"traces");return Ie.existsSync(o)?Ie.readdirSync(o).filter(r=>r.endsWith(".json")).map(r=>{let i=Ie.statSync(go.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(go.join(o,r.file),"utf8"));return{runId:i.runId,model:i.model,prompt:i.prompt.slice(0,80),date:i.startedAt,cost:i.totalCostUsd}}catch{return null}}).filter(Boolean):[]}static lastRunId(){let e=s.list(1);return e.length>0?e[0].runId:null}};U();function pf(s,e={}){Vw(s),e.tree?Kw(s):zw(s,e.verbose),Yw(s),Xw(s)}l(pf,"renderTrace");function Vw(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(Sn(s.tokensIn))} in / ${a.white(Sn(s.tokensOut))} out${s.tokensCached?` / ${a.dim(Sn(s.tokensCached)+" cached")}`:""}`),console.log(` ${a.dim("Files:")} ${o} accessed`),console.log(` ${a.dim("Turns:")} ${s.turns.length}`),console.log()}l(Vw,"renderHeader");function zw(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)Jw(t,e);console.log()}l(zw,"renderTimeline");function Jw(s,e){let t=s.tokens?a.dim(` (${Sn(s.tokens)} tok)`):"",o=s.durationMs?a.dim(` ${s.durationMs}ms`):"";switch(s.type){case"thinking":{let n=e?s.content||"":(s.content||"").split(`
|
|
514
|
+
`)[0].slice(0,80);console.log(` ${a.blue("\u{1F4AD}")} ${a.blue("Thinking")}${t}`),n&&console.log(` ${a.dim(n)}`);break}case"tool_call":{let n=Qw(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(Jw,"renderTurn");function Kw(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(` [${Sn(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(`
|
|
515
|
+
`)[0].slice(0,70);console.log(`${o}${a.dim("\u2502 "+i)}`)}e=Math.min(e+1,4);break;case"tool_call":console.log(`${o}${a.green("\u251C\u2500 \u{1F527} "+(t.tool||"tool"))}${r}`),t.resultPreview&&console.log(`${o}${a.dim("\u2502 \u2192 "+t.resultPreview.slice(0,60))}`);break;case"context_compact":e=Math.max(0,e-1),console.log(`${o}${a.yellow("\u251C\u2500 \u{1F4E6} Compact")}${n}`);break;case"error":console.log(`${o}${a.red("\u2514\u2500 \u274C Error")}: ${t.content}`);break}}console.log()}l(Kw,"renderTree");function Yw(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(Yw,"renderFileGraph");function Xw(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(Xw,"renderFooter");function Qw(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(Qw,"getToolIcon");function Sn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Sn,"formatNum");var ff=y(require("node:fs"),1),Xc=y(require("node:path"),1);X();var No={thinking:"#4A90D9",tool_call:"#2ECC71",context_compact:"#F39C12",error:"#E74C3C",root:"#34495E"};function gf(s){let e=T(De()),t=Xc.join(e.data,"traces"),o=Xc.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 mf(s,r,o)}return mf(s,n,o)}l(gf,"generateFlamegraph");function mf(s,e,t){let c=[];c.push({name:`Run: ${s.model} \u2014 ${s.prompt.slice(0,50)}`,tokens:e,color:No.root,x:0,width:1200,y:0,detail:`Total: ${Yc(e)} tokens, $${s.totalCostUsd.toFixed(4)}`});let u=0;for(let m of s.turns){let g=m.tokens||Zw(m);if(g===0)continue;let h=Math.max(g/e*1200,2),b=No[m.type]||No.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}: ${Yc(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
516
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 ${p}" width="1200" height="${p}">
|
|
515
517
|
<style>
|
|
516
518
|
.frame { cursor: pointer; }
|
|
@@ -529,13 +531,13 @@ ${t}
|
|
|
529
531
|
|
|
530
532
|
<!-- Legend -->
|
|
531
533
|
<g class="legend" transform="translate(800, 20)">
|
|
532
|
-
<rect x="0" y="0" width="12" height="12" fill="${
|
|
534
|
+
<rect x="0" y="0" width="12" height="12" fill="${No.thinking}"/>
|
|
533
535
|
<text x="16" y="11">Thinking</text>
|
|
534
|
-
<rect x="80" y="0" width="12" height="12" fill="${
|
|
536
|
+
<rect x="80" y="0" width="12" height="12" fill="${No.tool_call}"/>
|
|
535
537
|
<text x="96" y="11">Tools</text>
|
|
536
|
-
<rect x="150" y="0" width="12" height="12" fill="${
|
|
538
|
+
<rect x="150" y="0" width="12" height="12" fill="${No.context_compact}"/>
|
|
537
539
|
<text x="166" y="11">Compact</text>
|
|
538
|
-
<rect x="230" y="0" width="12" height="12" fill="${
|
|
540
|
+
<rect x="230" y="0" width="12" height="12" fill="${No.error}"/>
|
|
539
541
|
<text x="246" y="11">Error</text>
|
|
540
542
|
</g>
|
|
541
543
|
|
|
@@ -547,8 +549,8 @@ ${t}
|
|
|
547
549
|
<text x="${h}" y="${g+24-8}">${Zr(b)}</text>
|
|
548
550
|
</g>
|
|
549
551
|
`}return f+=`</g>
|
|
550
|
-
</svg>`,ff.writeFileSync(t,f),t}l(mf,"generateSvg");function Zw(s){return s.tokens?s.tokens:s.content?Math.ceil(s.content.length/4):s.result?Math.ceil(s.result.length/4):10}l(Zw,"estimateTurnTokens");function Yc(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Yc,"formatTokens");function ek(s,e){return s.length>e?s.slice(0,e-1)+"\u2026":s}l(ek,"truncate");function Zr(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}l(Zr,"escapeXml");function yf(s){let e=ks.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(yf,"traceList");function bf(s,e){let t=s==="last"?ks.lastRunId():s;if(!t){console.log(a.red("No traces found. Run an agent first."));return}let o=ks.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=gf(o);console.log(a.green(`Flamegraph saved: ${n}`));let r=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,hf.exec)(`${r} "${n}"`,i=>{i&&console.log(a.dim(`Open manually: ${n}`))});return}pf(o,{tree:e.tree,verbose:e.verbose})}l(bf,"traceShow");U();Q();oe();var Jt=class{static{l(this,"MarketplaceClient")}baseUrl;token;constructor(e){let t=
|
|
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,kf.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 Df(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)Ef(n)}catch(o){console.log(a.red(`Search failed: ${o.message}`))}}l(Df,"marketplaceSearch");async function vf(s){let e=new
|
|
552
|
+
</svg>`,ff.writeFileSync(t,f),t}l(mf,"generateSvg");function Zw(s){return s.tokens?s.tokens:s.content?Math.ceil(s.content.length/4):s.result?Math.ceil(s.result.length/4):10}l(Zw,"estimateTurnTokens");function Yc(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Yc,"formatTokens");function ek(s,e){return s.length>e?s.slice(0,e-1)+"\u2026":s}l(ek,"truncate");function Zr(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}l(Zr,"escapeXml");function yf(s){let e=ks.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(yf,"traceList");function bf(s,e){let t=s==="last"?ks.lastRunId():s;if(!t){console.log(a.red("No traces found. Run an agent first."));return}let o=ks.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=gf(o);console.log(a.green(`Flamegraph saved: ${n}`));let r=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,hf.exec)(`${r} "${n}"`,i=>{i&&console.log(a.dim(`Open manually: ${n}`))});return}pf(o,{tree:e.tree,verbose:e.verbose})}l(bf,"traceShow");U();Q();oe();var Jt=class{static{l(this,"MarketplaceClient")}baseUrl;token;constructor(e){let t=z();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),ho=y(require("node:path"),1),wf=require("node:child_process");X();var Lo=class{static{l(this,"SkillInstaller")}client;skillsDir;registryPath;constructor(){this.client=new Jt;let e=T(De());this.skillsDir=ho.join(e.config,"skills"),this.registryPath=ho.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=ho.join(this.skillsDir,n,r);ye.existsSync(i)&&ye.rmSync(i,{recursive:!0}),ye.mkdirSync(i,{recursive:!0});let c=ho.join(i,".tmp.tar.gz");ye.writeFileSync(c,o);try{(0,wf.execSync)(`tar -xzf "${c}" -C "${i}" --strip-components=1`,{stdio:"pipe"})}finally{ye.unlinkSync(c)}let u=ho.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=ho.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),kf=require("node:child_process");var ei=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(`
|
|
553
|
+
`)){let c=i.match(/^(\w+):\s*(.+)$/);if(!c)continue;let[,u,d]=c;switch(u){case"name":r.name=d.trim();break;case"description":r.description=d.trim();break;case"version":r.version=d.trim();break;case"author":r.author=d.trim();break;case"category":r.category=d.trim();break;case"tags":r.tags=d.split(",").map(p=>p.trim().replace(/^\[|\]$/g,""));break}}return r}createTarball(e){let t=dt.join(e,".publish.tar.gz");try{return(0,kf.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 Df(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)Ef(n)}catch(o){console.log(a.red(`Search failed: ${o.message}`))}}l(Df,"marketplaceSearch");async function vf(s){let e=new Lo;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(vf,"marketplaceInstall");function Sf(s){new Lo().uninstall(s)?console.log(a.green(`\u2713 Uninstalled ${s}`)):console.log(a.red(`Skill not found: ${s}`))}l(Sf,"marketplaceUninstall");async function xf(s,e){let t=new ei;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(xf,"marketplacePublish");async function Cf(){let s=new Lo;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(Cf,"marketplaceUpdate");function $f(){let e=new Lo().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($f,"marketplaceList");async function _f(){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)Ef(t)}catch(e){console.log(a.red(`Failed to fetch featured: ${e.message}`))}}l(_f,"marketplaceFeatured");function Ef(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(Ef,"renderSkillCard");U();var yo=y(require("node:fs"),1),ti=y(require("node:path"),1);X();var tk=`You translate natural language permission rules into structured JSON policies.
|
|
552
554
|
|
|
553
555
|
Each policy has:
|
|
554
556
|
- tool: glob pattern for which tools this applies to (e.g., "delete_file", "bash", "*")
|
|
@@ -572,12 +574,12 @@ Input: "Ask before modifying any file with 'config' in the name"
|
|
|
572
574
|
Output: {"tool":"*_file","condition":"path.includes('config')","action":"prompt","message":"This file contains configuration. Proceed?"}
|
|
573
575
|
|
|
574
576
|
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 ok(s){let e=sk(s);return e||await nk(s)}l(ok,"translateNaturalRule");function sk(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(sk,"tryLocalTranslation");async function nk(s){try{let{AgentLoop:e}=await Promise.resolve().then(()=>(
|
|
577
|
+
Output: {"tool":"bash","condition":"command.includes('sudo')","action":"deny","message":"sudo is not allowed per project policy"}`;async function ok(s){let e=sk(s);return e||await nk(s)}l(ok,"translateNaturalRule");function sk(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(sk,"tryLocalTranslation");async function nk(s){try{let{AgentLoop:e}=await Promise.resolve().then(()=>(ze(),Xo)),{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 Qc(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(`${tk}
|
|
576
578
|
|
|
577
579
|
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?Qc(s):d}catch{return Qc(s)}}l(nk,"llmTranslation");function Qc(s){return{tool:"*",condition:"true",action:"prompt",message:`Custom rule: ${s}`}}l(Qc,"fallbackPolicy");function Ff(){let s=T(De());return ti.join(s.config,"natural-permissions.json")}l(Ff,"getPermissionsPath");function xn(){let s=Ff();if(!
|
|
580
|
+
Output: `);let u=c.trim().replace(/^```json?\n?/,"").replace(/\n?```$/,""),d=JSON.parse(u);return!d.tool||!d.condition||!d.action||!d.message?Qc(s):d}catch{return Qc(s)}}l(nk,"llmTranslation");function Qc(s){return{tool:"*",condition:"true",action:"prompt",message:`Custom rule: ${s}`}}l(Qc,"fallbackPolicy");function Ff(){let s=T(De());return ti.join(s.config,"natural-permissions.json")}l(Ff,"getPermissionsPath");function xn(){let s=Ff();if(!yo.existsSync(s))return{naturalRules:[]};try{return JSON.parse(yo.readFileSync(s,"utf8"))}catch{return{naturalRules:[]}}}l(xn,"loadNaturalPermissions");function Tf(s){let e=Ff(),t=ti.dirname(e);yo.mkdirSync(t,{recursive:!0}),yo.writeFileSync(e,JSON.stringify(s,null,2))}l(Tf,"saveNaturalPermissions");async function Rf(s){let e=await ok(s),t={text:s,generatedPolicy:e,createdAt:new Date().toISOString(),enabled:!0},o=xn();return o.naturalRules.push(t),Tf(o),t}l(Rf,"addNaturalRule");function Af(s){let e=xn();return s<0||s>=e.naturalRules.length?!1:(e.naturalRules.splice(s,1),Tf(e),!0)}l(Af,"removeNaturalRule");function Pf(s,e){let t=xn();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(Pf,"evaluateNaturalRules");async function Of(s){console.log(a.dim("Translating rule..."));let e=await Rf(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:")} ${Zc(e.generatedPolicy.action)}`),console.log(` ${a.dim("Message:")} ${e.generatedPolicy.message}`),console.log()}l(Of,"permissionsSet");function Mf(){let s=xn();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=Zc(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(Mf,"permissionsList");function If(s){let e=Af(s);console.log(e?a.green(`\u2713 Rule ${s} removed`):a.red(`Rule ${s} not found`))}l(If,"permissionsRemove");function jf(s,e){let t;try{t=JSON.parse(e)}catch{console.log(a.red("Invalid JSON for args"));return}let o=Pf(s,t);console.log(),console.log(` ${a.dim("Tool:")} ${s}`),console.log(` ${a.dim("Args:")} ${JSON.stringify(t)}`),console.log(` ${a.dim("Result:")} ${Zc(o.action)}`),o.message&&console.log(` ${a.dim("Message:")} ${o.message}`),console.log()}l(jf,"permissionsTest");function Zc(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(Zc,"colorAction");var vs=y(require("node:fs"),1),ni=y(require("node:path"),1);U();var Ue=y(require("node:fs"),1),Ds=y(require("node:path"),1),oi=require("node:child_process");function rk(s){let e={name:"Unnamed Benchmark",setup:[],steps:[],score:{testsPass:50,noRegressions:30,codeQuality:20}},t=s.split(`
|
|
579
581
|
`),o="",n={};for(let r of t){let i=r.trim();if(!i||i.startsWith("#"))continue;let c=i.match(/^(\w+):\s*(.*)$/);if(c&&!r.startsWith(" ")&&!r.startsWith(" ")){let[,p,f]=c;p==="name"&&(e.name=f.replace(/^["']|["']$/g,"")),p==="description"&&(e.description=f),p==="setup"&&(o="setup"),p==="steps"&&(o="steps"),p==="score"&&(o="score");continue}let u=i.match(/^-\s+(.+)$/);if(u){o==="setup"&&e.setup.push(u[1].replace(/^["']|["']$/g,""));continue}let d=i.match(/^(\w+):\s*(.+)$/);if(d){let[,p,f]=d,m=f.replace(/^["']|["']$/g,"");o==="steps"&&(p==="prompt"&&(n.prompt&&e.steps.push(n),n={prompt:m}),p==="verify"&&(n.verify=m),p==="expected_files_changed"&&(n.expectedFilesChanged=m.replace(/^\[|\]$/g,"").split(",").map(g=>g.trim().replace(/^["']|["']$/g,""))),p==="max_tokens"&&(n.maxTokens=parseInt(m)),p==="timeout_ms"&&(n.timeoutMs=parseInt(m))),o==="score"&&(p==="tests_pass"&&(e.score.testsPass=parseInt(m)),p==="no_regressions"&&(e.score.noRegressions=parseInt(m)),p==="code_quality"&&(e.score.codeQuality=parseInt(m)))}}return n.prompt&&e.steps.push(n),e}l(rk,"parseSimpleYaml");var si=class{static{l(this,"BenchmarkRunner")}workspace;constructor(e){this.workspace=e}loadSpec(e){let t=Ue.readFileSync(e,"utf8");return rk(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,oi.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(()=>(
|
|
582
|
+
${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop:m}=await Promise.resolve().then(()=>(ze(),Xo)),{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||"",v=new m({platformUrl:b.platformUrl,token:k,model:t,workspace:this.workspace,mode:"auto",maxTurns:p.maxTokens?Math.ceil(p.maxTokens/1e3):20,sandboxed:!0}),x=0,_=0,C=[];v.on("event",ae=>{if(ae.type==="state_update"&&(x=(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&&!C.includes(K)&&C.push(K)}}),await v.run(p.prompt);let E=!1,I="";try{I=(0,oi.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+=x,i+=_,c.push({prompt:p.prompt,passed:E,verifyOutput:I,durationMs:Date.now()-f,tokensUsed:x,filesChanged:C,score:this.scoreStep(p,E,C,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,oi.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)&&!ik(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 ik(s,e){return e.some(t=>{let o=t.replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(o).test(s)})}l(ik,"matchesGlob");function el(s){let{getPlatformPaths:e,detectPlatform:t}=(X(),Es(vo)),o=e(t()),n=Ds.join(o.data,"benchmarks");Ue.mkdirSync(n,{recursive:!0});let r=`${s.name.replace(/\s+/g,"-").toLowerCase()}-${s.model}-${Date.now()}.json`,i=Ds.join(n,r);return Ue.writeFileSync(i,JSON.stringify(s,null,2)),i}l(el,"saveBenchmarkResult");function Nf(s=20){let{getPlatformPaths:e,detectPlatform:t}=(X(),Es(vo)),o=e(t()),n=Ds.join(o.data,"benchmarks");return Ue.existsSync(n)?Ue.readdirSync(n).filter(r=>r.endsWith(".json")).map(r=>{let i=Ue.statSync(Ds.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(Ds.join(n,r.file),"utf8"))}catch{return null}}).filter(Boolean):[]}l(Nf,"loadBenchmarkResults");U();function Lf(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:")} ${Wf(s.totalScore,s.maxScore)} ${a.dim(`(${e}%)`)}`),console.log(` ${a.dim("Duration:")} ${t}s`),console.log(` ${a.dim("Tokens:")} ${Cn(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 ${Cn(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(Lf,"renderResult");function Bf(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))}`+Wf(c.totalScore,c.maxScore).padEnd(20)+a.dim(((c.durationMs/1e3).toFixed(1)+"s").padEnd(10))+a.dim(Cn(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(Bf,"renderComparison");function Uf(s){if(s.length===0)return`# No Results
|
|
581
583
|
`;let e=`# Benchmark Report: ${s[0].name}
|
|
582
584
|
|
|
583
585
|
`;e+=`Generated: ${new Date().toISOString()}
|
|
@@ -594,9 +596,9 @@ ${f.message}`)}let c=[];for(let p of e.steps){let f=Date.now();try{let{AgentLoop
|
|
|
594
596
|
`,e+=`- Score: ${r.score}/${o.maxScore} | Time: ${(r.durationMs/1e3).toFixed(1)}s | Tokens: ${Cn(r.tokensUsed)}
|
|
595
597
|
`,e+=`- Files: ${r.filesChanged.join(", ")||"none"}
|
|
596
598
|
|
|
597
|
-
`}}return e}l(Uf,"generateMarkdownReport");function Wf(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(Wf,"colorScore");function Cn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Cn,"formatNum");async function Hf(s,e){let t=ni.resolve(s),o=e.workspace||process.cwd();if(!vs.existsSync(t)){console.log(a.red(`Benchmark not found: ${t}`));return}let n=new si(o),r=e.model||["capuchin-reason"],i=ak(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)el(d);Bf(u)}else{console.log(a.dim(`Running benchmark: ${c.name} with ${r[0]}...`));let u=await n.run(c,r[0]);el(u),Lf(u)}}l(Hf,"benchmarkCustom");function Gf(s){let e=Nf(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(Uf(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))+ck(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(Gf,"benchmarkResults");function ak(s,e){return vs.statSync(s).isFile()?[e.loadSpec(s)]:vs.readdirSync(s).filter(o=>o.endsWith(".yaml")||o.endsWith(".yml")).map(o=>e.loadSpec(ni.join(s,o)))}l(ak,"loadSpecs");function ck(s){let e=parseInt(s);return e>=80?a.green(s):e>=50?a.yellow(s):a.red(s)}l(ck,"colorScore");U();var
|
|
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(
|
|
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=
|
|
599
|
+
`}}return e}l(Uf,"generateMarkdownReport");function Wf(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(Wf,"colorScore");function Cn(s){return s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":String(s)}l(Cn,"formatNum");async function Hf(s,e){let t=ni.resolve(s),o=e.workspace||process.cwd();if(!vs.existsSync(t)){console.log(a.red(`Benchmark not found: ${t}`));return}let n=new si(o),r=e.model||["capuchin-reason"],i=ak(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)el(d);Bf(u)}else{console.log(a.dim(`Running benchmark: ${c.name} with ${r[0]}...`));let u=await n.run(c,r[0]);el(u),Lf(u)}}l(Hf,"benchmarkCustom");function Gf(s){let e=Nf(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(Uf(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))+ck(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(Gf,"benchmarkResults");function ak(s,e){return vs.statSync(s).isFile()?[e.loadSpec(s)]:vs.readdirSync(s).filter(o=>o.endsWith(".yaml")||o.endsWith(".yml")).map(o=>e.loadSpec(ni.join(s,o)))}l(ak,"loadSpecs");function ck(s){let e=parseInt(s);return e>=80?a.green(s):e>=50?a.yellow(s):a.red(s)}l(ck,"colorScore");U();var Jf=y(require("node:readline"),1);var qf=y(require("node:crypto"),1),Vf=require("node:events");en();var $n=class extends Vf.EventEmitter{static{l(this,"SharedSession")}sessionId;role;ws=null;participants=new Map;userId;userName;relayUrl;reconnectTimer=null;constructor(e){super(),this.sessionId=e.sessionId||this.generateSessionId(),this.role=e.sessionId?"observer":"host",this.userId=qf.randomUUID(),this.userName=e.userName,this.relayUrl=e.relayUrl}async connect(){return new Promise((e,t)=>{let o=`${this.relayUrl}/v1/collab/${this.sessionId}?role=${this.role}&user=${encodeURIComponent(this.userName)}`;this.ws=new 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();U();function zf(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(`
|
|
600
|
+
`).slice(0,10);for(let t of e)console.log(a.dim(` ${t}`))}break;case"error":console.log(a.red(` \u2717 Error: ${s.message||s.error||"unknown"}`));break;case"complete":console.log(""),console.log(a.green(" \u2713 Complete")),s.result?.summary&&console.log(a.dim(` ${s.result.summary}`));break;case"cost_update":break;default:process.env.MC_DEBUG&&console.log(a.dim(` [${s.type}] ${JSON.stringify(s).slice(0,100)}`));break}}l(zf,"renderEvent");async function Kf(s){console.log(a.dim(`Joining session ${s}...`));let e=z();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 $n({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=>{zf(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(`
|
|
601
|
+
Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()=>{console.log(a.green("Reconnected."))}),n.on("error",r=>{console.log(a.red(`Session error: ${r.message}`))});try{await n.connect(),console.log(a.green(`\u2713 Connected to session ${s}`)),console.log(a.dim("Waiting for host activity... Press Ctrl+C to leave."));let r=Jf.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(Kf,"joinSession");async function Yf(){let s=z();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 $n({relayUrl:s.platformUrl||"wss://api.monkeyscode.com",userName:t});o.on("participant_joined",n=>{console.log(a.green(`
|
|
600
602
|
\u2192 ${n} joined your session
|
|
601
603
|
`))}),o.on("participant_left",n=>{console.log(a.dim(`
|
|
602
604
|
\u2190 ${n} left your session
|
|
@@ -647,7 +649,7 @@ Disconnected from session. Attempting to reconnect...`))}),n.on("reconnected",()
|
|
|
647
649
|
</script>
|
|
648
650
|
</body>
|
|
649
651
|
</html>
|
|
650
|
-
`.trim()}l(Xf,"generateHtmlPreview");var tl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=Qf.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(Xf(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new ic.default({server:this.server,path:"/ws"})}start(e=3030){this.port=e,this.server.listen(e,()=>{console.log(a.green(`\u{1F3A8} Design artboard live at http://localhost:${e}`))})}stop(){this.wss.close(),this.server.close()}updateDesign(e){this.currentHtml=e;for(let t of this.wss.clients)t.readyState===rt.OPEN&&t.send("reload")}},Zf=new tl;U();function lk(s){let e=new Date(s),o=new Date().getTime()-s,n=Math.floor(o/6e4),r=Math.floor(o/36e5),i=Math.floor(o/864e5);return n<1?"just now":n<60?`${n}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:e.toLocaleDateString()}l(lk,"formatDate");function ri(s){return s.substring(0,8)}l(ri,"formatShortId");function uk(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(uk,"truncatePath");function eg(){let e=new 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")(ri(t.id)),n=uk(t.workspace),r=String(t.turnCount).padEnd(8),i=lk(t.lastActive).padEnd(14),c=a.dim(t.preview.substring(0,30));console.log(` ${o} ${n.padEnd(40)} ${r}${i}${c}`)}console.log(""),console.log(a.dim(` ${e.length} session(s). Use "mc sessions show <id>" for details.`)),console.log("")}l(eg,"sessionsListCommand");function tg(s){let e=new 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 ${ri(n.id)}`)),console.log(a.dim(" \u2500".repeat(35))),console.log(` ${a.bold("ID:")} ${n.id}`),console.log(` ${a.bold("Workspace:")} ${n.workspace}`),console.log(` ${a.bold("Model:")} ${n.model}`),console.log(` ${a.bold("Mode:")} ${n.mode}`),console.log(` ${a.bold("Started:")} ${new Date(n.startTime).toLocaleString()}`),console.log(` ${a.bold("Last active:")} ${new Date(n.lastActive).toLocaleString()}`),console.log(` ${a.bold("Turns:")} ${n.turnCount}`),console.log(` ${a.bold("Tokens:")} ${n.stats.tokensUsed.toLocaleString()}`),console.log(` ${a.bold("Tool calls:")} ${n.stats.toolCalls}`),n.stats.filesChanged.length>0){console.log(` ${a.bold("Files changed:")}`);for(let r of n.stats.filesChanged.slice(0,10))console.log(` ${r}`);n.stats.filesChanged.length>10&&console.log(a.dim(` ... and ${n.stats.filesChanged.length-10} more`))}console.log(""),console.log(a.bold(" Conversation:")),console.log(a.dim(" \u2500".repeat(35)));for(let r of n.messages.slice(-10)){let i=r.role==="user"?a.hex("#6B8DD6").bold("You"):r.role==="assistant"?a.hex("#A3CAD3").bold("MC"):a.dim("System"),c=new Date(r.timestamp).toLocaleTimeString(),u=r.content.substring(0,120).replace(/\n/g," ");console.log(` ${a.dim(c)} ${i}: ${u}`)}n.messages.length>10&&console.log(a.dim(` ... ${n.messages.length-10} earlier messages`)),console.log(""),console.log(a.dim(` Resume with: mc --continue ${ri(n.id)}`)),console.log("")}l(tg,"sessionsShowCommand");function og(s){let e=new 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 ${ri(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(og,"sessionsDeleteCommand");function sg(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(sg,"sessionsPruneCommand");sn();U();Q();oe();var ol=class{static{l(this,"ScheduleApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/schedules`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async create(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify({prompt:e.prompt,cronExpression:e.cron,model:e.model,autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPR,workspace:e.workspace}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,scheduleId:o.id||o.scheduleId}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async list(){try{let e=await fetch(this.baseUrl,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).schedules||[]).map(dk):[]}catch{return[]}}async delete(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:t.ok,error:t.ok?void 0:`HTTP ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async togglePause(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/${t?"pause":"resume"}`,{method:"POST",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:o.ok,error:o.ok?void 0:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};function _n(){let s=J(),t=me()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new ol(s.platformUrl,t)}l(_n,"getClient");async function sl(s){pk(s.cron)||(console.error(a.red(` \u274C Invalid cron expression: "${s.cron}"`)),console.log(a.dim(" Expected 5-field format: minute hour day-of-month month day-of-week")),console.log(a.dim(' Example: "0 9 * * 1" = Every Monday at 9:00 AM')),process.exit(4));let t=await _n().create(s);t.success||(console.error(a.red(` \u274C Failed to create schedule: ${t.error}`)),process.exit(1)),console.log(""),console.log(a.bold(" \u23F0 Schedule created")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` ID: ${a.cyan(t.scheduleId)}`),console.log(` Prompt: "${s.prompt.substring(0,50)}${s.prompt.length>50?"...":""}"`),console.log(` Cron: ${s.cron} (${mk(s.cron)})`),console.log(` Auto-PR: ${s.autoPR?a.green("Yes"):"No"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Manage: ${a.dim("mc schedule list")}`),console.log("")}l(sl,"scheduleCreate");async function ng(){let e=await _n().list();if(e.length===0){console.log(a.dim(" No scheduled jobs found.")),console.log(a.dim(' Create one: mc schedule "your task" --cron "0 9 * * 1"'));return}let t=" "+"\u2500".repeat(90);console.log(t),console.log(a.bold(` ${"ID".padEnd(16)} ${"Status".padEnd(10)} ${"Cron".padEnd(16)} ${"Next Run".padEnd(20)} Prompt`)),console.log(t);for(let o of e){let n=o.status==="active"?a.green("\u25B6 Active"):a.yellow("\u23F8 Paused"),r=o.nextRunAt?o.nextRunAt.toLocaleString():"\u2014",i=o.prompt.length>30?`"${o.prompt.substring(0,28)}..."`:`"${o.prompt}"`;console.log(` ${o.id.padEnd(16)} ${n.padEnd(10)} ${o.cronExpression.padEnd(16)} ${r.padEnd(20)} ${i}`)}console.log(t)}l(ng,"scheduleList");async function rg(s){let t=await _n().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(rg,"scheduleDelete");async function ig(s){let t=await _n().togglePause(s,!0);t.success?console.log(a.yellow(` \u23F8 Schedule ${s} paused.`)):console.error(a.red(` \u274C Failed to pause schedule: ${t.error}`))}l(ig,"schedulePause");async function ag(s){let t=await _n().togglePause(s,!1);t.success?console.log(a.green(` \u25B6 Schedule ${s} resumed.`)):console.error(a.red(` \u274C Failed to resume schedule: ${t.error}`))}l(ag,"scheduleResume");function dk(s){return{id:s.id||s.scheduleId,prompt:s.prompt||"",cronExpression:s.cronExpression||s.cron||"",model:s.model||"default",status:s.status||"active",autoBranch:s.autoBranch??!1,autoCommit:s.autoCommit??!1,autoPR:s.autoPR??!1,nextRunAt:s.nextRunAt?new Date(s.nextRunAt):void 0,lastRunAt:s.lastRunAt?new Date(s.lastRunAt):void 0,lastJobId:s.lastJobId,runCount:s.runCount||0,createdAt:new Date(s.createdAt||Date.now())}}l(dk,"parseSchedule");function pk(s){let e=s.trim().split(/\s+/);if(e.length!==5)return!1;let t=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return e.every(o=>t.test(o))}l(pk,"validateCron");function mk(s){let e=s.trim().split(/\s+/);if(e.length!==5)return s;let[t,o,n,r,i]=e;return s==="0 * * * *"?"every hour":s==="*/5 * * * *"?"every 5 minutes":s==="*/15 * * * *"?"every 15 minutes":s==="*/30 * * * *"?"every 30 minutes":t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i==="*"?`daily at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[i]||`day ${i}`}s at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:s}l(mk,"describeCron");Ec();Cc();ln();var ke=y(require("node:fs"),1),St=y(require("node:path"),1),Lo=require("node:child_process");U();Je();Q();oe();async function cg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=J(),n,r;if(s.pr?(n=await yk(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Lo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Lo.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Lo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes")),!n.trim()){console.log(a.dim(" No changes to review."));return}let i=fk(s.workspace),c=s.focus?s.focus.split(",").map(b=>b.trim()):[],u=gk(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new Se({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",b=>{b.type==="streaming_chunk"&&(p+=b.content,s.output==="text"&&process.stdout.write(b.content))});try{await d.run(u)}catch(b){console.error(a.red(` \u274C Review failed: ${b instanceof Error?b.message:b}`)),process.exit(1)}let f=ug(p);switch(s.output){case"json":{let b=new ds;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let b=new ps(f,s.workspace);console.log(b.formatFindings(f));break}case"github":{for(let b of f){let k=b.severity==="high"?"error":b.severity==="medium"?"warning":"notice";console.log(`::${k} file=${b.file},line=${b.line}::${b.message}`)}break}case"text":default:f.length>0&&(console.log(""),dg(f));break}s.postComments&&s.pr&&await bk(s.pr,f,s.workspace),s.autoFix&&f.some(b=>b.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),pg(f,s.workspace));let m={high:3,medium:2,low:1,info:0},g=m[s.severityThreshold]||3;f.some(b=>(m[b.severity]||0)>=g)&&process.exit(1)}l(cg,"reviewCommand");async function lg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=J(),n=St.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=wk(n,[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java"]):r=[n]:(console.error(a.red(` \u274C Target not found: ${s.target}`)),process.exit(4)),r.length===0){console.log(a.dim(" No source files found to scan."));return}console.log(""),console.log(a.bold(` \u{1F50D} Bug Finder \u2014 scanning ${r.length} file(s)`)),console.log(a.dim(` Model: ${s.model}`)),console.log("");let i=1e5,c="",u=[];for(let v of r){let x=ke.readFileSync(v,"utf8");if(c.length+x.length>i)break;let _=St.relative(s.workspace,v);c+=`
|
|
652
|
+
`.trim()}l(Xf,"generateHtmlPreview");var tl=class{static{l(this,"DesignServer")}server;wss;port=3030;currentHtml="<h1>Waiting for design...</h1>";constructor(){this.server=Qf.createServer((e,t)=>{e.url==="/"?(t.writeHead(200,{"Content-Type":"text/html"}),t.end(Xf(this.currentHtml).replace("__PORT__",String(this.port)))):(t.writeHead(404),t.end("Not found"))}),this.wss=new ic.default({server:this.server,path:"/ws"})}start(e=3030){this.port=e,this.server.listen(e,()=>{console.log(a.green(`\u{1F3A8} Design artboard live at http://localhost:${e}`))})}stop(){this.wss.close(),this.server.close()}updateDesign(e){this.currentHtml=e;for(let t of this.wss.clients)t.readyState===rt.OPEN&&t.send("reload")}},Zf=new tl;U();function lk(s){let e=new Date(s),o=new Date().getTime()-s,n=Math.floor(o/6e4),r=Math.floor(o/36e5),i=Math.floor(o/864e5);return n<1?"just now":n<60?`${n}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:e.toLocaleDateString()}l(lk,"formatDate");function ri(s){return s.substring(0,8)}l(ri,"formatShortId");function uk(s,e=40){return s.length<=e?s:`\u2026${s.substring(s.length-e+1)}`}l(uk,"truncatePath");function eg(){let e=new jt().list();if(e.length===0){console.log(a.dim(" No saved sessions.")),console.log(a.dim(" Sessions are automatically saved when you use the CLI."));return}console.log(""),console.log(a.bold(" Recent Sessions")),console.log(a.dim(" \u2500".repeat(35))),console.log(""),console.log(a.dim(" ")+a.bold("ID".padEnd(10))+a.bold("Workspace".padEnd(42))+a.bold("Turns".padEnd(8))+a.bold("Last Active".padEnd(14))+a.bold("Preview")),console.log(a.dim(" "+"\u2500".repeat(90)));for(let t of e){let o=a.hex("#6B8DD6")(ri(t.id)),n=uk(t.workspace),r=String(t.turnCount).padEnd(8),i=lk(t.lastActive).padEnd(14),c=a.dim(t.preview.substring(0,30));console.log(` ${o} ${n.padEnd(40)} ${r}${i}${c}`)}console.log(""),console.log(a.dim(` ${e.length} session(s). Use "mc sessions show <id>" for details.`)),console.log("")}l(eg,"sessionsListCommand");function tg(s){let e=new jt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.load(o.id);if(!n){console.log(a.red(` \u2717 Failed to load session "${o.id}".`));return}if(console.log(""),console.log(a.bold(` Session ${ri(n.id)}`)),console.log(a.dim(" \u2500".repeat(35))),console.log(` ${a.bold("ID:")} ${n.id}`),console.log(` ${a.bold("Workspace:")} ${n.workspace}`),console.log(` ${a.bold("Model:")} ${n.model}`),console.log(` ${a.bold("Mode:")} ${n.mode}`),console.log(` ${a.bold("Started:")} ${new Date(n.startTime).toLocaleString()}`),console.log(` ${a.bold("Last active:")} ${new Date(n.lastActive).toLocaleString()}`),console.log(` ${a.bold("Turns:")} ${n.turnCount}`),console.log(` ${a.bold("Tokens:")} ${n.stats.tokensUsed.toLocaleString()}`),console.log(` ${a.bold("Tool calls:")} ${n.stats.toolCalls}`),n.stats.filesChanged.length>0){console.log(` ${a.bold("Files changed:")}`);for(let r of n.stats.filesChanged.slice(0,10))console.log(` ${r}`);n.stats.filesChanged.length>10&&console.log(a.dim(` ... and ${n.stats.filesChanged.length-10} more`))}console.log(""),console.log(a.bold(" Conversation:")),console.log(a.dim(" \u2500".repeat(35)));for(let r of n.messages.slice(-10)){let i=r.role==="user"?a.hex("#6B8DD6").bold("You"):r.role==="assistant"?a.hex("#A3CAD3").bold("MC"):a.dim("System"),c=new Date(r.timestamp).toLocaleTimeString(),u=r.content.substring(0,120).replace(/\n/g," ");console.log(` ${a.dim(c)} ${i}: ${u}`)}n.messages.length>10&&console.log(a.dim(` ... ${n.messages.length-10} earlier messages`)),console.log(""),console.log(a.dim(` Resume with: mc --continue ${ri(n.id)}`)),console.log("")}l(tg,"sessionsShowCommand");function og(s){let e=new jt,o=e.list().find(r=>r.id===s||r.id.startsWith(s));if(!o){console.log(a.red(` \u2717 Session "${s}" not found.`));return}let n=e.delete(o.id);console.log(n?a.green(` \u2713 Deleted session ${ri(o.id)}`):a.red(` \u2717 Failed to delete session "${o.id}".`))}l(og,"sessionsDeleteCommand");function sg(s=30){let e=new jt,t=s*24*60*60*1e3,{deleted:o,remaining:n}=e.prune(t);console.log(o===0?a.dim(` No sessions older than ${s} days.`):a.green(` \u2713 Pruned ${o} session(s) older than ${s} days.`)),console.log(a.dim(` ${n} session(s) remaining.`))}l(sg,"sessionsPruneCommand");sn();U();Q();oe();var ol=class{static{l(this,"ScheduleApiClient")}baseUrl;token;constructor(e,t){this.baseUrl=`${e}/api/schedules`,this.token=t}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async create(e){try{let t=await fetch(this.baseUrl,{method:"POST",headers:this.headers(),body:JSON.stringify({prompt:e.prompt,cronExpression:e.cron,model:e.model,autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPR,workspace:e.workspace}),signal:AbortSignal.timeout(1e4)});if(!t.ok){let n=await t.text().catch(()=>"");return{success:!1,error:`HTTP ${t.status}: ${n}`}}let o=await t.json();return{success:!0,scheduleId:o.id||o.scheduleId}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async list(){try{let e=await fetch(this.baseUrl,{headers:this.headers(),signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).schedules||[]).map(dk):[]}catch{return[]}}async delete(e){try{let t=await fetch(`${this.baseUrl}/${e}`,{method:"DELETE",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:t.ok,error:t.ok?void 0:`HTTP ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async togglePause(e,t){try{let o=await fetch(`${this.baseUrl}/${e}/${t?"pause":"resume"}`,{method:"POST",headers:this.headers(),signal:AbortSignal.timeout(1e4)});return{success:o.ok,error:o.ok?void 0:`HTTP ${o.status}`}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}};function _n(){let s=z(),t=me()?.access_token;return t||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3)),new ol(s.platformUrl,t)}l(_n,"getClient");async function sl(s){pk(s.cron)||(console.error(a.red(` \u274C Invalid cron expression: "${s.cron}"`)),console.log(a.dim(" Expected 5-field format: minute hour day-of-month month day-of-week")),console.log(a.dim(' Example: "0 9 * * 1" = Every Monday at 9:00 AM')),process.exit(4));let t=await _n().create(s);t.success||(console.error(a.red(` \u274C Failed to create schedule: ${t.error}`)),process.exit(1)),console.log(""),console.log(a.bold(" \u23F0 Schedule created")),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` ID: ${a.cyan(t.scheduleId)}`),console.log(` Prompt: "${s.prompt.substring(0,50)}${s.prompt.length>50?"...":""}"`),console.log(` Cron: ${s.cron} (${mk(s.cron)})`),console.log(` Auto-PR: ${s.autoPR?a.green("Yes"):"No"}`),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(` Manage: ${a.dim("mc schedule list")}`),console.log("")}l(sl,"scheduleCreate");async function ng(){let e=await _n().list();if(e.length===0){console.log(a.dim(" No scheduled jobs found.")),console.log(a.dim(' Create one: mc schedule "your task" --cron "0 9 * * 1"'));return}let t=" "+"\u2500".repeat(90);console.log(t),console.log(a.bold(` ${"ID".padEnd(16)} ${"Status".padEnd(10)} ${"Cron".padEnd(16)} ${"Next Run".padEnd(20)} Prompt`)),console.log(t);for(let o of e){let n=o.status==="active"?a.green("\u25B6 Active"):a.yellow("\u23F8 Paused"),r=o.nextRunAt?o.nextRunAt.toLocaleString():"\u2014",i=o.prompt.length>30?`"${o.prompt.substring(0,28)}..."`:`"${o.prompt}"`;console.log(` ${o.id.padEnd(16)} ${n.padEnd(10)} ${o.cronExpression.padEnd(16)} ${r.padEnd(20)} ${i}`)}console.log(t)}l(ng,"scheduleList");async function rg(s){let t=await _n().delete(s);t.success?console.log(a.green(` \u2705 Schedule ${s} deleted.`)):console.error(a.red(` \u274C Failed to delete schedule: ${t.error}`))}l(rg,"scheduleDelete");async function ig(s){let t=await _n().togglePause(s,!0);t.success?console.log(a.yellow(` \u23F8 Schedule ${s} paused.`)):console.error(a.red(` \u274C Failed to pause schedule: ${t.error}`))}l(ig,"schedulePause");async function ag(s){let t=await _n().togglePause(s,!1);t.success?console.log(a.green(` \u25B6 Schedule ${s} resumed.`)):console.error(a.red(` \u274C Failed to resume schedule: ${t.error}`))}l(ag,"scheduleResume");function dk(s){return{id:s.id||s.scheduleId,prompt:s.prompt||"",cronExpression:s.cronExpression||s.cron||"",model:s.model||"default",status:s.status||"active",autoBranch:s.autoBranch??!1,autoCommit:s.autoCommit??!1,autoPR:s.autoPR??!1,nextRunAt:s.nextRunAt?new Date(s.nextRunAt):void 0,lastRunAt:s.lastRunAt?new Date(s.lastRunAt):void 0,lastJobId:s.lastJobId,runCount:s.runCount||0,createdAt:new Date(s.createdAt||Date.now())}}l(dk,"parseSchedule");function pk(s){let e=s.trim().split(/\s+/);if(e.length!==5)return!1;let t=/^(\*|[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)*)(\/[0-9]+)?$/;return e.every(o=>t.test(o))}l(pk,"validateCron");function mk(s){let e=s.trim().split(/\s+/);if(e.length!==5)return s;let[t,o,n,r,i]=e;return s==="0 * * * *"?"every hour":s==="*/5 * * * *"?"every 5 minutes":s==="*/15 * * * *"?"every 15 minutes":s==="*/30 * * * *"?"every 30 minutes":t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i==="*"?`daily at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:t!=="*"&&o!=="*"&&n==="*"&&r==="*"&&i!=="*"?`${{0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}[i]||`day ${i}`}s at ${o.padStart(2,"0")}:${t.padStart(2,"0")}`:s}l(mk,"describeCron");Ec();Cc();ln();var ke=y(require("node:fs"),1),St=y(require("node:path"),1),Bo=require("node:child_process");U();ze();Q();oe();async function cg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=z(),n,r;if(s.pr?(n=await yk(s.pr,s.workspace),r=`PR #${s.pr}`):s.staged?(n=(0,Bo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes"):(n=(0,Bo.execSync)("git diff",{cwd:s.workspace,encoding:"utf8"}),n.trim()?r="unstaged changes":(n=(0,Bo.execSync)("git diff --cached",{cwd:s.workspace,encoding:"utf8"}),r="staged changes")),!n.trim()){console.log(a.dim(" No changes to review."));return}let i=fk(s.workspace),c=s.focus?s.focus.split(",").map(b=>b.trim()):[],u=gk(n,r,c,i);console.log(""),console.log(a.bold(` \u{1F50D} Reviewing ${r}...`)),console.log(a.dim(` Model: ${s.model}`)),c.length>0&&console.log(a.dim(` Focus: ${c.join(", ")}`)),console.log("");let d=new Se({platformUrl:o.platformUrl,token:e,model:s.model,workspace:s.workspace,mode:"plan",maxTurns:5,sandboxed:!0,webEnabled:!1,effort:"reasoning",userId:t?.user?.id,orgId:t?.org?.id}),p="";d.on("event",b=>{b.type==="streaming_chunk"&&(p+=b.content,s.output==="text"&&process.stdout.write(b.content))});try{await d.run(u)}catch(b){console.error(a.red(` \u274C Review failed: ${b instanceof Error?b.message:b}`)),process.exit(1)}let f=ug(p);switch(s.output){case"json":{let b=new ds;console.log(JSON.stringify({source:r,findings:f,summary:`Found ${f.length} issue(s)`},null,2));break}case"sarif":{let b=new ps(f,s.workspace);console.log(b.formatFindings(f));break}case"github":{for(let b of f){let k=b.severity==="high"?"error":b.severity==="medium"?"warning":"notice";console.log(`::${k} file=${b.file},line=${b.line}::${b.message}`)}break}case"text":default:f.length>0&&(console.log(""),dg(f));break}s.postComments&&s.pr&&await bk(s.pr,f,s.workspace),s.autoFix&&f.some(b=>b.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),pg(f,s.workspace));let m={high:3,medium:2,low:1,info:0},g=m[s.severityThreshold]||3;f.some(b=>(m[b.severity]||0)>=g)&&process.exit(1)}l(cg,"reviewCommand");async function lg(s){let e=await Ae(void 0);e||(console.error(a.red(" \u274C Not authenticated. Run `mc auth login` first.")),process.exit(3));let t=me(),o=z(),n=St.resolve(s.workspace,s.target),r=[];if(ke.existsSync(n)?ke.statSync(n).isDirectory()?r=wk(n,[".ts",".tsx",".js",".jsx",".py",".go",".rs",".java"]):r=[n]:(console.error(a.red(` \u274C Target not found: ${s.target}`)),process.exit(4)),r.length===0){console.log(a.dim(" No source files found to scan."));return}console.log(""),console.log(a.bold(` \u{1F50D} Bug Finder \u2014 scanning ${r.length} file(s)`)),console.log(a.dim(` Model: ${s.model}`)),console.log("");let i=1e5,c="",u=[];for(let v of r){let x=ke.readFileSync(v,"utf8");if(c.length+x.length>i)break;let _=St.relative(s.workspace,v);c+=`
|
|
651
653
|
--- ${_} ---
|
|
652
654
|
${x}
|
|
653
655
|
`,u.push(_)}let d=s.focus?s.focus.split(",").map(v=>v.trim()):[],p=hk(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",v=>{v.type==="streaming_chunk"&&(m+=v.content)});try{await f.run(p)}catch(v){console.error(a.red(` \u274C Bug scan failed: ${v instanceof Error?v.message:v}`)),process.exit(1)}let g=ug(m);switch(s.output){case"json":console.log(JSON.stringify({scannedFiles:u,findings:g,summary:nl(g)},null,2));break;case"sarif":{let v=new ps(g,s.workspace);console.log(v.formatFindings(g));break}case"github":for(let v of g){let x=v.severity==="high"?"error":v.severity==="medium"?"warning":"notice";console.log(`::${x} file=${v.file},line=${v.line}::${v.message}`)}break;case"text":default:dg(g);break}s.autoFix&&g.some(v=>v.fix)&&(console.log(""),console.log(a.bold(" \u{1F527} Applying auto-fixes...")),pg(g,s.workspace));let h={high:3,medium:2,low:1,info:0},b=h[s.severityThreshold]||3;g.some(v=>(h[v.severity]||0)>=b)&&process.exit(1)}l(lg,"bugfindCommand");function fk(s){let e=St.join(s,".monkeyscode","review-rules.md");return ke.existsSync(e)?ke.readFileSync(e,"utf8"):""}l(fk,"loadReviewRules");function gk(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.
|
|
@@ -687,24 +689,24 @@ Focus on:
|
|
|
687
689
|
${s}`,o}l(hk,"buildBugfindPrompt");function ug(s){let e=[],t=s.split(`
|
|
688
690
|
`);for(let o=0;o<t.length;o++){let r=t[o].match(/\[SEVERITY:(HIGH|MEDIUM|LOW|INFO)\]\s*\[FILE:([^\]]+)\]\s*\[LINE:(\d+)\]\s*(.*)/i);if(r){let i={severity:r[1].toLowerCase(),file:r[2],line:parseInt(r[3],10),message:r[4].trim()};if(o+1<t.length){let c=t[o+1].match(/\[FIX:\d+\]\s*(.*)/);c&&(i.fix=c[1],o++)}e.push(i)}}return e}l(ug,"parseFindings");function dg(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(` ${nl(s)}`),console.log("")}l(dg,"printFindingsTable");function nl(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(nl,"formatSeveritySummary");function pg(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
691
|
`);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(pg,"applyFixes");async function yk(s,e){let t=mg(e),o=fg();if(!o){console.log(a.dim(" No GitHub/GitLab token found. Using local git diff against main."));try{return(0,
|
|
692
|
+
`)),t++,console.log(a.dim(` \u2713 Fixed ${o.file}:${o.line}`)))}catch{console.log(a.yellow(` \u26A0 Could not apply fix to ${o.file}:${o.line}`))}}console.log(` Applied ${t} fix(es).`)}l(pg,"applyFixes");async function yk(s,e){let t=mg(e),o=fg();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
693
|
`)||""}throw new Error(`Unsupported remote: ${t.url}`)}l(yk,"fetchPRDiff");async function bk(s,e,t){let o=mg(t),n=fg();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
694
|
`);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
695
|
|
|
694
696
|
${r}
|
|
695
697
|
|
|
696
|
-
${nl(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(bk,"postReviewComments");function mg(s){try{let e=(0,
|
|
698
|
+
${nl(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(bk,"postReviewComments");function mg(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(mg,"getGitRemote");function fg(){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(fg,"getGitToken");function wk(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(wk,"collectFiles");Jm();Im();globalThis.__mcChalk=a;var ai="0.1.3",Wo="auto";function bg(s){let e=Mo(s);return{defaultModel:e.get("model"),defaultMode:e.get("defaultMode"),maxTokens:e.get("maxTokens")}}l(bg,"loadConfig");var q=new Sl;q.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
|
|
697
699
|
Runs independently of the IDE and Agent Manager.
|
|
698
|
-
Connects directly to model-proxy via SSE streaming.`).version(ai);q.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",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=bg(t),n=s||e.prompt;if(n&&n.startsWith("/"))switch(n.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":n=void 0;break;case"/version":case"/v":console.log(ai),process.exit(0);break;case"/doctor":await on(),process.exit(0);break;case"/exit":case"/quit":case"/q":process.exit(0);break;default:break}if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=gt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await am(c)});var Fn=q.command("auth").description("Manage authentication");Fn.command("login").description("Authenticate with MonkeysCode (device code flow \u2014 opens browser)").option("--email","Use email/password login instead of browser").option("--sso","Use enterprise SSO (SAML/OIDC)").option("--profile <name>","Auth profile name","default").action(async s=>{s.sso?await ha(s.profile):s.email?await ua():await la()});Fn.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ya(s.profile));Fn.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>pa(s,e.profile));Fn.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await Yn(s.profile));Fn.command("refresh").description("Manually refresh the access token").action(async()=>await ma());q.command("status").description("Show account and agent status").action(async()=>{let s=bg(),e=new vo,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),o=t();e.printBanner("System Status"),await Yn(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});q.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>on(s));q.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Rm(s));q.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Wm(s));q.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Hm(s,e));q.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";Ym({since:s.since,review:s.review,mode:e})});var Tn=q.command("config").description("Manage CLI configuration");Tn.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=N.resolve(t.workspace),n=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}]`)});Tn.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))});Tn.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));Dm(e)});Tn.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.`)});Tn.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 Rn=q.command("mcp").description("Manage MCP (Model Context Protocol) servers");Rn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await pm(N.resolve(s.workspace))});Rn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{mm(N.resolve(o.workspace),s,e,t||[])});Rn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{fm(N.resolve(e.workspace),s)});Rn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await gm(N.resolve(e.workspace),s)});Rn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{hm(s)});var Tk=q.command("agents").description("View active agent sessions dashboard").action(async()=>{await Ac(!0)});Tk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Ac(!1)});var Ss=q.command("context").description("Semantic code search and workspace indexing");Ss.command("index").description("Index the current workspace for semantic search").action(async()=>{await Io(["index"],{})});Ss.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await Io(["search",s],{topK:e.topK})});Ss.command("status").description("Show index status and statistics").action(async()=>{await Io(["status"],{})});Ss.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await Io(["rebuild"],{})});Ss.command("related <file>").description("Find files related to a given file").action(async s=>{await Io(["related",s],{})});Ss.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(lm(o)),console.log("")):console.log(cm(o))});var li=q.command("sessions").description("Manage saved conversation sessions");li.command("list").description("List recent sessions").action(()=>eg());li.command("show <id>").description("Show session details").action(s=>tg(s));li.command("delete <id>").description("Delete a session").action(s=>og(s));li.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{sg(parseInt(s.olderThan,10))});var 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(gc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);wc(d)});Kt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=hc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=yc(s);jr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Oe(o.platformUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);jr(i,c)});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))Nr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(yg(),hg));u(s,`"${c.prompt.substring(0,60)}" \u2014 ${c.status}${c.duration?` in ${Math.round(c.duration/1e3)}s`:""}`,c.status==="completed")}}else{let c=await i.logs(s);for(let u of c)Nr(u)}});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)),bc(N.resolve(e.workspace),s,c.branch)});Kt.action(()=>{Kt.outputHelp()});var Bo=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",".");Bo.action(async(s,e)=>{s&&e.cron?await sl({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Bo.outputHelp()});Bo.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 sl({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)})});Bo.command("list").description("List all scheduled jobs").action(async()=>{await ng()});Bo.command("delete <id>").description("Delete a scheduled job").action(async s=>{await rg(s)});Bo.command("pause <id>").description("Pause a scheduled job").action(async s=>{await ig(s)});Bo.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await ag(s)});var En=q.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",Uo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");En.action(async(s,e)=>{s.length>0?await Lr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):En.outputHelp()});En.command("spawn").description("Spawn a team of agents, each in its own worktree").argument("<tasks...>","Task prompts for each agent").option("--model <model>","Model to use",Uo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Lr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});En.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{$c(N.resolve(s.workspace))});En.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{_c(N.resolve(e.workspace),s)});var ci=q.command("worktrees").description("Manage git worktrees used by agent teams");ci.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=fs(N.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});ci.command("clean").description("Remove stale worktrees older than TTL").option("--ttl <hours>","TTL in hours (default: 24)","24").option("--force","Force removal",!1).option("--workspace <path>","Workspace path",".").action(s=>{let e=zp({workspace:N.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});ci.action(()=>{ci.outputHelp()});var cl=q.command("messages").description("Cross-session messaging");cl.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new cn(o.platformUrl,n.access_token,"cli").getMessageHistory(parseInt(s.limit,10));if(i.length===0){console.log(" No recent messages.");return}console.log(" \u{1F4E8} Recent Messages");let c=" "+"\u2500".repeat(70);console.log(c),console.log(` ${"Time".padEnd(12)} ${"From".padEnd(16)} ${"To".padEnd(16)} Message`),console.log(c);for(let u of i){let d=u.timestamp.toLocaleTimeString(),p=u.from.substring(0,14),f=u.to==="broadcast"?"[broadcast]":u.to.substring(0,14),m=u.content.substring(0,40)+(u.content.length>40?"...":"");console.log(` ${d.padEnd(12)} ${p.padEnd(16)} ${f.padEnd(16)} "${m}"`)}console.log(c)});cl.action(()=>{cl.outputHelp()});var wg=q.command("hooks").description("Manage lifecycle hooks");wg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Pc(N.resolve(s.workspace))});wg.action(()=>{Pc(N.resolve("."))});var kg=q.command("models").description("Manage available models");kg.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();$a(s?.org?.plan)});kg.action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();$a(s?.org?.plan)});q.command("usage").description("Show monthly usage breakdown").action(async()=>{await vm()});q.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md"),o=N.join(e,".monkeyscode","config.json");if(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.`)),
|
|
700
|
+
Connects directly to model-proxy via SSE streaming.`).version(ai);q.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",Wo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Et("-o, --output <format>","Output format").choices(["text","json","jsonl","diff","markdown","github","azure","sarif","stream"]).default("text")).option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("--continue","Resume the last session",!1).option("--auto-approve","Auto-approve all tool calls",!1).option("--approve-for-me","Smart auto-approval (safe=auto, risky=prompt, dangerous=block)",!1).option("--yolo","Bypass all permission checks (requires explicit opt-in)",!1).addOption(new Et("--permission-mode <mode>","Permission mode").choices(["default","plan","ask","acceptEdits","bypassPermissions"]).default("default")).option("--allowed-tools <tools>","Comma-separated list of allowed tool names","").option("--denied-tools <tools>","Comma-separated list of denied tool names","").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new Et("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Et("--sandbox-provider <provider>","Sandbox provider override").choices(["auto","bubblewrap","sandbox-exec","docker","windows-sandbox"])).option("--no-hooks","Disable all lifecycle hooks").option("--hook-timeout <ms>","Hook timeout in milliseconds","10000").option("--no-web","Disable web search (air-gapped mode)").option("--auto-branch","Create a new branch for changes",!1).option("--auto-commit","Auto-commit changes after successful run",!1).option("--auto-pr","Create a pull request after background job completes",!1).option("--worktree","Run agent in an isolated git worktree",!1).option("--resume <job-id>","Resume from a completed cloud job").option("--profile <name>","Auth profile to use","default").option("--endpoint <url>","Custom model gateway URL").option("--ca-cert <path>","Custom CA certificate for corporate proxies").option("--offline","Offline mode \u2014 no internet, local models only",!1).option("--accessible","Screen reader-friendly output (no ANSI, no spinners)",!1).option("--screen-reader","Alias for --accessible",!1).option("--max-cost <dollars>","Maximum session cost in dollars (e.g. 2.00)").option("--max-tokens <count>","Maximum total tokens (input + output)").option("--timeout <ms>","Headless timeout in milliseconds (default: 300000)","300000").action(async(s,e)=>{let t=N.resolve(e.workspace),o=bg(t),n=s||e.prompt;if(n&&n.startsWith("/"))switch(n.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":n=void 0;break;case"/version":case"/v":console.log(ai),process.exit(0);break;case"/doctor":await on(),process.exit(0);break;case"/exit":case"/quit":case"/q":process.exit(0);break;default:break}if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=gt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await am(c)});var Fn=q.command("auth").description("Manage authentication");Fn.command("login").description("Authenticate with MonkeysCode (device code flow \u2014 opens browser)").option("--email","Use email/password login instead of browser").option("--sso","Use enterprise SSO (SAML/OIDC)").option("--profile <name>","Auth profile name","default").action(async s=>{s.sso?await ha(s.profile):s.email?await ua():await la()});Fn.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ya(s.profile));Fn.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>pa(s,e.profile));Fn.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await Yn(s.profile));Fn.command("refresh").description("Manually refresh the access token").action(async()=>await ma());q.command("status").description("Show account and agent status").action(async()=>{let s=bg(),e=new So,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),o=t();e.printBanner("System Status"),await Yn(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});q.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>on(s));q.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Rm(s));q.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Wm(s));q.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Hm(s,e));q.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";Ym({since:s.since,review:s.review,mode:e})});var Tn=q.command("config").description("Manage CLI configuration");Tn.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=N.resolve(t.workspace),n=Mo(o),r=t.project?"project":"global",i=e;e==="true"?i=!0:e==="false"?i=!1:isNaN(Number(e))||(i=Number(e));let c=n.set(s,i,r);c&&(console.error(` \u26A0\uFE0F ${c}`),process.exit(1)),console.log(` Set ${s} = ${e} [${r}]`)});Tn.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=Mo(N.resolve(e.workspace));if(s){let o=t.getResolved(s);console.log(` ${s} = ${JSON.stringify(o.value)} [${o.source}]`)}else console.log(JSON.stringify(t.getConfig(),null,2))});Tn.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=Mo(N.resolve(s.workspace));Dm(e)});Tn.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{Mo().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});Tn.command("path").description("Show config file locations").action(()=>{let s=T(),t=Mo().getPaths();console.log(` Global: ${t.global}`),console.log(` Project: ${t.project}`),console.log(` Data: ${s.data}`),console.log(` Logs: ${s.logs}`),console.log(` PID: ${s.pidFile}`)});q.command("index [path]").description("Index a workspace for context retrieval").option("--force","Force full re-index",!1).action(async(s,e)=>{let t=N.resolve(s||"."),o=new So;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new co;o.startSpinner("Connecting to daemon...");try{await n.connect(),o.succeedSpinner("Connected"),o.startSpinner("Indexing workspace...");let r=await n.call("index",{workspace:t,force:e.force});o.succeedSpinner("Indexing complete"),console.log(` Files scanned: ${r.files_scanned}`),console.log(` Chunks created: ${r.chunks_created}`),console.log(` Duration: ${r.duration_ms}ms`),console.log("")}catch(r){o.failSpinner("Indexing failed"),console.error(` Error: ${r instanceof Error?r.message:r}`)}finally{n.disconnect()}});var Rn=q.command("mcp").description("Manage MCP (Model Context Protocol) servers");Rn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await pm(N.resolve(s.workspace))});Rn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{mm(N.resolve(o.workspace),s,e,t||[])});Rn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{fm(N.resolve(e.workspace),s)});Rn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await gm(N.resolve(e.workspace),s)});Rn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{hm(s)});var Tk=q.command("agents").description("View active agent sessions dashboard").action(async()=>{await Ac(!0)});Tk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Ac(!1)});var Ss=q.command("context").description("Semantic code search and workspace indexing");Ss.command("index").description("Index the current workspace for semantic search").action(async()=>{await jo(["index"],{})});Ss.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await jo(["search",s],{topK:e.topK})});Ss.command("status").description("Show index status and statistics").action(async()=>{await jo(["status"],{})});Ss.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await jo(["rebuild"],{})});Ss.command("related <file>").description("Find files related to a given file").action(async s=>{await jo(["related",s],{})});Ss.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await jo(["rank",s],{})});var Ho=q.command("triggers").description("Manage event-driven agent triggers");Ho.command("list").description("Show configured triggers").action(async()=>{await fo(["list"],{})});Ho.command("add").description("Add a new trigger").requiredOption("--event <type>","Event type (github.*, cron, file.changed)").requiredOption("--prompt <text>","Agent prompt when trigger fires").option("--name <name>","Trigger name").option("--schedule <cron>","Cron expression (for cron events)").option("--model <model>","Model to use").option("--filter <json>","Event filter (JSON)").action(async s=>{await fo(["add"],s)});Ho.command("remove <name>").description("Remove a trigger by name").action(async s=>{await fo(["remove",s],{})});Ho.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await fo(["test",s],{})});Ho.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await fo(["enable",s],{})});Ho.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await fo(["disable",s],{})});Ho.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await fo(["serve"],{port:s.port})});q.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish, pwsh)").option("--install","Show install instructions instead of the script").action((s,e)=>{let t=["bash","zsh","fish","pwsh"];t.includes(s)||(console.error(` Invalid shell: ${s}. Supported: ${t.join(", ")}`),process.exit(1));let o=s;e.install?(console.log(""),console.log(lm(o)),console.log("")):console.log(cm(o))});var li=q.command("sessions").description("Manage saved conversation sessions");li.command("list").description("List recent sessions").action(()=>eg());li.command("show <id>").description("Show session details").action(s=>tg(s));li.command("delete <id>").description("Delete a session").action(s=>og(s));li.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{sg(parseInt(s.olderThan,10))});var Yt=q.command("jobs").description("Manage background agent jobs");Yt.command("list").description("List all background jobs").option("--status <status>","Filter by status: running, queued, completed, failed").option("--since <duration>","Show jobs since (e.g., 7d, 24h)").option("--limit <n>","Max results","20").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Oe(o.platformUrl,n.access_token),i=parseInt(s.limit,10),[c,u]=await Promise.all([r.list({status:s.status,since:s.since,limit:i}).catch(()=>[]),Promise.resolve(gc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);wc(d)});Yt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=hc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=yc(s);jr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Oe(o.platformUrl,n.access_token),i=await r.status(s);i||(console.error(`Job ${s} not found.`),process.exit(1));let c=await r.logs(s);jr(i,c)});Yt.command("logs <id>").description("Full log output of a job").option("--follow","Live tail logs",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Oe(n.platformUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Nr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(yg(),hg));u(s,`"${c.prompt.substring(0,60)}" \u2014 ${c.status}${c.duration?` in ${Math.round(c.duration/1e3)}s`:""}`,c.status==="completed")}}else{let c=await i.logs(s);for(let u of c)Nr(u)}});Yt.command("cancel <id>").description("Cancel a running or queued job").option("--force","Skip confirmation",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();if(r?.access_token||(console.error("Not authenticated."),process.exit(3)),!e.force){let d=(await import("node:readline")).createInterface({input:process.stdin,output:process.stdout}),p=await new Promise(f=>d.question(` Cancel job ${s}? [y/N] `,f));if(d.close(),p.toLowerCase()!=="y"){console.log(" Cancelled.");return}}let c=await new Oe(n.platformUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Yt.command("retry <id>").description("Retry a failed job").option("--model <model>","Use a different model").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Oe(n.platformUrl,r.access_token).retry(s,{model:e.model});c.success?(console.log(` \u{1F504} Job retried \u2192 new ID: ${c.jobId}`),c.branch&&console.log(` Branch: ${c.branch}`)):console.error(` \u274C Retry failed: ${c.error}`)});Yt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Oe(o.platformUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Yt.command("pull <id>").description("Pull changes from a completed job into current branch").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:o}=await Promise.resolve().then(()=>(oe(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Oe(n.platformUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),bc(N.resolve(e.workspace),s,c.branch)});Yt.action(()=>{Yt.outputHelp()});var Uo=q.command("schedule").description("Manage scheduled/recurring agent jobs").argument("[prompt]","Task prompt (shorthand for `schedule create`)").option("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",Wo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".");Uo.action(async(s,e)=>{s&&e.cron?await sl({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Uo.outputHelp()});Uo.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",Wo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await sl({prompt:s,cron:e.cron,model:gt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:N.resolve(e.workspace)})});Uo.command("list").description("List all scheduled jobs").action(async()=>{await ng()});Uo.command("delete <id>").description("Delete a scheduled job").action(async s=>{await rg(s)});Uo.command("pause <id>").description("Pause a scheduled job").action(async s=>{await ig(s)});Uo.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await ag(s)});var En=q.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",Wo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");En.action(async(s,e)=>{s.length>0?await Lr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):En.outputHelp()});En.command("spawn").description("Spawn a team of agents, each in its own worktree").argument("<tasks...>","Task prompts for each agent").option("--model <model>","Model to use",Wo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Lr({tasks:s,workspace:N.resolve(e.workspace),model:gt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});En.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{$c(N.resolve(s.workspace))});En.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{_c(N.resolve(e.workspace),s)});var ci=q.command("worktrees").description("Manage git worktrees used by agent teams");ci.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=fs(N.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});ci.command("clean").description("Remove stale worktrees older than TTL").option("--ttl <hours>","TTL in hours (default: 24)","24").option("--force","Force removal",!1).option("--workspace <path>","Workspace path",".").action(s=>{let e=Jp({workspace:N.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});ci.action(()=>{ci.outputHelp()});var cl=q.command("messages").description("Cross-session messaging");cl.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),ve)),{loadAuth:t}=await Promise.resolve().then(()=>(oe(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new cn(o.platformUrl,n.access_token,"cli").getMessageHistory(parseInt(s.limit,10));if(i.length===0){console.log(" No recent messages.");return}console.log(" \u{1F4E8} Recent Messages");let c=" "+"\u2500".repeat(70);console.log(c),console.log(` ${"Time".padEnd(12)} ${"From".padEnd(16)} ${"To".padEnd(16)} Message`),console.log(c);for(let u of i){let d=u.timestamp.toLocaleTimeString(),p=u.from.substring(0,14),f=u.to==="broadcast"?"[broadcast]":u.to.substring(0,14),m=u.content.substring(0,40)+(u.content.length>40?"...":"");console.log(` ${d.padEnd(12)} ${p.padEnd(16)} ${f.padEnd(16)} "${m}"`)}console.log(c)});cl.action(()=>{cl.outputHelp()});var wg=q.command("hooks").description("Manage lifecycle hooks");wg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Pc(N.resolve(s.workspace))});wg.action(()=>{Pc(N.resolve("."))});var kg=q.command("models").description("Manage available models");kg.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();$a(s?.org?.plan)});kg.action(async()=>{let s=(await Promise.resolve().then(()=>(oe(),ge))).loadAuth();$a(s?.org?.plan)});q.command("usage").description("Show monthly usage breakdown").action(async()=>{await vm()});q.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=N.resolve(s.workspace),t=N.join(e,".monkeyscode","rules.md"),o=N.join(e,".monkeyscode","config.json");if(J.existsSync(t)&&J.existsSync(o)){console.log(""),console.log(a.yellow(" \u26A0\uFE0F .monkeyscode/ already exists.")),console.log(a.dim(` ${t}`)),console.log(a.dim(` ${o}`)),console.log(" Use `mc memory` to modify rules, `mc config set` for config."),console.log("");return}console.log(""),console.log(a.bold(" \u{1F435} Initializing MonkeysCode")),console.log("");let n=["# Project Conventions",""],r=N.join(e,"package.json"),i=N.join(e,"Cargo.toml"),c=N.join(e,"pyproject.toml"),u=N.join(e,"tsconfig.json"),d=N.join(e,"go.mod"),p=J.readdirSync(e).filter(h=>h.endsWith(".csproj")),f="Unknown";if(J.existsSync(r))try{let h=JSON.parse(J.readFileSync(r,"utf8"));f=h.type==="module"?"TypeScript/ESM":"JavaScript/CJS",n.push(`## Language: ${f}`),h.scripts?.test&&n.push(`- Test command: \`${h.scripts.test}\``),h.scripts?.lint&&n.push(`- Lint command: \`${h.scripts.lint}\``),h.scripts?.build&&n.push(`- Build command: \`${h.scripts.build}\``),h.dependencies?.react&&n.push("- Framework: React"),h.dependencies?.next&&n.push("- Framework: Next.js"),h.dependencies?.express&&n.push("- Server: Express"),h.dependencies?.fastify&&n.push("- Server: Fastify"),n.push("")}catch{}J.existsSync(u)&&(n.push("## TypeScript"),n.push("- Use strict TypeScript with explicit types"),n.push("- Prefer `interface` over `type` for object shapes"),n.push(""),f="TypeScript"),J.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),J.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),J.existsSync(d)&&(n.push("## Language: Go"),n.push("- Follow Go conventions (gofmt, error wrapping)"),n.push(""),f="Go"),p.length>0&&(n.push("## Language: C# / .NET"),n.push("- Follow .NET naming conventions (PascalCase)"),n.push(""),f="C#/.NET"),n.push("## Style"),n.push("- Keep functions small and focused"),n.push("- Write clear error messages"),n.push("- Add JSDoc/docstrings for public APIs"),n.push(""),n.push("## Testing"),n.push("- Write tests for all new functionality"),n.push("- Use descriptive test names"),n.push("");let m=n.join(`
|
|
701
|
+
`),g=Math.ceil(m.length/4);g>2e3&&console.log(a.yellow(` \u26A0\uFE0F Rules file is ~${g} tokens. Consider keeping it under 2000 for optimal context usage.`)),J.mkdirSync(N.join(e,".monkeyscode"),{recursive:!0}),J.writeFileSync(t,m,"utf8"),J.existsSync(o)||J.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 xs=q.command("memory").description("Manage project conventions and rules");xs.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))),J.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=J.readFileSync(o,"utf8");for(let u of i.split(`
|
|
700
702
|
`))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(
|
|
702
|
-
`))console.log(` ${i}`);console.log("")}if(
|
|
703
|
-
`))console.log(` ${i}`);console.log("")}console.log("")});xs.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");
|
|
704
|
-
`,r=s.replace(/^["']|["']$/g,"");
|
|
703
|
+
\u26A0\uFE0F ~${c} tokens \u2014 consider shortening for better context usage.`)),console.log("")}else console.log(a.dim(" No project rules. Run: mc init")),console.log("");if(J.existsSync(n)){console.log(a.cyan(" [global]")+a.dim(` ${n}`));for(let i of J.readFileSync(n,"utf8").split(`
|
|
704
|
+
`))console.log(` ${i}`);console.log("")}if(J.existsSync(r)){console.log(a.magenta(" [memory]")+a.dim(` ${r}`));for(let i of J.readFileSync(r,"utf8").split(`
|
|
705
|
+
`))console.log(` ${i}`);console.log("")}console.log("")});xs.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");J.mkdirSync(N.dirname(o),{recursive:!0});let n=J.existsSync(o)?J.readFileSync(o,"utf8"):`# Project Conventions
|
|
706
|
+
`,r=s.replace(/^["']|["']$/g,"");J.writeFileSync(o,n.trimEnd()+`
|
|
705
707
|
- `+r+`
|
|
706
|
-
`,"utf8"),console.log(` \u2705 Added: ${r}`)});xs.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(!
|
|
707
|
-
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&
|
|
708
|
-
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});xs.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])});xs.action(s=>{let e=process.cwd(),t=N.join(e,".monkeyscode","rules.md");if(
|
|
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(
|
|
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",
|
|
708
|
+
`,"utf8"),console.log(` \u2705 Added: ${r}`)});xs.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(!J.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}`)}});xs.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(!J.existsSync(c))continue;let d=J.readFileSync(c,"utf8").split(`
|
|
709
|
+
`).filter(p=>p.toLowerCase().includes(i.toLowerCase())?(r++,!1):!0);r>0&&J.writeFileSync(c,d.join(`
|
|
710
|
+
`),"utf8")}r>0?console.log(` \u2705 Removed ${r} line(s) matching "${i}".`):console.log(a.dim(` No lines matching "${i}" found.`))});xs.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])});xs.action(s=>{let e=process.cwd(),t=N.join(e,".monkeyscode","rules.md");if(J.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 J.readFileSync(t,"utf8").split(`
|
|
711
|
+
`))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(J.existsSync(t)){console.log(""),console.log(a.bold(" \u{1F4DD} Project Rules"));for(let o of J.readFileSync(t,"utf8").split(`
|
|
712
|
+
`))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",Wo).option("--workspace <path>","Workspace path",".").action(async s=>{let e=gt(s.model);await cg({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",Wo).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let t=gt(e.model);await lg({workspace:N.resolve(e.workspace),model:t,target:s||".",output:e.output,autoFix:e.autoFix,focus:e.focus,severityThreshold:e.severityThreshold})});var Dg=q.command("trace").description("Inspect agent execution traces");Dg.command("list").action(async s=>{yf(s)});Dg.command("show <id>").option("--tree").option("--flamegraph").option("--verbose").action(async(s,e)=>{bf(s,e)});var Go=q.command("marketplace").description("Browse and manage agent skills");Go.command("search <query>").option("--category <cat>").action(async(s,e)=>{await Df(s,e)});Go.command("install <id>").action(async s=>{await vf(s)});Go.command("uninstall <id>").action(async s=>{Sf(s)});Go.command("publish <dir>").option("--name <name>").option("--bump <bump>").action(async(s,e)=>{await xf(s,e)});Go.command("update").action(async()=>{await Cf()});Go.command("list").action(()=>{$f()});Go.command("featured").action(async()=>{await _f()});q.command("join <sessionId>").description("Join a live collaboration session").action(async s=>{await Kf(s)});q.command("share").description("Start a new live collaboration session").action(async()=>{await Yf()&&console.log(a.dim("Host session running..."))});var ui=q.command("permissions").description("Manage natural language policies");ui.command("set <text>").action(async s=>{await Of(s)});ui.command("list").action(()=>{Mf()});ui.command("remove <index>").action(s=>{If(parseInt(s,10))});ui.command("test <tool> <args>").action((s,e)=>{jf(s,e)});var vg=q.command("benchmark").description("Run agent benchmarks");vg.command("custom <path>").option("--model [models...]").option("--workspace <dir>").action(async(s,e)=>{await Hf(s,e)});vg.command("results").option("--limit <n>").option("--format <fmt>").action(s=>{Gf(s)});q.command("design").description("Start the local design artboard server").option("--port <p>").action(s=>{Zf.start(s.port?parseInt(s.port,10):void 0)});Gm()&&process.argv.length<=2?qm().then(()=>q.parse()).catch(()=>q.parse()):($m(ai),Bm("cli_start",{version:ai}),q.parse(),process.on("beforeExit",()=>{_m()}));
|