monkeyscode-cli 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -54,7 +54,7 @@ Exit codes (print mode, -p):
54
54
  `)+`
55
55
  `}var St,TAe,BA=P(()=>{"use strict";St={success:0,runtime:1,usage:2,auth:3,quota:4,guard:5,denied:6,timeout:124,interrupted:130},TAe=[[St.success,"success"],[St.runtime,"runtime error (model, tool or network failure after retries)"],[St.usage,"usage error (bad flags, missing prompt, unreadable --json-schema)"],[St.auth,"authentication error (not logged in, 401)"],[St.quota,"quota or entitlement (plan limit reached, 402/403)"],[St.guard,"cost or token guard tripped (--max-cost / --max-tokens)"],[St.denied,"permission denied (every mutating tool call was refused)"],[St.timeout,"--timeout reached"],[St.interrupted,"interrupted (SIGINT)"]];i(jy,"exitForError");i(QU,"exitCodesHelp")});function GU(t,e){if(!t)return e;let n={...t.prompt_tokens_details,...Nk(e.prompt_tokens_details)},r={...t.completion_tokens_details,...Nk(e.completion_tokens_details)};return{...t,...Nk(e),...Object.keys(n).length?{prompt_tokens_details:n}:{},...Object.keys(r).length?{completion_tokens_details:r}:{}}}function Nk(t){return t?Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null&&typeof e!="object")):{}}async function*HU(t,e){if(!t.body)throw new Error("Response body is null \u2014 streaming not supported");let n=t.body.getReader();e&&(e.cancel=()=>{n.cancel().catch(()=>{})});let r=new TextDecoder,s="";try{for(;;){let{done:o,value:a}=await n.read();if(o)break;s+=r.decode(a,{stream:!0});let l=s.split(`
56
56
  `);s=l.pop();for(let c of l){let u=c.trim();if(!(!u||u.startsWith(":"))&&u.startsWith("data: ")){let p=u.slice(6).trim();if(p==="[DONE]"){e&&(e.done=!0);return}try{yield JSON.parse(p)}catch{}}}}if(s.trim()){let o=s.trim();if(o.startsWith("data: ")){let a=o.slice(6).trim();if(a==="[DONE]")e&&(e.done=!0);else try{yield JSON.parse(a)}catch{}}}}finally{n.releaseLock()}}var Ky,YU=P(()=>{"use strict";i(GU,"mergeUsage");i(Nk,"defined");i(HU,"parseSSEStream");Ky=class{static{i(this,"ToolCallAccumulator")}_calls=new Map;feed(e){for(let n of e){let r=this._calls.get(n.index);n.id&&n.function?.name?this._calls.set(n.index,{id:n.id,name:n.function.name,arguments:n.function.arguments||""}):r&&n.function?.arguments&&(r.arguments+=n.function.arguments)}}flush(){let e=Array.from(this._calls.values());return this._calls.clear(),e}get hasPending(){return this._calls.size>0}}});function Bd(t){return Math.ceil(t.length/4)}function IAe(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let n of t){let r=n;r&&r.type==="text"&&typeof r.text=="string"&&e.push(r.text)}return e.join(`
57
- `)}function xk(t){let e=Bd(IAe(t.content));return t.tool_calls&&t.tool_calls.length>0&&(e+=Bd(JSON.stringify(t.tool_calls))),e}function Ok(t,e=6e3){let n=e;for(let r of t)n+=xk(r);return n}function qU(t,e,n,r={}){let s=r.estimate??Ok;if(!n||n.promptTokens<=0||n.messageCount>t.length)return s(t,e);let o=n.promptTokens+s(t.slice(n.messageCount),0);return r.atLeastEstimate?Math.max(s(t,e),o):o}var Mk=P(()=>{"use strict";i(Bd,"estimateTokens");i(IAe,"contentText");i(xk,"estimateMessageTokens");i(Ok,"estimateContextTokens");i(qU,"contextTokensForTrigger")});function jU(t){Vy.clear();for(let e of t){if(!e||!e.id)continue;let n={},r=e.contextWindow??e.context_window;typeof r=="number"&&r>0&&(n.window=r),typeof e.maxOutputTokens=="number"&&e.maxOutputTokens>0&&(n.outputCap=e.maxOutputTokens);let s=e.inputPerM??e.cost_input_micros,o=e.cachedInputPerM??e.cost_cache_read_micros;typeof s=="number"&&s>0&&typeof o=="number"&&o>=0&&(n.cacheReadRatio=o/s),Vy.set(e.id,n)}}function vAe(t){let e,n=-1;for(let[r,s]of wAe)t.startsWith(r)&&r.length>n&&(e=s,n=r.length);return e}function KU(t,e,n=128e3){if(typeof e=="number"&&e>0)return e;let r=Vy.get(t)?.window;if(r)return r;let s=WU[t]?.window;return s||(vAe(t.toLowerCase())??(n>0?n:128e3))}function VU(t){return Vy.get(t)?.outputCap??WU[t]?.outputCap??8192}function zy(t){let e=t.toLowerCase();return/claude|anthropic|opus|sonnet|haiku|fable/.test(e)?"anthropic-explicit":/gemini/.test(e)?"gemini-implicit":/capuchin|glm|monkeyscode-|^custom:/.test(e)?"radix-auto":"openai-auto"}function Jy(t){return/haiku/i.test(t)?4096:/opus-5|sonnet-5|fable-5/i.test(t)?512:1024}function RAe(t){return t==="low"||t==="medium"||t==="high"?t:void 0}function Bk(t,e){return typeof e=="string"&&e.length>0||zU.has(t)}function JU(t,e,n){if(Bk(t,n))return e?"high":RAe(n)??"medium"}var WU,wAe,Vy,zU,Pk=P(()=>{"use strict";WU={"capuchin-reason":{window:2e5,outputCap:16384,cacheReadRatio:0},"capuchin-flash":{window:2e5,outputCap:8192,cacheReadRatio:0},"claude-opus-5.5":{window:1e6,outputCap:32768,cacheReadRatio:.05},"claude-fable-5.1":{window:2e5,outputCap:8192,cacheReadRatio:.025},"claude-sonnet-5.5":{window:1e6,outputCap:16384,cacheReadRatio:.1},"claude-haiku-4.5":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-6-astra":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.6-sol":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.6-terra":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.6-luna":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.5":{window:1e6,outputCap:16384,cacheReadRatio:.1},"gpt-5.4-pro":{window:272e3,outputCap:16384,cacheReadRatio:.1},"gpt-5.4":{window:272e3,outputCap:8192,cacheReadRatio:.1},"gpt-5.4-mini":{window:272e3,outputCap:8192,cacheReadRatio:.1},"gpt-5.4-nano":{window:272e3,outputCap:8192,cacheReadRatio:.1},"gpt-4o":{window:128e3,outputCap:8192,cacheReadRatio:.1},o3:{window:2e5,outputCap:16384,cacheReadRatio:.1},"o4-mini":{window:2e5,outputCap:16384,cacheReadRatio:.1},"gemini-3.1-pro":{window:1048576,outputCap:16384,cacheReadRatio:.1},"gemini-3.8-flash":{window:1048576,outputCap:8192,cacheReadRatio:.1},"gemini-3.5-flash":{window:1048576,outputCap:8192,cacheReadRatio:.1}},wAe=[["gemini-",1048576],["claude-opus-5",1e6],["claude-sonnet-5",1e6],["claude-",2e5],["gpt-6",2e5],["gpt-5.6",2e5],["gpt-5.5",1e6],["gpt-5.4",272e3],["gpt-5",2e5],["gpt-4.1",1e6],["gpt-4o",128e3],["o3",2e5],["o4-",2e5],["capuchin-",2e5],["codestral",256e3],["mistral",128e3],["deepseek",131072],["llama",128e3],["custom:",32768]],Vy=new Map;i(jU,"updateFromCatalog");i(vAe,"bestPrefix");i(KU,"contextWindowFor");i(VU,"outputCapFor");i(zy,"cachingStrategy");i(Jy,"minCacheTokens");zU=new Set(["claude-opus-5.5","claude-fable-5.1","gpt-6-astra","gpt-5.6-sol","gpt-5.5","gpt-5.4-pro","o3","gemini-3.1-pro"]);i(RAe,"normalizeEffortLevel");i(Bk,"isLargeModel");i(JU,"largeModelEffort")});function XU(t){return zy(t)==="anthropic-explicit"}function ZU(t){let e=-1;for(let n=0;n<t.length;n++){let r=t[n].cacheTier;if(r==="A"||r==="B")e=n;else if(r==="C")break}return e}function Lk(t,e){let n=zy(t);return n==="anthropic-explicit"?e>=Jy(t):n==="radix-auto"?e>0:e>=1024}function eQ(t,e){let{modelId:n}=e,r=e.toolTokens??0;if(!XU(n))return{messages:t.map(y=>({...y})),breakpointIndices:[],markTools:!1};let s=Jy(n),o=new Set,a=!1,l=kAe,c=[],u=r;for(let y of t)u+=xk(y),c.push(u);r>=s&&l>0&&(a=!0,l--);let p=-1;for(let y=0;y<t.length;y++){let b=t[y].cacheTier;(b==="A"||b==="B")&&(p=y)}p>=0&&l>0&&c[p]>=s&&(o.add(p),l--);let f=-1;for(;f+1<t.length&&t[f+1].role==="system";)f++;let h=Math.max(p,f),_=new Set;for(let y=1;y<t.length;y++){let b=t[y];b.role==="user"&&!b.tool_call_id&&y-1>h&&_.add(y-1)}for(let y=0;y<t.length;y++){if(t[y].role!=="tool")continue;let b=t[y+1];b&&b.role==="tool"||y>h&&_.add(y)}let E=[..._].sort((y,b)=>y-b);for(let y of E.slice(-2)){if(l<=0)break;if(o.has(y))continue;let b=Math.max(p>=0?c[p]:r,...[...o].map(w=>c[w]));c[y]-b<s||(o.add(y),l--)}return{messages:t.map((y,b)=>o.has(b)?{...y,cacheBreakpoint:!0}:{...y}),breakpointIndices:[...o].sort((y,b)=>y-b),markTools:a}}var kAe,tQ=P(()=>{"use strict";Pk();Mk();kAe=4;i(XU,"supportsExplicitCaching");i(ZU,"computeCacheBoundary");i(Lk,"isBoundaryWorthCaching");i(eQ,"placeCacheBreakpoints")});function NAe(t){let e=t.slice(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=e.lastIndexOf(".");return n<=0?e==="Rakefile"||e==="Gemfile"?"ruby":void 0:DAe[e.slice(n+1).toLowerCase()]}function PA(t,e){for(let n of t){let r=n.re.exec(e);if(r&&r[1])return{name:r[1],kind:n.kind}}}function sQ(t){let e=0;for(let n of t)if(n===" ")e++;else if(n===" ")e+=4;else break;return e}function Fk(t,e,n,r,s){let o=[],a=0,l=!1,c=-1,u=!1;for(let p=0;p<t.length&&o.length<400;p++){let f=t[p],h=f.trim(),_=a;if(!l&&h.length>0&&!h.startsWith("//")&&!h.startsWith("*")&&!h.startsWith("#[")){if(_===0){let y=PA(e,h);y&&(o.push({name:y.name,kind:y.kind,line:p+1,depth:0}),r.has(y.kind)&&(u=!0))}else if(c>=0&&_===c){let y=PA(n,h);y&&!s.has(y.name)&&o.push({name:y.name,kind:y.kind,line:p+1,depth:1})}}let E;for(let y=0;y<f.length;y++){let b=f[y],w=f[y+1];if(l){b==="*"&&w==="/"&&(l=!1,y++);continue}if(E){b==="\\"?y++:b===E&&(E=void 0);continue}if(b==="/"&&w==="/")break;if(b==="/"&&w==="*"){l=!0,y++;continue}if(b==='"'||b==="'"||b==="`"){E=b;continue}b==="{"?(a++,u&&a===1&&(c=1,u=!1)):b==="}"&&(a=Math.max(0,a-1),a===0&&(c=-1))}}return o}function UAe(t){let e=[],n=!1,r=-1;for(let s=0;s<t.length&&e.length<400;s++){let o=t[s],a=o.trim();if(a.length===0||a.startsWith("#"))continue;let l=sQ(o);l===0?(n=!1,r=-1):n&&r<0&&(r=l);let c=PA(FAe,a);c&&(l===0?(e.push({name:c.name,kind:c.kind,line:s+1,depth:0}),n=c.kind==="class"):n&&l===r&&c.kind==="function"&&e.push({name:c.name,kind:"method",line:s+1,depth:1}))}return e}function QAe(t){let e=[],n=[];for(let r=0;r<t.length&&e.length<400;r++){let s=t[r],o=s.trim();if(o.length===0||o.startsWith("#"))continue;let a=sQ(s);for(;n.length>0&&a<=n[n.length-1]&&/^end\b/.test(o);)n.pop();let l=PA($Ae,o);if(!l)continue;let c=Math.min(1,n.length);(c===0||l.kind==="method"||n.length===1)&&e.push({name:l.name,kind:l.kind,line:r+1,depth:c}),(l.kind==="class"||l.kind==="module")&&n.push(a)}return e}function GAe(t){let e=[];for(let n=0;n<t.length&&e.length<400;n++){let r=t[n];if(r.length===0||r[0]===" "||r[0]===" "||r[0]==="/")continue;let s=PA(BAe,r);s&&e.push({name:s.name,kind:s.kind,line:n+1,depth:0})}return e}function oQ(t,e,n){switch(n??NAe(e)){case"ts":return Fk(t,xAe,OAe,HAe,MAe);case"php":return Fk(t,PAe,LAe,YAe,nQ);case"rust":return Fk(t,rQ,WAe,qAe,nQ).map(s=>s.depth===1&&s.kind==="function"?{...s,kind:"method"}:s);case"go":return GAe(t);case"python":return UAe(t);case"ruby":return QAe(t);default:return[]}}function iQ(t){let e=String(t.reduce((n,r)=>Math.max(n,r.line),0)).length;return t.map(n=>`${n.depth>0?" ":""}L${String(n.line).padStart(e)} ${n.kind} ${n.name}`).join(`
57
+ `)}function xk(t){let e=Bd(IAe(t.content));return t.tool_calls&&t.tool_calls.length>0&&(e+=Bd(JSON.stringify(t.tool_calls))),e}function Ok(t,e=6e3){let n=e;for(let r of t)n+=xk(r);return n}function qU(t,e,n,r={}){let s=r.estimate??Ok;if(!n||n.promptTokens<=0||n.messageCount>t.length)return s(t,e);let o=n.promptTokens+s(t.slice(n.messageCount),0);return r.atLeastEstimate?Math.max(s(t,e),o):o}var Mk=P(()=>{"use strict";i(Bd,"estimateTokens");i(IAe,"contentText");i(xk,"estimateMessageTokens");i(Ok,"estimateContextTokens");i(qU,"contextTokensForTrigger")});function jU(t){Vy.clear();for(let e of t){if(!e||!e.id)continue;let n={},r=e.contextWindow??e.context_window;typeof r=="number"&&r>0&&(n.window=r),typeof e.maxOutputTokens=="number"&&e.maxOutputTokens>0&&(n.outputCap=e.maxOutputTokens);let s=e.inputPerM??e.cost_input_micros,o=e.cachedInputPerM??e.cost_cache_read_micros;typeof s=="number"&&s>0&&typeof o=="number"&&o>=0&&(n.cacheReadRatio=o/s),Vy.set(e.id,n)}}function vAe(t){let e,n=-1;for(let[r,s]of wAe)t.startsWith(r)&&r.length>n&&(e=s,n=r.length);return e}function KU(t,e,n=128e3){if(typeof e=="number"&&e>0)return e;let r=Vy.get(t)?.window;if(r)return r;let s=WU[t]?.window;return s||(vAe(t.toLowerCase())??(n>0?n:128e3))}function VU(t){return Vy.get(t)?.outputCap??WU[t]?.outputCap??8192}function zy(t){let e=t.toLowerCase();return/claude|anthropic|opus|sonnet|haiku|fable/.test(e)?"anthropic-explicit":/gemini/.test(e)?"gemini-implicit":/capuchin|glm|monkeyscode-|^custom:/.test(e)?"radix-auto":"openai-auto"}function Jy(t){return/haiku/i.test(t)?4096:/opus-5|sonnet-5|fable-5/i.test(t)?512:1024}function RAe(t){return t==="low"||t==="medium"||t==="high"?t:void 0}function Bk(t,e){return typeof e=="string"&&e.length>0||zU.has(t)}function JU(t,e,n){if(Bk(t,n))return e?"high":RAe(n)??"medium"}var WU,wAe,Vy,zU,Pk=P(()=>{"use strict";WU={"capuchin-reason":{window:2e5,outputCap:16384,cacheReadRatio:0},"capuchin-flash":{window:2e5,outputCap:8192,cacheReadRatio:0},"claude-opus-5.5":{window:1e6,outputCap:32768,cacheReadRatio:.05},"claude-fable-5.1":{window:2e5,outputCap:8192,cacheReadRatio:.025},"claude-sonnet-5.5":{window:1e6,outputCap:16384,cacheReadRatio:.1},"claude-haiku-4.5":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-6-astra":{window:105e4,outputCap:16384,cacheReadRatio:.1},"gpt-6.1-sol":{window:105e4,outputCap:16384,cacheReadRatio:.05},"gpt-6-luna":{window:105e4,outputCap:16384,cacheReadRatio:.1},"gpt-5.6-sol":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.6-terra":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.6-luna":{window:2e5,outputCap:8192,cacheReadRatio:.1},"gpt-5.5":{window:1e6,outputCap:16384,cacheReadRatio:.1},"gpt-5.4-pro":{window:272e3,outputCap:16384,cacheReadRatio:.1},"gpt-5.4":{window:272e3,outputCap:8192,cacheReadRatio:.1},"gpt-5.4-mini":{window:272e3,outputCap:8192,cacheReadRatio:.1},"gpt-5.4-nano":{window:272e3,outputCap:8192,cacheReadRatio:.1},"gpt-4o":{window:128e3,outputCap:8192,cacheReadRatio:.1},o3:{window:2e5,outputCap:16384,cacheReadRatio:.1},"o4-mini":{window:2e5,outputCap:16384,cacheReadRatio:.1},"gemini-3.1-pro":{window:1048576,outputCap:16384,cacheReadRatio:.1},"gemini-3.8-flash":{window:1048576,outputCap:8192,cacheReadRatio:.1},"gemini-3.5-flash":{window:1048576,outputCap:8192,cacheReadRatio:.1}},wAe=[["gemini-",1048576],["claude-opus-5",1e6],["claude-sonnet-5",1e6],["claude-",2e5],["gpt-6",105e4],["gpt-5.6",2e5],["gpt-5.5",1e6],["gpt-5.4",272e3],["gpt-5",2e5],["gpt-4.1",1e6],["gpt-4o",128e3],["o3",2e5],["o4-",2e5],["capuchin-",2e5],["codestral",256e3],["mistral",128e3],["deepseek",131072],["llama",128e3],["custom:",32768]],Vy=new Map;i(jU,"updateFromCatalog");i(vAe,"bestPrefix");i(KU,"contextWindowFor");i(VU,"outputCapFor");i(zy,"cachingStrategy");i(Jy,"minCacheTokens");zU=new Set(["claude-opus-5.5","claude-fable-5.1","gpt-6-astra","gpt-6.1-sol","gpt-5.6-sol","gpt-5.5","gpt-5.4-pro","o3","gemini-3.1-pro"]);i(RAe,"normalizeEffortLevel");i(Bk,"isLargeModel");i(JU,"largeModelEffort")});function XU(t){return zy(t)==="anthropic-explicit"}function ZU(t){let e=-1;for(let n=0;n<t.length;n++){let r=t[n].cacheTier;if(r==="A"||r==="B")e=n;else if(r==="C")break}return e}function Lk(t,e){let n=zy(t);return n==="anthropic-explicit"?e>=Jy(t):n==="radix-auto"?e>0:e>=1024}function eQ(t,e){let{modelId:n}=e,r=e.toolTokens??0;if(!XU(n))return{messages:t.map(y=>({...y})),breakpointIndices:[],markTools:!1};let s=Jy(n),o=new Set,a=!1,l=kAe,c=[],u=r;for(let y of t)u+=xk(y),c.push(u);r>=s&&l>0&&(a=!0,l--);let p=-1;for(let y=0;y<t.length;y++){let b=t[y].cacheTier;(b==="A"||b==="B")&&(p=y)}p>=0&&l>0&&c[p]>=s&&(o.add(p),l--);let f=-1;for(;f+1<t.length&&t[f+1].role==="system";)f++;let h=Math.max(p,f),_=new Set;for(let y=1;y<t.length;y++){let b=t[y];b.role==="user"&&!b.tool_call_id&&y-1>h&&_.add(y-1)}for(let y=0;y<t.length;y++){if(t[y].role!=="tool")continue;let b=t[y+1];b&&b.role==="tool"||y>h&&_.add(y)}let E=[..._].sort((y,b)=>y-b);for(let y of E.slice(-2)){if(l<=0)break;if(o.has(y))continue;let b=Math.max(p>=0?c[p]:r,...[...o].map(w=>c[w]));c[y]-b<s||(o.add(y),l--)}return{messages:t.map((y,b)=>o.has(b)?{...y,cacheBreakpoint:!0}:{...y}),breakpointIndices:[...o].sort((y,b)=>y-b),markTools:a}}var kAe,tQ=P(()=>{"use strict";Pk();Mk();kAe=4;i(XU,"supportsExplicitCaching");i(ZU,"computeCacheBoundary");i(Lk,"isBoundaryWorthCaching");i(eQ,"placeCacheBreakpoints")});function NAe(t){let e=t.slice(Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"))+1),n=e.lastIndexOf(".");return n<=0?e==="Rakefile"||e==="Gemfile"?"ruby":void 0:DAe[e.slice(n+1).toLowerCase()]}function PA(t,e){for(let n of t){let r=n.re.exec(e);if(r&&r[1])return{name:r[1],kind:n.kind}}}function sQ(t){let e=0;for(let n of t)if(n===" ")e++;else if(n===" ")e+=4;else break;return e}function Fk(t,e,n,r,s){let o=[],a=0,l=!1,c=-1,u=!1;for(let p=0;p<t.length&&o.length<400;p++){let f=t[p],h=f.trim(),_=a;if(!l&&h.length>0&&!h.startsWith("//")&&!h.startsWith("*")&&!h.startsWith("#[")){if(_===0){let y=PA(e,h);y&&(o.push({name:y.name,kind:y.kind,line:p+1,depth:0}),r.has(y.kind)&&(u=!0))}else if(c>=0&&_===c){let y=PA(n,h);y&&!s.has(y.name)&&o.push({name:y.name,kind:y.kind,line:p+1,depth:1})}}let E;for(let y=0;y<f.length;y++){let b=f[y],w=f[y+1];if(l){b==="*"&&w==="/"&&(l=!1,y++);continue}if(E){b==="\\"?y++:b===E&&(E=void 0);continue}if(b==="/"&&w==="/")break;if(b==="/"&&w==="*"){l=!0,y++;continue}if(b==='"'||b==="'"||b==="`"){E=b;continue}b==="{"?(a++,u&&a===1&&(c=1,u=!1)):b==="}"&&(a=Math.max(0,a-1),a===0&&(c=-1))}}return o}function UAe(t){let e=[],n=!1,r=-1;for(let s=0;s<t.length&&e.length<400;s++){let o=t[s],a=o.trim();if(a.length===0||a.startsWith("#"))continue;let l=sQ(o);l===0?(n=!1,r=-1):n&&r<0&&(r=l);let c=PA(FAe,a);c&&(l===0?(e.push({name:c.name,kind:c.kind,line:s+1,depth:0}),n=c.kind==="class"):n&&l===r&&c.kind==="function"&&e.push({name:c.name,kind:"method",line:s+1,depth:1}))}return e}function QAe(t){let e=[],n=[];for(let r=0;r<t.length&&e.length<400;r++){let s=t[r],o=s.trim();if(o.length===0||o.startsWith("#"))continue;let a=sQ(s);for(;n.length>0&&a<=n[n.length-1]&&/^end\b/.test(o);)n.pop();let l=PA($Ae,o);if(!l)continue;let c=Math.min(1,n.length);(c===0||l.kind==="method"||n.length===1)&&e.push({name:l.name,kind:l.kind,line:r+1,depth:c}),(l.kind==="class"||l.kind==="module")&&n.push(a)}return e}function GAe(t){let e=[];for(let n=0;n<t.length&&e.length<400;n++){let r=t[n];if(r.length===0||r[0]===" "||r[0]===" "||r[0]==="/")continue;let s=PA(BAe,r);s&&e.push({name:s.name,kind:s.kind,line:n+1,depth:0})}return e}function oQ(t,e,n){switch(n??NAe(e)){case"ts":return Fk(t,xAe,OAe,HAe,MAe);case"php":return Fk(t,PAe,LAe,YAe,nQ);case"rust":return Fk(t,rQ,WAe,qAe,nQ).map(s=>s.depth===1&&s.kind==="function"?{...s,kind:"method"}:s);case"go":return GAe(t);case"python":return UAe(t);case"ruby":return QAe(t);default:return[]}}function iQ(t){let e=String(t.reduce((n,r)=>Math.max(n,r.line),0)).length;return t.map(n=>`${n.depth>0?" ":""}L${String(n.line).padStart(e)} ${n.kind} ${n.name}`).join(`
58
58
  `)}var DAe,xAe,OAe,MAe,BAe,PAe,LAe,FAe,rQ,$Ae,HAe,YAe,qAe,WAe,nQ,$k=P(()=>{"use strict";DAe={ts:"ts",tsx:"ts",mts:"ts",cts:"ts",js:"ts",jsx:"ts",mjs:"ts",cjs:"ts",go:"go",php:"php",py:"python",pyi:"python",rs:"rust",rb:"ruby",rake:"ruby"};i(NAe,"outlineLanguageFor");xAe=[{re:/^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/,kind:"class"},{re:/^(?:export\s+)?(?:declare\s+)?interface\s+([A-Za-z_$][\w$]*)/,kind:"interface"},{re:/^(?:export\s+)?(?:declare\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^=]*>)?\s*=/,kind:"type"},{re:/^(?:export\s+)?(?:declare\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/,kind:"enum"},{re:/^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/,kind:"function"},{re:/^(?:export\s+)?(?:declare\s+)?(?:namespace|module)\s+([A-Za-z_$][\w$.]*)/,kind:"module"},{re:/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/,kind:"function"},{re:/^export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/,kind:"const"}],OAe=[{re:/^(?:(?:public|private|protected|static|readonly|abstract|override|async|get|set|declare)\s+)*\*?\s*(#?[A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(/,kind:"method"}],MAe=new Set(["if","for","while","switch","catch","return","function","new","await","typeof","super","this","else","do","try","throw","yield","delete","void"]),BAe=[{re:/^func\s+\([^)]*\)\s*([A-Za-z_]\w*)/,kind:"method"},{re:/^func\s+([A-Za-z_]\w*)/,kind:"function"},{re:/^type\s+([A-Za-z_]\w*)\s+struct\b/,kind:"struct"},{re:/^type\s+([A-Za-z_]\w*)\s+interface\b/,kind:"interface"},{re:/^type\s+([A-Za-z_]\w*)\b/,kind:"type"}],PAe=[{re:/^(?:final\s+|abstract\s+|readonly\s+)*class\s+([A-Za-z_]\w*)/,kind:"class"},{re:/^interface\s+([A-Za-z_]\w*)/,kind:"interface"},{re:/^trait\s+([A-Za-z_]\w*)/,kind:"trait"},{re:/^enum\s+([A-Za-z_]\w*)/,kind:"enum"},{re:/^function\s+&?\s*([A-Za-z_]\w*)/,kind:"function"}],LAe=[{re:/^(?:(?:public|private|protected|static|final|abstract)\s+)*function\s+&?\s*([A-Za-z_]\w*)/,kind:"method"}],FAe=[{re:/^class\s+([A-Za-z_]\w*)/,kind:"class"},{re:/^(?:async\s+)?def\s+([A-Za-z_]\w*)/,kind:"function"}],rQ=[{re:/^(?:pub(?:\([^)]*\))?\s+)?(?:const\s+)?(?:async\s+)?(?:unsafe\s+)?(?:extern\s+"[^"]*"\s+)?fn\s+([A-Za-z_]\w*)/,kind:"function"},{re:/^(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_]\w*)/,kind:"struct"},{re:/^(?:pub(?:\([^)]*\))?\s+)?enum\s+([A-Za-z_]\w*)/,kind:"enum"},{re:/^(?:pub(?:\([^)]*\))?\s+)?(?:unsafe\s+)?trait\s+([A-Za-z_]\w*)/,kind:"trait"},{re:/^(?:pub(?:\([^)]*\))?\s+)?type\s+([A-Za-z_]\w*)/,kind:"type"},{re:/^(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_]\w*)/,kind:"module"},{re:/^(?:unsafe\s+)?impl\b(?:\s*<[^>]*>)?\s+(?:[\w:<>, ]+\s+for\s+)?([A-Za-z_][\w:]*)/,kind:"impl"}],$Ae=[{re:/^class\s+([A-Z][\w:]*)/,kind:"class"},{re:/^module\s+([A-Z][\w:]*)/,kind:"module"},{re:/^def\s+((?:self\.)?[A-Za-z_]\w*[?!=]?)/,kind:"method"}];i(PA,"match");i(sQ,"indentOf");i(Fk,"braceOutline");i(UAe,"pythonOutline");i(QAe,"rubyOutline");i(GAe,"goOutline");HAe=new Set(["class"]),YAe=new Set(["class","trait","interface","enum"]),qAe=new Set(["impl","trait"]),WAe=[rQ[0]],nQ=new Set;i(oQ,"outlineSymbols");i(iQ,"renderOutline")});function LA(t,e,n){let r=[];for(let s=e;s<=n;s++)r.push({n:s,text:t[s-1]??""});return r}function Uk(t,e,n,r){let s=0;for(let o=e;o<=n;o++)if(s+=(t[o-1]?.length??0)+1,s>r)return Math.max(e,o-1);return n}function mQ(t){let e=t.lines.length,n=t.wholeMaxLines??dQ,r=t.headLines??pQ,s=t.maxChars??Qk,o=t.path;if(t.startLine!==void 0||t.endLine!==void 0){let f=Math.max(1,Math.floor(t.startLine??1)),h=Math.min(e,Math.floor(t.endLine??e));if(f>e)return{kind:"error",from:0,to:0,totalLines:e,body:[],complete:!1,error:`start_line ${f} is beyond the end of the file (${e} lines)`};if(h<f)return{kind:"error",from:0,to:0,totalLines:e,body:[],complete:!1,error:`end_line ${h} is before start_line ${f}`};let _=Uk(t.lines,f,h,s);return _<h?{kind:"char-capped",from:f,to:_,totalLines:e,body:LA(t.lines,f,_),complete:!1,note:`Lines ${f}-${_} shown (${Math.round(s/1e3)}K-character limit). Continue with read_file(path: "${o}", start_line: ${_+1}, end_line: ${h}).`}:{kind:"range",from:f,to:h,totalLines:e,body:LA(t.lines,f,h),complete:f===1&&h===e}}if(t.full||e<=n){let f=e===0?0:Uk(t.lines,1,e,s);return f<e?{kind:"char-capped",from:1,to:f,totalLines:e,body:LA(t.lines,1,f),complete:!1,note:`Lines 1-${f} of ${e} shown (${Math.round(s/1e3)}K-character limit). Continue with read_file(path: "${o}", start_line: ${f+1}, end_line: ${e}).`}:{kind:"whole",from:e===0?0:1,to:e,totalLines:e,body:LA(t.lines,1,e),complete:!0}}let l=Uk(t.lines,1,Math.min(r,e),s),c=t.outline??oQ(t.lines,o),u=iQ(c.filter(f=>f.line>l));if(u.length>aQ){let f=u.slice(0,aQ);u=f.slice(0,f.lastIndexOf(`
