monkeyscode-cli 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/monkeyscode-cli.cjs +12 -12
- package/package.json +1 -1
package/dist/monkeyscode-cli.cjs
CHANGED
|
@@ -269,7 +269,7 @@ ${e.map(r=>{let s=eG*4,o=r.content.length>s?`${r.content.slice(0,s)}
|
|
|
269
269
|
[\u2026 truncated; read ${r.path} for the rest]`:r.content;return`<memory source="${r.label}">
|
|
270
270
|
${o.trim()}
|
|
271
271
|
</memory>`}).join(`
|
|
272
|
-
`)}`}};i(lye,"globMatches");i(cye,"realpath");i(uye,"read")});function w_(t=process.env,e=pye){let n=t.MC_CLIENT?.trim().toLowerCase();return n&&rG.test(n)?n:`cli/${(t.MC_VERSION||e||"0.0.0").toLowerCase().replace(/[^a-z0-9._-]/g,"")||"0.0.0"}`.slice(0,40)}function MN(t){let e={};t?.sessionId&&dye.test(t.sessionId)&&(e["X-Session-ID"]=t.sessionId);let n=t?.client?.trim().toLowerCase();n&&rG.test(n)&&(e["X-MC-Client"]=n);for(let[r,s]of Object.entries(t?.autoHints??{}))(r==="X-MC-Phase"||r==="X-MC-Signals")&&s&&(e[r]=s);return e}function BN(t,e,n,r){if(ro(t))return{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...n,...MN(r)},isDirect:!1,provider:"proxy (auto)"};let s=Ro(t),o=s?.provider||"monkeyscode",a=e.providerKeys||{};return!s&&e.customEndpoint?{url:`${e.customEndpoint.replace(/\/$/,"")}/v1/chat/completions`,headers:{"Content-Type":"application/json",...e.customEndpointKey?{Authorization:`Bearer ${e.customEndpointKey}`}:{}},isDirect:!0,provider:"custom"}:o==="anthropic"&&a.anthropic?{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...n,"X-BYOK-Key":a.anthropic,...MN(r)},isDirect:!1,provider:"proxy (anthropic, your key)"}:o==="openai"&&a.openai?{url:`${nG.openai}/v1/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.openai}`},isDirect:!0,provider:"openai"}:o==="google"&&a.google?{url:`${nG.google}/v1beta/openai/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.google}`},isDirect:!0,provider:"google"}:{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...n,...MN(r)},isDirect:!1,provider:o==="monkeyscode"?"proxy":`proxy (${o})`}}var nG,rG,dye,pye,PN=L(()=>{"use strict";Jr();nG={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"},rG=/^[a-z0-9._/-]{1,40}$/,dye=/^[A-Za-z0-9._:-]{1,64}$/,pye="1.1.
|
|
272
|
+
`)}`}};i(lye,"globMatches");i(cye,"realpath");i(uye,"read")});function w_(t=process.env,e=pye){let n=t.MC_CLIENT?.trim().toLowerCase();return n&&rG.test(n)?n:`cli/${(t.MC_VERSION||e||"0.0.0").toLowerCase().replace(/[^a-z0-9._-]/g,"")||"0.0.0"}`.slice(0,40)}function MN(t){let e={};t?.sessionId&&dye.test(t.sessionId)&&(e["X-Session-ID"]=t.sessionId);let n=t?.client?.trim().toLowerCase();n&&rG.test(n)&&(e["X-MC-Client"]=n);for(let[r,s]of Object.entries(t?.autoHints??{}))(r==="X-MC-Phase"||r==="X-MC-Signals")&&s&&(e[r]=s);return e}function BN(t,e,n,r){if(ro(t))return{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...n,...MN(r)},isDirect:!1,provider:"proxy (auto)"};let s=Ro(t),o=s?.provider||"monkeyscode",a=e.providerKeys||{};return!s&&e.customEndpoint?{url:`${e.customEndpoint.replace(/\/$/,"")}/v1/chat/completions`,headers:{"Content-Type":"application/json",...e.customEndpointKey?{Authorization:`Bearer ${e.customEndpointKey}`}:{}},isDirect:!0,provider:"custom"}:o==="anthropic"&&a.anthropic?{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...n,"X-BYOK-Key":a.anthropic,...MN(r)},isDirect:!1,provider:"proxy (anthropic, your key)"}:o==="openai"&&a.openai?{url:`${nG.openai}/v1/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.openai}`},isDirect:!0,provider:"openai"}:o==="google"&&a.google?{url:`${nG.google}/v1beta/openai/chat/completions`,headers:{"Content-Type":"application/json",Authorization:`Bearer ${a.google}`},isDirect:!0,provider:"google"}:{url:`${e.platformUrl}/v1/chat/completions`,headers:{"Content-Type":"application/json",...n,...MN(r)},isDirect:!1,provider:o==="monkeyscode"?"proxy":`proxy (${o})`}}var nG,rG,dye,pye,PN=L(()=>{"use strict";Jr();nG={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com",google:"https://generativelanguage.googleapis.com"},rG=/^[a-z0-9._/-]{1,40}$/,dye=/^[A-Za-z0-9._:-]{1,64}$/,pye="1.1.2";i(w_,"cliClientId");i(MN,"attributionHeaders");i(BN,"resolveModelRoute")});function sG(t,e){if(!t)return;if(typeof t.get=="function")return t.get(e)??void 0;let n=t,r=Object.keys(n).find(s=>s.toLowerCase()===e.toLowerCase());return r?n[r]:void 0}function gye(t,e=Date.now()){let n=sG(t,"retry-after")?.trim();if(n){if(/^\d+(\.\d+)?$/.test(n))return Math.round(parseFloat(n)*1e3);let s=Date.parse(n);if(!Number.isNaN(s))return Math.max(0,s-e)}let r=sG(t,"x-ratelimit-reset")?.trim();if(r&&/^\d+$/.test(r)){let s=parseInt(r,10);return s>1e9?Math.max(0,s*1e3-e):s*1e3}}function fye(t){try{let e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch{return}}function Aye(t,e,n){let r=t?Date.parse(t):e!==void 0?n+e:NaN;if(Number.isNaN(r))return;let s=Math.max(1,Math.round((r-n)/6e4)),o=s>=60?`${Math.floor(s/60)}h ${s%60}m`:`${s}m`,a=new Date(r).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});return`resets in ${o} (${a})`}function _ye(t){let e=t.trim().replace(/\s+/g," ");return e.length>300?e.slice(0,300)+"\u2026":e}function iG(t,e,n,r=Date.now()){let s=fye(n),o=typeof s?.error=="object"?s.error:void 0,a=o?.type??(typeof s?.error=="string"?s.error:void 0),l=o?.message??s?.message,c=gye(e,r),u=typeof o?.retry_after_seconds=="number"?o.retry_after_seconds*1e3:void 0,p=c??u;if(t===401)return new Lr("auth","Authentication failed (401) \u2014 run `mc auth login` to authenticate.",{status:t});if(t===402&&a==="plan_required"){let f={code:o?.code??"plan_required",title:o?.title,message:l||"This needs a paid plan.",accountState:o?.account_state,requiredPlan:o?.required_plan,upgradeUrl:Qg(o?.upgrade_url),fallbackModel:o?.fallback_model,fallbackLabel:o?.fallback_label},h=[f.title?`${f.title}: ${f.message}`:f.message];return f.upgradeUrl&&h.push(`Upgrade: ${f.upgradeUrl}`),f.fallbackModel&&h.push(`Or continue with /model ${f.fallbackModel}.`),new Lr("plan_required",h.join(`
|
|
273
273
|
`),{status:t,plan:f})}if(t===402){let f=[l||"Your plan or credits do not cover this request."],h=hye(o?.credits_remaining_cents??s?.usage?.credits_remaining_cents);h&&o?.code!=="key_spend_limit_reached"&&f.push(`Credits remaining: ${h}`);let _=Qg(o?.upgrade_url),E=Qg(o?.buy_credits_url);return E&&f.push(`Buy credits: ${E}`),_&&f.push(`Upgrade: ${_}`),new Lr("entitlement",f.join(`
|
|
274
274
|
`),{status:t})}if(t===403){if(a==="model_not_included"){let f=[l||"Your plan does not include this model."];return s?.allowed_models?.length&&f.push(`Included models: ${s.allowed_models.join(", ")}`),f.push(`Upgrade: ${Qg(s?.upgrade_url)??oG+"/dashboard/billing"}`),new Lr("forbidden",f.join(`
|
|
275
275
|
`),{status:t})}return new Lr("forbidden",l?`Access denied (403): ${l}`:"Access denied (403) \u2014 your plan may not include this model.",{status:t})}if(t===429){if(a==="quota_exceeded"||a==="insufficient_quota"){let f=[l||"Usage quota exhausted."],h=Aye(o?.reset_at,p,r);h&&!/resets in/i.test(f[0])&&(f[0]+=` (${h})`);let _=Qg(o?.buy_credits_url),E=Qg(o?.upgrade_url);switch(o?.overage?.reason){case"no_credits":_&&f.push(`Continue now with credits: ${_}`);break;case"promo_plan":case"not_eligible":E&&f.push(`Upgrade to keep going: ${E}`);break;default:E&&f.push(`Upgrade: ${E}`)}return f.push("Or switch to another model with /model."),new Lr("quota",f.join(`
|
|
@@ -402,7 +402,7 @@ ${_}
|
|
|
402
402
|
|
|
403
403
|
<session-start-context>
|
|
404
404
|
${je}
|
|
405
|
-
</session-start-context>`,je="");let It=await yY({prompt:Te,runModel:Kt,runDecider:nn,decider:z,history:u,sessionId:p,workspace:a,settings:Q,token:Le,tools:J,hookRunner:le,permissionMode:X,guard:Ee,opts:e,ac:s,emit:U,record:Y,log:o,internals:b,checkpointsAll:ge,onLoop:i(Re=>{_=Re},"onLoop"),stopReason:i(()=>y,"stopReason")});_=void 0,u=It.history,ue?.checkpoint(u);let Cn,qe,Hr=It.text,mt=It.subtype,xt=It.error;if(e.jsonSchema&&mt==="success"){let Re=await LM(e.jsonSchema,Hr);for(let Qe=1;!Re.ok&&Qe<=2&&!s.signal.aborted;Qe++){o(`[json-schema] answer did not validate (attempt ${Qe}/2): ${Re.errors.slice(0,3).join("; ")}`);let tt=await yY({prompt:_Y(e.jsonSchema,Re.errors),runModel:Kt,runDecider:nn,decider:z,history:u,sessionId:p,workspace:a,settings:Q,token:Le,tools:J,hookRunner:le,permissionMode:X,guard:Ee,opts:e,ac:s,emit:U,record:Y,log:o,internals:b,checkpointsAll:ge,onLoop:i(ht=>{_=ht},"onLoop"),stopReason:i(()=>y,"stopReason")});if(_=void 0,u=tt.history,ue?.checkpoint(u),tt.subtype!=="success"){mt=tt.subtype,xt=tt.error;break}Hr=tt.text,Re=await LM(e.jsonSchema,Hr)}mt==="success"&&(Re.ok?Cn=Re.value:(mt="error_during_execution",qe=Re.errors,xt=`Final answer does not match --json-schema: ${Re.errors.slice(0,3).join("; ")}`))}let hs=z.denials.slice(ft);mt==="success"&&hs.length>0&&z.allowedMutations===Tt&&(mt="error_permission_denied");let Tr=NRe(mt,It.transportKind,xt);_e=Tr;let Yr=_x();Yr.input_tokens=It.tokensIn,Yr.output_tokens=It.tokensOut,Yr.cached_tokens=It.tokensCached,Yr.thinking_tokens=It.tokensThinking;let rs={type:"result",subtype:mt,is_error:mt!=="success",result:Hr,...Cn!==void 0?{structured:Cn}:{},session_id:p,num_turns:It.responses,duration_ms:Date.now()-Ue,usage:Yr,cost_usd:Ee.cost(),is_estimated:Ee.estimated,permission_denials:z.denials.slice(),exit_code:Tr,...xt?{error:xt}:{},...qe?{schema_errors:qe}:{},...It.plan?{plan_required:DRe(It.plan)}:{}};U(rs),f(rs),h=Promise.resolve(rs),(E||y||mt==="error_max_cost"||mt==="error_max_tokens"||mt==="error_auth"||mt==="error_quota"||mt==="error_timeout")&&r.close()}}finally{await le.run("SessionEnd",{workspace:a,sessionId:p,data:{reason:"headless",exitCode:_e,durationMs:Date.now()-G}}).catch(()=>null),we.stop(),ue?.close()}},"run")().catch(N=>{let $=N instanceof Error?N.message:String(N),Q=N.exitCode??_C(v_(N).kind,$),re={type:"result",subtype:Q===Ct.usage?"error_during_execution":xRe(Q),is_error:!0,result:"",session_id:p,num_turns:0,duration_ms:0,usage:_x(),cost_usd:0,is_estimated:!0,permission_denials:[],exit_code:Q,error:$};n.push(re),f(re),h=Promise.resolve(re)}).finally(()=>n.close()),R=i(N=>{y??=N,_?.cancel(),r.close()},"stop"),M={sessionId:p,get result(){return h},interrupt(){_?.interrupt()},send(N){r.push(typeof N=="string"?N:N.content)},end(){r.close()},get pendingPermissions(){return 0},[Symbol.asyncIterator]:()=>n[Symbol.asyncIterator](),[GM]:b};if(e.timeoutMs){let N=setTimeout(()=>R("timeout"),e.timeoutMs);N.unref?.(),v.finally(()=>clearTimeout(N))}return s.signal.aborted?R("abort"):s.signal.addEventListener("abort",()=>R("abort"),{once:!0}),M}async function yY(t){let{opts:e,settings:n}=t,r=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,s=new _r({platformUrl:e.platformUrl??n.platformUrl,token:t.token,model:t.runModel,workspace:t.workspace,mode:ep(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 Mg(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 ef(()=>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,costTracked:y.costTracked})??l,l&&(t.log(`[guard] ${yx(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,plan:y.plan},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(Ub(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=v_(y);a={message:y instanceof Error?y.message:String(y),kind:b.kind,plan:b.plan}}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=yx(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=_C(a.kind,a.message);_=y===Ct.auth?"error_auth":y===Ct.quota?"error_quota":"error_during_execution",E=a.message}return{subtype:_,text:o.lastText.trim(),error:E,transportKind:a?.kind,plan:a?.plan,history:s.getMessages(),responses:o.responses,tokensIn:u.tokensIn,tokensOut:u.tokensOut,tokensCached:u.tokensCached,tokensThinking:c}}function DRe(t){return{code:t.code,message:t.message,...t.title?{title:t.title}:{},...t.accountState?{account_state:t.accountState}:{},...t.requiredPlan?{required_plan:t.requiredPlan}:{},...t.upgradeUrl?{upgrade_url:t.upgradeUrl}:{},...t.fallbackModel?{fallback_model:t.fallbackModel}:{},...t.fallbackLabel?{fallback_label:t.fallbackLabel}:{}}}function NRe(t,e,n){switch(t){case"success":return Ct.success;case"error_max_cost":case"error_max_tokens":return Ct.guard;case"error_permission_denied":return Ct.denied;case"error_timeout":return Ct.timeout;case"error_interrupted":return Ct.interrupted;case"error_auth":return Ct.auth;case"error_quota":return Ct.quota;default:return e?_C(e,n):Ct.runtime}}function xRe(t){return t===Ct.auth?"error_auth":t===Ct.quota?"error_quota":"error_during_execution"}var vT,CY,kRe,GM,wT,UM,QM,TY=L(()=>{"use strict";vT=k(require("node:path"),1),CY=k(require("node:crypto"),1);Ps();wt();i_();ub();OG();LN();Mn();io();h_();T_();wu();Zg();$b();lb();JA();l6();Ex();Q_();c6();Jr();EY();IT();kRe="1.1.1",GM=Symbol.for("monkeyscode.query.internals"),wT=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")}}},UM=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:vi(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=vi(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.`}}},QM=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(bY,"query");i(yY,"runTurn");i(DRe,"planRequiredJson");i(NRe,"exitFor");i(xRe,"subtypeForExit")});var RT,IY=L(()=>{"use strict";RT=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 ORe(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(`
|
|
405
|
+
</session-start-context>`,je="");let It=await yY({prompt:Te,runModel:Kt,runDecider:nn,decider:z,history:u,sessionId:p,workspace:a,settings:Q,token:Le,tools:J,hookRunner:le,permissionMode:X,guard:Ee,opts:e,ac:s,emit:U,record:Y,log:o,internals:b,checkpointsAll:ge,onLoop:i(Re=>{_=Re},"onLoop"),stopReason:i(()=>y,"stopReason")});_=void 0,u=It.history,ue?.checkpoint(u);let Cn,qe,Hr=It.text,mt=It.subtype,xt=It.error;if(e.jsonSchema&&mt==="success"){let Re=await LM(e.jsonSchema,Hr);for(let Qe=1;!Re.ok&&Qe<=2&&!s.signal.aborted;Qe++){o(`[json-schema] answer did not validate (attempt ${Qe}/2): ${Re.errors.slice(0,3).join("; ")}`);let tt=await yY({prompt:_Y(e.jsonSchema,Re.errors),runModel:Kt,runDecider:nn,decider:z,history:u,sessionId:p,workspace:a,settings:Q,token:Le,tools:J,hookRunner:le,permissionMode:X,guard:Ee,opts:e,ac:s,emit:U,record:Y,log:o,internals:b,checkpointsAll:ge,onLoop:i(ht=>{_=ht},"onLoop"),stopReason:i(()=>y,"stopReason")});if(_=void 0,u=tt.history,ue?.checkpoint(u),tt.subtype!=="success"){mt=tt.subtype,xt=tt.error;break}Hr=tt.text,Re=await LM(e.jsonSchema,Hr)}mt==="success"&&(Re.ok?Cn=Re.value:(mt="error_during_execution",qe=Re.errors,xt=`Final answer does not match --json-schema: ${Re.errors.slice(0,3).join("; ")}`))}let hs=z.denials.slice(ft);mt==="success"&&hs.length>0&&z.allowedMutations===Tt&&(mt="error_permission_denied");let Tr=NRe(mt,It.transportKind,xt);_e=Tr;let Yr=_x();Yr.input_tokens=It.tokensIn,Yr.output_tokens=It.tokensOut,Yr.cached_tokens=It.tokensCached,Yr.thinking_tokens=It.tokensThinking;let rs={type:"result",subtype:mt,is_error:mt!=="success",result:Hr,...Cn!==void 0?{structured:Cn}:{},session_id:p,num_turns:It.responses,duration_ms:Date.now()-Ue,usage:Yr,cost_usd:Ee.cost(),is_estimated:Ee.estimated,permission_denials:z.denials.slice(),exit_code:Tr,...xt?{error:xt}:{},...qe?{schema_errors:qe}:{},...It.plan?{plan_required:DRe(It.plan)}:{}};U(rs),f(rs),h=Promise.resolve(rs),(E||y||mt==="error_max_cost"||mt==="error_max_tokens"||mt==="error_auth"||mt==="error_quota"||mt==="error_timeout")&&r.close()}}finally{await le.run("SessionEnd",{workspace:a,sessionId:p,data:{reason:"headless",exitCode:_e,durationMs:Date.now()-G}}).catch(()=>null),we.stop(),ue?.close()}},"run")().catch(N=>{let $=N instanceof Error?N.message:String(N),Q=N.exitCode??_C(v_(N).kind,$),re={type:"result",subtype:Q===Ct.usage?"error_during_execution":xRe(Q),is_error:!0,result:"",session_id:p,num_turns:0,duration_ms:0,usage:_x(),cost_usd:0,is_estimated:!0,permission_denials:[],exit_code:Q,error:$};n.push(re),f(re),h=Promise.resolve(re)}).finally(()=>n.close()),R=i(N=>{y??=N,_?.cancel(),r.close()},"stop"),M={sessionId:p,get result(){return h},interrupt(){_?.interrupt()},send(N){r.push(typeof N=="string"?N:N.content)},end(){r.close()},get pendingPermissions(){return 0},[Symbol.asyncIterator]:()=>n[Symbol.asyncIterator](),[GM]:b};if(e.timeoutMs){let N=setTimeout(()=>R("timeout"),e.timeoutMs);N.unref?.(),v.finally(()=>clearTimeout(N))}return s.signal.aborted?R("abort"):s.signal.addEventListener("abort",()=>R("abort"),{once:!0}),M}async function yY(t){let{opts:e,settings:n}=t,r=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,s=new _r({platformUrl:e.platformUrl??n.platformUrl,token:t.token,model:t.runModel,workspace:t.workspace,mode:ep(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 Mg(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 ef(()=>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,costTracked:y.costTracked})??l,l&&(t.log(`[guard] ${yx(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,plan:y.plan},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(Ub(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=v_(y);a={message:y instanceof Error?y.message:String(y),kind:b.kind,plan:b.plan}}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=yx(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=_C(a.kind,a.message);_=y===Ct.auth?"error_auth":y===Ct.quota?"error_quota":"error_during_execution",E=a.message}return{subtype:_,text:o.lastText.trim(),error:E,transportKind:a?.kind,plan:a?.plan,history:s.getMessages(),responses:o.responses,tokensIn:u.tokensIn,tokensOut:u.tokensOut,tokensCached:u.tokensCached,tokensThinking:c}}function DRe(t){return{code:t.code,message:t.message,...t.title?{title:t.title}:{},...t.accountState?{account_state:t.accountState}:{},...t.requiredPlan?{required_plan:t.requiredPlan}:{},...t.upgradeUrl?{upgrade_url:t.upgradeUrl}:{},...t.fallbackModel?{fallback_model:t.fallbackModel}:{},...t.fallbackLabel?{fallback_label:t.fallbackLabel}:{}}}function NRe(t,e,n){switch(t){case"success":return Ct.success;case"error_max_cost":case"error_max_tokens":return Ct.guard;case"error_permission_denied":return Ct.denied;case"error_timeout":return Ct.timeout;case"error_interrupted":return Ct.interrupted;case"error_auth":return Ct.auth;case"error_quota":return Ct.quota;default:return e?_C(e,n):Ct.runtime}}function xRe(t){return t===Ct.auth?"error_auth":t===Ct.quota?"error_quota":"error_during_execution"}var vT,CY,kRe,GM,wT,UM,QM,TY=L(()=>{"use strict";vT=k(require("node:path"),1),CY=k(require("node:crypto"),1);Ps();wt();i_();ub();OG();LN();Mn();io();h_();T_();wu();Zg();$b();lb();JA();l6();Ex();Q_();c6();Jr();EY();IT();kRe="1.1.2",GM=Symbol.for("monkeyscode.query.internals"),wT=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")}}},UM=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:vi(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=vi(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.`}}},QM=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(bY,"query");i(yY,"runTurn");i(DRe,"planRequiredJson");i(NRe,"exitFor");i(xRe,"subtypeForExit")});var RT,IY=L(()=>{"use strict";RT=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 ORe(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(`
|
|
406
406
|
`):void 0}}async function*vY(t,e){let n=wY.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 Op(`invalid JSON (${c.message})`,r)}if(e?.handle(a))continue;if(a.type==="control_response"||a.type==="control_request")throw new Op("control message received but --permission-prompt stdio is not enabled",r);let l=ORe(a);if(l===void 0)throw new Op(`expected {"type":"user","message":{"content":\u2026}}, got type ${JSON.stringify(a.type)}`,r);yield l}}finally{n.close(),e?.close()}}var wY,Op,RY=L(()=>{"use strict";wY=k(require("node:readline"),1),Op=class extends Error{constructor(n,r){super(`stdin line ${r}: ${n}`);this.line=r;this.name="StdinProtocolError"}static{i(this,"StdinProtocolError")}};i(ORe,"userText");i(vY,"readStreamJsonInput")});var DY={};rt(DY,{joinPromptAndStdin:()=>HM,readSettingsFlag:()=>DT,resolvePrintFlags:()=>BRe});function BRe(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(`
|
|
407
407
|
|
|
408
408
|
`):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 MRe)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=PRe(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&&!kT(e.systemPromptFile))return u(`--system-prompt-file: cannot read ${e.systemPromptFile}`);for(let p of e.mcpConfig??[])if(!kT(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=LRe(e.settings);if(p)return u(p)}return c}function kT(t){try{return ic.accessSync(t,ic.constants.R_OK),ic.statSync(t).isFile()}catch{return!1}}function PRe(t){if(!kT(t))return`--json-schema: cannot read ${t}`;try{let e=JSON.parse(ic.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 kY(t){let e=t.trimStart().charAt(0);return e==="{"||e==="["}function DT(t){let e=kY(t)?t:ic.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 LRe(t){if(!kY(t)&&!kT(t))return`--settings: cannot read ${t}`;try{DT(t)}catch(e){return`--settings: ${e.message}`}}function HM(t,e){let n=t?.trim(),r=e?.trim();return n&&r?`${n}
|
|
@@ -426,7 +426,7 @@ ${e.error}
|
|
|
426
426
|
`)}}finish(e){this.format!=="stream"&&this.write(this.formatter.formatResult(e)+`
|
|
427
427
|
`)}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(`
|
|
428
428
|
[partial response discarded \u2014 retrying]
|
|
429
|
-
`)}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 QY={};rt(QY,{queryOptionsFrom:()=>UY,runPrint:()=>GRe});async function QRe(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 UY(t,e){let n=Object.assign({},...(t.mcpConfig??[]).map(NY));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?DT(t.settingsFlag):void 0,ignoreRepoSettings:t.ignoreRepoSettings||void 0,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPromptFile?eB.readFileSync(t.systemPromptFile,"utf8"):void 0,maxCostUsd:t.maxCost,maxTokens:t.maxTokens,jsonSchema:t.jsonSchema?JSON.parse(eB.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||Kl(),webEnabled:t.offline?!1:void 0,cliVersion:"1.1.
|
|
429
|
+
`)}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 QY={};rt(QY,{queryOptionsFrom:()=>UY,runPrint:()=>GRe});async function QRe(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 UY(t,e){let n=Object.assign({},...(t.mcpConfig??[]).map(NY));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?DT(t.settingsFlag):void 0,ignoreRepoSettings:t.ignoreRepoSettings||void 0,appendSystemPrompt:t.appendSystemPrompt,systemPrompt:t.systemPromptFile?eB.readFileSync(t.systemPromptFile,"utf8"):void 0,maxCostUsd:t.maxCost,maxTokens:t.maxTokens,jsonSchema:t.jsonSchema?JSON.parse(eB.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||Kl(),webEnabled:t.offline?!1:void 0,cliVersion:"1.1.2",log:e,retry:{maxAttempts:8,maxWaitMs:Math.min(6e4,t.timeout||3e5)}}}async function GRe(t,e,n=URe()){let r=i(N=>{n.stderr.write(N.endsWith(`
|
|
430
430
|
`)?N:`${N}
|
|
431
431
|
`)},"log"),s=e.output??"text",o=e.inputFormat==="stream-json",a;try{a=UY(e,r)}catch(N){return r(`Error: ${N.message}`),Ct.usage}let l,c,u=i(N=>{n.stdout.write(JSON.stringify(N)+`
|
|
432
432
|
`)},"writeLine");if(o)e.permissionPrompt==="stdio"&&(c=new RT(u,e.permissionTimeoutMs??3e5,()=>y?.interrupt()),a.canUseTool=c.canUseTool),l=vY(n.stdin,c);else{let N=HM(t,await QRe(n.stdin));if(!N)return r('Error: No prompt provided. Use -p "your prompt" or pipe via stdin.'),Ct.usage;l=N}let p=s==="text"||s==="json"||s==="stream-json"?void 0:new OT(s,e.workspace,N=>n.stdout.write(N)),f=Date.now(),h,_="",E,y;try{y=bY({prompt:typeof l=="string"?l:HRe(l,N=>{E=N}),options:a})}catch(N){return r(`Error: ${N.message}`),N.exitCode??(N instanceof yf?Ct.usage:Ct.runtime)}let b=y,I=0,v=i(()=>{I++,r(I===1?`
|
|
@@ -840,7 +840,7 @@ ${e}`,"wrappedToString"),c8e=Object.getOwnPropertyDescriptor(Function.prototype,
|
|
|
840
840
|
`).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(`
|
|
841
841
|
`)}function k8e(t){let e=it(),n=yt(e),r=bo(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(`
|
|
842
842
|
`)}function Xce(t,e){let n=it();return` ${yt(n).tool} ${t}: ${e.summary}`}function D8e(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 N8e(t,e){switch(t){case"file_edit":return Z2(String(e.file||e.filePath||e.path||"unknown file"));case"file_read":return Z2(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 Z2(t){return process.platform==="win32"?t.replace(/\//g,"\\"):t}var eue=L(()=>{"use strict";Ye();Or();Jce();i(e$,"renderToolStart");i(t$,"renderToolResult");i(Zce,"renderToolError");i(C8e,"renderFileEdit");i(b8e,"renderFileRead");i(T8e,"renderTerminal");i(I8e,"renderSearch");i(w8e,"renderGit");i(v8e,"renderBrowser");i(R8e,"renderMcp");i(k8e,"renderWebSearch");i(Xce,"renderGeneric");i(D8e,"getToolIcon");i(N8e,"getToolArgsSummary");i(Z2,"displayPath")});function x8e(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toString()}function tue(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}var Fw,nue=L(()=>{"use strict";Ye();Or();Fw=class{static{i(this,"StatusBar")}data;caps;icons;intervalId=null;enabled=!1;lastRendered="";constructor(e){this.caps=it(),this.icons=yt(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(`
|
|
843
|
-
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=it(),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=x8e(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),I=y-b,v=E("\u2588".repeat(b))+g.dim("\u2591".repeat(I));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=tue(l).length,p=tue(c).length,f=Math.max(1,e-u-p),h=g.bgHex("#0d1117"),_=h(" ".repeat(f));return h(l)+_+h(c)}};i(x8e,"formatTokensCompact");i(tue,"stripAnsi")});var rue={};rt(rue,{BRAND:()=>Ho,LOGO_INLINE:()=>n$,LOGO_INLINE_ASCII:()=>r$,isDarkBackground:()=>s$,pickLogoSize:()=>i$,renderLogo:()=>o$,visibleWidth:()=>$w});function s$(){let t=process.env.COLORFGBG;if(!t)return!0;let e=Number(t.split(";").pop());return Number.isNaN(e)?!0:e<8}function o$(t,e={}){let{color:n=!0,dark:r=!0,indent:s=2,center:o}=e,a=P8e[t],l=r?Ho.navyOnDark:Ho.navy,c=n?g.hex(l):h=>h,u=n?g.hex(Ho.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="",I=E[0]??".";for(let v=0;v<h.length;v++){let R=E[v]??".";R!==I&&(y+=p(b,I),b="",I=R),b+=h[v]}return y+=p(b,I),(f+y).replace(/\s+$/,"")})}function i$(t,e){return e?t>=72?"large":t>=46?"medium":t>=24?"mini":null:null}function $w(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}var Ho,O8e,M8e,B8e,P8e,n$,r$,tS=L(()=>{"use strict";Ye();Ho={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},O8e={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..................."]},M8e={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............"]},B8e={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..."]},P8e={large:O8e,medium:M8e,mini:B8e},n$="\u25C1\u2571\u25B7",r$="</>";i(s$,"isDarkBackground");i(o$,"renderLogo");i(i$,"pickLogoSize");i($w,"visibleWidth")});function F8e(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 L8e,Rc,Uw=L(()=>{"use strict";Ye();jce();Or();eue();R1();rd();nue();tS();L8e={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Rc=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={...L8e,...e},this.caps=it(),this.icons=yt(this.caps),this.box=bo(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 Fw(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(Ho.accent):p=>p,o=r?g.dim:p=>p,a=r?g.white.bold:p=>p,l="v1.1.1";console.log("");let c=n.logo??"auto",u=c==="none"?null:c==="auto"?i$(this.caps.columns,this.caps.unicode):c;if(u){let f=o$(u,{color:r,dark:s$(),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":n$} MonkeysCode`,E="CLI Agent",y=Math.max(0,f-$w(_)-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}`:""}`,I=Math.max(0,f-$w(b)-2);console.log(` ${s(p.vertical)} ${s(l)}${e?` ${o("\xB7")} ${o(e)}`:""}${" ".repeat(I)} ${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(` ${r$} 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(Ho.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,`
|
|
843
|
+
`),this.render(),this.intervalId=setInterval(()=>this.render(),1e3),process.stdout.on("resize",()=>{this.caps=it(),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=x8e(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),I=y-b,v=E("\u2588".repeat(b))+g.dim("\u2591".repeat(I));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=tue(l).length,p=tue(c).length,f=Math.max(1,e-u-p),h=g.bgHex("#0d1117"),_=h(" ".repeat(f));return h(l)+_+h(c)}};i(x8e,"formatTokensCompact");i(tue,"stripAnsi")});var rue={};rt(rue,{BRAND:()=>Ho,LOGO_INLINE:()=>n$,LOGO_INLINE_ASCII:()=>r$,isDarkBackground:()=>s$,pickLogoSize:()=>i$,renderLogo:()=>o$,visibleWidth:()=>$w});function s$(){let t=process.env.COLORFGBG;if(!t)return!0;let e=Number(t.split(";").pop());return Number.isNaN(e)?!0:e<8}function o$(t,e={}){let{color:n=!0,dark:r=!0,indent:s=2,center:o}=e,a=P8e[t],l=r?Ho.navyOnDark:Ho.navy,c=n?g.hex(l):h=>h,u=n?g.hex(Ho.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="",I=E[0]??".";for(let v=0;v<h.length;v++){let R=E[v]??".";R!==I&&(y+=p(b,I),b="",I=R),b+=h[v]}return y+=p(b,I),(f+y).replace(/\s+$/,"")})}function i$(t,e){return e?t>=72?"large":t>=46?"medium":t>=24?"mini":null:null}function $w(t){return t.replace(/\x1b\[[0-9;]*m/g,"").length}var Ho,O8e,M8e,B8e,P8e,n$,r$,tS=L(()=>{"use strict";Ye();Ho={navy:"#051e50",navyOnDark:"#2c5fa8",ice:"#a3cad3",accent:"#4A7CBA"},O8e={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..................."]},M8e={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............"]},B8e={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..."]},P8e={large:O8e,medium:M8e,mini:B8e},n$="\u25C1\u2571\u25B7",r$="</>";i(s$,"isDarkBackground");i(o$,"renderLogo");i(i$,"pickLogoSize");i($w,"visibleWidth")});function F8e(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 L8e,Rc,Uw=L(()=>{"use strict";Ye();jce();Or();eue();R1();rd();nue();tS();L8e={verbose:!1,showThinking:!1,maxToolOutputLines:50,sandboxed:!1,accessible:!1},Rc=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={...L8e,...e},this.caps=it(),this.icons=yt(this.caps),this.box=bo(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 Fw(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(Ho.accent):p=>p,o=r?g.dim:p=>p,a=r?g.white.bold:p=>p,l="v1.1.2";console.log("");let c=n.logo??"auto",u=c==="none"?null:c==="auto"?i$(this.caps.columns,this.caps.unicode):c;if(u){let f=o$(u,{color:r,dark:s$(),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":n$} MonkeysCode`,E="CLI Agent",y=Math.max(0,f-$w(_)-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}`:""}`,I=Math.max(0,f-$w(b)-2);console.log(` ${s(p.vertical)} ${s(l)}${e?` ${o("\xB7")} ${o(e)}`:""}${" ".repeat(I)} ${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(` ${r$} 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(Ho.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,`
|
|
844
844
|
`+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(Ho.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(e$(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=eS({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(t$(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(Zce(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(`
|
|
845
845
|
`).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=eS({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(Ho.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(e$(e,n)),!this.opts.accessible&&this.caps.ansi){let r=eS({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(t$(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(`
|
|
846
846
|
`).reduce((s,o)=>s+Math.max(1,Math.ceil(es(o)/n)),0);if(this.caps.ansi&&Oae(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=_l(e,{caps:this.caps,width:this.caps.columns-6});if(this.caps.unicode){let o=g.dim(` ${this.box.vertical} `),a=s.split(`
|
|
@@ -1012,7 +1012,7 @@ ${e.problems.map(r=>` - ${r}`).join(`
|
|
|
1012
1012
|
`));return}if(!r.length){let l=Fc.find(c=>c.key===n);t.printStatus(`${n} = ${Jh(wv(s,n))}${l?g.dim(` (${l.help})`):""}`);return}let o=mme(n,r.join(" "));if(!o.ok){t.printError(o.error);return}let a=fr("user",n,o.value);if(a){t.printError(a);return}t.printSuccess(`${n} = ${Jh(o.value)} (user settings). Takes effect in new sessions.`)}},NHe={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.")}},hme=[kHe,DHe,fme,NHe]});function _me(){let t=new Aw;return t.register(...pue,..._ue,...yue,...wue,...zde,...ype,...bpe,...Npe,p9,...Rpe,...hme),t.register(Dle(t),c9(t)),t}var Eme=L(()=>{"use strict";si();mue();Eue();Cue();vue();Jde();Cpe();Tpe();kpe();xpe();lme();Ame();_w();Cv();si();_w();i(_me,"createDefaultRegistry")});function MHe(t,e){let n={},r=[];for(let o of t.matchAll(xHe))o[1]!==void 0&&e.includes(o[1])?n[o[1]]=o[2].replace(OHe,""):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 Sme(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=MHe(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 xHe,OHe,yme=L(()=>{"use strict";xHe=new RegExp(String.raw`([A-Za-z_][\w-]*)=("[^"]*"|'[^']*'|\S+)|"([^"]*)"|'([^']*)'|(\S+)`,"g"),OHe=new RegExp(String.raw`^["']|["']$`,"g");i(MHe,"parsePromptArgs");i(Sme,"mcpPromptCommands")});var bme={};rt(bme,{analyzeImpact:()=>Cme,notifyAffectedSessions:()=>PHe});function Cme(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=Tl.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=Tl.relative(o.workspace,u),_=Tl.dirname(h).split(Tl.sep)[0];_&&a.includes(_.toLowerCase())&&.7>c&&(c=.7,l=`Task involves "${_}" directory where changes were made`)}for(let h of BHe)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 PHe(t,e,n){if(e.length===0)return[];let r=await t.listAgents(),s=Cme(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=>Tl.basename(p)).join(", "):`${e.slice(0,3).map(p=>Tl.basename(p)).join(", ")} (+${e.length-3} more)`}`,`Reason: ${a.reason}`,`This may affect your task: "${a.task.substring(0,60)}"`].join(`
|
|
1013
1013
|
`),u=await t.sendMessage(a.sessionId,c);o.push(u)}return o}var Tl,BHe,Tme=L(()=>{"use strict";Tl=k(require("node:path"),1),BHe=[{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(Cme,"analyzeImpact");i(PHe,"notifyAffectedSessions")});async function vv(t){let{options:e,token:n,auth:r}=t,s=At({workspace:e.workspace});for(let ue of s.warnings)t.onWarning(ue);let o=_g(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=Tu(e.workspace,{allowedTools:e.allowedTools,deniedTools:e.deniedTools,addDirs:e.addDirs,approveSafeCommands:e.approveForMe},s),u,p=new N_({engine:c,getMode:i(()=>u.getPermissionMode(),"getMode"),prompt:t.prompt}),f=tl.fromSettings(e.workspace,s,{interactiveAuth:process.stdin.isTTY===!0,onAuthPrompt:i(ue=>t.onWarning(ue),"onAuthPrompt")});f.start();let h=new tc(e.workspace,{enabled:e.hooks!==!1,timeoutMs:e.hookTimeoutMs??1e4,effective:s,trustRepoHooks:!1}),_=!1,E=FN(e.workspace,typeof s.value.outputStyle=="string"?s.value.outputStyle:void 0);E.warning&&t.onWarning(E.warning);let y=new Cs,b=`interactive-${Date.now().toString(36)}`,I=Date.now(),v=new Set,R=new Set,M=null;t.resumeId?(M=y.load(t.resumeId)??FHe(y,t.resumeId),M||t.onWarning(`No saved session matches "${t.resumeId}" \u2014 starting fresh.`)):e.continueSession&&(M=y.loadLatest(e.workspace),M||t.onWarning("No previous session found in this directory \u2014 starting fresh."));let N=M;if(M)for(let ue of M.stats.filesChanged)v.add(ue);let $=null;try{let{MessageBroker:ue}=await Promise.resolve().then(()=>(ES(),uv));n&&o.platformUrl&&($=new ue(o.platformUrl,n,b))}catch{}let Q=i(()=>{if(!N)return;let ue=u.toJSON();N.history=ue.history,N.transcript=ue.transcript,N.branch=$c(e.workspace)||N.branch,N.model=u.getModel();try{y.save(N)}catch{}},"persist");u=new Hw({loop:{platformUrl:o.platformUrl,token:n,model:e.model,workspace:e.workspace,mode:ep(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 Mg(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:M?.history,initialTranscript:M?.transcript,sessionId:i(()=>N?.id,"sessionId"),onTurnStart(ue){N||(N=y.create(e.workspace,e.model,e.mode)),N.title||(N.title=LHe(ue)),y.addMessage(N,"user",ue)},async onTurnEnd(ue,U){for(let Y of ue.filesModified)v.add(Y);N&&y.updateStats(N,ue.tokensIn+ue.tokensOut,0,ue.filesModified),Q();try{let Y=await Promise.resolve().then(()=>(CE(),yE));Y.shouldNotify({enabled:s.value.notifyOnIdle,kind:"turn",durationMs:ue.duration,headless:!process.stdout.isTTY})&&Y.notifyTurnComplete(ue.duration,ue.filesModified.length)}catch{}if(ue.filesModified.length>0&&$)try{let{notifyAffectedSessions:Y}=await Promise.resolve().then(()=>(Tme(),bme));await Y($,ue.filesModified,b)}catch{}}});let re=new ef(()=>N?.id??b),j=[];u.on("event",ue=>{for(let U of re.map(ue))j.push(U);if(ue.type==="request_usage"&&j.push(Ub(N?.id??b,ue.usage)),ue.type==="run_complete"&&N){let U=ue.summary,Y=re.lastText.trim();j.push({type:"result",subtype:"success",is_error:!1,result:Y,session_id:N.id,num_turns:U.turns,duration_ms:U.duration,usage:{input_tokens:U.tokensIn,output_tokens:U.tokensOut,cached_tokens:U.tokensCached,thinking_tokens:0},cost_usd:U.costTracked?U.costUsd:oo(u.getModel(),U.tokensIn,U.tokensOut,0,{tokensCached:U.tokensCached}),is_estimated:!0,permission_denials:[],exit_code:0});let oe=j;j=[];try{y.appendEvents(N,oe)}catch{}}}),u.on("event",ue=>{if(ue.type!=="tool_call_start")return;let U=ue.args?.file_path??ue.args?.path;U&&(/^(read_file|file_read)$/.test(ue.name)&&R.add(String(U)),/^(edit_file|create_file|write_file|replace_in_file|patch_file|file_edit|file_write|file_create)$/.test(ue.name)&&v.add(String(U)))});let X=new bu({engine:c,getMode:i(()=>u.getPermissionMode(),"getMode"),onDenied:i(ue=>t.onBackgroundDenied?.(`background agent: ${ue.description} \u2014 ${ue.reason}`),"onDenied")}),pe=new Gw({workspace:e.workspace,model:e.model,token:n,userId:r?.user?.id,orgId:r?.org?.id,permissionDecider:X},t.renderer),ye=_me(),z=new bv({workspace:e.workspace,commands:ye,hooks:h,mcp:f,grantReadRoot:i(ue=>{try{p.grantReadRoot?.(ue)}catch{}},"grantReadRoot"),loadSettings:i(()=>At({workspace:e.workspace}),"loadSettings")});try{let ue=await z.reload();for(let U of Tv(ue))t.onWarning(U);for(let U of NS(ue.conflicts))t.onWarning(U)}catch(ue){t.onWarning(`plugins: ${ue.message}`);try{let{conflicts:U}=yv(ye,e.workspace);for(let Y of NS(U))t.onWarning(Y)}catch(U){t.onWarning(`custom commands: ${U.message}`)}}let le=i(()=>{try{ye.replaceDynamic("mcp-prompts",Sme(f))}catch{}},"syncMcpPrompts");f.on("change",le),le();let Ae=!1,we=i(async()=>{if(!Ae){Ae=!0,Q(),f.stop(),z.dispose();try{await h.run("SessionEnd",{sessionId:b,workspace:e.workspace,data:{reason:"exit"}})}catch{}}},"shutdown"),Fe=!1;return{session:u,settings:o,effective:s,engine:c,decider:p,backgroundDecider:X,mcp:f,hookRunner:h,sessionStore:y,subtaskManager:pe,registry:ye,extensions:z,sessionId:b,startedAt:I,filesRead:R,filesModified:v,getCurrentSession:i(()=>N,"getCurrentSession"),resumed:M,initialMode:l,messageBroker:$,pollMessages:i(async()=>{if(!$)return[];try{return(await $.pollMessages()??[]).map(U=>({from:U.from||U.senderId||"unknown",content:U.content||U.message||"",timestamp:U.timestamp?new Date(U.timestamp):new Date}))}catch{return[]}},"pollMessages"),persist:Q,buildCommandContext:i(ue=>({session:u,options:e,token:n,auth:r,sessionId:b,print:ue.print,printSuccess:ue.printSuccess,printError:ue.printError,printWarning:ue.printWarning,printStatus:ue.printStatus,clearScreen:ue.clearScreen,exit:ue.exit,submit:i(U=>u.submit(U),"submit"),submitWith:i((U,Y)=>u.submit(U,{run:Y}),"submitWith"),services:{sessionStore:y,hookRunner:h,subtaskManager:pe,renderer:t.renderer,getCurrentSession:i(()=>N,"getCurrentSession"),setCurrentSession:i(U=>{N=U},"setCurrentSession"),filesRead:R,filesModified:v,mcp:f,permissionEngine:c,foregroundDecider:p,backgroundDecider:X,effective:s,extensions:z},ui:ue.ui}),"buildCommandContext"),shutdown:we,resolveWorkspaceTrust:i(async ue=>{let U=fp(e.workspace,gp(h.getAllHooks(),s));if(!Fe){Fe=!0;let Y=U.trusted;if(!Y){let ke="not-now";try{ke=await ue(U)}catch{}if(ke==="trust"){try{ox(e.workspace,U)}catch(je){t.onWarning(`could not save workspace trust: ${je.message}`)}Y=!0}else t.onWarning(`Repository hooks${U.items.some(je=>je.kind==="status-line")?" and status line":""} are off for this session (workspace not trusted). /trust to review.`)}_=Y,h.setTrusted(Y);for(let ke of h.warnings)t.onWarning(ke);let oe=await h.run("SessionStart",{sessionId:b,workspace:e.workspace,data:{source:M?"resume":"startup",model:e.model,mode:l}}).catch(()=>null);for(let ke of oe?.errors??[])t.onWarning(ke);return oe?.additionalContext.length&&u.addSessionContext(oe.additionalContext.join(`
|
|
1014
1014
|
|
|
1015
|
-
`)),{...U,trusted:Y}}return{...U,trusted:_}},"resolveWorkspaceTrust"),isWorkspaceTrusted:i(()=>_,"isWorkspaceTrusted")}}async function xS(t,e,n={}){let r=0;try{let{listAllSkills:c}=await Promise.resolve().then(()=>(op(),m_));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.1.
|
|
1015
|
+
`)),{...U,trusted:Y}}return{...U,trusted:_}},"resolveWorkspaceTrust"),isWorkspaceTrusted:i(()=>_,"isWorkspaceTrusted")}}async function xS(t,e,n={}){let r=0;try{let{listAllSkills:c}=await Promise.resolve().then(()=>(op(),m_));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.1.2",model:t.session.getModel(),permissionMode:t.session.getPermissionMode(),workspace:e.workspace,branch:$c(e.workspace)||void 0,dirty:OS(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 LHe(t){let n=(t.split(`
|
|
1016
1016
|
`).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 FHe(t,e){let n=t.list().find(r=>r.id.startsWith(e));return n?t.load(n.id):null}function $c(t){try{return(0,g9.execSync)("git rev-parse --abbrev-ref HEAD",{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return""}}function OS(t){try{return(0,g9.execSync)("git status --porcelain",{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim().length>0}catch{return!1}}function Rv(t){let e=Math.floor(t/6e4),n=Math.floor(t%6e4/1e3);return e>0?`${e}m ${n}s`:`${n}s`}function MS(t,e){return Ime.relative(t,e)||e}var Ime,g9,BS=L(()=>{"use strict";Ime=k(require("node:path"),1),g9=require("node:child_process");Mn();ub();wt();i_();io();kf();T_();iue();due();Zg();Eme();Cv();Hg();wu();yme();u9();Ex();Q_();Jr();i(vv,"bootstrapSession");i(xS,"welcomeInfo");i(LHe,"titleFromPrompt");i(FHe,"findByPrefix");i($c,"gitBranch");i(OS,"gitDirty");i(Rv,"formatElapsed");i(MS,"relativeTo")});async function kv(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,wme.spawn)(r,s,{cwd:e.workspace,env:cs({FORCE_COLOR:"0",CI:process.env.CI}),stdio:["ignore","pipe","pipe"],detached:!n}),u=i(_=>{let E=_.toString("utf8");a+=E,a.length>PS*2&&(a=a.slice(-PS)),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:$He(t,a,_,l)})},"finish");c.on("error",_=>{a+=`
|
|
1017
1017
|
${_.message}`,h(127)}),c.on("close",_=>h(_))})}function $He(t,e,n,r=!1){let s=e.replace(/\x1b\[[0-9;?]*[A-Za-z]/g,"").replace(/\s+$/,"");s.length>PS&&(s=`[\u2026 ${s.length-PS} chars truncated \u2026]
|
|
1018
1018
|
`+s.slice(-PS));let o=r?"[killed]":`[exit ${n??"?"}]`;return`The user ran a shell command locally:
|
|
@@ -1033,7 +1033,7 @@ ${s}${s?`
|
|
|
1033
1033
|
`).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}. ${VHe(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(`
|
|
1034
1034
|
`))}};i(Gme,"createAccessiblePrompt");i(KHe,"formatApprovalPlain");i(VHe,"statusWord");i(zHe,"summarizeArgs")});var jme={};rt(jme,{checkForUpdate:()=>qme,gitBranch:()=>$c,gitDirty:()=>OS,isNewerVersion:()=>Wme,startPlainRepl:()=>JHe});function Yme(t,e){let n=" ".repeat(e);return t.split(`
|
|
1035
1035
|
`).map(r=>r&&n+r).join(`
|
|
1036
|
-
`)}async function qme(){if(Kl()||/^(1|true)$/i.test(process.env.MONKEYSCODE_NO_UPDATE_CHECK??""))return null;let t="1.1.
|
|
1036
|
+
`)}async function qme(){if(Kl()||/^(1|true)$/i.test(process.env.MONKEYSCODE_NO_UPDATE_CHECK??""))return null;let t="1.1.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||!Wme(r,t)?null:{latest:r,plain:`Update available: v${t} to v${r}. Run npm i -g monkeyscode-cli to update.`,styled:g.hex(Ho.accent)(` \u2B06 Update available: ${g.dim(`v${t}`)} \u2192 ${g.bold(`v${r}`)}`)+`
|
|
1037
1037
|
`+g.dim(` Run ${g.bold("npm i -g monkeyscode-cli")} to update.`)}}catch{return null}}function Wme(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 JHe({initialPrompt:t,options:e,token:n,auth:r,accessible:s,resumeId:o}){let a=it();s&&(g.level=0,a.ansi=!1,a.emoji=!1);let l=s?new Mv:null,c=i(J=>console.log(s?`Warning: ${J}`:g.yellow(` \u26A0 ${J}`)),"warn"),u,p=new Rc({verbose:e.verbose,showThinking:e.showThinking,sandboxed:e.sandbox,accessible:!!s}),f=await vv({options:e,token:n,auth:r,renderer:p,resumeId:o,prompt:s?Gme(()=>u,e.workspace):Ume(()=>u),onWarning:c,onBackgroundDenied:i(J=>console.log(s?`
|
|
1038
1038
|
Warning: ${J}`:g.yellow(`
|
|
1039
1039
|
\u26A0 ${J}`)),"onBackgroundDenied")}),{session:h,settings:_,hookRunner:E,mcp:y,registry:b,filesModified:I}=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:$c(e.workspace)}):console.log(LS(await xS(f,e),{columns:a.columns,unicode:a.unicode,color:a.ansi}));let v=s?null:p.getStatusBar({model:e.model,mode:e.mode,branch:$c(e.workspace),dirty:OS(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()?R:""})});let R="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=Y1();J&&console.log(s?J:g.dim(` ${J}`))}qme().then(J=>{J&&(console.log(""),console.log(s?J.plain:J.styled))}),await f.resolveWorkspaceTrust(async J=>{let Ee=yS(J);if(console.log(s?Ee.join(`
|
|
@@ -1073,9 +1073,9 @@ Cancelling the current run.`:`
|
|
|
1073
1073
|
`),"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 Ki(a.message)}}function P9(t,e){let n=At({workspace:t}).value.mcpServers?.[e],r=new Ru({server:e,url:n?.url??"http://localhost",store:Xo()}).logout();return console.log(r?g.green(` \u2713 Removed stored tokens for ${e}`):g.dim(` No stored tokens for ${e}`)),!0}function g7e(t,e={}){let n=e.home??uge.homedir(),r={added:[],skipped:[]},s=At({workspace:t,userDir:e.userDir}).value.mcpServers??{},o=i(f=>{try{return JSON.parse(Dm.readFileSync(f,"utf8"))}catch{return}},"readJson"),a=[],l=o(Qc.join(n,".claude.json"));l?.mcpServers&&a.push({from:"~/.claude.json",scope:"user",servers:l.mcpServers});let c=Dm.existsSync(t)?Dm.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(Qc.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=Mp(_);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 L9(t,e,n={}){if(e!=="claude")return Ki(`Unknown source "${e}". Supported: claude`);let r=g7e(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).
|
|
1074
1074
|
`)),!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
|
|
1075
1075
|
`)),!0}async function F9(t){let{ServeDecider:e}=await Promise.resolve().then(()=>(tge(),ege)),{McpServe:n}=await Promise.resolve().then(()=>(age(),ige)),{createPermissionEngine:r}=await Promise.resolve().then(()=>(io(),dp)),{ToolExecutor:s}=await Promise.resolve().then(()=>(CN(),y3)),{HookRunner:o}=await Promise.resolve().then(()=>(T_(),q3)),{evaluateWorkspaceTrust:a,requiresTrustHeadless:l,workspaceExecItems:c}=await Promise.resolve().then(()=>(wu(),lx)),{normalizePermissionMode:u}=await Promise.resolve().then(()=>(eo(),QQ)),{getPlatformPaths:p}=await Promise.resolve().then(()=>(Gt(),su)),{getAccessToken:f}=await Promise.resolve().then(()=>(An(),Kr)),h=Dm.realpathSync(Qc.resolve(t.workspace)),_=At({workspace:h}),E=i(Q=>process.stderr.write(`[mc mcp serve] ${Q}
|
|
1076
|
-
`),"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},_),I=new e({engine:b,mode:y,readOnly:t.readOnly,explicitAllow:t.allow}),v=await f().catch(()=>null)??"",R=new s({workspace:h,platformUrl:_.value.platformUrl??"",token:v}),M;t.hooks!==!1&&(M=new o(h,{effective:_,trustRepoHooks:!0}),l(_)&&!a(h,c(M.getAllHooks(),_)).trusted&&(M.setTrusted(!1),E("workspace not trusted: repository hooks are skipped (managed requireWorkspaceTrust)")));let N=new Date().toISOString().slice(0,10),$=new n({workspace:h,decider:I,executor:R,readOnly:t.readOnly,webEnabled:_.value.webEnabled!==!1&&!!v,isHidden:i(Q=>b.isToolHidden(Q),"isHidden"),hooks:M,log:E,tracePath:Qc.join(p().data,"traces",`mcp-serve-${N}.jsonl`),version:"1.1.
|
|
1076
|
+
`),"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},_),I=new e({engine:b,mode:y,readOnly:t.readOnly,explicitAllow:t.allow}),v=await f().catch(()=>null)??"",R=new s({workspace:h,platformUrl:_.value.platformUrl??"",token:v}),M;t.hooks!==!1&&(M=new o(h,{effective:_,trustRepoHooks:!0}),l(_)&&!a(h,c(M.getAllHooks(),_)).trusted&&(M.setTrusted(!1),E("workspace not trusted: repository hooks are skipped (managed requireWorkspaceTrust)")));let N=new Date().toISOString().slice(0,10),$=new n({workspace:h,decider:I,executor:R,readOnly:t.readOnly,webEnabled:_.value.webEnabled!==!1&&!!v,isHidden:i(Q=>b.isToolHidden(Q),"isHidden"),hooks:M,log:E,tracePath:Qc.join(p().data,"traces",`mcp-serve-${N}.jsonl`),version:"1.1.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 Dm,uge,Qc,u7e,dge,d7e,$9=L(()=>{"use strict";Ye();Dm=k(require("node:fs"),1),uge=k(require("node:os"),1),Qc=k(require("node:path"),1);WM();T9();Zg();px();dx();GA();Mn();eo();u7e=new RegExp("^https?://","i"),dge=new RegExp("\\$\\{"),d7e=new RegExp("token|secret|password|key|authorization|cookie","i");i(R9,"trustAdded");i(Lv,"targetOf");i(lge,"redact");i(Ki,"fail");i(p7e,"mcpListRows");i(k9,"mcpListCommand");i(D9,"mcpGetCommand");i(Fv,"parseScope");i(cge,"parsePairs");i(m7e,"buildAddEntry");i(N9,"mcpAddCommand");i(x9,"mcpAddJsonCommand");i(O9,"mcpRemoveCommand");i(M9,"mcpTestCommand");i(B9,"mcpLoginCommand");i(P9,"mcpLogoutCommand");i(g7e,"importClaudeMcp");i(L9,"mcpImportCommand");i(F9,"mcpServeCommand")});function vge(t,e=60){if(!Gc.ansi){console.log(`
|
|
1077
1077
|
${t}
|
|
1078
|
-
${"\u2500".repeat(e)}`);return}let n="\u2500".repeat(Math.max(0,e-t.length-4));console.log(""),console.log(` ${Rr.accent("\u2500\u2500")} ${Rr.bold(t)} ${Rr.accent(n)}`)}function Rge(t,e){let n=" "+t.map(s=>{let o=s.header;return wge(o,s.width,s.align||"left")}).join(" ");console.log(Gc.ansi?Rr.dim(n):n);let r=" "+t.map(s=>"\u2500".repeat(s.width)).join("\u2500\u2500");console.log(Gc.ansi?Rr.dim(r):r);for(let s of e){let o=" "+s.cells.map((a,l)=>{let c=t[l];return wge(a,c.width,c.align||"left")}).join(" ");s.dim&&Gc.ansi?o=Rr.dim(o):s.highlight&&Gc.ansi&&(o=Rr.accent(o)),console.log(o)}}function wge(t,e,n){let r=y7e(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 Qv(t){console.log(Gc.ansi?` ${Rr.dim(t)}`:` ${t}`)}function kge(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 q9(t){return t===0?Gc.ansi?Rr.success("Free"):"Free":`$${t.toFixed(t<1?4:2)}`}function y7e(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function US(){console.log("")}var S7e,Rr,Gc,aRt,lRt,Dge=L(()=>{"use strict";Ye();Or();S7e=k(require("node:readline"),1),Rr={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},Gc=it(),aRt=yt(Gc),lRt=bo(Gc);i(vge,"sectionHeader");i(Rge,"printTable");i(wge,"padCell");i(Qv,"hint");i(kge,"formatTokens");i(q9,"formatCost");i(y7e,"stripAnsi");i(US,"blank")});var $ge={};rt($ge,{default:()=>D7e});var D7e,Uge=L(()=>{D7e={name:"monkeyscode-cli",version:"1.1.
|
|
1078
|
+
${"\u2500".repeat(e)}`);return}let n="\u2500".repeat(Math.max(0,e-t.length-4));console.log(""),console.log(` ${Rr.accent("\u2500\u2500")} ${Rr.bold(t)} ${Rr.accent(n)}`)}function Rge(t,e){let n=" "+t.map(s=>{let o=s.header;return wge(o,s.width,s.align||"left")}).join(" ");console.log(Gc.ansi?Rr.dim(n):n);let r=" "+t.map(s=>"\u2500".repeat(s.width)).join("\u2500\u2500");console.log(Gc.ansi?Rr.dim(r):r);for(let s of e){let o=" "+s.cells.map((a,l)=>{let c=t[l];return wge(a,c.width,c.align||"left")}).join(" ");s.dim&&Gc.ansi?o=Rr.dim(o):s.highlight&&Gc.ansi&&(o=Rr.accent(o)),console.log(o)}}function wge(t,e,n){let r=y7e(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 Qv(t){console.log(Gc.ansi?` ${Rr.dim(t)}`:` ${t}`)}function kge(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 q9(t){return t===0?Gc.ansi?Rr.success("Free"):"Free":`$${t.toFixed(t<1?4:2)}`}function y7e(t){return t.replace(/\x1b\[[0-9;]*m/g,"")}function US(){console.log("")}var S7e,Rr,Gc,aRt,lRt,Dge=L(()=>{"use strict";Ye();Or();S7e=k(require("node:readline"),1),Rr={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},Gc=it(),aRt=yt(Gc),lRt=bo(Gc);i(vge,"sectionHeader");i(Rge,"printTable");i(wge,"padCell");i(Qv,"hint");i(kge,"formatTokens");i(q9,"formatCost");i(y7e,"stripAnsi");i(US,"blank")});var $ge={};rt($ge,{default:()=>D7e});var D7e,Uge=L(()=>{D7e={name:"monkeyscode-cli",version:"1.1.2",description:"MonkeysCode CLI \u2014 standalone terminal coding agent. Works independently of the IDE and Agent Manager.",license:"MIT",type:"module",main:"dist/monkeyscode-cli.cjs",bin:{mc:"dist/monkeyscode-cli.cjs",mcode:"dist/monkeyscode-cli.cjs",monkeyscode:"dist/monkeyscode-cli.cjs"},files:["dist/monkeyscode-cli.cjs","README.md","LICENSE"],scripts:{"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 zv,lfe=L(()=>{"use strict";zv=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 qS,n5,Jv,cfe=L(()=>{"use strict";qS=k(require("node:fs"),1),n5=k(require("node:path"),1),Jv=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=qS.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=qS.readdirSync(e,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()||s.name.startsWith(".")||s.name==="node_modules")continue;let o=n5.join(e,s.name);try{let a=qS.watch(o,(l,c)=>{!c||!this.running||this.onFileChange(n5.join(s.name,c))});this.watchers.push(a),this.watchDirectories(o,n+1)}catch{}}}catch{}}}});var dfe={};rt(dfe,{TriggerEngine:()=>r5});var Rl,WS,ufe,r5,pfe=L(()=>{"use strict";Rl=k(require("node:fs"),1),WS=k(require("node:path"),1),ufe=require("node:events");Ps();wt();io();lfe();cfe();r5=class extends ufe.EventEmitter{static{i(this,"TriggerEngine")}triggers=[];state=new Map;opts;cronScheduler;fileWatcher;statePath;activeRuns=new Map;constructor(e){super(),this.opts=e,this.statePath=WS.join(e.workspace,".monkeyscode",".trigger-state.json"),this.cronScheduler=new zv,this.fileWatcher=new Jv(e.workspace),this.loadState()}loadTriggers(){let e=WS.join(this.opts.workspace,".monkeyscode","triggers.json");if(!Rl.existsSync(e))return this.triggers=[],[];try{let n=JSON.parse(Rl.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=pt(),a=new _r({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:pp(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(`
|
|
1079
1079
|
`);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=WS.dirname(this.statePath);Rl.mkdirSync(e,{recursive:!0}),Rl.writeFileSync(this.statePath,JSON.stringify(Object.fromEntries(this.state),null,2))}catch{}}loadState(){try{if(Rl.existsSync(this.statePath)){let e=JSON.parse(Rl.readFileSync(this.statePath,"utf8"));this.state=new Map(Object.entries(e))}}catch{this.state=new Map}}}});var gfe={};rt(gfe,{GitHubWebhookServer:()=>s5});var mfe,oA,s5,ffe=L(()=>{"use strict";mfe=k(require("node:http"),1),oA=k(require("node:crypto"),1),s5=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=mfe.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"]||oA.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="+oA.createHmac("sha256",r).update(e).digest("hex");return oA.timingSafeEqual(Buffer.from(n),Buffer.from(s))}}});var FYe,uhe=L(()=>{"use strict";FYe=require("node:child_process")});var qYe,fhe=L(()=>{"use strict";qYe=require("node:crypto")});function gqe(t){return/^[a-z][a-z0-9_]*$/.test(t)||t.startsWith("mcp__")}function Lhe(t){let e=t.trim(),n=mqe[e];return n?{value:n,changes:[{from:e,to:n}],unmapped:[]}:gqe(e)||e==="*"?{value:e,changes:[],unmapped:[]}:{value:e,changes:[],unmapped:[e]}}function fqe(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=Lhe(n[1]),s=`${r.value}${n[2]??""}`;return{value:s,changes:s===e?[]:[{from:e,to:s}],unmapped:r.unmapped.length?[e]:[]}}function Fhe(t){let e=Array.isArray(t)?t:VD(t),n={value:[],changes:[],unmapped:[]};for(let r of e.map(s=>s.trim()).filter(Boolean)){let s=fqe(r);n.value.push(s.value),n.changes.push(...s.changes),n.unmapped.push(...s.unmapped)}return n}function hqe(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=>Lhe(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 y5(t){if(!t||t==="inherit")return{value:t,changes:[],unmapped:[]};let e=so(t);return Ro(t)?{value:e,changes:e===t?[]:[{from:t,to:e}],unmapped:[]}:{value:"inherit",changes:[{from:t,to:"inherit"}],unmapped:[`model ${t}`]}}function $he(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 _=y5(Uhe(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=Fhe(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(`
|
|
1080
1080
|
`)+n[3]+t.slice(n[0].length),e}function Uhe(t){return/^(['"]).*\1$/.test(t)?t.slice(1,-1):t}function Qhe(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=Fhe(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 Ghe(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=hqe(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 Hhe(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=>Uhe(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(`
|
|
1081
1081
|
`)+n[3]+t.slice(n[0].length),e}var mqe,Yhe=L(()=>{"use strict";Jr();mu();mqe={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(gqe,"isNative");i(Lhe,"translateToolName");i(fqe,"translateRule");i(Fhe,"translateToolList");i(hqe,"translateMatcher");i(y5,"translateModel");i($he,"translateFrontmatter");i(Uhe,"unquote");i(Qhe,"translatePermissions");i(Ghe,"translateHooks");i(Hhe,"translateCursorRule")});var zhe={};rt(zhe,{importClaude:()=>Whe,importCommand:()=>yqe,importCursor:()=>Khe,renderImportReport:()=>Vhe});function C5(t){try{let e=JSON.parse(Wa(dr.readFileSync(t,"utf8")));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function qhe(t){let e=[],n=i(r=>{let s;try{s=dr.readdirSync(r,{withFileTypes:!0})}catch{return}for(let o of s.sort((a,l)=>a.name.localeCompare(l.name))){let a=ln.join(r,o.name);o.isDirectory()?n(a):o.isFile()&&e.push(a)}},"walk");return n(t),e}function _qe(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 Whe(t){let e=new iR(t),n=e.ws,r=e.userScope?ln.join(t.home??b5.homedir(),".claude"):ln.join(n,".claude");for(let o of Aqe){let a=ln.join(r,o);for(let l of qhe(a)){let c=ln.relative(a,l),u=`${e.display(r)}/${o}/${c.split(ln.sep).join("/")}`,p=ln.join(e.targetRoot,o,c);if(/\.md$/i.test(l)){let f=$he(dr.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?[ln.join(r,"settings.json")]:[ln.join(r,"settings.json"),ln.join(r,"settings.local.json")];for(let o of s){let a=C5(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 _=Qhe(f);e.setting("permissions",_.value,h,_,c);break}case"hooks":{let _=Ghe(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 _=y5(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":{Sqe(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,Eqe[p]??"no MonkeysCode equivalent")}}}e.userScope||jhe(e,ln.join(n,".mcp.json"));for(let o of["CLAUDE.md",ln.join(".claude","CLAUDE.md")])dr.existsSync(ln.join(n,o))&&e.record(o,`${o} (read as-is)`,void 0);return e.finish()}function Sqe(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=Mp(o);if("error"in a){t.notMapped(`${n}.${s}`,a.error);continue}t.setting(`mcpServers.${s}`,a.entry,`${n}.${s}`,void 0,r)}}function jhe(t,e){let n=C5(e);if(!n)return;let r=n.mcpServers??n.servers;if(!r||typeof r!="object")return;let s=ln.join(t.ws,".monkeyscode","mcp.json"),o=C5(s)??{},a={...o.mcpServers??{}},l=t.display(e),c=!1;for(let[u,p]of Object.entries(r)){let f=`${l} ${u}`,h=Mp(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&&(dr.mkdirSync(ln.dirname(s),{recursive:!0}),dr.writeFileSync(s,JSON.stringify({...o,mcpServers:a},null,2)+`
|
|
@@ -1254,11 +1254,11 @@ ${n}
|
|
|
1254
1254
|
`));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>")}
|
|
1255
1255
|
`))}}i(mge,"mcpBrowseCommand");Gt();pv();Uw();Ye();var Age=k(require("node:path"),1),G9=k(require("node:fs"),1);Mn();wo();var Il=k(require("node:fs"),1),tA=k(require("node:path"),1);Mn();var f7e=".settings-migrated-v2";function $v(t){try{let e=JSON.parse(Wa(Il.readFileSync(t,"utf8")));return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}i($v,"readRaw");function h7e(t){let e={},n=[],r=$v(t.config);if(r){n.push(t.config);let l=jl(r);delete l.version,Object.assign(e,l)}let s=$v(t.permissions);if(s){n.push(t.permissions);let l=gC(s).permissions??{},c=e.permissions??{};e.permissions={...c,allow:Q9([...c.allow??[],...l.allow??[]]),deny:Q9([...c.deny??[],...l.deny??[]]),...!c.defaultMode&&l.defaultMode?{defaultMode:l.defaultMode}:{}}}let o=$v(t.mcp),a=o?fC(o):{};return a.mcpServers&&(n.push(t.mcp),e.mcpServers=a.mcpServers),{merged:e,sources:n}}i(h7e,"mergeLegacy");function A7e(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=Q9([...U9(a[c]),...U9(u)]);p.length!==U9(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(A7e,"underlay");function gge(t,e,n){let{merged:r,sources:s}=h7e(e);if(s.length===0)return{target:t,sources:s,keys:[],skipped:"no legacy files"};let o=$v(t)??{},{out:a,keys:l}=A7e(o,r);return l.length>0&&!n&&(Il.mkdirSync(tA.dirname(t),{recursive:!0}),Il.writeFileSync(t,JSON.stringify(a,null,2)+`
|
|
1256
1256
|
`)),{target:t,sources:s,keys:l}}i(gge,"migrateScope");function fge(t=gr()){let e=tA.join(t,f7e);if(Il.existsSync(e))return null;let n=cu(process.cwd(),t),r=null;try{r=gge(n.user,{config:n.legacy.userConfig,permissions:n.legacy.userPermissions,mcp:n.legacy.userMcp},!1),Il.mkdirSync(t,{recursive:!0}),Il.writeFileSync(e,new Date().toISOString()+`
|
|
1257
|
-
`)}catch{}return r}i(fge,"migrateUserSettingsOnce");function hge(t,e={}){let n=cu(tA.resolve(t));return gge(n.project,{config:n.legacy.projectConfig,permissions:n.legacy.projectPermissions,mcp:n.legacy.projectMcp},e.dryRun??!1)}i(hge,"migrateProjectSettings");function U9(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}i(U9,"strs");function Q9(t){return[...new Set(t)]}i(Q9,"dedupe");eo();var _7e=/(key|token|secret|password)$/i;function H9(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(H9,"normalizeKey");function E7e(t,e){switch(t){case"permissions.defaultMode":{let n=Zo(e);return n?[n,null]:[e,`must be one of: ${iD.join(", ")}`]}case"effort":{let n=Ms(e);return n?[n,null]:[e,`must be one of: ${lu.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(E7e,"validateSetting");function Y9(t,e){return _7e.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(Y9,"display");function _ge(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;_ge(s,o,n)}else{if(Array.isArray(s)&&s.length===0)continue;n.push([o,s])}}return n}i(_ge,"flatten");function Ege(t){let e=At({workspace:t.workspace}),n=_ge(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=>ja(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=>ja(l.source,l.file)).join(" + ")})`):"";console.log(` ${g.bold(s.padEnd(r))} ${Y9(s,o)}${a}`)}for(let s of e.warnings)console.log(g.yellow(` \u26A0 ${s}`));console.log("")}i(Ege,"configListCommand");function Sge(t,e){let n=H9(t),r=At({workspace:e.workspace}),s=Ag(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=>ja(a.source,a.file)).join(" + ")})`:"";console.log(`${Y9(n,s)}${o}`)}i(Sge,"configGetCommand");function yge(t,e,n){let r=Ige(n),s=H9(t);s==="model"&&/^(monkeyscode-auto(-max)?|auto-mode|auto-max)$/i.test(e.trim())&&(console.error(" \u26A0\uFE0F Auto mode can't be the default model. Pick it per session with /model auto-mode or --model auto-mode."),process.exit(1));let[o,a]=E7e(s,uD(e));a&&(console.error(` \u26A0\uFE0F ${s} ${a}`),process.exit(1));let l=fr(r,s,o,{workspace:n.workspace});l&&(console.error(` \u26A0\uFE0F ${l}`),process.exit(1)),console.log(` Set ${s} = ${Y9(s,o)} ${g.dim(`(${r}: ${Uv(ei(r,{workspace:n.workspace}))})`)}`)}i(yge,"configSetCommand");function Cge(t,e){let n=Ige(e),r=H9(t),s=du(n,r,{workspace:e.workspace});console.log(s?` Removed ${r} from ${n} settings.`:` ${r} was not set in ${n} settings.`)}i(Cge,"configUnsetCommand");function bge(t){let e=cu(t.workspace,gr()),n=i((s,o)=>{let a=G9.existsSync(o);console.log(` ${s.padEnd(10)} ${a?o:g.dim(o+" (not found)")}`)},"row");console.log("");for(let s of zA())n("Managed",s);n("Local",e.local),n("Project",e.project),n("User",e.user);let r=Object.values(e.legacy).filter(s=>G9.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(bge,"configPathCommand");function Tge(t){let e=hge(t.workspace,{dryRun:t.dryRun});if(e.skipped){console.log(` Nothing to migrate (${e.skipped}).`);return}if(e.keys.length===0){console.log(` ${Uv(e.target)} already contains everything from the legacy files.`);return}console.log(` ${t.dryRun?"Would migrate":"Migrated"} into ${Uv(e.target)}:`);for(let n of e.keys)console.log(` + ${n}`);console.log(g.dim(` From: ${e.sources.map(Uv).join(", ")}`)),t.dryRun||console.log(g.dim(" The legacy files were left in place; delete them once you have reviewed the result."))}i(Tge,"configMigrateCommand");function Ige(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(Ige,"resolveScope");function Uv(t){let e=process.env.HOME||process.env.USERPROFILE;return e&&t.startsWith(e)?"~"+t.slice(e.length):Age.normalize(t)}i(Uv,"tilde");wt();wo();eo();Mn();io();i_();Jr();Ye();Or();Jr();Bh();Dge();function Nge(t){let e=it().ansi,n=it().emoji;vge("Available Models"),US();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=vo.map(a=>{let l=tb(a.id,t),c=!l.allowed,p={monkeyscode:e?Rr.accent("MonkeysCode"):"MonkeysCode",anthropic:e?g.hex("#D97757")("Anthropic"):"Anthropic",google:e?g.hex("#4285F4")("Google"):"Google",openai:e?g.hex("#74AA9C")("OpenAI"):"OpenAI"}[a.provider]||a.provider,f=a.speed==="fast"?n?"\u26A1 Fast":"Fast":n?"\u{1F9E0} Deep":"Deep",h=a.costInputPerM===0?e?Rr.success("Free"):"Free":`${q9(a.costInputPerM)} / ${q9(a.costOutputPerM)}`,_=[];a.thinking&&_.push(n?"\u{1F4AD} Think":"Think"),c&&_.push(e?Rr.warning(`\u{1F512} ${l.requiredPlan}+`):`[${l.requiredPlan}+]`);let E=_.join(" ");return{cells:[e?c?Rr.dim(a.displayName):g.bold(a.displayName):a.displayName,p,kge(a.contextWindow),f,h,E],dim:c}}),o=aa().map(a=>{let l=a.locked===!0,c=c$(a),u=l?e?Rr.warning(`\u{1F512} ${a.requiredPlan??"paid"}+`):`[${a.requiredPlan??"paid"}+]`:"";return{cells:[e?l?Rr.dim(c):g.bold(c):c,e?Rr.accent("MonkeysCode"):"MonkeysCode","\u2014","Routed","Plan",u],dim:l}});if(Rge(r,[...o,...s]),US(),e){console.log(` ${Rr.dim("Aliases:")}`);for(let a of vo)if(a.aliases.length>0){let l=a.aliases.map(c=>Rr.accent(c)).join(Rr.dim(", "));console.log(` ${Rr.dim(" "+a.displayName+":")} ${l}`)}}else{console.log(" Aliases:");for(let a of vo)a.aliases.length>0&&console.log(` ${a.displayName}: ${a.aliases.join(", ")}`)}US(),Qv("Use --model <name|alias> to select a model"),aa().length>0&&Qv("Use --model auto-mode (or auto-max) for Auto mode: Capuchin, with the frontier model when it helps"),Qv("Use --model auto for your default model"),US()}i(Nge,"printModelList");var Oge=k(require("node:path"),1);Ye();Or();An();kf();RE();Q_();no();var xge=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Mge(){let t=it(),e=yt(t),n=t.ansi,r=Un();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 Br();if(u){let p=await fetch(`${xge}/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=Nm(s.tokensIn),c=Nm(s.tokensOut);if(console.log(` Tokens: ${l} input, ${c} output`),s.tokensThinking>0&&console.log(` Thinking: ${Nm(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.");try{let u=await Br();if(u){let p=await fetch(`${xge}/v1/usage/auto-summary`,{headers:{Authorization:`Bearer ${u}`},signal:AbortSignal.timeout(4e3)}),f=p.ok?e8(await p.json()):void 0;if(f)for(let h of C7e(f))console.log(n?g.dim(h):h)}}catch{}console.log("")}i(Mge,"usageCommand");function C7e(t,e=Date.now()){let n=[` ${z4(t)}`];if(t.locked){let s=Z4(t);return s&&n.push(` Upgrade: ${s}`),n}let r=J4(t,e);return r&&(n.push(` ${r}`),(t.premium_pool?.remaining??1)<=0&&n.push(` ${X4}`)),n}i(C7e,"autoUsageLines");function Bge(t,e={}){let n=e.log??(u=>console.log(u)),r=e.store??new Cs,s=r.list(Number.MAX_SAFE_INTEGER),o;if(!t||t==="last"){let u=Oge.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=EB(a),c=Qb(l);if(e.json)return n(JSON.stringify({session_id:o,...c},null,2)),0;for(let u of b7e(o,c))n(u);return 0}i(Bge,"sessionUsageCommand");function b7e(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: ${Nm(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: ${Nm(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)} ${Nm(s.chars).padStart(6)} chars (~${Nm(Math.round(s.chars/4))} tokens, before request ${s.request})`)}return n.push(""),n}i(b7e,"formatSessionReport");function Nm(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:String(t)}i(Nm,"formatTokenCount");var Na=k(require("node:fs"),1),Qge=k(require("node:path"),1),xm=require("node:child_process");Ye();var nA=k(require("node:fs"),1),Gv=k(require("node:path"),1);Gt();var T7e="https://monkeyscode.com/api/latest-version",I7e="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",w7e=4*60*60*1e3;function Fge(){let t=et();return Gv.join(t.config,"update-check")}i(Fge,"getCachePath");function v7e(){try{let t=nA.readFileSync(Fge(),"utf8");return JSON.parse(t)}catch{return null}}i(v7e,"readCache");function W9(t){try{let e=Fge();nA.mkdirSync(Gv.dirname(e),{recursive:!0}),nA.writeFileSync(e,JSON.stringify(t))}catch{}}i(W9,"writeCache");function Pge(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(Pge,"isNewerVersion");function R7e(){let t=process.platform,e=process.arch;return`cli-${t}-${e}`}i(R7e,"getAssetKey");async function j9(t,e=!1){if(!e){let n=v7e();if(n&&Date.now()-n.lastCheck<w7e)return n.latestVersion&&Pge(n.latestVersion,t)?{version:n.latestVersion,currentVersion:t,downloadUrl:n.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let n=await Lge(T7e);if(n||(n=await Lge(I7e)),!n)return W9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let r=n.productVersion||n.version,s=R7e(),o=n.assets?.[s],a=o?.url||"https://monkeyscode.com/download";return W9({lastCheck:Date.now(),latestVersion:r,downloadUrl:a}),r&&Pge(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 W9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}i(j9,"checkForUpdate");async function Lge(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(Lge,"fetchManifest");function K9(){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(K9,"detectInstallMethod");async function Gge(t){let n=(await Promise.resolve().then(()=>(Uge(),$ge)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"1.1.1";if(t.rollback){await $7e(n);return}if(t.check){await N7e(n);return}await x7e(n,t.version)}i(Gge,"updateCommand");async function N7e(t){console.log(g.dim(` Current version: v${t}`)),console.log(g.dim(" Checking for updates...")),console.log("");let e=await j9(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(N7e,"checkOnly");async function x7e(t,e){let n=K9();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 O7e(e);break;case"homebrew":await M7e();break;case"winget":await B7e();break;case"chocolatey":await P7e();break;case"scoop":await L7e();break;case"binary":await F7e(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(x7e,"performUpdate");async function O7e(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,xm.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(O7e,"updateViaNpm");async function M7e(){console.log(g.dim(" Running: brew upgrade monkeyscode")),(0,xm.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Homebrew"))}i(M7e,"updateViaHomebrew");async function B7e(){console.log(g.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,xm.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via winget"))}i(B7e,"updateViaWinget");async function P7e(){console.log(g.dim(" Running: choco upgrade monkeyscode-cli")),(0,xm.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Chocolatey"))}i(P7e,"updateViaChocolatey");async function L7e(){console.log(g.dim(" Running: scoop update monkeyscode")),(0,xm.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Scoop"))}i(L7e,"updateViaScoop");async function F7e(t,e){let n=await j9(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{Na.copyFileSync(s,o),console.log(g.dim(` Backed up current binary to: ${Qge.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{Na.writeFileSync(s,l),Na.chmodSync(s,493),console.log(g.green(` \u2705 Updated to v${n?.version||e}`))}catch(c){try{Na.copyFileSync(o,s),console.log(g.yellow(" Restored backup after failed update"))}catch{}throw c}}i(F7e,"updateViaBinaryDownload");async function $7e(t){if(console.log(""),console.log(g.bold(" \u23EA Rollback")),console.log(""),K9()==="binary"){let n=process.execPath+".backup";if(!Na.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{Na.copyFileSync(n,process.execPath),Na.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($7e,"rollback");Ye();var rA=k(require("node:fs"),1),Yv=k(require("node:path"),1),qge=k(require("node:crypto"),1);Gt();var Hc=!0,V9="",Vi=[],Hge=!1,U7e="https://monkeyscode.com/api/telemetry",Hv=50,Q7e=6e4;function Wge(){let t=et();return Yv.join(t.config,"telemetry.json")}i(Wge,"getConfigPath");function z9(){try{let t=rA.readFileSync(Wge(),"utf8");return JSON.parse(t)}catch{let t={enabled:!0,clientId:G7e()};return J9(t),t}}i(z9,"loadConfig");function J9(t){try{let e=Wge();rA.mkdirSync(Yv.dirname(e),{recursive:!0}),rA.writeFileSync(e,JSON.stringify(t,null,2))}catch{}}i(J9,"saveConfig");function G7e(){return qge.randomUUID()}i(G7e,"generateClientId");function jge(){if(Hge)return;if(Hge=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Hc=!1;return}let t=z9();Hc=t.enabled,V9=t.clientId,Hc&&(setInterval(()=>Yge(),Q7e).unref(),process.on("beforeExit",()=>Yge()))}i(jge,"initTelemetry");function Kge(){return Hc}i(Kge,"isTelemetryEnabled");function Vge(){Hc=!0;let t=z9();t.enabled=!0,J9(t)}i(Vge,"enableTelemetry");function zge(){Hc=!1,Vi=[];let t=z9();t.enabled=!1,J9(t)}i(zge,"disableTelemetry");function X9(t,e={}){Hc&&(Vi.push({name:t,properties:e,timestamp:new Date().toISOString()}),Vi.length>Hv&&(Vi=Vi.slice(-Hv)))}i(X9,"trackEvent");async function Yge(){if(!Hc||Vi.length===0)return;let t=[...Vi];Vi=[];let e=Os(),r={clientId:V9,cliVersion:"1.1.1",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:t};try{await fetch(U7e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)})}catch{Vi.unshift(...t),Vi.length>Hv&&(Vi=Vi.slice(-Hv))}}i(Yge,"flushEvents");function Jge(){let t=Os();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 1.1.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: ${Hc?"ENABLED":"DISABLED"}`,`Client ID: ${V9||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
1258
|
-
`)}i(Jge,"getCollectedDataSummary");async function Xge(t){switch(t){case"enable":Vge(),console.log(""),console.log(g.green(" \u2705 Telemetry enabled")),console.log(g.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":zge(),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(Jge()),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)")):Kge()?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(Xge,"telemetryCommand");var wl=k(require("node:fs"),1),QS=k(require("node:path"),1);Ye();Gt();async function Zge(t,e){let n=Os(),r="1.1.
|
|
1257
|
+
`)}catch{}return r}i(fge,"migrateUserSettingsOnce");function hge(t,e={}){let n=cu(tA.resolve(t));return gge(n.project,{config:n.legacy.projectConfig,permissions:n.legacy.projectPermissions,mcp:n.legacy.projectMcp},e.dryRun??!1)}i(hge,"migrateProjectSettings");function U9(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}i(U9,"strs");function Q9(t){return[...new Set(t)]}i(Q9,"dedupe");eo();var _7e=/(key|token|secret|password)$/i;function H9(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(H9,"normalizeKey");function E7e(t,e){switch(t){case"permissions.defaultMode":{let n=Zo(e);return n?[n,null]:[e,`must be one of: ${iD.join(", ")}`]}case"effort":{let n=Ms(e);return n?[n,null]:[e,`must be one of: ${lu.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(E7e,"validateSetting");function Y9(t,e){return _7e.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(Y9,"display");function _ge(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;_ge(s,o,n)}else{if(Array.isArray(s)&&s.length===0)continue;n.push([o,s])}}return n}i(_ge,"flatten");function Ege(t){let e=At({workspace:t.workspace}),n=_ge(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=>ja(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=>ja(l.source,l.file)).join(" + ")})`):"";console.log(` ${g.bold(s.padEnd(r))} ${Y9(s,o)}${a}`)}for(let s of e.warnings)console.log(g.yellow(` \u26A0 ${s}`));console.log("")}i(Ege,"configListCommand");function Sge(t,e){let n=H9(t),r=At({workspace:e.workspace}),s=Ag(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=>ja(a.source,a.file)).join(" + ")})`:"";console.log(`${Y9(n,s)}${o}`)}i(Sge,"configGetCommand");function yge(t,e,n){let r=Ige(n),s=H9(t);s==="model"&&/^(monkeyscode-auto(-max)?|auto-mode|auto-max)$/i.test(e.trim())&&(console.error(" \u26A0\uFE0F Auto mode can't be the default model. Pick it per session with /model auto-mode or --model auto-mode."),process.exit(1));let[o,a]=E7e(s,uD(e));a&&(console.error(` \u26A0\uFE0F ${s} ${a}`),process.exit(1));let l=fr(r,s,o,{workspace:n.workspace});l&&(console.error(` \u26A0\uFE0F ${l}`),process.exit(1)),console.log(` Set ${s} = ${Y9(s,o)} ${g.dim(`(${r}: ${Uv(ei(r,{workspace:n.workspace}))})`)}`)}i(yge,"configSetCommand");function Cge(t,e){let n=Ige(e),r=H9(t),s=du(n,r,{workspace:e.workspace});console.log(s?` Removed ${r} from ${n} settings.`:` ${r} was not set in ${n} settings.`)}i(Cge,"configUnsetCommand");function bge(t){let e=cu(t.workspace,gr()),n=i((s,o)=>{let a=G9.existsSync(o);console.log(` ${s.padEnd(10)} ${a?o:g.dim(o+" (not found)")}`)},"row");console.log("");for(let s of zA())n("Managed",s);n("Local",e.local),n("Project",e.project),n("User",e.user);let r=Object.values(e.legacy).filter(s=>G9.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(bge,"configPathCommand");function Tge(t){let e=hge(t.workspace,{dryRun:t.dryRun});if(e.skipped){console.log(` Nothing to migrate (${e.skipped}).`);return}if(e.keys.length===0){console.log(` ${Uv(e.target)} already contains everything from the legacy files.`);return}console.log(` ${t.dryRun?"Would migrate":"Migrated"} into ${Uv(e.target)}:`);for(let n of e.keys)console.log(` + ${n}`);console.log(g.dim(` From: ${e.sources.map(Uv).join(", ")}`)),t.dryRun||console.log(g.dim(" The legacy files were left in place; delete them once you have reviewed the result."))}i(Tge,"configMigrateCommand");function Ige(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(Ige,"resolveScope");function Uv(t){let e=process.env.HOME||process.env.USERPROFILE;return e&&t.startsWith(e)?"~"+t.slice(e.length):Age.normalize(t)}i(Uv,"tilde");wt();wo();eo();Mn();io();i_();Jr();Ye();Or();Jr();Bh();Dge();function Nge(t){let e=it().ansi,n=it().emoji;vge("Available Models"),US();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=vo.map(a=>{let l=tb(a.id,t),c=!l.allowed,p={monkeyscode:e?Rr.accent("MonkeysCode"):"MonkeysCode",anthropic:e?g.hex("#D97757")("Anthropic"):"Anthropic",google:e?g.hex("#4285F4")("Google"):"Google",openai:e?g.hex("#74AA9C")("OpenAI"):"OpenAI"}[a.provider]||a.provider,f=a.speed==="fast"?n?"\u26A1 Fast":"Fast":n?"\u{1F9E0} Deep":"Deep",h=a.costInputPerM===0?e?Rr.success("Free"):"Free":`${q9(a.costInputPerM)} / ${q9(a.costOutputPerM)}`,_=[];a.thinking&&_.push(n?"\u{1F4AD} Think":"Think"),c&&_.push(e?Rr.warning(`\u{1F512} ${l.requiredPlan}+`):`[${l.requiredPlan}+]`);let E=_.join(" ");return{cells:[e?c?Rr.dim(a.displayName):g.bold(a.displayName):a.displayName,p,kge(a.contextWindow),f,h,E],dim:c}}),o=aa().map(a=>{let l=a.locked===!0,c=c$(a),u=l?e?Rr.warning(`\u{1F512} ${a.requiredPlan??"paid"}+`):`[${a.requiredPlan??"paid"}+]`:"";return{cells:[e?l?Rr.dim(c):g.bold(c):c,e?Rr.accent("MonkeysCode"):"MonkeysCode","\u2014","Routed","Plan",u],dim:l}});if(Rge(r,[...o,...s]),US(),e){console.log(` ${Rr.dim("Aliases:")}`);for(let a of vo)if(a.aliases.length>0){let l=a.aliases.map(c=>Rr.accent(c)).join(Rr.dim(", "));console.log(` ${Rr.dim(" "+a.displayName+":")} ${l}`)}}else{console.log(" Aliases:");for(let a of vo)a.aliases.length>0&&console.log(` ${a.displayName}: ${a.aliases.join(", ")}`)}US(),Qv("Use --model <name|alias> to select a model"),aa().length>0&&Qv("Use --model auto-mode (or auto-max) for Auto mode: Capuchin, with the frontier model when it helps"),Qv("Use --model auto for your default model"),US()}i(Nge,"printModelList");var Oge=k(require("node:path"),1);Ye();Or();An();kf();RE();Q_();no();var xge=process.env.MONKEYSCODE_AUTH_URL||"https://api.monkeyscode.com";async function Mge(){let t=it(),e=yt(t),n=t.ansi,r=Un();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 Br();if(u){let p=await fetch(`${xge}/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=Nm(s.tokensIn),c=Nm(s.tokensOut);if(console.log(` Tokens: ${l} input, ${c} output`),s.tokensThinking>0&&console.log(` Thinking: ${Nm(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.");try{let u=await Br();if(u){let p=await fetch(`${xge}/v1/usage/auto-summary`,{headers:{Authorization:`Bearer ${u}`},signal:AbortSignal.timeout(4e3)}),f=p.ok?e8(await p.json()):void 0;if(f)for(let h of C7e(f))console.log(n?g.dim(h):h)}}catch{}console.log("")}i(Mge,"usageCommand");function C7e(t,e=Date.now()){let n=[` ${z4(t)}`];if(t.locked){let s=Z4(t);return s&&n.push(` Upgrade: ${s}`),n}let r=J4(t,e);return r&&(n.push(` ${r}`),(t.premium_pool?.remaining??1)<=0&&n.push(` ${X4}`)),n}i(C7e,"autoUsageLines");function Bge(t,e={}){let n=e.log??(u=>console.log(u)),r=e.store??new Cs,s=r.list(Number.MAX_SAFE_INTEGER),o;if(!t||t==="last"){let u=Oge.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=EB(a),c=Qb(l);if(e.json)return n(JSON.stringify({session_id:o,...c},null,2)),0;for(let u of b7e(o,c))n(u);return 0}i(Bge,"sessionUsageCommand");function b7e(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: ${Nm(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: ${Nm(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)} ${Nm(s.chars).padStart(6)} chars (~${Nm(Math.round(s.chars/4))} tokens, before request ${s.request})`)}return n.push(""),n}i(b7e,"formatSessionReport");function Nm(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(0)}K`:String(t)}i(Nm,"formatTokenCount");var Na=k(require("node:fs"),1),Qge=k(require("node:path"),1),xm=require("node:child_process");Ye();var nA=k(require("node:fs"),1),Gv=k(require("node:path"),1);Gt();var T7e="https://monkeyscode.com/api/latest-version",I7e="https://storage.googleapis.com/colibriv-capuchin-serving-editor-releases/cli/latest-version.json",w7e=4*60*60*1e3;function Fge(){let t=et();return Gv.join(t.config,"update-check")}i(Fge,"getCachePath");function v7e(){try{let t=nA.readFileSync(Fge(),"utf8");return JSON.parse(t)}catch{return null}}i(v7e,"readCache");function W9(t){try{let e=Fge();nA.mkdirSync(Gv.dirname(e),{recursive:!0}),nA.writeFileSync(e,JSON.stringify(t))}catch{}}i(W9,"writeCache");function Pge(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(Pge,"isNewerVersion");function R7e(){let t=process.platform,e=process.arch;return`cli-${t}-${e}`}i(R7e,"getAssetKey");async function j9(t,e=!1){if(!e){let n=v7e();if(n&&Date.now()-n.lastCheck<w7e)return n.latestVersion&&Pge(n.latestVersion,t)?{version:n.latestVersion,currentVersion:t,downloadUrl:n.downloadUrl||"https://monkeyscode.com/download",publishedAt:"",commit:"",quality:"stable"}:null}try{let n=await Lge(T7e);if(n||(n=await Lge(I7e)),!n)return W9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null;let r=n.productVersion||n.version,s=R7e(),o=n.assets?.[s],a=o?.url||"https://monkeyscode.com/download";return W9({lastCheck:Date.now(),latestVersion:r,downloadUrl:a}),r&&Pge(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 W9({lastCheck:Date.now(),latestVersion:null,downloadUrl:null}),null}}i(j9,"checkForUpdate");async function Lge(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(Lge,"fetchManifest");function K9(){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(K9,"detectInstallMethod");async function Gge(t){let n=(await Promise.resolve().then(()=>(Uge(),$ge)).catch(()=>({default:{version:"0.0.0"}}))).default.version||"1.1.2";if(t.rollback){await $7e(n);return}if(t.check){await N7e(n);return}await x7e(n,t.version)}i(Gge,"updateCommand");async function N7e(t){console.log(g.dim(` Current version: v${t}`)),console.log(g.dim(" Checking for updates...")),console.log("");let e=await j9(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(N7e,"checkOnly");async function x7e(t,e){let n=K9();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 O7e(e);break;case"homebrew":await M7e();break;case"winget":await B7e();break;case"chocolatey":await P7e();break;case"scoop":await L7e();break;case"binary":await F7e(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(x7e,"performUpdate");async function O7e(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,xm.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(O7e,"updateViaNpm");async function M7e(){console.log(g.dim(" Running: brew upgrade monkeyscode")),(0,xm.execSync)("brew upgrade monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Homebrew"))}i(M7e,"updateViaHomebrew");async function B7e(){console.log(g.dim(" Running: winget upgrade MonkeysCode.CLI")),(0,xm.execSync)("winget upgrade MonkeysCode.CLI",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via winget"))}i(B7e,"updateViaWinget");async function P7e(){console.log(g.dim(" Running: choco upgrade monkeyscode-cli")),(0,xm.execSync)("choco upgrade monkeyscode-cli -y",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Chocolatey"))}i(P7e,"updateViaChocolatey");async function L7e(){console.log(g.dim(" Running: scoop update monkeyscode")),(0,xm.execSync)("scoop update monkeyscode",{stdio:"inherit"}),console.log(g.green(" \u2705 Updated via Scoop"))}i(L7e,"updateViaScoop");async function F7e(t,e){let n=await j9(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{Na.copyFileSync(s,o),console.log(g.dim(` Backed up current binary to: ${Qge.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{Na.writeFileSync(s,l),Na.chmodSync(s,493),console.log(g.green(` \u2705 Updated to v${n?.version||e}`))}catch(c){try{Na.copyFileSync(o,s),console.log(g.yellow(" Restored backup after failed update"))}catch{}throw c}}i(F7e,"updateViaBinaryDownload");async function $7e(t){if(console.log(""),console.log(g.bold(" \u23EA Rollback")),console.log(""),K9()==="binary"){let n=process.execPath+".backup";if(!Na.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{Na.copyFileSync(n,process.execPath),Na.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($7e,"rollback");Ye();var rA=k(require("node:fs"),1),Yv=k(require("node:path"),1),qge=k(require("node:crypto"),1);Gt();var Hc=!0,V9="",Vi=[],Hge=!1,U7e="https://monkeyscode.com/api/telemetry",Hv=50,Q7e=6e4;function Wge(){let t=et();return Yv.join(t.config,"telemetry.json")}i(Wge,"getConfigPath");function z9(){try{let t=rA.readFileSync(Wge(),"utf8");return JSON.parse(t)}catch{let t={enabled:!0,clientId:G7e()};return J9(t),t}}i(z9,"loadConfig");function J9(t){try{let e=Wge();rA.mkdirSync(Yv.dirname(e),{recursive:!0}),rA.writeFileSync(e,JSON.stringify(t,null,2))}catch{}}i(J9,"saveConfig");function G7e(){return qge.randomUUID()}i(G7e,"generateClientId");function jge(){if(Hge)return;if(Hge=!0,process.env.DO_NOT_TRACK==="1"||process.env.DO_NOT_TRACK==="true"){Hc=!1;return}let t=z9();Hc=t.enabled,V9=t.clientId,Hc&&(setInterval(()=>Yge(),Q7e).unref(),process.on("beforeExit",()=>Yge()))}i(jge,"initTelemetry");function Kge(){return Hc}i(Kge,"isTelemetryEnabled");function Vge(){Hc=!0;let t=z9();t.enabled=!0,J9(t)}i(Vge,"enableTelemetry");function zge(){Hc=!1,Vi=[];let t=z9();t.enabled=!1,J9(t)}i(zge,"disableTelemetry");function X9(t,e={}){Hc&&(Vi.push({name:t,properties:e,timestamp:new Date().toISOString()}),Vi.length>Hv&&(Vi=Vi.slice(-Hv)))}i(X9,"trackEvent");async function Yge(){if(!Hc||Vi.length===0)return;let t=[...Vi];Vi=[];let e=Os(),r={clientId:V9,cliVersion:"1.1.2",os:e.os,arch:e.arch,shell:e.shell,nodeVersion:process.version,events:t};try{await fetch(U7e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(5e3)})}catch{Vi.unshift(...t),Vi.length>Hv&&(Vi=Vi.slice(-Hv))}}i(Yge,"flushEvents");function Jge(){let t=Os();return["MonkeysCode Telemetry \u2014 Data Collection Summary","\u2500".repeat(50),"","\u2705 Collected (if enabled):"," \u2022 CLI version: 1.1.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: ${Hc?"ENABLED":"DISABLED"}`,`Client ID: ${V9||"not initialized"}`,"","Disable: mc telemetry disable","Or set: DO_NOT_TRACK=1"].join(`
|
|
1258
|
+
`)}i(Jge,"getCollectedDataSummary");async function Xge(t){switch(t){case"enable":Vge(),console.log(""),console.log(g.green(" \u2705 Telemetry enabled")),console.log(g.dim(" Thank you for helping improve MonkeysCode!")),console.log("");break;case"disable":zge(),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(Jge()),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)")):Kge()?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(Xge,"telemetryCommand");var wl=k(require("node:fs"),1),QS=k(require("node:path"),1);Ye();Gt();async function Zge(t,e){let n=Os(),r="1.1.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=q7e();a?(s.crashLog=a,console.log(g.dim(" \u{1F4CE} Attached latest crash report"))):console.log(g.dim(" No crash reports found"))}if(await H7e(s))console.log(g.green(" \u2705 Bug report submitted")),console.log(g.dim(" Thank you! Our team will review your report."));else{let a=Y7e(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(Zge,"bugCommand");async function H7e(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(H7e,"submitReport");function Y7e(t){let e=et(),n=QS.join(e.config,"bug-reports");wl.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=QS.join(n,`${r}.json`);return wl.writeFileSync(s,JSON.stringify(t,null,2)),s}i(Y7e,"saveReportLocally");function q7e(){try{let t=et(),e=QS.join(t.config,"crashes");if(!wl.existsSync(e))return null;let n=wl.readdirSync(e).filter(r=>r.endsWith(".log")).sort().reverse();return n.length===0?null:wl.readFileSync(QS.join(e,n[0]),"utf8")}catch{return null}}i(q7e,"getLatestCrashLog");var Om=k(require("node:fs"),1),Z9=k(require("node:path"),1);Ye();Gt();Or();function efe(){let t=et(),e=Z9.join(t.config,"config.json");return!Om.existsSync(e)}i(efe,"isFirstRun");function W7e(){let e=et().config,n=Z9.join(e,"config.json");Om.mkdirSync(e,{recursive:!0}),Om.existsSync(n)||Om.writeFileSync(n,JSON.stringify({onboardingComplete:!0,createdAt:new Date().toISOString()},null,2))}i(W7e,"markOnboardingComplete");async function tfe(){let t=it(),e=Os();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(`
|
|
1259
1259
|
`)[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(""),W7e()}i(tfe,"runOnboarding");hm();var yd=k(require("node:fs"),1),qv=k(require("node:path"),1);Gt();var nfe=[];function sfe(){process.on("uncaughtException",t=>{rfe(t,"uncaughtException"),console.error(`
|
|
1260
1260
|
\u{1F4A5} MonkeysCode crashed. Report saved to ~/.monkeyscode/crashes/`),console.error(` ${t.message}
|
|
1261
|
-
`),process.exit(1)}),process.on("unhandledRejection",t=>{let e=t instanceof Error?t:new Error(String(t));rfe(e,"unhandledRejection")})}i(sfe,"installCrashHandler");function j7e(){let t=et();return qv.join(t.config,"crashes")}i(j7e,"getCrashDir");function rfe(t,e){try{let n=j7e();yd.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=qv.join(n,`${r}.log`),o=Os(),l=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 1.1.
|
|
1261
|
+
`),process.exit(1)}),process.on("unhandledRejection",t=>{let e=t instanceof Error?t:new Error(String(t));rfe(e,"unhandledRejection")})}i(sfe,"installCrashHandler");function j7e(){let t=et();return qv.join(t.config,"crashes")}i(j7e,"getCrashDir");function rfe(t,e){try{let n=j7e();yd.mkdirSync(n,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),s=qv.join(n,`${r}.log`),o=Os(),l=["\u2550".repeat(60)," MONKEYSCODE CLI CRASH REPORT","\u2550".repeat(60),"",`Timestamp: ${new Date().toISOString()}`,`Type: ${e}`,"CLI Version: 1.1.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",nfe.length>0?nfe.map((c,u)=>` ${u+1}. ${c}`).join(`
|
|
1262
1262
|
`):" (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(`
|
|
1263
1263
|
`);yd.writeFileSync(s,l),K7e(n,20)}catch{}}i(rfe,"writeCrashReport");function K7e(t,e){try{let n=yd.readdirSync(t).filter(r=>r.endsWith(".log")).sort().reverse();for(let r=e;r<n.length;r++)yd.unlinkSync(qv.join(t,n[r]))}catch{}}i(K7e,"pruneOldReports");wS();Ye();var zs=k(require("node:fs"),1),xa=k(require("node:path"),1),jv=k(require("node:crypto"),1),Kv=require("node:child_process");Gt();function ofe(t,e){let n=t.split(`
|
|
1264
1264
|
`);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 V7e(n);case"python":return z7e(n);default:return J7e(n,50)}}i(ofe,"chunkCode");function V7e(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(`
|
|
@@ -1436,7 +1436,7 @@ ${t}`,r}i(cqe,"buildBugfindPrompt");function xhe(t){return Iw(t).map(({severity:
|
|
|
1436
1436
|
|
|
1437
1437
|
${o}
|
|
1438
1438
|
|
|
1439
|
-
${S5(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(dqe,"postReviewComments");function Bhe(t){try{let e=(0,Fm.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(Bhe,"getGitRemote");function Phe(){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=At({workspace:process.cwd()}).value;return typeof t.githubToken=="string"&&t.githubToken?t.githubToken:typeof t.gitlabToken=="string"&&t.gitlabToken?t.gitlabToken:null}i(Phe,"getGitToken");function pqe(t,e){let n=[];function s(o){if(n.length>=50)return;let a=zi.readdirSync(o,{withFileTypes:!0});for(let l of a){if(n.length>=50)return;let c=$m.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(pqe,"collectFiles");sfe();jge();jQ()&&(g.level=0);globalThis.__mcChalk=g;var gR="1.1.
|
|
1439
|
+
${S5(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(dqe,"postReviewComments");function Bhe(t){try{let e=(0,Fm.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(Bhe,"getGitRemote");function Phe(){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=At({workspace:process.cwd()}).value;return typeof t.githubToken=="string"&&t.githubToken?t.githubToken:typeof t.gitlabToken=="string"&&t.gitlabToken?t.gitlabToken:null}i(Phe,"getGitToken");function pqe(t,e){let n=[];function s(o){if(n.length>=50)return;let a=zi.readdirSync(o,{withFileTypes:!0});for(let l of a){if(n.length>=50)return;let c=$m.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(pqe,"collectFiles");sfe();jge();jQ()&&(g.level=0);globalThis.__mcChalk=g;var gR="1.1.2",Qm="auto";fge();function fAe(t){let e=pt({workspace:t});return{defaultModel:e.defaultModel,permissionMode:e.permissionMode,effort:e.effort}}i(fAe,"loadConfig");var dt=new _Q;dt.name("mc").description(`MonkeysCode CLI \u2014 standalone terminal coding agent.
|
|
1440
1440
|
Runs independently of the IDE and Agent Manager.
|
|
1441
1441
|
Connects directly to model-proxy via SSE streaming.`).version(gR).enablePositionalOptions();dt.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 xs("--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",Qm).option("--mode <mode>","[deprecated] plan \u2192 --permission-mode plan \xB7 fast/thinking \u2192 --effort low/high").addOption(new xs("--effort <level>","Reasoning effort").choices(["low","medium","high"])).option("--workspace <path>","Workspace path",".").option("--budget <tokens>","Maximum token budget","1000000").addOption(new xs("-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 xs("--output <format>","Alias for --output-format").hideHelp().choices(["text","json","stream-json","jsonl","diff","markdown","github","azure","sarif","stream"])).addOption(new xs("--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 xs("--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 xs("--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 xs("--sandbox-network <mode>","Sandbox network mode").choices(["none","local","full"]).default("none")).addOption(new xs("--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",KQ()).action(async(t,e)=>{let n=ut.resolve(e.workspace),r=fAe(n),{resolvePrintFlags:s}=await Promise.resolve().then(()=>(YM(),DY)),o=s(t,e);o.error&&(process.stderr.write(`Error: ${o.error}
|
|
1442
1442
|
`),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(gR),process.exit(0);break;case"/doctor":await SS(),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=so(e.model||r.defaultModel);!a&&process.stdin.isTTY&&!e.continue&&e.headless;let c=V8(e.mode);c.warning&&process.stderr.write(g.yellow(` \u26A0 ${c.warning}
|