monkeyscode-cli 0.1.8 → 0.1.9
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 +7 -7
- package/package.json +1 -1
package/dist/monkeyscode-cli.cjs
CHANGED
|
@@ -174,7 +174,7 @@ ${r}`)}}catch{}return e.length>0?e.join(`
|
|
|
174
174
|
|
|
175
175
|
`).filter(Boolean);for(let n of o){let r=n.split(`
|
|
176
176
|
`),i=r.find(h=>h.startsWith("worktree "))?.replace("worktree ",""),c=r.find(h=>h.startsWith("HEAD "))?.replace("HEAD ",""),u=r.find(h=>h.startsWith("branch "))?.replace("branch refs/heads/",""),d=r.some(h=>h==="bare");if(!i||!c)continue;let p;try{p=dt.statSync(i).birthtime}catch{}let f=i.split(Dt.sep),m=f.indexOf(pn.replace(/\//g,Dt.sep).split(Dt.sep)[0]),g=m>=0?f.slice(m+1).join("/"):void 0;t.push({path:i,branch:u||"(detached)",commit:c.substring(0,8),isMain:d||!i.includes(pn),createdAt:p,label:g})}return t}function ys(s){return Ub(s).filter(e=>e.path.includes(pn))}function em(s){let e=s.ttlMs??Lb,t=Date.now(),o=[],n=[],r=ys(s.workspace);for(let c of r)if((c.createdAt?t-c.createdAt.getTime():1/0)>e)try{Cc(s.workspace,c.path,s.force??!0),o.push(c.path)}catch(d){n.push(`${c.path}: ${d instanceof Error?d.message:d}`)}let i=Dt.join(s.workspace,pn);try{tm(i)}catch{}return{removed:o,errors:n}}function tm(s){if(!dt.existsSync(s))return;let e=dt.readdirSync(s,{withFileTypes:!0});for(let t of e)t.isDirectory()&&tm(Dt.join(s,t.name));dt.readdirSync(s).length===0&&dt.rmdirSync(s)}function _c(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").substring(0,40).replace(/^-|-$/g,"")}var dt,Dt,qt,pn,Lb,Bb,xc,Ec=G(()=>{"use strict";dt=b(require("node:fs"),1),Dt=b(require("node:path"),1),qt=require("node:child_process"),pn=".monkeyscode-worktrees",Lb=24*60*60*1e3,Bb=500,xc=3;l($c,"createWorktree");l(Cc,"removeWorktree");l(Ub,"listWorktrees");l(ys,"listManagedWorktrees");l(em,"cleanStaleWorktrees");l(tm,"cleanEmptyDirs");l(_c,"slugify")});var sm={};Ae(sm,{mergeTeam:()=>Tc,runInWorktree:()=>Hb,showTeamStatus:()=>Fc,spawnTeam:()=>Gr});async function Gr(s){let e=Gb(),t=s.tasks.map((m,g)=>({index:g+1,task:m,slug:_c(m),status:"queued"}));console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Spawning Agent Team: ${e}`)),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(` Tasks: ${t.length}`),console.log(` Max agents: ${s.maxAgents}`),console.log(` Model: ${s.model}`),console.log(a.dim(" "+"\u2500".repeat(50))),console.log("");for(let m of t)try{console.log(a.dim(` \u{1F4C1} Creating worktree for agent #${m.index}: "${m.task.substring(0,40)}..."`)),m.worktree=$c({workspace:s.workspace,teamId:e,taskSlug:m.slug}),console.log(a.dim(` Branch: ${m.worktree.branch}`))}catch(g){m.status="failed",m.error=g instanceof Error?g.message:String(g),console.error(a.red(` \u274C Failed to create worktree for agent #${m.index}: ${m.error}`))}let o=K(),r=fe()?.access_token||"",i=t.filter(m=>m.status!=="failed"),c=new Set,u=l(async m=>{if(!m.worktree)return;m.status="running";let g=Date.now();console.log(a.cyan(` \u25B6 Agent #${m.index} started: "${m.task.substring(0,50)}"`));try{let h=(0,fo.execSync)(`node "${process.argv[1]}" -p "${m.task.replace(/"/g,'\\"')}" --headless --auto-approve --model "${s.model}" --workspace "${m.worktree.path}" -o json`,{cwd:m.worktree.path,encoding:"utf8",timeout:6e5,env:{...process.env,MONKEYSCODE_API_KEY:process.env.MONKEYSCODE_API_KEY||""},stdio:["pipe","pipe","pipe"]});try{let y=JSON.parse(h);m.filesChanged=y.filesChanged?.length||0}catch{m.filesChanged=0}m.status="completed",m.duration=Date.now()-g;try{(0,fo.execSync)("git add -A",{cwd:m.worktree.path,stdio:"pipe"}),(0,fo.execSync)(`git commit -m "feat: ${m.task.substring(0,72)}" --allow-empty`,{cwd:m.worktree.path,stdio:"pipe"})}catch{}console.log(a.green(` \u2705 Agent #${m.index} completed (${om(m.duration)}, ${m.filesChanged} files)`))}catch(h){m.status="failed",m.duration=Date.now()-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(y=>setTimeout(y,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=mn.join(s.workspace,".monkeyscode-worktrees",e);pt.mkdirSync(m,{recursive:!0});let g=mn.join(m,"state.json");pt.writeFileSync(g,JSON.stringify({teamId:e,createdAt:new Date().toISOString(),agents:t.map(h=>({index:h.index,task:h.task,slug:h.slug,status:h.status,duration:h.duration,filesChanged:h.filesChanged,error:h.error,branch:h.worktree?.branch}))},null,2))}catch{}let p=t.filter(m=>m.status==="completed").length,f=t.filter(m=>m.status==="failed").length;return console.log(""),console.log(a.dim(" "+"\u2500".repeat(50))),console.log(a.bold(` Team ${e}: ${p} completed, ${f} failed`)),console.log(a.dim(` Merge: mc team merge ${e}`)),console.log(""),{teamId:e,agents:t,createdAt:new Date}}function Fc(s){let e=mn.join(s,".monkeyscode-worktrees");if(!pt.existsSync(e)){console.log(a.dim(" No active agent teams found."));return}let t=[];try{let c=pt.readdirSync(e,{withFileTypes:!0});for(let u of c)if(u.isDirectory()){let d=mn.join(e,u.name,"state.json");if(pt.existsSync(d))try{t.push(JSON.parse(pt.readFileSync(d,"utf8")))}catch{}}}catch{}let o=ys(s),n=new Set(t.map(c=>c.teamId)),r=new Map;for(let c of o){let d=(c.label?.split("/")||[])[0]||"unknown";n.has(d)||(r.has(d)||r.set(d,[]),r.get(d).push(c))}if(t.length===0&&r.size===0){console.log(a.dim(" No active agent teams found."));return}let i=l(c=>{switch(c){case"completed":return"\u2705";case"running":return"\u{1F504}";case"queued":return"\u23F3";case"failed":return"\u274C";default:return"?"}},"statusIcon");for(let c of t){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c.teamId}`));let u=" "+"\u2500".repeat(76);console.log(u),console.log(a.bold(` ${"Agent".padEnd(8)} ${"Task".padEnd(34)} ${"Status".padEnd(12)} ${"Duration".padEnd(10)} ${"Files".padEnd(6)}`)),console.log(u);for(let d of c.agents){let p=i(d.status),f=d.duration?om(d.duration):"\u2014",m=d.filesChanged!==void 0?String(d.filesChanged):"\u2014",g=d.task.length>32?d.task.substring(0,29)+"...":d.task;console.log(` ${"#"+d.index.toString().padEnd(7)} ${('"'+g+'"').padEnd(34)} ${(p+" "+Wb(d.status)).padEnd(12)} ${f.padEnd(10)} ${m.padEnd(6)}`)}console.log(u)}for(let[c,u]of r){console.log(""),console.log(a.bold(` \u{1F3D7}\uFE0F Agent Team: ${c}`)+a.dim(" (no state file)"));let d=" "+"\u2500".repeat(70);console.log(d);for(let p=0;p<u.length;p++){let f=u[p],m=f.label?.split("/").slice(1).join("/")||"?";console.log(` ${"#"+(p+1).toString().padEnd(7)} ${m.padEnd(36)} ${f.branch.padEnd(30)}`)}console.log(d)}console.log("")}function Wb(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Tc(s,e){let t=ys(s).filter(r=>r.label?.startsWith(e));if(t.length===0){console.error(a.red(` \u274C No worktrees found for team ${e}.`));return}console.log(""),console.log(a.bold(` \u{1F500} Merging team ${e} (${t.length} branches)`));let o=0,n=0;for(let r of t){let i=r.label?.split("/").slice(1).join("/")||"?";console.log(a.dim(` Merging: ${r.branch} (${i})`));try{(0,fo.execSync)(`git merge --no-ff "${r.branch}" -m "merge: team ${e} \u2014 ${i}"`,{cwd:s,stdio:"inherit"}),o++,console.log(a.green(` \u2705 Merged ${r.branch}`))}catch{n++,console.error(a.yellow(` \u26A0 Merge conflict on ${r.branch}. Resolve and continue.`)),console.log(a.dim(" After resolving: git merge --continue")),console.log(a.dim(" Then re-run: mc team merge "+e));return}}if(n===0){console.log(a.dim(" \u{1F9F9} Cleaning up worktrees..."));for(let r of t)try{Cc(s,r.path,!0)}catch{}}console.log(""),console.log(a.dim(" "+"\u2500".repeat(40))),console.log(a.bold(` Merged: ${o}, Conflicts: ${n}`)),console.log("")}async function Hb(s,e,t){let o=_c(s),n=`solo-${Date.now().toString(36)}`;console.log(a.dim(" \u{1F4C1} Creating isolated worktree..."));let r=$c({workspace:e,teamId:n,taskSlug:o});console.log(a.dim(` Branch: ${r.branch}`)),console.log(a.dim(` Path: ${r.path}`)),console.log("");try{(0,fo.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,fo.execSync)("git add -A",{cwd:r.path,stdio:"pipe"}),(0,fo.execSync)(`git commit -m "feat: ${s.substring(0,72)}"`,{cwd:r.path,stdio:"pipe"})}catch{}console.log(a.green(" \u2705 Worktree task completed.")),console.log(a.dim(` Merge: git merge --no-ff ${r.branch}`))}catch(i){console.error(a.red(` \u274C Worktree task failed: ${i instanceof Error?i.message:i}`))}}function Gb(){return`team-${Date.now().toString(36)}-${Math.random().toString(36).substring(2,6)}`}function om(s){let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),o=e%60;return`${t}m ${o}s`}var pt,mn,fo,Rc=G(()=>{"use strict";pt=b(require("node:fs"),1),mn=b(require("node:path"),1),fo=require("node:child_process");W();Ec();Q();ee();l(Gr,"spawnTeam");l(Fc,"showTeamStatus");l(Wb,"capitalize");l(Tc,"mergeTeam");l(Hb,"runInWorktree");l(Gb,"generateTeamId");l(om,"formatDuration")});var qr={};Ae(qr,{MessageBroker:()=>fn});function qb(){try{let s=rm.join(im.homedir(),".monkeyscode","daemon.port"),e=nm.readFileSync(s,"utf8").trim(),t=parseInt(e,10);return isNaN(t)?null:t}catch{return null}}var nm,rm,im,Ac,Pc,fn,gn=G(()=>{"use strict";nm=b(require("node:fs"),1),rm=b(require("node:path"),1),im=b(require("node:os"),1);an();Ac=class{static{l(this,"DaemonTransport")}ws=null;port;connected=!1;pendingCalls=new Map;callId=0;constructor(e){this.port=e}async ensureConnection(){return this.ws&&this.connected?this.ws:new Promise((e,t)=>{let o=new lt(`ws://127.0.0.1:${this.port}`),n=setTimeout(()=>{o.close(),t(new Error("Daemon connection timeout"))},3e3);o.on("open",()=>{clearTimeout(n),this.ws=o,this.connected=!0,e(o)}),o.on("message",r=>{try{let i=JSON.parse(r.toString());if(i.id&&this.pendingCalls.has(i.id)){let c=this.pendingCalls.get(i.id);this.pendingCalls.delete(i.id),i.error?c.reject(new Error(i.error.message||i.error)):c.resolve(i.result)}}catch{}}),o.on("close",()=>{this.connected=!1,this.ws=null}),o.on("error",()=>{clearTimeout(n),this.connected=!1,this.ws=null,t(new Error("Daemon WS connection failed"))})})}async rpcCall(e,t){let o=await this.ensureConnection(),n=String(++this.callId);return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingCalls.delete(n),i(new Error("RPC call timeout"))},5e3);this.pendingCalls.set(n,{resolve:l(u=>{clearTimeout(c),r(u)},"resolve"),reject:l(u=>{clearTimeout(c),i(u)},"reject")}),o.send(JSON.stringify({jsonrpc:"2.0",method:e,params:t,id:n}))})}async sendMessage(e,t,o){try{return{success:!0,messageId:(await this.rpcCall("messaging/send",{from:e,to:t,content:o}))?.id}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{return(await this.rpcCall("messaging/agents",{})||[]).map(t=>({id:t.id,task:t.task||"",status:t.status||"running",type:t.session_type||"interactive",workspace:t.workspace||"",startedAt:new Date(t.connected_at||Date.now()),model:t.model||"unknown"}))}catch{return[]}}async pollMessages(e){try{return(await this.rpcCall("messaging/poll",{session_id:e})||[]).map(o=>({id:o.id,from:o.from,to:o.to,content:o.content,timestamp:new Date(o.timestamp),delivered:o.delivered??!0}))}catch{return[]}}async getMessageHistory(e,t){return[]}async register(e,t,o,n){try{await this.rpcCall("messaging/register",{id:e,task:t,workspace:o,model:n,type:"interactive"})}catch{}}async unregister(e){try{await this.rpcCall("messaging/unregister",{id:e})}catch{}this.ws?.close()}},Pc=class{constructor(e,t){this.platformUrl=e;this.token=t}static{l(this,"CloudTransport")}headers(){return{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`}}async sendMessage(e,t,o){try{let n=await fetch(`${this.platformUrl}/api/messages`,{method:"POST",headers:this.headers(),body:JSON.stringify({from:e,to:t,content:o,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(!n.ok){let i=await n.text().catch(()=>"");return{success:!1,error:`HTTP ${n.status}: ${i}`}}return{success:!0,messageId:(await n.json()).messageId}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async listAgents(){try{let e=await fetch(`${this.platformUrl}/api/sessions`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return e.ok?((await e.json()).sessions||[]).map(o=>({id:o.id,task:o.task||o.prompt?.substring(0,80)||"(no task)",status:o.status||"running",type:o.type||"interactive",workspace:o.workspace||"",startedAt:new Date(o.startedAt||o.createdAt),model:o.model||"unknown"})):[]}catch{return[]}}async pollMessages(e){try{let t=await fetch(`${this.platformUrl}/api/messages/pending?session=${e}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)});if(!t.ok)return[];let n=((await t.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:!1}));for(let r of n)try{await fetch(`${this.platformUrl}/api/messages/${r.id}/ack`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(5e3)})}catch{}return n}catch{return[]}}async getMessageHistory(e,t){try{let o=await fetch(`${this.platformUrl}/api/messages?session=${e}&limit=${t}`,{headers:{Authorization:`Bearer ${this.token}`},signal:AbortSignal.timeout(1e4)});return o.ok?((await o.json()).messages||[]).map(r=>({id:r.id,from:r.from,to:r.to,content:r.content,timestamp:new Date(r.timestamp),delivered:r.delivered??!0})):[]}catch{return[]}}async register(){}async unregister(){}};l(qb,"readDaemonPort");fn=class{static{l(this,"MessageBroker")}transport;sessionId;onMessageCallback;constructor(e,t,o){this.sessionId=o;let n=qb();n?this.transport=new Ac(n):this.transport=new Pc(e,t)}async init(e,t,o){await this.transport.register(this.sessionId,e,t,o)}async dispose(){await this.transport.unregister(this.sessionId)}async sendMessage(e,t){return this.transport.sendMessage(this.sessionId,e,t)}async broadcast(e){return this.sendMessage("broadcast",e)}async listAgents(){return this.transport.listAgents()}async getMessageHistory(e=50){return this.transport.getMessageHistory(this.sessionId,e)}async checkPendingMessages(){return this.transport.pollMessages(this.sessionId)}onMessage(e){this.onMessageCallback=e}async pollMessages(){let e=await this.checkPendingMessages();if(this.onMessageCallback)for(let t of e)this.onMessageCallback(t);return e}static getToolSchemas(){return[{name:"SendMessage",description:"Send a message to another active agent session. Use when you make changes that affect shared code and other agents need to know.",parameters:{type:"object",properties:{target:{type:"string",description:'Target session ID (from ListAgents) or "broadcast" to notify all.'},message:{type:"string",description:"Message content describing what changed and what other agents should do."}},required:["target","message"]}},{name:"ListAgents",description:"List all active agent sessions on the current machine. Returns session IDs, tasks, and status.",parameters:{type:"object",properties:{}}}]}}});var cm={};Ae(cm,{analyzeImpact:()=>am,notifyAffectedSessions:()=>zb});function am(s,e,t){let o=e.filter(r=>r.id!==t&&(r.status==="running"||r.status==="idle"));if(o.length===0||s.length===0)return{modifiedFiles:s,affectedSessions:[]};let n=[];for(let r of o){let i=r.task.toLowerCase(),c="",u=0;for(let d of s){let p=vt.basename(d).toLowerCase(),f=d.toLowerCase();if(i.includes(p)&&.9>u&&(u=.9,c=`Task mentions "${p}" which was modified`),r.workspace){let m=vt.relative(r.workspace,d),g=vt.dirname(m).split(vt.sep)[0];g&&i.includes(g.toLowerCase())&&.7>u&&(u=.7,c=`Task involves "${g}" directory where changes were made`)}for(let m of Vb)if(m.pathPattern.test(f))for(let g of m.keywords)i.includes(g)&&.6>u&&(u=.6,c=`Modified ${p} (${g}-related) \u2014 task mentions "${g}"`)}u>=.5&&n.push({sessionId:r.id,task:r.task,reason:c,confidence:u})}return n.sort((r,i)=>i.confidence-r.confidence),{modifiedFiles:s,affectedSessions:n}}async function zb(s,e,t){if(e.length===0)return[];let o=await s.listAgents(),n=am(e,o,t);if(n.affectedSessions.length===0)return[];let r=[];for(let i of n.affectedSessions){let u=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>vt.basename(p)).join(", "):`${e.slice(0,3).map(p=>vt.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${i.reason}`,`This may affect your task: "${i.task.substring(0,60)}"`].join(`
|
|
177
|
-
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var vt,Vb,lm=G(()=>{"use strict";vt=b(require("node:path"),1),Vb=[{pathPattern:/\bauth\b/i,keywords:["auth","login","session","token","jwt","permission"]},{pathPattern:/\bapi\b/i,keywords:["api","endpoint","route","handler","rest","graphql"]},{pathPattern:/\bmodel\b|\btypes?\b|\binterface\b/i,keywords:["model","type","interface","schema","struct"]},{pathPattern:/\bconfig\b|\bsettings?\b/i,keywords:["config","settings","env","environment"]},{pathPattern:/\btest\b|\bspec\b/i,keywords:["test","spec","assert","mock","fixture"]},{pathPattern:/\bdatabase\b|\bdb\b|\bstore\b/i,keywords:["database","migration","schema","query","sql"]},{pathPattern:/\butils?\b|\bhelpers?\b|\blib\b|\bshared\b|\bcommon\b/i,keywords:["util","helper","shared","common","lib"]},{pathPattern:/\bstyle\b|\bcss\b|\btheme\b/i,keywords:["style","css","theme","layout","design"]},{pathPattern:/package\.json|cargo\.toml|go\.mod/i,keywords:["dependency","package","install","version"]}];l(am,"analyzeImpact");l(zb,"notifyAffectedSessions")});var dm={};Ae(dm,{fetchModels:()=>um,getModelInfo:()=>Jb});async function um(){let s=K(),e=await Fe(),t={};e&&(t.Authorization=`Bearer ${e}`);let o=await fetch(`${s.platformUrl}/v1/models`,{headers:t});if(!o.ok)throw o.status===401?new Error("Authentication expired \u2014 run `mc auth login`."):new Error(`Failed to fetch models: ${o.status} ${o.statusText}`);let n=await o.json(),r,i=n.flat;if(Array.isArray(i)&&i.length>0)r=i.map(c=>({id:c.id,name:c.display_name||c.id,contextWindow:c.context_window||128e3,supportsReasoning:c.supports_thinking||!1,supportsTools:!0,inputCostPer1M:c.cost_input_micros?c.cost_input_micros/1e6:void 0,outputCostPer1M:c.cost_output_micros?c.cost_output_micros/1e6:void 0}));else{let c=n.data;if(!Array.isArray(c))return[];r=c.map(u=>{let d=u.capabilities,p=u.pricing;return{id:u.id,name:u.name||u.id,contextWindow:u.context_window||128e3,supportsReasoning:d?.reasoning||!1,supportsTools:d?.tools!==!1,inputCostPer1M:p?.input_per_1m,outputCostPer1M:p?.output_per_1m}})}return ld(r),r}async function Jb(s){try{return(await um()).find(t=>t.id===s)||null}catch{return null}}var pm=G(()=>{"use strict";ee();Q();gr();l(um,"fetchModels");l(Jb,"getModelInfo")});var Om={};Ae(Om,{default:()=>pw});var pw,Im=G(()=>{pw={name:"monkeyscode-cli",version:"0.1.
|
|
177
|
+
`),d=await s.sendMessage(i.sessionId,u);r.push(d)}return r}var vt,Vb,lm=G(()=>{"use strict";vt=b(require("node:path"),1),Vb=[{pathPattern:/\bauth\b/i,keywords:["auth","login","session","token","jwt","permission"]},{pathPattern:/\bapi\b/i,keywords:["api","endpoint","route","handler","rest","graphql"]},{pathPattern:/\bmodel\b|\btypes?\b|\binterface\b/i,keywords:["model","type","interface","schema","struct"]},{pathPattern:/\bconfig\b|\bsettings?\b/i,keywords:["config","settings","env","environment"]},{pathPattern:/\btest\b|\bspec\b/i,keywords:["test","spec","assert","mock","fixture"]},{pathPattern:/\bdatabase\b|\bdb\b|\bstore\b/i,keywords:["database","migration","schema","query","sql"]},{pathPattern:/\butils?\b|\bhelpers?\b|\blib\b|\bshared\b|\bcommon\b/i,keywords:["util","helper","shared","common","lib"]},{pathPattern:/\bstyle\b|\bcss\b|\btheme\b/i,keywords:["style","css","theme","layout","design"]},{pathPattern:/package\.json|cargo\.toml|go\.mod/i,keywords:["dependency","package","install","version"]}];l(am,"analyzeImpact");l(zb,"notifyAffectedSessions")});var dm={};Ae(dm,{fetchModels:()=>um,getModelInfo:()=>Jb});async function um(){let s=K(),e=await Fe(),t={};e&&(t.Authorization=`Bearer ${e}`);let o=await fetch(`${s.platformUrl}/v1/models`,{headers:t});if(!o.ok)throw o.status===401?new Error("Authentication expired \u2014 run `mc auth login`."):new Error(`Failed to fetch models: ${o.status} ${o.statusText}`);let n=await o.json(),r,i=n.flat;if(Array.isArray(i)&&i.length>0)r=i.map(c=>({id:c.id,name:c.display_name||c.id,contextWindow:c.context_window||128e3,supportsReasoning:c.supports_thinking||!1,supportsTools:!0,inputCostPer1M:c.cost_input_micros?c.cost_input_micros/1e6:void 0,outputCostPer1M:c.cost_output_micros?c.cost_output_micros/1e6:void 0}));else{let c=n.data;if(!Array.isArray(c))return[];r=c.map(u=>{let d=u.capabilities,p=u.pricing;return{id:u.id,name:u.name||u.id,contextWindow:u.context_window||128e3,supportsReasoning:d?.reasoning||!1,supportsTools:d?.tools!==!1,inputCostPer1M:p?.input_per_1m,outputCostPer1M:p?.output_per_1m}})}return ld(r),r}async function Jb(s){try{return(await um()).find(t=>t.id===s)||null}catch{return null}}var pm=G(()=>{"use strict";ee();Q();gr();l(um,"fetchModels");l(Jb,"getModelInfo")});var Om={};Ae(Om,{default:()=>pw});var pw,Im=G(()=>{pw={name:"monkeyscode-cli",version:"0.1.9",description:"MonkeysCode CLI \u2014 standalone terminal coding agent. Works independently of the IDE and Agent Manager.",license:"MIT",type:"module",main:"dist/monkeyscode-cli.cjs",bin:{mc:"dist/monkeyscode-cli.cjs",mcode:"dist/monkeyscode-cli.cjs",monkeyscode:"dist/monkeyscode-cli.cjs"},files:["dist/monkeyscode-cli.cjs","README.md","LICENSE"],scripts:{build:"tsc","build:watch":"tsc --watch",bundle:"node esbuild.config.mjs","bundle:prod":"node esbuild.config.mjs --prod","build:sea":"bash scripts/build.sh --sea",release:"bash scripts/build.sh --all --checksums",dev:"tsx src/main.ts",start:"node dist/main.js",lint:"eslint src/",test:"node --import tsx --test tests/**/*.test.ts","test:watch":"node --import tsx --test --watch tests/**/*.test.ts",clean:"rm -rf dist",prepublishOnly:"npm run clean && npm run bundle:prod"},keywords:["monkeyscode","cli","coding-agent","terminal","ai","standalone"],dependencies:{chalk:"^5.4.0","cli-highlight":"^2.1.11",commander:"^13.0.0",diff:"^7.0.0",marked:"^18.0.11",ora:"^8.1.0",ws:"^8.18.0"},devDependencies:{"@types/diff":"^6.0.0","@types/node":"^22.0.0","@types/ws":"^8.5.0",esbuild:"^0.24.0",tsx:"^4.19.0",typescript:"^5.7.0"},engines:{node:">=20.0.0"}}});var ti,cf=G(()=>{"use strict";ti=class{static{l(this,"CronScheduler")}jobs=new Map;running=!1;add(e){let t={...e,timer:null,runCount:0,nextRunAt:null,active:!1};this.jobs.set(e.id,t),this.running&&this.scheduleNext(t)}remove(e){let t=this.jobs.get(e);return t?(t.timer&&clearTimeout(t.timer),this.jobs.delete(e),!0):!1}start(){this.running=!0;for(let e of this.jobs.values())this.scheduleNext(e)}stop(){this.running=!1;for(let e of this.jobs.values())e.timer&&(clearTimeout(e.timer),e.timer=null),e.active=!1}list(){return[...this.jobs.values()].map(e=>({id:e.id,expression:e.expression,nextRunAt:e.nextRunAt,runCount:e.runCount,active:e.active}))}scheduleNext(e){if(!this.running||e.maxRuns&&e.runCount>=e.maxRuns)return;let t=this.getNextCronTime(e.expression);if(!t)return;e.nextRunAt=t,e.active=!0;let o=t.getTime()-Date.now();e.timer=setTimeout(async()=>{e.runCount++;try{await e.callback()}catch{}this.scheduleNext(e)},Math.max(o,0)),e.timer&&typeof e.timer.unref=="function"&&e.timer.unref()}getNextCronTime(e){let t=e.trim().split(/\s+/);if(t.length!==5)return null;let[o,n,r,i,c]=t,u=new Date;for(let d=0;d<366*24*60;d++){let p=new Date(u.getTime()+d*6e4);if(p.setSeconds(0,0),!(p.getTime()<=u.getTime())&&this.matchesCronField(p.getMinutes(),o,0,59)&&this.matchesCronField(p.getHours(),n,0,23)&&this.matchesCronField(p.getDate(),r,1,31)&&this.matchesCronField(p.getMonth()+1,i,1,12)&&this.matchesCronField(p.getDay(),c,0,6))return p}return null}matchesCronField(e,t,o,n){if(t==="*")return!0;let r=t.split(",");for(let i of r)if(i.includes("/")){let[c,u]=i.split("/"),d=parseInt(u,10);if(c==="*"){if((e-o)%d===0)return!0}else if(c.includes("-")){let[p,f]=c.split("-").map(Number);if(e>=p&&e<=f&&(e-p)%d===0)return!0}}else if(i.includes("-")){let[c,u]=i.split("-").map(Number);if(e>=c&&e<=u)return!0}else if(parseInt(i,10)===e)return!0;return!1}}});var $n,Yc,oi,lf=G(()=>{"use strict";$n=b(require("node:fs"),1),Yc=b(require("node:path"),1),oi=class{static{l(this,"FileWatcher")}workspace;rules=[];watchers=[];pendingChanges=new Map;debounceMs=500;running=!1;constructor(e,t=500){this.workspace=e,this.debounceMs=t}watch(e,t){this.rules.push({patterns:e,callback:t})}start(){if(!this.running){this.running=!0;try{let e=$n.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=$n.readdirSync(e,{withFileTypes:!0});for(let n of o){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let r=Yc.join(e,n.name);try{let i=$n.watch(r,(c,u)=>{!u||!this.running||this.onFileChange(Yc.join(n.name,u))});this.watchers.push(i),this.watchDirectories(r,t+1)}catch{}}}catch{}}}});var df={};Ae(df,{TriggerEngine:()=>Xc});var $t,Cn,uf,Xc,pf=G(()=>{"use strict";$t=b(require("node:fs"),1),Cn=b(require("node:path"),1),uf=require("node:events");Ke();Q();cf();lf();Xc=class extends uf.EventEmitter{static{l(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=Cn.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new ti,this.fileWatcher=new oi(e.workspace),this.loadState()}loadTriggers(){let e=Cn.join(this.opts.workspace,".monkeyscode","triggers.json");if(!$t.existsSync(e))return this.triggers=[],[];try{let t=JSON.parse($t.readFileSync(e,"utf8"));return this.triggers=(t.triggers||[]).filter(o=>o.enabled!==!1),this.triggers}catch{return[]}}start(){this.loadTriggers();for(let e of this.triggers)e.event==="cron"&&e.schedule&&this.cronScheduler.add({id:e.name,expression:e.schedule,callback:l(()=>this.fire(e,{type:"cron",payload:{schedule:e.schedule},source:"cron-scheduler",timestamp:Date.now()}),"callback")}),e.event==="file.changed"&&this.fileWatcher.watch(e.watchPatterns||["**/*"],t=>{this.fire(e,{type:"file.changed",payload:{files:t},source:"file-watcher",timestamp:Date.now()})});this.cronScheduler.start(),this.fileWatcher.start(),this.emit("started",{triggerCount:this.triggers.length})}stop(){this.cronScheduler.stop(),this.fileWatcher.stop();for(let e of this.activeRuns.values())e.cancel();this.activeRuns.clear(),this.saveState()}async processEvent(e){for(let t of this.triggers)this.matches(t,e)&&await this.fire(t,e)}listTriggers(){return this.triggers.map(e=>({...e,state:this.state.get(e.name)||{name:e.name,lastFired:0,fireCount:0,lastResult:null}}))}dryRun(e){let t=this.triggers.find(o=>o.name===e);return t?{matched:!0,prompt:t.prompt,model:t.model||"default"}:{matched:!1,prompt:"",model:""}}matches(e,t){if(e.event!==t.type)return!1;if(e.filter){for(let[o,n]of Object.entries(e.filter))if(t.payload[o]!==n)return!1}return!0}async fire(e,t){let o=this.state.get(e.name),n=(e.cooldownSeconds||300)*1e3;if(o&&Date.now()-o.lastFired<n){this.emit("cooldown",{trigger:e.name,remaining:n-(Date.now()-o.lastFired)});return}if(this.activeRuns.has(e.name))return;this.emit("firing",{trigger:e.name,event:t.type});let r=K(),i=new xe({platformUrl:r.platformUrl,token:this.opts.token,model:e.model||r.defaultModel||"capuchin-reason",workspace:this.opts.workspace,mode:"auto",maxTurns:30,sandboxed:!0,webEnabled:!1,effort:"fast",userId:this.opts.userId,orgId:this.opts.orgId});this.activeRuns.set(e.name,i);try{let c=[`[Trigger: ${e.name}]`,`Event: ${t.type}`,t.payload?`Payload: ${JSON.stringify(t.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
|
|
178
178
|
`);await i.run(c),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(c){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:c instanceof Error?c.message:String(c)})}finally{this.activeRuns.delete(e.name)}}updateState(e,t){let o=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};o.lastFired=Date.now(),o.fireCount++,o.lastResult=t,this.state.set(e,o),this.saveState()}saveState(){try{let e=Cn.dirname(this.statePath);$t.mkdirSync(e,{recursive:!0}),$t.writeFileSync(this.statePath,JSON.stringify(Object.fromEntries(this.state),null,2))}catch{}}loadState(){try{if($t.existsSync(this.statePath)){let e=JSON.parse($t.readFileSync(this.statePath,"utf8"));this.state=new Map(Object.entries(e))}}catch{this.state=new Map}}}});var ff={};Ae(ff,{GitHubWebhookServer:()=>Qc});var mf,vs,Qc,gf=G(()=>{"use strict";mf=b(require("node:http"),1),vs=b(require("node:crypto"),1),Qc=class s{static{l(this,"GitHubWebhookServer")}server=null;opts;constructor(e){this.opts={port:9122,...e}}async start(){return new Promise((e,t)=>{this.server=mf.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"]||vs.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="+vs.createHmac("sha256",o).update(e).digest("hex");return vs.timingSafeEqual(Buffer.from(t),Buffer.from(n))}}});var Sg={};Ae(Sg,{getNotificationBackend:()=>jk,notifyJobComplete:()=>Mk,notifyUpdateAvailable:()=>Ok,sendNotification:()=>dl,supportsNotifications:()=>Ik});function dl(s){if(process.env.CI==="true"||process.env.CI==="1")return!1;try{switch(process.platform){case"darwin":return Nk(s);case"linux":return Lk(s);case"win32":return Hk(s);default:return!1}}catch{return!1}}function Mk(s,e,t){return dl({title:t?"\u2705 Job Complete":"\u274C Job Failed",body:`Job ${s}: ${e}`,subtitle:"MonkeysCode",sound:t?"Glass":"Basso",urgency:t?"normal":"critical"})}function Ok(s){return dl({title:"\u{1F504} Update Available",body:`MonkeysCode v${s} is available. Run: mc update`,subtitle:"MonkeysCode",urgency:"low"})}function Ik(){if(process.env.CI==="true"||process.env.CI==="1")return!1;switch(process.platform){case"darwin":return Et("osascript");case"linux":return!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY?!1:Et("notify-send")||Et("kdialog")||Et("zenity");case"win32":return!0;default:return!1}}function jk(){switch(process.platform){case"darwin":return"macOS (osascript)";case"linux":return Et("notify-send")?"Linux (notify-send)":Et("kdialog")?"Linux (kdialog)":Et("zenity")?"Linux (zenity)":"Linux (terminal bell)";case"win32":return"Windows (PowerShell toast)";default:return"Unsupported"}}function Nk(s){let e=ui(s.title),o=`display notification "${ui(s.body)}" with title "${e}"`;s.subtitle&&(o+=` subtitle "${ui(s.subtitle)}"`),s.sound&&(o+=` sound name "${ui(s.sound)}"`);let n=ll.join(ul.tmpdir(),`mc-notify-${process.pid}.scpt`);try{return Do.writeFileSync(n,o,"utf8"),(0,Xt.execFileSync)("osascript",[n],{stdio:"pipe",timeout:5e3}),!0}finally{try{Do.unlinkSync(n)}catch{}}}function ui(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Lk(s){if(!!(process.env.DISPLAY||process.env.WAYLAND_DISPLAY)){if(Et("notify-send"))return Bk(s);if(Et("kdialog"))return Uk(s);if(Et("zenity"))return Wk(s)}return process.stderr.write("\x07"),process.stderr.write(`[Notification] ${s.title}: ${s.body}
|
|
179
179
|
`),!0}function Bk(s){let e=[s.title,s.body,"--app-name=MonkeysCode",`--expire-time=${s.urgency==="critical"?0:1e4}`],t=s.urgency||"normal";e.push(`--urgency=${t}`);let o=["/usr/share/icons/hicolor/48x48/apps/monkeyscode.png","/usr/share/pixmaps/monkeyscode.png","dialog-information"];for(let n of o)if(n.startsWith("/")){if(Do.existsSync(n)){e.push(`--icon=${n}`);break}}else{e.push(`--icon=${n}`);break}try{return(0,Xt.execFileSync)("notify-send",e,{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Uk(s){try{return(0,Xt.execFileSync)("kdialog",["--passivepopup",s.body,"10","--title",s.title],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Wk(s){try{return(0,Xt.execFileSync)("zenity",["--notification",`--text=${s.title}: ${s.body}`,"--window-icon=info"],{stdio:"pipe",timeout:5e3}),!0}catch{return!1}}function Hk(s){let e=vg(s.title),t=vg(s.body),o=`
|
|
180
180
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
@@ -262,7 +262,7 @@ ${e}`,"wrappedToString"),kh=Object.getOwnPropertyDescriptor(Function.prototype,"
|
|
|
262
262
|
`),n=[],r=!1,i="",c=[];for(let u of o){let d=u.match(/^```(\w+)?/);if(d){r?(n.push(yu(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 D=h[1],C=Xn(h[3]);n.push(`${D} \u2022 ${C}`);continue}let y=u.match(/^(\s*)(\d+)\.\s(.+)/);if(y){let D=y[1],C=y[2],x=Xn(y[3]);n.push(`${D} ${a.dim(C+".")} ${x}`);continue}let S=u.match(/^>\s?(.*)/);if(S){n.push(a.dim(" \u2502 ")+a.italic(Xn(S[1])));continue}if(u.trim()===""){n.push("");continue}n.push(Xn(u))}return r&&c.length>0&&n.push(yu(c,i)),n.join(`
|
|
263
263
|
`)}l(Qn,"renderMarkdown");function Xn(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(Xn,"renderInline");function yu(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}${dy(c,e)}`);return[n,...i,r].join(`
|
|
264
264
|
`)}l(yu,"renderCodeBlock");function dy(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=py(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(dy,"highlightSyntax");function py(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(py,"getLanguageKeywords");function bu(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(bu,"containsMarkdown");W();_e();var Zn=class{static{l(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=I(),this.icons=H(this.caps),this.data={model:"",mode:"code",branch:"",dirty:!1,sandbox:!1,tokensIn:0,tokensOut:0,cost:0,turn:0,contextPct:0,activity:"",busy:!1,budgetUsd:0,...e}}start(){!this.caps.stdoutTTY||!this.caps.ansi||(this.enabled=!0,process.stdout.write(`
|
|
265
|
-
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=I(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,y=t.dirty?a.yellow:a.green,S=t.dirty?" \u25CF":"";o.push(y(` ${h} ${t.branch}${S} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=my(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,y=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(y(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,y=6,S=Math.round(t.contextPct/100*y),D=y-S,C=h("\u2588".repeat(S))+a.dim("\u2591".repeat(D));r.push(` ${C} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=wu(c).length,p=wu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function my(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(my,"formatTokensCompact");function wu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(wu,"stripAnsi");W();var Je={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},fy={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..................."]},gy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},hy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},yy={large:fy,medium:gy,mini:hy},ku="\u25C1\u2571\u25B7",Du="</>";function vu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(vu,"isDarkBackground");function Su(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=yy[s],c=o?Je.navyOnDark:Je.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Je.ice):m=>m,p=l((m,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],y="",S="",D=h[0]??".";for(let C=0;C<m.length;C++){let x=h[C]??".";x!==D&&(y+=p(S,D),S="",D=x),S+=m[C]}return y+=p(S,D),(f+y).replace(/\s+$/,"")})}l(Su,"renderLogo");function xu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(xu,"pickLogoSize");function ia(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(ia,"visibleWidth");var by={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Co=class{static{l(this,"TuiRenderer")}caps;icons;box;opts;spinner=null;activeToolSpinners=new Map;toolDurations=new Map;toolStartTimes=new Map;tokenBuffer="";lastWasToken=!1;statusBar=null;currentTurn=0;turnTokens=0;constructor(e={}){this.opts={...by,...e},this.caps=I(),this.icons=H(this.caps),this.box=Oe(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(Je.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.8";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?xu(this.caps.columns,this.caps.unicode):u;if(d){let f=Su(d,{color:o,dark:vu(),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":ku} MonkeysCode`,h="CLI Agent",y=Math.max(0,f-ia(g)-h.length-2);console.log(` ${n(p.vertical)} ${i(g)}${" ".repeat(y)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let S=`${c}${e?` \xB7 ${e}`:""}`,D=Math.max(0,f-ia(S)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(D)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${Du} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let t=a.hex(Je.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
265
|
+
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=I(),this.render()}))}update(e){Object.assign(this.data,e),this.enabled&&this.render()}stop(){if(this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.enabled){let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}this.enabled=!1}hide(){if(!this.enabled)return;let e=process.stdout.rows||24;process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${e};1H`),process.stdout.write("\x1B[2K"),process.stdout.write("\x1B8")}show(){this.enabled&&this.render()}getData(){return this.data}render(){if(!this.enabled)return;let e=process.stdout.columns||80,t=process.stdout.rows||24,o=this.formatBar(e);o!==this.lastRendered&&(this.lastRendered=o,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${t};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(o),process.stdout.write("\x1B8"))}formatBar(e){let t=this.data,o=[];if(t.model){let h=t.model.length>20?t.model.slice(0,18)+"..":t.model;o.push(a.hex("#6B8DD6").bold(` ${this.icons.model} ${h} `))}let n=t.mode==="plan"?a.bgHex("#713F12").hex("#FBBF24"):t.mode==="ask"?a.bgHex("#1E3A5F").hex("#6B8DD6"):a.bgHex("#1a1a2e").hex("#A3CAD3");if(o.push(n(` ${t.mode} `)),t.branch){let h=this.icons.branch,y=t.dirty?a.yellow:a.green,S=t.dirty?" \u25CF":"";o.push(y(` ${h} ${t.branch}${S} `))}t.sandbox&&o.push(a.green(` ${this.icons.lock} `));let r=[],i=t.tokensIn+t.tokensOut;if(i>0){let h=my(i);r.push(a.dim(` ${h} tokens `))}if(t.cost>0){let h=t.cost<1?`$${t.cost.toFixed(3)}`:`$${t.cost.toFixed(2)}`,y=t.budgetUsd>0&&t.cost/t.budgetUsd>.8?a.red:t.budgetUsd>0&&t.cost/t.budgetUsd>.5?a.yellow:a.dim;r.push(y(` ${this.icons.cost} ${h} `))}if(t.turn>0&&r.push(a.dim(` T${t.turn} `)),t.contextPct>0){let h=t.contextPct>=80?a.red:t.contextPct>=60?a.yellow:a.green,y=6,S=Math.round(t.contextPct/100*y),D=y-S,C=h("\u2588".repeat(S))+a.dim("\u2591".repeat(D));r.push(` ${C} ${h(`${t.contextPct}%`)} `)}if(t.activity){let h=t.activity.length>30?t.activity.slice(0,28)+"..":t.activity;r.push(a.dim.italic(` ${h} `))}let c=o.join(a.dim("\u2502")),u=r.join(a.dim("\u2502")),d=wu(c).length,p=wu(u).length,f=Math.max(1,e-d-p),m=a.bgHex("#0d1117"),g=m(" ".repeat(f));return m(c)+g+m(u)}};function my(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toString()}l(my,"formatTokensCompact");function wu(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}l(wu,"stripAnsi");W();var Je={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},fy={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..................."]},gy={width:30,height:13,glyphs:[" \u2584\u2584\u2588 \u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2584 "," \u2588\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2588\u2588\u2588 ","\u2584\u2584\u2588\u2588\u2584\u2588\u2588\u2588 \u2588\u2588\u2588\u2584\u2588\u2588\u2584\u2584","\u2588\u2588\u2580\u2580\u2580\u2588\u2588\u2580 \u2584\u2584 \u2584\u2584 \u2584 \u2580\u2588\u2588\u2580\u2580\u2580\u2588\u2588","\u2588\u2588\u2584 \u2584\u2588\u2588\u2580 \u2588\u2588 \u2588\u2588\u2584\u2584 \u2584\u2588\u2588","\u2580\u2580\u2588\u2588\u2588 \u2588\u2588\u2588\u2584 \u2588\u2588\u2580 \u2584\u2588\u2588 \u2588\u2588\u2588\u2580\u2580"," \u2580\u2584\u2584 \u2580\u2588\u2588 \u2588\u2588\u2580 \u2588\u2580\u2580 \u2584\u2584\u2580 "," \u2588\u2588\u2588\u2584\u2584 \u2580\u2580 \u2584\u2584\u2588\u2588\u2588 "," \u2580\u2588\u2588\u2588\u2588\u2588\u2584 \u2584\u2588\u2588\u2588\u2588\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2584 \u2584\u2588\u2588\u2580\u2580 "," \u2580\u2580\u2588\u2588\u2580\u2580 "],mask:["..............nnn.n...........","...........nnnnnnnnn..........",".......nnnnnnnnnnnnnnnn.......",".....nnnnnnnnnnnnnnnnnnnn.....","nnnnnnnn..............nnnnnnnn","nnnnnnnn..ll....ll.l..nnnnnnnn","nnn.....llll...ll..llll....nnn","nnnnn..llll...lll...lll..nnnnn","....nnn..lll.lll...lll.nnn....",".....nnnnn...ll.....nnnnn.....","......nnnnnnn....nnnnnnn......",".........nnnnn..nnnnn.........","............nnnnnn............"]},hy={width:15,height:5,glyphs:[" \u2584\u2584\u2588\u2588\u2588\u2588\u2588\u2584\u2584 "," \u2584\u2588\u2580 \u2580\u2588\u2584 ","\u2588\u2588 </> \u2588\u2588"," \u2580\u2588\u2584 \u2584\u2588\u2580 "," \u2580\u2580\u2588\u2588\u2588\u2588\u2588\u2580\u2580 "],mask:["...nnnnnnnnn...",".nnn.......nnn.","nn....lll....nn",".nnn.......nnn.","...nnnnnnnnn..."]},yy={large:fy,medium:gy,mini:hy},ku="\u25C1\u2571\u25B7",Du="</>";function vu(){let s=process.env.COLORFGBG;if(!s)return!0;let e=Number(s.split(";").pop());return Number.isNaN(e)?!0:e<8}l(vu,"isDarkBackground");function Su(s,e={}){let{color:t=!0,dark:o=!0,indent:n=2,center:r}=e,i=yy[s],c=o?Je.navyOnDark:Je.navy,u=t?a.hex(c):m=>m,d=t?a.hex(Je.ice):m=>m,p=l((m,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],y="",S="",D=h[0]??".";for(let C=0;C<m.length;C++){let x=h[C]??".";x!==D&&(y+=p(S,D),S="",D=x),S+=m[C]}return y+=p(S,D),(f+y).replace(/\s+$/,"")})}l(Su,"renderLogo");function xu(s,e){return e?s>=72?"large":s>=46?"medium":s>=24?"mini":null:null}l(xu,"pickLogoSize");function ia(s){return s.replace(/\x1b\[[0-9;]*m/g,"").length}l(ia,"visibleWidth");var by={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Co=class{static{l(this,"TuiRenderer")}caps;icons;box;opts;spinner=null;activeToolSpinners=new Map;toolDurations=new Map;toolStartTimes=new Map;tokenBuffer="";lastWasToken=!1;statusBar=null;currentTurn=0;turnTokens=0;constructor(e={}){this.opts={...by,...e},this.caps=I(),this.icons=H(this.caps),this.box=Oe(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(Je.accent):p=>p,r=o?a.dim:p=>p,i=o?a.white.bold:p=>p,c="v0.1.9";console.log("");let u=t.logo??"auto",d=u==="none"?null:u==="auto"?xu(this.caps.columns,this.caps.unicode):u;if(d){let f=Su(d,{color:o,dark:vu(),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":ku} MonkeysCode`,h="CLI Agent",y=Math.max(0,f-ia(g)-h.length-2);console.log(` ${n(p.vertical)} ${i(g)}${" ".repeat(y)}${r(h)} ${n(p.vertical)}`),console.log(n(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let S=`${c}${e?` \xB7 ${e}`:""}`,D=Math.max(0,f-ia(S)-2);console.log(` ${n(p.vertical)} ${n(c)}${e?` ${r("\xB7")} ${r(e)}`:""}${" ".repeat(D)} ${n(p.vertical)}`),console.log(n(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${i("MonkeysCode")} ${n(c)} ${r("\xB7 CLI Agent")}`),e&&console.log(` ${r(e)}`)):(console.log(` ${Du} MC - MonkeysCode CLI ${c}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(o?a.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(o?a.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let t=a.hex(Je.accent),o=Math.min(56,this.caps.columns-6);console.log(""),console.log(t(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,o-9))}${this.box.topRight}`)),process.stdout.write(a.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let t=e.content.replace(/\n/g,`
|
|
266
266
|
`+a.dim(` ${this.box.vertical} `));process.stdout.write(t)}else process.stdout.write(e.content);this.turnTokens+=e.content.length,this.statusBar&&this.statusBar.update({activity:"streaming..."})}renderThinking(e){if(!this.opts.showThinking)return;this.lastWasToken&&(console.log(""),this.lastWasToken=!1);let t=this.caps.ansi,o=` ${this.icons.thinking} ${e.content}`;console.log(t?a.dim.italic(o):o)}renderRunStarted(e){this.lastWasToken=!1;let t=this.caps.ansi,o=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(t?a.dim(o):o),console.log(t?` ${a.bold("Model:")} ${e.model} ${a.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(t?a.dim(o):o),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let t=this.caps.ansi,o=(e.duration/1e3).toFixed(1),n=this.box;if(this.caps.unicode){let r=Math.min(54,this.caps.columns-6),i=a.hex(Je.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(na(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=Ws({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(ra(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(hu(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 y=e.riskLevel==="dangerous"?" [y] Allow once [n] Deny":" [y] Allow [n] Deny [a] Always [!] YOLO",S=Math.max(0,i-y.length);console.log(r.color(` ${o.vertical}`)+a.dim(` ${y}${" ".repeat(S)}`)+r.color(o.vertical)),console.log(r.color(` ${o.bottomLeft}${o.horizontal.repeat(i)}${o.bottomRight}`))}else{console.log(""),console.log(r.color(` ${r.icon} Permission required: ${e.toolName}`)),console.log(r.color(` ${e.description}`)),console.log(r.color(` Risk: ${r.label}`));let i=JSON.stringify(e.args,null,2).split(`
|
|
267
267
|
`).slice(0,5);for(let c of i)console.log(t?a.dim(` ${c}`):` ${c}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let t=this.caps.ansi;console.log(t?a.dim(` ${e}`):` ${e}`)}printSuccess(e){let t=this.caps.ansi;console.log(t?a.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let t=this.caps.ansi;console.error(t?a.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let t=this.caps.ansi;console.log(t?a.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=Ws({text:e,indent:2,spinner:"dots"}).start()}succeedSpinner(e){this.spinner&&(this.spinner.succeed(e),this.spinner=null)}failSpinner(e){this.spinner&&(this.spinner.fail(e),this.spinner=null)}clearSpinners(){this.spinner&&(this.spinner.stop(),this.spinner=null);for(let[e,t]of this.activeToolSpinners)t.stop();this.activeToolSpinners.clear()}getToolAvgDuration(e){let t=this.toolDurations.get(e);if(!t||t.length===0)return 0;let o=t.reduce((n,r)=>n+r,0);return Math.round(o/t.length)}recordToolDuration(e,t){let o=this.toolDurations.get(e)??[];o.push(t),o.length>10&&o.shift(),this.toolDurations.set(e,o)}printSessionSummary(e){let t=this.caps.ansi,o=e.endTime?((e.endTime-e.startTime)/1e3).toFixed(1):"?";if(this.caps.unicode){let n=this.box,r=Math.min(48,this.caps.columns-6),i=a.hex(Je.accent),c=a.dim,u=[["Duration",`${o}s`],["Tokens",e.tokensUsed.toLocaleString()],["Tools",`${e.toolCalls} calls`],["Files",`${e.filesChanged.length} changed`]];console.log(""),console.log(i(` ${n.topLeft}${n.horizontal} \u{1F4CB} Session Summary ${n.horizontal.repeat(Math.max(0,r-22))}${n.topRight}`));for(let[d,p]of u){let f=d.padEnd(12),m=`${f}${p}`,g=Math.max(0,r-m.length-4);console.log(i(` ${n.vertical}`)+` ${c(f)}${p}${" ".repeat(g)}`+i(n.vertical))}if(e.filesChanged.length>0){console.log(i(` ${n.teeRight}${n.horizontal.repeat(r)}${n.teeLeft}`));for(let d of e.filesChanged){let p=d.split("/").slice(-2).join("/"),f=` ${this.icons.edit} ${p}`,m=Math.max(0,r-f.length);console.log(i(` ${n.vertical}`)+`${f}${" ".repeat(m)}`+i(n.vertical))}}console.log(i(` ${n.bottomLeft}${n.horizontal.repeat(r)}${n.bottomRight}`)),console.log("")}else{let n=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(""),console.log(t?a.dim(n):n),console.log(" Session Summary"),console.log(` Tokens: ${e.tokensUsed.toLocaleString()}`),console.log(` Tool calls: ${e.toolCalls}`),console.log(` Files changed: ${e.filesChanged.length}`),console.log(` Duration: ${o}s`),console.log(t?a.dim(n):n),console.log("")}}printToolCallStart(e,t){if(this.lastWasToken&&(console.log(""),this.lastWasToken=!1),console.log(""),console.log(na(e,t)),!this.opts.accessible&&this.caps.ansi){let o=Ws({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(ra(e,r,n))}printTodoList(e){let t=this.caps.ansi,o=t?a.dim:r=>r,n=t?a.bold:r=>r;console.log(""),console.log(n(" \u{1F4CB} Task Plan:"));for(let r of e){let i=r.status==="done"?"\u2705":r.status==="in_progress"?"\u{1F504}":"\u2B1C",c=r.status==="done"?t?a.green:u=>u:r.status==="in_progress"?t?a.yellow:u=>u:o;console.log(c(` ${i} ${r.content}`))}console.log("")}flushTokenBuffer(){if(!this.tokenBuffer)return;let e=this.tokenBuffer.replace(/<think>[\s\S]*?<\/think>/g,"").trim();this.tokenBuffer="";let t=e.split(`
|
|
268
268
|
`).length;if(this.caps.ansi&&bu(e)){for(let n=0;n<t;n++)process.stdout.write("\x1B[2K"),n<t-1&&process.stdout.write("\x1B[1A");process.stdout.write("\r");let o=Qn(e,{caps:this.caps});if(this.caps.unicode){let n=a.dim(` ${this.box.vertical} `),r=o.split(`
|
|
@@ -315,7 +315,7 @@ ${e.error}
|
|
|
315
315
|
`)}catch{}}t.push(`::set-output name=success::${e.success}`),t.push(`::set-output name=status::${e.status}`),t.push(`::set-output name=summary::${e.summary}`),t.push(`::set-output name=files-changed::${e.filesChanged.map(r=>Gt(r.path)).join(",")}`),t.push(`::set-output name=cost::${e.cost.toFixed(4)}`),t.push(`::set-output name=tokens::${e.tokens.total}`),t.push(`::set-output name=duration::${e.duration}`),t.push(`::set-output name=model::${e.model}`),t.push(`::set-output name=session-id::${e.sessionId}`);let n=process.env.GITHUB_STEP_SUMMARY;if(n){let r=new Ur().formatResult(e);try{dc.appendFileSync(n,r+`
|
|
316
316
|
`)}catch{}}return!e.success&&e.error&&t.push(`::error::${e.error}`),t.join(`
|
|
317
317
|
`)}},hc=class{static{l(this,"AzureFormatter")}formatResult(e){let t=[];return t.push(`##vso[task.setvariable variable=agentSuccess]${e.success}`),t.push(`##vso[task.setvariable variable=agentStatus]${e.status}`),t.push(`##vso[task.setvariable variable=agentSummary]${e.summary}`),t.push(`##vso[task.setvariable variable=agentCost]${e.cost.toFixed(4)}`),t.push(`##vso[task.setvariable variable=agentFilesChanged]${e.filesChanged.map(o=>Gt(o.path)).join(",")}`),t.push(`##vso[task.setvariable variable=agentTokens]${e.tokens.total}`),t.push(`##vso[task.setvariable variable=agentDuration]${e.duration}`),e.success?t.push(`##vso[task.complete result=Succeeded;]${e.summary}`):t.push(`##vso[task.complete result=Failed;]${e.error||e.summary}`),t.push(`##vso[task.uploadsummary]MonkeysCode: ${e.summary}`),t.join(`
|
|
318
|
-
`)}},gs=class{static{l(this,"SarifFormatter")}findings;workspace;constructor(e=[],t="."){this.findings=e,this.workspace=t}formatResult(e){return this.formatFindings(this.findings)}formatFindings(e){let t={$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"MonkeysCode",informationUri:"https://monkeyscode.com",version:"1.0.0",rules:this.extractRules(e)}},results:e.map((o,n)=>({ruleId:o.ruleId||`MC${String(n+1).padStart(3,"0")}`,level:this.mapSeverity(o.severity),message:{text:o.message},locations:[{physicalLocation:{artifactLocation:{uri:Gt(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:Gt(o.file),uriBaseId:"%SRCROOT%"},replacements:[{deletedRegion:{startLine:o.line},insertedContent:{text:o.fix}}]}]}]}:{}}))}]};return JSON.stringify(t,null,2)}extractRules(e){let t=new Set;return e.filter(o=>{let n=o.ruleId||"MC001";return t.has(n)?!1:(t.add(n),!0)}).map((o,n)=>({id:o.ruleId||`MC${String(n+1).padStart(3,"0")}`,shortDescription:{text:o.message.substring(0,100)},defaultConfiguration:{level:this.mapSeverity(o.severity)}}))}mapSeverity(e){switch(e){case"high":return"error";case"medium":return"warning";case"low":return"note";default:return"none"}}};function Up(s,e={}){switch(s){case"json":return new fs;case"jsonl":return new mc;case"diff":return new fc(e.workspace||".");case"markdown":return new Ur;case"github":return new gc;case"azure":return new hc;case"sarif":return new gs(e.findings,e.workspace);case"text":case"stream":default:return new fs}}l(Up,"createFormatter");function Wp(s,e){return{success:!1,status:"failed",summary:"",platform:process.platform,filesChanged:[],toolCalls:[],tokens:{input:0,output:0,thinking:0,total:0},cost:0,duration:0,model:s,sessionId:e}}l(Wp,"createEmptyResult");function gm(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(gm,"mapMode");async function hm(s){let e=I(),t=s.prompt;!t&&!e.interactive&&(t=await Xb());let o=await Fe();if(o||(console.error(a.red(" Error: Not authenticated. Run `mc auth login` first.")),process.exit(1)),s.model==="auto"){let r=K();s.model=r.defaultModel}let n=fe();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(Zp(),Qp));await r({jobId:s.resume,workspace:s.workspace}),await mm(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Rc(),sm));await r(s.prompt,s.workspace,s.model)}else s.headless?await Kb(t,s,o,n):s.background?await Yb(t,s):await mm(t,s,o,n)}l(hm,"runCommand");async function mm(s,e,t,o){let n=I(),r=K(),i=new Co({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new To(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new Lt,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,g=new Set,h=0,y=0,S=0,D=0,C=null,x=!1;if(e.continueSession){let M=u.loadLatest(e.workspace);if(M){d=M,D=M.turnCount;for(let N of M.stats.filesChanged)m.add(N);i.printSuccess(`Resumed session ${M.id.substring(0,8)} (${M.turnCount} turns, ${M.stats.tokensUsed.toLocaleString()} tokens)`)}else console.log(a.dim(" No previous session found \u2014 starting fresh."))}i.printBanner(`${e.mode} mode \xB7 ${e.model}`);{let M=a.dim,N=a.green,T=a.yellow,O=a.hex("#6B8DD6"),_=a.bold(e.model),w=M(e.mode);console.log(` ${O("Model:")} ${_} ${M("\xB7")} ${w} mode`);let k=(()=>{try{return(0,Qe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),$=(()=>{try{return(0,Qe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),F=k?` ${M("\xB7")} ${M("branch:")} ${k}${$?T(" \u25CF"):N(" \u2713")}`:"";console.log(` ${O("Path:")} ${M(e.workspace)}${F}`);let R=e.sandbox?N("\u{1F512} on"):T("off"),q=e.permissionMode!=="default"?` ${M("\xB7")} ${M("perm:")} ${e.permissionMode}`:"",P=e.autoApprove?` ${M("\xB7")} ${T("auto-approve")}`:e.approveForMe?` ${M("\xB7")} ${N("smart-approve")}`:"";console.log(` ${O("Sandbox:")} ${R}${q}${P}`);let tt=c.getHooks(),$e=tt.length>0?`${tt.length} hooks`:M("none"),ot=0;try{let{listAllSkills:Re}=await Promise.resolve().then(()=>(pr(),Pa));ot=Re(e.workspace).length}catch{}let Ts=ot>0?`${ot} skills`:M("none");console.log(` ${O("Plugins:")} ${$e} ${M("\xB7")} ${Ts}`);let Rs=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${O("Engine:")} ${M(Rs)}`)}console.log("");let v=i.getStatusBar({model:e.model,mode:e.mode,branch:(()=>{try{return(0,Qe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),dirty:(()=>{try{return(0,Qe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),sandbox:e.sandbox,budgetUsd:e.maxCost||0});v.start(),console.log(a.dim(" Type a prompt to start. /help for commands, /exit to quit, Ctrl+C to cancel."));let E="0.1.
|
|
318
|
+
`)}},gs=class{static{l(this,"SarifFormatter")}findings;workspace;constructor(e=[],t="."){this.findings=e,this.workspace=t}formatResult(e){return this.formatFindings(this.findings)}formatFindings(e){let t={$schema:"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"MonkeysCode",informationUri:"https://monkeyscode.com",version:"1.0.0",rules:this.extractRules(e)}},results:e.map((o,n)=>({ruleId:o.ruleId||`MC${String(n+1).padStart(3,"0")}`,level:this.mapSeverity(o.severity),message:{text:o.message},locations:[{physicalLocation:{artifactLocation:{uri:Gt(o.file),uriBaseId:"%SRCROOT%"},region:{startLine:o.line,...o.endLine?{endLine:o.endLine}:{}}}}],...o.fix?{fixes:[{description:{text:"Suggested fix"},artifactChanges:[{artifactLocation:{uri:Gt(o.file),uriBaseId:"%SRCROOT%"},replacements:[{deletedRegion:{startLine:o.line},insertedContent:{text:o.fix}}]}]}]}:{}}))}]};return JSON.stringify(t,null,2)}extractRules(e){let t=new Set;return e.filter(o=>{let n=o.ruleId||"MC001";return t.has(n)?!1:(t.add(n),!0)}).map((o,n)=>({id:o.ruleId||`MC${String(n+1).padStart(3,"0")}`,shortDescription:{text:o.message.substring(0,100)},defaultConfiguration:{level:this.mapSeverity(o.severity)}}))}mapSeverity(e){switch(e){case"high":return"error";case"medium":return"warning";case"low":return"note";default:return"none"}}};function Up(s,e={}){switch(s){case"json":return new fs;case"jsonl":return new mc;case"diff":return new fc(e.workspace||".");case"markdown":return new Ur;case"github":return new gc;case"azure":return new hc;case"sarif":return new gs(e.findings,e.workspace);case"text":case"stream":default:return new fs}}l(Up,"createFormatter");function Wp(s,e){return{success:!1,status:"failed",summary:"",platform:process.platform,filesChanged:[],toolCalls:[],tokens:{input:0,output:0,thinking:0,total:0},cost:0,duration:0,model:s,sessionId:e}}l(Wp,"createEmptyResult");function gm(s){switch(s){case"plan":return"plan";case"fast":return"auto";case"thinking":return"auto";default:return"auto"}}l(gm,"mapMode");async function hm(s){let e=I(),t=s.prompt;!t&&!e.interactive&&(t=await Xb());let o=await Fe();if(o||(console.error(a.red(" Error: Not authenticated. Run `mc auth login` first.")),process.exit(1)),s.model==="auto"){let r=K();s.model=r.defaultModel}let n=fe();if(s.resume){let{resumeFromJob:r}=await Promise.resolve().then(()=>(Zp(),Qp));await r({jobId:s.resume,workspace:s.workspace}),await mm(void 0,s,o,n)}else if(s.worktree&&s.prompt){let{runInWorktree:r}=await Promise.resolve().then(()=>(Rc(),sm));await r(s.prompt,s.workspace,s.model)}else s.headless?await Kb(t,s,o,n):s.background?await Yb(t,s):await mm(t,s,o,n)}l(hm,"runCommand");async function mm(s,e,t,o){let n=I(),r=K(),i=new Co({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox}),c=new To(e.workspace,{enabled:!0,timeoutMs:1e4}),u=new Lt,d=null,p=`interactive-${Date.now().toString(36)}`,f=Date.now(),m=new Set,g=new Set,h=0,y=0,S=0,D=0,C=null,x=!1;if(e.continueSession){let M=u.loadLatest(e.workspace);if(M){d=M,D=M.turnCount;for(let N of M.stats.filesChanged)m.add(N);i.printSuccess(`Resumed session ${M.id.substring(0,8)} (${M.turnCount} turns, ${M.stats.tokensUsed.toLocaleString()} tokens)`)}else console.log(a.dim(" No previous session found \u2014 starting fresh."))}i.printBanner(`${e.mode} mode \xB7 ${e.model}`);{let M=a.dim,N=a.green,T=a.yellow,O=a.hex("#6B8DD6"),_=a.bold(e.model),w=M(e.mode);console.log(` ${O("Model:")} ${_} ${M("\xB7")} ${w} mode`);let k=(()=>{try{return(0,Qe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),$=(()=>{try{return(0,Qe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),F=k?` ${M("\xB7")} ${M("branch:")} ${k}${$?T(" \u25CF"):N(" \u2713")}`:"";console.log(` ${O("Path:")} ${M(e.workspace)}${F}`);let R=e.sandbox?N("\u{1F512} on"):T("off"),q=e.permissionMode!=="default"?` ${M("\xB7")} ${M("perm:")} ${e.permissionMode}`:"",P=e.autoApprove?` ${M("\xB7")} ${T("auto-approve")}`:e.approveForMe?` ${M("\xB7")} ${N("smart-approve")}`:"";console.log(` ${O("Sandbox:")} ${R}${q}${P}`);let tt=c.getHooks(),$e=tt.length>0?`${tt.length} hooks`:M("none"),ot=0;try{let{listAllSkills:Re}=await Promise.resolve().then(()=>(pr(),Pa));ot=Re(e.workspace).length}catch{}let Ts=ot>0?`${ot} skills`:M("none");console.log(` ${O("Plugins:")} ${$e} ${M("\xB7")} ${Ts}`);let Rs=r.providerKeys?.anthropic||r.providerKeys?.openai||r.providerKeys?.google?"Direct API":r.customEndpoint?`Custom (${r.customEndpoint})`:`Proxy (${r.platformUrl})`;console.log(` ${O("Engine:")} ${M(Rs)}`)}console.log("");let v=i.getStatusBar({model:e.model,mode:e.mode,branch:(()=>{try{return(0,Qe.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim()}catch{return""}})(),dirty:(()=>{try{return(0,Qe.execSync)("git status --porcelain",{cwd:e.workspace,stdio:["pipe","pipe","pipe"]}).toString().trim().length>0}catch{return!1}})(),sandbox:e.sandbox,budgetUsd:e.maxCost||0});v.start(),console.log(a.dim(" Type a prompt to start. /help for commands, /exit to quit, Ctrl+C to cancel."));let E="0.1.9";(async()=>{try{let M=await fetch("https://registry.npmjs.org/monkeyscode-cli/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!M.ok)return;let T=(await M.json()).version;if(!T)return;let O=E.split(".").map(Number),_=T.split(".").map(Number),w=!1;for(let k=0;k<3;k++){if((_[k]||0)>(O[k]||0)){w=!0;break}if((_[k]||0)<(O[k]||0))break}w&&(console.log(""),console.log(a.hex(Je.accent)(` \u2B06 Update available: ${a.dim(`v${E}`)} \u2192 ${a.bold(`v${T}`)}`)),console.log(a.dim(` Run ${a.bold("npm i -g monkeyscode-cli")} to update.`)))}catch{}})(),await c.fire("SessionStart",{workspace:e.workspace,data:{model:e.model,mode:e.mode}});let oe=["exit","quit","clear","model","mode","diff","undo","commit","files","cost","context","compact","permissions","doctor","fork","sessions","resume","continue","goal","subtask","sub","search","docs","help","init","memory","plan","ask","cloud","bug","feedback","vim","review","skill","skills","hooks","hook"],U=fm.createInterface({input:process.stdin,output:process.stdout,terminal:!0,prompt:(()=>{let M=H(n);return n.ansi?`
|
|
319
319
|
${a.hex("#6B8DD6")(M.prompt)} `:`
|
|
320
320
|
${M.prompt} `})(),historySize:200,completer:l(M=>{if(M.startsWith("/")){let N=M.slice(1).toLowerCase(),T=oe.filter(O=>O.startsWith(N)).map(O=>`/${O}`);return[T.length?T:oe.map(O=>`/${O}`),M]}if(M.startsWith("/context ")){let N=M.slice(9);try{let T=J.dirname(J.resolve(e.workspace,N)),O=J.basename(N);return[j.readdirSync(T).filter(k=>k.startsWith(O)).map(k=>`/context ${N.replace(O,"")}${k}`),M]}catch{return[[],M]}}return[[],M]},"completer")});new hr().wire(U);let ne=null,De=null,Jo=!1,ht=null,Zt=new kr({workspace:e.workspace,model:e.model,token:t,userId:o?.user?.id,orgId:o?.org?.id},i),eo=null;try{let{MessageBroker:M}=await Promise.resolve().then(()=>(gn(),qr));t&&r.platformUrl&&(eo=new M(r.platformUrl,t,p))}catch{}let Es=l(async()=>{if(eo)try{let M=await eo.pollMessages();if(M&&M.length>0)for(let N of M)i.renderMessageCard({from:N.from||N.senderId||"unknown",content:N.content||N.message||"",timestamp:N.timestamp?new Date(N.timestamp):new Date})}catch{}},"pollAndRenderMessages"),Ft=l(async M=>{d||(d=u.create(e.workspace,e.model,e.mode)),u.addMessage(d,"user",M),D++,v.update({turn:D,busy:!0,activity:"thinking..."});let N=new xe({platformUrl:r.platformUrl,token:t,model:e.model,workspace:e.workspace,mode:gm(e.mode),maxTurns:r.maxTurns,sandboxed:e.sandbox,webEnabled:r.webEnabled,effort:e.mode==="thinking"?"reasoning":"fast",userId:o?.user?.id,orgId:o?.org?.id});ne=N;let T="";N.on("event",_=>{switch(_.type){case"streaming_chunk":T+=_.content,process.stdout.write(_.content);break;case"streaming_end":if(T.trim()){let k=T.split(`
|
|
321
321
|
`).length;process.stdout.write(`\x1B[${k}A\x1B[J`),console.log(Qn(T))}else console.log("");T="";break;case"tool_call_start":i.printToolCallStart(_.name,_.args),_.name==="file_read"&&_.args?.file_path&&g.add(String(_.args.file_path)),["file_edit","file_write","file_create"].includes(_.name)&&_.args?.file_path&&m.add(String(_.args.file_path));break;case"tool_call_result":i.printToolCallResult(_.name,_.result);break;case"ask_user":console.log(a.cyan(`
|
|
@@ -486,11 +486,11 @@ ${t}
|
|
|
486
486
|
`));for(let o of t){let n=o.official?a.green(" \u2713 official"):"";console.log(` ${o.icon} ${a.bold(o.name)}${n}`),console.log(` ${a.dim(o.description)}`),console.log(` ${a.dim("Install:")} ${a.cyan(`mc mcp add ${o.id}`)}`),o.install.envVars?.length&&console.log(` ${a.dim("Requires:")} ${o.install.envVars.join(", ")}`),console.log()}}else{let o=e.getCategories();console.log(a.bold(`
|
|
487
487
|
\u{1F50C} MCP Server Registry
|
|
488
488
|
`));for(let n of o){console.log(a.bold(` \u2500\u2500 ${n.label} (${n.count}) \u2500\u2500`));let r=e.getByCategory(n.category);for(let i of r){let c=i.official?a.green(" \u2713"):"",u=i.install.envVars?.length?a.dim(` (needs ${i.install.envVars[0]})`):"";console.log(` ${i.icon} ${a.bold(i.name)}${c}${u} \u2014 ${a.dim(i.description)}`)}console.log()}console.log(a.dim(` Add a server: ${a.cyan("mc mcp add <id>")}`)),console.log(a.dim(` Search: ${a.cyan("mc mcp browse <query>")}
|
|
489
|
-
`))}}l($m,"mcpBrowseCommand");X();var Ze=b(require("node:fs"),1),kn=b(require("node:path"),1);X();W();var wn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var Cm=["plan","fast","thinking"],_m=["dark","light","auto"],Em=["text","json","stream"],Fm={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>Cm.includes(s)?null:`must be one of: ${Cm.join(", ")}`,"defaultMode"),theme:l(s=>_m.includes(s)?null:`must be one of: ${_m.join(", ")}`,"theme"),outputFormat:l(s=>Em.includes(s)?null:`must be one of: ${Em.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Nc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:wn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(wn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=Fm[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Ze.mkdirSync(kn.dirname(r),{recursive:!0}),Ze.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Ze.existsSync(o)&&(n=JSON.parse(Ze.readFileSync(o,"utf8")))}catch{}delete n[e],Ze.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...wn};for(let t of Object.keys(wn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=A();return kn.join(e.config,"config.json")}getProjectConfigPath(){return kn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Ze.existsSync(e)){let o=JSON.parse(Ze.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=Fm[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(wn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Ze.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Tm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Tm,"printConfigList");var jc=null;function No(s){return(!jc||s)&&(jc=new Nc(s)),jc}l(No,"getConfigSystem");ur();W();_e();ee();var rw=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Rm(){let s=I(),e=H(s),t=s.ansi,o=fe();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Fe();if(d){let p=await fetch(`${rw}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Lc(n.tokensIn),u=Lc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Lc(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(Rm,"usageCommand");function Lc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Lc,"formatTokenCount");var mt=b(require("node:fs"),1),jm=b(require("node:path"),1),ws=require("node:child_process");W();var bs=b(require("node:fs"),1),Jr=b(require("node:path"),1);X();var iw="https://monkeyscode.com/api/latest-version",aw="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",cw=4*60*60*1e3;function Mm(){let s=A();return Jr.join(s.config,"update-check")}l(Mm,"getCachePath");function lw(){try{let s=bs.readFileSync(Mm(),"utf8");return JSON.parse(s)}catch{return null}}l(lw,"readCache");function Bc(s){try{let e=Mm();bs.mkdirSync(Jr.dirname(e),{recursive:!0}),bs.writeFileSync(e,JSON.stringify(s))}catch{}}l(Bc,"writeCache");function Am(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Am,"isNewerVersion");function uw(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(uw,"getAssetKey");async function Uc(s,e=!1){if(!e){let t=lw();if(t&&Date.now()-t.lastCheck<cw)return t.latestVersion&&Am(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await Pm(iw);if(t||(t=await Pm(aw)),!t)return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=uw(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Bc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Am(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Uc,"checkForUpdate");async function Pm(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(Pm,"fetchManifest");function Wc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Wc,"detectInstallMethod");async function Nm(s){let t=(await Promise.resolve().then(()=>(Im(),Om)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.8";if(s.rollback){await Dw(t);return}if(s.check){await mw(t);return}await fw(t,s.version)}l(Nm,"updateCommand");async function mw(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Uc(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(mw,"checkOnly");async function fw(s,e){let t=Wc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await gw(e);break;case"homebrew":await hw();break;case"winget":await yw();break;case"chocolatey":await bw();break;case"scoop":await ww();break;case"binary":await kw(s,e);break;default:console.log(a.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${a.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${a.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${a.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(o){console.error(a.red(` \u274C Update failed: ${o instanceof Error?o.message:String(o)}`)),console.log(a.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}l(fw,"performUpdate");async function gw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,ws.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(gw,"updateViaNpm");async function hw(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,ws.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(hw,"updateViaHomebrew");async function yw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,ws.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(yw,"updateViaWinget");async function bw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,ws.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(bw,"updateViaChocolatey");async function ww(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,ws.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(ww,"updateViaScoop");async function kw(s,e){let t=await Uc(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{mt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${jm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{mt.writeFileSync(n,c),mt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{mt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(kw,"updateViaBinaryDownload");async function Dw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Wc()==="binary"){let t=process.execPath+".backup";if(!mt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{mt.copyFileSync(t,process.execPath),mt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(Dw,"rollback");W();var ks=b(require("node:fs"),1),Yr=b(require("node:path"),1),Um=b(require("node:crypto"),1);X();var zt=!0,Hc="",et=[],Lm=!1,vw="https://monkeyscode.com/api/telemetry",Kr=50,Sw=6e4;function Wm(){let s=A();return Yr.join(s.config,"telemetry.json")}l(Wm,"getConfigPath");function Gc(){try{let s=ks.readFileSync(Wm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:xw()};return qc(s),s}}l(Gc,"loadConfig");function qc(s){try{let e=Wm();ks.mkdirSync(Yr.dirname(e),{recursive:!0}),ks.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(qc,"saveConfig");function xw(){return Um.randomUUID()}l(xw,"generateClientId");function Hm(){if(Lm)return;if(Lm=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){zt=!1;return}let s=Gc();zt=s.enabled,Hc=s.clientId,zt&&(setInterval(()=>Bm(),Sw).unref(),process.on("beforeExit",()=>Bm()))}l(Hm,"initTelemetry");function Gm(){return zt}l(Gm,"isTelemetryEnabled");function qm(){zt=!0;let s=Gc();s.enabled=!0,qc(s)}l(qm,"enableTelemetry");function Vm(){zt=!1,et=[];let s=Gc();s.enabled=!1,qc(s)}l(Vm,"disableTelemetry");function zm(s,e={}){zt&&(et.push({name:s,properties:e,timestamp:new Date().toISOString()}),et.length>Kr&&(et=et.slice(-Kr)))}l(zm,"trackEvent");async function Bm(){if(!zt||et.length===0)return;let s=[...et];et=[];let e=Ce(),o={clientId:Hc,cliVersion:"0.1.8",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(vw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{et.unshift(...s),et.length>Kr&&(et=et.slice(-Kr))}}l(Bm,"flushEvents");function Jm(){let s=Ce();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.8",` \u2022 OS: ${s.os} (${s.arch})`,` \u2022 Shell: ${s.shell}`,` \u2022 Node.js version: ${process.version}`," \u2022 Command used (interactive, headless, background)"," \u2022 Model selected"," \u2022 Duration and token count"," \u2022 Error types (not error content)"," \u2022 Tool usage frequency","","\u274C Never collected:"," \u2022 Prompts or conversation content"," \u2022 Source code or file contents"," \u2022 File paths or project names"," \u2022 Authentication tokens or API keys"," \u2022 Personal information","",`Status: ${zt?"ENABLED":"DISABLED"}`,`Client ID: ${Hc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
490
|
-
`)}l(Jm,"getCollectedDataSummary");async function Km(s){switch(s){case"enable":qm(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":Vm(),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(Jm()),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)")):Gm()?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(Km,"telemetryCommand");var St=b(require("node:fs"),1),Dn=b(require("node:path"),1);W();X();async function Ym(s,e){let t=Ce(),o="0.1.
|
|
489
|
+
`))}}l($m,"mcpBrowseCommand");X();var Ze=b(require("node:fs"),1),kn=b(require("node:path"),1);X();W();var wn={model:"auto",thinkingMode:"fast",maxTokens:1e6,autoApprove:!1,autoCommit:!1,autoBranch:!1,outputFormat:"text",allowedTools:null,deniedTools:[],verbose:!1,theme:"dark",telemetry:!0,endpoint:"",maxCostPerSession:0,maxCostPerMonth:0,costWarningThreshold:.8,defaultMode:"fast",maxTurns:0,webEnabled:!0,offline:!1,dreamAuto:!1,auth:{method:"oauth"},githubToken:"",gitlabToken:"",headlessTimeout:3e5,headlessSandbox:"auto"};var Cm=["plan","fast","thinking"],_m=["dark","light","auto"],Em=["text","json","stream"],Fm={model:l(s=>typeof s!="string"?"must be a string":null,"model"),thinkingMode:l(s=>["fast","reasoning"].includes(s)?null:'must be "fast" or "reasoning"',"thinkingMode"),defaultMode:l(s=>Cm.includes(s)?null:`must be one of: ${Cm.join(", ")}`,"defaultMode"),theme:l(s=>_m.includes(s)?null:`must be one of: ${_m.join(", ")}`,"theme"),outputFormat:l(s=>Em.includes(s)?null:`must be one of: ${Em.join(", ")}`,"outputFormat"),maxTokens:l(s=>typeof s!="number"||s<1?"must be a positive number":null,"maxTokens"),maxTurns:l(s=>typeof s!="number"||s<0?"must be a non-negative number (0 = no limit)":null,"maxTurns"),maxCostPerSession:l(s=>typeof s!="number"||s<0?"must be a non-negative number":null,"maxCostPerSession"),costWarningThreshold:l(s=>typeof s!="number"||s<0||s>1?"must be between 0 and 1":null,"costWarningThreshold")},Nc=class{static{l(this,"ConfigSystem")}globalConfig={};projectConfig={};flagOverrides={};workspace;errors=[];constructor(e){this.workspace=e??process.cwd(),this.reload()}reload(){this.errors=[],this.globalConfig=this.loadFile(this.getGlobalConfigPath(),"global"),this.projectConfig=this.loadFile(this.getProjectConfigPath(),"project")}applyFlags(e){this.flagOverrides=e}get(e){return this.getResolved(e).value}getResolved(e){if(e in this.flagOverrides&&this.flagOverrides[e]!==void 0)return{value:this.flagOverrides[e],source:"flag"};let t=this.getFromEnv(e);return t!==void 0?{value:t,source:"env"}:e in this.projectConfig&&this.projectConfig[e]!==void 0?{value:this.projectConfig[e],source:"project"}:e in this.globalConfig&&this.globalConfig[e]!==void 0?{value:this.globalConfig[e],source:"global"}:{value:wn[e],source:"default"}}listAll(){let e={};for(let t of Object.keys(wn))e[t]=this.getResolved(t);return e}set(e,t,o="global"){let n=Fm[e];if(n){let c=n(t);if(c)return`Invalid value for "${e}": ${c}`}let r=o==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),i=o==="project"?{...this.projectConfig}:{...this.globalConfig};return i[e]=t,Ze.mkdirSync(kn.dirname(r),{recursive:!0}),Ze.writeFileSync(r,JSON.stringify(i,null,2)),this.reload(),null}reset(e,t="global"){let o=t==="project"?this.getProjectConfigPath():this.getGlobalConfigPath(),n={};try{Ze.existsSync(o)&&(n=JSON.parse(Ze.readFileSync(o,"utf8")))}catch{}delete n[e],Ze.writeFileSync(o,JSON.stringify(n,null,2)),this.reload()}getErrors(){return[...this.errors]}getPaths(){return{global:this.getGlobalConfigPath(),project:this.getProjectConfigPath()}}getConfig(){let e={...wn};for(let t of Object.keys(wn))e[t]=this.get(t);return e}getGlobalConfigPath(){let e=A();return kn.join(e.config,"config.json")}getProjectConfigPath(){return kn.join(this.workspace,".monkeyscode","config.json")}loadFile(e,t){try{if(Ze.existsSync(e)){let o=JSON.parse(Ze.readFileSync(e,"utf8"));o=this.migrateConfig(o,e,t);for(let[n,r]of Object.entries(o)){let i=Fm[n];if(i){let c=i(r);c&&(this.errors.push(`\u26A0\uFE0F ${t} config: "${n}" ${c}. Using default.`),delete o[n])}}return o}}catch(o){this.errors.push(`\u26A0\uFE0F Failed to parse ${t} config at ${e}: ${o instanceof Error?o.message:o}`)}return{}}migrateConfig(e,t,o){let n=!1,r={defaultModel:"model",effort:"thinkingMode",platformUrl:"endpoint"};for(let[c,u]of Object.entries(r))c in e&&!(u in e)&&(e[u]=e[c],delete e[c],n=!0);"webEnabled"in e&&!("offline"in e)&&(e.offline=!e.webEnabled,delete e.webEnabled,n=!0),e.defaultMode==="auto"&&(e.defaultMode="fast",n=!0);let i=new Set(Object.keys(wn));for(let c of Object.keys(e))i.has(c);if(n){this.errors.push(`\u2139\uFE0F Migrated ${o} config at ${t}`);try{Ze.writeFileSync(t,JSON.stringify(e,null,2))}catch{}}return e}getFromEnv(e){let o={model:"MONKEYSCODE_MODEL",endpoint:"MONKEYSCODE_PLATFORM_URL",offline:"MONKEYSCODE_OFFLINE",verbose:"MONKEYSCODE_VERBOSE",telemetry:"MONKEYSCODE_TELEMETRY"}[e];if(!o)return;let n=process.env[o];if(n!==void 0)return e==="offline"||e==="verbose"||e==="telemetry"?n==="1"||n.toLowerCase()==="true":n}};function Tm(s){let e=s.listAll(),t=s.getPaths();console.log(""),console.log(a.bold(" \u2699\uFE0F Configuration")),console.log(a.dim(` Global: ${t.global}`)),console.log(a.dim(` Project: ${t.project}`)),console.log(a.dim(" "+"\u2500".repeat(60)));let o={default:a.dim,global:a.cyan,project:a.green,env:a.yellow,flag:a.magenta},n={default:"default",global:"global ",project:"project",env:"env ",flag:"flag "};for(let[i,c]of Object.entries(e)){let u=o[c.source],d=n[c.source],p=typeof c.value=="object"?JSON.stringify(c.value):String(c.value);console.log(` ${a.bold(i.padEnd(24))} ${u(`[${d}]`)} ${p}`)}let r=s.getErrors();if(r.length>0){console.log("");for(let i of r)console.log(a.yellow(` ${i}`))}console.log("")}l(Tm,"printConfigList");var jc=null;function No(s){return(!jc||s)&&(jc=new Nc(s)),jc}l(No,"getConfigSystem");ur();W();_e();ee();var rw=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Rm(){let s=I(),e=H(s),t=s.ansi,o=fe();if(!o){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let n=null;try{let d=await Fe();if(d){let p=await fetch(`${rw}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${d}`}});p.ok&&(n=await p.json())}}catch{}if(!n){let d=new Date;n={period:`${d.toLocaleString("default",{month:"long"})} ${d.getFullYear()}`,plan:o.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let r=n.period,i=n.plan.charAt(0).toUpperCase()+n.plan.slice(1);console.log(t?a.bold(` \u{1F4CA} Monthly Usage (${r})`):` Monthly Usage (${r})`),console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${i}`),console.log(` Sessions: ${n.sessionsCount}`);let c=Lc(n.tokensIn),u=Lc(n.tokensOut);if(console.log(` Tokens: ${c} input, ${u} output`),n.tokensThinking>0&&console.log(` Thinking: ${Lc(n.tokensThinking)}`),n.costLimit>0){let d=Math.round(n.totalCost/n.costLimit*100),p=d>=80?t?a.red(`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`):`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`:`$${n.totalCost.toFixed(2)} / $${n.costLimit.toFixed(2)} (${d}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${n.totalCost.toFixed(2)}`);if(n.byModel.length>0){console.log(" By model:");for(let d of n.byModel)console.log(` ${d.model.padEnd(18)} $${d.cost.toFixed(2)} (${d.sessions} sessions)`)}console.log(t?a.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),n.sessionsCount===0&&n.totalCost===0&&console.log(t?a.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}l(Rm,"usageCommand");function Lc(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(0)}K`:String(s)}l(Lc,"formatTokenCount");var mt=b(require("node:fs"),1),jm=b(require("node:path"),1),ws=require("node:child_process");W();var bs=b(require("node:fs"),1),Jr=b(require("node:path"),1);X();var iw="https://monkeyscode.com/api/latest-version",aw="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",cw=4*60*60*1e3;function Mm(){let s=A();return Jr.join(s.config,"update-check")}l(Mm,"getCachePath");function lw(){try{let s=bs.readFileSync(Mm(),"utf8");return JSON.parse(s)}catch{return null}}l(lw,"readCache");function Bc(s){try{let e=Mm();bs.mkdirSync(Jr.dirname(e),{recursive:!0}),bs.writeFileSync(e,JSON.stringify(s))}catch{}}l(Bc,"writeCache");function Am(s,e){let t=s.split(".").map(Number),o=e.split(".").map(Number);for(let n=0;n<3;n++){if((t[n]||0)>(o[n]||0))return!0;if((t[n]||0)<(o[n]||0))return!1}return!1}l(Am,"isNewerVersion");function uw(){let s=process.platform,e=process.arch;return`cli-${s}-${e}`}l(uw,"getAssetKey");async function Uc(s,e=!1){if(!e){let t=lw();if(t&&Date.now()-t.lastCheck<cw)return t.latestVersion&&Am(t.latestVersion,s)?{version:t.latestVersion,currentVersion:s,downloadUrl:t.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let t=await Pm(iw);if(t||(t=await Pm(aw)),!t)return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let o=t.productVersion||t.version,n=uw(),r=t.assets?.[n],i=r?.url||"https://monkeyscode.com/download";return Bc({lastCheck:Date.now(),latestVersion:o,downloadUrl:i}),o&&Am(o,s)?{version:o,currentVersion:s,downloadUrl:i,sha256:r?.sha256,size:r?.size,publishedAt:t.date||"",commit:t.commit||"",quality:t.quality||"stable"}:null}catch{return Bc({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}l(Uc,"checkForUpdate");async function Pm(s){try{let e=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}l(Pm,"fetchManifest");function Wc(){let s=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":s.includes("/opt/homebrew/")||s.includes("/usr/local/Cellar/")?"homebrew":s.includes("\\scoop\\")?"scoop":s.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(s.includes("\\WindowsApps\\")||s.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}l(Wc,"detectInstallMethod");async function Nm(s){let t=(await Promise.resolve().then(()=>(Im(),Om)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"0.1.9";if(s.rollback){await Dw(t);return}if(s.check){await mw(t);return}await fw(t,s.version)}l(Nm,"updateCommand");async function mw(s){console.log(a.dim(` Current version: v${s}`)),console.log(a.dim(" Checking for updates...")),console.log("");let e=await Uc(s,!0);e?(console.log(a.green(` \u2705 Update available: v${s} \u2192 v${e.version}`)),console.log(a.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(a.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${a.bold("mc update")} to install.`)):console.log(a.green(` \u2705 You're on the latest version (v${s})`)),console.log("")}l(mw,"checkOnly");async function fw(s,e){let t=Wc();console.log(""),console.log(a.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(a.dim(` Current: v${s} \xB7 Method: ${t}`)),console.log(""),e&&console.log(a.dim(` Target version: v${e}`));try{switch(t){case"npm":await gw(e);break;case"homebrew":await hw();break;case"winget":await yw();break;case"chocolatey":await bw();break;case"scoop":await ww();break;case"binary":await kw(s,e);break;default:console.log(a.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${a.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${a.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${a.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(o){console.error(a.red(` \u274C Update failed: ${o instanceof Error?o.message:String(o)}`)),console.log(a.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}l(fw,"performUpdate");async function gw(s){let e=s?`@monkeyscode/cli@${s}`:"@monkeyscode/cli";console.log(a.dim(` Running: npm install -g ${e}`)),(0,ws.execSync)(`npm install -g ${e}`,{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via npm"))}l(gw,"updateViaNpm");async function hw(){console.log(a.dim(" Running: brew upgrade monkeyscode")),(0,ws.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Homebrew"))}l(hw,"updateViaHomebrew");async function yw(){console.log(a.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,ws.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via winget"))}l(yw,"updateViaWinget");async function bw(){console.log(a.dim(" Running: choco upgrade monkeyscode-cli")),(0,ws.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Chocolatey"))}l(bw,"updateViaChocolatey");async function ww(){console.log(a.dim(" Running: scoop update monkeyscode")),(0,ws.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(a.green(" \u2705 Updated via Scoop"))}l(ww,"updateViaScoop");async function kw(s,e){let t=await Uc(s,!0);if(!t&&!e){console.log(a.green(` \u2705 Already on latest version (v${s})`));return}let o=t?.downloadUrl;if(!o)throw new Error("Could not determine download URL");console.log(a.dim(` Downloading from: ${o}`));let n=process.execPath,r=n+".backup";try{mt.copyFileSync(n,r),console.log(a.dim(` Backed up current binary to: ${jm.basename(r)}`))}catch{console.log(a.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let i=await fetch(o,{signal:AbortSignal.timeout(6e4)});if(!i.ok)throw new Error(`Download failed: HTTP ${i.status}`);let c=Buffer.from(await i.arrayBuffer());if(t?.sha256){let d=(await import("node:crypto")).createHash("sha256").update(c).digest("hex");if(d!==t.sha256)throw new Error(`Checksum mismatch (expected ${t.sha256}, got ${d})`);console.log(a.dim(" \u2705 Checksum verified"))}try{mt.writeFileSync(n,c),mt.chmodSync(n,493),console.log(a.green(` \u2705 Updated to v${t?.version||e}`))}catch(u){try{mt.copyFileSync(r,n),console.log(a.yellow(" Restored backup after failed update"))}catch{}throw u}}l(kw,"updateViaBinaryDownload");async function Dw(s){if(console.log(""),console.log(a.bold(" \u23EA Rollback")),console.log(""),Wc()==="binary"){let t=process.execPath+".backup";if(!mt.existsSync(t)){console.log(a.red(" \u274C No backup found. Cannot rollback.")),console.log(a.dim(" Rollback is only available after a binary update."));return}try{mt.copyFileSync(t,process.execPath),mt.chmodSync(process.execPath,493),console.log(a.green(" \u2705 Rolled back to previous version")),console.log(a.dim(" Restart the CLI to use the previous version."))}catch(o){console.error(a.red(` \u274C Rollback failed: ${o instanceof Error?o.message:String(o)}`))}}else console.log(a.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${a.dim(`mc update --version ${s}`)}`);console.log("")}l(Dw,"rollback");W();var ks=b(require("node:fs"),1),Yr=b(require("node:path"),1),Um=b(require("node:crypto"),1);X();var zt=!0,Hc="",et=[],Lm=!1,vw="https://monkeyscode.com/api/telemetry",Kr=50,Sw=6e4;function Wm(){let s=A();return Yr.join(s.config,"telemetry.json")}l(Wm,"getConfigPath");function Gc(){try{let s=ks.readFileSync(Wm(),"utf8");return JSON.parse(s)}catch{let s={enabled:!0,clientId:xw()};return qc(s),s}}l(Gc,"loadConfig");function qc(s){try{let e=Wm();ks.mkdirSync(Yr.dirname(e),{recursive:!0}),ks.writeFileSync(e,JSON.stringify(s,null,2))}catch{}}l(qc,"saveConfig");function xw(){return Um.randomUUID()}l(xw,"generateClientId");function Hm(){if(Lm)return;if(Lm=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){zt=!1;return}let s=Gc();zt=s.enabled,Hc=s.clientId,zt&&(setInterval(()=>Bm(),Sw).unref(),process.on("beforeExit",()=>Bm()))}l(Hm,"initTelemetry");function Gm(){return zt}l(Gm,"isTelemetryEnabled");function qm(){zt=!0;let s=Gc();s.enabled=!0,qc(s)}l(qm,"enableTelemetry");function Vm(){zt=!1,et=[];let s=Gc();s.enabled=!1,qc(s)}l(Vm,"disableTelemetry");function zm(s,e={}){zt&&(et.push({name:s,properties:e,timestamp:new Date().toISOString()}),et.length>Kr&&(et=et.slice(-Kr)))}l(zm,"trackEvent");async function Bm(){if(!zt||et.length===0)return;let s=[...et];et=[];let e=Ce(),o={clientId:Hc,cliVersion:"0.1.9",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:s};try{await fetch(vw,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(5e3)})}catch{et.unshift(...s),et.length>Kr&&(et=et.slice(-Kr))}}l(Bm,"flushEvents");function Jm(){let s=Ce();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 0.1.9",` \u2022 OS: ${s.os} (${s.arch})`,` \u2022 Shell: ${s.shell}`,` \u2022 Node.js version: ${process.version}`," \u2022 Command used (interactive, headless, background)"," \u2022 Model selected"," \u2022 Duration and token count"," \u2022 Error types (not error content)"," \u2022 Tool usage frequency","","\u274C Never collected:"," \u2022 Prompts or conversation content"," \u2022 Source code or file contents"," \u2022 File paths or project names"," \u2022 Authentication tokens or API keys"," \u2022 Personal information","",`Status: ${zt?"ENABLED":"DISABLED"}`,`Client ID: ${Hc||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
490
|
+
`)}l(Jm,"getCollectedDataSummary");async function Km(s){switch(s){case"enable":qm(),console.log(""),console.log(a.green(" \u2705 Telemetry enabled")),console.log(a.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":Vm(),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(Jm()),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)")):Gm()?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(Km,"telemetryCommand");var St=b(require("node:fs"),1),Dn=b(require("node:path"),1);W();X();async function Ym(s,e){let t=Ce(),o="0.1.9";console.log(""),console.log(a.bold(" \u{1F41B} Bug Report")),console.log("");let n={description:s||"(no description provided)",cliVersion:o,nodeVersion:process.version,os:`${t.os} (${t.arch})`,arch:t.arch,shell:t.shell,timestamp:new Date().toISOString()};if(e?.attachCrash){let i=_w();i?(n.crashLog=i,console.log(a.dim(" \u{1F4CE} Attached latest crash report"))):console.log(a.dim(" No crash reports found"))}if(await $w(n))console.log(a.green(" \u2705 Bug report submitted")),console.log(a.dim(" Thank you! Our team will review your report."));else{let i=Cw(n);console.log(a.yellow(" \u26A0\uFE0F Could not submit online (saved locally)")),console.log(a.dim(` Report: ${i}`)),console.log(a.dim(" Submit later: mc bug --submit-local"))}console.log("")}l(Ym,"bugCommand");async function $w(s){try{return(await fetch("https://monkeyscode.com/api/bug-reports",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:AbortSignal.timeout(1e4)})).ok}catch{return!1}}l($w,"submitReport");function Cw(s){let e=A(),t=Dn.join(e.config,"bug-reports");St.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Dn.join(t,`${o}.json`);return St.writeFileSync(n,JSON.stringify(s,null,2)),n}l(Cw,"saveReportLocally");function _w(){try{let s=A(),e=Dn.join(s.config,"crashes");if(!St.existsSync(e))return null;let t=St.readdirSync(e).filter(o=>o.endsWith(".log")).sort().reverse();return t.length===0?null:St.readFileSync(Dn.join(e,t[0]),"utf8")}catch{return null}}l(_w,"getLatestCrashLog");var Lo=b(require("node:fs"),1),Vc=b(require("node:path"),1);W();X();_e();function Xm(){let s=A(),e=Vc.join(s.config,"config.json");return!Lo.existsSync(e)}l(Xm,"isFirstRun");function Ew(){let e=A().config,t=Vc.join(e,"config.json");Lo.mkdirSync(e,{recursive:!0}),Lo.existsSync(t)||Lo.writeFileSync(t,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}l(Ew,"markOnboardingComplete");async function Qm(){let s=I(),e=Ce();console.log(""),console.log(a.bold(" \u{1F435} Welcome to MonkeysCode!")),console.log(a.dim(" \u2500".repeat(30))),console.log(""),console.log(" MonkeysCode is an AI coding agent that lives in your terminal."),console.log(" It can edit files, run commands, search code, and manage git \u2014"),console.log(" all from natural language prompts."),console.log(""),console.log(a.dim(` Platform: ${e.os} (${e.arch}) \xB7 Shell: ${e.shell}`)),console.log(""),console.log(a.bold(" \u{1FA7A} Quick Setup Check")),console.log("");let t=[],o=parseInt(process.version.slice(1).split(".")[0],10);t.push({name:"Node.js",ok:o>=20,msg:o>=20?process.version:`${process.version} (requires >= 20)`});try{let{execSync:n}=await import("node:child_process"),r=n("git --version",{encoding:"utf8"}).trim();t.push({name:"Git",ok:!0,msg:r.replace("git version ","")})}catch{t.push({name:"Git",ok:!1,msg:"not found"})}try{let{execSync:n}=await import("node:child_process"),r=n("rg --version",{encoding:"utf8"}).split(`
|
|
491
491
|
`)[0];t.push({name:"ripgrep",ok:!0,msg:r.replace("ripgrep ","")})}catch{t.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let n of t){let r=n.ok?a.green(" \u2705"):a.yellow(" \u26A0\uFE0F ");console.log(`${r} ${n.name}: ${a.dim(n.msg)}`)}console.log(""),console.log(a.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${a.cyan("mc auth login")}`),console.log(""),console.log(a.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${a.dim("Interactive:")} ${a.cyan("mc")} Open the REPL`),console.log(` ${a.dim("One-shot:")} ${a.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${a.dim("Background:")} ${a.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${a.dim("Health:")} ${a.cyan("mc doctor")} Check your setup`),console.log(` ${a.dim("Help:")} ${a.cyan("mc --help")} See all commands`),console.log(""),console.log(a.dim(" \u2500".repeat(30))),console.log(a.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),Ew()}l(Qm,"runOnboarding");var go=b(require("node:fs"),1),Xr=b(require("node:path"),1);X();var Zm=[];function tf(){process.on("uncaughtException",s=>{ef(s,"uncaughtException"),console.error(`
|
|
492
492
|
\u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${s.message}
|
|
493
|
-
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));ef(e,"unhandledRejection")})}l(tf,"installCrashHandler");function Fw(){let s=A();return Xr.join(s.config,"crashes")}l(Fw,"getCrashDir");function ef(s,e){try{let t=Fw();go.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Xr.join(t,`${o}.log`),r=Ce(),c=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 0.1.
|
|
493
|
+
`),process.exit(1)}),process.on("unhandledRejection",s=>{let e=s instanceof Error?s:new Error(String(s));ef(e,"unhandledRejection")})}l(tf,"installCrashHandler");function Fw(){let s=A();return Xr.join(s.config,"crashes")}l(Fw,"getCrashDir");function ef(s,e){try{let t=Fw();go.mkdirSync(t,{recursive:!0});let o=new Date().toISOString().replace(/[:.]/g,"-"),n=Xr.join(t,`${o}.log`),r=Ce(),c=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 0.1.9",`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",Zm.length>0?Zm.map((u,d)=>` ${d+1}. ${u}`).join(`
|
|
494
494
|
`):" (none)","","\u2500\u2500 Environment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`TERM: ${process.env.TERM||"(not set)"}`,`CI: ${process.env.CI||"false"}`,`MONKEYSCODE_HEADLESS: ${process.env.MONKEYSCODE_HEADLESS||"false"}`,"","\u2550".repeat(60)," Submit this report: mc bug --attach-crash","\u2550".repeat(60),""].join(`
|
|
495
495
|
`);go.writeFileSync(n,c),Tw(t,20)}catch{}}l(ef,"writeCrashReport");function Tw(s,e){try{let t=go.readdirSync(s).filter(o=>o.endsWith(".log")).sort().reverse();for(let o=e;o<t.length;o++)go.unlinkSync(Xr.join(s,t[o]))}catch{}}l(Tw,"pruneOldReports");var Me=b(require("node:fs"),1),Kt=b(require("node:path"),1),Rw=require("node:child_process");W();X();_e();var Aw="MEMORY.md",of=".monkeyscode";async function sf(s={}){let e=H(I()),t=A(),o=s.since||"7d";if(s.mode&&s.mode!=="consolidate"){await Ow(s.mode);return}console.log(),console.log(a.bold(" \u{1F4A4} Memory Consolidation")),console.log(a.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));let n=Kt.join(t.data,"sessions");if(!Me.existsSync(n)){console.log(` ${e.info} No sessions found. Use ${a.cyan("mc")} to create some first.`);return}let r=Pw(o),i=Me.readdirSync(n).filter(h=>h.endsWith(".json")).map(h=>({name:h,path:Kt.join(n,h),mtime:Me.statSync(Kt.join(n,h)).mtimeMs})).filter(h=>h.mtime>=r).sort((h,y)=>y.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 y=JSON.parse(Me.readFileSync(h.path,"utf8"));if(y.toolCalls){for(let S of y.toolCalls)if(S.tool==="file_edit"&&S.args?.path){let D=Kt.extname(S.args.path);if(D){let C=`Works primarily with ${D} files`;c.set(C,(c.get(C)||0)+1)}}}if(y.messages){let S=JSON.stringify(y.messages).toLowerCase();S.includes("vitest")&&Jt(c,"Uses vitest for testing"),S.includes("jest")&&Jt(c,"Uses jest for testing"),S.includes("mocha")&&Jt(c,"Uses mocha for testing"),S.includes("zod")&&Jt(c,"Uses Zod for runtime validation"),S.includes("joi")&&Jt(c,"Uses Joi for validation"),S.includes("tailwind")&&Jt(c,"Uses Tailwind CSS"),S.includes("styled-components")&&Jt(c,"Uses styled-components"),S.includes("result<")&&Jt(c,"Uses Result<T, E> pattern for error handling"),(S.includes("try/catch")||S.includes("try {"))&&Jt(c,"Uses try/catch for error handling")}}catch{}let u=Math.max(2,Math.floor(i.length*.3)),d=[];for(let[h,y]of c)y>=u&&d.push({rule:h,count:y});if(d.sort((h,y)=>y.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=Kt.join(process.cwd(),of,Aw);Me.mkdirSync(Kt.join(process.cwd(),of),{recursive:!0});let f="";Me.existsSync(p)&&(f=Me.readFileSync(p,"utf8"));let m=new Date().toISOString().split("T")[0],g=f.trimEnd();g||(g=`# Project Memory
|
|
496
496
|
|
|
@@ -708,7 +708,7 @@ ${s}`,o}l(Tk,"buildBugfindPrompt");function yg(s){let e=[],t=s.split(`
|
|
|
708
708
|
|
|
709
709
|
${r}
|
|
710
710
|
|
|
711
|
-
${cl(e)}`})});i.ok?console.log(a.green(` \u2705 Review posted on PR #${s}`)):console.log(a.yellow(` \u26A0 Failed to post review: ${i.status}`))}catch(i){console.log(a.yellow(` \u26A0 Failed to post review: ${i instanceof Error?i.message:i}`))}}l(Ak,"postReviewComments");function kg(s){try{let e=(0,Ho.execSync)("git remote get-url origin",{cwd:s,encoding:"utf8"}).trim(),t=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(t)return{type:"github",owner:t[1],repo:t[2],url:e};let o=e.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);return o?{type:"gitlab",owner:o[1],repo:o[2],url:e}:{type:"unknown",owner:"",repo:"",url:e}}catch{return{type:"unknown",owner:"",repo:"",url:""}}}l(kg,"getGitRemote");function Dg(){if(process.env.GITHUB_TOKEN)return process.env.GITHUB_TOKEN;if(process.env.GH_TOKEN)return process.env.GH_TOKEN;if(process.env.GITLAB_TOKEN)return process.env.GITLAB_TOKEN;try{let s=_t.join(process.cwd(),".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}try{let s=_t.join(process.env.HOME||process.env.USERPROFILE||"",".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}return null}l(Dg,"getGitToken");function Pk(s,e){let t=[];function n(r){if(t.length>=50)return;let i=ke.readdirSync(r,{withFileTypes:!0});for(let c of i){if(t.length>=50)return;let u=_t.join(r,c.name);if(c.isDirectory()){if(["node_modules",".git","vendor","dist","build","__pycache__",".next"].includes(c.name))continue;n(u)}else e.some(d=>c.name.endsWith(d))&&t.push(u)}}return l(n,"walk"),n(s),t}l(Pk,"collectFiles");tf();Hm();globalThis.__mcChalk=a;var ml="0.1.
|
|
711
|
+
${cl(e)}`})});i.ok?console.log(a.green(` \u2705 Review posted on PR #${s}`)):console.log(a.yellow(` \u26A0 Failed to post review: ${i.status}`))}catch(i){console.log(a.yellow(` \u26A0 Failed to post review: ${i instanceof Error?i.message:i}`))}}l(Ak,"postReviewComments");function kg(s){try{let e=(0,Ho.execSync)("git remote get-url origin",{cwd:s,encoding:"utf8"}).trim(),t=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(t)return{type:"github",owner:t[1],repo:t[2],url:e};let o=e.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);return o?{type:"gitlab",owner:o[1],repo:o[2],url:e}:{type:"unknown",owner:"",repo:"",url:e}}catch{return{type:"unknown",owner:"",repo:"",url:""}}}l(kg,"getGitRemote");function Dg(){if(process.env.GITHUB_TOKEN)return process.env.GITHUB_TOKEN;if(process.env.GH_TOKEN)return process.env.GH_TOKEN;if(process.env.GITLAB_TOKEN)return process.env.GITLAB_TOKEN;try{let s=_t.join(process.cwd(),".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}try{let s=_t.join(process.env.HOME||process.env.USERPROFILE||"",".monkeyscode","config.json");if(ke.existsSync(s)){let e=JSON.parse(ke.readFileSync(s,"utf8"));if(e.githubToken)return e.githubToken;if(e.gitlabToken)return e.gitlabToken}}catch{}return null}l(Dg,"getGitToken");function Pk(s,e){let t=[];function n(r){if(t.length>=50)return;let i=ke.readdirSync(r,{withFileTypes:!0});for(let c of i){if(t.length>=50)return;let u=_t.join(r,c.name);if(c.isDirectory()){if(["node_modules",".git","vendor","dist","build","__pycache__",".next"].includes(c.name))continue;n(u)}else e.some(d=>c.name.endsWith(d))&&t.push(u)}}return l(n,"walk"),n(s),t}l(Pk,"collectFiles");tf();Hm();globalThis.__mcChalk=a;var ml="0.1.9",qo="auto";function $g(s){let e=No(s);return{defaultModel:e.get("model"),defaultMode:e.get("defaultMode"),maxTokens:e.get("maxTokens")}}l($g,"loadConfig");var z=new Fl;z.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
|
|
712
712
|
Runs independently of the IDE and Agent Manager.
|
|
713
713
|
Connects directly to model-proxy via SSE streaming.`).version(ml);z.argument("[prompt]","Prompt for the agent").option("-p, --prompt <prompt>","Prompt (alternative to positional argument)").option("--headless","Headless mode \u2014 run without interactive UI",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",qo).option("--mode <mode>","Agent mode: plan, fast, thinking","fast").option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Rt("-o, --output <format>","Output format").choices(["text","json","jsonl","diff","markdown","github","azure","sarif","stream"]).default("text")).option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("--continue","Resume the last session",!1).option("--auto-approve","Auto-approve all tool calls",!1).option("--approve-for-me","Smart auto-approval (safe=auto, risky=prompt, dangerous=block)",!1).option("--yolo","Bypass all permission checks (requires explicit opt-in)",!1).addOption(new Rt("--permission-mode <mode>","Permission mode").choices(["default","plan","ask","acceptEdits","bypassPermissions"]).default("default")).option("--allowed-tools <tools>","Comma-separated list of allowed tool names","").option("--denied-tools <tools>","Comma-separated list of denied tool names","").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new Rt("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Rt("--sandbox-provider <provider>","Sandbox provider override").choices(["auto","bubblewrap","sandbox-exec","docker","windows-sandbox"])).option("--no-hooks","Disable all lifecycle hooks").option("--hook-timeout <ms>","Hook timeout in milliseconds","10000").option("--no-web","Disable web search (air-gapped mode)").option("--auto-branch","Create a new branch for changes",!1).option("--auto-commit","Auto-commit changes after successful run",!1).option("--auto-pr","Create a pull request after background job completes",!1).option("--worktree","Run agent in an isolated git worktree",!1).option("--resume <job-id>","Resume from a completed cloud job").option("--profile <name>","Auth profile to use","default").option("--endpoint <url>","Custom model gateway URL").option("--ca-cert <path>","Custom CA certificate for corporate proxies").option("--offline","Offline mode \u2014 no internet, local models only",!1).option("--accessible","Screen reader-friendly output (no ANSI, no spinners)",!1).option("--screen-reader","Alias for --accessible",!1).option("--max-cost <dollars>","Maximum session cost in dollars (e.g. 2.00)").option("--max-tokens <count>","Maximum total tokens (input + output)").option("--timeout <ms>","Headless timeout in milliseconds (default: 300000)","300000").action(async(s,e)=>{let t=L.resolve(e.workspace),o=$g(t),n=s||e.prompt;if(n&&n.startsWith("/"))switch(n.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":n=void 0;break;case"/version":case"/v":console.log(ml),process.exit(0);break;case"/doctor":await ln(),process.exit(0);break;case"/exit":case"/quit":case"/q":process.exit(0);break;default:break}if(e.caCert||process.env.MONKEYSCODE_CA_CERT){let u=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=u}let r=wt(e.model||o.defaultModel);!n&&process.stdin.isTTY&&!e.continue&&e.headless;let i=e.yolo?"bypassPermissions":e.permissionMode||"default",c={prompt:n,workspace:t,model:r,mode:e.mode||o.defaultMode,headless:e.headless,background:e.background,autoApprove:e.autoApprove||e.yolo,approveForMe:e.approveForMe,permissionMode:i,sandbox:e.sandbox??!1,verbose:e.verbose,showThinking:e.showThinking,output:e.output,budget:parseInt(e.budget,10),continueSession:e.continue,allowedTools:e.allowedTools?e.allowedTools.split(",").map(u=>u.trim()):[],deniedTools:e.deniedTools?e.deniedTools.split(",").map(u=>u.trim()):[],maxCost:e.maxCost?parseFloat(e.maxCost):void 0,profile:e.profile,offline:e.offline,timeout:parseInt(e.timeout,10),autoBranch:e.autoBranch,autoPR:e.autoPr,autoCommit:e.autoCommit,worktree:e.worktree,resume:e.resume};await hm(c)});var On=z.command("auth").description("Manage authentication");On.command("login").description("Authenticate with MonkeysCode (device code flow \u2014 opens browser)").option("--email","Use email/password login instead of browser").option("--sso","Use enterprise SSO (SAML/OIDC)").option("--profile <name>","Auth profile name","default").action(async s=>{s.sso?await wa(s.profile):s.email?await ma():await pa()});On.command("logout").description("Remove stored credentials").option("--profile <name>","Auth profile name","default").action(s=>ka(s.profile));On.command("token <token>").description("Set API token directly (for CI/CD environments)").option("--profile <name>","Auth profile name","default").action((s,e)=>ga(s,e.profile));On.command("status").description("Check authentication status").option("--profile <name>","Auth profile name","default").action(async s=>await er(s.profile));On.command("refresh").description("Manually refresh the access token").action(async()=>await ha());z.command("status").description("Show account and agent status").action(async()=>{let s=$g(),e=new Co,{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),o=t();e.printBanner("System Status"),await er(),console.log(` Model: ${s.defaultModel}`),console.log(` Mode: ${s.defaultMode}`),console.log(` Proxy: ${o.platformUrl}`),console.log(" Engine: Standalone (no daemon)"),console.log("")});z.command("doctor").description("Run system health checks").option("--fix","Auto-fix common issues").action(s=>ln(s));z.command("update").description("Update MonkeysCode CLI to the latest version").option("--check","Only check for updates, do not install").option("--version <version>","Install a specific version").option("--rollback","Rollback to the previous version").action(s=>Nm(s));z.command("telemetry [action]").description("Manage telemetry (status, enable, disable, show)").action(s=>Km(s));z.command("bug [description]").description("Submit a bug report with session context").option("--attach-crash","Attach the latest crash report").action((s,e)=>Ym(s,e));z.command("dream").description("Consolidate session history into project memory").option("--since <duration>","Time range (e.g., 7d, 14d, 1m)","7d").option("--review","Preview changes without writing",!1).option("--audit","Run security + dependency audit",!1).option("--refactor","Find refactoring opportunities",!1).option("--docs","Generate/update documentation",!1).option("--test-gaps","Find untested code paths",!1).action(s=>{let e=s.audit?"audit":s.refactor?"refactor":s.docs?"docs":s.testGaps?"test-gaps":"consolidate";sf({since:s.since,review:s.review,mode:e})});var In=z.command("config").description("Manage CLI configuration");In.command("set <key> <value>").description("Set a config value").option("--project","Set at project level instead of global",!1).option("--workspace <path>","Workspace path",".").action((s,e,t)=>{let o=L.resolve(t.workspace),n=No(o),r=t.project?"project":"global",i=e;e==="true"?i=!0:e==="false"?i=!1:isNaN(Number(e))||(i=Number(e));let c=n.set(s,i,r);c&&(console.error(` \u26A0\uFE0F ${c}`),process.exit(1)),console.log(` Set ${s} = ${e} [${r}]`)});In.command("get [key]").description("Get a config value (or all values)").option("--workspace <path>","Workspace path",".").action((s,e)=>{let t=No(L.resolve(e.workspace));if(s){let o=t.getResolved(s);console.log(` ${s} = ${JSON.stringify(o.value)} [${o.source}]`)}else console.log(JSON.stringify(t.getConfig(),null,2))});In.command("list").description("Show all resolved config values with their source").option("--workspace <path>","Workspace path",".").action(s=>{let e=No(L.resolve(s.workspace));Tm(e)});In.command("reset <key>").description("Reset a config key to its default").option("--project","Reset at project level",!1).action((s,e)=>{No().reset(s,e.project?"project":"global"),console.log(` Reset ${s} to default.`)});In.command("path").description("Show config file locations").action(()=>{let s=A(),t=No().getPaths();console.log(` Global: ${t.global}`),console.log(` Project: ${t.project}`),console.log(` Data: ${s.data}`),console.log(` Logs: ${s.logs}`),console.log(` PID: ${s.pidFile}`)});z.command("index [path]").description("Index a workspace for context retrieval").option("--force","Force full re-index",!1).action(async(s,e)=>{let t=L.resolve(s||"."),o=new Co;o.printBanner("Workspace Indexer"),console.log(` Path: ${t}`),console.log("");let n=new po;o.startSpinner("Connecting to daemon...");try{await n.connect(),o.succeedSpinner("Connected"),o.startSpinner("Indexing workspace...");let r=await n.call("index",{workspace:t,force:e.force});o.succeedSpinner("Indexing complete"),console.log(` Files scanned: ${r.files_scanned}`),console.log(` Chunks created: ${r.chunks_created}`),console.log(` Duration: ${r.duration_ms}ms`),console.log("")}catch(r){o.failSpinner("Indexing failed"),console.error(` Error: ${r instanceof Error?r.message:r}`)}finally{n.disconnect()}});var jn=z.command("mcp").description("Manage MCP (Model Context Protocol) servers");jn.command("list").description("List configured MCP servers").option("--workspace <path>","Workspace path",".").action(async s=>{await Dm(L.resolve(s.workspace))});jn.command("add <name> [command] [args...]").description("Add an MCP server (from registry or manually)").option("--workspace <path>","Workspace path",".").action((s,e,t,o)=>{vm(L.resolve(o.workspace),s,e,t||[])});jn.command("remove <name>").description("Remove an MCP server from project config").option("--workspace <path>","Workspace path",".").action((s,e)=>{Sm(L.resolve(e.workspace),s)});jn.command("test <name>").description("Test connectivity to an MCP server").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await xm(L.resolve(e.workspace),s)});jn.command("browse [query]").description("Browse 35+ curated MCP servers").action(s=>{$m(s)});var Gk=z.command("agents").description("View active agent sessions dashboard").action(async()=>{await Oc(!0)});Gk.command("list").description("List active agents (non-interactive, for scripting)").action(async()=>{await Oc(!1)});var Cs=z.command("context").description("Semantic code search and workspace indexing");Cs.command("index").description("Index the current workspace for semantic search").action(async()=>{await Bo(["index"],{})});Cs.command("search <query>").description("Semantic search across indexed code").option("-k, --top-k <number>","Number of results","10").action(async(s,e)=>{await Bo(["search",s],{topK:e.topK})});Cs.command("status").description("Show index status and statistics").action(async()=>{await Bo(["status"],{})});Cs.command("rebuild").description("Force a full re-index of the workspace").action(async()=>{await Bo(["rebuild"],{})});Cs.command("related <file>").description("Find files related to a given file").action(async s=>{await Bo(["related",s],{})});Cs.command("rank <query>").description("Rank workspace files by relevance to a query").action(async s=>{await Bo(["rank",s],{})});var Vo=z.command("triggers").description("Manage event-driven agent triggers");Vo.command("list").description("Show configured triggers").action(async()=>{await yo(["list"],{})});Vo.command("add").description("Add a new trigger").requiredOption("--event <type>","Event type (github.*, cron, file.changed)").requiredOption("--prompt <text>","Agent prompt when trigger fires").option("--name <name>","Trigger name").option("--schedule <cron>","Cron expression (for cron events)").option("--model <model>","Model to use").option("--filter <json>","Event filter (JSON)").action(async s=>{await yo(["add"],s)});Vo.command("remove <name>").description("Remove a trigger by name").action(async s=>{await yo(["remove",s],{})});Vo.command("test <name>").description("Dry-run a trigger to test matching").action(async s=>{await yo(["test",s],{})});Vo.command("enable <name>").description("Enable a disabled trigger").action(async s=>{await yo(["enable",s],{})});Vo.command("disable <name>").description("Disable a trigger without removing it").action(async s=>{await yo(["disable",s],{})});Vo.command("serve").description("Start the trigger engine daemon (webhooks, cron, file watcher)").option("--port <port>","Webhook server port","9122").action(async s=>{await yo(["serve"],{port:s.port})});z.command("completions <shell>").description("Generate shell completion scripts (bash, zsh, fish, pwsh)").option("--install","Show install instructions instead of the script").action((s,e)=>{let t=["bash","zsh","fish","pwsh"];t.includes(s)||(console.error(` Invalid shell: ${s}. Supported: ${t.join(", ")}`),process.exit(1));let o=s;e.install?(console.log(""),console.log(bm(o)),console.log("")):console.log(ym(o))});var pi=z.command("sessions").description("Manage saved conversation sessions");pi.command("list").description("List recent sessions").action(()=>ag());pi.command("show <id>").description("Show session details").action(s=>cg(s));pi.command("delete <id>").description("Delete a session").action(s=>lg(s));pi.command("prune").description("Remove old sessions").option("--older-than <days>","Delete sessions older than N days","30").action(s=>{ug(parseInt(s.olderThan,10))});var Qt=z.command("jobs").description("Manage background agent jobs");Qt.command("list").description("List all background jobs").option("--status <status>","Filter by status: running, queued, completed, failed").option("--since <duration>","Show jobs since (e.g., 7d, 24h)").option("--limit <n>","Max results","20").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated. Run `mc auth login`."),process.exit(3));let r=new Ne(o.platformUrl,n.access_token),i=parseInt(s.limit,10),[c,u]=await Promise.all([r.list({status:s.status,since:s.since,limit:i}).catch(()=>[]),Promise.resolve(bc({status:s.status,limit:i}))]),d=[...c,...u].sort((p,f)=>f.createdAt.getTime()-p.createdAt.getTime()).slice(0,i);vc(d)});Qt.command("status <id>").description("Detailed status of a background job").action(async s=>{if(s.startsWith("local-")){let u=wc(s);u||(console.error(`Job ${s} not found.`),process.exit(1));let d=kc(s);Wr(u,d);return}let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let r=new Ne(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);Wr(i,c)});Qt.command("logs <id>").description("Full log output of a job").option("--follow","Live tail logs",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let i=new Ne(n.platformUrl,r.access_token);if(e.follow){for await(let u of i.followLogs(s))Hr(u);let c=await i.status(s);if(c&&(c.status==="completed"||c.status==="failed")){let{notifyJobComplete:u}=await Promise.resolve().then(()=>(xg(),Sg));u(s,`"${c.prompt.substring(0,60)}" \u2014 ${c.status}${c.duration?` in ${Math.round(c.duration/1e3)}s`:""}`,c.status==="completed")}}else{let c=await i.logs(s);for(let u of c)Hr(u)}});Qt.command("cancel <id>").description("Cancel a running or queued job").option("--force","Skip confirmation",!1).action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),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 Ne(n.platformUrl,r.access_token).cancel(s);c.success?console.log(` \u2705 Job ${s} cancelled.`):console.error(` \u274C Failed: ${c.error}`)});Qt.command("retry <id>").description("Retry a failed job").option("--model <model>","Use a different model").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(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}`)});Qt.command("diff <id>").description("Show unified diff from a completed job").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new Ne(o.platformUrl,n.access_token).diff(s);i?process.stdout.write(i):console.error(` No diff available for job ${s}.`)});Qt.command("pull <id>").description("Pull changes from a completed job into current branch").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{let{loadSettings:t}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:o}=await Promise.resolve().then(()=>(ee(),ge)),n=t(),r=o();r?.access_token||(console.error("Not authenticated."),process.exit(3));let c=await new Ne(n.platformUrl,r.access_token).status(s);c?.branch||(console.error(` No branch found for job ${s}.`),process.exit(1)),Dc(L.resolve(e.workspace),s,c.branch)});Qt.action(()=>{Qt.outputHelp()});var Go=z.command("schedule").description("Manage scheduled/recurring agent jobs").argument("[prompt]","Task prompt (shorthand for `schedule create`)").option("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".");Go.action(async(s,e)=>{s&&e.cron?await al({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:L.resolve(e.workspace)}):s?(console.error('Error: --cron is required. Usage: mc schedule "prompt" --cron "0 9 * * 1"'),process.exit(1)):Go.outputHelp()});Go.command("create <prompt>").description("Create a recurring scheduled job").requiredOption("--cron <expression>","Cron expression (5 fields)").option("--model <model>","Model to use",qo).option("--auto-branch","Create branch for each run",!1).option("--auto-commit","Auto-commit changes",!1).option("--auto-pr","Create PR on completion",!1).option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await al({prompt:s,cron:e.cron,model:wt(e.model),autoBranch:e.autoBranch,autoCommit:e.autoCommit,autoPR:e.autoPr,workspace:L.resolve(e.workspace)})});Go.command("list").description("List all scheduled jobs").action(async()=>{await dg()});Go.command("delete <id>").description("Delete a scheduled job").action(async s=>{await pg(s)});Go.command("pause <id>").description("Pause a scheduled job").action(async s=>{await mg(s)});Go.command("resume <id>").description("Resume a paused scheduled job").action(async s=>{await fg(s)});var Mn=z.command("team").description("Spawn parallel agent teams in git worktrees").argument("[tasks...]","Task prompts (shorthand for `team spawn`)").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".");Mn.action(async(s,e)=>{s.length>0?await Gr({tasks:s,workspace:L.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1}):Mn.outputHelp()});Mn.command("spawn").description("Spawn a team of agents, each in its own worktree").argument("<tasks...>","Task prompts for each agent").option("--model <model>","Model to use",qo).option("--max-agents <n>","Max concurrent agents","3").option("--workspace <path>","Workspace path",".").action(async(s,e)=>{await Gr({tasks:s,workspace:L.resolve(e.workspace),model:wt(e.model),maxAgents:parseInt(e.maxAgents,10),background:!1})});Mn.command("status").description("Show status of all agent teams").option("--workspace <path>","Workspace path",".").action(s=>{Fc(L.resolve(s.workspace))});Mn.command("merge <team-id>").description("Merge all completed agent branches into current branch").option("--workspace <path>","Workspace path",".").action((s,e)=>{Tc(L.resolve(e.workspace),s)});var di=z.command("worktrees").description("Manage git worktrees used by agent teams");di.command("list").description("List all active MonkeysCode worktrees").option("--workspace <path>","Workspace path",".").action(s=>{let e=ys(L.resolve(s.workspace));if(e.length===0){console.log(" No active worktrees.");return}console.log(` Found ${e.length} worktree(s):`);for(let t of e){let o=t.createdAt?`${Math.round((Date.now()-t.createdAt.getTime())/36e5)}h ago`:"";console.log(` ${t.branch.padEnd(40)} ${t.path.padEnd(50)} ${o}`)}});di.command("clean").description("Remove stale worktrees older than TTL").option("--ttl <hours>","TTL in hours (default: 24)","24").option("--force","Force removal",!1).option("--workspace <path>","Workspace path",".").action(s=>{let e=em({workspace:L.resolve(s.workspace),ttlMs:parseInt(s.ttl,10)*36e5,force:s.force});if(e.removed.length>0?console.log(` \u{1F9F9} Removed ${e.removed.length} stale worktree(s).`):console.log(" No stale worktrees to clean."),e.errors.length>0)for(let t of e.errors)console.error(` \u26A0 ${t}`)});di.action(()=>{di.outputHelp()});var pl=z.command("messages").description("Cross-session messaging");pl.command("list").description("Show recent cross-session messages").option("--limit <n>","Max messages","50").action(async s=>{let{loadSettings:e}=await Promise.resolve().then(()=>(Q(),Se)),{loadAuth:t}=await Promise.resolve().then(()=>(ee(),ge)),o=e(),n=t();n?.access_token||(console.error("Not authenticated."),process.exit(3));let i=await new fn(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)});pl.action(()=>{pl.outputHelp()});var Cg=z.command("hooks").description("Manage lifecycle hooks");Cg.command("list").description("List all active hooks").option("--workspace <path>","Workspace path",".").action(s=>{Ic(L.resolve(s.workspace))});Cg.action(()=>{Ic(L.resolve("."))});var _g=z.command("models").description("Manage available models");_g.command("list").description("Show available models with pricing and capabilities").action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),ge))).loadAuth();Fa(s?.org?.plan)});_g.action(async()=>{let s=(await Promise.resolve().then(()=>(ee(),ge))).loadAuth();Fa(s?.org?.plan)});z.command("usage").description("Show monthly usage breakdown").action(async()=>{await Rm()});z.command("init").description("Initialize MonkeysCode for this project (generates rules & config)").option("--workspace <path>","Workspace path",".").action(async s=>{let e=L.resolve(s.workspace),t=L.join(e,".monkeyscode","rules.md"),o=L.join(e,".monkeyscode","config.json");if(Y.existsSync(t)&&Y.existsSync(o)){console.log(""),console.log(a.yellow(" \u26A0\uFE0F .monkeyscode/ already exists.")),console.log(a.dim(` ${t}`)),console.log(a.dim(` ${o}`)),console.log(" Use `mc memory` to modify rules, `mc config set` for config."),console.log("");return}console.log(""),console.log(a.bold(" \u{1F435} Initializing MonkeysCode")),console.log("");let n=["# Project Conventions",""],r=L.join(e,"package.json"),i=L.join(e,"Cargo.toml"),c=L.join(e,"pyproject.toml"),u=L.join(e,"tsconfig.json"),d=L.join(e,"go.mod"),p=Y.readdirSync(e).filter(h=>h.endsWith(".csproj")),f="Unknown";if(Y.existsSync(r))try{let h=JSON.parse(Y.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{}Y.existsSync(u)&&(n.push("## TypeScript"),n.push("- Use strict TypeScript with explicit types"),n.push("- Prefer `interface` over `type` for object shapes"),n.push(""),f="TypeScript"),Y.existsSync(i)&&(n.push("## Language: Rust"),n.push("- Follow Rust idioms (Result/Option, no unwrap in production)"),n.push(""),f="Rust"),Y.existsSync(c)&&(n.push("## Language: Python"),n.push("- Follow PEP 8 conventions"),n.push(""),f="Python"),Y.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(`
|
|
714
714
|
`),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.`)),Y.mkdirSync(L.join(e,".monkeyscode"),{recursive:!0}),Y.writeFileSync(t,m,"utf8"),Y.existsSync(o)||Y.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 _s=z.command("memory").description("Manage project conventions and rules");_s.command("show").description("Show resolved rules from all sources").option("--workspace <path>","Workspace path",".").action(s=>{let e=L.resolve(s.workspace),t=A(),o=L.join(e,".monkeyscode","rules.md"),n=L.join(t.config,"rules.md"),r=L.join(e,".monkeyscode","MEMORY.md");if(console.log(""),console.log(a.bold(" \u{1F4DD} Resolved Rules")),console.log(a.dim(" "+"\u2500".repeat(50))),Y.existsSync(o)){console.log(a.green(" [project]")+a.dim(` ${o}`));let i=Y.readFileSync(o,"utf8");for(let u of i.split(`
|