59
59
  `))+`
60
60
  ... (outline cut; search with grep_search for other symbols)`}let p=`Showing lines 1-${l} of ${e}`+(u?", then an outline of the rest":"")+`. Read more with read_file(path: "${o}", start_line, end_line), or full: true for the whole file.`;return{kind:"head-outline",from:1,to:l,totalLines:e,body:LA(t.lines,1,l),outline:u||void 0,note:p,complete:!1}}function gQ(t={start:"start_line",end:"end_line"}){return`Read a file with line numbers. Files up to ${dQ} lines are returned whole. Larger files return the first ${pQ} lines and an outline of the rest (symbols with line numbers): then read the part you need with ${t.start}/${t.end}, or pass full: true for the whole file. Ranges are never cut by line count.`}function fQ(t="max_results",e=!0){return`Returns at most ${nC} matches by default (raise ${t}, up to ${Gk})`+(e?'; use mode "files_with_matches" when you only need which files match.':".")}function hQ(){return`Long output keeps the first ${eC/1e3}K and last ${tC/1e3}K characters plus every error-looking line from the middle, and names a file holding the complete output (read it with read_file and a line range).`}function VAe(t){return KAe.test(t)}function uQ(t){let e=0;for(let n=0;n<t.length;n++)t.charCodeAt(n)===10&&e++;return e}function Hk(t){let e=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.floor(e),Gk):nC}function AQ(t,e,n={}){let r=e!==void 0&&e>t?` of ${e}`:"",s=n.param??"max_results",o=n.hasFilesMode===!1?"":'Use mode: "files_with_matches" to list the files, ';return`[Truncated: showing ${t}${r} matches. ${o}${o?"narrow":"Narrow"} the path or pattern, or raise ${s} (up to ${Gk}).]`}var dQ,pQ,Qk,aQ,eC,tC,jAe,lQ,cQ,KAe,Xy,Zy,nC,Gk,_Q=P(()=>{"use strict";$k();dQ=800,pQ=200,Qk=2e5,aQ=12e3;i(LA,"lineSlice");i(Uk,"capByChars");i(mQ,"sizeFileRead");i(gQ,"readToolDescription");i(fQ,"searchCapDescription");i(hQ,"commandOutputDescription");eC=8e3,tC=16e3,jAe=40,lQ=300,cQ=2e3,KAe=/(?:error|errors|exception)\b|\b(?:fail|failed|failure|failures|panic|panicked|fatal)\b|\u2716|\u2717|^\s*not ok\b|Traceback \(most recent call last\)/i;i(VAe,"isErrorLine");i(uQ,"countLines");Xy=class t{static{i(this,"MiddleScanner")}constructor(e,n){this.firstLine=e,this.maxErrors=n,this.piece=0,this.chars=0,this.errors=0,this.endsWithNewline=!1,this.kept=[],this.line="",this.lineLength=0}feed(e){if(!e)return;this.chars+=e.length;let n=0;for(let r=e.indexOf(`
@@ -375,7 +375,7 @@ ${_}
375
375
 
376
376
  <session-start-context>
377
377
  ${We}
378
- </session-start-context>`,We="");let Lt=await jH({prompt:Be,runModel:rn,runDecider:zt,decider:z,history:u,sessionId:p,workspace:a,settings:q,token:te,tools:Se,hookRunner:de,permissionMode:Z,guard:Le,opts:e,ac:s,emit:Q,record:G,log:o,internals:b,checkpointsAll:K,onLoop:i(Oe=>{_=Oe},"onLoop"),stopReason:i(()=>y,"stopReason")});_=void 0,u=Lt.history,oe?.checkpoint(u);let Es,ut,Mr=Lt.text,it=Lt.subtype,_e=Lt.error;if(e.jsonSchema&&it==="success"){let Oe=await $O(e.jsonSchema,Mr);for(let je=1;!Oe.ok&&je<=2&&!s.signal.aborted;je++){o(`[json-schema] answer did not validate (attempt ${je}/2): ${Oe.errors.slice(0,3).join("; ")}`);let rt=await jH({prompt:YH(e.jsonSchema,Oe.errors),runModel:rn,runDecider:zt,decider:z,history:u,sessionId:p,workspace:a,settings:q,token:te,tools:Se,hookRunner:de,permissionMode:Z,guard:Le,opts:e,ac:s,emit:Q,record:G,log:o,internals:b,checkpointsAll:K,onLoop:i(xt=>{_=xt},"onLoop"),stopReason:i(()=>y,"stopReason")});if(_=void 0,u=rt.history,oe?.checkpoint(u),rt.subtype!=="success"){it=rt.subtype,_e=rt.error;break}Mr=rt.text,Oe=await $O(e.jsonSchema,Mr)}it==="success"&&(Oe.ok?Es=Oe.value:(it="error_during_execution",ut=Oe.errors,_e=`Final answer does not match --json-schema: ${Oe.errors.slice(0,3).join("; ")}`))}let mt=z.denials.slice(Fe);it==="success"&&mt.length>0&&z.allowedMutations===$e&&(it="error_permission_denied");let wt=fwe(it,Lt.transportKind,_e);Re=wt;let hn=SN();hn.input_tokens=Lt.tokensIn,hn.output_tokens=Lt.tokensOut,hn.cached_tokens=Lt.tokensCached,hn.thinking_tokens=Lt.tokensThinking;let Ss={type:"result",subtype:it,is_error:it!=="success",result:Mr,...Es!==void 0?{structured:Es}:{},session_id:p,num_turns:Lt.responses,duration_ms:Date.now()-ye,usage:hn,cost_usd:Le.cost(),is_estimated:Le.estimated,permission_denials:z.denials.slice(),exit_code:wt,..._e?{error:_e}:{},...ut?{schema_errors:ut}:{}};Q(Ss),f(Ss),h=Promise.resolve(Ss),(E||y||it==="error_max_cost"||it==="error_max_tokens"||it==="error_auth"||it==="error_quota"||it==="error_timeout")&&r.close()}}finally{await de.run("SessionEnd",{workspace:a,sessionId:p,data:{reason:"headless",exitCode:Re,durationMs:Date.now()-se}}).catch(()=>null),be.stop(),oe?.close()}},"run")().catch(R=>{let $=R instanceof Error?R.message:String(R),q=R.exitCode??jy(c_(R).kind,$),ne={type:"result",subtype:q===St.usage?"error_during_execution":hwe(q),is_error:!0,result:"",session_id:p,num_turns:0,duration_ms:0,usage:SN(),cost_usd:0,is_estimated:!0,permission_denials:[],exit_code:q,error:$};n.push(ne),f(ne),h=Promise.resolve(ne)}).finally(()=>n.close()),k=i(R=>{y??=R,_?.cancel(),r.close()},"stop"),O={sessionId:p,get result(){return h},interrupt(){_?.interrupt()},send(R){r.push(typeof R=="string"?R:R.content)},end(){r.close()},get pendingPermissions(){return 0},[Symbol.asyncIterator]:()=>n[Symbol.asyncIterator](),[YO]:b};if(e.timeoutMs){let R=setTimeout(()=>k("timeout"),e.timeoutMs);R.unref?.(),v.finally(()=>clearTimeout(R))}return s.signal.aborted?k("abort"):s.signal.addEventListener("abort",()=>k("abort"),{once:!0}),O}async function jH(t){let{opts:e,settings:n}=t,r=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,s=new ur({platformUrl:e.platformUrl??n.platformUrl,token:t.token,model:t.runModel,workspace:t.workspace,mode:Yd(t.permissionMode),permissionMode:t.permissionMode,maxTurns:n.maxTurns,sandboxed:e.sandbox??r,webEnabled:(e.webEnabled??n.webEnabled)!==!1,effort:e.effort??n.effort,permissionDecider:t.runDecider,mcp:t.tools,history:t.history,retry:e.retry??{maxAttempts:8,maxWaitMs:6e4},services:t.internals.effective.value.diagnostics===!1?void 0:{diagnostics:new Tg(t.workspace)},hookRunner:t.hookRunner,systemPrompt:e.appendSystemPrompt||e.systemPrompt?{append:e.appendSystemPrompt,replaceBase:e.systemPrompt}:void 0,sessionId:t.sessionId});t.onLoop(s),t.stopReason()&&s.cancel();let o=new Yg(()=>t.sessionId),a,l,c=0,u={tokensIn:0,tokensOut:0,tokensCached:0},p=new Map;s.on("event",y=>{switch(y.type){case"tool_call_start":t.decider.currentToolUseId=y.toolCallId,y.toolCallId&&p.set(y.toolCallId,{name:y.name,args:y.args??{},at:Date.now()}),t.log(`[tool] ${y.name}(${JSON.stringify(y.args??{}).substring(0,100)})`);break;case"tool_call_result":{let b=y.toolCallId?p.get(y.toolCallId):void 0;t.internals.toolCalls.push({tool:y.name,args:b?.args??{},duration:y.durationMs??(b?Date.now()-b.at:0),result:typeof y.result=="string"?y.result.substring(0,200):void 0});break}case"usage":u={tokensIn:y.tokensIn,tokensOut:y.tokensOut,tokensCached:y.tokensCached},l=t.guard.update({tokensIn:y.tokensIn,tokensOut:y.tokensOut,tokensCached:y.tokensCached,costUsd:y.costUsd,costReported:y.costReported})??l,l&&(t.log(`[guard] ${bN(l)}`),s.cancel());break;case"run_complete":c+=y.summary.tokensThinking??0,u={tokensIn:y.summary.tokensIn,tokensOut:y.summary.tokensOut,tokensCached:y.summary.tokensCached};break;case"run_error":a={message:y.error||"unknown",kind:y.kind},t.log(`[headless] Error: ${a.message}`);break;case"retrying":{let b=y.maxAttempts?`/${y.maxAttempts-1}`:"";t.log(`[headless] \u21BB retrying (${y.attempt}${b}) in ${Math.round(y.delayMs/100)/10}s \u2014 ${y.reason}`);break}case"ask_user":t.log(`[headless] Input prompt skipped (headless mode): ${y.question}`),s.resolveUserInput("");break;case"request_usage":t.record(cb(t.sessionId,y.usage));break}for(let b of o.map(y))t.emit(b)});try{await s.run(t.prompt)}catch(y){let b=c_(y);a={message:y instanceof Error?y.message:String(y),kind:b.kind}}for(let[y,b]of s.getCheckpoints())t.checkpointsAll.has(y)||t.checkpointsAll.set(y,b);let f=t.stopReason(),h=s.wasInterrupted()||!!f,_="success",E;if(l)_=l.kind==="cost"?"error_max_cost":"error_max_tokens",E=bN(l);else if(f==="timeout")_="error_timeout",E=`Timed out after ${Math.round((e.timeoutMs??0)/1e3)}s`;else if(h)_="error_interrupted",E="Interrupted";else if(a){let y=jy(a.kind,a.message);_=y===St.auth?"error_auth":y===St.quota?"error_quota":"error_during_execution",E=a.message}return{subtype:_,text:o.lastText.trim(),error:E,transportKind:a?.kind,history:s.getMessages(),responses:o.responses,tokensIn:u.tokensIn,tokensOut:u.tokensOut,tokensCached:u.tokensCached,tokensThinking:c}}function fwe(t,e,n){switch(t){case"success":return St.success;case"error_max_cost":case"error_max_tokens":return St.guard;case"error_permission_denied":return St.denied;case"error_timeout":return St.timeout;case"error_interrupted":return St.interrupted;case"error_auth":return St.auth;case"error_quota":return St.quota;default:return e?jy(e,n):St.runtime}}function hwe(t){return t===St.auth?"error_auth":t===St.quota?"error_quota":"error_during_execution"}var zb,KH,gwe,YO,Vb,GO,HO,zH=P(()=>{"use strict";zb=N(require("node:path"),1),KH=N(require("node:crypto"),1);ks();Rt();YA();xC();o3();UD();vn();Ys();XA();i_();fu();Gg();lb();DC();BA();M3();yN();C_();B3();$o();qH();Kb();gwe="1.0.1",YO=Symbol.for("monkeyscode.query.internals"),Vb=class{static{i(this,"Channel")}items=[];waiters=[];closed=!1;push(e){if(this.closed)return;let n=this.waiters.shift();n?n({value:e,done:!1}):this.items.push(e)}close(){this.closed=!0;for(let e of this.waiters.splice(0))e({value:void 0,done:!0})}async next(){return this.items.length?{value:this.items.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>this.waiters.push(e))}[Symbol.asyncIterator](){return{next:i(()=>this.next(),"next")}}},GO=class{constructor(e){this.o=e}static{i(this,"QueryDecider")}denials=[];legacy=[];allowedMutations=0;currentToolUseId;rechecking=!1;verdict(e){return this.o.engine.evaluate({name:e.toolName,args:e.args},this.o.mode())}check(e){let n=this.verdict(e);if(this.rechecking)return this.rechecking=!1,n.kind==="deny"?this.deny(e,n.reason,void 0,n.reason):{action:"allow"};if(n.kind==="allow")return this.countAllowed(e),{action:"allow"};if(n.kind==="deny")return this.deny(e,n.reason,void 0,n.reason);if(this.o.canUseTool&&!n.destructive)return{action:"ask"};if(this.o.autoApprove&&!n.destructive)return this.countAllowed(e),{action:"allow"};let r=n.destructive?"Destructive command \u2014 never auto-approved headless":`Not approved (headless): ${n.reason}`;return this.deny(e,r,n.suggestedRule)}async decide(e){let n=this.check(e);if(n.action!=="ask")return n;let r=this.verdict(e),s=r.kind==="ask"&&r.suggestedRule?[r.suggestedRule]:[];try{let o=await this.o.canUseTool(e.toolName,e.args,{signal:this.o.signal,suggestions:s,description:mi(e.toolName,e.args),toolUseId:this.currentToolUseId});return o.behavior==="allow"?(this.countAllowed(e),o.updatedInput?(this.rechecking=!0,{action:"allow",updatedInput:o.updatedInput}):{action:"allow"}):this.deny(e,o.message||"Denied by the permission callback",s[0])}catch(o){return this.deny(e,`Permission callback failed: ${o instanceof Error?o.message:String(o)}`,s[0])}}isToolHidden(e){return this.o.engine.isToolHidden(e)}grantReadRoot(e){this.o.engine.addReadOnlyRoot(e)}hookMayApprove(e){let n=this.verdict(e);return n.kind==="ask"&&!n.guard&&!n.destructive}countAllowed(e){this.o.engine.isReadOnlyTool(e.toolName)||this.allowedMutations++}deny(e,n,r,s){let o=mi(e.toolName,e.args);if(this.denials.push({tool_name:e.toolName,...this.currentToolUseId?{tool_use_id:this.currentToolUseId}:{},tool_input:e.args,reason:n,...r?{suggested_rule:r}:{}}),this.legacy.push({tool:e.toolName,description:o,reason:n,...r?{suggestedRule:r}:{}}),this.o.log(`[permission] denied ${o} \u2014 ${n}${r?` (allow with --allowed-tools "${r}")`:""}`),s)return{action:"deny",message:s};let a=r?` To allow it, the user can re-run with --allowed-tools "${r}".`:"";return{action:"deny",message:`${n}.${a} Continue without this action if possible.`}}},HO=class{constructor(e){this.providers=e}static{i(this,"CombinedTools")}getToolSchemas(){return this.providers.flatMap(e=>e.getToolSchemas())}resolveToolName(e){for(let n of this.providers){let r=n.resolveToolName(e);if(r)return r}}callTool(e,n){for(let r of this.providers)if(r.resolveToolName(e))return r.callTool(r.resolveToolName(e),n);return Promise.resolve({output:`Error: unknown tool ${e}`})}};i(VH,"query");i(jH,"runTurn");i(fwe,"exitFor");i(hwe,"subtypeForExit")});var Jb,JH=P(()=>{"use strict";Jb=class{constructor(e,n=3e5,r=()=>{}){this.send=e;this.timeoutMs=n;this.onInterrupt=r}static{i(this,"ControlChannel")}seq=0;pending=new Map;get outstanding(){return this.pending.size}canUseTool=i((e,n,r)=>new Promise(s=>{let o=`req_${++this.seq}`,a=setTimeout(()=>{this.pending.delete(o),s({behavior:"deny",message:`No answer to the permission request within ${Math.round(this.timeoutMs/1e3)}s`})},this.timeoutMs);a.unref?.(),this.pending.set(o,{resolve:s,timer:a});let l=i(()=>this.settle(o,{behavior:"deny",message:"Interrupted"}),"onAbort");r.signal.addEventListener("abort",l,{once:!0}),this.send({type:"control_request",request_id:o,request:{subtype:"can_use_tool",tool_name:e,input:n,description:r.description,...r.toolUseId?{tool_use_id:r.toolUseId}:{},...r.suggestions.length?{suggestions:r.suggestions}:{}}})}),"canUseTool");handle(e){if(e.type==="control_response"){let n=String(e.request_id??""),r=e.response??{};if(r.behavior==="allow"){let s=r.updated_input??r.updatedInput;this.settle(n,{behavior:"allow",...s&&typeof s=="object"?{updatedInput:s}:{}})}else this.settle(n,{behavior:"deny",message:typeof r.message=="string"?r.message:"Denied by the parent process"});return!0}if(e.type==="control_request"){let n=String(e.request_id??""),r=e.request??{};return r.subtype==="interrupt"?(this.onInterrupt(),this.send({type:"control_response",request_id:n,response:{subtype:"success"}})):this.send({type:"control_response",request_id:n,response:{subtype:"error",error:`unsupported control request "${String(r.subtype)}"`}}),!0}return!1}close(e="The parent process closed stdin"){for(let n of[...this.pending.keys()])this.settle(n,{behavior:"deny",message:e})}settle(e,n){let r=this.pending.get(e);r&&(clearTimeout(r.timer),this.pending.delete(e),r.resolve(n))}}});function Awe(t){if(t.type!=="user")return;let n=(t.message??{}).content;if(typeof n=="string")return n;if(Array.isArray(n)){let r=n.filter(s=>!!s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string");return r.length?r.map(s=>s.text).join(`
378
+ </session-start-context>`,We="");let Lt=await jH({prompt:Be,runModel:rn,runDecider:zt,decider:z,history:u,sessionId:p,workspace:a,settings:q,token:te,tools:Se,hookRunner:de,permissionMode:Z,guard:Le,opts:e,ac:s,emit:Q,record:G,log:o,internals:b,checkpointsAll:K,onLoop:i(Oe=>{_=Oe},"onLoop"),stopReason:i(()=>y,"stopReason")});_=void 0,u=Lt.history,oe?.checkpoint(u);let Es,ut,Mr=Lt.text,it=Lt.subtype,_e=Lt.error;if(e.jsonSchema&&it==="success"){let Oe=await $O(e.jsonSchema,Mr);for(let je=1;!Oe.ok&&je<=2&&!s.signal.aborted;je++){o(`[json-schema] answer did not validate (attempt ${je}/2): ${Oe.errors.slice(0,3).join("; ")}`);let rt=await jH({prompt:YH(e.jsonSchema,Oe.errors),runModel:rn,runDecider:zt,decider:z,history:u,sessionId:p,workspace:a,settings:q,token:te,tools:Se,hookRunner:de,permissionMode:Z,guard:Le,opts:e,ac:s,emit:Q,record:G,log:o,internals:b,checkpointsAll:K,onLoop:i(xt=>{_=xt},"onLoop"),stopReason:i(()=>y,"stopReason")});if(_=void 0,u=rt.history,oe?.checkpoint(u),rt.subtype!=="success"){it=rt.subtype,_e=rt.error;break}Mr=rt.text,Oe=await $O(e.jsonSchema,Mr)}it==="success"&&(Oe.ok?Es=Oe.value:(it="error_during_execution",ut=Oe.errors,_e=`Final answer does not match --json-schema: ${Oe.errors.slice(0,3).join("; ")}`))}let mt=z.denials.slice(Fe);it==="success"&&mt.length>0&&z.allowedMutations===$e&&(it="error_permission_denied");let wt=fwe(it,Lt.transportKind,_e);Re=wt;let hn=SN();hn.input_tokens=Lt.tokensIn,hn.output_tokens=Lt.tokensOut,hn.cached_tokens=Lt.tokensCached,hn.thinking_tokens=Lt.tokensThinking;let Ss={type:"result",subtype:it,is_error:it!=="success",result:Mr,...Es!==void 0?{structured:Es}:{},session_id:p,num_turns:Lt.responses,duration_ms:Date.now()-ye,usage:hn,cost_usd:Le.cost(),is_estimated:Le.estimated,permission_denials:z.denials.slice(),exit_code:wt,..._e?{error:_e}:{},...ut?{schema_errors:ut}:{}};Q(Ss),f(Ss),h=Promise.resolve(Ss),(E||y||it==="error_max_cost"||it==="error_max_tokens"||it==="error_auth"||it==="error_quota"||it==="error_timeout")&&r.close()}}finally{await de.run("SessionEnd",{workspace:a,sessionId:p,data:{reason:"headless",exitCode:Re,durationMs:Date.now()-se}}).catch(()=>null),be.stop(),oe?.close()}},"run")().catch(R=>{let $=R instanceof Error?R.message:String(R),q=R.exitCode??jy(c_(R).kind,$),ne={type:"result",subtype:q===St.usage?"error_during_execution":hwe(q),is_error:!0,result:"",session_id:p,num_turns:0,duration_ms:0,usage:SN(),cost_usd:0,is_estimated:!0,permission_denials:[],exit_code:q,error:$};n.push(ne),f(ne),h=Promise.resolve(ne)}).finally(()=>n.close()),k=i(R=>{y??=R,_?.cancel(),r.close()},"stop"),O={sessionId:p,get result(){return h},interrupt(){_?.interrupt()},send(R){r.push(typeof R=="string"?R:R.content)},end(){r.close()},get pendingPermissions(){return 0},[Symbol.asyncIterator]:()=>n[Symbol.asyncIterator](),[YO]:b};if(e.timeoutMs){let R=setTimeout(()=>k("timeout"),e.timeoutMs);R.unref?.(),v.finally(()=>clearTimeout(R))}return s.signal.aborted?k("abort"):s.signal.addEventListener("abort",()=>k("abort"),{once:!0}),O}async function jH(t){let{opts:e,settings:n}=t,r=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,s=new ur({platformUrl:e.platformUrl??n.platformUrl,token:t.token,model:t.runModel,workspace:t.workspace,mode:Yd(t.permissionMode),permissionMode:t.permissionMode,maxTurns:n.maxTurns,sandboxed:e.sandbox??r,webEnabled:(e.webEnabled??n.webEnabled)!==!1,effort:e.effort??n.effort,permissionDecider:t.runDecider,mcp:t.tools,history:t.history,retry:e.retry??{maxAttempts:8,maxWaitMs:6e4},services:t.internals.effective.value.diagnostics===!1?void 0:{diagnostics:new Tg(t.workspace)},hookRunner:t.hookRunner,systemPrompt:e.appendSystemPrompt||e.systemPrompt?{append:e.appendSystemPrompt,replaceBase:e.systemPrompt}:void 0,sessionId:t.sessionId});t.onLoop(s),t.stopReason()&&s.cancel();let o=new Yg(()=>t.sessionId),a,l,c=0,u={tokensIn:0,tokensOut:0,tokensCached:0},p=new Map;s.on("event",y=>{switch(y.type){case"tool_call_start":t.decider.currentToolUseId=y.toolCallId,y.toolCallId&&p.set(y.toolCallId,{name:y.name,args:y.args??{},at:Date.now()}),t.log(`[tool] ${y.name}(${JSON.stringify(y.args??{}).substring(0,100)})`);break;case"tool_call_result":{let b=y.toolCallId?p.get(y.toolCallId):void 0;t.internals.toolCalls.push({tool:y.name,args:b?.args??{},duration:y.durationMs??(b?Date.now()-b.at:0),result:typeof y.result=="string"?y.result.substring(0,200):void 0});break}case"usage":u={tokensIn:y.tokensIn,tokensOut:y.tokensOut,tokensCached:y.tokensCached},l=t.guard.update({tokensIn:y.tokensIn,tokensOut:y.tokensOut,tokensCached:y.tokensCached,costUsd:y.costUsd,costReported:y.costReported})??l,l&&(t.log(`[guard] ${bN(l)}`),s.cancel());break;case"run_complete":c+=y.summary.tokensThinking??0,u={tokensIn:y.summary.tokensIn,tokensOut:y.summary.tokensOut,tokensCached:y.summary.tokensCached};break;case"run_error":a={message:y.error||"unknown",kind:y.kind},t.log(`[headless] Error: ${a.message}`);break;case"retrying":{let b=y.maxAttempts?`/${y.maxAttempts-1}`:"";t.log(`[headless] \u21BB retrying (${y.attempt}${b}) in ${Math.round(y.delayMs/100)/10}s \u2014 ${y.reason}`);break}case"ask_user":t.log(`[headless] Input prompt skipped (headless mode): ${y.question}`),s.resolveUserInput("");break;case"request_usage":t.record(cb(t.sessionId,y.usage));break}for(let b of o.map(y))t.emit(b)});try{await s.run(t.prompt)}catch(y){let b=c_(y);a={message:y instanceof Error?y.message:String(y),kind:b.kind}}for(let[y,b]of s.getCheckpoints())t.checkpointsAll.has(y)||t.checkpointsAll.set(y,b);let f=t.stopReason(),h=s.wasInterrupted()||!!f,_="success",E;if(l)_=l.kind==="cost"?"error_max_cost":"error_max_tokens",E=bN(l);else if(f==="timeout")_="error_timeout",E=`Timed out after ${Math.round((e.timeoutMs??0)/1e3)}s`;else if(h)_="error_interrupted",E="Interrupted";else if(a){let y=jy(a.kind,a.message);_=y===St.auth?"error_auth":y===St.quota?"error_quota":"error_during_execution",E=a.message}return{subtype:_,text:o.lastText.trim(),error:E,transportKind:a?.kind,history:s.getMessages(),responses:o.responses,tokensIn:u.tokensIn,tokensOut:u.tokensOut,tokensCached:u.tokensCached,tokensThinking:c}}function fwe(t,e,n){switch(t){case"success":return St.success;case"error_max_cost":case"error_max_tokens":return St.guard;case"error_permission_denied":return St.denied;case"error_timeout":return St.timeout;case"error_interrupted":return St.interrupted;case"error_auth":return St.auth;case"error_quota":return St.quota;default:return e?jy(e,n):St.runtime}}function hwe(t){return t===St.auth?"error_auth":t===St.quota?"error_quota":"error_during_execution"}var zb,KH,gwe,YO,Vb,GO,HO,zH=P(()=>{"use strict";zb=N(require("node:path"),1),KH=N(require("node:crypto"),1);ks();Rt();YA();xC();o3();UD();vn();Ys();XA();i_();fu();Gg();lb();DC();BA();M3();yN();C_();B3();$o();qH();Kb();gwe="1.0.2",YO=Symbol.for("monkeyscode.query.internals"),Vb=class{static{i(this,"Channel")}items=[];waiters=[];closed=!1;push(e){if(this.closed)return;let n=this.waiters.shift();n?n({value:e,done:!1}):this.items.push(e)}close(){this.closed=!0;for(let e of this.waiters.splice(0))e({value:void 0,done:!0})}async next(){return this.items.length?{value:this.items.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>this.waiters.push(e))}[Symbol.asyncIterator](){return{next:i(()=>this.next(),"next")}}},GO=class{constructor(e){this.o=e}static{i(this,"QueryDecider")}denials=[];legacy=[];allowedMutations=0;currentToolUseId;rechecking=!1;verdict(e){return this.o.engine.evaluate({name:e.toolName,args:e.args},this.o.mode())}check(e){let n=this.verdict(e);if(this.rechecking)return this.rechecking=!1,n.kind==="deny"?this.deny(e,n.reason,void 0,n.reason):{action:"allow"};if(n.kind==="allow")return this.countAllowed(e),{action:"allow"};if(n.kind==="deny")return this.deny(e,n.reason,void 0,n.reason);if(this.o.canUseTool&&!n.destructive)return{action:"ask"};if(this.o.autoApprove&&!n.destructive)return this.countAllowed(e),{action:"allow"};let r=n.destructive?"Destructive command \u2014 never auto-approved headless":`Not approved (headless): ${n.reason}`;return this.deny(e,r,n.suggestedRule)}async decide(e){let n=this.check(e);if(n.action!=="ask")return n;let r=this.verdict(e),s=r.kind==="ask"&&r.suggestedRule?[r.suggestedRule]:[];try{let o=await this.o.canUseTool(e.toolName,e.args,{signal:this.o.signal,suggestions:s,description:mi(e.toolName,e.args),toolUseId:this.currentToolUseId});return o.behavior==="allow"?(this.countAllowed(e),o.updatedInput?(this.rechecking=!0,{action:"allow",updatedInput:o.updatedInput}):{action:"allow"}):this.deny(e,o.message||"Denied by the permission callback",s[0])}catch(o){return this.deny(e,`Permission callback failed: ${o instanceof Error?o.message:String(o)}`,s[0])}}isToolHidden(e){return this.o.engine.isToolHidden(e)}grantReadRoot(e){this.o.engine.addReadOnlyRoot(e)}hookMayApprove(e){let n=this.verdict(e);return n.kind==="ask"&&!n.guard&&!n.destructive}countAllowed(e){this.o.engine.isReadOnlyTool(e.toolName)||this.allowedMutations++}deny(e,n,r,s){let o=mi(e.toolName,e.args);if(this.denials.push({tool_name:e.toolName,...this.currentToolUseId?{tool_use_id:this.currentToolUseId}:{},tool_input:e.args,reason:n,...r?{suggested_rule:r}:{}}),this.legacy.push({tool:e.toolName,description:o,reason:n,...r?{suggestedRule:r}:{}}),this.o.log(`[permission] denied ${o} \u2014 ${n}${r?` (allow with --allowed-tools "${r}")`:""}`),s)return{action:"deny",message:s};let a=r?` To allow it, the user can re-run with --allowed-tools "${r}".`:"";return{action:"deny",message:`${n}.${a} Continue without this action if possible.`}}},HO=class{constructor(e){this.providers=e}static{i(this,"CombinedTools")}getToolSchemas(){return this.providers.flatMap(e=>e.getToolSchemas())}resolveToolName(e){for(let n of this.providers){let r=n.resolveToolName(e);if(r)return r}}callTool(e,n){for(let r of this.providers)if(r.resolveToolName(e))return r.callTool(r.resolveToolName(e),n);return Promise.resolve({output:`Error: unknown tool ${e}`})}};i(VH,"query");i(jH,"runTurn");i(fwe,"exitFor");i(hwe,"subtypeForExit")});var Jb,JH=P(()=>{"use strict";Jb=class{constructor(e,n=3e5,r=()=>{}){this.send=e;this.timeoutMs=n;this.onInterrupt=r}static{i(this,"ControlChannel")}seq=0;pending=new Map;get outstanding(){return this.pending.size}canUseTool=i((e,n,r)=>new Promise(s=>{let o=`req_${++this.seq}`,a=setTimeout(()=>{this.pending.delete(o),s({behavior:"deny",message:`No answer to the permission request within ${Math.round(this.timeoutMs/1e3)}s`})},this.timeoutMs);a.unref?.(),this.pending.set(o,{resolve:s,timer:a});let l=i(()=>this.settle(o,{behavior:"deny",message:"Interrupted"}),"onAbort");r.signal.addEventListener("abort",l,{once:!0}),this.send({type:"control_request",request_id:o,request:{subtype:"can_use_tool",tool_name:e,input:n,description:r.description,...r.toolUseId?{tool_use_id:r.toolUseId}:{},...r.suggestions.length?{suggestions:r.suggestions}:{}}})}),"canUseTool");handle(e){if(e.type==="control_response"){let n=String(e.request_id??""),r=e.response??{};if(r.behavior==="allow"){let s=r.updated_input??r.updatedInput;this.settle(n,{behavior:"allow",...s&&typeof s=="object"?{updatedInput:s}:{}})}else this.settle(n,{behavior:"deny",message:typeof r.message=="string"?r.message:"Denied by the parent process"});return!0}if(e.type==="control_request"){let n=String(e.request_id??""),r=e.request??{};return r.subtype==="interrupt"?(this.onInterrupt(),this.send({type:"control_response",request_id:n,response:{subtype:"success"}})):this.send({type:"control_response",request_id:n,response:{subtype:"error",error:`unsupported control request "${String(r.subtype)}"`}}),!0}return!1}close(e="The parent process closed stdin"){for(let n of[...this.pending.keys()])this.settle(n,{behavior:"deny",message:e})}settle(e,n){let r=this.pending.get(e);r&&(clearTimeout(r.timer),this.pending.delete(e),r.resolve(n))}}});function Awe(t){if(t.type!=="user")return;let n=(t.message??{}).content;if(typeof n=="string")return n;if(Array.isArray(n)){let r=n.filter(s=>!!s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string");return r.length?r.map(s=>s.text).join(`
379
379
  `):void 0}}async function*ZH(t,e){let n=XH.createInterface({input:t,crlfDelay:1/0}),r=0;try{for await(let s of n){r++;let o=s.trim();if(!o)continue;let a;try{let c=JSON.parse(o);if(!c||typeof c!="object"||Array.isArray(c))throw new Error("not a JSON object");a=c}catch(c){throw new Cp(`invalid JSON (${c.message})`,r)}if(e?.handle(a))continue;if(a.type==="control_response"||a.type==="control_request")throw new Cp("control message received but --permission-prompt stdio is not enabled",r);let l=Awe(a);if(l===void 0)throw new Cp(`expected {"type":"user","message":{"content":\u2026}}, got type ${JSON.stringify(a.type)}`,r);yield l}}finally{n.close(),e?.close()}}var XH,Cp,e7=P(()=>{"use strict";XH=N(require("node:readline"),1),Cp=class extends Error{constructor(n,r){super(`stdin line ${r}: ${n}`);this.line=r;this.name="StdinProtocolError"}static{i(this,"StdinProtocolError")}};i(Awe,"userText");i(ZH,"readStreamJsonInput")});var n7={};ot(n7,{joinPromptAndStdin:()=>qO,readSettingsFlag:()=>Zb,resolvePrintFlags:()=>Ewe});function Ewe(t,e){let n=e.print,r=n!==void 0&&n!==!1||!!e.headless,s=[typeof n=="string"?n:void 0,t,e.prompt].filter(p=>typeof p=="string"&&p.trim()!==""),o=s.length?s.join(`
