monkeyscode-cli 0.1.1 → 0.1.2
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 +6 -6
- package/package.json +1 -1
package/dist/monkeyscode-cli.cjs
CHANGED
|
@@ -165,7 +165,7 @@ ${r}`)}}catch{}return e.length>0?e.join(`
|
|
|
165
165
|
|
|
166
166
|
`).filter(Boolean);for(let n of o){let r=n.split(`
|
|
167
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.
|
|
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.2",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:()=>Jc});var Dt,kn,of,Jc,nf=H(()=>{"use strict";Dt=y(require("node:fs"),1),kn=y(require("node:path"),1),of=require("node:events");Je();Q();ef();tf();Jc=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=J(),i=new Se({platformUrl:r.platformUrl,token:this.opts.token,model:e.model||r.defaultModel||"capuchin-reason",workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!0,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeRuns.set(e.name,i);try{let c=[`[Trigger: ${e.name}]`,`Event: ${t.type}`,t.payload?`Payload: ${JSON.stringify(t.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
|
|
169
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:()=>zc});var rf,ws,zc,cf=H(()=>{"use strict";rf=y(require("node:http"),1),ws=y(require("node:crypto"),1),zc=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 yo.writeFileSync(n,o,"utf8"),(0,zt.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{yo.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
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(yo.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,zt.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function _k(s){try{return(0,zt.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Ek(s){try{return(0,zt.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Fk(s){let e=gg(s.title),t=gg(s.body),o=`
|
|
171
171
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
@@ -253,7 +253,7 @@ ${e}`,"wrappedToString"),ah=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
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
254
|
`)}l(Jn,"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
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 zn=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 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,`
|
|
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.2";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
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(zo.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
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(t?a.bold(" Session Summary"):" Session Summary"),console.log(` Tokens: ${e.tokensUsed.toLocaleString()}`),console.log(` Tool calls: ${e.toolCalls}`),console.log(` Files changed: ${e.filesChanged.length}`),console.log(` Duration: ${o}s`),console.log(t?a.dim(n):n),console.log("")}printToolCallStart(e,t){if(this.lastWasToken&&(console.log(""),this.lastWasToken=!1),console.log(""),console.log(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
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=Jn(e,{caps:this.caps});process.stdout.write(o)}else console.log("")}renderMessageCard(e){let t=this.box,o=this.caps.emoji?"\u{1F4E8}":">>",n=Math.min(60,Math.max(40,e.content.length+6)),r=` ${o} Message from ${e.from} `,i=e.timestamp.toLocaleTimeString(),c=Math.max(0,n-r.length-2),u=` ${t.topLeft}${t.horizontal}${r}${t.horizontal.repeat(c)}${t.topRight}`,d=n-4,p=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();Je();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),no=y(require("node:path"),1),ld=y(require("node:crypto"),1);X();var Ty="sessions",Ry=20,Ay=30*24*60*60*1e3,It=class{static{l(this,"SessionStore")}sessionsDir;constructor(){let e=T();this.sessionsDir=no.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:no.resolve(e),startTime:Date.now(),lastActive:Date.now(),turnCount:0,model:t,mode:o,messages:[],stats:{tokensUsed:0,toolCalls:0,filesChanged:[]}};return this.save(n),n}addMessage(e,t,o){e.messages.push({role:t,content:o,timestamp:Date.now()}),e.lastActive=Date.now(),t==="user"&&e.turnCount++,this.save(e)}updateStats(e,t,o,n){e.stats.tokensUsed+=t,e.stats.toolCalls+=o;for(let r of n)e.stats.filesChanged.includes(r)||e.stats.filesChanged.push(r);e.lastActive=Date.now(),this.save(e)}load(e){let t=this.sessionPath(e);if(!he.existsSync(t))return null;try{let o=he.readFileSync(t,"utf-8");return JSON.parse(o)}catch{return null}}loadLatest(e){let t=this.list(),o=e?t.filter(n=>n.workspace===no.resolve(e)):t;return o.length===0?null:this.load(o[0].id)}list(){this.ensureDir();let e=he.readdirSync(this.sessionsDir).filter(o=>o.endsWith(".json")).map(o=>no.join(this.sessionsDir,o)),t=[];for(let o of e)try{let n=he.readFileSync(o,"utf-8"),r=JSON.parse(n),i=r.messages.find(c=>c.role==="user");t.push({id:r.id,workspace:r.workspace,startTime:r.startTime,lastActive:r.lastActive,turnCount:r.turnCount,model:r.model,preview:i?i.content.substring(0,80).replace(/\n/g," "):"(empty)"})}catch{}return t.sort((o,n)=>n.lastActive-o.lastActive),t.slice(0,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=>no.join(this.sessionsDir,i));for(let i of n)try{let c=he.readFileSync(i,"utf-8"),u=JSON.parse(c);t-u.lastActive>e&&(he.unlinkSync(i),o++)}catch{}let r=he.readdirSync(this.sessionsDir).filter(i=>i.endsWith(".json")).length;return{deleted:o,remaining:r}}sessionPath(e){let t=e.replace(/[^a-zA-Z0-9-]/g,"");return no.join(this.sessionsDir,`${t}.json`)}ensureDir(){he.existsSync(this.sessionsDir)||he.mkdirSync(this.sessionsDir,{recursive:!0})}};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(`
|
|
@@ -471,11 +471,11 @@ ${t}
|
|
|
471
471
|
`));for(let o of t){let n=o.official?a.green(" \u2713 official"):"";console.log(` ${o.icon} ${a.bold(o.name)}${n}`),console.log(` ${a.dim(o.description)}`),console.log(` ${a.dim("Install:")} ${a.cyan(`mc mcp add ${o.id}`)}`),o.install.envVars?.length&&console.log(` ${a.dim("Requires:")} ${o.install.envVars.join(", ")}`),console.log()}}else{let o=e.getCategories();console.log(a.bold(`
|
|
472
472
|
\u{1F50C} MCP Server Registry
|
|
473
473
|
`));for(let n of o){console.log(a.bold(` \u2500\u2500 ${n.label} (${n.count}) \u2500\u2500`));let r=e.getByCategory(n.category);for(let i of r){let c=i.official?a.green(" \u2713"):"",u=i.install.envVars?.length?a.dim(` (needs ${i.install.envVars[0]})`):"";console.log(` ${i.icon} ${a.bold(i.name)}${c}${u} \u2014 ${a.dim(i.description)}`)}console.log()}console.log(a.dim(` Add a server: ${a.cyan("mc mcp add <id>")}`)),console.log(a.dim(` Search: ${a.cyan("mc mcp browse <query>")}
|
|
474
|
-
`))}}l(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.
|
|
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.2";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.2",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.2",` \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.2";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 Mo=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!Mo.existsSync(e)}l(Gm,"isFirstRun");function fw(){let e=T().config,t=Wc.join(e,"config.json");Mo.mkdirSync(e,{recursive:!0}),Mo.existsSync(t)||Mo.writeFileSync(t,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}l(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(`
|
|
476
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 uo=y(require("node:fs"),1),Jr=y(require("node:path"),1);X();var Vm=[];function zm(){process.on("uncaughtException",s=>{Jm(s,"uncaughtException"),console.error(`
|
|
477
477
|
\u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${s.message}
|
|
478
|
-
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));Jm(e,"unhandledRejection")})}l(zm,"installCrashHandler");function gw(){let s=T();return Jr.join(s.config,"crashes")}l(gw,"getCrashDir");function Jm(s,e){try{let t=gw();uo.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Jr.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.
|
|
478
|
+
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));Jm(e,"unhandledRejection")})}l(zm,"installCrashHandler");function gw(){let s=T();return Jr.join(s.config,"crashes")}l(gw,"getCrashDir");function Jm(s,e){try{let t=gw();uo.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Jr.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.2",`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
479
|
`):" (none)","","\u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`TERM: ${process.env.TERM||"(not set)"}`,`CI: ${process.env.CI||"false"}`,`MONKEYSCODE_HEADLESS: ${process.env.MONKEYSCODE_HEADLESS||"false"}`,"","\u2550".repeat(60)," Submit this report: mc bug --attach-crash","\u2550".repeat(60),""].join(`
|
|
480
480
|
`);uo.writeFileSync(n,c),hw(t,20)}catch{}}l(Jm,"writeCrashReport");function hw(s,e){try{let t=uo.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)uo.unlinkSync(Jr.join(s,t[o]))}catch{}}l(hw,"pruneOldReports");var Fe=y(require("node:fs"),1),Vt=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=Vt.join(t.data,"sessions");if(!Fe.existsSync(n)){console.log(` ${e.info} No sessions found. Use ${a.cyan("mc")} to create some first.`);return}let r=ww(o),i=Fe.readdirSync(n).filter(h=>h.endsWith(".json")).map(h=>({name:h,path:Vt.join(n,h),mtime:Fe.statSync(Vt.join(n,h)).mtimeMs})).filter(h=>h.mtime>=r).sort((h,b)=>b.mtime-h.mtime);if(console.log(` Sessions reviewed: ${a.bold(String(i.length))} (last ${o})`),i.length===0){console.log(` ${e.info} No sessions in the last ${o}. Nothing to consolidate.`);return}let c=new Map;for(let h of i)try{let b=JSON.parse(Fe.readFileSync(h.path,"utf8"));if(b.toolCalls){for(let k of b.toolCalls)if(k.tool==="file_edit"&&k.args?.path){let v=Vt.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")&&qt(c,"Uses vitest for testing"),k.includes("jest")&&qt(c,"Uses jest for testing"),k.includes("mocha")&&qt(c,"Uses mocha for testing"),k.includes("zod")&&qt(c,"Uses Zod for runtime validation"),k.includes("joi")&&qt(c,"Uses Joi for validation"),k.includes("tailwind")&&qt(c,"Uses Tailwind CSS"),k.includes("styled-components")&&qt(c,"Uses styled-components"),k.includes("result<")&&qt(c,"Uses Result<T, E> pattern for error handling"),(k.includes("try/catch")||k.includes("try {"))&&qt(c,"Uses try/catch for error handling")}}catch{}let u=Math.max(2,Math.floor(i.length*.3)),d=[];for(let[h,b]of c)b>=u&&d.push({rule:h,count:b});if(d.sort((h,b)=>b.count-h.count),d.length===0){console.log(` ${e.info} No strong patterns detected (need at least ${u} occurrences).`);return}console.log(" New conventions found:");for(let h of d)console.log(` ${e.success} "${h.rule}" (seen in ${h.count}/${i.length} sessions)`);if(s.review){console.log(),console.log(a.yellow(` ${e.info} Review mode \u2014 no changes written.`)),console.log(` Run ${a.cyan("mc dream")} (without --review) to write these.`);return}let p=Vt.join(process.cwd(),Km,bw);Fe.mkdirSync(Vt.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
481
|
|
|
@@ -693,7 +693,7 @@ ${s}`,o}l(hk,"buildBugfindPrompt");function ug(s){let e=[],t=s.split(`
|
|
|
693
693
|
|
|
694
694
|
${r}
|
|
695
695
|
|
|
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,Lo.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");zm();Im();globalThis.__mcChalk=a;var ai="0.1.
|
|
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,Lo.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");zm();Im();globalThis.__mcChalk=a;var ai="0.1.2",Uo="auto";function bg(s){let e=Oo(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
697
|
Runs independently of the IDE and Agent Manager.
|
|
698
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
699
|
`),g=Math.ceil(m.length/4);g>2e3&&console.log(a.yellow(` \u26A0\uFE0F Rules file is ~${g} tokens. Consider keeping it under 2000 for optimal context usage.`)),z.mkdirSync(N.join(e,".monkeyscode"),{recursive:!0}),z.writeFileSync(t,m,"utf8"),z.existsSync(o)||z.writeFileSync(o,JSON.stringify({model:"auto",defaultMode:"fast"},null,2),"utf8"),console.log(` Detected: ${f}`),console.log(" Created: .monkeyscode/rules.md"),console.log(" Created: .monkeyscode/config.json"),console.log(""),console.log(a.dim(" Edit rules with: mc memory edit")),console.log(a.dim(" Edit config with: mc config set <key> <value> --project")),console.log("")});var 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))),z.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=z.readFileSync(o,"utf8");for(let u of i.split(`
|