380
380
 
381
381
  `):void 0,a=e.outputFormat??e.output??"text",l=e.inputFormat??"text",c={print:r,prompt:o,outputFormat:a,inputFormat:l},u=i(p=>({...c,error:p}),"fail");if(!r){for(let[p,f]of _we)if(e[p]!==void 0)return u(`${f} requires print mode (-p)`);if((e.outputFormat??e.output)!==void 0&&a!=="text")return u(`--output-format ${a} requires print mode (-p)`)}if(l==="stream-json"&&a!=="stream-json")return u("--input-format stream-json requires --output-format stream-json");if(l==="stream-json"&&o)return u("--input-format stream-json reads prompts from stdin; do not also pass a prompt");if(e.permissionPrompt==="stdio"&&l!=="stream-json")return u("--permission-prompt stdio requires --input-format stream-json (answers arrive on stdin)");if(e.permissionTimeout!==void 0&&!(parseFloat(e.permissionTimeout)>0))return u("--permission-timeout must be a positive number of seconds");if(e.forkSession&&!e.continue&&e.resume===void 0)return u("--fork-session needs a session to fork: add -c or -r <id>");if(e.jsonSchema!==void 0){let p=Swe(e.jsonSchema);if(p)return u(p);if(a!=="json"&&a!=="stream-json"&&a!=="text")return u(`--json-schema works with -o text, json or stream-json (not ${a})`)}if(e.maxCost!==void 0&&!(parseFloat(e.maxCost)>0))return u("--max-cost must be a positive dollar amount");if(e.maxTokens!==void 0&&!(parseInt(e.maxTokens,10)>0))return u("--max-tokens must be a positive integer");if(e.systemPromptFile!==void 0&&!Xb(e.systemPromptFile))return u(`--system-prompt-file: cannot read ${e.systemPromptFile}`);for(let p of e.mcpConfig??[])if(!Xb(p))return u(`--mcp-config: cannot read ${p}`);if(e.strictMcpConfig&&!e.mcpConfig?.length)return u("--strict-mcp-config needs at least one --mcp-config file");if(e.settings!==void 0){let p=ywe(e.settings);if(p)return u(p)}return c}function Xb(t){try{return Vl.accessSync(t,Vl.constants.R_OK),Vl.statSync(t).isFile()}catch{return!1}}function Swe(t){if(!Xb(t))return`--json-schema: cannot read ${t}`;try{let e=JSON.parse(Vl.readFileSync(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))return`--json-schema: ${t} is not a JSON Schema object`}catch(e){return`--json-schema: ${t} is not valid JSON (${e.message})`}}function t7(t){let e=t.trimStart().charAt(0);return e==="{"||e==="["}function Zb(t){let e=t7(t)?t:Vl.readFileSync(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("must be a JSON object");return n}function ywe(t){if(!t7(t)&&!Xb(t))return`--settings: cannot read ${t}`;try{Zb(t)}catch(e){return`--settings: ${e.message}`}}function qO(t,e){let n=t?.trim(),r=e?.trim();return n&&r?`${n}
@@ -399,7 +399,7 @@ ${e.error}
399
399
  `)}}finish(e){this.format!=="stream"&&this.write(this.formatter.formatResult(e)+`
400
400
  `)}pushStream(e){if(e.type==="assistant")for(let n of e.message.content)n.type==="text"&&this.write(n.text);else e.type==="system"&&e.subtype==="stream_reset"&&this.write(`
401
401
  [partial response discarded \u2014 retrying]
402
- `)}toLegacy(e){let n=Date.now();if(e.type==="assistant"){let r=[];for(let s of e.message.content)s.type==="text"?r.push({type:"chunk",timestamp:n,data:{content:s.text}}):(this.toolNames.set(s.id,s.name),r.push({type:"tool_start",timestamp:n,data:{tool:s.name,args:s.input}}));return r}return e.type==="user"&&Array.isArray(e.message.content)?e.message.content.map(r=>({type:"tool_result",timestamp:n,data:{tool:this.toolNames.get(r.tool_use_id)??"",result:r.content.substring(0,200),is_error:r.is_error}})):e.type==="system"&&e.subtype==="retrying"?[{type:"retrying",timestamp:n,data:{attempt:e.attempt,delayMs:e.delay_ms,reason:e.reason,kind:e.kind}}]:e.type==="system"&&e.subtype==="stream_reset"?[{type:"stream_reset",timestamp:n,data:{}}]:e.type==="result"&&e.is_error&&e.error?[{type:"error",timestamp:n,data:{message:e.error,subtype:e.subtype}}]:[]}}});var m7={};ot(m7,{queryOptionsFrom:()=>p7,runPrint:()=>wwe});async function Iwe(t){return t.isTTY?"":new Promise(e=>{let n="";t.setEncoding?.("utf8"),t.on("data",r=>{n+=r}),t.on("end",()=>e(n)),t.on("error",()=>e(n))})}function p7(t,e){let n=Object.assign({},...(t.mcpConfig??[]).map(r7));return{cwd:t.workspace,model:t.model,permissionMode:t.permissionMode,effort:t.effort,allowedTools:t.allowedTools,disallowedTools:t.deniedTools,addDirs:t.addDirs,autoApprove:t.autoApprove,approveSafeCommands:t.approveForMe,mcpServers:Object.keys(n).length?n:void 0,strictMcpConfig:t.strictMcpConfig,settings:t.settingsFlag?Zb(t.settingsFlag):void 0,ignoreRepoSettings:t.ignoreRepoSettings||void 0,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPromptFile?nM.readFileSync(t.systemPromptFile,"utf8"):void 0,maxCostUsd:t.maxCost,maxTokens:t.maxTokens,jsonSchema:t.jsonSchema?JSON.parse(nM.readFileSync(t.jsonSchema,"utf8")):void 0,resume:t.resumeSession||void 0,continue:t.continueSession,forkSession:t.forkSession,enableSettingsHooks:t.hooks!==!1,timeoutMs:t.timeout,sandbox:t.sandbox||$l(),webEnabled:t.offline?!1:void 0,cliVersion:"1.0.1",log:e,retry:{maxAttempts:8,maxWaitMs:Math.min(6e4,t.timeout||3e5)}}}async function wwe(t,e,n=Twe()){let r=i(R=>{n.stderr.write(R.endsWith(`
402
+ `)}toLegacy(e){let n=Date.now();if(e.type==="assistant"){let r=[];for(let s of e.message.content)s.type==="text"?r.push({type:"chunk",timestamp:n,data:{content:s.text}}):(this.toolNames.set(s.id,s.name),r.push({type:"tool_start",timestamp:n,data:{tool:s.name,args:s.input}}));return r}return e.type==="user"&&Array.isArray(e.message.content)?e.message.content.map(r=>({type:"tool_result",timestamp:n,data:{tool:this.toolNames.get(r.tool_use_id)??"",result:r.content.substring(0,200),is_error:r.is_error}})):e.type==="system"&&e.subtype==="retrying"?[{type:"retrying",timestamp:n,data:{attempt:e.attempt,delayMs:e.delay_ms,reason:e.reason,kind:e.kind}}]:e.type==="system"&&e.subtype==="stream_reset"?[{type:"stream_reset",timestamp:n,data:{}}]:e.type==="result"&&e.is_error&&e.error?[{type:"error",timestamp:n,data:{message:e.error,subtype:e.subtype}}]:[]}}});var m7={};ot(m7,{queryOptionsFrom:()=>p7,runPrint:()=>wwe});async function Iwe(t){return t.isTTY?"":new Promise(e=>{let n="";t.setEncoding?.("utf8"),t.on("data",r=>{n+=r}),t.on("end",()=>e(n)),t.on("error",()=>e(n))})}function p7(t,e){let n=Object.assign({},...(t.mcpConfig??[]).map(r7));return{cwd:t.workspace,model:t.model,permissionMode:t.permissionMode,effort:t.effort,allowedTools:t.allowedTools,disallowedTools:t.deniedTools,addDirs:t.addDirs,autoApprove:t.autoApprove,approveSafeCommands:t.approveForMe,mcpServers:Object.keys(n).length?n:void 0,strictMcpConfig:t.strictMcpConfig,settings:t.settingsFlag?Zb(t.settingsFlag):void 0,ignoreRepoSettings:t.ignoreRepoSettings||void 0,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPromptFile?nM.readFileSync(t.systemPromptFile,"utf8"):void 0,maxCostUsd:t.maxCost,maxTokens:t.maxTokens,jsonSchema:t.jsonSchema?JSON.parse(nM.readFileSync(t.jsonSchema,"utf8")):void 0,resume:t.resumeSession||void 0,continue:t.continueSession,forkSession:t.forkSession,enableSettingsHooks:t.hooks!==!1,timeoutMs:t.timeout,sandbox:t.sandbox||$l(),webEnabled:t.offline?!1:void 0,cliVersion:"1.0.2",log:e,retry:{maxAttempts:8,maxWaitMs:Math.min(6e4,t.timeout||3e5)}}}async function wwe(t,e,n=Twe()){let r=i(R=>{n.stderr.write(R.endsWith(`
403
403
  `)?R:`${R}
404
404
  `)},"log"),s=e.output??"text",o=e.inputFormat==="stream-json",a;try{a=p7(e,r)}catch(R){return r(`Error: ${R.message}`),St.usage}let l,c,u=i(R=>{n.stdout.write(JSON.stringify(R)+`
405
405
  `)},"writeLine");if(o)e.permissionPrompt==="stdio"&&(c=new Jb(u,e.permissionTimeoutMs??3e5,()=>y?.interrupt()),a.canUseTool=c.canUseTool),l=ZH(n.stdin,c);else{let R=qO(t,await Iwe(n.stdin));if(!R)return r('Error: No prompt provided. Use -p "your prompt" or pipe via stdin.'),St.usage;l=R}let p=s==="text"||s==="json"||s==="stream-json"?void 0:new nT(s,e.workspace,R=>n.stdout.write(R)),f=Date.now(),h,_="",E,y;try{y=VH({prompt:typeof l=="string"?l:vwe(l,R=>{E=R}),options:a})}catch(R){return r(`Error: ${R.message}`),R.exitCode??(R instanceof df?St.usage:St.runtime)}let b=y,w=0,v=i(()=>{w++,r(w===1?`
@@ -801,7 +801,7 @@ ${e}`,"wrappedToString"),BUe=Object.getOwnPropertyDescriptor(Function.prototype,
801
801
  `).length-10} more lines`):"..."}`);let _=`${r.bottomLeft}${r.horizontal.repeat(Math.max(0,o-2))}${r.bottomRight}`;return a.push(s?g.blue(_):_),a.join(`
802
802
  `)}function tQe(t){let e=st(),n=_t(e),r=io(e),s=e.ansi,o=e.columns,a=[],l=`${r.topLeft}${r.horizontal} ${n.web} web_search `,c=r.horizontal.repeat(Math.max(0,o-l.length-3));a.push(s?g.cyan(l+c+r.topRight):l+c+r.topRight),a.push(`${r.vertical} Query: "${t.query}"`),a.push(`${r.vertical} Results:`);for(let p=0;p<t.results.length&&p<5;p++){let f=t.results[p],h=` ${p+1}. `;a.push(s?`${r.vertical}${h}${g.bold(f.title)} (${g.dim(f.url)})`:`${r.vertical}${h}${f.title} (${f.url})`)}a.push(`${r.vertical} Context injected: ${t.tokensInjected.toLocaleString()} tokens`);let u=`${r.bottomLeft}${r.horizontal.repeat(Math.max(0,o-2))}${r.bottomRight}`;return a.push(s?g.cyan(u):u),a.join(`
803
803
  `)}function ale(t,e){let n=st();return` ${_t(n).tool} ${t}: ${e.summary}`}function nQe(t,e){let n={file_edit:e.edit,edit_file:e.edit,file_read:e.file,read_file:e.file,terminal:e.terminal,bash:e.terminal,run_command:e.terminal,shell_output:e.terminal,shell_kill:e.terminal,search:e.search,grep:e.search,grep_search:e.search,git:e.git,browser:e.browser,web_search:e.web,delete_file:e.delete,create_file:e.add,write_file:e.add};return t.includes("::")?e.mcp:n[t]||e.tool}function rQe(t,e){switch(t){case"file_edit":return jF(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return jF(String(e.file||e.filePath||e.path||"unknown file"));case"terminal":case"bash":return String(e.command||e.cmd||"");case"search":case"grep":return`"${e.query||e.pattern||""}"`;case"git":return String(e.command||e.args||"");case"browser":return String(e.url||"");case"web_search":return`"${e.query||""}"`;default:return t.includes("::")?Object.keys(e).slice(0,3).map(r=>`${r}=${JSON.stringify(e[r])}`).join(", "):JSON.stringify(e).slice(0,80)}}function jF(t){return process.platform==="win32"?t.replace(/\//g,"\\"):t}var cle=P(()=>{"use strict";He();wr();ile();i(KF,"renderToolStart");i(VF,"renderToolResult");i(lle,"renderToolError");i(KUe,"renderFileEdit");i(VUe,"renderFileRead");i(zUe,"renderTerminal");i(JUe,"renderSearch");i(XUe,"renderGit");i(ZUe,"renderBrowser");i(eQe,"renderMcp");i(tQe,"renderWebSearch");i(ale,"renderGeneric");i(nQe,"getToolIcon");i(rQe,"getToolArgsSummary");i(jF,"displayPath")});function sQe(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function ule(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}var iw,dle=P(()=>{"use strict";He();wr();iw=class{static{i(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=st(),this.icons=_t(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(`
804
- `),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=st(),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,n=process.stdout.rows||24,r=this.formatBar(e);r!==this.lastRendered&&(this.lastRendered=r,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${n};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(r),process.stdout.write("\x1B8"))}formatBar(e){let n=this.data,r=[];if(n.model){let E=n.model.length>20?n.model.slice(0,18)+"..":n.model;r.push(g.hex("#6B8DD6").bold(` ${this.icons.model} ${E} `))}let s=n.mode==="plan"?g.bgHex("#713F12").hex("#FBBF24"):n.mode==="ask"?g.bgHex("#1E3A5F").hex("#6B8DD6"):g.bgHex("#1a1a2e").hex("#A3CAD3");if(r.push(s(` ${n.mode} `)),n.branch){let E=this.icons.branch,y=n.dirty?g.yellow:g.green,b=n.dirty?" \u25CF":"";r.push(y(` ${E} ${n.branch}${b} `))}if(n.sandbox&&r.push(g.green(` ${this.icons.lock} `)),n.mcpNotice){let E=n.mcpNotice.length>40?n.mcpNotice.slice(0,38)+"..":n.mcpNotice;r.push(g.yellow(` ${E} `))}let o=[],a=n.tokensIn+n.tokensOut;if(a>0){let E=sQe(a);o.push(g.dim(` ${E} tokens `))}if(n.cost>0){let E=n.cost<1?`$${n.cost.toFixed(3)}`:`$${n.cost.toFixed(2)}`,y=n.budgetUsd>0&&n.cost/n.budgetUsd>.8?g.red:n.budgetUsd>0&&n.cost/n.budgetUsd>.5?g.yellow:g.dim;o.push(y(` ${this.icons.cost} ${E} `))}if(n.turn>0&&o.push(g.dim(` T${n.turn} `)),n.contextPct>0){let E=n.contextPct>=80?g.red:n.contextPct>=60?g.yellow:g.green,y=6,b=Math.round(n.contextPct/100*y),w=y-b,v=E("\u2588".repeat(b))+g.dim("\u2591".repeat(w));o.push(` ${v} ${E(`${n.contextPct}%`)} `)}if(n.activity){let E=n.activity.length>30?n.activity.slice(0,28)+"..":n.activity;o.push(g.dim.italic(` ${E} `))}let l=r.join(g.dim("\u2502")),c=o.join(g.dim("\u2502")),u=ule(l).length,p=ule(c).length,f=Math.max(1,e-u-p),h=g.bgHex("#0d1117"),_=h(" ".repeat(f));return h(l)+_+h(c)}};i(sQe,"formatTokensCompact");i(ule,"stripAnsi")});var ple={};ot(ple,{BRAND:()=>wo,LOGO_INLINE:()=>zF,LOGO_INLINE_ASCII:()=>JF,isDarkBackground:()=>XF,pickLogoSize:()=>e2,renderLogo:()=>ZF,visibleWidth:()=>aw});function XF(){let t=process.env.COLORFGBG;if(!t)return!0;let e=Number(t.split(";").pop());return Number.isNaN(e)?!0:e<8}function ZF(t,e={}){let{color:n=!0,dark:r=!0,indent:s=2,center:o}=e,a=lQe[t],l=r?wo.navyOnDark:wo.navy,c=n?g.hex(l):h=>h,u=n?g.hex(wo.ice):h=>h,p=i((h,_)=>_==="n"?c(h):_==="l"?u(h):h,"paint"),f=" ".repeat(o!==void 0?Math.max(0,Math.floor((o-a.width)/2)):s);return a.glyphs.map((h,_)=>{let E=a.mask[_],y="",b="",w=E[0]??".";for(let v=0;v<h.length;v++){let k=E[v]??".";k!==w&&(y+=p(b,w),b="",w=k),b+=h[v]}return y+=p(b,w),(f+y).replace(/\s+$/,"")})}function e2(t,e){return e?t>=72?"large":t>=46?"medium":t>=24?"mini":null:null}function aw(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}var wo,oQe,iQe,aQe,lQe,zF,JF,M1=P(()=>{"use strict";He();wo={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},oQe={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..................."]},iQe={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............"]},aQe={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..."]},lQe={large:oQe,medium:iQe,mini:aQe},zF="\u25C1\u2571\u25B7",JF="</>";i(XF,"isDarkBackground");i(ZF,"renderLogo");i(e2,"pickLogoSize");i(aw,"visibleWidth")});function uQe(t,e){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let s=r.lastIndexOf(" ",e);s<=0&&(s=e),n.push(r.substring(0,s)),r=r.substring(s).trimStart()}return n}var cQe,Ac,lw=P(()=>{"use strict";He();nle();wr();cle();a1();Wu();dle();M1();cQe={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Ac=class{static{i(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={...cQe,...e},this.caps=st(),this.icons=_t(this.caps),this.box=io(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:i(n=>this.renderToken(n),"onToken"),onThinking:i(n=>this.renderThinking(n),"onThinking"),onRunStarted:i(n=>this.renderRunStarted(n),"onRunStarted"),onRunComplete:i(n=>this.renderRunComplete(n),"onRunComplete"),onRunError:i(n=>this.renderRunError(n),"onRunError"),onToolStart:i(n=>this.renderToolStart(n),"onToolStart"),onToolProgress:i(n=>this.renderToolProgress(n),"onToolProgress"),onToolResult:i(n=>this.renderToolResult(n),"onToolResult"),onToolError:i(n=>this.renderToolError(n),"onToolError"),onApprovalRequest:i(n=>this.renderApprovalRequest(n),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new iw(e)),this.statusBar}printTurnBoundary(e,n,r,s){let o=this.caps.ansi,a=Math.min(60,this.caps.columns-4),l=n>=1e3?`${(n/1e3).toFixed(1)}K`:`${n}`,c=r?` ${this.icons.cost} $${r.toFixed(3)}`:"",u=s?` ${g.dim(`total: $${s.toFixed(2)}`)}`:"",p=` Turn ${e} ${g.dim("\xB7")} ${l} tokens${c}${u} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,h=Math.max(0,a-f),_=Math.floor(h/2),E=` ${this.box.horizontal.repeat(_)}${p}${this.box.horizontal.repeat(h-_)}`;console.log(""),console.log(o?g.dim(E):E),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,n={}){let r=this.caps.ansi,s=r?g.hex(wo.accent):p=>p,o=r?g.dim:p=>p,a=r?g.white.bold:p=>p,l="v1.0.1";console.log("");let c=n.logo??"auto",u=c==="none"?null:c==="auto"?e2(this.caps.columns,this.caps.unicode):c;if(u){let f=ZF(u,{color:r,dark:XF(),center:Math.min(56,this.caps.columns)});for(let h of f)console.log(h);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,f=52;console.log(s(` ${p.topLeft}${p.horizontal.repeat(f)}${p.topRight}`));let _=`${this.caps.nerdFont?"\uF120":zF} MonkeysCode`,E="CLI Agent",y=Math.max(0,f-aw(_)-E.length-2);console.log(` ${s(p.vertical)} ${a(_)}${" ".repeat(y)}${o(E)} ${s(p.vertical)}`),console.log(s(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let b=`${l}${e?` \xB7 ${e}`:""}`,w=Math.max(0,f-aw(b)-2);console.log(` ${s(p.vertical)} ${s(l)}${e?` ${o("\xB7")} ${o(e)}`:""}${" ".repeat(w)} ${s(p.vertical)}`),console.log(s(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${a("MonkeysCode")} ${s(l)} ${o("\xB7 CLI Agent")}`),e&&console.log(` ${o(e)}`)):(console.log(` ${JF} MC - MonkeysCode CLI ${l}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(r?g.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(r?g.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let n=g.hex(wo.accent),r=Math.min(56,this.caps.columns-6);console.log(""),console.log(n(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,r-9))}${this.box.topRight}`)),process.stdout.write(g.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let n=e.content.replace(/\n/g,`
804
+ `),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=st(),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,n=process.stdout.rows||24,r=this.formatBar(e);r!==this.lastRendered&&(this.lastRendered=r,process.stdout.write("\x1B7"),process.stdout.write(`\x1B[${n};1H`),process.stdout.write("\x1B[2K"),process.stdout.write(r),process.stdout.write("\x1B8"))}formatBar(e){let n=this.data,r=[];if(n.model){let E=n.model.length>20?n.model.slice(0,18)+"..":n.model;r.push(g.hex("#6B8DD6").bold(` ${this.icons.model} ${E} `))}let s=n.mode==="plan"?g.bgHex("#713F12").hex("#FBBF24"):n.mode==="ask"?g.bgHex("#1E3A5F").hex("#6B8DD6"):g.bgHex("#1a1a2e").hex("#A3CAD3");if(r.push(s(` ${n.mode} `)),n.branch){let E=this.icons.branch,y=n.dirty?g.yellow:g.green,b=n.dirty?" \u25CF":"";r.push(y(` ${E} ${n.branch}${b} `))}if(n.sandbox&&r.push(g.green(` ${this.icons.lock} `)),n.mcpNotice){let E=n.mcpNotice.length>40?n.mcpNotice.slice(0,38)+"..":n.mcpNotice;r.push(g.yellow(` ${E} `))}let o=[],a=n.tokensIn+n.tokensOut;if(a>0){let E=sQe(a);o.push(g.dim(` ${E} tokens `))}if(n.cost>0){let E=n.cost<1?`$${n.cost.toFixed(3)}`:`$${n.cost.toFixed(2)}`,y=n.budgetUsd>0&&n.cost/n.budgetUsd>.8?g.red:n.budgetUsd>0&&n.cost/n.budgetUsd>.5?g.yellow:g.dim;o.push(y(` ${this.icons.cost} ${E} `))}if(n.turn>0&&o.push(g.dim(` T${n.turn} `)),n.contextPct>0){let E=n.contextPct>=80?g.red:n.contextPct>=60?g.yellow:g.green,y=6,b=Math.round(n.contextPct/100*y),w=y-b,v=E("\u2588".repeat(b))+g.dim("\u2591".repeat(w));o.push(` ${v} ${E(`${n.contextPct}%`)} `)}if(n.activity){let E=n.activity.length>30?n.activity.slice(0,28)+"..":n.activity;o.push(g.dim.italic(` ${E} `))}let l=r.join(g.dim("\u2502")),c=o.join(g.dim("\u2502")),u=ule(l).length,p=ule(c).length,f=Math.max(1,e-u-p),h=g.bgHex("#0d1117"),_=h(" ".repeat(f));return h(l)+_+h(c)}};i(sQe,"formatTokensCompact");i(ule,"stripAnsi")});var ple={};ot(ple,{BRAND:()=>wo,LOGO_INLINE:()=>zF,LOGO_INLINE_ASCII:()=>JF,isDarkBackground:()=>XF,pickLogoSize:()=>e2,renderLogo:()=>ZF,visibleWidth:()=>aw});function XF(){let t=process.env.COLORFGBG;if(!t)return!0;let e=Number(t.split(";").pop());return Number.isNaN(e)?!0:e<8}function ZF(t,e={}){let{color:n=!0,dark:r=!0,indent:s=2,center:o}=e,a=lQe[t],l=r?wo.navyOnDark:wo.navy,c=n?g.hex(l):h=>h,u=n?g.hex(wo.ice):h=>h,p=i((h,_)=>_==="n"?c(h):_==="l"?u(h):h,"paint"),f=" ".repeat(o!==void 0?Math.max(0,Math.floor((o-a.width)/2)):s);return a.glyphs.map((h,_)=>{let E=a.mask[_],y="",b="",w=E[0]??".";for(let v=0;v<h.length;v++){let k=E[v]??".";k!==w&&(y+=p(b,w),b="",w=k),b+=h[v]}return y+=p(b,w),(f+y).replace(/\s+$/,"")})}function e2(t,e){return e?t>=72?"large":t>=46?"medium":t>=24?"mini":null:null}function aw(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}var wo,oQe,iQe,aQe,lQe,zF,JF,M1=P(()=>{"use strict";He();wo={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},oQe={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..................."]},iQe={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............"]},aQe={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..."]},lQe={large:oQe,medium:iQe,mini:aQe},zF="\u25C1\u2571\u25B7",JF="</>";i(XF,"isDarkBackground");i(ZF,"renderLogo");i(e2,"pickLogoSize");i(aw,"visibleWidth")});function uQe(t,e){if(t.length<=e)return[t];let n=[],r=t;for(;r.length>0;){if(r.length<=e){n.push(r);break}let s=r.lastIndexOf(" ",e);s<=0&&(s=e),n.push(r.substring(0,s)),r=r.substring(s).trimStart()}return n}var cQe,Ac,lw=P(()=>{"use strict";He();nle();wr();cle();a1();Wu();dle();M1();cQe={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Ac=class{static{i(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={...cQe,...e},this.caps=st(),this.icons=_t(this.caps),this.box=io(this.caps),this.opts.accessible&&(this.caps.ansi=!1,this.caps.emoji=!1)}attachToDispatcher(e){e.registerHandlers({onToken:i(n=>this.renderToken(n),"onToken"),onThinking:i(n=>this.renderThinking(n),"onThinking"),onRunStarted:i(n=>this.renderRunStarted(n),"onRunStarted"),onRunComplete:i(n=>this.renderRunComplete(n),"onRunComplete"),onRunError:i(n=>this.renderRunError(n),"onRunError"),onToolStart:i(n=>this.renderToolStart(n),"onToolStart"),onToolProgress:i(n=>this.renderToolProgress(n),"onToolProgress"),onToolResult:i(n=>this.renderToolResult(n),"onToolResult"),onToolError:i(n=>this.renderToolError(n),"onToolError"),onApprovalRequest:i(n=>this.renderApprovalRequest(n),"onApprovalRequest")})}getStatusBar(e){return this.statusBar||(this.statusBar=new iw(e)),this.statusBar}printTurnBoundary(e,n,r,s){let o=this.caps.ansi,a=Math.min(60,this.caps.columns-4),l=n>=1e3?`${(n/1e3).toFixed(1)}K`:`${n}`,c=r?` ${this.icons.cost} $${r.toFixed(3)}`:"",u=s?` ${g.dim(`total: $${s.toFixed(2)}`)}`:"",p=` Turn ${e} ${g.dim("\xB7")} ${l} tokens${c}${u} `,f=p.replace(/\x1b\[[0-9;]*m/g,"").length,h=Math.max(0,a-f),_=Math.floor(h/2),E=` ${this.box.horizontal.repeat(_)}${p}${this.box.horizontal.repeat(h-_)}`;console.log(""),console.log(o?g.dim(E):E),console.log(""),this.currentTurn=e,this.turnTokens=0}printBanner(e,n={}){let r=this.caps.ansi,s=r?g.hex(wo.accent):p=>p,o=r?g.dim:p=>p,a=r?g.white.bold:p=>p,l="v1.0.2";console.log("");let c=n.logo??"auto",u=c==="none"?null:c==="auto"?e2(this.caps.columns,this.caps.unicode):c;if(u){let f=ZF(u,{color:r,dark:XF(),center:Math.min(56,this.caps.columns)});for(let h of f)console.log(h);console.log("")}if(this.caps.unicode&&this.caps.columns>=56){let p=this.box,f=52;console.log(s(` ${p.topLeft}${p.horizontal.repeat(f)}${p.topRight}`));let _=`${this.caps.nerdFont?"\uF120":zF} MonkeysCode`,E="CLI Agent",y=Math.max(0,f-aw(_)-E.length-2);console.log(` ${s(p.vertical)} ${a(_)}${" ".repeat(y)}${o(E)} ${s(p.vertical)}`),console.log(s(` ${p.teeRight}${p.horizontal.repeat(f)}${p.teeLeft}`));let b=`${l}${e?` \xB7 ${e}`:""}`,w=Math.max(0,f-aw(b)-2);console.log(` ${s(p.vertical)} ${s(l)}${e?` ${o("\xB7")} ${o(e)}`:""}${" ".repeat(w)} ${s(p.vertical)}`),console.log(s(` ${p.bottomLeft}${p.horizontal.repeat(f)}${p.bottomRight}`))}else this.caps.unicode?(console.log(` ${a("MonkeysCode")} ${s(l)} ${o("\xB7 CLI Agent")}`),e&&console.log(` ${o(e)}`)):(console.log(` ${JF} MC - MonkeysCode CLI ${l}`),console.log(" Standalone Terminal Coding Agent"),e&&console.log(` ${e}`));if(console.log(""),this.opts.sandboxed){let p=` ${this.icons.lock} Sandboxed`;console.log(r?g.green(p):p)}else{let p=` ${this.icons.unlock} Unsandboxed`;console.log(r?g.yellow(p):p)}console.log("")}renderToken(e){if(!this.lastWasToken&&(this.clearSpinners(),this.lastWasToken=!0,this.caps.unicode)){let n=g.hex(wo.accent),r=Math.min(56,this.caps.columns-6);console.log(""),console.log(n(` ${this.box.topLeft}${this.box.horizontal} Agent ${this.box.horizontal.repeat(Math.max(0,r-9))}${this.box.topRight}`)),process.stdout.write(g.dim(` ${this.box.vertical} `))}if(this.tokenBuffer+=e.content,this.caps.unicode){let n=e.content.replace(/\n/g,`
805
805
  `+g.dim(` ${this.box.vertical} `));process.stdout.write(n)}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 n=this.caps.ansi,r=` ${this.icons.thinking} ${e.content}`;console.log(n?g.dim.italic(r):r)}renderRunStarted(e){this.lastWasToken=!1;let n=this.caps.ansi,r=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(n?g.dim(r):r),console.log(n?` ${g.bold("Model:")} ${e.model} ${g.bold("Mode:")} ${e.mode}`:` Model: ${e.model} Mode: ${e.mode}`),console.log(n?g.dim(r):r),console.log("")}renderRunComplete(e){this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),this.clearSpinners();let n=this.caps.ansi,r=(e.duration/1e3).toFixed(1),s=this.box;if(this.caps.unicode){let o=Math.min(54,this.caps.columns-6),a=g.hex(wo.accent),l=g.green,c=g.dim,u=i((p,f)=>{let h=(p+f).replace(/\x1b\[[0-9;]*m/g,""),_=Math.max(0,o-h.length-4);return` ${a(s.vertical)} ${p}${" ".repeat(_)}${f} ${a(s.vertical)}`},"pad");if(console.log(""),console.log(a(` ${s.topLeft}${s.horizontal} ${l(`${this.icons.success} Run Complete`)} ${s.horizontal.repeat(Math.max(0,o-17))}${s.topRight}`)),console.log(u(" Duration:",`${r}s`)),console.log(u(" Tokens:",`${e.tokensUsed.toLocaleString()}`)),console.log(u(" Tools:",`${e.toolCalls} calls`)),e.filesChanged.length>0){console.log(a(` ${s.teeRight}${s.horizontal.repeat(o)}${s.teeLeft}`)),console.log(u(" Files Changed:",`${e.filesChanged.length}`));for(let p of e.filesChanged){let f=p.split("/").slice(-2).join("/");console.log(u(` ${this.icons.edit} ${f}`,""))}}console.log(a(` ${s.bottomLeft}${s.horizontal.repeat(o)}${s.bottomRight}`)),console.log("")}else{let o=this.box.separator.repeat(Math.min(60,this.caps.columns-2)),a=[`${this.icons.success} Done`,`${e.tokensUsed.toLocaleString()} tokens`,`${e.toolCalls} tool calls`,`${e.filesChanged.length} files changed`,`${r}s`].join(" \xB7 ");if(console.log(""),console.log(o),console.log(` ${a}`),e.filesChanged.length>0){console.log(""),console.log(" Files changed:");for(let l of e.filesChanged)console.log(` ${l}`)}console.log(o),console.log("")}this.statusBar&&this.statusBar.update({busy:!1,activity:""})}renderRunError(e){this.lastWasToken&&(console.log(""),this.lastWasToken=!1),this.clearSpinners();let n=this.caps.ansi,r=` ${this.icons.error} Agent error: ${e.message}`;console.log(n?g.red(r):r),e.code&&console.log(n?g.dim(` Code: ${e.code}`):` Code: ${e.code}`)}renderToolStart(e){if(this.lastWasToken&&(this.flushTokenBuffer(),this.lastWasToken=!1),console.log(""),console.log(KF(e.toolName,e.args)),this.toolStartTimes.set(e.toolId,Date.now()),!this.opts.accessible&&this.caps.ansi){let n=this.getToolAvgDuration(e.toolName),r=n?` (~${(n/1e3).toFixed(1)}s)`:"",s=O1({text:`${e.toolName} executing...${r}`,indent:4,spinner:"dots"}).start();this.activeToolSpinners.set(e.toolId,s)}}renderToolProgress(e){let n=this.activeToolSpinners.get(e.toolId);if(n&&(e.progress!==void 0&&(n.text=`${e.toolName} (${e.progress}%)`),e.output)){n.stop();let r=this.caps.ansi,s=` ${e.output}`;console.log(r?g.dim(s):s),n.start()}}renderToolResult(e){let n=this.activeToolSpinners.get(e.toolId);n&&(n.stop(),this.activeToolSpinners.delete(e.toolId));let r=this.toolStartTimes.get(e.toolId);if(r){let o=Date.now()-r;this.recordToolDuration(e.toolName,o),this.toolStartTimes.delete(e.toolId)}let s={maxOutputLines:this.opts.maxToolOutputLines,verbose:this.opts.verbose};console.log(VF(e.toolName,e.result,s))}renderToolError(e){let n=this.activeToolSpinners.get(e.toolId);n?(n.fail(e.message),this.activeToolSpinners.delete(e.toolId)):console.log(lle(e.toolName,e.message))}renderApprovalRequest(e){this.lastWasToken&&(console.log(""),this.lastWasToken=!1),this.clearSpinners();let n=this.caps.ansi,r=this.box,s={safe:{color:n?g.green:a=>a,icon:this.icons.success,label:"Safe"},moderate:{color:n?g.yellow:a=>a,icon:this.icons.warning,label:"Moderate"},dangerous:{color:n?g.red:a=>a,icon:this.icons.error,label:"Destructive"}},o=s[e.riskLevel]||s.moderate;if(this.caps.unicode){let a=Math.min(54,this.caps.columns-6);console.log(""),console.log(o.color(` ${r.topLeft}${r.horizontal} ${o.icon} Approval Required ${r.horizontal.repeat(Math.max(0,a-23))}${r.topRight}`)),console.log(o.color(` ${r.vertical}${" ".repeat(a)}${r.vertical}`));let l=` Tool: ${e.toolName}`,c=Math.max(0,a-l.length);console.log(o.color(` ${r.vertical}`)+` ${l}${" ".repeat(c)}`+o.color(r.vertical));let u=` ${e.description}`.slice(0,a-2),p=Math.max(0,a-u.length);console.log(o.color(` ${r.vertical}`)+` ${u}${" ".repeat(p)}`+o.color(r.vertical));let f=` Risk: ${o.icon} ${o.label}`,h=f.replace(/\x1b\[[0-9;]*m/g,""),_=Math.max(0,a-h.length);console.log(o.color(` ${r.vertical}`)+` ${f}${" ".repeat(_)}`+o.color(r.vertical)),console.log(o.color(` ${r.vertical}${" ".repeat(a)}${r.vertical}`));let y=e.riskLevel==="dangerous"?" [y] Allow once [n] Deny":" [y] Allow [n] Deny [a] Always [!] YOLO",b=Math.max(0,a-y.length);console.log(o.color(` ${r.vertical}`)+g.dim(` ${y}${" ".repeat(b)}`)+o.color(r.vertical)),console.log(o.color(` ${r.bottomLeft}${r.horizontal.repeat(a)}${r.bottomRight}`))}else{console.log(""),console.log(o.color(` ${o.icon} Permission required: ${e.toolName}`)),console.log(o.color(` ${e.description}`)),console.log(o.color(` Risk: ${o.label}`));let a=JSON.stringify(e.args,null,2).split(`
806
806
  `).slice(0,5);for(let l of a)console.log(n?g.dim(` ${l}`):` ${l}`)}this.statusBar&&this.statusBar.update({activity:`approval: ${e.toolName}`,busy:!1})}printStatus(e){let n=this.caps.ansi;console.log(n?g.dim(` ${e}`):` ${e}`)}printSuccess(e){let n=this.caps.ansi;console.log(n?g.green(` ${this.icons.success} ${e}`):` ${this.icons.success} ${e}`)}printError(e){let n=this.caps.ansi;console.error(n?g.red(` ${this.icons.error} ${e}`):` ${this.icons.error} ${e}`)}printWarning(e){let n=this.caps.ansi;console.log(n?g.yellow(` ${this.icons.warning} ${e}`):` ${this.icons.warning} ${e}`)}startSpinner(e){if(this.opts.accessible||!this.caps.ansi){console.log(` ${e}...`);return}this.spinner=O1({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,n]of this.activeToolSpinners)n.stop();this.activeToolSpinners.clear()}getToolAvgDuration(e){let n=this.toolDurations.get(e);if(!n||n.length===0)return 0;let r=n.reduce((s,o)=>s+o,0);return Math.round(r/n.length)}recordToolDuration(e,n){let r=this.toolDurations.get(e)??[];r.push(n),r.length>10&&r.shift(),this.toolDurations.set(e,r)}printSessionSummary(e){let n=this.caps.ansi,r=e.endTime?((e.endTime-e.startTime)/1e3).toFixed(1):"?";if(this.caps.unicode){let s=this.box,o=Math.min(48,this.caps.columns-6),a=g.hex(wo.accent),l=g.dim,c=[["Duration",`${r}s`],["Tokens",e.tokensUsed.toLocaleString()],["Tools",`${e.toolCalls} calls`],["Files",`${e.filesChanged.length} changed`]];console.log(""),console.log(a(` ${s.topLeft}${s.horizontal} \u{1F4CB} Session Summary ${s.horizontal.repeat(Math.max(0,o-22))}${s.topRight}`));for(let[u,p]of c){let f=u.padEnd(12),h=`${f}${p}`,_=Math.max(0,o-h.length-4);console.log(a(` ${s.vertical}`)+` ${l(f)}${p}${" ".repeat(_)}`+a(s.vertical))}if(e.filesChanged.length>0){console.log(a(` ${s.teeRight}${s.horizontal.repeat(o)}${s.teeLeft}`));for(let u of e.filesChanged){let p=u.split("/").slice(-2).join("/"),f=` ${this.icons.edit} ${p}`,h=Math.max(0,o-f.length);console.log(a(` ${s.vertical}`)+`${f}${" ".repeat(h)}`+a(s.vertical))}}console.log(a(` ${s.bottomLeft}${s.horizontal.repeat(o)}${s.bottomRight}`)),console.log("")}else{let s=this.box.separator.repeat(Math.min(60,this.caps.columns-2));console.log(""),console.log(n?g.dim(s):s),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: ${r}s`),console.log(n?g.dim(s):s),console.log("")}}printToolCallStart(e,n){if(this.lastWasToken&&(console.log(""),this.lastWasToken=!1),console.log(""),console.log(KF(e,n)),!this.opts.accessible&&this.caps.ansi){let r=O1({text:`${e} executing...`,indent:4,spinner:"dots"}).start();this.activeToolSpinners.set(e,r)}}printToolCallResult(e,n){let r=this.activeToolSpinners.get(e);r&&(r.stop(),this.activeToolSpinners.delete(e));let s={maxOutputLines:this.opts.maxToolOutputLines,verbose:this.opts.verbose},o={type:"generic",summary:n.slice(0,200),data:n};console.log(VF(e,o,s))}printTodoList(e){let n=this.caps.ansi,r=n?g.dim:o=>o,s=n?g.bold:o=>o;console.log(""),console.log(s(" \u{1F4CB} Task Plan:"));for(let o of e){let a=o.status==="completed"||o.status==="done"?"\u2705":o.status==="in_progress"?"\u{1F504}":"\u2B1C",l=o.status==="completed"||o.status==="done"?n?g.green:c=>c:o.status==="in_progress"?n?g.yellow:c=>c:r;console.log(l(` ${a} ${o.content}`))}console.log("")}flushTokenBuffer(){if(!this.tokenBuffer)return;let e=this.tokenBuffer.replace(/<think>[\s\S]*?<\/think>/g,"").trim();this.tokenBuffer="";let n=Math.max(20,this.caps.columns-4),r=e.split(`
807
807
  `).reduce((s,o)=>s+Math.max(1,Math.ceil(Yr(o)/n)),0);if(this.caps.ansi&&Woe(e)){for(let o=0;o<r;o++)process.stdout.write("\x1B[2K"),o<r-1&&process.stdout.write("\x1B[1A");process.stdout.write("\r");let s=cl(e,{caps:this.caps,width:this.caps.columns-6});if(this.caps.unicode){let o=g.dim(` ${this.box.vertical} `),a=s.split(`
@@ -965,7 +965,7 @@ ${e.problems.map(r=>` - ${r}`).join(`
965
965
  `));return}if(!r.length){let l=wc.find(c=>c.key===n);t.printStatus(`${n} = ${Ph(Ww(s,n))}${l?g.dim(` (${l.help})`):""}`);return}let o=bde(n,r.join(" "));if(!o.ok){t.printError(o.error);return}let a=lr("user",n,o.value);if(a){t.printError(a);return}t.printSuccess(`${n} = ${Ph(o.value)} (user settings). Takes effect in new sessions.`)}},W3e={name:"rewind",description:"Roll back to an earlier prompt (conversation + files) \xB7 Esc Esc",usage:"/rewind",category:"session",run(t){if(t.ui?.rewind){t.ui.rewind();return}t.printWarning("Rewind needs the full-screen UI. In the plain REPL use /undo to revert the last file change.")}},wde=[Y3e,q3e,Ide,W3e]});function Rde(){let t=new $I;return t.register(...yle,...vle,...Dle,...Ble,...oue,...Due,...xue,...Que,r9,...Lue,...wde),t.register(Qie(t),e9(t)),t}var kde=P(()=>{"use strict";Go();Cle();Rle();Nle();Ple();iue();Nue();Oue();Fue();Gue();_de();vde();UI();Gw();Go();UI();i(Rde,"createDefaultRegistry")});function V3e(t,e){let n={},r=[];for(let o of t.matchAll(j3e))o[1]!==void 0&&e.includes(o[1])?n[o[1]]=o[2].replace(K3e,""):r.push(o[3]??o[4]??o[5]??o[0]);let s=e.filter(o=>n[o]===void 0);return s.forEach((o,a)=>{r.length!==0&&(n[o]=a===s.length-1?r.splice(0).join(" "):r.shift())}),n}function Dde(t){return t.listPrompts().map(e=>{let n=`/${e.command} ${e.arguments.map(r=>`${r.name}=\u2026`).join(" ")}`.trim();return{name:e.command,description:(e.description||`MCP prompt ${e.name}`).slice(0,100),argHint:e.arguments.map(r=>r.required?`<${r.name}>`:`[${r.name}]`).join(" ")||void 0,usage:n,category:"tools",source:`mcp:${e.server}`,async run(r,s){let o=V3e(s,e.arguments.map(l=>l.name)),a=e.arguments.filter(l=>l.required&&!o[l.name]).map(l=>l.name);if(a.length){r.printError(`Missing argument${a.length>1?"s":""}: ${a.join(", ")} \u2014 usage: ${n}`);return}try{let l=await t.getPrompt(e.server,e.name,o);if(!l.text.trim()){r.printWarning(`Prompt ${e.name} returned no text.`);return}await r.submit(l.text)}catch(l){r.printError(`MCP prompt ${e.name}: ${l.message}`)}}}})}var j3e,K3e,Nde=P(()=>{"use strict";j3e=new RegExp(String.raw`([A-Za-z_][\w-]*)=("[^"]*"|'[^']*'|\S+)|"([^"]*)"|'([^']*)'|(\S+)`,"g"),K3e=new RegExp(String.raw`^["']|["']$`,"g");i(V3e,"parsePromptArgs");i(Dde,"mcpPromptCommands")});var Ode={};ot(Ode,{analyzeImpact:()=>xde,notifyAffectedSessions:()=>J3e});function xde(t,e,n){let r=e.filter(o=>o.id!==n&&(o.status==="running"||o.status==="idle"));if(r.length===0||t.length===0)return{modifiedFiles:t,affectedSessions:[]};let s=[];for(let o of r){let a=o.task.toLowerCase(),l="",c=0;for(let u of t){let p=fl.basename(u).toLowerCase(),f=u.toLowerCase();if(a.includes(p)&&.9>c&&(c=.9,l=`Task mentions "${p}" which was modified`),o.workspace){let h=fl.relative(o.workspace,u),_=fl.dirname(h).split(fl.sep)[0];_&&a.includes(_.toLowerCase())&&.7>c&&(c=.7,l=`Task involves "${_}" directory where changes were made`)}for(let h of z3e)if(h.pathPattern.test(f))for(let _ of h.keywords)a.includes(_)&&.6>c&&(c=.6,l=`Modified ${p} (${_}-related) \u2014 task mentions "${_}"`)}c>=.5&&s.push({sessionId:o.id,task:o.task,reason:l,confidence:c})}return s.sort((o,a)=>a.confidence-o.confidence),{modifiedFiles:t,affectedSessions:s}}async function J3e(t,e,n){if(e.length===0)return[];let r=await t.listAgents(),s=xde(e,r,n);if(s.affectedSessions.length===0)return[];let o=[];for(let a of s.affectedSessions){let c=[`\u26A0\uFE0F Heads up: I modified ${e.length<=3?e.map(p=>fl.basename(p)).join(", "):`${e.slice(0,3).map(p=>fl.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${a.reason}`,`This may affect your task: "${a.task.substring(0,60)}"`].join(`
966
966
  `),u=await t.sendMessage(a.sessionId,c);o.push(u)}return o}var fl,z3e,Mde=P(()=>{"use strict";fl=N(require("node:path"),1),z3e=[{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"]}];i(xde,"analyzeImpact");i(J3e,"notifyAffectedSessions")});async function jw(t){let{options:e,token:n,auth:r}=t,s=ft({workspace:e.workspace});for(let oe of s.warnings)t.onWarning(oe);let o=cg(s.value),a=s.value.permissions?.disableBypassPermissionsMode==="disable",l=e.permissionMode??o.permissionMode??"default";l==="bypass"&&a&&(t.onWarning("bypass mode is disabled by managed settings; starting in default mode"),l="default");let c=mu(e.workspace,{allowedTools:e.allowedTools,deniedTools:e.deniedTools,addDirs:e.addDirs,approveSafeCommands:e.approveForMe},s),u,p=new p_({engine:c,getMode:i(()=>u.getPermissionMode(),"getMode"),prompt:t.prompt}),f=Wa.fromSettings(e.workspace,s,{interactiveAuth:process.stdin.isTTY===!0,onAuthPrompt:i(oe=>t.onWarning(oe),"onAuthPrompt")});f.start();let h=new Yl(e.workspace,{enabled:e.hooks!==!1,timeoutMs:e.hookTimeoutMs??1e4,effective:s,trustRepoHooks:!1}),_=!1,E=QD(e.workspace,typeof s.value.outputStyle=="string"?s.value.outputStyle:void 0);E.warning&&t.onWarning(E.warning);let y=new gs,b=`interactive-${Date.now().toString(36)}`,w=Date.now(),v=new Set,k=new Set,O=null;t.resumeId?(O=y.load(t.resumeId)??Z3e(y,t.resumeId),O||t.onWarning(`No saved session matches "${t.resumeId}" \u2014 starting fresh.`)):e.continueSession&&(O=y.loadLatest(e.workspace),O||t.onWarning("No previous session found in this directory \u2014 starting fresh."));let R=O;if(O)for(let oe of O.stats.filesChanged)v.add(oe);let $=null;try{let{MessageBroker:oe}=await Promise.resolve().then(()=>(K1(),Dw));n&&o.platformUrl&&($=new oe(o.platformUrl,n,b))}catch{}let q=i(()=>{if(!R)return;let oe=u.toJSON();R.history=oe.history,R.transcript=oe.transcript,R.branch=vc(e.workspace)||R.branch,R.model=u.getModel();try{y.save(R)}catch{}},"persist");u=new dw({loop:{platformUrl:o.platformUrl,token:n,model:e.model,workspace:e.workspace,mode:Yd(l),maxTurns:o.maxTurns,sandboxed:e.sandbox,webEnabled:o.webEnabled,effort:e.effort??o.effort,userId:r?.user?.id,orgId:r?.org?.id,mcp:f.hasServers?f:void 0,services:s.value.diagnostics===!1?void 0:{diagnostics:new Tg(e.workspace)},hookRunner:h,responseStyle:E.style.name==="default"?void 0:E.style.instructions},outputStyle:E.style.name,permissionMode:l,permissionDecider:p,bypassDisabled:a,cycleBypass:s.value.cycleBypass===!0,maxCostUsd:e.maxCost,initialHistory:O?.history,initialTranscript:O?.transcript,sessionId:i(()=>R?.id,"sessionId"),onTurnStart(oe){R||(R=y.create(e.workspace,e.model,e.mode)),R.title||(R.title=X3e(oe)),y.addMessage(R,"user",oe)},async onTurnEnd(oe,Q){for(let G of oe.filesModified)v.add(G);R&&y.updateStats(R,oe.tokensIn+oe.tokensOut,0,oe.filesModified),q();try{let G=await Promise.resolve().then(()=>(rE(),nE));G.shouldNotify({enabled:s.value.notifyOnIdle,kind:"turn",durationMs:oe.duration,headless:!process.stdout.isTTY})&&G.notifyTurnComplete(oe.duration,oe.filesModified.length)}catch{}if(oe.filesModified.length>0&&$)try{let{notifyAffectedSessions:G}=await Promise.resolve().then(()=>(Mde(),Ode));await G($,oe.filesModified,b)}catch{}}});let ne=new Yg(()=>R?.id??b),W=[];u.on("event",oe=>{for(let Q of ne.map(oe))W.push(Q);if(oe.type==="request_usage"&&W.push(cb(R?.id??b,oe.usage)),oe.type==="run_complete"&&R){let Q=oe.summary,G=ne.lastText.trim();W.push({type:"result",subtype:"success",is_error:!1,result:G,session_id:R.id,num_turns:Q.turns,duration_ms:Q.duration,usage:{input_tokens:Q.tokensIn,output_tokens:Q.tokensOut,cached_tokens:Q.tokensCached,thinking_tokens:0},cost_usd:zi(u.getModel(),Q.tokensIn,Q.tokensOut,0,{tokensCached:Q.tokensCached}),is_estimated:!0,permission_denials:[],exit_code:0});let ie=W;W=[];try{y.appendEvents(R,ie)}catch{}}}),u.on("event",oe=>{if(oe.type!=="tool_call_start")return;let Q=oe.args?.file_path??oe.args?.path;Q&&(/^(read_file|file_read)$/.test(oe.name)&&k.add(String(Q)),/^(edit_file|create_file|write_file|replace_in_file|patch_file|file_edit|file_write|file_create)$/.test(oe.name)&&v.add(String(Q)))});let Z=new pu({engine:c,getMode:i(()=>u.getPermissionMode(),"getMode"),onDenied:i(oe=>t.onBackgroundDenied?.(`background agent: ${oe.description} \u2014 ${oe.reason}`),"onDenied")}),ue=new uw({workspace:e.workspace,model:e.model,token:n,userId:r?.user?.id,orgId:r?.org?.id,permissionDecider:Z},t.renderer),he=Rde(),z=new Hw({workspace:e.workspace,commands:he,hooks:h,mcp:f,grantReadRoot:i(oe=>{try{p.grantReadRoot?.(oe)}catch{}},"grantReadRoot"),loadSettings:i(()=>ft({workspace:e.workspace}),"loadSettings")});try{let oe=await z.reload();for(let Q of Yw(oe))t.onWarning(Q);for(let Q of iS(oe.conflicts))t.onWarning(Q)}catch(oe){t.onWarning(`plugins: ${oe.message}`);try{let{conflicts:Q}=Qw(he,e.workspace);for(let G of iS(Q))t.onWarning(G)}catch(Q){t.onWarning(`custom commands: ${Q.message}`)}}let de=i(()=>{try{he.replaceDynamic("mcp-prompts",Dde(f))}catch{}},"syncMcpPrompts");f.on("change",de),de();let ge=!1,be=i(async()=>{if(!ge){ge=!0,q(),f.stop(),z.dispose();try{await h.run("SessionEnd",{sessionId:b,workspace:e.workspace,data:{reason:"exit"}})}catch{}}},"shutdown"),Ue=!1;return{session:u,settings:o,effective:s,engine:c,decider:p,backgroundDecider:Z,mcp:f,hookRunner:h,sessionStore:y,subtaskManager:ue,registry:he,extensions:z,sessionId:b,startedAt:w,filesRead:k,filesModified:v,getCurrentSession:i(()=>R,"getCurrentSession"),resumed:O,initialMode:l,messageBroker:$,pollMessages:i(async()=>{if(!$)return[];try{return(await $.pollMessages()??[]).map(Q=>({from:Q.from||Q.senderId||"unknown",content:Q.content||Q.message||"",timestamp:Q.timestamp?new Date(Q.timestamp):new Date}))}catch{return[]}},"pollMessages"),persist:q,buildCommandContext:i(oe=>({session:u,options:e,token:n,auth:r,sessionId:b,print:oe.print,printSuccess:oe.printSuccess,printError:oe.printError,printWarning:oe.printWarning,printStatus:oe.printStatus,clearScreen:oe.clearScreen,exit:oe.exit,submit:i(Q=>u.submit(Q),"submit"),submitWith:i((Q,G)=>u.submit(Q,{run:G}),"submitWith"),services:{sessionStore:y,hookRunner:h,subtaskManager:ue,renderer:t.renderer,getCurrentSession:i(()=>R,"getCurrentSession"),setCurrentSession:i(Q=>{R=Q},"setCurrentSession"),filesRead:k,filesModified:v,mcp:f,permissionEngine:c,foregroundDecider:p,backgroundDecider:Z,effective:s,extensions:z},ui:oe.ui}),"buildCommandContext"),shutdown:be,resolveWorkspaceTrust:i(async oe=>{let Q=op(e.workspace,sp(h.getAllHooks(),s));if(!Ue){Ue=!0;let G=Q.trusted;if(!G){let Ce="not-now";try{Ce=await oe(Q)}catch{}if(Ce==="trust"){try{aN(e.workspace,Q)}catch(We){t.onWarning(`could not save workspace trust: ${We.message}`)}G=!0}else t.onWarning(`Repository hooks${Q.items.some(We=>We.kind==="status-line")?" and status line":""} are off for this session (workspace not trusted). /trust to review.`)}_=G,h.setTrusted(G);for(let Ce of h.warnings)t.onWarning(Ce);let ie=await h.run("SessionStart",{sessionId:b,workspace:e.workspace,data:{source:O?"resume":"startup",model:e.model,mode:l}}).catch(()=>null);for(let Ce of ie?.errors??[])t.onWarning(Ce);return ie?.additionalContext.length&&u.addSessionContext(ie.additionalContext.join(`
967
967
 
968
- `)),{...Q,trusted:G}}return{...Q,trusted:_}},"resolveWorkspaceTrust"),isWorkspaceTrusted:i(()=>_,"isWorkspaceTrusted")}}async function aS(t,e,n={}){let r=0;try{let{listAllSkills:c}=await Promise.resolve().then(()=>(Vd(),VA));r=c(e.workspace).length}catch{}let s=t.extensions.summary?.active.length??0,o=t.settings,a=o.providerKeys?.anthropic||o.providerKeys?.openai||o.providerKeys?.google?"Direct API keys":o.customEndpoint?`Custom endpoint ${o.customEndpoint}`:void 0,l=t.resumed;return{version:"1.0.1",model:t.session.getModel(),permissionMode:t.session.getPermissionMode(),workspace:e.workspace,branch:vc(e.workspace)||void 0,dirty:lS(e.workspace),sandboxed:!!e.sandbox,mcpServers:t.mcp.list().length,skills:r,hooks:t.hookRunner.getHooks().length,plugins:s,engine:a,resumed:l?`Resumed "${l.title??l.id.slice(0,8)}" \xB7 ${l.turnCount} turn${l.turnCount===1?"":"s"}`:void 0,tabs:n.tabs}}function X3e(t){let n=(t.split(`
968
+ `)),{...Q,trusted:G}}return{...Q,trusted:_}},"resolveWorkspaceTrust"),isWorkspaceTrusted:i(()=>_,"isWorkspaceTrusted")}}async function aS(t,e,n={}){let r=0;try{let{listAllSkills:c}=await Promise.resolve().then(()=>(Vd(),VA));r=c(e.workspace).length}catch{}let s=t.extensions.summary?.active.length??0,o=t.settings,a=o.providerKeys?.anthropic||o.providerKeys?.openai||o.providerKeys?.google?"Direct API keys":o.customEndpoint?`Custom endpoint ${o.customEndpoint}`:void 0,l=t.resumed;return{version:"1.0.2",model:t.session.getModel(),permissionMode:t.session.getPermissionMode(),workspace:e.workspace,branch:vc(e.workspace)||void 0,dirty:lS(e.workspace),sandboxed:!!e.sandbox,mcpServers:t.mcp.list().length,skills:r,hooks:t.hookRunner.getHooks().length,plugins:s,engine:a,resumed:l?`Resumed "${l.title??l.id.slice(0,8)}" \xB7 ${l.turnCount} turn${l.turnCount===1?"":"s"}`:void 0,tabs:n.tabs}}function X3e(t){let n=(t.split(`
969
969
  `).map(o=>o.trim()).find(o=>o.length>0)??"").replace(/\s+/g," ").replace(/^[/!#]+/,"").trim();if(n.length<=60)return n||"(untitled)";let r=n.slice(0,59),s=r.lastIndexOf(" ");return(s>40?r.slice(0,s):r)+"\u2026"}function Z3e(t,e){let n=t.list().find(r=>r.id.startsWith(e));return n?t.load(n.id):null}function vc(t){try{return(0,o9.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function lS(t){try{return(0,o9.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().length>0}catch{return!1}}function Kw(t){let e=Math.floor(t/6e4),n=Math.floor(t%6e4/1e3);return e>0?`${e}m ${n}s`:`${n}s`}function cS(t,e){return Bde.relative(t,e)||e}var Bde,o9,uS=P(()=>{"use strict";Bde=N(require("node:path"),1),o9=require("node:child_process");vn();xC();Rt();YA();Ys();Ef();i_();fle();Sle();Gg();kde();Gw();xg();fu();Nde();t9();yN();C_();$o();i(jw,"bootstrapSession");i(aS,"welcomeInfo");i(X3e,"titleFromPrompt");i(Z3e,"findByPrefix");i(vc,"gitBranch");i(lS,"gitDirty");i(Kw,"formatElapsed");i(cS,"relativeTo")});async function Vw(t,e){if(e.decider){let o=await e.decider.decide({toolName:"run_command",args:{command:t,cwd:e.workspace},runId:"bang-shell"});if(o.action==="deny")return{denied:o.message??"denied by permissions",exitCode:null,output:"",killed:!1,contextBlock:""}}let n=process.platform==="win32",r=n?process.env.ComSpec||"cmd.exe":process.env.SHELL||"/bin/sh",s=n?["/d","/s","/c",t]:["-c",t];return new Promise(o=>{let a="",l=!1,c=(0,Pde.spawn)(r,s,{cwd:e.workspace,env:Xr({FORCE_COLOR:"0",CI:process.env.CI}),stdio:["ignore","pipe","pipe"],detached:!n}),u=i(_=>{let E=_.toString("utf8");a+=E,a.length>dS*2&&(a=a.slice(-dS)),e.onOutput?.(E)},"onData");c.stdout?.on("data",u),c.stderr?.on("data",u);let p=i(()=>{if(c.exitCode===null){l=!0;try{!n&&c.pid?process.kill(-c.pid,"SIGTERM"):c.kill()}catch{}}},"kill"),f=setTimeout(p,e.timeoutMs??10*6e4);e.signal?.addEventListener("abort",p,{once:!0});let h=i(_=>{clearTimeout(f),e.signal?.removeEventListener("abort",p),o({exitCode:_,output:a,killed:l,contextBlock:eGe(t,a,_,l)})},"finish");c.on("error",_=>{a+=`
970
970
  ${_.message}`,h(127)}),c.on("close",_=>h(_))})}function eGe(t,e,n,r=!1){let s=e.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"").replace(/\s+$/,"");s.length>dS&&(s=`[\u2026 ${s.length-dS} chars truncated \u2026]
971
971
  `+s.slice(-dS));let o=r?"[killed]":`[exit ${n??"?"}]`;return`The user ran a shell command locally:
@@ -986,7 +986,7 @@ ${s}${s?`
986
986
  `).length;this.line(`Tool ${e.name} finished${e.durationMs!==void 0?` in ${(e.durationMs/1e3).toFixed(1)} seconds`:""}. ${r} line${r===1?"":"s"} of output.`);break}case"tool_call_error":this.line(`Tool ${e.name} failed: ${e.error}`);break;case"approval_resolved":this.line(`Decision for ${e.toolName}: ${e.decision.action==="allow"?"allowed":"denied"}.`);break;case"todo_update":{let r=e.todos.filter(s=>s.status==="completed").length;this.line(`Todo list, ${r} of ${e.todos.length} done:`),e.todos.forEach((s,o)=>this.line(` ${o+1}. ${s.content}. ${uGe(s.status)}.`));break}case"context_compacted":e.serverTrimmed&&this.line(`Context was trimmed by the server, ${e.serverTrimmed} messages. Compacted.`),this.line(`Context compacted. ${e.elided} tool results summarized. Context now ${Math.round(e.contextUsed/e.contextWindow*100)} percent full.`);break;case"retrying":this.line(`Connection problem: ${e.reason}. Retry ${e.attempt} in ${Math.round(e.delayMs/1e3)} seconds.`);break;case"stream_reset":this.endStream(),this.line("Partial response discarded; retrying.");break;case"run_error":this.endStream(),this.line(`Error: ${e.error}`);break;case"run_complete":{this.endStream();let r=e.summary,s=n?.getStats();this.line(`Done. ${r.turns} model turn${r.turns===1?"":"s"}, ${r.tokensIn+r.tokensOut} tokens, ${(r.duration/1e3).toFixed(1)} seconds.`+(r.filesModified.length?` ${r.filesModified.length} file${r.filesModified.length===1?"":"s"} modified.`:"")+(s?` Session cost ${s.costUsd.toFixed(2)} dollars. Context ${Math.round(s.contextUsed/Math.max(1,s.contextWindow)*100)} percent full.`:""));let o=n?.getQueued?.()??[];o.length&&this.line(`${o.length} queued message${o.length===1?"":"s"} will run next.`);break}}}exitSummary(e){this.line(""),this.line(`Session ended. Duration ${e.duration}. ${e.turns} turns. ${e.tokens} tokens. Cost ${e.cost.toFixed(2)} dollars.`),e.files.length&&this.line(`Files changed: ${e.files.join(", ")}.`),e.resumable&&this.line("Resume with: mc -c")}endThinking(){this.thinkingStart&&(this.line(`Thought for ${((Date.now()-this.thinkingStart)/1e3).toFixed(1)} seconds.`),this.thinkingStart=0)}endStream(){this.streaming&&(this.streaming=!1,process.stdout.write(`
987
987
  `))}};i(zde,"createAccessiblePrompt");i(cGe,"formatApprovalPlain");i(uGe,"statusWord");i(dGe,"summarizeArgs")});var tpe={};ot(tpe,{checkForUpdate:()=>Zde,gitBranch:()=>vc,gitDirty:()=>lS,isNewerVersion:()=>epe,startPlainRepl:()=>pGe});function Xde(t,e){let n=" ".repeat(e);return t.split(`
988
988
  `).map(r=>r&&n+r).join(`
989
- `)}async function Zde(){if($l()||/^(1|true)$/i.test(process.env.MONKEYSCODE_NO_UPDATE_CHECK??""))return null;let t="1.0.1";try{let e=await fetch("https://registry.npmjs.org/monkeyscode-cli/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!e.ok)return null;let r=(await e.json()).version;return!r||!epe(r,t)?null:{latest:r,plain:`Update available: v${t} to v${r}. Run npm i -g monkeyscode-cli to update.`,styled:g.hex(wo.accent)(` \u2B06 Update available: ${g.dim(`v${t}`)} \u2192 ${g.bold(`v${r}`)}`)+`
989
+ `)}async function Zde(){if($l()||/^(1|true)$/i.test(process.env.MONKEYSCODE_NO_UPDATE_CHECK??""))return null;let t="1.0.2";try{let e=await fetch("https://registry.npmjs.org/monkeyscode-cli/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(5e3)});if(!e.ok)return null;let r=(await e.json()).version;return!r||!epe(r,t)?null:{latest:r,plain:`Update available: v${t} to v${r}. Run npm i -g monkeyscode-cli to update.`,styled:g.hex(wo.accent)(` \u2B06 Update available: ${g.dim(`v${t}`)} \u2192 ${g.bold(`v${r}`)}`)+`
990
990
  `+g.dim(` Run ${g.bold("npm i -g monkeyscode-cli")} to update.`)}}catch{return null}}function epe(t,e){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let s=0;s<3;s++){if((r[s]||0)>(n[s]||0))return!0;if((r[s]||0)<(n[s]||0))return!1}return!1}async function pGe({initialPrompt:t,options:e,token:n,auth:r,accessible:s,resumeId:o}){let a=st();s&&(g.level=0,a.ansi=!1,a.emoji=!1);let l=s?new ev:null,c=i(J=>console.log(s?`Warning: ${J}`:g.yellow(` \u26A0 ${J}`)),"warn"),u,p=new Ac({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox,accessible:!!s}),f=await jw({options:e,token:n,auth:r,renderer:p,resumeId:o,prompt:s?zde(()=>u,e.workspace):Kde(()=>u),onWarning:c,onBackgroundDenied:i(J=>console.log(s?`
991
991
  Warning: ${J}`:g.yellow(`
992
992
  \u26A0 ${J}`)),"onBackgroundDenied")}),{session:h,settings:_,hookRunner:E,mcp:y,registry:b,filesModified:w}=f;if(f.resumed){let J=f.resumed;p.printSuccess(`Resumed session ${J.id.substring(0,8)}${J.title?` "${J.title}"`:""} (${J.turnCount} turns, ${J.stats.tokensUsed.toLocaleString()} tokens${J.history?.length?", memory restored":""})`)}s?l.header({model:e.model,mode:h.getPermissionMode(),effort:e.effort??_.effort,workspace:e.workspace,branch:vc(e.workspace)}):console.log(pS(await aS(f,e),{columns:a.columns,unicode:a.unicode,color:a.ansi}));let v=s?null:p.getStatusBar({model:e.model,mode:e.mode,branch:vc(e.workspace),dirty:lS(e.workspace),sandbox:e.sandbox,budgetUsd:e.maxCost||0,mcpNotice:y.statusNotice()??""});v?.start(),y.on("change",()=>v?.update({mcpNotice:y.statusNotice()??""})),h.on("change",()=>{if(!v)return;let J=h.getStats();v.update({tokensIn:J.tokensIn,tokensOut:J.tokensOut,cost:J.costUsd,turn:J.turns,busy:h.isRunning(),activity:h.isRunning()?k:""})});let k="thinking...";if(s&&console.log("Type a prompt to start. Type /help for commands, /exit to quit. Press Control C to cancel a run."),!t){let J=T1();J&&console.log(s?J:g.dim(` ${J}`))}Zde().then(J=>{J&&(console.log(""),console.log(s?J.plain:J.styled))}),await f.resolveWorkspaceTrust(async J=>{let Se=z1(J);if(console.log(s?Se.join(`
@@ -1024,9 +1024,9 @@ Cancelling the current run.`:`
1024
1024
  `),"onAuthPrompt")});try{return await o.login(s),console.log(g.green(` \u2713 Signed in to ${e}. Tokens are in the OS credential store.`)),!0}catch(a){return Mi(a.message)}}function v9(t,e){let n=ft({workspace:t}).value.mcpServers?.[e],r=new Au({server:e,url:n?.url??"http://localhost",store:Po()}).logout();return console.log(r?g.green(` \u2713 Removed stored tokens for ${e}`):g.dim(` No stored tokens for ${e}`)),!0}function kGe(t,e={}){let n=e.home??_pe.homedir(),r={added:[],skipped:[]},s=ft({workspace:t,userDir:e.userDir}).value.mcpServers??{},o=i(f=>{try{return JSON.parse(Em.readFileSync(f,"utf8"))}catch{return}},"readJson"),a=[],l=o(kc.join(n,".claude.json"));l?.mcpServers&&a.push({from:"~/.claude.json",scope:"user",servers:l.mcpServers});let c=Em.existsSync(t)?Em.realpathSync(t):t,u=l?.projects?.[t]??l?.projects?.[c];u?.mcpServers&&a.push({from:"~/.claude.json (this project)",scope:"local",servers:u.mcpServers});let p=o(kc.join(t,".mcp.json"));p?.mcpServers&&a.push({from:".mcp.json",scope:"project",servers:p.mcpServers});for(let f of a)for(let[h,_]of Object.entries(f.servers)){if(s[h]||r.added.some(y=>y.name===h)){r.skipped.push({name:h,reason:"already configured",from:f.from});continue}let E=bp(_);if("error"in E){r.skipped.push({name:h,reason:E.error,from:f.from});continue}e.dryRun||eE(f.scope,t,h,E.entry,e.userDir),r.added.push({name:h,scope:f.scope,from:f.from})}return r}function R9(t,e,n={}){if(e!=="claude")return Mi(`Unknown source "${e}". Supported: claude`);let r=kGe(t,n);if(console.log(""),!r.added.length&&!r.skipped.length)return console.log(g.dim(` No Claude Code MCP servers found (~/.claude.json, .mcp.json).
1025
1025
  `)),!0;for(let s of r.added)console.log(` ${g.green(n.dryRun?"+ would add":"\u2713 added")} ${g.bold(s.name)} ${g.dim(`\u2192 ${s.scope} (from ${s.from})`)}`);for(let s of r.skipped)console.log(` ${g.yellow("\u2013 skipped")} ${g.bold(s.name)} ${g.dim(`${s.reason} (from ${s.from})`)}`);return console.log(""),r.added.some(s=>s.scope==="project")&&!n.dryRun&&console.log(g.dim(" Project servers (.mcp.json) need approval like any repository server: mc mcp approve <name>")),!n.dryRun&&r.added.length&&console.log(g.dim(` Check them with: mc mcp list
1026
1026
  `)),!0}async function k9(t){let{ServeDecider:e}=await Promise.resolve().then(()=>(cpe(),lpe)),{McpServe:n}=await Promise.resolve().then(()=>(fpe(),gpe)),{createPermissionEngine:r}=await Promise.resolve().then(()=>(Ys(),tp)),{ToolExecutor:s}=await Promise.resolve().then(()=>(RD(),K4)),{HookRunner:o}=await Promise.resolve().then(()=>(i_(),_8)),{evaluateWorkspaceTrust:a,requiresTrustHeadless:l,workspaceExecItems:c}=await Promise.resolve().then(()=>(fu(),uN)),{normalizePermissionMode:u}=await Promise.resolve().then(()=>(Hs(),MU)),{getPlatformPaths:p}=await Promise.resolve().then(()=>($t(),jc)),{getAccessToken:f}=await Promise.resolve().then(()=>(sn(),Rr)),h=Em.realpathSync(kc.resolve(t.workspace)),_=ft({workspace:h}),E=i(q=>process.stderr.write(`[mc mcp serve] ${q}
1027
- `),"log"),y=u(t.permissionMode)??_.value.permissions?.defaultMode??"default";y==="bypass"&&_.value.permissions?.disableBypassPermissionsMode==="disable"&&(E("bypass mode is disabled by managed settings; using default"),y="default");let b=r(h,{allowedTools:t.allow,deniedTools:t.deny},_),w=new e({engine:b,mode:y,readOnly:t.readOnly,explicitAllow:t.allow}),v=await f().catch(()=>null)??"",k=new s({workspace:h,platformUrl:_.value.platformUrl??"",token:v}),O;t.hooks!==!1&&(O=new o(h,{effective:_,trustRepoHooks:!0}),l(_)&&!a(h,c(O.getAllHooks(),_)).trusted&&(O.setTrusted(!1),E("workspace not trusted: repository hooks are skipped (managed requireWorkspaceTrust)")));let R=new Date().toISOString().slice(0,10),$=new n({workspace:h,decider:w,executor:k,readOnly:t.readOnly,webEnabled:_.value.webEnabled!==!1&&!!v,isHidden:i(q=>b.isToolHidden(q),"isHidden"),hooks:O,log:E,tracePath:kc.join(p().data,"traces",`mcp-serve-${R}.jsonl`),version:"1.0.1"});E(`serving ${h} (mode ${y}${t.readOnly?", read-only":""})`),E("Your allow rules apply; calls MonkeysCode would ask about are confirmed by the MCP client."),E("Deny rules, destructive commands and paths outside the workspace are always refused."),await $.done}var Em,_pe,kc,IGe,Epe,wGe,D9=P(()=>{"use strict";He();Em=N(require("node:fs"),1),_pe=N(require("node:os"),1),kc=N(require("node:path"),1);KO();f9();Gg();gN();mN();vA();vn();Hs();IGe=new RegExp("^https?://","i"),Epe=new RegExp("\\$\\{"),wGe=new RegExp("token|secret|password|key|authorization|cookie","i");i(E9,"trustAdded");i(rv,"targetOf");i(hpe,"redact");i(Mi,"fail");i(vGe,"mcpListRows");i(S9,"mcpListCommand");i(y9,"mcpGetCommand");i(sv,"parseScope");i(Ape,"parsePairs");i(RGe,"buildAddEntry");i(C9,"mcpAddCommand");i(b9,"mcpAddJsonCommand");i(T9,"mcpRemoveCommand");i(I9,"mcpTestCommand");i(w9,"mcpLoginCommand");i(v9,"mcpLogoutCommand");i(kGe,"importClaudeMcp");i(R9,"mcpImportCommand");i(k9,"mcpServeCommand")});function Bpe(t,e=60){if(!Dc.ansi){console.log(`
1027
+ `),"log"),y=u(t.permissionMode)??_.value.permissions?.defaultMode??"default";y==="bypass"&&_.value.permissions?.disableBypassPermissionsMode==="disable"&&(E("bypass mode is disabled by managed settings; using default"),y="default");let b=r(h,{allowedTools:t.allow,deniedTools:t.deny},_),w=new e({engine:b,mode:y,readOnly:t.readOnly,explicitAllow:t.allow}),v=await f().catch(()=>null)??"",k=new s({workspace:h,platformUrl:_.value.platformUrl??"",token:v}),O;t.hooks!==!1&&(O=new o(h,{effective:_,trustRepoHooks:!0}),l(_)&&!a(h,c(O.getAllHooks(),_)).trusted&&(O.setTrusted(!1),E("workspace not trusted: repository hooks are skipped (managed requireWorkspaceTrust)")));let R=new Date().toISOString().slice(0,10),$=new n({workspace:h,decider:w,executor:k,readOnly:t.readOnly,webEnabled:_.value.webEnabled!==!1&&!!v,isHidden:i(q=>b.isToolHidden(q),"isHidden"),hooks:O,log:E,tracePath:kc.join(p().data,"traces",`mcp-serve-${R}.jsonl`),version:"1.0.2"});E(`serving ${h} (mode ${y}${t.readOnly?", read-only":""})`),E("Your allow rules apply; calls MonkeysCode would ask about are confirmed by the MCP client."),E("Deny rules, destructive commands and paths outside the workspace are always refused."),await $.done}var Em,_pe,kc,IGe,Epe,wGe,D9=P(()=>{"use strict";He();Em=N(require("node:fs"),1),_pe=N(require("node:os"),1),kc=N(require("node:path"),1);KO();f9();Gg();gN();mN();vA();vn();Hs();IGe=new RegExp("^https?://","i"),Epe=new RegExp("\\$\\{"),wGe=new RegExp("token|secret|password|key|authorization|cookie","i");i(E9,"trustAdded");i(rv,"targetOf");i(hpe,"redact");i(Mi,"fail");i(vGe,"mcpListRows");i(S9,"mcpListCommand");i(y9,"mcpGetCommand");i(sv,"parseScope");i(Ape,"parsePairs");i(RGe,"buildAddEntry");i(C9,"mcpAddCommand");i(b9,"mcpAddJsonCommand");i(T9,"mcpRemoveCommand");i(I9,"mcpTestCommand");i(w9,"mcpLoginCommand");i(v9,"mcpLogoutCommand");i(kGe,"importClaudeMcp");i(R9,"mcpImportCommand");i(k9,"mcpServeCommand")});function Bpe(t,e=60){if(!Dc.ansi){console.log(`
1028
1028
  ${t}
1029
- ${"\u2500".repeat(e)}`);return}let n="\u2500".repeat(Math.max(0,e-t.length-4));console.log(""),console.log(` ${ls.accent("\u2500\u2500")} ${ls.bold(t)} ${ls.accent(n)}`)}function Ppe(t,e){let n=" "+t.map(s=>{let o=s.header;return Mpe(o,s.width,s.align||"left")}).join(" ");console.log(Dc.ansi?ls.dim(n):n);let r=" "+t.map(s=>"\u2500".repeat(s.width)).join("\u2500\u2500");console.log(Dc.ansi?ls.dim(r):r);for(let s of e){let o=" "+s.cells.map((a,l)=>{let c=t[l];return Mpe(a,c.width,c.align||"left")}).join(" ");s.dim&&Dc.ansi?o=ls.dim(o):s.highlight&&Dc.ansi&&(o=ls.accent(o)),console.log(o)}}function Mpe(t,e,n){let r=PGe(t),s=Math.max(0,e-r.length);switch(n){case"right":return" ".repeat(s)+t;case"center":return" ".repeat(Math.floor(s/2))+t+" ".repeat(Math.ceil(s/2));default:return t+" ".repeat(s)}}function P9(t){console.log(Dc.ansi?` ${ls.dim(t)}`:` ${t}`)}function Lpe(t){return t>=1e6?`${(t/1e6).toFixed(t%1e6===0?0:1)}M`:t>=1e3?`${(t/1e3).toFixed(t%1e3===0?0:1)}K`:t.toString()}function L9(t){return t===0?Dc.ansi?ls.success("Free"):"Free":`$${t.toFixed(t<1?4:2)}`}function PGe(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function fS(){console.log("")}var BGe,ls,Dc,C0t,b0t,Fpe=P(()=>{"use strict";He();wr();BGe=N(require("node:readline"),1),ls={navy:g.hex("#051E50"),teal:g.hex("#A3CAD3"),accent:g.hex("#6B8DD6"),success:g.hex("#4ADE80"),warning:g.hex("#FBBF24"),error:g.hex("#F87171"),dim:g.dim,bold:g.bold,muted:g.gray},Dc=st(),C0t=_t(Dc),b0t=io(Dc);i(Bpe,"sectionHeader");i(Ppe,"printTable");i(Mpe,"padCell");i(P9,"hint");i(Lpe,"formatTokens");i(L9,"formatCost");i(PGe,"stripAnsi");i(fS,"blank")});var qpe={};ot(qpe,{default:()=>qGe});var qGe,Wpe=P(()=>{qGe={name:"monkeyscode-cli",version:"1.0.1",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:{"ensure:kernel":"node ../../scripts/ensure-context-kernel.mjs",prebuild:"npm run ensure:kernel",prebundle:"npm run ensure:kernel","prebundle:prod":"npm run ensure:kernel",predev:"npm run ensure:kernel",pretest:"npm run ensure:kernel","pretest:watch":"npm run ensure:kernel",pretypecheck:"npm run ensure:kernel",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 tests/*.test.tsx","test:watch":"node --import tsx --test --watch tests/*.test.ts",typecheck:"tsc -p tsconfig.json --noEmit",clean:"rm -rf dist",prepublishOnly:"npm run clean && npm run bundle:prod"},keywords:["monkeyscode","cli","coding-agent","terminal","ai","standalone"],dependencies:{"@monkeyscode/context-kernel":"file:../../packages/context-kernel","@monkeyscode/sdk":"file:../../packages/sdk-typescript",ajv:"^8.20.0",chalk:"^5.4.0","cli-highlight":"^2.1.11",commander:"^13.0.0",diff:"^7.0.0",ink:"^5.2.1","ink-text-input":"^6.0.0",marked:"^18.0.11",ora:"^8.1.0",react:"^18.3.1","string-width":"^7.2.0","wrap-ansi":"^9.0.2",ws:"^8.18.0"},devDependencies:{"@types/diff":"^6.0.0","@types/node":"^22.0.0","@types/react":"^18.3.31","@types/ws":"^8.5.0",esbuild:"^0.24.0","ink-testing-library":"^4.0.0",tsx:"^4.19.0",typescript:"^5.7.0"},engines:{node:">=20.0.0"}}});var fv,gme=P(()=>{"use strict";fv=class{static{i(this,"CronScheduler")}jobs=new Map;running=!1;add(e){let n={...e,timer:null,runCount:0,nextRunAt:null,active:!1};this.jobs.set(e.id,n),this.running&&this.scheduleNext(n)}remove(e){let n=this.jobs.get(e);return n?(n.timer&&clearTimeout(n.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 n=this.getNextCronTime(e.expression);if(!n)return;e.nextRunAt=n,e.active=!0;let r=n.getTime()-Date.now();e.timer=setTimeout(async()=>{e.runCount++;try{await e.callback()}catch{}this.scheduleNext(e)},Math.max(r,0)),e.timer&&typeof e.timer.unref=="function"&&e.timer.unref()}getNextCronTime(e){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,s,o,a,l]=n,c=new Date;for(let u=0;u<366*24*60;u++){let p=new Date(c.getTime()+u*6e4);if(p.setSeconds(0,0),!(p.getTime()<=c.getTime())&&this.matchesCronField(p.getMinutes(),r,0,59)&&this.matchesCronField(p.getHours(),s,0,23)&&this.matchesCronField(p.getDate(),o,1,31)&&this.matchesCronField(p.getMonth()+1,a,1,12)&&this.matchesCronField(p.getDay(),l,0,6))return p}return null}matchesCronField(e,n,r,s){if(n==="*")return!0;let o=n.split(",");for(let a of o)if(a.includes("/")){let[l,c]=a.split("/"),u=parseInt(c,10);if(l==="*"){if((e-r)%u===0)return!0}else if(l.includes("-")){let[p,f]=l.split("-").map(Number);if(e>=p&&e<=f&&(e-p)%u===0)return!0}}else if(a.includes("-")){let[l,c]=a.split("-").map(Number);if(e>=l&&e<=c)return!0}else if(parseInt(a,10)===e)return!0;return!1}}});var SS,V9,hv,fme=P(()=>{"use strict";SS=N(require("node:fs"),1),V9=N(require("node:path"),1),hv=class{static{i(this,"FileWatcher")}workspace;rules=[];watchers=[];pendingChanges=new Map;debounceMs=500;running=!1;constructor(e,n=500){this.workspace=e,this.debounceMs=n}watch(e,n){this.rules.push({patterns:e,callback:n})}start(){if(!this.running){this.running=!0;try{let e=SS.watch(this.workspace,{recursive:!0},(n,r)=>{!r||!this.running||r.startsWith(".git/")||r.includes("node_modules/")||this.onFileChange(r)});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 n=this.pendingChanges.get(e);n&&clearTimeout(n),this.pendingChanges.set(e,setTimeout(()=>{this.pendingChanges.delete(e),this.fireRules(e)},this.debounceMs))}fireRules(e){for(let n of this.rules)if(this.matchesAny(e,n.patterns))try{n.callback([e])}catch{}}matchesAny(e,n){for(let r of n)if(r==="**/*"||this.globMatch(e,r))return!0;return!1}globMatch(e,n){let r=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/{{DOUBLESTAR}}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${r}$`).test(e)}watchDirectories(e,n=0){if(!(n>3))try{let r=SS.readdirSync(e,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith(".")||s.name==="node_modules")continue;let o=V9.join(e,s.name);try{let a=SS.watch(o,(l,c)=>{!c||!this.running||this.onFileChange(V9.join(s.name,c))});this.watchers.push(a),this.watchDirectories(o,n+1)}catch{}}}catch{}}}});var Ame={};ot(Ame,{TriggerEngine:()=>z9});var El,yS,hme,z9,_me=P(()=>{"use strict";El=N(require("node:fs"),1),yS=N(require("node:path"),1),hme=require("node:events");ks();Rt();Ys();gme();fme();z9=class extends hme.EventEmitter{static{i(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=yS.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new fv,this.fileWatcher=new hv(e.workspace),this.loadState()}loadTriggers(){let e=yS.join(this.opts.workspace,".monkeyscode","triggers.json");if(!El.existsSync(e))return this.triggers=[],[];try{let n=JSON.parse(El.readFileSync(e,"utf8"));return this.triggers=(n.triggers||[]).filter(r=>r.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:i(()=>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||["**/*"],n=>{this.fire(e,{type:"file.changed",payload:{files:n},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 n of this.triggers)this.matches(n,e)&&await this.fire(n,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 n=this.triggers.find(r=>r.name===e);return n?{matched:!0,prompt:n.prompt,model:n.model||"default"}:{matched:!1,prompt:"",model:""}}matches(e,n){if(e.event!==n.type)return!1;if(e.filter){for(let[r,s]of Object.entries(e.filter))if(n.payload[r]!==s)return!1}return!0}async fire(e,n){let r=this.state.get(e.name),s=(e.cooldownSeconds||300)*1e3;if(r&&Date.now()-r.lastFired<s){this.emit("cooldown",{trigger:e.name,remaining:s-(Date.now()-r.lastFired)});return}if(this.activeRuns.has(e.name))return;this.emit("firing",{trigger:e.name,event:n.type});let o=Et(),a=new ur({platformUrl:o.platformUrl,token:this.opts.token,model:e.model||o.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,permissionDecider:np(this.opts.workspace)});this.activeRuns.set(e.name,a);try{let l=[`[Trigger: ${e.name}]`,`Event: ${n.type}`,n.payload?`Payload: ${JSON.stringify(n.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
1029
+ ${"\u2500".repeat(e)}`);return}let n="\u2500".repeat(Math.max(0,e-t.length-4));console.log(""),console.log(` ${ls.accent("\u2500\u2500")} ${ls.bold(t)} ${ls.accent(n)}`)}function Ppe(t,e){let n=" "+t.map(s=>{let o=s.header;return Mpe(o,s.width,s.align||"left")}).join(" ");console.log(Dc.ansi?ls.dim(n):n);let r=" "+t.map(s=>"\u2500".repeat(s.width)).join("\u2500\u2500");console.log(Dc.ansi?ls.dim(r):r);for(let s of e){let o=" "+s.cells.map((a,l)=>{let c=t[l];return Mpe(a,c.width,c.align||"left")}).join(" ");s.dim&&Dc.ansi?o=ls.dim(o):s.highlight&&Dc.ansi&&(o=ls.accent(o)),console.log(o)}}function Mpe(t,e,n){let r=PGe(t),s=Math.max(0,e-r.length);switch(n){case"right":return" ".repeat(s)+t;case"center":return" ".repeat(Math.floor(s/2))+t+" ".repeat(Math.ceil(s/2));default:return t+" ".repeat(s)}}function P9(t){console.log(Dc.ansi?` ${ls.dim(t)}`:` ${t}`)}function Lpe(t){return t>=1e6?`${(t/1e6).toFixed(t%1e6===0?0:1)}M`:t>=1e3?`${(t/1e3).toFixed(t%1e3===0?0:1)}K`:t.toString()}function L9(t){return t===0?Dc.ansi?ls.success("Free"):"Free":`$${t.toFixed(t<1?4:2)}`}function PGe(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function fS(){console.log("")}var BGe,ls,Dc,C0t,b0t,Fpe=P(()=>{"use strict";He();wr();BGe=N(require("node:readline"),1),ls={navy:g.hex("#051E50"),teal:g.hex("#A3CAD3"),accent:g.hex("#6B8DD6"),success:g.hex("#4ADE80"),warning:g.hex("#FBBF24"),error:g.hex("#F87171"),dim:g.dim,bold:g.bold,muted:g.gray},Dc=st(),C0t=_t(Dc),b0t=io(Dc);i(Bpe,"sectionHeader");i(Ppe,"printTable");i(Mpe,"padCell");i(P9,"hint");i(Lpe,"formatTokens");i(L9,"formatCost");i(PGe,"stripAnsi");i(fS,"blank")});var qpe={};ot(qpe,{default:()=>qGe});var qGe,Wpe=P(()=>{qGe={name:"monkeyscode-cli",version:"1.0.2",description:"MonkeysCode CLI \u2014 standalone terminal coding agent. Works independently of the IDE and Agent Manager.",license:"MIT",type:"module",main:"dist/monkeyscode-cli.cjs",bin:{mc:"dist/monkeyscode-cli.cjs",mcode:"dist/monkeyscode-cli.cjs",monkeyscode:"dist/monkeyscode-cli.cjs"},files:["dist/monkeyscode-cli.cjs","README.md","LICENSE"],scripts:{"ensure:kernel":"node ../../scripts/ensure-context-kernel.mjs",prebuild:"npm run ensure:kernel",prebundle:"npm run ensure:kernel","prebundle:prod":"npm run ensure:kernel",predev:"npm run ensure:kernel",pretest:"npm run ensure:kernel","pretest:watch":"npm run ensure:kernel",pretypecheck:"npm run ensure:kernel",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 tests/*.test.tsx","test:watch":"node --import tsx --test --watch tests/*.test.ts",typecheck:"tsc -p tsconfig.json --noEmit",clean:"rm -rf dist",prepublishOnly:"npm run clean && npm run bundle:prod"},keywords:["monkeyscode","cli","coding-agent","terminal","ai","standalone"],dependencies:{"@monkeyscode/context-kernel":"file:../../packages/context-kernel","@monkeyscode/sdk":"file:../../packages/sdk-typescript",ajv:"^8.20.0",chalk:"^5.4.0","cli-highlight":"^2.1.11",commander:"^13.0.0",diff:"^7.0.0",ink:"^5.2.1","ink-text-input":"^6.0.0",marked:"^18.0.11",ora:"^8.1.0",react:"^18.3.1","string-width":"^7.2.0","wrap-ansi":"^9.0.2",ws:"^8.18.0"},devDependencies:{"@types/diff":"^6.0.0","@types/node":"^22.0.0","@types/react":"^18.3.31","@types/ws":"^8.5.0",esbuild:"^0.24.0","ink-testing-library":"^4.0.0",tsx:"^4.19.0",typescript:"^5.7.0"},engines:{node:">=20.0.0"}}});var fv,gme=P(()=>{"use strict";fv=class{static{i(this,"CronScheduler")}jobs=new Map;running=!1;add(e){let n={...e,timer:null,runCount:0,nextRunAt:null,active:!1};this.jobs.set(e.id,n),this.running&&this.scheduleNext(n)}remove(e){let n=this.jobs.get(e);return n?(n.timer&&clearTimeout(n.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 n=this.getNextCronTime(e.expression);if(!n)return;e.nextRunAt=n,e.active=!0;let r=n.getTime()-Date.now();e.timer=setTimeout(async()=>{e.runCount++;try{await e.callback()}catch{}this.scheduleNext(e)},Math.max(r,0)),e.timer&&typeof e.timer.unref=="function"&&e.timer.unref()}getNextCronTime(e){let n=e.trim().split(/\s+/);if(n.length!==5)return null;let[r,s,o,a,l]=n,c=new Date;for(let u=0;u<366*24*60;u++){let p=new Date(c.getTime()+u*6e4);if(p.setSeconds(0,0),!(p.getTime()<=c.getTime())&&this.matchesCronField(p.getMinutes(),r,0,59)&&this.matchesCronField(p.getHours(),s,0,23)&&this.matchesCronField(p.getDate(),o,1,31)&&this.matchesCronField(p.getMonth()+1,a,1,12)&&this.matchesCronField(p.getDay(),l,0,6))return p}return null}matchesCronField(e,n,r,s){if(n==="*")return!0;let o=n.split(",");for(let a of o)if(a.includes("/")){let[l,c]=a.split("/"),u=parseInt(c,10);if(l==="*"){if((e-r)%u===0)return!0}else if(l.includes("-")){let[p,f]=l.split("-").map(Number);if(e>=p&&e<=f&&(e-p)%u===0)return!0}}else if(a.includes("-")){let[l,c]=a.split("-").map(Number);if(e>=l&&e<=c)return!0}else if(parseInt(a,10)===e)return!0;return!1}}});var SS,V9,hv,fme=P(()=>{"use strict";SS=N(require("node:fs"),1),V9=N(require("node:path"),1),hv=class{static{i(this,"FileWatcher")}workspace;rules=[];watchers=[];pendingChanges=new Map;debounceMs=500;running=!1;constructor(e,n=500){this.workspace=e,this.debounceMs=n}watch(e,n){this.rules.push({patterns:e,callback:n})}start(){if(!this.running){this.running=!0;try{let e=SS.watch(this.workspace,{recursive:!0},(n,r)=>{!r||!this.running||r.startsWith(".git/")||r.includes("node_modules/")||this.onFileChange(r)});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 n=this.pendingChanges.get(e);n&&clearTimeout(n),this.pendingChanges.set(e,setTimeout(()=>{this.pendingChanges.delete(e),this.fireRules(e)},this.debounceMs))}fireRules(e){for(let n of this.rules)if(this.matchesAny(e,n.patterns))try{n.callback([e])}catch{}}matchesAny(e,n){for(let r of n)if(r==="**/*"||this.globMatch(e,r))return!0;return!1}globMatch(e,n){let r=n.replace(/\./g,"\\.").replace(/\*\*/g,"{{DOUBLESTAR}}").replace(/\*/g,"[^/]*").replace(/{{DOUBLESTAR}}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${r}$`).test(e)}watchDirectories(e,n=0){if(!(n>3))try{let r=SS.readdirSync(e,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith(".")||s.name==="node_modules")continue;let o=V9.join(e,s.name);try{let a=SS.watch(o,(l,c)=>{!c||!this.running||this.onFileChange(V9.join(s.name,c))});this.watchers.push(a),this.watchDirectories(o,n+1)}catch{}}}catch{}}}});var Ame={};ot(Ame,{TriggerEngine:()=>z9});var El,yS,hme,z9,_me=P(()=>{"use strict";El=N(require("node:fs"),1),yS=N(require("node:path"),1),hme=require("node:events");ks();Rt();Ys();gme();fme();z9=class extends hme.EventEmitter{static{i(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=yS.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new fv,this.fileWatcher=new hv(e.workspace),this.loadState()}loadTriggers(){let e=yS.join(this.opts.workspace,".monkeyscode","triggers.json");if(!El.existsSync(e))return this.triggers=[],[];try{let n=JSON.parse(El.readFileSync(e,"utf8"));return this.triggers=(n.triggers||[]).filter(r=>r.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:i(()=>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||["**/*"],n=>{this.fire(e,{type:"file.changed",payload:{files:n},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 n of this.triggers)this.matches(n,e)&&await this.fire(n,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 n=this.triggers.find(r=>r.name===e);return n?{matched:!0,prompt:n.prompt,model:n.model||"default"}:{matched:!1,prompt:"",model:""}}matches(e,n){if(e.event!==n.type)return!1;if(e.filter){for(let[r,s]of Object.entries(e.filter))if(n.payload[r]!==s)return!1}return!0}async fire(e,n){let r=this.state.get(e.name),s=(e.cooldownSeconds||300)*1e3;if(r&&Date.now()-r.lastFired<s){this.emit("cooldown",{trigger:e.name,remaining:s-(Date.now()-r.lastFired)});return}if(this.activeRuns.has(e.name))return;this.emit("firing",{trigger:e.name,event:n.type});let o=Et(),a=new ur({platformUrl:o.platformUrl,token:this.opts.token,model:e.model||o.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,permissionDecider:np(this.opts.workspace)});this.activeRuns.set(e.name,a);try{let l=[`[Trigger: ${e.name}]`,`Event: ${n.type}`,n.payload?`Payload: ${JSON.stringify(n.payload,null,2)}`:"","",e.prompt,"","Complete this task autonomously. Do not ask for user input."].filter(Boolean).join(`
1030
1030
  `);await a.run(l),this.updateState(e.name,"success"),this.emit("completed",{trigger:e.name})}catch(l){this.updateState(e.name,"failed"),this.emit("failed",{trigger:e.name,error:l instanceof Error?l.message:String(l)})}finally{this.activeRuns.delete(e.name)}}updateState(e,n){let r=this.state.get(e)||{name:e,lastFired:0,fireCount:0,lastResult:null};r.lastFired=Date.now(),r.fireCount++,r.lastResult=n,this.state.set(e,r),this.saveState()}saveState(){try{let e=yS.dirname(this.statePath);El.mkdirSync(e,{recursive:!0}),El.writeFileSync(this.statePath,JSON.stringify(Object.fromEntries(this.state),null,2))}catch{}}loadState(){try{if(El.existsSync(this.statePath)){let e=JSON.parse(El.readFileSync(this.statePath,"utf8"));this.state=new Map(Object.entries(e))}}catch{this.state=new Map}}}});var Sme={};ot(Sme,{GitHubWebhookServer:()=>J9});var Eme,Yh,J9,yme=P(()=>{"use strict";Eme=N(require("node:http"),1),Yh=N(require("node:crypto"),1),J9=class t{static{i(this,"GitHubWebhookServer")}server=null;opts;constructor(e){this.opts={port:9122,...e}}async start(){return new Promise((e,n)=>{this.server=Eme.createServer(async(r,s)=>{if(r.method!=="POST"||r.url!=="/webhook"){s.writeHead(404),s.end("Not Found");return}try{let o=await this.readBody(r),a=r.headers["x-github-event"],l=r.headers["x-hub-signature-256"],c=r.headers["x-github-delivery"]||Yh.randomUUID();if(this.opts.secret&&!this.validateSignature(o,l,this.opts.secret)){s.writeHead(401),s.end("Invalid signature");return}let u=JSON.parse(o),p={event:a||"unknown",payload:u,deliveryId:c};await this.opts.onEvent(p),s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({ok:!0,event:a,deliveryId:c}))}catch{s.writeHead(500),s.end("Internal Server Error")}}),this.server.listen(this.opts.port,()=>{e(this.opts.port)}),this.server.on("error",n)})}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,n){if(n){let r=`github.${e}.${n}`,s=`github.${e}`,o=t.eventMappings();return r in o?r:s}return`github.${e}`}readBody(e){return new Promise((n,r)=>{let s=[];e.on("data",o=>s.push(o)),e.on("end",()=>n(Buffer.concat(s).toString())),e.on("error",r)})}validateSignature(e,n,r){if(!n)return!1;let s="sha256="+Yh.createHmac("sha256",r).update(e).digest("hex");return Yh.timingSafeEqual(Buffer.from(n),Buffer.from(s))}}});var Z6e,hge=P(()=>{"use strict";Z6e=require("node:child_process")});var iHe,yge=P(()=>{"use strict";iHe=require("node:crypto")});function kHe(t){return/^[a-z][a-z0-9_]*$/.test(t)||t.startsWith("mcp__")}function Hge(t){let e=t.trim(),n=RHe[e];return n?{value:n,changes:[{from:e,to:n}],unmapped:[]}:kHe(e)||e==="*"?{value:e,changes:[],unmapped:[]}:{value:e,changes:[],unmapped:[e]}}function DHe(t){let e=t.trim();if(e.startsWith("/"))return{value:e,changes:[],unmapped:[]};let n=/^([A-Za-z_][\w-]*)(\((.*)\))?$/s.exec(e);if(!n)return{value:e,changes:[],unmapped:[e]};let r=Hge(n[1]),s=`${r.value}${n[2]??""}`;return{value:s,changes:s===e?[]:[{from:e,to:s}],unmapped:r.unmapped.length?[e]:[]}}function Yge(t){let e=Array.isArray(t)?t:lD(t),n={value:[],changes:[],unmapped:[]};for(let r of e.map(s=>s.trim()).filter(Boolean)){let s=DHe(r);n.value.push(s.value),n.changes.push(...s.changes),n.unmapped.push(...s.unmapped)}return n}function NHe(t){if(!t||t==="*")return{value:t,changes:[],unmapped:[]};if(!/^[A-Za-z_][\w]*(\|[A-Za-z_][\w]*)*$/.test(t))return{value:t,changes:[],unmapped:[]};let e=t.split("|").map(r=>Hge(r)),n=[...new Set(e.map(r=>r.value))].join("|");return{value:n,changes:n===t?[]:[{from:t,to:n}],unmapped:e.flatMap(r=>r.unmapped)}}function g$(t){if(!t||t==="inherit")return{value:t,changes:[],unmapped:[]};let e=di(t);return pi(t)?{value:e,changes:e===t?[]:[{from:t,to:e}],unmapped:[]}:{value:"inherit",changes:[{from:t,to:"inherit"}],unmapped:[`model ${t}`]}}function qge(t){let e={value:t,changes:[],unmapped:[]},n=/^(---\r?\n)([\s\S]*?)(\r?\n---\r?\n?)/.exec(t);if(!n)return e;let r=n[2].split(/\r?\n/);for(let s=0;s<r.length;s++){let o=/^(\s*)(tools|allowed-tools|allowed_tools|allowedTools|disallowed-tools|model)(\s*:\s*)(.*)$/.exec(r[s]);if(!o)continue;let[,a,l,c,u]=o;if(l==="model"){let _=g$(Wge(u.trim()));_.changes.length&&(r[s]=`${a}${l}${c}${_.value}`,e.changes.push(..._.changes)),e.unmapped.push(..._.unmapped);continue}let p=/^\[(.*)\]$/.exec(u.trim()),f=Yge(p?p[1]:u);if(!f.changes.length){e.unmapped.push(...f.unmapped);continue}let h=f.value.join(", ");r[s]=`${a}${l}${c}${p?`[${h}]`:h}`,e.changes.push(...f.changes),e.unmapped.push(...f.unmapped)}return e.value=n[1]+r.join(`
1031
1031
  `)+n[3]+t.slice(n[0].length),e}function Wge(t){return/^(['"]).*\1$/.test(t)?t.slice(1,-1):t}function jge(t){let e={value:{},changes:[],unmapped:[]};if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[n,r]of Object.entries(t))if((n==="allow"||n==="deny"||n==="ask")&&Array.isArray(r)){let s=Yge(r.map(String));e.value[n]=s.value,e.changes.push(...s.changes),e.unmapped.push(...s.unmapped)}else e.value[n]=r;return e}function Kge(t){let e={value:{},changes:[],unmapped:[]};if(!t||typeof t!="object"||Array.isArray(t))return e;for(let[n,r]of Object.entries(t)){if(!Array.isArray(r)){e.value[n]=r;continue}e.value[n]=r.map(s=>{if(!s||typeof s!="object")return s;let o=NHe(s.matcher);return e.changes.push(...o.changes),e.unmapped.push(...o.unmapped),o.value===void 0?s:{...s,matcher:o.value}})}return e}function Vge(t){let e={value:t,changes:[],unmapped:[]},n=/^(---\r?\n)([\s\S]*?)(\r?\n---\r?\n?)/.exec(t);if(!n)return e;let r=n[2].split(/\r?\n/).map(s=>{let o=/^globs\s*:\s*(.+)$/.exec(s.trim());if(!o||/^\[/.test(o[1].trim()))return s;let l=`globs: [${o[1].split(",").map(c=>Wge(c.trim())).filter(Boolean).map(c=>JSON.stringify(c)).join(", ")}]`;return e.changes.push({from:s.trim(),to:l}),l});return e.value=n[1]+r.join(`
1032
1032
  `)+n[3]+t.slice(n[0].length),e}var RHe,zge=P(()=>{"use strict";$o();nu();RHe={Bash:"run_command",Edit:"edit_file",MultiEdit:"edit_file",Write:"write_file",Read:"read_file",LS:"list_dir",Grep:"grep_search",Glob:"glob_files",WebFetch:"read_url",WebSearch:"web_search",TodoWrite:"todo_write",Task:"spawn_subagent",NotebookEdit:"edit_file",NotebookRead:"read_file"};i(kHe,"isNative");i(Hge,"translateToolName");i(DHe,"translateRule");i(Yge,"translateToolList");i(NHe,"translateMatcher");i(g$,"translateModel");i(qge,"translateFrontmatter");i(Wge,"unquote");i(jge,"translatePermissions");i(Kge,"translateHooks");i(Vge,"translateCursorRule")});var nfe={};ot(nfe,{importClaude:()=>Xge,importCommand:()=>PHe,importCursor:()=>efe,renderImportReport:()=>tfe});function f$(t){try{let e=JSON.parse(Fl(sr.readFileSync(t,"utf8")));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Jge(t){let e=[],n=i(r=>{let s;try{s=sr.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of s.sort((a,l)=>a.name.localeCompare(l.name))){let a=Zt.join(r,o.name);o.isDirectory()?n(a):o.isFile()&&e.push(a)}},"walk");return n(t),e}function OHe(t){let e=new Set;return t.filter(n=>{let r=`${n.from}\0${n.to}`;return e.has(r)?!1:(e.add(r),!0)})}function Xge(t){let e=new Iv(t),n=e.ws,r=e.userScope?Zt.join(t.home??h$.homedir(),".claude"):Zt.join(n,".claude");for(let o of xHe){let a=Zt.join(r,o);for(let l of Jge(a)){let c=Zt.relative(a,l),u=`${e.display(r)}/${o}/${c.split(Zt.sep).join("/")}`,p=Zt.join(e.targetRoot,o,c);if(/\.md$/i.test(l)){let f=qge(sr.readFileSync(l,"utf8")),h=f.changes.length||!t.link?f.value:void 0;e.put(u,p,h,l)&&e.record(u,e.display(p),f)}else e.put(u,p,void 0,l)&&e.record(u,e.display(p),void 0)}}let s=e.userScope?[Zt.join(r,"settings.json")]:[Zt.join(r,"settings.json"),Zt.join(r,"settings.local.json")];for(let o of s){let a=f$(o);if(!a)continue;let l=o.endsWith("settings.local.json"),c=e.userScope?"user":l?"local":"project",u=e.display(o);for(let[p,f]of Object.entries(a)){let h=`${u} ${p}`;switch(p){case"permissions":{let _=jge(f);e.setting("permissions",_.value,h,_,c);break}case"hooks":{let _=Kge(f);e.setting("hooks",_.value,h,_,c),e.userScope||e.report.notes.push("Imported hooks are repository config: you will be asked to trust them on the next `mc` start.");break}case"statusLine":case"outputStyle":e.setting(p,f,h,void 0,c);break;case"model":{let _=g$(typeof f=="string"?f:void 0);_.value&&_.value!=="inherit"?e.setting("model",_.value,h,_,c):e.notMapped(h,`unknown model "${String(f)}"`);break}case"mcpServers":{BHe(e,f,h,c);break}case"env":c==="user"?e.setting("env",f,h,void 0,"user"):e.notMapped(h,"env can only be set in user settings \u2014 re-run with --scope user");break;case"enabledPlugins":{let _=f&&typeof f=="object"?Object.entries(f).filter(([,E])=>E).map(([E])=>E):[];e.notMapped(h,`plugins are never installed automatically \u2014 install each with \`mc plugin install <git-url>\`${_.length?`: ${_.join(", ")}`:""}`);break}default:e.notMapped(h,MHe[p]??"no MonkeysCode equivalent")}}}e.userScope||Zge(e,Zt.join(n,".mcp.json"));for(let o of["CLAUDE.md",Zt.join(".claude","CLAUDE.md")])sr.existsSync(Zt.join(n,o))&&e.record(o,`${o} (read as-is)`,void 0);return e.finish()}function BHe(t,e,n,r){if(!e||typeof e!="object"){t.notMapped(n,"expected an object");return}for(let[s,o]of Object.entries(e)){let a=bp(o);if("error"in a){t.notMapped(`${n}.${s}`,a.error);continue}t.setting(`mcpServers.${s}`,a.entry,`${n}.${s}`,void 0,r)}}function Zge(t,e){let n=f$(e);if(!n)return;let r=n.mcpServers??n.servers;if(!r||typeof r!="object")return;let s=Zt.join(t.ws,".monkeyscode","mcp.json"),o=f$(s)??{},a={...o.mcpServers??{}},l=t.display(e),c=!1;for(let[u,p]of Object.entries(r)){let f=`${l} ${u}`,h=bp(p);if("error"in h){t.notMapped(f,h.error);continue}if(a[u]&&!t.o.force){t.report.skipped.push({source:f,target:".monkeyscode/mcp.json",reason:"already configured"});continue}a[u]=h.entry,c=!0,t.record(f,".monkeyscode/mcp.json",void 0)}c&&!t.o.dryRun&&(sr.mkdirSync(Zt.dirname(s),{recursive:!0}),sr.writeFileSync(s,JSON.stringify({...o,mcpServers:a},null,2)+`
@@ -1205,11 +1205,11 @@ ${n}
1205
1205
  `));for(let s of r){console.log(g.bold(` \u2500\u2500 ${s.label} (${s.count}) \u2500\u2500`));let o=e.getByCategory(s.category);for(let a of o){let l=a.official?g.green(" \u2713"):"",c=a.install.envVars?.length?g.dim(` (needs ${a.install.envVars[0]})`):"";console.log(` ${a.icon} ${g.bold(a.name)}${l}${c} \u2014 ${g.dim(a.description)}`)}console.log()}console.log(g.dim(` Add a server: ${g.cyan("mc mcp add <id>")}`)),console.log(g.dim(` Search: ${g.cyan("mc mcp browse <query>")}
1206
1206
  `))}}i(ype,"mcpBrowseCommand");$t();xw();lw();He();var Ipe=N(require("node:path"),1),O9=N(require("node:fs"),1);vn();co();var hl=N(require("node:fs"),1),Uh=N(require("node:path"),1);vn();var DGe=".settings-migrated-v2";function ov(t){try{let e=JSON.parse(Fl(hl.readFileSync(t,"utf8")));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}i(ov,"readRaw");function NGe(t){let e={},n=[],r=ov(t.config);if(r){n.push(t.config);let l=Ll(r);delete l.version,Object.assign(e,l)}let s=ov(t.permissions);if(s){n.push(t.permissions);let l=Hy(s).permissions??{},c=e.permissions??{};e.permissions={...c,allow:x9([...c.allow??[],...l.allow??[]]),deny:x9([...c.deny??[],...l.deny??[]]),...!c.defaultMode&&l.defaultMode?{defaultMode:l.defaultMode}:{}}}let o=ov(t.mcp),a=o?Yy(o):{};return a.mcpServers&&(n.push(t.mcp),e.mcpServers=a.mcpServers),{merged:e,sources:n}}i(NGe,"mergeLegacy");function xGe(t,e){let n={...t},r=[];for(let[s,o]of Object.entries(e))if(o!==void 0)if(s==="permissions"||s==="mcpServers"){let a=n[s]??{},l={...a};for(let[c,u]of Object.entries(o))if(Array.isArray(u)){let p=x9([...N9(a[c]),...N9(u)]);p.length!==N9(a[c]).length&&(l[c]=p,r.push(`${s}.${c}`))}else l[c]===void 0&&(l[c]=u,r.push(`${s}.${c}`));n[s]=l}else n[s]===void 0&&(n[s]=o,r.push(s));return{out:n,keys:r}}i(xGe,"underlay");function Cpe(t,e,n){let{merged:r,sources:s}=NGe(e);if(s.length===0)return{target:t,sources:s,keys:[],skipped:"no legacy files"};let o=ov(t)??{},{out:a,keys:l}=xGe(o,r);return l.length>0&&!n&&(hl.mkdirSync(Uh.dirname(t),{recursive:!0}),hl.writeFileSync(t,JSON.stringify(a,null,2)+`
1207
1207
  `)),{target:t,sources:s,keys:l}}i(Cpe,"migrateScope");function bpe(t=ar()){let e=Uh.join(t,DGe);if(hl.existsSync(e))return null;let n=Xc(process.cwd(),t),r=null;try{r=Cpe(n.user,{config:n.legacy.userConfig,permissions:n.legacy.userPermissions,mcp:n.legacy.userMcp},!1),hl.mkdirSync(t,{recursive:!0}),hl.writeFileSync(e,new Date().toISOString()+`
1208
- `)}catch{}return r}i(bpe,"migrateUserSettingsOnce");function Tpe(t,e={}){let n=Xc(Uh.resolve(t));return Cpe(n.project,{config:n.legacy.projectConfig,permissions:n.legacy.projectPermissions,mcp:n.legacy.projectMcp},e.dryRun??!1)}i(Tpe,"migrateProjectSettings");function N9(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}i(N9,"strs");function x9(t){return[...new Set(t)]}i(x9,"dedupe");Hs();var OGe=/(key|token|secret|password)$/i;function M9(t){switch(t){case"defaultModel":return"model";case"thinkingMode":return"effort";case"defaultMode":case"mode":case"permissionMode":return"permissions.defaultMode";case"allowedTools":return"permissions.allow";case"deniedTools":return"permissions.deny";default:return t}}i(M9,"normalizeKey");function MGe(t,e){switch(t){case"permissions.defaultMode":{let n=Lo(e);return n?[n,null]:[e,`must be one of: ${wk.join(", ")}`]}case"effort":{let n=vs(e);return n?[n,null]:[e,`must be one of: ${xd.join(", ")}`]}case"permissions.allow":case"permissions.deny":case"permissions.ask":case"permissions.additionalDirectories":return typeof e=="string"?[e.split(",").map(n=>n.trim()).filter(Boolean),null]:Array.isArray(e)?[e,null]:[e,"must be a list"];case"maxTurns":case"maxCostPerSession":case"headlessTimeout":return typeof e=="number"&&e>=0?[e,null]:[e,"must be a non-negative number"];case"webEnabled":case"autoApprove":case"telemetry":case"verbose":return typeof e=="boolean"?[e,null]:[e,"must be true or false"];default:return[e,null]}}i(MGe,"validateSetting");function B9(t,e){return OGe.test(t)&&typeof e=="string"&&e?"\u2022\u2022\u2022\u2022"+e.slice(-4):e&&typeof e=="object"?JSON.stringify(t==="providerKeys"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r&&"\u2022\u2022\u2022\u2022"])):e):String(e)}i(B9,"display");function wpe(t,e="",n=[]){for(let[r,s]of Object.entries(t)){let o=e?`${e}.${r}`:r;if(s&&typeof s=="object"&&!Array.isArray(s)&&o!=="hooks"&&o!=="statusLine"&&!e.startsWith("mcpServers")&&r!=="providerKeys"){if(Object.keys(s).length===0)continue;wpe(s,o,n)}else{if(Array.isArray(s)&&s.length===0)continue;n.push([o,s])}}return n}i(wpe,"flatten");function vpe(t){let e=ft({workspace:t.workspace}),n=wpe(e.value).sort(([s],[o])=>s.localeCompare(o));if(t.json){let s={};for(let[o,a]of n)s[o]=t.showOrigin?{value:a,origin:(e.origins.get(o)??[{source:"default"}]).map(l=>Pa(l.source,l.file))}:a;console.log(JSON.stringify(s,null,2));return}console.log("");let r=Math.min(34,Math.max(...n.map(([s])=>s.length))+2);for(let[s,o]of n){let a=t.showOrigin?" "+g.dim(`(${(e.origins.get(s)??[{source:"default"}]).map(l=>Pa(l.source,l.file)).join(" + ")})`):"";console.log(` ${g.bold(s.padEnd(r))} ${B9(s,o)}${a}`)}for(let s of e.warnings)console.log(g.yellow(` \u26A0 ${s}`));console.log("")}i(vpe,"configListCommand");function Rpe(t,e){let n=M9(t),r=ft({workspace:e.workspace}),s=lg(r.value,n);if(s===void 0){console.error(` ${n} is not set`),process.exitCode=1;return}let o=e.showOrigin?` (${(r.origins.get(n)??[{source:"default"}]).map(a=>Pa(a.source,a.file)).join(" + ")})`:"";console.log(`${B9(n,s)}${o}`)}i(Rpe,"configGetCommand");function kpe(t,e,n){let r=Ope(n),s=M9(t),[o,a]=MGe(s,Dk(e));a&&(console.error(` \u26A0\uFE0F ${s} ${a}`),process.exit(1));let l=lr(r,s,o,{workspace:n.workspace});l&&(console.error(` \u26A0\uFE0F ${l}`),process.exit(1)),console.log(` Set ${s} = ${B9(s,o)} ${g.dim(`(${r}: ${iv(Fo(r,{workspace:n.workspace}))})`)}`)}i(kpe,"configSetCommand");function Dpe(t,e){let n=Ope(e),r=M9(t),s=eu(n,r,{workspace:e.workspace});console.log(s?` Removed ${r} from ${n} settings.`:` ${r} was not set in ${n} settings.`)}i(Dpe,"configUnsetCommand");function Npe(t){let e=Xc(t.workspace,ar()),n=i((s,o)=>{let a=O9.existsSync(o);console.log(` ${s.padEnd(10)} ${a?o:g.dim(o+" (not found)")}`)},"row");console.log("");for(let s of MA())n("Managed",s);n("Local",e.local),n("Project",e.project),n("User",e.user);let r=Object.values(e.legacy).filter(s=>O9.existsSync(s));if(r.length>0){console.log(""),console.log(g.dim(" Legacy (still read; run `mc config migrate` to fold into settings.json):"));for(let s of r)console.log(g.dim(` ${s}`))}console.log("")}i(Npe,"configPathCommand");function xpe(t){let e=Tpe(t.workspace,{dryRun:t.dryRun});if(e.skipped){console.log(` Nothing to migrate (${e.skipped}).`);return}if(e.keys.length===0){console.log(` ${iv(e.target)} already contains everything from the legacy files.`);return}console.log(` ${t.dryRun?"Would migrate":"Migrated"} into ${iv(e.target)}:`);for(let n of e.keys)console.log(` + ${n}`);console.log(g.dim(` From: ${e.sources.map(iv).join(", ")}`)),t.dryRun||console.log(g.dim(" The legacy files were left in place; delete them once you have reviewed the result."))}i(xpe,"configMigrateCommand");function Ope(t){if(t.project)return"project";let e=t.scope??"user";if(e==="global")return"user";if(e==="user"||e==="project"||e==="local")return e;console.error(" \u26A0\uFE0F --scope must be user, project or local"),process.exit(1)}i(Ope,"resolveScope");function iv(t){let e=process.env.HOME||process.env.USERPROFILE;return e&&t.startsWith(e)?"~"+t.slice(e.length):Ipe.normalize(t)}i(iv,"tilde");Rt();co();Hs();vn();Ys();YA();$o();He();wr();$o();Fpe();function F9(t){let e=st().ansi,n=st().emoji;Bpe("Available Models"),fS();let r=[{header:"Model",width:24},{header:"Provider",width:12},{header:"Context",width:10,align:"right"},{header:"Speed",width:10},{header:"In / Out",width:16},{header:"Features",width:14}],s=Qa.map(o=>{let a=y4(o.id,t),l=!a.allowed,u={monkeyscode:e?ls.accent("MonkeysCode"):"MonkeysCode",anthropic:e?g.hex("#D97757")("Anthropic"):"Anthropic",google:e?g.hex("#4285F4")("Google"):"Google",openai:e?g.hex("#74AA9C")("OpenAI"):"OpenAI"}[o.provider]||o.provider,p=o.speed==="fast"?n?"\u26A1 Fast":"Fast":n?"\u{1F9E0} Deep":"Deep",f=o.costInputPerM===0?e?ls.success("Free"):"Free":`${L9(o.costInputPerM)} / ${L9(o.costOutputPerM)}`,h=[];o.thinking&&h.push(n?"\u{1F4AD} Think":"Think"),l&&h.push(e?ls.warning(`\u{1F512} ${a.requiredPlan}+`):`[${a.requiredPlan}+]`);let _=h.join(" ");return{cells:[e?l?ls.dim(o.displayName):g.bold(o.displayName):o.displayName,u,Lpe(o.contextWindow),p,f,_],dim:l}});if(Ppe(r,s),fS(),e){console.log(` ${ls.dim("Aliases:")}`);for(let o of Qa)if(o.aliases.length>0){let a=o.aliases.map(l=>ls.accent(l)).join(ls.dim(", "));console.log(` ${ls.dim(" "+o.displayName+":")} ${a}`)}}else{console.log(" Aliases:");for(let o of Qa)o.aliases.length>0&&console.log(` ${o.displayName}: ${o.aliases.join(", ")}`)}fS(),P9("Use --model <name|alias> to select a model"),P9("Use --model auto for smart routing based on task complexity"),fS()}i(F9,"printModelList");var $pe=N(require("node:path"),1);He();wr();sn();Ef();cE();C_();var LGe=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Upe(){let t=st(),e=_t(t),n=t.ansi,r=On();if(!r){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let s=null;try{let u=await Fr();if(u){let p=await fetch(`${LGe}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${u}`}});p.ok&&(s=await p.json())}}catch{}if(!s){let u=new Date;s={period:`${u.toLocaleString("default",{month:"long"})} ${u.getFullYear()}`,plan:r.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let o=s.period,a=s.plan.charAt(0).toUpperCase()+s.plan.slice(1);console.log(n?g.bold(` \u{1F4CA} Monthly Usage (${o})`):` Monthly Usage (${o})`),console.log(n?g.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${a}`),console.log(` Sessions: ${s.sessionsCount}`);let l=Sm(s.tokensIn),c=Sm(s.tokensOut);if(console.log(` Tokens: ${l} input, ${c} output`),s.tokensThinking>0&&console.log(` Thinking: ${Sm(s.tokensThinking)}`),s.costLimit>0){let u=Math.round(s.totalCost/s.costLimit*100),p=u>=80?n?g.red(`$${s.totalCost.toFixed(2)} / $${s.costLimit.toFixed(2)} (${u}%)`):`$${s.totalCost.toFixed(2)} / $${s.costLimit.toFixed(2)} (${u}%)`:`$${s.totalCost.toFixed(2)} / $${s.costLimit.toFixed(2)} (${u}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${s.totalCost.toFixed(2)}`);if(s.byModel.length>0){console.log(" By model:");for(let u of s.byModel)console.log(` ${u.model.padEnd(18)} $${u.cost.toFixed(2)} (${u.sessions} sessions)`)}console.log(n?g.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),s.sessionsCount===0&&s.totalCost===0&&console.log(n?g.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}i(Upe,"usageCommand");function Qpe(t,e={}){let n=e.log??(u=>console.log(u)),r=e.store??new gs,s=r.list(Number.MAX_SAFE_INTEGER),o;if(!t||t==="last"){let u=$pe.resolve(e.workspace??".");o=(s.find(p=>p.workspace===u)??s[0])?.id}else o=s.find(u=>u.id===t)?.id??s.find(u=>u.id.startsWith(t))?.id;let a=o?r.transcripts.read(o):void 0;if(!o||!a)return n(` No session matches "${t||"last"}".`),1;let l=yM(a),c=ub(l);if(e.json)return n(JSON.stringify({session_id:o,...c},null,2)),0;for(let u of FGe(o,c))n(u);return 0}i(Qpe,"sessionUsageCommand");function FGe(t,e){let n=["",` Session ${t.slice(0,8)} \u2014 ${e.requests} request${e.requests===1?"":"s"}${e.models.length?` (${e.models.join(", ")})`:""}`];if(e.requests===0)return n.push(" No per-request records in this session (it predates them, or no request finished).",""),n;let r=i(s=>s===null?"n/a":`${(s*100).toFixed(1)}%`,"pct");if(n.push(` Input: ${Sm(e.promptTokens)} tokens over ${e.withPromptTokens} reported request${e.withPromptTokens===1?"":"s"}`),n.push(` Cached share: ${r(e.cachedShare)}${e.cachedShare===null?" (the endpoint did not report cached tokens)":""}`),n.push(` Cache writes: ${r(e.cacheWriteRatio)}${e.cacheWriteRatio===null?" (not reported by this provider)":` of input (n=${e.withCacheWrites})`}`),n.push(` Output: ${Sm(e.completionTokens)} tokens`),e.compactions&&n.push(` Compactions: ${e.compactions}`),e.largestToolResults.length){n.push(" Largest tool results:");for(let s of e.largestToolResults)n.push(` ${s.name.padEnd(20)} ${Sm(s.chars).padStart(6)} chars (~${Sm(Math.round(s.chars/4))} tokens, before request ${s.request})`)}return n.push(""),n}i(FGe,"formatSessionReport");function Sm(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:String(t)}i(Sm,"formatTokenCount");var ya=N(require("node:fs"),1),jpe=N(require("node:path"),1),ym=require("node:child_process");He();var Qh=N(require("node:fs"),1),av=N(require("node:path"),1);$t();var $Ge="https://monkeyscode.com/api/latest-version",UGe="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",QGe=4*60*60*1e3;function Ype(){let t=Ze();return av.join(t.config,"update-check")}i(Ype,"getCachePath");function GGe(){try{let t=Qh.readFileSync(Ype(),"utf8");return JSON.parse(t)}catch{return null}}i(GGe,"readCache");function $9(t){try{let e=Ype();Qh.mkdirSync(av.dirname(e),{recursive:!0}),Qh.writeFileSync(e,JSON.stringify(t))}catch{}}i($9,"writeCache");function Gpe(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){if((n[s]||0)>(r[s]||0))return!0;if((n[s]||0)<(r[s]||0))return!1}return!1}i(Gpe,"isNewerVersion");function HGe(){let t=process.platform,e=process.arch;return`cli-${t}-${e}`}i(HGe,"getAssetKey");async function U9(t,e=!1){if(!e){let n=GGe();if(n&&Date.now()-n.lastCheck<QGe)return n.latestVersion&&Gpe(n.latestVersion,t)?{version:n.latestVersion,currentVersion:t,downloadUrl:n.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let n=await Hpe($Ge);if(n||(n=await Hpe(UGe)),!n)return $9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let r=n.productVersion||n.version,s=HGe(),o=n.assets?.[s],a=o?.url||"https://monkeyscode.com/download";return $9({lastCheck:Date.now(),latestVersion:r,downloadUrl:a}),r&&Gpe(r,t)?{version:r,currentVersion:t,downloadUrl:a,sha256:o?.sha256,size:o?.size,publishedAt:n.date||"",commit:n.commit||"",quality:n.quality||"stable"}:null}catch{return $9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}i(U9,"checkForUpdate");async function Hpe(t){try{let e=await fetch(t,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}i(Hpe,"fetchManifest");function Q9(){let t=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":t.includes("/opt/homebrew/")||t.includes("/usr/local/Cellar/")?"homebrew":t.includes("\\scoop\\")?"scoop":t.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(t.includes("\\WindowsApps\\")||t.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}i(Q9,"detectInstallMethod");async function Kpe(t){let n=(await Promise.resolve().then(()=>(Wpe(),qpe)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"1.0.1";if(t.rollback){await e6e(n);return}if(t.check){await WGe(n);return}await jGe(n,t.version)}i(Kpe,"updateCommand");async function WGe(t){console.log(g.dim(` Current version: v${t}`)),console.log(g.dim(" Checking for updates...")),console.log("");let e=await U9(t,!0);e?(console.log(g.green(` \u2705 Update available: v${t} \u2192 v${e.version}`)),console.log(g.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(g.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${g.bold("mc update")} to install.`)):console.log(g.green(` \u2705 You're on the latest version (v${t})`)),console.log("")}i(WGe,"checkOnly");async function jGe(t,e){let n=Q9();console.log(""),console.log(g.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(g.dim(` Current: v${t} \xB7 Method: ${n}`)),console.log(""),e&&console.log(g.dim(` Target version: v${e}`));try{switch(n){case"npm":await KGe(e);break;case"homebrew":await VGe();break;case"winget":await zGe();break;case"chocolatey":await JGe();break;case"scoop":await XGe();break;case"binary":await ZGe(t,e);break;default:console.log(g.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${g.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${g.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${g.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(r){console.error(g.red(` \u274C Update failed: ${r instanceof Error?r.message:String(r)}`)),console.log(g.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}i(jGe,"performUpdate");async function KGe(t){if(t&&!/^[0-9A-Za-z.+-]+$/.test(t))throw new Error(`Invalid version: ${t}`);let e=t?`@monkeyscode/cli@${t}`:"@monkeyscode/cli";console.log(g.dim(` Running: npm install -g ${e}`)),(0,ym.execFileSync)(process.platform==="win32"?"npm.cmd":"npm",["install","-g",e],{stdio:"inherit",shell:process.platform==="win32"}),console.log(g.green(" \u2705 Updated via npm"))}i(KGe,"updateViaNpm");async function VGe(){console.log(g.dim(" Running: brew upgrade monkeyscode")),(0,ym.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Homebrew"))}i(VGe,"updateViaHomebrew");async function zGe(){console.log(g.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,ym.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via winget"))}i(zGe,"updateViaWinget");async function JGe(){console.log(g.dim(" Running: choco upgrade monkeyscode-cli")),(0,ym.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Chocolatey"))}i(JGe,"updateViaChocolatey");async function XGe(){console.log(g.dim(" Running: scoop update monkeyscode")),(0,ym.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Scoop"))}i(XGe,"updateViaScoop");async function ZGe(t,e){let n=await U9(t,!0);if(!n&&!e){console.log(g.green(` \u2705 Already on latest version (v${t})`));return}let r=n?.downloadUrl;if(!r)throw new Error("Could not determine download URL");console.log(g.dim(` Downloading from: ${r}`));let s=process.execPath,o=s+".backup";try{ya.copyFileSync(s,o),console.log(g.dim(` Backed up current binary to: ${jpe.basename(o)}`))}catch{console.log(g.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let a=await fetch(r,{signal:AbortSignal.timeout(6e4)});if(!a.ok)throw new Error(`Download failed: HTTP ${a.status}`);let l=Buffer.from(await a.arrayBuffer());if(n?.sha256){let u=(await import("node:crypto")).createHash("sha256").update(l).digest("hex");if(u!==n.sha256)throw new Error(`Checksum mismatch (expected ${n.sha256}, got ${u})`);console.log(g.dim(" \u2705 Checksum verified"))}try{ya.writeFileSync(s,l),ya.chmodSync(s,493),console.log(g.green(` \u2705 Updated to v${n?.version||e}`))}catch(c){try{ya.copyFileSync(o,s),console.log(g.yellow(" Restored backup after failed update"))}catch{}throw c}}i(ZGe,"updateViaBinaryDownload");async function e6e(t){if(console.log(""),console.log(g.bold(" \u23EA Rollback")),console.log(""),Q9()==="binary"){let n=process.execPath+".backup";if(!ya.existsSync(n)){console.log(g.red(" \u274C No backup found. Cannot rollback.")),console.log(g.dim(" Rollback is only available after a binary update."));return}try{ya.copyFileSync(n,process.execPath),ya.chmodSync(process.execPath,493),console.log(g.green(" \u2705 Rolled back to previous version")),console.log(g.dim(" Restart the CLI to use the previous version."))}catch(r){console.error(g.red(` \u274C Rollback failed: ${r instanceof Error?r.message:String(r)}`))}}else console.log(g.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${g.dim(`mc update --version ${t}`)}`);console.log("")}i(e6e,"rollback");He();var Gh=N(require("node:fs"),1),cv=N(require("node:path"),1),Jpe=N(require("node:crypto"),1);$t();var Nc=!0,G9="",Bi=[],Vpe=!1,t6e="https://monkeyscode.com/api/telemetry",lv=50,n6e=6e4;function Xpe(){let t=Ze();return cv.join(t.config,"telemetry.json")}i(Xpe,"getConfigPath");function H9(){try{let t=Gh.readFileSync(Xpe(),"utf8");return JSON.parse(t)}catch{let t={enabled:!0,clientId:r6e()};return Y9(t),t}}i(H9,"loadConfig");function Y9(t){try{let e=Xpe();Gh.mkdirSync(cv.dirname(e),{recursive:!0}),Gh.writeFileSync(e,JSON.stringify(t,null,2))}catch{}}i(Y9,"saveConfig");function r6e(){return Jpe.randomUUID()}i(r6e,"generateClientId");function Zpe(){if(Vpe)return;if(Vpe=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Nc=!1;return}let t=H9();Nc=t.enabled,G9=t.clientId,Nc&&(setInterval(()=>zpe(),n6e).unref(),process.on("beforeExit",()=>zpe()))}i(Zpe,"initTelemetry");function eme(){return Nc}i(eme,"isTelemetryEnabled");function tme(){Nc=!0;let t=H9();t.enabled=!0,Y9(t)}i(tme,"enableTelemetry");function nme(){Nc=!1,Bi=[];let t=H9();t.enabled=!1,Y9(t)}i(nme,"disableTelemetry");function q9(t,e={}){Nc&&(Bi.push({name:t,properties:e,timestamp:new Date().toISOString()}),Bi.length>lv&&(Bi=Bi.slice(-lv)))}i(q9,"trackEvent");async function zpe(){if(!Nc||Bi.length===0)return;let t=[...Bi];Bi=[];let e=ws(),r={clientId:G9,cliVersion:"1.0.1",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:t};try{await fetch(t6e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)})}catch{Bi.unshift(...t),Bi.length>lv&&(Bi=Bi.slice(-lv))}}i(zpe,"flushEvents");function rme(){let t=ws();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 1.0.1",` \u2022 OS: ${t.os} (${t.arch})`,` \u2022 Shell: ${t.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: ${Nc?"ENABLED":"DISABLED"}`,`Client ID: ${G9||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
1209
- `)}i(rme,"getCollectedDataSummary");async function sme(t){switch(t){case"enable":tme(),console.log(""),console.log(g.green(" \u2705 Telemetry enabled")),console.log(g.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":nme(),console.log(""),console.log(g.yellow(" \u26A0\uFE0F Telemetry disabled")),console.log(g.dim(" No data will be collected.")),console.log("");break;case"show":console.log(""),console.log(rme()),console.log("");break;case"status":default:console.log(""),process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"?console.log(g.yellow(" \u26A0\uFE0F Telemetry: DISABLED (DO_NOT_TRACK env var is set)")):eme()?console.log(g.green(" \u2705 Telemetry: ENABLED")):console.log(g.dim(" \u2B55 Telemetry: DISABLED")),console.log(""),console.log(g.dim(" Commands:")),console.log(g.dim(" mc telemetry enable \u2014 enable anonymous usage data")),console.log(g.dim(" mc telemetry disable \u2014 disable all telemetry")),console.log(g.dim(" mc telemetry show \u2014 see what data is collected")),console.log("");break}}i(sme,"telemetryCommand");var Al=N(require("node:fs"),1),hS=N(require("node:path"),1);He();$t();async function ome(t,e){let n=ws(),r="1.0.1";console.log(""),console.log(g.bold(" \u{1F41B} Bug Report")),console.log("");let s={description:t||"(no description provided)",cliVersion:r,nodeVersion:process.version,os:`${n.os} (${n.arch})`,arch:n.arch,shell:n.shell,timestamp:new Date().toISOString()};if(e?.attachCrash){let a=i6e();a?(s.crashLog=a,console.log(g.dim(" \u{1F4CE} Attached latest crash report"))):console.log(g.dim(" No crash reports found"))}if(await s6e(s))console.log(g.green(" \u2705 Bug report submitted")),console.log(g.dim(" Thank you! Our team will review your report."));else{let a=o6e(s);console.log(g.yellow(" \u26A0\uFE0F Could not submit online (saved locally)")),console.log(g.dim(` Report: ${a}`)),console.log(g.dim(" Submit later: mc bug --submit-local"))}console.log("")}i(ome,"bugCommand");async function s6e(t){try{return(await fetch("https://monkeyscode.com/api/bug-reports",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)})).ok}catch{return!1}}i(s6e,"submitReport");function o6e(t){let e=Ze(),n=hS.join(e.config,"bug-reports");Al.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=hS.join(n,`${r}.json`);return Al.writeFileSync(s,JSON.stringify(t,null,2)),s}i(o6e,"saveReportLocally");function i6e(){try{let t=Ze(),e=hS.join(t.config,"crashes");if(!Al.existsSync(e))return null;let n=Al.readdirSync(e).filter(r=>r.endsWith(".log")).sort().reverse();return n.length===0?null:Al.readFileSync(hS.join(e,n[0]),"utf8")}catch{return null}}i(i6e,"getLatestCrashLog");var Cm=N(require("node:fs"),1),W9=N(require("node:path"),1);He();$t();wr();function ime(){let t=Ze(),e=W9.join(t.config,"config.json");return!Cm.existsSync(e)}i(ime,"isFirstRun");function a6e(){let e=Ze().config,n=W9.join(e,"config.json");Cm.mkdirSync(e,{recursive:!0}),Cm.existsSync(n)||Cm.writeFileSync(n,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}i(a6e,"markOnboardingComplete");async function ame(){let t=st(),e=ws();console.log(""),console.log(g.bold(" \u{1F435} Welcome to MonkeysCode!")),console.log(g.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(g.dim(` Platform: ${e.os} (${e.arch}) \xB7 Shell: ${e.shell}`)),console.log(""),console.log(g.bold(" \u{1FA7A} Quick Setup Check")),console.log("");let n=[],r=parseInt(process.version.slice(1).split(".")[0],10);n.push({name:"Node.js",ok:r>=20,msg:r>=20?process.version:`${process.version} (requires >= 20)`});try{let{execSync:s}=await import("node:child_process"),o=s("git --version",{encoding:"utf8"}).trim();n.push({name:"Git",ok:!0,msg:o.replace("git version ","")})}catch{n.push({name:"Git",ok:!1,msg:"not found"})}try{let{execSync:s}=await import("node:child_process"),o=s("rg --version",{encoding:"utf8"}).split(`
1208
+ `)}catch{}return r}i(bpe,"migrateUserSettingsOnce");function Tpe(t,e={}){let n=Xc(Uh.resolve(t));return Cpe(n.project,{config:n.legacy.projectConfig,permissions:n.legacy.projectPermissions,mcp:n.legacy.projectMcp},e.dryRun??!1)}i(Tpe,"migrateProjectSettings");function N9(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}i(N9,"strs");function x9(t){return[...new Set(t)]}i(x9,"dedupe");Hs();var OGe=/(key|token|secret|password)$/i;function M9(t){switch(t){case"defaultModel":return"model";case"thinkingMode":return"effort";case"defaultMode":case"mode":case"permissionMode":return"permissions.defaultMode";case"allowedTools":return"permissions.allow";case"deniedTools":return"permissions.deny";default:return t}}i(M9,"normalizeKey");function MGe(t,e){switch(t){case"permissions.defaultMode":{let n=Lo(e);return n?[n,null]:[e,`must be one of: ${wk.join(", ")}`]}case"effort":{let n=vs(e);return n?[n,null]:[e,`must be one of: ${xd.join(", ")}`]}case"permissions.allow":case"permissions.deny":case"permissions.ask":case"permissions.additionalDirectories":return typeof e=="string"?[e.split(",").map(n=>n.trim()).filter(Boolean),null]:Array.isArray(e)?[e,null]:[e,"must be a list"];case"maxTurns":case"maxCostPerSession":case"headlessTimeout":return typeof e=="number"&&e>=0?[e,null]:[e,"must be a non-negative number"];case"webEnabled":case"autoApprove":case"telemetry":case"verbose":return typeof e=="boolean"?[e,null]:[e,"must be true or false"];default:return[e,null]}}i(MGe,"validateSetting");function B9(t,e){return OGe.test(t)&&typeof e=="string"&&e?"\u2022\u2022\u2022\u2022"+e.slice(-4):e&&typeof e=="object"?JSON.stringify(t==="providerKeys"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r&&"\u2022\u2022\u2022\u2022"])):e):String(e)}i(B9,"display");function wpe(t,e="",n=[]){for(let[r,s]of Object.entries(t)){let o=e?`${e}.${r}`:r;if(s&&typeof s=="object"&&!Array.isArray(s)&&o!=="hooks"&&o!=="statusLine"&&!e.startsWith("mcpServers")&&r!=="providerKeys"){if(Object.keys(s).length===0)continue;wpe(s,o,n)}else{if(Array.isArray(s)&&s.length===0)continue;n.push([o,s])}}return n}i(wpe,"flatten");function vpe(t){let e=ft({workspace:t.workspace}),n=wpe(e.value).sort(([s],[o])=>s.localeCompare(o));if(t.json){let s={};for(let[o,a]of n)s[o]=t.showOrigin?{value:a,origin:(e.origins.get(o)??[{source:"default"}]).map(l=>Pa(l.source,l.file))}:a;console.log(JSON.stringify(s,null,2));return}console.log("");let r=Math.min(34,Math.max(...n.map(([s])=>s.length))+2);for(let[s,o]of n){let a=t.showOrigin?" "+g.dim(`(${(e.origins.get(s)??[{source:"default"}]).map(l=>Pa(l.source,l.file)).join(" + ")})`):"";console.log(` ${g.bold(s.padEnd(r))} ${B9(s,o)}${a}`)}for(let s of e.warnings)console.log(g.yellow(` \u26A0 ${s}`));console.log("")}i(vpe,"configListCommand");function Rpe(t,e){let n=M9(t),r=ft({workspace:e.workspace}),s=lg(r.value,n);if(s===void 0){console.error(` ${n} is not set`),process.exitCode=1;return}let o=e.showOrigin?` (${(r.origins.get(n)??[{source:"default"}]).map(a=>Pa(a.source,a.file)).join(" + ")})`:"";console.log(`${B9(n,s)}${o}`)}i(Rpe,"configGetCommand");function kpe(t,e,n){let r=Ope(n),s=M9(t),[o,a]=MGe(s,Dk(e));a&&(console.error(` \u26A0\uFE0F ${s} ${a}`),process.exit(1));let l=lr(r,s,o,{workspace:n.workspace});l&&(console.error(` \u26A0\uFE0F ${l}`),process.exit(1)),console.log(` Set ${s} = ${B9(s,o)} ${g.dim(`(${r}: ${iv(Fo(r,{workspace:n.workspace}))})`)}`)}i(kpe,"configSetCommand");function Dpe(t,e){let n=Ope(e),r=M9(t),s=eu(n,r,{workspace:e.workspace});console.log(s?` Removed ${r} from ${n} settings.`:` ${r} was not set in ${n} settings.`)}i(Dpe,"configUnsetCommand");function Npe(t){let e=Xc(t.workspace,ar()),n=i((s,o)=>{let a=O9.existsSync(o);console.log(` ${s.padEnd(10)} ${a?o:g.dim(o+" (not found)")}`)},"row");console.log("");for(let s of MA())n("Managed",s);n("Local",e.local),n("Project",e.project),n("User",e.user);let r=Object.values(e.legacy).filter(s=>O9.existsSync(s));if(r.length>0){console.log(""),console.log(g.dim(" Legacy (still read; run `mc config migrate` to fold into settings.json):"));for(let s of r)console.log(g.dim(` ${s}`))}console.log("")}i(Npe,"configPathCommand");function xpe(t){let e=Tpe(t.workspace,{dryRun:t.dryRun});if(e.skipped){console.log(` Nothing to migrate (${e.skipped}).`);return}if(e.keys.length===0){console.log(` ${iv(e.target)} already contains everything from the legacy files.`);return}console.log(` ${t.dryRun?"Would migrate":"Migrated"} into ${iv(e.target)}:`);for(let n of e.keys)console.log(` + ${n}`);console.log(g.dim(` From: ${e.sources.map(iv).join(", ")}`)),t.dryRun||console.log(g.dim(" The legacy files were left in place; delete them once you have reviewed the result."))}i(xpe,"configMigrateCommand");function Ope(t){if(t.project)return"project";let e=t.scope??"user";if(e==="global")return"user";if(e==="user"||e==="project"||e==="local")return e;console.error(" \u26A0\uFE0F --scope must be user, project or local"),process.exit(1)}i(Ope,"resolveScope");function iv(t){let e=process.env.HOME||process.env.USERPROFILE;return e&&t.startsWith(e)?"~"+t.slice(e.length):Ipe.normalize(t)}i(iv,"tilde");Rt();co();Hs();vn();Ys();YA();$o();He();wr();$o();Fpe();function F9(t){let e=st().ansi,n=st().emoji;Bpe("Available Models"),fS();let r=[{header:"Model",width:24},{header:"Provider",width:12},{header:"Context",width:10,align:"right"},{header:"Speed",width:10},{header:"In / Out",width:16},{header:"Features",width:14}],s=Qa.map(o=>{let a=y4(o.id,t),l=!a.allowed,u={monkeyscode:e?ls.accent("MonkeysCode"):"MonkeysCode",anthropic:e?g.hex("#D97757")("Anthropic"):"Anthropic",google:e?g.hex("#4285F4")("Google"):"Google",openai:e?g.hex("#74AA9C")("OpenAI"):"OpenAI"}[o.provider]||o.provider,p=o.speed==="fast"?n?"\u26A1 Fast":"Fast":n?"\u{1F9E0} Deep":"Deep",f=o.costInputPerM===0?e?ls.success("Free"):"Free":`${L9(o.costInputPerM)} / ${L9(o.costOutputPerM)}`,h=[];o.thinking&&h.push(n?"\u{1F4AD} Think":"Think"),l&&h.push(e?ls.warning(`\u{1F512} ${a.requiredPlan}+`):`[${a.requiredPlan}+]`);let _=h.join(" ");return{cells:[e?l?ls.dim(o.displayName):g.bold(o.displayName):o.displayName,u,Lpe(o.contextWindow),p,f,_],dim:l}});if(Ppe(r,s),fS(),e){console.log(` ${ls.dim("Aliases:")}`);for(let o of Qa)if(o.aliases.length>0){let a=o.aliases.map(l=>ls.accent(l)).join(ls.dim(", "));console.log(` ${ls.dim(" "+o.displayName+":")} ${a}`)}}else{console.log(" Aliases:");for(let o of Qa)o.aliases.length>0&&console.log(` ${o.displayName}: ${o.aliases.join(", ")}`)}fS(),P9("Use --model <name|alias> to select a model"),P9("Use --model auto for smart routing based on task complexity"),fS()}i(F9,"printModelList");var $pe=N(require("node:path"),1);He();wr();sn();Ef();cE();C_();var LGe=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Upe(){let t=st(),e=_t(t),n=t.ansi,r=On();if(!r){console.log(""),console.log(` ${e.error} Not logged in. Run: mc auth login`),console.log("");return}console.log("");let s=null;try{let u=await Fr();if(u){let p=await fetch(`${LGe}/v1/usage/monthly`,{headers:{Authorization:`Bearer ${u}`}});p.ok&&(s=await p.json())}}catch{}if(!s){let u=new Date;s={period:`${u.toLocaleString("default",{month:"long"})} ${u.getFullYear()}`,plan:r.org?.plan||"free",sessionsCount:0,tokensIn:0,tokensOut:0,tokensThinking:0,totalCost:0,costLimit:0,byModel:[]}}let o=s.period,a=s.plan.charAt(0).toUpperCase()+s.plan.slice(1);console.log(n?g.bold(` \u{1F4CA} Monthly Usage (${o})`):` Monthly Usage (${o})`),console.log(n?g.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),console.log(` Plan: ${a}`),console.log(` Sessions: ${s.sessionsCount}`);let l=Sm(s.tokensIn),c=Sm(s.tokensOut);if(console.log(` Tokens: ${l} input, ${c} output`),s.tokensThinking>0&&console.log(` Thinking: ${Sm(s.tokensThinking)}`),s.costLimit>0){let u=Math.round(s.totalCost/s.costLimit*100),p=u>=80?n?g.red(`$${s.totalCost.toFixed(2)} / $${s.costLimit.toFixed(2)} (${u}%)`):`$${s.totalCost.toFixed(2)} / $${s.costLimit.toFixed(2)} (${u}%)`:`$${s.totalCost.toFixed(2)} / $${s.costLimit.toFixed(2)} (${u}%)`;console.log(` Cost: ${p}`)}else console.log(` Cost: $${s.totalCost.toFixed(2)}`);if(s.byModel.length>0){console.log(" By model:");for(let u of s.byModel)console.log(` ${u.model.padEnd(18)} $${u.cost.toFixed(2)} (${u.sessions} sessions)`)}console.log(n?g.dim(" "+"\u2500".repeat(40)):" "+"-".repeat(40)),s.sessionsCount===0&&s.totalCost===0&&console.log(n?g.dim(" Usage data not available. Ensure you are connected."):" Usage data not available. Ensure you are connected."),console.log("")}i(Upe,"usageCommand");function Qpe(t,e={}){let n=e.log??(u=>console.log(u)),r=e.store??new gs,s=r.list(Number.MAX_SAFE_INTEGER),o;if(!t||t==="last"){let u=$pe.resolve(e.workspace??".");o=(s.find(p=>p.workspace===u)??s[0])?.id}else o=s.find(u=>u.id===t)?.id??s.find(u=>u.id.startsWith(t))?.id;let a=o?r.transcripts.read(o):void 0;if(!o||!a)return n(` No session matches "${t||"last"}".`),1;let l=yM(a),c=ub(l);if(e.json)return n(JSON.stringify({session_id:o,...c},null,2)),0;for(let u of FGe(o,c))n(u);return 0}i(Qpe,"sessionUsageCommand");function FGe(t,e){let n=["",` Session ${t.slice(0,8)} \u2014 ${e.requests} request${e.requests===1?"":"s"}${e.models.length?` (${e.models.join(", ")})`:""}`];if(e.requests===0)return n.push(" No per-request records in this session (it predates them, or no request finished).",""),n;let r=i(s=>s===null?"n/a":`${(s*100).toFixed(1)}%`,"pct");if(n.push(` Input: ${Sm(e.promptTokens)} tokens over ${e.withPromptTokens} reported request${e.withPromptTokens===1?"":"s"}`),n.push(` Cached share: ${r(e.cachedShare)}${e.cachedShare===null?" (the endpoint did not report cached tokens)":""}`),n.push(` Cache writes: ${r(e.cacheWriteRatio)}${e.cacheWriteRatio===null?" (not reported by this provider)":` of input (n=${e.withCacheWrites})`}`),n.push(` Output: ${Sm(e.completionTokens)} tokens`),e.compactions&&n.push(` Compactions: ${e.compactions}`),e.largestToolResults.length){n.push(" Largest tool results:");for(let s of e.largestToolResults)n.push(` ${s.name.padEnd(20)} ${Sm(s.chars).padStart(6)} chars (~${Sm(Math.round(s.chars/4))} tokens, before request ${s.request})`)}return n.push(""),n}i(FGe,"formatSessionReport");function Sm(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:String(t)}i(Sm,"formatTokenCount");var ya=N(require("node:fs"),1),jpe=N(require("node:path"),1),ym=require("node:child_process");He();var Qh=N(require("node:fs"),1),av=N(require("node:path"),1);$t();var $Ge="https://monkeyscode.com/api/latest-version",UGe="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",QGe=4*60*60*1e3;function Ype(){let t=Ze();return av.join(t.config,"update-check")}i(Ype,"getCachePath");function GGe(){try{let t=Qh.readFileSync(Ype(),"utf8");return JSON.parse(t)}catch{return null}}i(GGe,"readCache");function $9(t){try{let e=Ype();Qh.mkdirSync(av.dirname(e),{recursive:!0}),Qh.writeFileSync(e,JSON.stringify(t))}catch{}}i($9,"writeCache");function Gpe(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let s=0;s<3;s++){if((n[s]||0)>(r[s]||0))return!0;if((n[s]||0)<(r[s]||0))return!1}return!1}i(Gpe,"isNewerVersion");function HGe(){let t=process.platform,e=process.arch;return`cli-${t}-${e}`}i(HGe,"getAssetKey");async function U9(t,e=!1){if(!e){let n=GGe();if(n&&Date.now()-n.lastCheck<QGe)return n.latestVersion&&Gpe(n.latestVersion,t)?{version:n.latestVersion,currentVersion:t,downloadUrl:n.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let n=await Hpe($Ge);if(n||(n=await Hpe(UGe)),!n)return $9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let r=n.productVersion||n.version,s=HGe(),o=n.assets?.[s],a=o?.url||"https://monkeyscode.com/download";return $9({lastCheck:Date.now(),latestVersion:r,downloadUrl:a}),r&&Gpe(r,t)?{version:r,currentVersion:t,downloadUrl:a,sha256:o?.sha256,size:o?.size,publishedAt:n.date||"",commit:n.commit||"",quality:n.quality||"stable"}:null}catch{return $9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}i(U9,"checkForUpdate");async function Hpe(t){try{let e=await fetch(t,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});return e.ok?await e.json():null}catch{return null}}i(Hpe,"fetchManifest");function Q9(){let t=process.execPath,e=process.argv[1]||"";return e.includes("node_modules")||e.includes(".npm")?"npm":t.includes("/opt/homebrew/")||t.includes("/usr/local/Cellar/")?"homebrew":t.includes("\\scoop\\")?"scoop":t.includes("\\chocolatey\\")?"chocolatey":process.platform==="win32"&&(t.includes("\\WindowsApps\\")||t.includes("\\Programs\\"))?"winget":process.__sea?"binary":"unknown"}i(Q9,"detectInstallMethod");async function Kpe(t){let n=(await Promise.resolve().then(()=>(Wpe(),qpe)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"1.0.2";if(t.rollback){await e6e(n);return}if(t.check){await WGe(n);return}await jGe(n,t.version)}i(Kpe,"updateCommand");async function WGe(t){console.log(g.dim(` Current version: v${t}`)),console.log(g.dim(" Checking for updates...")),console.log("");let e=await U9(t,!0);e?(console.log(g.green(` \u2705 Update available: v${t} \u2192 v${e.version}`)),console.log(g.dim(` Published: ${e.publishedAt||"unknown"}`)),console.log(g.dim(` Download: ${e.downloadUrl}`)),console.log(""),console.log(` Run ${g.bold("mc update")} to install.`)):console.log(g.green(` \u2705 You're on the latest version (v${t})`)),console.log("")}i(WGe,"checkOnly");async function jGe(t,e){let n=Q9();console.log(""),console.log(g.bold(" \u{1F504} MonkeysCode CLI Update")),console.log(g.dim(` Current: v${t} \xB7 Method: ${n}`)),console.log(""),e&&console.log(g.dim(` Target version: v${e}`));try{switch(n){case"npm":await KGe(e);break;case"homebrew":await VGe();break;case"winget":await zGe();break;case"chocolatey":await JGe();break;case"scoop":await XGe();break;case"binary":await ZGe(t,e);break;default:console.log(g.yellow(" \u26A0\uFE0F Could not detect installation method.")),console.log(""),console.log(" Try one of:"),console.log(` ${g.dim("npm")}: npm update -g @monkeyscode/cli`),console.log(` ${g.dim("brew")}: brew upgrade monkeyscode`),console.log(` ${g.dim("curl")}: curl -fsSL https://monkeyscode.com/install.sh | sh`);break}}catch(r){console.error(g.red(` \u274C Update failed: ${r instanceof Error?r.message:String(r)}`)),console.log(g.dim(" Try updating manually or run mc doctor for help.")),process.exitCode=1}console.log("")}i(jGe,"performUpdate");async function KGe(t){if(t&&!/^[0-9A-Za-z.+-]+$/.test(t))throw new Error(`Invalid version: ${t}`);let e=t?`@monkeyscode/cli@${t}`:"@monkeyscode/cli";console.log(g.dim(` Running: npm install -g ${e}`)),(0,ym.execFileSync)(process.platform==="win32"?"npm.cmd":"npm",["install","-g",e],{stdio:"inherit",shell:process.platform==="win32"}),console.log(g.green(" \u2705 Updated via npm"))}i(KGe,"updateViaNpm");async function VGe(){console.log(g.dim(" Running: brew upgrade monkeyscode")),(0,ym.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Homebrew"))}i(VGe,"updateViaHomebrew");async function zGe(){console.log(g.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,ym.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via winget"))}i(zGe,"updateViaWinget");async function JGe(){console.log(g.dim(" Running: choco upgrade monkeyscode-cli")),(0,ym.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Chocolatey"))}i(JGe,"updateViaChocolatey");async function XGe(){console.log(g.dim(" Running: scoop update monkeyscode")),(0,ym.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Scoop"))}i(XGe,"updateViaScoop");async function ZGe(t,e){let n=await U9(t,!0);if(!n&&!e){console.log(g.green(` \u2705 Already on latest version (v${t})`));return}let r=n?.downloadUrl;if(!r)throw new Error("Could not determine download URL");console.log(g.dim(` Downloading from: ${r}`));let s=process.execPath,o=s+".backup";try{ya.copyFileSync(s,o),console.log(g.dim(` Backed up current binary to: ${jpe.basename(o)}`))}catch{console.log(g.yellow(" \u26A0\uFE0F Could not create backup (continuing anyway)"))}let a=await fetch(r,{signal:AbortSignal.timeout(6e4)});if(!a.ok)throw new Error(`Download failed: HTTP ${a.status}`);let l=Buffer.from(await a.arrayBuffer());if(n?.sha256){let u=(await import("node:crypto")).createHash("sha256").update(l).digest("hex");if(u!==n.sha256)throw new Error(`Checksum mismatch (expected ${n.sha256}, got ${u})`);console.log(g.dim(" \u2705 Checksum verified"))}try{ya.writeFileSync(s,l),ya.chmodSync(s,493),console.log(g.green(` \u2705 Updated to v${n?.version||e}`))}catch(c){try{ya.copyFileSync(o,s),console.log(g.yellow(" Restored backup after failed update"))}catch{}throw c}}i(ZGe,"updateViaBinaryDownload");async function e6e(t){if(console.log(""),console.log(g.bold(" \u23EA Rollback")),console.log(""),Q9()==="binary"){let n=process.execPath+".backup";if(!ya.existsSync(n)){console.log(g.red(" \u274C No backup found. Cannot rollback.")),console.log(g.dim(" Rollback is only available after a binary update."));return}try{ya.copyFileSync(n,process.execPath),ya.chmodSync(process.execPath,493),console.log(g.green(" \u2705 Rolled back to previous version")),console.log(g.dim(" Restart the CLI to use the previous version."))}catch(r){console.error(g.red(` \u274C Rollback failed: ${r instanceof Error?r.message:String(r)}`))}}else console.log(g.yellow(" \u26A0\uFE0F Rollback is only supported for binary installs.")),console.log(""),console.log(" For other methods, install a specific version:"),console.log(` ${g.dim(`mc update --version ${t}`)}`);console.log("")}i(e6e,"rollback");He();var Gh=N(require("node:fs"),1),cv=N(require("node:path"),1),Jpe=N(require("node:crypto"),1);$t();var Nc=!0,G9="",Bi=[],Vpe=!1,t6e="https://monkeyscode.com/api/telemetry",lv=50,n6e=6e4;function Xpe(){let t=Ze();return cv.join(t.config,"telemetry.json")}i(Xpe,"getConfigPath");function H9(){try{let t=Gh.readFileSync(Xpe(),"utf8");return JSON.parse(t)}catch{let t={enabled:!0,clientId:r6e()};return Y9(t),t}}i(H9,"loadConfig");function Y9(t){try{let e=Xpe();Gh.mkdirSync(cv.dirname(e),{recursive:!0}),Gh.writeFileSync(e,JSON.stringify(t,null,2))}catch{}}i(Y9,"saveConfig");function r6e(){return Jpe.randomUUID()}i(r6e,"generateClientId");function Zpe(){if(Vpe)return;if(Vpe=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Nc=!1;return}let t=H9();Nc=t.enabled,G9=t.clientId,Nc&&(setInterval(()=>zpe(),n6e).unref(),process.on("beforeExit",()=>zpe()))}i(Zpe,"initTelemetry");function eme(){return Nc}i(eme,"isTelemetryEnabled");function tme(){Nc=!0;let t=H9();t.enabled=!0,Y9(t)}i(tme,"enableTelemetry");function nme(){Nc=!1,Bi=[];let t=H9();t.enabled=!1,Y9(t)}i(nme,"disableTelemetry");function q9(t,e={}){Nc&&(Bi.push({name:t,properties:e,timestamp:new Date().toISOString()}),Bi.length>lv&&(Bi=Bi.slice(-lv)))}i(q9,"trackEvent");async function zpe(){if(!Nc||Bi.length===0)return;let t=[...Bi];Bi=[];let e=ws(),r={clientId:G9,cliVersion:"1.0.2",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:t};try{await fetch(t6e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)})}catch{Bi.unshift(...t),Bi.length>lv&&(Bi=Bi.slice(-lv))}}i(zpe,"flushEvents");function rme(){let t=ws();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 1.0.2",` \u2022 OS: ${t.os} (${t.arch})`,` \u2022 Shell: ${t.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: ${Nc?"ENABLED":"DISABLED"}`,`Client ID: ${G9||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
1209
+ `)}i(rme,"getCollectedDataSummary");async function sme(t){switch(t){case"enable":tme(),console.log(""),console.log(g.green(" \u2705 Telemetry enabled")),console.log(g.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":nme(),console.log(""),console.log(g.yellow(" \u26A0\uFE0F Telemetry disabled")),console.log(g.dim(" No data will be collected.")),console.log("");break;case"show":console.log(""),console.log(rme()),console.log("");break;case"status":default:console.log(""),process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"?console.log(g.yellow(" \u26A0\uFE0F Telemetry: DISABLED (DO_NOT_TRACK env var is set)")):eme()?console.log(g.green(" \u2705 Telemetry: ENABLED")):console.log(g.dim(" \u2B55 Telemetry: DISABLED")),console.log(""),console.log(g.dim(" Commands:")),console.log(g.dim(" mc telemetry enable \u2014 enable anonymous usage data")),console.log(g.dim(" mc telemetry disable \u2014 disable all telemetry")),console.log(g.dim(" mc telemetry show \u2014 see what data is collected")),console.log("");break}}i(sme,"telemetryCommand");var Al=N(require("node:fs"),1),hS=N(require("node:path"),1);He();$t();async function ome(t,e){let n=ws(),r="1.0.2";console.log(""),console.log(g.bold(" \u{1F41B} Bug Report")),console.log("");let s={description:t||"(no description provided)",cliVersion:r,nodeVersion:process.version,os:`${n.os} (${n.arch})`,arch:n.arch,shell:n.shell,timestamp:new Date().toISOString()};if(e?.attachCrash){let a=i6e();a?(s.crashLog=a,console.log(g.dim(" \u{1F4CE} Attached latest crash report"))):console.log(g.dim(" No crash reports found"))}if(await s6e(s))console.log(g.green(" \u2705 Bug report submitted")),console.log(g.dim(" Thank you! Our team will review your report."));else{let a=o6e(s);console.log(g.yellow(" \u26A0\uFE0F Could not submit online (saved locally)")),console.log(g.dim(` Report: ${a}`)),console.log(g.dim(" Submit later: mc bug --submit-local"))}console.log("")}i(ome,"bugCommand");async function s6e(t){try{return(await fetch("https://monkeyscode.com/api/bug-reports",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)})).ok}catch{return!1}}i(s6e,"submitReport");function o6e(t){let e=Ze(),n=hS.join(e.config,"bug-reports");Al.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=hS.join(n,`${r}.json`);return Al.writeFileSync(s,JSON.stringify(t,null,2)),s}i(o6e,"saveReportLocally");function i6e(){try{let t=Ze(),e=hS.join(t.config,"crashes");if(!Al.existsSync(e))return null;let n=Al.readdirSync(e).filter(r=>r.endsWith(".log")).sort().reverse();return n.length===0?null:Al.readFileSync(hS.join(e,n[0]),"utf8")}catch{return null}}i(i6e,"getLatestCrashLog");var Cm=N(require("node:fs"),1),W9=N(require("node:path"),1);He();$t();wr();function ime(){let t=Ze(),e=W9.join(t.config,"config.json");return!Cm.existsSync(e)}i(ime,"isFirstRun");function a6e(){let e=Ze().config,n=W9.join(e,"config.json");Cm.mkdirSync(e,{recursive:!0}),Cm.existsSync(n)||Cm.writeFileSync(n,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}i(a6e,"markOnboardingComplete");async function ame(){let t=st(),e=ws();console.log(""),console.log(g.bold(" \u{1F435} Welcome to MonkeysCode!")),console.log(g.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(g.dim(` Platform: ${e.os} (${e.arch}) \xB7 Shell: ${e.shell}`)),console.log(""),console.log(g.bold(" \u{1FA7A} Quick Setup Check")),console.log("");let n=[],r=parseInt(process.version.slice(1).split(".")[0],10);n.push({name:"Node.js",ok:r>=20,msg:r>=20?process.version:`${process.version} (requires >= 20)`});try{let{execSync:s}=await import("node:child_process"),o=s("git --version",{encoding:"utf8"}).trim();n.push({name:"Git",ok:!0,msg:o.replace("git version ","")})}catch{n.push({name:"Git",ok:!1,msg:"not found"})}try{let{execSync:s}=await import("node:child_process"),o=s("rg --version",{encoding:"utf8"}).split(`
1210
1210
  `)[0];n.push({name:"ripgrep",ok:!0,msg:o.replace("ripgrep ","")})}catch{n.push({name:"ripgrep",ok:!1,msg:"not found (optional but recommended)"})}for(let s of n){let o=s.ok?g.green(" \u2705"):g.yellow(" \u26A0\uFE0F ");console.log(`${o} ${s.name}: ${g.dim(s.msg)}`)}console.log(""),console.log(g.bold(" \u{1F510} Authentication")),console.log(""),console.log(" To start using MonkeysCode, authenticate with your account:"),console.log(""),console.log(` ${g.cyan("mc auth login")}`),console.log(""),console.log(g.bold(" \u{1F4A1} Quick Start")),console.log(""),console.log(` ${g.dim("Interactive:")} ${g.cyan("mc")} Open the REPL`),console.log(` ${g.dim("One-shot:")} ${g.cyan('mc "fix the login bug"')} Run a single prompt`),console.log(` ${g.dim("Background:")} ${g.cyan('mc run "add unit tests"')} Run in the background`),console.log(` ${g.dim("Health:")} ${g.cyan("mc doctor")} Check your setup`),console.log(` ${g.dim("Help:")} ${g.cyan("mc --help")} See all commands`),console.log(""),console.log(g.dim(" \u2500".repeat(30))),console.log(g.dim(" In the REPL: /help for commands, /model to change models")),console.log(""),a6e()}i(ame,"runOnboarding");om();var ud=N(require("node:fs"),1),uv=N(require("node:path"),1);$t();var lme=[];function ume(){process.on("uncaughtException",t=>{cme(t,"uncaughtException"),console.error(`
1211
1211
  \u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${t.message}
1212
- `),process.exit(1)}),process.on("unhandledRejection",t=>{let e=t instanceof Error?t:new Error(String(t));cme(e,"unhandledRejection")})}i(ume,"installCrashHandler");function l6e(){let t=Ze();return uv.join(t.config,"crashes")}i(l6e,"getCrashDir");function cme(t,e){try{let n=l6e();ud.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=uv.join(n,`${r}.log`),o=ws(),l=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 1.0.1",`Node.js: ${process.version}`,`Platform: ${o.os} (${o.arch})`,`Shell: ${o.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: ${t.name}`,`Message: ${t.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",t.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",lme.length>0?lme.map((c,u)=>` ${u+1}. ${c}`).join(`
1212
+ `),process.exit(1)}),process.on("unhandledRejection",t=>{let e=t instanceof Error?t:new Error(String(t));cme(e,"unhandledRejection")})}i(ume,"installCrashHandler");function l6e(){let t=Ze();return uv.join(t.config,"crashes")}i(l6e,"getCrashDir");function cme(t,e){try{let n=l6e();ud.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=uv.join(n,`${r}.log`),o=ws(),l=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 1.0.2",`Node.js: ${process.version}`,`Platform: ${o.os} (${o.arch})`,`Shell: ${o.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: ${t.name}`,`Message: ${t.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",t.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",lme.length>0?lme.map((c,u)=>` ${u+1}. ${c}`).join(`
1213
1213
  `):" (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(`
1214
1214
  `);ud.writeFileSync(s,l),c6e(n,20)}catch{}}i(cme,"writeCrashReport");function c6e(t,e){try{let n=ud.readdirSync(t).filter(r=>r.endsWith(".log")).sort().reverse();for(let r=e;r<n.length;r++)ud.unlinkSync(uv.join(t,n[r]))}catch{}}i(c6e,"pruneOldReports");tS();He();var Us=N(require("node:fs"),1),Ca=N(require("node:path"),1),pv=N(require("node:crypto"),1),mv=require("node:child_process");$t();function dme(t,e){let n=t.split(`
1215
1215
  `);if(n.length<=50)return[{content:t,startLine:1,endLine:n.length,type:"module"}];switch(e){case"typescript":case"javascript":case"go":case"rust":case"java":case"c":case"cpp":case"csharp":return u6e(n);case"python":return d6e(n);default:return p6e(n,50)}}i(dme,"chunkCode");function u6e(t){let e=[],n=0,r=0,s="module";for(let o=0;o<t.length;o++){let a=t[o],l=a.trim();n===0&&(/^(?:export\s+)?(?:async\s+)?function\s/.test(l)||/^(?:export\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\(/.test(l)||/^\w+\s*\(/.test(l)?s="function":(/^(?:export\s+)?class\s/.test(l)||/^(?:export\s+)?interface\s/.test(l))&&(s="class"));for(let c of a)c==="{"?n++:c==="}"&&n--;if(n===0&&o>r&&(l.endsWith("}")||l==="}")){let c=t.slice(r,o+1);c.length>=5&&(e.push({content:c.join(`
@@ -1387,7 +1387,7 @@ ${t}`,r}i(THe,"buildBugfindPrompt");function Fge(t){return jI(t).map(({severity:
1387
1387
 
1388
1388
  ${o}
1389
1389
 
1390
- ${m$(e)}`})});a.ok?console.error(g.green(` \u2705 Review posted on PR #${t}`)):console.error(g.yellow(` \u26A0 Failed to post review: ${a.status}`))}catch(a){console.error(g.yellow(` \u26A0 Failed to post review: ${a instanceof Error?a.message:a}`))}}i(wHe,"postReviewComments");function Qge(t){try{let e=(0,vm.execSync)("git remote get-url origin",{cwd:t,encoding:"utf8"}).trim(),n=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{type:"github",owner:n[1],repo:n[2],url:e};let r=e.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);return r?{type:"gitlab",owner:r[1],repo:r[2],url:e}:{type:"unknown",owner:"",repo:"",url:e}}catch{return{type:"unknown",owner:"",repo:"",url:""}}}i(Qge,"getGitRemote");function Gge(){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;let t=ft({workspace:process.cwd()}).value;return typeof t.githubToken=="string"&&t.githubToken?t.githubToken:typeof t.gitlabToken=="string"&&t.gitlabToken?t.gitlabToken:null}i(Gge,"getGitToken");function vHe(t,e){let n=[];function s(o){if(n.length>=50)return;let a=Pi.readdirSync(o,{withFileTypes:!0});for(let l of a){if(n.length>=50)return;let c=Rm.join(o,l.name);if(l.isDirectory()){if(["node_modules",".git","vendor","dist","build","__pycache__",".next"].includes(l.name))continue;s(c)}else e.some(u=>l.name.endsWith(u))&&n.push(c)}}return i(s,"walk"),s(t),n}i(vHe,"collectFiles");ume();Zpe();UU()&&(g.level=0);globalThis.__mcChalk=g;var Ov="1.0.1",Dm="auto";bpe();function yfe(t){let e=Et({workspace:t});return{defaultModel:e.defaultModel,permissionMode:e.permissionMode,effort:e.effort}}i(yfe,"loadConfig");var pt=new dU;pt.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
1390
+ ${m$(e)}`})});a.ok?console.error(g.green(` \u2705 Review posted on PR #${t}`)):console.error(g.yellow(` \u26A0 Failed to post review: ${a.status}`))}catch(a){console.error(g.yellow(` \u26A0 Failed to post review: ${a instanceof Error?a.message:a}`))}}i(wHe,"postReviewComments");function Qge(t){try{let e=(0,vm.execSync)("git remote get-url origin",{cwd:t,encoding:"utf8"}).trim(),n=e.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(n)return{type:"github",owner:n[1],repo:n[2],url:e};let r=e.match(/gitlab\.com[:/]([^/]+)\/([^/.]+)/);return r?{type:"gitlab",owner:r[1],repo:r[2],url:e}:{type:"unknown",owner:"",repo:"",url:e}}catch{return{type:"unknown",owner:"",repo:"",url:""}}}i(Qge,"getGitRemote");function Gge(){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;let t=ft({workspace:process.cwd()}).value;return typeof t.githubToken=="string"&&t.githubToken?t.githubToken:typeof t.gitlabToken=="string"&&t.gitlabToken?t.gitlabToken:null}i(Gge,"getGitToken");function vHe(t,e){let n=[];function s(o){if(n.length>=50)return;let a=Pi.readdirSync(o,{withFileTypes:!0});for(let l of a){if(n.length>=50)return;let c=Rm.join(o,l.name);if(l.isDirectory()){if(["node_modules",".git","vendor","dist","build","__pycache__",".next"].includes(l.name))continue;s(c)}else e.some(u=>l.name.endsWith(u))&&n.push(c)}}return i(s,"walk"),s(t),n}i(vHe,"collectFiles");ume();Zpe();UU()&&(g.level=0);globalThis.__mcChalk=g;var Ov="1.0.2",Dm="auto";bpe();function yfe(t){let e=Et({workspace:t});return{defaultModel:e.defaultModel,permissionMode:e.permissionMode,effort:e.effort}}i(yfe,"loadConfig");var pt=new dU;pt.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
1391
1391
  Runs independently of the IDE and Agent Manager.
1392
1392
  Connects directly to model-proxy via SSE streaming.`).version(Ov).enablePositionalOptions();pt.argument("[prompt]","Prompt for the agent (interactive unless -p)").option("-p, --print [prompt]","Print mode: run once non-interactively and print the result (stdin is appended to the prompt)").addOption(new Is("--prompt <prompt>","Prompt (alternative to the positional argument)").hideHelp()).option("--headless","Alias for -p/--print",!1).option("--background","Submit as background job and exit",!1).option("--model <model>","Model to use",Dm).option("--mode <mode>","[deprecated] plan \u2192 --permission-mode plan \xB7 fast/thinking \u2192 --effort low/high").addOption(new Is("--effort <level>","Reasoning effort").choices(["low","medium","high"])).option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new Is("-o, --output-format <format>","Print-mode output: text | json | stream-json (reporters: jsonl, sarif, github, azure, diff, markdown, stream)").choices(["text","json","stream-json","jsonl","diff","markdown","github","azure","sarif","stream"])).addOption(new Is("--output <format>","Alias for --output-format").hideHelp().choices(["text","json","stream-json","jsonl","diff","markdown","github","azure","sarif","stream"])).addOption(new Is("--input-format <format>","Print-mode input: text (default) | stream-json (NDJSON user messages on stdin, multi-turn)").choices(["text","stream-json"])).option("--json-schema <file>","Validate the final answer against this JSON Schema (result.structured); repaired up to 2 times").option("--fork-session","With -r/-c: continue in a new session id, leaving the original untouched",!1).option("--append-system-prompt <text>","Append text to the system prompt").option("--system-prompt-file <file>","Replace the base instructions (tools, memory and safety sections are kept)").option("--mcp-config <files...>",'MCP servers from JSON file(s) ({"mcpServers": {\u2026}}); trusted for this run').option("--strict-mcp-config","Use only the servers from --mcp-config",!1).option("--settings <fileOrJson>","Extra settings layer for this run (file path or inline JSON); managed settings still win").option("--ignore-repo-settings","Ignore the repository's .monkeyscode settings, hooks and MCP servers (untrusted code, e.g. fork PRs)",!1).addOption(new Is("--permission-prompt <channel>",'Where "ask" permissions go in print mode: stdio (control_request over stream-json)').choices(["stdio"])).option("--permission-timeout <seconds>","Deny a --permission-prompt request after this long (default 300)").option("--verbose","Show verbose output (full diffs, full terminal output)",!1).option("--show-thinking","Show model reasoning traces",!1).option("-c, --continue","Resume the last session in this directory",!1).option("-r, --resume [session-id]","Resume a saved session (no id: pick from a list)").option("--resume-job <job-id>","Resume from a completed cloud job").option("--no-tui","Use the plain line-based interface instead of the full-screen TUI").option("--auto-approve","Headless: approve everything that would prompt (deny rules and destructive commands still apply)",!1).option("--approve-for-me","Auto-approve known-safe shell commands (tests, builds, git status\u2026); everything else asks",!1).option("--yolo","Alias for --permission-mode bypass",!1).addOption(new Is("--permission-mode <mode>",'Permission mode (default: from settings, else "default")').choices(["default","acceptEdits","plan","bypass","bypassPermissions","ask"])).option("--allowed-tools <rules...>",'Allow rules, e.g. "run_command(npm test:*)" "edit_file(src/**)"').option("--disallowed-tools <rules...>","Deny rules; bare tool names are also hidden from the model").option("--denied-tools <rules...>","Alias for --disallowed-tools").option("--add-dir <dirs...>","Extra directories the agent may access as if inside the workspace").option("--sandbox","Run in sandbox mode",!1).option("--no-sandbox","Disable sandbox").addOption(new Is("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new Is("--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("--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").addHelpText("after",QU()).action(async(t,e)=>{let n=dt.resolve(e.workspace),r=yfe(n),{resolvePrintFlags:s}=await Promise.resolve().then(()=>(WO(),n7)),o=s(t,e);o.error&&(process.stderr.write(`Error: ${o.error}
1393
1393
  `),process.exit(2));let a=o.prompt;if(!o.print&&a&&a.startsWith("/"))switch(a.split(/\s+/)[0].toLowerCase()){case"/help":case"/h":a=void 0;break;case"/version":case"/v":console.log(Ov),process.exit(0);break;case"/doctor":await V1(),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 h=e.caCert||process.env.MONKEYSCODE_CA_CERT;process.env.NODE_EXTRA_CA_CERTS=h}let l=di(e.model||r.defaultModel);!a&&process.stdin.isTTY&&!e.continue&&e.headless;let c=_4(e.mode);c.warning&&process.stderr.write(g.yellow(` \u26A0 ${c.warning}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monkeyscode-cli",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "MonkeysCode CLI — standalone terminal coding agent. Works independently of the IDE and Agent Manager.",
5
5
  "license": "MIT",
6
6
  "type": "module",